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 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "github.com/gorilla/csrf"
  6. "github.com/gorilla/mux"
  7. "github.com/gorilla/sessions"
  8. "github.com/jamiealquiza/envy"
  9. "html/template"
  10. "log"
  11. "math/rand"
  12. "net/http"
  13. "net/smtp"
  14. "os"
  15. "strings"
  16. )
  17. const (
  18. csrfFieldName = "csrf.Token"
  19. sessionName = "contactform"
  20. bodyKey = "body"
  21. replyToKey = "replyTo"
  22. captchaKey = "captchaId"
  23. )
  24. var (
  25. fromAddress, toAddress, subject *string
  26. smtpServer, smtpUsername, smtpPassword *string
  27. csrfKey, sessionKey *string
  28. smtpPort, port *int
  29. enableCaptcha *bool
  30. store *sessions.CookieStore
  31. formTemplate *template.Template
  32. captchaTemplate *template.Template
  33. successTemplate, failureTemplate *template.Template
  34. )
  35. func sendMail(replyTo, message string) bool {
  36. auth := smtp.PlainAuth("", *smtpUsername, *smtpPassword, *smtpServer)
  37. 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)
  38. err := smtp.SendMail(fmt.Sprintf("%s:%d", *smtpServer, *smtpPort), auth, *fromAddress, []string{*toAddress}, []byte(body))
  39. if err != nil {
  40. log.Printf("Unable to send mail: %s", err)
  41. return false
  42. }
  43. return true
  44. }
  45. func handleSubmit(rw http.ResponseWriter, req *http.Request) {
  46. body := ""
  47. for k, v := range req.Form {
  48. if k != csrfFieldName {
  49. body += fmt.Sprintf("%s:\r\n%s\r\n\r\n", strings.ToUpper(k), v[0])
  50. }
  51. }
  52. replyTo := req.Form.Get("from")
  53. replyTo = strings.ReplaceAll(replyTo, "\n", "")
  54. replyTo = strings.ReplaceAll(replyTo, "\r", "")
  55. if *enableCaptcha {
  56. beginCaptcha(rw, req, body, replyTo)
  57. } else if sendMail(replyTo, body) {
  58. rw.Header().Add("Location", "success")
  59. rw.WriteHeader(http.StatusSeeOther)
  60. } else {
  61. rw.Header().Add("Location", "failure")
  62. rw.WriteHeader(http.StatusSeeOther)
  63. }
  64. }
  65. func showForm(rw http.ResponseWriter, req *http.Request) {
  66. params := make(map[string]string)
  67. for k, vs := range req.URL.Query() {
  68. if len(vs) == 1 {
  69. params[k] = vs[0]
  70. }
  71. }
  72. _ = formTemplate.ExecuteTemplate(rw, "form.html", map[string]interface{}{
  73. csrf.TemplateTag: csrf.TemplateField(req),
  74. "params": params,
  75. })
  76. }
  77. func showSuccess(rw http.ResponseWriter, req *http.Request) {
  78. _ = successTemplate.ExecuteTemplate(rw, "success.html", map[string]interface{}{
  79. csrf.TemplateTag: csrf.TemplateField(req),
  80. })
  81. }
  82. func showFailure(rw http.ResponseWriter, req *http.Request) {
  83. _ = failureTemplate.ExecuteTemplate(rw, "failure.html", map[string]interface{}{
  84. csrf.TemplateTag: csrf.TemplateField(req),
  85. })
  86. }
  87. func randomKey() string {
  88. var runes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  89. b := make([]rune, 32)
  90. for i := range b {
  91. b[i] = runes[rand.Intn(len(runes))]
  92. }
  93. return string(b)
  94. }
  95. func checkFlag(value string, name string) {
  96. if len(value) == 0 {
  97. _, _ = fmt.Fprintf(os.Stderr, "No %s specified\n", name)
  98. flag.Usage()
  99. os.Exit(1)
  100. }
  101. }
  102. func loadTemplate(file string) (result *template.Template) {
  103. var err error
  104. result, err = template.ParseFiles(file)
  105. if err != nil {
  106. _, _ = fmt.Fprintf(os.Stderr, "Unable to load %s: %s\n", file, err.Error())
  107. os.Exit(1)
  108. }
  109. return
  110. }
  111. func main() {
  112. fromAddress = flag.String("from", "", "address to send e-mail from")
  113. toAddress = flag.String("to", "", "address to send e-mail to")
  114. subject = flag.String("subject", "Contact form submission", "e-mail subject")
  115. smtpServer = flag.String("smtp-host", "", "SMTP server to connect to")
  116. smtpPort = flag.Int("smtp-port", 25, "port to use when connecting to the SMTP server")
  117. smtpUsername = flag.String("smtp-user", "", "username to supply to the SMTP server")
  118. smtpPassword = flag.String("smtp-pass", "", "password to supply to the SMTP server")
  119. csrfKey = flag.String("crsf-key", "", "CRSF key to use")
  120. sessionKey = flag.String("session-key", "", "Session key to use (for captcha support)")
  121. enableCaptcha = flag.Bool("enable-captcha", false, "Whether to require captchas to be completed")
  122. port = flag.Int("port", 8080, "port to listen on for connections")
  123. envy.Parse("CONTACT")
  124. flag.Parse()
  125. checkFlag(*fromAddress, "from address")
  126. checkFlag(*toAddress, "to address")
  127. checkFlag(*smtpServer, "SMTP server")
  128. checkFlag(*smtpUsername, "SMTP username")
  129. checkFlag(*smtpPassword, "SMTP password")
  130. if len(*csrfKey) != 32 {
  131. newKey := randomKey()
  132. csrfKey = &newKey
  133. }
  134. if len(*sessionKey) != 32 {
  135. newKey := randomKey()
  136. sessionKey = &newKey
  137. }
  138. store = sessions.NewCookieStore([]byte(*sessionKey))
  139. store.Options = &sessions.Options{
  140. MaxAge: 0,
  141. Secure: true, // Set to false for local development
  142. HttpOnly: true,
  143. SameSite: http.SameSiteStrictMode,
  144. }
  145. formTemplate = loadTemplate("form.html")
  146. captchaTemplate = loadTemplate("captcha.html")
  147. successTemplate = loadTemplate("success.html")
  148. failureTemplate = loadTemplate("failure.html")
  149. r := mux.NewRouter()
  150. r.HandleFunc("/", showForm).Methods("GET")
  151. r.HandleFunc("/success", showSuccess).Methods("GET")
  152. r.HandleFunc("/failure", showFailure).Methods("GET")
  153. r.HandleFunc("/submit", handleSubmit).Methods("POST")
  154. // Captcha endpoints
  155. r.HandleFunc("/captcha", showCaptcha).Methods("GET")
  156. r.HandleFunc("/captcha.png", writeCaptchaImage).Methods("GET")
  157. r.HandleFunc("/captcha.wav", writeCaptchaAudio).Methods("GET")
  158. r.HandleFunc("/solve", handleSolve).Methods("POST")
  159. // If developing locally, you'll need to pass csrf.Secure(false) as an argument below.
  160. CSRF := csrf.Protect([]byte(*csrfKey), csrf.FieldName(csrfFieldName))
  161. err := http.ListenAndServe(fmt.Sprintf(":%d", *port), CSRF(r))
  162. if err != nil {
  163. _, _ = fmt.Fprintf(os.Stderr, "Unable to listen on port %d: %s\n", *port, err.Error())
  164. }
  165. }