You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.go 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/gorilla/csrf"
  6. "github.com/gorilla/mux"
  7. "github.com/jamiealquiza/envy"
  8. "html/template"
  9. "log"
  10. "math/rand"
  11. "net/http"
  12. "net/smtp"
  13. "os"
  14. "strings"
  15. )
  16. const (
  17. csrfFieldName = "csrf.Token"
  18. )
  19. var (
  20. fromAddress, toAddress, subject, smtpServer, smtpUsername, smtpPassword, csrfKey *string
  21. smtpPort, port *int
  22. formTemplate, successTemplate, failureTemplate *template.Template
  23. )
  24. func sendMail(replyTo, message string) bool {
  25. auth := smtp.PlainAuth("", *smtpUsername, *smtpPassword, *smtpServer)
  26. body := fmt.Sprintf("To: %s\r\nSubject: %s\r\nReply-to: %s\r\nFrom: Online contact form <%s>\r\n\r\n%s\r\n", *toAddress, *subject, replyTo, *fromAddress, message)
  27. err := smtp.SendMail(fmt.Sprintf("%s:%d", *smtpServer, *smtpPort), auth, *fromAddress, []string{*toAddress}, []byte(body))
  28. if err != nil {
  29. log.Printf("Unable to send mail: %s", err)
  30. return false
  31. }
  32. return true
  33. }
  34. func handleForm(rw http.ResponseWriter, req *http.Request) {
  35. body := ""
  36. for k, v := range req.Form {
  37. if k != csrfFieldName {
  38. body += fmt.Sprintf("%s:\r\n%s\r\n\r\n", strings.ToUpper(k), v[0])
  39. }
  40. }
  41. replyTo := req.Form.Get("from")
  42. replyTo = strings.ReplaceAll(replyTo, "\n", "")
  43. replyTo = strings.ReplaceAll(replyTo, "\r", "")
  44. if sendMail(replyTo, body) {
  45. rw.Header().Add("Location", "success")
  46. } else {
  47. rw.Header().Add("Location", "failure")
  48. }
  49. rw.WriteHeader(http.StatusSeeOther)
  50. }
  51. func showForm(rw http.ResponseWriter, req *http.Request) {
  52. params := make(map[string]string)
  53. for k, vs := range req.URL.Query() {
  54. if len(vs) == 1 {
  55. params[k] = vs[0]
  56. }
  57. }
  58. _ = formTemplate.ExecuteTemplate(rw, "form.html", map[string]interface{}{
  59. csrf.TemplateTag: csrf.TemplateField(req),
  60. "params": params,
  61. })
  62. }
  63. func showSuccess(rw http.ResponseWriter, req *http.Request) {
  64. _ = successTemplate.ExecuteTemplate(rw, "success.html", map[string]interface{}{
  65. csrf.TemplateTag: csrf.TemplateField(req),
  66. })
  67. }
  68. func showFailure(rw http.ResponseWriter, req *http.Request) {
  69. _ = failureTemplate.ExecuteTemplate(rw, "failure.html", map[string]interface{}{
  70. csrf.TemplateTag: csrf.TemplateField(req),
  71. })
  72. }
  73. func randomKey() string {
  74. var runes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  75. b := make([]rune, 32)
  76. for i := range b {
  77. b[i] = runes[rand.Intn(len(runes))]
  78. }
  79. return string(b)
  80. }
  81. func checkFlag(value string, name string) {
  82. if len(value) == 0 {
  83. _, _ = fmt.Fprintf(os.Stderr, "No %s specified\n", name)
  84. flag.Usage()
  85. os.Exit(1)
  86. }
  87. }
  88. func loadTemplate(file string) (result *template.Template) {
  89. var err error
  90. result, err = template.ParseFiles(file)
  91. if err != nil {
  92. _, _ = fmt.Fprintf(os.Stderr, "Unable to load %s: %s\n", file, err.Error())
  93. os.Exit(1)
  94. }
  95. return
  96. }
  97. func main() {
  98. fromAddress = flag.String("from", "", "address to send e-mail from")
  99. toAddress = flag.String("to", "", "address to send e-mail to")
  100. subject = flag.String("subject", "Contact form submission", "e-mail subject")
  101. smtpServer = flag.String("smtp-host", "", "SMTP server to connect to")
  102. smtpPort = flag.Int("smtp-port", 25, "port to use when connecting to the SMTP server")
  103. smtpUsername = flag.String("smtp-user", "", "username to supply to the SMTP server")
  104. smtpPassword = flag.String("smtp-pass", "", "password to supply to the SMTP server")
  105. csrfKey = flag.String("crsf-key", "", "CRSF key to use")
  106. port = flag.Int("port", 8080, "port to listen on for connections")
  107. envy.Parse("CONTACT")
  108. flag.Parse()
  109. checkFlag(*fromAddress, "from address")
  110. checkFlag(*toAddress, "to address")
  111. checkFlag(*smtpServer, "SMTP server")
  112. checkFlag(*smtpUsername, "SMTP username")
  113. checkFlag(*smtpPassword, "SMTP password")
  114. if len(*csrfKey) != 32 {
  115. newKey := randomKey()
  116. csrfKey = &newKey
  117. }
  118. formTemplate = loadTemplate("form.html")
  119. successTemplate = loadTemplate("success.html")
  120. failureTemplate = loadTemplate("failure.html")
  121. r := mux.NewRouter()
  122. r.HandleFunc("/", showForm).Methods("GET")
  123. r.HandleFunc("/success", showSuccess).Methods("GET")
  124. r.HandleFunc("/failure", showFailure).Methods("GET")
  125. r.HandleFunc("/submit", handleForm).Methods("POST")
  126. CSRF := csrf.Protect([]byte(*csrfKey), csrf.FieldName(csrfFieldName))
  127. err := http.ListenAndServe(fmt.Sprintf(":%d", *port), CSRF(r))
  128. if err != nil {
  129. _, _ = fmt.Fprintf(os.Stderr, "Unable to listen on port %d: %s\n", *port, err.Error())
  130. }
  131. }