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.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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. _ = formTemplate.ExecuteTemplate(rw, "form.html", map[string]interface{}{
  53. csrf.TemplateTag: csrf.TemplateField(req),
  54. })
  55. }
  56. func showSuccess(rw http.ResponseWriter, req *http.Request) {
  57. _ = successTemplate.ExecuteTemplate(rw, "success.html", map[string]interface{}{
  58. csrf.TemplateTag: csrf.TemplateField(req),
  59. })
  60. }
  61. func showFailure(rw http.ResponseWriter, req *http.Request) {
  62. _ = failureTemplate.ExecuteTemplate(rw, "failure.html", map[string]interface{}{
  63. csrf.TemplateTag: csrf.TemplateField(req),
  64. })
  65. }
  66. func randomKey() string {
  67. var runes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  68. b := make([]rune, 32)
  69. for i := range b {
  70. b[i] = runes[rand.Intn(len(runes))]
  71. }
  72. return string(b)
  73. }
  74. func checkFlag(value string, name string) {
  75. if len(value) == 0 {
  76. _, _ = fmt.Fprintf(os.Stderr, "No %s specified\n", name)
  77. flag.Usage()
  78. os.Exit(1)
  79. }
  80. }
  81. func loadTemplate(file string) (result *template.Template) {
  82. var err error
  83. result, err = template.ParseFiles(file)
  84. if err != nil {
  85. _, _ = fmt.Fprintf(os.Stderr, "Unable to load %s: %s\n", file, err.Error())
  86. os.Exit(1)
  87. }
  88. return
  89. }
  90. func main() {
  91. fromAddress = flag.String("from", "", "address to send e-mail from")
  92. toAddress = flag.String("to", "", "address to send e-mail to")
  93. subject = flag.String("subject", "Contact form submission", "e-mail subject")
  94. smtpServer = flag.String("smtp-host", "", "SMTP server to connect to")
  95. smtpPort = flag.Int("smtp-port", 25, "port to use when connecting to the SMTP server")
  96. smtpUsername = flag.String("smtp-user", "", "username to supply to the SMTP server")
  97. smtpPassword = flag.String("smtp-pass", "", "password to supply to the SMTP server")
  98. csrfKey = flag.String("crsf-key", "", "CRSF key to use")
  99. port = flag.Int("port", 8080, "port to listen on for connections")
  100. envy.Parse("CONTACT")
  101. flag.Parse()
  102. checkFlag(*fromAddress, "from address")
  103. checkFlag(*toAddress, "to address")
  104. checkFlag(*smtpServer, "SMTP server")
  105. checkFlag(*smtpUsername, "SMTP username")
  106. checkFlag(*smtpPassword, "SMTP password")
  107. if len(*csrfKey) != 32 {
  108. newKey := randomKey()
  109. csrfKey = &newKey
  110. }
  111. formTemplate = loadTemplate("form.html")
  112. successTemplate = loadTemplate("success.html")
  113. failureTemplate = loadTemplate("failure.html")
  114. r := mux.NewRouter()
  115. r.HandleFunc("/", showForm).Methods("GET")
  116. r.HandleFunc("/success", showSuccess).Methods("GET")
  117. r.HandleFunc("/failure", showFailure).Methods("GET")
  118. r.HandleFunc("/submit", handleForm).Methods("POST")
  119. CSRF := csrf.Protect([]byte(*csrfKey), csrf.FieldName(csrfFieldName))
  120. err := http.ListenAndServe(fmt.Sprintf(":%d", *port), CSRF(r))
  121. if err != nil {
  122. _, _ = fmt.Fprintf(os.Stderr, "Unable to listen on port %d: %s\n", *port, err.Error())
  123. }
  124. }