-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
427 lines (374 loc) · 13.5 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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// home is Dmitri Shuralyov's personal website.
package main
import (
"context"
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/shurcooL/home/assets"
"github.com/shurcooL/home/component"
"github.com/shurcooL/home/httphandler"
"github.com/shurcooL/home/httputil"
"github.com/shurcooL/home/indieauth"
codepkg "github.com/shurcooL/home/internal/code"
"github.com/shurcooL/home/internal/exp/service/auth"
"github.com/shurcooL/home/internal/exp/service/auth/directfetch"
"github.com/shurcooL/home/internal/exp/service/auth/gcpfetch"
"github.com/shurcooL/httpfs/filter"
"github.com/shurcooL/httpgzip"
"github.com/shurcooL/issues"
"github.com/shurcooL/users"
"golang.org/x/net/webdav"
)
var (
httpFlag = flag.String("http", ":8080", "Listen for HTTP connections on this address.")
metricsHTTPFlag = flag.String("metrics-http", "", "Listen for metrics HTTP connections on this address, if any.")
secureCookieFlag = flag.Bool("secure-cookie", false, "Value of cookie attribute Secure.")
storeDirFlag = flag.String("store-dir", filepath.Join(os.TempDir(), "home-store"), "Directory of home store (required).")
stateFileFlag = flag.String("state-file", "", "Optional path to file to save/load state (file is deleted after loading).")
analyticsFileFlag = flag.String("analytics-file", "", "Optional path to file containing analytics HTML to insert at the beginning of <head>.")
noRobotsFlag = flag.Bool("no-robots", false, "Disallow all robots on all pages.")
siteNameFlag = flag.String("site-name", "home (local devel)", "Name of site, displayed on sign in page.")
indieauthMeFlag = indieauth.MeFlag("indieauth-me", "", "Canonical IndieAuth 'me' user profile URL for this home instance, or the empty string to disable the IndieAuth authorization endpoint. See https://indieauth.spec.indieweb.org/#user-profile-url.")
githubRelMeFlag = flag.String("github-rel-me", "dmitshur", "GitHub username to advertise in a rel='me' link.")
fetchFuncURLFlag = flag.String("fetch-func-url", "", "Optional URL to FetchService function.")
fetchKeyFileFlag = flag.String("fetch-key-file", "", "Optional path to key file for FetchService function.")
)
func init() {
flag.BoolVar(&component.RedLogo, "red-logo", false, "Display the logo in red.")
}
var (
analyticsHTML template.HTML // Set early in run.
)
func main() {
flag.Parse()
int := make(chan os.Signal, 1)
signal.Notify(int, os.Interrupt)
ctx, cancel := context.WithCancel(context.Background())
go func() { <-int; cancel() }()
err := run(ctx, cancel, *storeDirFlag, *stateFileFlag, *analyticsFileFlag, *noRobotsFlag)
if err != nil {
log.Fatalln(err)
}
}
func run(ctx context.Context, cancel context.CancelFunc, storeDir, stateFile, analyticsFile string, noRobots bool) error {
if err := mime.AddExtensionType(".md", "text/markdown"); err != nil {
return err
}
if err := mime.AddExtensionType(".woff2", "font/woff2"); err != nil {
return err
}
if analyticsFile != "" {
b, err := ioutil.ReadFile(analyticsFile)
if err != nil {
return err
}
analyticsHTML = template.HTML(b)
}
if noRobots {
http.HandleFunc("/robots.txt", func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
io.WriteString(w, "User-agent: *\nDisallow: /\n")
})
}
if component.RedLogo {
http.HandleFunc("/icon.png", func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "image/png")
w.Header()["Content-Encoding"] = nil // Disable automatic gzip compression, png is already compressed.
err := serveFile(w, req, filepath.Join(os.Getenv("HOME"), "Dropbox", "Public", "dmitri", "icon-red.png"))
if err != nil {
log.Println(`serveFile("icon-red.png"):`, err)
}
})
}
initStores := func(storeDir string) error {
// Make sure storeDir exists and is a directory.
fi, err := os.Stat(storeDir)
if os.IsNotExist(err) {
return fmt.Errorf("store directory %q does not exist: %v", storeDir, err)
} else if err != nil {
return err
}
if !fi.IsDir() {
return fmt.Errorf("store directory %q is not a directory", storeDir)
}
// Create store directories if they're missing.
for _, storeName := range []string{
"users",
"reactions",
"notifications",
"notificationv2",
"events",
"issues",
"usercontent",
"repositories",
} {
err := os.MkdirAll(filepath.Join(storeDir, storeName), 0700)
if err != nil {
return err
}
}
return nil
}
err := initStores(storeDir)
if err != nil {
return err
}
var wg sync.WaitGroup
users, userStore, err := newUsersService(
webdav.Dir(filepath.Join(storeDir, "users")),
)
if err != nil {
return fmt.Errorf("newUsersService: %v", err)
}
reactions, err := newReactionsService(
webdav.Dir(filepath.Join(storeDir, "reactions")),
users,
)
if err != nil {
return fmt.Errorf("newReactionsService: %v", err)
}
githubRouter := dmitshurSeesHomeRouter{users: users}
githubActivity, gerritActivity, err := initNotificationsV2(
ctx, &wg, http.DefaultServeMux,
webdav.Dir(filepath.Join(storeDir, "notificationv2")),
filepath.Join(storeDir, "mail", "githubnotif"),
filepath.Join(storeDir, "mail", "gerritnotif"),
users,
githubRouter,
)
if err != nil {
return fmt.Errorf("initNotificationsV2: %v", err)
}
notifications := initNotifications(
http.DefaultServeMux,
webdav.Dir(filepath.Join(storeDir, "notifications")),
gerritActivity,
users,
githubRouter,
)
events, err := newEventsService(
webdav.Dir(filepath.Join(storeDir, "events")),
githubActivity,
gerritActivity,
users,
)
if err != nil {
return fmt.Errorf("newEventsService: %v", err)
}
issuesService, err := newIssuesService(
webdav.Dir(filepath.Join(storeDir, "issues")),
notifications, events, users, githubRouter,
)
if err != nil {
return fmt.Errorf("newIssuesService: %v", err)
}
changeService := newChangeService(reactions, users, githubRouter)
var fs auth.FetchService
switch *fetchFuncURLFlag {
case "":
fs = directfetch.NewService()
default:
var err error
fs, err = gcpfetch.NewService(*fetchFuncURLFlag, *fetchKeyFileFlag)
if err != nil {
return fmt.Errorf("gcpfetch.NewService: %v", err)
}
}
initAuth(fs, users, userStore)
if me := indieauthMeFlag.Me; me != nil {
initIndieAuth(users, me)
}
usersAPIHandler := httphandler.Users{Users: users}
http.Handle("/api/userspec", cookieAuth{httputil.ErrorHandler(users, usersAPIHandler.GetAuthenticatedSpec)})
http.Handle("/api/user", cookieAuth{httputil.ErrorHandler(users, usersAPIHandler.GetAuthenticated)})
http.Handle("/api/user/", cookieAuth{httputil.ErrorHandler(users, usersAPIHandler.Get)})
reactionsAPIHandler := httphandler.Reactions{Reactions: reactions}
http.Handle("/api/react", cookieAuth{httputil.ErrorHandler(users, reactionsAPIHandler.GetOrToggle)})
http.Handle("/api/react/list", cookieAuth{httputil.ErrorHandler(users, reactionsAPIHandler.List)})
eventsAPIHandler := httphandler.Events{Events: events}
http.Handle("/api/events/list", headerAuth{httputil.ErrorHandler(users, eventsAPIHandler.List)})
userContentHandler := userContentHandler{
store: webdav.Dir(filepath.Join(storeDir, "usercontent")),
users: users,
}
http.Handle("/api/usercontent", cookieAuth{httputil.ErrorHandler(users, userContentHandler.Upload)})
http.Handle("/usercontent/", http.StripPrefix("/usercontent", cookieAuth{httputil.ErrorHandler(users, userContentHandler.Serve)}))
indexHandler := initIndex(events, notifications, users)
initAbout(notifications, users)
err = initBlog(http.DefaultServeMux, issuesService, issues.RepoSpec{URI: "dmitri.shuralyov.com/blog"}, notifications, users)
if err != nil {
return fmt.Errorf("initBlog: %v", err)
}
issuesApp := initIssues(http.DefaultServeMux, issuesService, changeService, notifications, users)
changesApp := initChanges(http.DefaultServeMux, changeService, issuesService, notifications, users)
emojisHandler := cookieAuth{httpgzip.FileServer(assets.Emojis, httpgzip.FileServerOptions{ServeError: detailedForAdmin{Users: users}.ServeError})}
http.Handle("/emojis/", http.StripPrefix("/emojis", emojisHandler))
assetsHandler := cookieAuth{httpgzip.FileServer(assets.Assets, httpgzip.FileServerOptions{ServeError: detailedForAdmin{Users: users}.ServeError})}
http.Handle("/assets/", assetsHandler)
fontsHandler := cookieAuth{httpgzip.FileServer(assets.Fonts, httpgzip.FileServerOptions{ServeError: detailedForAdmin{Users: users}.ServeError})}
http.Handle("/assets/fonts/", http.StripPrefix("/assets/fonts", fontsHandler))
initResume(reactions, notifications, users)
initIdiomaticGo(issuesService, notifications, users)
// Code repositories.
reposDir := filepath.Join(storeDir, "repositories")
code, err := codepkg.NewService(reposDir, notifications, events, users)
if err != nil {
return fmt.Errorf("code.NewService: %v", err)
}
moduleHandler := codepkg.ModuleHandler{Code: code}
http.Handle("/api/module/", http.StripPrefix("/api/module/", httputil.ErrorHandler(nil, moduleHandler.ServeModule)))
gitUsers, err := initGitUsers(users)
if err != nil {
return fmt.Errorf("initGitUsers: %v", err)
}
gitHooksDir := filepath.Join(storeDir, "bin", runtime.GOOS+"_"+runtime.GOARCH, "githook")
gitHandler, err := codepkg.NewGitHandler(code, reposDir, gitHooksDir, events, users, gitUsers, func(req *http.Request) *http.Request {
session, _ := lookUpSessionViaBasicAuth(req, users)
return withSession(req, session)
})
if err != nil {
return fmt.Errorf("code.NewGitHandler: %v", err)
}
codeHandler := codeHandler{code, reposDir, issuesApp, changesApp, issuesService, changeService, notifications, users, gitUsers}
servePackagesMaybe := initPackages(code, notifications, users)
initAction(code, users)
initTalks(
skipDot(http.Dir(filepath.Join(os.Getenv("HOME"), "Dropbox", "Public", "dmitri", "talks"))),
notifications, users)
initProjects(
http.DefaultServeMux,
skipDot(http.Dir(filepath.Join(os.Getenv("HOME"), "Dropbox", "Public", "dmitri", "projects"))),
notifications, users)
if *metricsHTTPFlag != "" {
initMetrics(cancel, *metricsHTTPFlag)
go measureGitHubV3RateLimit()
go measureGitHubV4RateLimit()
}
staticFiles := cookieAuth{httpgzip.FileServer(
skipDot(http.Dir(filepath.Join(os.Getenv("HOME"), "Dropbox", "Public", "dmitri"))),
httpgzip.FileServerOptions{
IndexHTML: true,
ServeError: detailedForAdmin{Users: users}.ServeError,
},
)}
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// Serve index page.
if req.URL.Path == "/" {
indexHandler.ServeHTTP(w, req)
return
}
// Serve git protocol requests for existing repos, if the request matches.
if ok := gitHandler.ServeGitMaybe(w, req); ok {
return
}
// Serve code pages for existing repos/packages, if the request matches.
if ok := codeHandler.ServeCodeMaybe(w, req); ok {
return
}
// Serve remaining import path pattern queries, if the request matches.
if ok := servePackagesMaybe(w, req); ok {
return
}
// Serve static files last.
staticFiles.ServeHTTP(w, req)
})
if stateFile != "" {
err := global.LoadAndRemove(stateFile)
global.mu.Lock()
n := len(global.sessions)
global.mu.Unlock()
log.Println("sessions.LoadAndRemove:", n, err)
}
server := &http.Server{Addr: *httpFlag, Handler: top{httputil.GzipHandler(http.DefaultServeMux)}}
go func() {
<-ctx.Done()
err := server.Close()
if err != nil {
log.Println("server.Close:", err)
}
}()
log.Println("Starting HTTP server.")
err = server.ListenAndServe()
if err != http.ErrServerClosed {
log.Println("server.ListenAndServe:", err)
cancel()
}
log.Println("Ended HTTP server.")
wg.Wait()
if stateFile != "" {
err := global.Save(stateFile)
log.Println("sessions.Save:", err)
}
return nil
}
// top adds some instrumentation on top of Handler.
type top struct{ Handler http.Handler }
func (t top) ServeHTTP(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
started := time.Now()
rw := &responseWriter{ResponseWriter: w, Flusher: w.(http.Flusher)}
t.Handler.ServeHTTP(rw, req)
fmt.Printf("TIMING: %s: %v\n", req.URL, time.Since(started))
if path != req.URL.Path {
log.Printf("warning: req.URL.Path was modified from %v to %v\n", path, req.URL.Path)
}
if rw.WroteBytes && !haveType(w) {
log.Printf("warning: Content-Type header not set for %v %q\n", req.Method, req.URL)
}
}
// haveType reports whether w has the Content-Type header set.
func haveType(w http.ResponseWriter) bool {
_, ok := w.Header()["Content-Type"]
return ok
}
// responseWriter wraps a real http.ResponseWriter and captures
// whether any bytes were written.
type responseWriter struct {
http.ResponseWriter
http.Flusher
WroteBytes bool // Whether non-zero bytes have been written.
}
func (rw *responseWriter) Write(p []byte) (n int, err error) {
if len(p) > 0 {
rw.WroteBytes = true
}
return rw.ResponseWriter.Write(p)
}
// skipDot returns src without dot files.
func skipDot(src http.FileSystem) http.FileSystem {
skip := func(path string, fi os.FileInfo) bool {
for _, e := range strings.Split(path[1:], "/") {
if strings.HasPrefix(e, ".") {
return true
}
}
return false
}
return filter.Skip(src, skip)
}
// detailedForAdmin serves detailed errors for admin users,
// but non-specific errors for others.
type detailedForAdmin struct {
Users users.Service
}
func (d detailedForAdmin) ServeError(w http.ResponseWriter, req *http.Request, err error) {
switch user, e := d.Users.GetAuthenticated(req.Context()); {
case e == nil && user.SiteAdmin:
httpgzip.Detailed(w, req, err)
default:
httpgzip.NonSpecific(w, req, err)
}
}