-
Notifications
You must be signed in to change notification settings - Fork 26
/
http.go
352 lines (310 loc) · 9.02 KB
/
http.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
package main
import (
"database/sql"
"errors"
"fmt"
"net"
"net/http"
"sort"
"strconv"
"time"
"github.com/dchest/captcha"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/justinas/alice"
"github.com/samber/lo"
"go.goblog.app/app/pkgs/bodylimit"
"go.goblog.app/app/pkgs/httpcompress"
"go.goblog.app/app/pkgs/maprouter"
"go.goblog.app/app/pkgs/plugintypes"
"golang.org/x/net/context"
)
const (
contentType = "Content-Type"
userAgent = "User-Agent"
appUserAgent = "GoBlog/1.0"
blogKey contextKey = "blog"
pathKey contextKey = "httpPath"
)
func (a *goBlog) startServer() (err error) {
a.info("Start server(s)...")
// Load router
a.reloadRouter()
// Set basic middlewares
h := alice.New()
h = h.Append(bodylimit.BodyLimit(100 * bodylimit.MB))
h = h.Append(middleware.Heartbeat("/ping"))
if a.cfg.Server.Logging {
h = h.Append(a.logMiddleware)
}
h = h.Append(middleware.Recoverer, httpcompress.CompressMiddleware)
if a.cfg.Server.SecurityHeaders {
h = h.Append(a.securityHeaders)
}
// Add plugin middlewares
middlewarePlugins := lo.Map(a.getPlugins(pluginMiddlewareType), func(item any, index int) plugintypes.Middleware { return item.(plugintypes.Middleware) })
sort.Slice(middlewarePlugins, func(i, j int) bool {
// Sort with descending prio
return middlewarePlugins[i].Prio() > middlewarePlugins[j].Prio()
})
for _, plugin := range middlewarePlugins {
h = h.Append(plugin.Handler)
}
// Finally...
finalHandler := h.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
a.d.ServeHTTP(w, r)
})
// Start Onion service
if a.cfg.Server.Tor {
go func() {
if err := a.startOnionService(finalHandler); err != nil {
a.error("Tor failed", "err", err)
}
}()
}
// Start server
if a.cfg.Server.HttpsRedirect {
go func() {
// Start HTTP server for redirects
h := http.Handler(http.HandlerFunc(a.redirectToHttps))
if m := a.getAutocertManager(); m != nil {
h = m.HTTPHandler(h)
}
httpServer := &http.Server{
Addr: ":80",
Handler: h,
ReadHeaderTimeout: 1 * time.Minute,
ReadTimeout: 5 * time.Minute,
WriteTimeout: 5 * time.Minute,
}
a.shutdown.Add(a.shutdownServer(httpServer, "http server"))
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
a.error("Failed to start HTTP server", "err", err)
}
}()
}
s := &http.Server{
Handler: finalHandler,
ReadHeaderTimeout: 1 * time.Minute,
ReadTimeout: 5 * time.Minute,
WriteTimeout: 5 * time.Minute,
}
a.shutdown.Add(a.shutdownServer(s, "main server"))
s.Addr = ":" + strconv.Itoa(a.cfg.Server.Port)
if a.cfg.Server.PublicHTTPS {
s.TLSConfig = a.getAutocertManager().TLSConfig()
err = s.ListenAndServeTLS("", "")
} else if a.cfg.Server.manualHttps {
err = s.ListenAndServeTLS(a.cfg.Server.HttpsCert, a.cfg.Server.HttpsKey)
} else {
err = s.ListenAndServe()
}
if err == http.ErrServerClosed {
return nil
}
return err
}
func (a *goBlog) shutdownServer(s *http.Server, name string) func() {
return func() {
toc, c := context.WithTimeout(context.Background(), 5*time.Second)
defer c()
if err := s.Shutdown(toc); err != nil {
a.error("Error on server shutdown (%v): %v", name, err)
}
a.info("Stopped server", "name", name)
}
}
func (*goBlog) redirectToHttps(w http.ResponseWriter, r *http.Request) {
requestHost, _, err := net.SplitHostPort(r.Host)
if err != nil {
requestHost = r.Host
}
w.Header().Set("Connection", "close")
http.Redirect(w, r, fmt.Sprintf("https://%s%s", requestHost, r.URL.RequestURI()), http.StatusMovedPermanently)
}
const (
paginationPath = "/page/{page:[0-9-]+}"
feedPath = ".{feed:(rss|json|atom|min\\.rss|min\\.json|min\\.atom)}"
)
func (a *goBlog) reloadRouter() {
a.d = a.buildRouter()
}
func (a *goBlog) serveReloadRouter(w http.ResponseWriter, r *http.Request) {
a.reloadRouter()
http.Redirect(w, r, "/", http.StatusFound)
}
func (a *goBlog) buildRouter() http.Handler {
mapRouter := &maprouter.MapRouter{
Handlers: map[string]http.Handler{},
}
if shn := a.cfg.Server.shortPublicHostname; shn != "" {
mapRouter.Handlers[shn] = http.HandlerFunc(a.redirectShortDomain)
}
if mhn := a.cfg.Server.mediaHostname; mhn != "" && !a.isPrivate() {
mr := chi.NewMux()
mr.Use(middleware.RedirectSlashes)
mr.Use(middleware.CleanPath)
mr.Group(a.mediaFilesRouter)
mapRouter.Handlers[mhn] = mr
}
// Default router
r := chi.NewMux()
// Basic middleware
r.Use(fixHTTPHandler)
r.Use(middleware.RedirectSlashes)
r.Use(middleware.CleanPath)
// Tor
if a.cfg.Server.Tor {
r.Use(a.addOnionLocation)
}
// Cache
if cache := a.cfg.Cache; cache != nil && !cache.Enable {
r.Use(middleware.NoCache)
}
// No Index Header
if a.isPrivate() {
r.Use(noIndexHeader)
}
// Login and captcha middleware
r.Use(a.checkIsLogin)
r.Use(a.checkIsCaptcha)
// Login
r.Group(a.loginRouter)
// Micropub
r.Route(micropubPath, a.micropubRouter)
// IndieAuth
r.Group(a.indieAuthRouter)
// ActivityPub and stuff
r.Group(a.activityPubRouter)
// Webmentions
r.Route(webmentionPath, a.webmentionsRouter)
// Notifications
r.Route(notificationsPath, a.notificationsRouter)
// Assets
r.Group(a.assetsRouter)
// Static files
r.Group(a.staticFilesRouter)
// Media files
r.Route("/m", a.mediaFilesRouter)
// Profile image
r.Group(a.profileImageRouter)
// Other routes
r.Route("/-", a.otherRoutesRouter)
// Captcha
r.Handle("/captcha/*", captcha.Server(500, 250))
// Blogs
for blog, blogConfig := range a.cfg.Blogs {
r.Group(a.blogRouter(blog, blogConfig))
}
// Sitemap
r.With(a.privateModeHandler, cacheLoggedIn, a.cacheMiddleware).Get(sitemapPath, a.serveSitemap)
// IndexNow
if a.indexNowEnabled() {
if inkey := a.indexNowKey(); len(inkey) > 0 {
r.With(cacheLoggedIn, a.cacheMiddleware).Get("/"+string(inkey)+".txt", a.serveIndexNow)
}
}
// Robots.txt
r.With(cacheLoggedIn, a.cacheMiddleware).Get(robotsTXTPath, a.serveRobotsTXT)
// Favicon
if !hasStaticPath("favicon.ico") {
r.With(a.cacheMiddleware).Get("/favicon.ico", a.serve404)
}
r.NotFound(a.servePostsAliasesRedirects())
r.MethodNotAllowed(a.serveNotAllowed)
mapRouter.DefaultHandler = r
return alice.New(headAsGetHandler).Then(mapRouter)
}
func (a *goBlog) servePostsAliasesRedirects() http.HandlerFunc {
// Private mode
alicePrivate := alice.New(a.privateModeHandler)
// Return handler func
return func(w http.ResponseWriter, r *http.Request) {
// Only allow GET requests
if r.Method != http.MethodGet {
a.serveNotAllowed(w, r)
return
}
// Check if post or alias
path := r.URL.Path
row, err := a.db.QueryRowContext(r.Context(), `
-- normal posts
select 'post', status, visibility, 200 from posts where path = @path
union all
-- short paths
select 'alias', path, '', 301 from shortpath where printf('/s/%x', id) = @path
union all
-- post aliases
select 'alias', path, '', 302 from post_parameters where parameter = 'aliases' and value = @path
union all
-- deleted posts
select 'deleted', '', '', 410 from deleted where path = @path
-- just select the first result
limit 1
`, sql.Named("path", path))
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
var pathType, value1, value2 string
var status int
err = row.Scan(&pathType, &value1, &value2, &status)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
// Error
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
// No result, continue...
} else {
// Found post or alias
switch pathType {
case "post":
// Check status
switch postStatus(value1) {
case statusPublished:
// Check visibility
switch postVisibility(value2) {
case visibilityPublic, visibilityUnlisted:
alicePrivate.Append(a.checkActivityStreamsRequest, a.cacheMiddleware).ThenFunc(a.servePost).ServeHTTP(w, r)
default: // private, etc.
alice.New(a.authMiddleware).ThenFunc(a.servePost).ServeHTTP(w, r)
}
return
case statusPublishedDeleted:
if a.isLoggedIn(r) {
a.servePost(w, r)
return
}
alicePrivate.Append(a.cacheMiddleware).ThenFunc(a.serve410).ServeHTTP(w, r)
return
default: // draft, scheduled, etc.
alice.New(a.authMiddleware).ThenFunc(a.servePost).ServeHTTP(w, r)
return
}
case "alias":
// Is alias, redirect
alicePrivate.Append(cacheLoggedIn, a.cacheMiddleware).ThenFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, value1, status)
}).ServeHTTP(w, r)
return
case "deleted":
// Is deleted, serve 410
alicePrivate.Append(a.cacheMiddleware).ThenFunc(a.serve410).ServeHTTP(w, r)
return
}
}
// No post, check template assets (dynamically registered), regex redirects or serve 404 error
alice.New(a.cacheMiddleware, a.checkTemplateAssets, a.checkRegexRedirects).ThenFunc(a.serve404).ServeHTTP(w, r)
}
}
func (a *goBlog) getAppRouter() http.Handler {
for {
// Wait until router is ready
if a.d != nil {
break
}
time.Sleep(time.Millisecond * 100)
}
return a.d
}