forked from davidlazar/git-mailbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailbot.go
308 lines (259 loc) · 7.22 KB
/
mailbot.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
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/tls"
"encoding/base32"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"golang.org/x/crypto/acme/autocert"
)
var hostname = flag.String("hostname", "", "ssl hostname")
var persistPath = flag.String("persist", "persist", "directory for persistent data")
var indexHTML []byte
var webhookSecret []byte
func init() {
data, err := ioutil.ReadFile("index.html")
if err != nil {
log.Fatalf("ReadFile: %s", err)
}
indexHTML = data
}
func main() {
flag.Parse()
if *hostname == "" {
log.Fatal("please set -hostname")
}
if err := os.MkdirAll(*persistPath, 0770); err != nil {
log.Fatal(err)
}
secretPath := filepath.Join(*persistPath, "webhook_secret")
secret, err := ioutil.ReadFile(secretPath)
if os.IsNotExist(err) {
r := make([]byte, 8)
rand.Read(r)
s := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(r)
secret = []byte(strings.ToLower(s))
err = ioutil.WriteFile(secretPath, secret, 0600)
if err != nil {
log.Fatal(err)
}
}
webhookSecret = secret
errorLogPath := filepath.Join(*persistPath, "errors.log")
errorFile, err := os.OpenFile(errorLogPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
if err != nil {
log.Fatal(err)
}
defer errorFile.Close()
errorLog := log.New(errorFile, "", log.LstdFlags|log.LUTC|log.Lshortfile)
sslKeysDir := filepath.Join(*persistPath, "ssl_keys")
certManager := autocert.Manager{
Cache: autocert.DirCache(sslKeysDir),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(*hostname),
}
go func() {
err := http.ListenAndServe(":http", certManager.HTTPHandler(nil))
if err != nil {
log.Fatalf("http.ListenAndServe: %s", err)
}
}()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.Write(indexHTML)
})
mux.HandleFunc("/webhook", githubEventHandler)
httpServer := &http.Server{
Addr: ":https",
Handler: mux,
TLSConfig: &tls.Config{GetCertificate: certManager.GetCertificate},
ErrorLog: errorLog,
ReadTimeout: 10 * time.Second,
WriteTimeout: 360 * time.Second,
IdleTimeout: 360 * time.Second,
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
shutdownDone := make(chan struct{})
go func() {
<-sigChan
log.Printf("Shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err := httpServer.Shutdown(ctx)
if err != nil {
log.Printf("HTTP server shutdown with error: %s", err)
}
close(shutdownDone)
}()
err = httpServer.ListenAndServeTLS("", "")
if err != nil {
log.Printf("http listen: %s", err)
}
<-shutdownDone
}
func redirect(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, "https://"+req.Host+req.URL.String(), http.StatusMovedPermanently)
}
type GithubEvent interface {
GetRepository() GithubRepo
GetSender() GithubSender
}
type GithubGenericEvent struct {
Repository GithubRepo
Sender GithubSender
}
func (e GithubGenericEvent) GetRepository() GithubRepo { return e.Repository }
func (e GithubGenericEvent) GetSender() GithubSender { return e.Sender }
type GithubRepo struct {
FullName string `json:"full_name"`
SSHURL string `json:"ssh_url"`
Private bool
}
type GithubSender struct {
Login string
}
type GithubPushEvent struct {
*GithubGenericEvent
Ref string
Before string
After string
Pusher struct {
Name string
Email string
}
}
func githubEventHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
http.Error(w, "unexpected method: "+req.Method, http.StatusBadRequest)
return
}
sig := req.Header.Get("X-Hub-Signature")
var expectedHash []byte
if n, err := fmt.Sscanf(sig, "sha1=%x", &expectedHash); n != 1 {
http.Error(w, "invalid signature: "+err.Error(), http.StatusBadRequest)
return
}
body := http.MaxBytesReader(w, req.Body, 1024*1024)
payload, _ := ioutil.ReadAll(body)
h := hmac.New(sha1.New, webhookSecret)
h.Write(payload)
actualHash := h.Sum(nil)
if !hmac.Equal(actualHash, expectedHash) {
http.Error(w, "signature verification failed", http.StatusBadRequest)
return
}
eventType := req.Header.Get("X-GitHub-Event")
var payloadData interface{}
switch eventType {
case "":
http.Error(w, "no event type specified", http.StatusBadRequest)
return
case "push":
payloadData = new(GithubPushEvent)
default:
payloadData = new(GithubGenericEvent)
}
if err := json.Unmarshal(payload, payloadData); err != nil {
http.Error(w, "failed to parse payload: "+err.Error(), http.StatusBadRequest)
return
}
event := payloadData.(GithubEvent)
log.Printf("%s: %s from %s", event.GetRepository().FullName, eventType, event.GetSender().Login)
if eventType == "ping" {
url := event.GetRepository().SSHURL
gitDir := filepath.Join(*persistPath, "repos", "github.com", event.GetRepository().FullName)
err := syncRepo(gitDir, url)
if err != nil {
err = fmt.Errorf("syncing repo %q failed: %s", url, err)
http.Error(w, err.Error(), http.StatusBadRequest)
log.Println(err)
return
}
w.Write([]byte("Pong"))
return
}
if eventType == "push" {
pushEvent := payloadData.(*GithubPushEvent)
err := githubPushHandler(pushEvent)
if err != nil {
err = fmt.Errorf("push handler failed: %s", err)
http.Error(w, err.Error(), http.StatusBadRequest)
log.Println(err)
return
}
w.Write([]byte("OK"))
log.Printf("%s: push success: %s %s -> %s", pushEvent.Repository.FullName, pushEvent.Ref, pushEvent.Before[:8], pushEvent.After[:8])
}
}
func syncRepo(gitDir string, url string) error {
fi, err := os.Stat(gitDir)
if os.IsNotExist(err) {
err := gitClone(url, gitDir)
if err != nil {
return err
}
log.Printf("Cloned %s to %s", url, gitDir)
} else if err != nil {
return err
} else if !fi.IsDir() {
return fmt.Errorf("%s exists and is not a directory", gitDir)
}
err = gitFetch(gitDir)
if err != nil {
return err
}
return nil
}
func githubPushHandler(ev *GithubPushEvent) error {
gitDir := filepath.Join(*persistPath, "repos", "github.com", ev.Repository.FullName)
if err := syncRepo(gitDir, ev.Repository.SSHURL); err != nil {
return err
}
cmd := exec.Command("./post-receive.py")
stdin := bytes.NewReader([]byte(fmt.Sprintf("%s %s %s", ev.Before, ev.After, ev.Ref)))
cmd.Stdin = stdin
cmd.Env = append(os.Environ(), "GIT_DIR="+gitDir)
_, err := cmd.Output()
if err == nil {
return nil
}
if ee, ok := err.(*exec.ExitError); ok {
return fmt.Errorf("post-receive.py failed: %s:\n%s", ee.ProcessState.String(), ee.Stderr)
}
return err
}
func gitClone(url string, dest string) error {
_, err := runGitCmd(dest, "clone", "--bare", "--quiet", url, dest)
return err
}
func gitFetch(gitDir string) error {
_, err := runGitCmd(gitDir, "fetch", "--quiet", "--force", "origin", "*:*")
return err
}
func runGitCmd(gitDir string, args ...string) ([]byte, error) {
cmd := exec.Command("git", args...)
cmd.Env = append(os.Environ(), "GIT_DIR="+gitDir)
out, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
return out, fmt.Errorf("git %v failed: %s: %q", args, ee.ProcessState.String(), ee.Stderr)
}
}
return out, err
}