-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
205 lines (176 loc) · 6.18 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package main
import (
"flag"
"fmt"
"github.com/alexedwards/scs/boltstore"
"github.com/alexedwards/scs/v2"
"github.com/csmith/envflag"
"github.com/gorilla/csrf"
"github.com/nelkinda/health-go"
"go.etcd.io/bbolt"
"html/template"
"log"
"math/rand"
"net/http"
"net/smtp"
"os"
"strings"
"time"
)
const (
csrfFieldName = "csrf.Token"
sessionName = "contactform"
bodyKey = "body"
replyToKey = "replyTo"
captchaKey = "captchaId"
)
var (
fromAddress = flag.String("from", "", "address to send e-mail from")
toAddress = flag.String("to", "", "address to send e-mail to")
subject = flag.String("subject", "Contact form submission", "e-mail subject")
smtpServer = flag.String("smtp-host", "", "SMTP server to connect to")
smtpPort = flag.Int("smtp-port", 25, "port to use when connecting to the SMTP server")
smtpUsername = flag.String("smtp-user", "", "username to supply to the SMTP server")
smtpPassword = flag.String("smtp-pass", "", "password to supply to the SMTP server")
csrfKey = flag.String("crsf-key", "", "CRSF key to use")
sessionPath = flag.String("session-path", "./sessions.db", "Path to persist session information")
enableCaptcha = flag.Bool("enable-captcha", false, "Whether to require captchas to be completed")
enableHealthCheck = flag.Bool("enable-health-check", false, "Whether to expose health checks at /_health")
port = flag.Int("port", 8080, "port to listen on for connections")
formTemplate *template.Template
captchaTemplate *template.Template
successTemplate *template.Template
failureTemplate *template.Template
sessionManager *scs.SessionManager
hc = &healthCheck{}
)
func sendMail(replyTo, message string) bool {
auth := smtp.PlainAuth("", *smtpUsername, *smtpPassword, *smtpServer)
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)
err := smtp.SendMail(fmt.Sprintf("%s:%d", *smtpServer, *smtpPort), auth, *fromAddress, []string{*toAddress}, []byte(body))
if err != nil {
log.Printf("Unable to send mail: %s", err)
hc.recordMailFailure(err)
return false
}
hc.recordMailSuccess()
return true
}
func handleSubmit(rw http.ResponseWriter, req *http.Request) {
body := ""
for k, v := range req.Form {
if k != csrfFieldName {
body += fmt.Sprintf("%s:\r\n%s\r\n\r\n", strings.ToUpper(k), v[0])
}
}
replyTo := req.Form.Get("from")
replyTo = strings.ReplaceAll(replyTo, "\n", "")
replyTo = strings.ReplaceAll(replyTo, "\r", "")
if *enableCaptcha {
beginCaptcha(rw, req, body, replyTo)
} else if sendMail(replyTo, body) {
rw.Header().Add("Location", "success")
rw.WriteHeader(http.StatusSeeOther)
} else {
rw.Header().Add("Location", "failure")
rw.WriteHeader(http.StatusSeeOther)
}
}
func showForm(rw http.ResponseWriter, req *http.Request) {
params := make(map[string]string)
for k, vs := range req.URL.Query() {
if len(vs) == 1 {
params[k] = vs[0]
}
}
_ = formTemplate.ExecuteTemplate(rw, "form.html", map[string]interface{}{
csrf.TemplateTag: csrf.TemplateField(req),
"params": params,
})
}
func showSuccess(rw http.ResponseWriter, req *http.Request) {
_ = successTemplate.ExecuteTemplate(rw, "success.html", map[string]interface{}{
csrf.TemplateTag: csrf.TemplateField(req),
})
}
func showFailure(rw http.ResponseWriter, req *http.Request) {
_ = failureTemplate.ExecuteTemplate(rw, "failure.html", map[string]interface{}{
csrf.TemplateTag: csrf.TemplateField(req),
})
}
func randomKey() string {
var runes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, 32)
for i := range b {
b[i] = runes[rand.Intn(len(runes))]
}
return string(b)
}
func checkFlag(value string, name string) {
if len(value) == 0 {
_, _ = fmt.Fprintf(os.Stderr, "No %s specified\n", name)
flag.Usage()
os.Exit(1)
}
}
func loadTemplate(file string) (result *template.Template) {
var err error
result, err = template.ParseFiles(file)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Unable to load %s: %s\n", file, err.Error())
os.Exit(1)
}
return
}
func main() {
envflag.Parse(envflag.WithPrefix("CONTACT_"))
flag.Parse()
checkFlag(*fromAddress, "from address")
checkFlag(*toAddress, "to address")
checkFlag(*smtpServer, "SMTP server")
checkFlag(*smtpUsername, "SMTP username")
checkFlag(*smtpPassword, "SMTP password")
if len(*csrfKey) != 32 {
newKey := randomKey()
csrfKey = &newKey
}
db, err := bbolt.Open(*sessionPath, 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
sessionManager = scs.New()
sessionManager.Store = boltstore.NewWithCleanupInterval(db, time.Hour)
sessionManager.Cookie.Name = sessionName
sessionManager.Cookie.HttpOnly = true
sessionManager.Cookie.Persist = false
sessionManager.Cookie.Secure = true
sessionManager.Cookie.SameSite = http.SameSiteStrictMode
formTemplate = loadTemplate("templates/form.html")
captchaTemplate = loadTemplate("templates/captcha.html")
successTemplate = loadTemplate("templates/success.html")
failureTemplate = loadTemplate("templates/failure.html")
r := http.NewServeMux()
r.HandleFunc("GET /", showForm)
r.HandleFunc("GET /success", showSuccess)
r.HandleFunc("GET /failure", showFailure)
r.HandleFunc("POST /submit", handleSubmit)
// Static files (with no index)
r.Handle("GET /static/{$}", http.NotFoundHandler())
r.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
// Captcha endpoints
r.HandleFunc("GET /captcha", showCaptcha)
r.HandleFunc("GET /captcha.png", writeCaptchaImage)
r.HandleFunc("GET /captcha.wav", writeCaptchaAudio)
r.HandleFunc("POST /solve", handleSolve)
// Health checks
if *enableHealthCheck {
h := health.New(health.Health{Version: "1"}, hc)
r.HandleFunc("GET /_health", h.Handler)
}
// If developing locally, you'll need to pass csrf.Secure(false) as an argument below.
CSRF := csrf.Protect([]byte(*csrfKey), csrf.FieldName(csrfFieldName))
if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), sessionManager.LoadAndSave(CSRF(r))); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Unable to listen on port %d: %s\n", *port, err.Error())
}
}