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

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