forked from golang/build
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsubhelper.go
412 lines (365 loc) · 9.66 KB
/
pubsubhelper.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// The pubsubhelper is an SMTP server for Gerrit updates and an HTTP
// server for Github webhook updates. It then lets other clients subscribe
// to those changes.
package main
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"net/textproto"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"time"
"github.com/bradfitz/go-smtpd/smtpd"
"github.com/jellevandenhooff/dkim"
"go4.org/types"
"golang.org/x/build/cmd/pubsubhelper/pubsubtypes"
"golang.org/x/crypto/acme/autocert"
)
var (
botEmail = flag.String("rcpt", "\x67\x6f\x70\x68\x65\x72\x62\x6f\[email protected]", "email address of bot. incoming emails must be to this address.")
httpListen = flag.String("http", ":80", "HTTP listen address")
acmeDomain = flag.String("autocert", "pubsubhelper.golang.org", "If non-empty, listen on port 443 and serve HTTPS with a LetsEncrypt cert for this domain.")
smtpListen = flag.String("smtp", ":25", "SMTP listen address")
)
func main() {
flag.Parse()
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func() {
sig := <-ch
log.Printf("Signal %v received; exiting with status 0.", sig)
os.Exit(0)
}()
http.HandleFunc("/", handleRoot)
http.HandleFunc("/waitevent", handleWaitEvent)
http.HandleFunc("/recent", handleRecent)
http.HandleFunc("/github-webhook", handleGithubWebhook)
errc := make(chan error)
go func() {
log.Printf("running pubsubhelper on %s", *smtpListen)
s := &smtpd.Server{
Addr: *smtpListen,
OnNewMail: onNewMail,
OnNewConnection: onNewConnection,
ReadTimeout: time.Minute,
}
err := s.ListenAndServe()
errc <- fmt.Errorf("SMTP ListenAndServe: %v", err)
}()
m := &autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(*acmeDomain),
}
go func() {
if *acmeDomain == "" {
return
}
if _, err := os.Stat("/autocert-cache"); err == nil {
m.Cache = autocert.DirCache("/autocert-cache")
} else {
log.Printf("Warning: running acme/autocert without cache")
}
log.Printf("running pubsubhelper HTTPS on :443 for %s", *acmeDomain)
s := &http.Server{
Addr: ":https",
TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 5 * time.Minute,
IdleTimeout: 5 * time.Minute,
}
err := s.ListenAndServeTLS("", "")
errc <- fmt.Errorf("HTTPS ListenAndServeTLS: %v", err)
}()
go func() {
log.Printf("running pubsubhelper HTTP on %s", *httpListen)
s := &http.Server{
Addr: *httpListen,
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 5 * time.Minute,
IdleTimeout: 5 * time.Minute,
Handler: m.HTTPHandler(http.DefaultServeMux),
}
err := s.ListenAndServe()
errc <- fmt.Errorf("HTTP ListenAndServe: %v", err)
}()
log.Fatal(<-errc)
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
io.WriteString(w, `<html>
<body>
This is <a href="https://godoc.org/golang.org/x/build/cmd/pubsubhelper">pubsubhelper</a>.
<ul>
<li><b><a href="/waitevent">/waitevent</a></b>: long-poll wait 30s for next event (use ?after=[RFC3339Nano] to resume at point)</li>
<li><b><a href="/recent">/recent</a></b>: recent events, without long-polling.</li>
</ul>
</body>
</html>
`)
}
func handleWaitEvent(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "requires GET", http.StatusBadRequest)
return
}
ch := make(chan *eventAndJSON, 1)
var after time.Time
if v := r.FormValue("after"); v != "" {
var err error
after, err = time.Parse(time.RFC3339Nano, v)
if err != nil {
http.Error(w, "'after' parameter is not in time.RFC3339Nano format", http.StatusBadRequest)
return
}
} else {
after = time.Now()
}
register(ch, after)
defer unregister(ch)
ctx := r.Context()
timer := time.NewTimer(30 * time.Second)
defer timer.Stop()
var e *eventAndJSON
select {
case <-ctx.Done():
return
case <-timer.C:
e = newEventAndJSON(&pubsubtypes.Event{
LongPollTimeout: true,
})
case e = <-ch:
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
io.WriteString(w, e.json)
}
func handleRecent(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var after time.Time
if v := r.FormValue("after"); v != "" {
var err error
after, err = time.Parse(time.RFC3339Nano, v)
if err != nil {
http.Error(w, "'after' parameter is not in time.RFC3339Nano format", http.StatusBadRequest)
return
}
}
var buf bytes.Buffer
mu.Lock()
buf.WriteString("[\n")
n := 0
for i := len(recent) - 1; i >= 0; i-- {
ev := recent[i]
if ev.Time.Time().Before(after) {
continue
}
if n > 0 {
buf.WriteString(",\n")
}
n++
buf.WriteString(ev.json)
}
buf.WriteString("\n]\n")
mu.Unlock()
w.Write(buf.Bytes())
}
type env struct {
from smtpd.MailAddress
body bytes.Buffer
conn smtpd.Connection
tooBig bool
hasRcpt bool
}
func (e *env) BeginData() error {
if !e.hasRcpt {
return smtpd.SMTPError("554 5.5.1 Error: no valid recipients")
}
return nil
}
func (e *env) AddRecipient(rcpt smtpd.MailAddress) error {
if e.hasRcpt {
return smtpd.SMTPError("554 5.5.1 Error: dup recipients")
}
to := rcpt.Email()
if to != *botEmail {
return errors.New("bogus recipient")
}
e.hasRcpt = true
return nil
}
func (e *env) Write(line []byte) error {
const maxSize = 5 << 20
if e.body.Len() > maxSize {
e.tooBig = true
return nil
}
e.body.Write(line)
return nil
}
var (
headerSep = []byte("\r\n\r\n")
dkimSignatureHeader = []byte("\nDKIM-Signature:")
)
func (e *env) Close() error {
if e.tooBig {
log.Printf("Ignoring too-large email from %q", e.from)
return nil
}
from := e.from.Email()
bodyBytes := e.body.Bytes()
if !bytes.Contains(bodyBytes, dkimSignatureHeader) {
log.Printf("Ignoring unsigned (~spam) email from %q", from)
return nil
}
headerBytes := bodyBytes
if i := bytes.Index(headerBytes, headerSep); i == -1 {
log.Printf("Ignoring email without header separator from %q", from)
return nil
} else {
headerBytes = headerBytes[:i+len(headerSep)]
}
ve, err := dkim.ParseAndVerify(string(headerBytes), dkim.HeadersOnly, dnsClient{})
if err != nil {
log.Printf("Email from %q didn't pass DKIM verifications: %v", from, err)
return nil
}
if !strings.HasSuffix(ve.Signature.Domain, "google.com") {
log.Printf("Ignoring DKIM-verified Gerrit email from non-Google domain %q", ve.Signature.Domain)
return nil
}
tp := textproto.NewReader(bufio.NewReader(bytes.NewReader(headerBytes)))
hdr, err := tp.ReadMIMEHeader()
if err != nil {
log.Printf("Ignoring ReadMIMEHeader error: %v from email:\n%s", err, headerBytes)
return nil
}
if e.from.Hostname() != "gerritcodereview.bounces.google.com" {
log.Printf("Ignoring signed, DKIM-verified, non-Gerrit email from %q:\n%s", from, bodyBytes)
return nil
}
changeNum, _ := strconv.Atoi(hdr.Get("X-Gerrit-Change-Number"))
// Extract gerrit project "oauth2" from List-Id header like:
// List-Id: <gerrit-oauth2.go-review.googlesource.com>
project := strings.TrimPrefix(hdr.Get("List-Id"), "<gerrit-")
if i := strings.IndexByte(project, '.'); i == -1 {
project = ""
} else {
project = project[:i]
}
publish(&pubsubtypes.Event{
Gerrit: &pubsubtypes.GerritEvent{
URL: strings.Trim(hdr.Get("X-Gerrit-ChangeURL"), "<>"),
Project: project,
CommitHash: hdr.Get("X-Gerrit-Commit"),
ChangeNumber: changeNum,
},
})
return nil
}
type eventAndJSON struct {
*pubsubtypes.Event
json string // JSON MarshalIndent of Event
}
var (
mu sync.Mutex // guards following
recent []*eventAndJSON // newest at end
waiting = map[chan *eventAndJSON]struct{}{}
)
const (
keepMin = 50
maxAge = 1 * time.Hour
)
func register(ch chan *eventAndJSON, after time.Time) {
mu.Lock()
defer mu.Unlock()
for _, e := range recent {
if e.Time.Time().After(after) {
ch <- e
return
}
}
waiting[ch] = struct{}{}
}
func unregister(ch chan *eventAndJSON) {
mu.Lock()
defer mu.Unlock()
delete(waiting, ch)
}
// numOldInRecentLocked returns how many leading items of recent are
// too old.
func numOldInRecentLocked() int {
if len(recent) <= keepMin {
return 0
}
n := 0
tooOld := time.Now().Add(-maxAge)
for _, e := range recent {
if e.Time.Time().After(tooOld) {
break
}
n++
}
return n
}
func newEventAndJSON(e *pubsubtypes.Event) *eventAndJSON {
e.Time = types.Time3339(time.Now())
j, err := json.MarshalIndent(e, "", "\t")
if err != nil {
log.Printf("JSON error: %v", err)
}
return &eventAndJSON{
Event: e,
json: string(j),
}
}
func publish(e *pubsubtypes.Event) {
ej := newEventAndJSON(e)
log.Printf("Event: %s", ej.json)
mu.Lock()
defer mu.Unlock()
recent = append(recent, ej)
// Trim old ones off the front of recent
if n := numOldInRecentLocked(); n > 0 {
copy(recent, recent[n:])
recent = recent[:len(recent)-n]
}
for ch := range waiting {
ch <- ej
delete(waiting, ch)
}
}
type dnsClient struct{}
var resolver = &net.Resolver{PreferGo: true}
func (dnsClient) LookupTxt(hostname string) ([]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
return resolver.LookupTXT(ctx, hostname)
}
func onNewMail(c smtpd.Connection, from smtpd.MailAddress) (smtpd.Envelope, error) {
return &env{
from: from,
conn: c,
}, nil
}
func onNewConnection(c smtpd.Connection) error {
log.Printf("smtpd: new connection from %v", c.Addr())
return nil
}