-
Notifications
You must be signed in to change notification settings - Fork 1
/
04-server.go
executable file
·193 lines (172 loc) · 4.79 KB
/
04-server.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
package main
import (
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
_ "net/http/pprof"
"net/url"
"strconv"
"strings"
"time"
"github.com/aerth/mbox"
"github.com/dchest/captcha"
"github.com/gorilla/csrf"
"github.com/microcosm-cc/bluemonday"
)
var funcMap = template.FuncMap{
"timesince": timesince,
}
func pubkeyHandler(w http.ResponseWriter, r *http.Request) {
if publicKey == nil {
redirecthomeHandler(w, r)
return
}
w.Write(publicKey)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
hitcounter = hitcounter + 1
cosgo.Visitors = hitcounter
if !*quiet {
log.Printf("Visitor #%v: %s %s %s %s", cosgo.Visitors, r.UserAgent(), r.RemoteAddr, r.Host, r.RequestURI)
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
fmt.Println(err)
return
}
var status, reason string
if query.Get("status") != "" {
if query["status"][0] == "1" {
status = "Thanks! Your message was sent."
}
}
if query.Get("r") != "" {
if query["status"][0] == "0" {
switch query["r"][0] {
default:
reason = "Error."
case "1":
reason = "Bad method."
case "2":
reason = "Bad endpoint."
case "3":
reason = "Bad capcha."
case "4":
reason = "Bad email address."
case "5":
reason = "Bad message."
case "6":
reason = "Bad error!"
}
status = "Your message was not sent: " + reason
}
}
thyme := time.Now()
nowtime := thyme.Format("Mon Jan 2 15:04:05 2006")
uptime := time.Since(timeboot).String()
fortune := newfortune()
t, templateerr := template.New("Index").Funcs(funcMap).ParseFiles(templateDir + "index.html")
if templateerr != nil {
// Something happened to the template since booting successfully. Must be 100% correct HTML syntax.
log.Println("Almost fatal")
log.Println(templateerr)
fmt.Fprintf(w, "We are experiencing some technical difficulties. Please come back soon!")
} else {
data := map[string]interface{}{
"Now": nowtime,
"Status": status,
"Version": version,
"Hits": hitcounter,
"Uptime": uptime,
"Boottime": timeboot,
"Fortune": fortune,
"PublicKey": string(publicKey),
"Key": getKey(),
csrf.TemplateTag: csrf.TemplateField(r),
"CaptchaId": captcha.NewLen(CaptchaLength + rand.Intn(CaptchaVariation)),
}
t.ExecuteTemplate(w, "Index", data)
}
}
// redirecthomeHandler redirects everyone home ("/") with a 301 redirect.
func redirecthomeHandler(rw http.ResponseWriter, r *http.Request) {
domain := getDomain(r)
p := bluemonday.UGCPolicy()
cleanURL := p.Sanitize(r.URL.Path)
log.Printf("%q from %s hit %q on domain: %q", r.UserAgent(), r.RemoteAddr, cleanURL, domain)
http.Redirect(rw, r, "/", 301)
}
// make sure user submitted a POST request
func verifyMethod(r *http.Request) bool {
if r.Method != "POST" {
return false
}
return true
}
// Very primitive way of flashing a message without session info
func srvError(r *http.Request, rw http.ResponseWriter, e int) {
http.Redirect(rw, r, "/?status=0&r="+strconv.Itoa(e)+"#contact", http.StatusFound)
return
}
// emailHandler checks the Captcha string, and the POST key, and sends on its way.
func emailHandler(rw http.ResponseWriter, r *http.Request) {
if !verifyMethod(r) {
log.Println("bad method")
srvError(r, rw, 1)
return
}
if !verifyKey(r) {
srvError(r, rw, 2)
return
}
if !verifyCaptcha(r) {
srvError(r, rw, 3)
return
}
if *debug {
log.Printf("Human Visitor: %s at %s", r.UserAgent(), r.RemoteAddr)
}
r.ParseForm()
// normalize and validate email, message
mailform := mbox.ParseFormGPG(destinationEmail, r.Form, publicKey)
// quick offline email address validation
if mailform.Email == "@" || mailform.Email == " " || !strings.ContainsAny(mailform.Email, "@") || !strings.ContainsAny(mailform.Email, ".") {
srvError(r, rw, 4)
return
}
if *sendgridKey != "" {
ok, str := sendgridder(destinationEmail, mailform)
if str != "" {
log.Println(str)
}
if !ok {
log.Printf("FAILURE-contact: %q at %s\n\t%q", r.UserAgent(), r.RemoteAddr, r.Form)
srvError(r, rw, 5)
return
}
log.Printf("SUCCESS-contact: %s at %s", r.UserAgent(), r.RemoteAddr)
srvSuccess(r, rw, 1)
return
}
// save the message
saving := mbox.Save(mailform)
if saving != nil {
log.Println(saving)
srvError(r, rw, 6)
return
}
log.Printf("SUCCESS-contact: %s at %s", r.UserAgent(), r.RemoteAddr)
srvSuccess(r, rw, 1)
}
func srvSuccess(r *http.Request, rw http.ResponseWriter, status int) {
http.Redirect(rw, r, "/?status=1", http.StatusFound)
}
// serverSingle just shows one file.
func serveSingle(pattern string, filename string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
log.Printf("Serving %s: %s at %s", pattern, r.UserAgent(), r.RemoteAddr)
http.ServeContent(w, r, filename, time.Now(), nil)
})
}