gunk-dev/the-valley

server.go

source535d69c9a69emain's published tip history
40.2 KiB
1// Package server is the web UI's read side. It serves the active export
2// of a receiver's store to anonymous readers, as the store's authorization
3// allows: the knots page, each knot, and a source browser over the main of
4// each project the authorization lets anyone read. The source browser also
5// serves a gzipped tar archive of each reachable commit.
6//
7// # Snapshots
8//
9// Every request reads the store's authorization when it arrives, opens
10// the store's active generation once, with export.Store.Open, and renders
11// its whole response from that generation under that authorization. An
12// activation during the request changes nothing the request reads. The
13// server keeps a snapshot of the newest generation it has read under one
14// authorization: the export, decoded, and its index for anyone. A request
15// opens its generation only once the generation has a snapshot under the
16// authorization it read, and every such request serves from the one
17// snapshot. A new authorization indexes the cached export again, and
18// reads no export.json.
19//
20// A request whose generation has no snapshot yet waits for a load. A load
21// runs in a worker of its own, which opens the active generation, holds
22// it while it reads and indexes the export, and then gives it back. At
23// most MaxLoads workers run at once. The requests that wait for a
24// generation share one load, so each export is read once. A waiting
25// request holds no generation, and stops waiting when its reader goes away
26// or its time runs out. A load stops once no request waits for it, and
27// the server keeps nothing of what it read.
28//
29// # Admission
30//
31// Every request's time is bounded from when it arrives: its waits, its
32// git commands and its rendering. A source request runs git, and at most
33// MaxGit run at once. A source request takes one of those slots before
34// it opens a generation, and waits for one only while fewer than
35// MaxWaiting wait. A request waits for a load only while fewer than
36// MaxLoadWaiting wait, and it is admitted among them before it opens
37// anything. A request the server cannot admit, or that runs out of time,
38// answers 503.
39//
40// A source request holds its git slot for gitTimeout at most. That time
41// runs from when it takes the slot, and covers its wait for its
42// generation's export to be read and its git commands. It gives the slot
43// back before it renders its page. A source request that runs out of
44// that time answers 503.
45//
46// A source request that shows Markdown renders it after its git commands,
47// and at most MaxRendering render at once. A request waits for a
48// rendering slot while it still holds its git slot, within its gitTimeout,
49// and gives the git slot back once it has one. So the requests that hold
50// a file's text while they wait to render are among the MaxGit. The
51// memory rendering takes grows with the file and not with the page, and
52// one render allocates less than 128 MiB (package markdown), so the
53// renders at once allocate at most MaxRendering times that.
54//
55// # Responses
56//
57// A response is rendered whole before it is written. A request gives back
58// its git slot before it renders, and its generation before it writes, so
59// a reader that reads slowly holds neither. It keeps its response until
60// the response is written.
61//
62// A response's body is at most MaxResponse bytes. A page or archive that
63// exceeds MaxResponse stops there, and the request answers with a short
64// page saying the page is too large. The server builds an archive in full
65// into the response body while holding the request's git slot. It writes
66// the tar itself from the commit's tree, applying no git attribute, and
67// streams each file through tar and gzip into the body, so it never holds
68// a whole file. An archive whose files add up to more than
69// MaxArchiveInput, or whose tree holds more than MaxArchiveEntries
70// entries, is refused with the same short page before any file is read.
71// Rendered
72// responses take their memory from a budget of MaxBuffered bytes, which
73// they give back once they are written. A request that finds the budget
74// spent answers 503.
75//
76// Responses larger than SmallPage hold at most MaxLarge of the budget
77// between them, counting their first SmallPage bytes. So readers that
78// never read large pages hold at most MaxLarge, however many there are,
79// and the rest of the budget is always there for small pages: the knots
80// page, most knots, and most directories and files.
81//
82// # Routes
83//
84// The server answers GET and HEAD alone. A project's pages are under its
85// group's name and its own web name, which need not be its identifier:
86//
87// / a redirect to the first project's tree at main's tip
88// /-/knots the knots page
89// /<group>/<project>/ a redirect to the tree at main's tip
90// /<group>/<project>/knots/<id> one knot, with its body and comments
91// /<group>/<project>/source/ a redirect to the tree at main's tip
92// /<group>/<project>/source/tree/<commit>/<path> a directory and its README
93// /<group>/<project>/source/blob/<commit>/<path> a file
94// /<group>/<project>/source/log/<commit> the history that ends at a commit
95// /<group>/<project>/source/log/<commit>?from=… an older page of that history
96// /<group>/<project>/source/archive/<commit>.tar.gz the commit's tree as a gzipped tar archive
97// /<group>/<project>/source/archive/main.tar.gz a redirect to the archive of main's tip
98// /<group>/<former name>/… a permanent redirect
99// /<alias>/… a permanent redirect
100// /-/... the server's own paths
101//
102// A group's alias redirects to the same path under the group's name, a
103// project's former name to the same path under its web name, and a
104// project's short alias to the same path under /<group>/<project>. The
105// redirect keeps the rest of the path and the query as they were sent.
106//
107// Every path but / and those under /-/ starts with a group's name or an
108// alias. No name starts with "-", so no group's path is ever one of the
109// server's own, whatever paths the server adds there. Under /-/ it serves
110// the knots page alone, and answers every other path there with the one
111// 404. / redirects to the tree at main's published tip of the first
112// project the reader may see, in the export's order, and to the knots
113// page when the reader may see none. Package export
114// refuses an export whose group names and aliases collide, or whose
115// projects' web names and former names collide within a group.
116//
117// Every source link names its group and project, a full commit ID, and a
118// path, or a full commit ID alone for an archive. A commit is served only
119// when export.Reachable finds it reachable from the project's published
120// source tip, and a path is resolved one tree entry at a time from that
121// commit's tree, so no other object can be named.
122//
123// # Access
124//
125// The store's authorization decides what is served. A request reads it
126// from the store when it arrives, and reads it again once its response is
127// rendered, before the first byte is written. A response rendered under an
128// authorization that has since been replaced is not written: the request
129// renders again under the new one. So the next request after the receiver
130// stores an authorization is held to it, with no restart and no cache in
131// between. A store with no authorization, or one that cannot be read,
132// serves no project: every page says nothing is published.
133//
134// The index a request serves from holds only the projects the
135// authorization lets anyone read, under the identity the export gives
136// them (visible). Every route, every reference between projects, every
137// alias and every redirect is built from that index, so a project the
138// authorization does not name answers exactly as a project that does not
139// exist: every 404 is the same page, made once when the server starts.
140//
141// # Safety
142//
143// Every page is rendered on the server with html/template, so everything
144// read from the export or a repository is escaped. Each response carries
145// a strict Content-Security-Policy: default-src 'self', and one inline
146// stylesheet and one inline script admitted by their SHA-256 hashes. No
147// page serves a repository file as raw content: a file is shown as escaped
148// text, and a binary file or one larger than MaxFile is not shown at all.
149// Raw repository files are served only inside a gzipped tar archive sent
150// as an attachment.
151//
152// A Markdown file, and a directory's Markdown README, is rendered by
153// package markdown, and ?plain=1 shows the file as escaped text. The
154// renderer writes only its own fixed set of elements and attributes, and
155// escapes every byte it takes from the file, raw HTML included. It
156// writes a link only for an http, https or mailto destination, or for a
157// relative one resolved to a page of the source browser at the same
158// commit, and no img, script, form or style attribute. So rendered
159// Markdown is no active content, and the policy above admits it as it
160// is.
161package server
162
163import (
164 "bytes"
165 "context"
166 "errors"
167 "fmt"
168 "io"
169 "log"
170 "net/http"
171 "net/url"
172 "os"
173 "strconv"
174 "strings"
175 "sync"
176 "syscall"
177 "time"
178
179 "the-valley/web/export"
180)
181
182// StaleAfter is how old an export may be before its pages mark it stale.
183const StaleAfter = 5 * time.Minute
184
185// The bounds on what one request reads from a repository.
186const (
187 // MaxFile is the largest file a page shows, README or otherwise.
188 MaxFile = 1 << 20
189 // MaxLines is the most lines of a file a page shows.
190 MaxLines = 10_000
191 // MaxShown is the most bytes a page spends on a file's text once it
192 // is escaped, counting each line's markup on a file page. A page
193 // stops at the line that would take it past MaxShown.
194 MaxShown = 2 << 20
195 // MaxEntries is the most entries a directory page lists.
196 MaxEntries = 1000
197 // MaxRead is the most bytes of output a page reads from one git
198 // listing: a directory's entries, or a page of history. git is
199 // stopped once it prints more.
200 MaxRead = 4 << 20
201 // MaxArchiveInput is the most bytes of files an archive holds before
202 // it is gzipped: the sizes of the files and symbolic links in its
203 // commit's tree, added up. An archive of a larger tree is refused
204 // before any file is read.
205 MaxArchiveInput = 32 << 20
206 // MaxArchiveEntries is the most entries an archive holds: its
207 // files, symbolic links, directories and submodules together. An
208 // archive of a tree that holds more is refused as one that passes
209 // MaxArchiveInput is.
210 MaxArchiveEntries = 10_000
211 // MaxDepth is the most path segments a source route takes.
212 MaxDepth = 64
213 // MaxPlanDepth is the most levels of knots a milestone's tree
214 // shows, and the most parents a knot's trail names.
215 MaxPlanDepth = 32
216 // LogPage is the number of commits on one page of a log.
217 LogPage = 50
218 // MaxFrontier is the most commits a link to an older page of a log
219 // names: the commits that page starts from.
220 MaxFrontier = 64
221 // MaxLeftToShow is the most commits a page of a log leaves to show.
222 // Its Older link starts from MaxFrontier of them, and each of the
223 // rest has a link of its own. A page ends before a merge that would
224 // leave more.
225 MaxLeftToShow = 192
226 // MaxParents is the most parents of one commit that a page of a log
227 // follows: the first MaxParents, in the commit's order. A page marks
228 // a merge that has more, and leaves none of its others to show.
229 MaxParents = 128
230 // MaxGit is the most source requests that run git at once.
231 MaxGit = 8
232 // MaxWaiting is the most source requests that wait for one of the
233 // MaxGit to finish. A source request that finds every slot taken
234 // and MaxWaiting waiting answers 503 at once.
235 MaxWaiting = 16
236 // MaxRendering is the most source requests that render Markdown at
237 // once.
238 MaxRendering = 2
239 // requestTimeout bounds a request from when it arrives: its wait for
240 // a git slot or for its generation's export to be read, its git
241 // commands and its rendering.
242 requestTimeout = 15 * time.Second
243 // gitTimeout bounds how long a source request holds its git slot,
244 // from when it takes it: its wait for its generation's export to be
245 // read, and its git commands, all of them together. A source request
246 // still holding its slot past it answers 503.
247 gitTimeout = 5 * time.Second
248 // MaxLoads is the most loads that run at once, each in a worker of
249 // its own that reads one generation's export.
250 MaxLoads = 2
251 // MaxLoadWaiting is the most requests that wait for loads. A request
252 // that would wait while MaxLoadWaiting do answers 503 at once.
253 MaxLoadWaiting = 64
254 // MaxResponse is the most bytes a response's body takes. A page
255 // that would take more stops rendering, and the request answers with
256 // a short page that says the page is too large.
257 MaxResponse = 8 << 20
258 // MaxBuffered is the most bytes of rendered responses the server
259 // holds at once, from when each starts rendering until it is
260 // written. A response takes them in pieces of pieceSize as it
261 // renders.
262 MaxBuffered = 64 << 20
263 // SmallPage is the largest response that takes from MaxBuffered
264 // alone.
265 SmallPage = 256 << 10
266 // MaxLarge is the most of MaxBuffered that responses larger than
267 // SmallPage hold between them, all of each counted. The rest,
268 // MaxBuffered less MaxLarge, is left to smaller responses.
269 MaxLarge = 48 << 20
270 // pieceSize is the size of the pieces a response is rendered into.
271 pieceSize = 64 << 10
272)
273
274// Config is what a Server serves from.
275type Config struct {
276 // Store is the receiver's state directory.
277 Store *export.Store
278 // Now is the clock an export's age is read against. Nil is time.Now.
279 Now func() time.Time
280 // Log is told of each failure a reader sees only as an error page.
281 // Nil logs with the standard logger.
282 Log func(error)
283}
284
285// Server is the read side's HTTP handler.
286type Server struct {
287 store *export.Store
288 now func() time.Time
289 log func(error)
290 // timeout is requestTimeout, gitTime is gitTimeout, and maxResponse
291 // is MaxResponse. A test shortens any of them.
292 timeout time.Duration
293 gitTime time.Duration
294 maxResponse int
295 // slots holds a token for each source request running git, and
296 // waiting one for each source request waiting for a slot.
297 slots chan struct{}
298 waiting chan struct{}
299 // renders holds a token for each source request rendering
300 // Markdown.
301 renders chan struct{}
302 // loaders holds a token for each load's worker, and loadWaiting one
303 // for each request waiting for a load.
304 loaders chan struct{}
305 loadWaiting chan struct{}
306 // pieces guards the response budget. held counts the pieces of
307 // responses being rendered or written, of MaxBuffered bytes in pieces
308 // of pieceSize. large counts the pieces of those responses that are
309 // larger than SmallPage, every piece of each, of MaxLarge bytes.
310 pieces sync.Mutex
311 held int
312 large int
313
314 mu sync.Mutex
315 // cached is the newest generation's snapshot read so far, under the
316 // authorization a load read last.
317 cached *snapshot
318 // auth is the last valid authorization readAuthorization read.
319 auth authState
320 // loads are the loads a request that waits may still join: those that
321 // have not ended, and that some request waits for.
322 loads map[*load]struct{}
323
324 // The test hooks. opened, when set, is called with each generation a
325 // request opens, before the request reads anything from it. admitted
326 // is called when a source request takes a git slot, before it opens
327 // a generation. loading is called by a load's worker with the
328 // generation it opened, before it reads the generation's export.
329 // rendering is called with a page's name before the page renders.
330 opened func(export.Generation)
331 admitted func()
332 loading func(export.Generation)
333 rendering func(name string)
334 // checked is called once a request has rendered its response, before
335 // it reads the authorization again. starting is called once that read
336 // found the authorization unchanged, with the serving lock held, before
337 // the response's headers are written.
338 checked func()
339 starting func()
340}
341
342// New is a Server over c's store.
343func New(c Config) *Server {
344 s := &Server{store: c.Store, now: c.Now, log: c.Log,
345 timeout: requestTimeout, gitTime: gitTimeout, maxResponse: MaxResponse,
346 slots: make(chan struct{}, MaxGit), waiting: make(chan struct{}, MaxWaiting),
347 renders: make(chan struct{}, MaxRendering),
348 loaders: make(chan struct{}, MaxLoads), loadWaiting: make(chan struct{}, MaxLoadWaiting),
349 loads: map[*load]struct{}{}}
350 if s.now == nil {
351 s.now = time.Now
352 }
353 if s.log == nil {
354 s.log = func(err error) { log.Print(err) }
355 }
356 return s
357}
358
359// snapshot is one generation's export, decoded, and its index under one
360// authorization, for anyone. A generation's export.json never changes once
361// it is active, and its sequence names it, and auth is the stored
362// authorization's signed note the index was built under, so a snapshot
363// serves every request that opens its generation under that authorization.
364type snapshot struct {
365 seq int64
366 auth authState
367 e *export.Export
368 idx *index
369}
370
371// authState is the stored authorization as one read found it: the signed
372// note, and the authorization parsed from it, or the error that left none.
373// Two reads are of one revision when their notes are the same bytes.
374type authState struct {
375 signed []byte
376 a *export.Authorization
377 err error
378}
379
380// same reports whether two reads found one revision of the authorization.
381func (st authState) same(o authState) bool {
382 return bytes.Equal(st.signed, o.signed) && (st.a == nil) == (o.a == nil)
383}
384
385// readAuthorization reads the stored authorization. It reads the file on
386// every call, and parses it again only when its bytes changed since the
387// last valid one it read.
388func (s *Server) readAuthorization() authState {
389 signed, err := s.store.ReadAuthorization()
390 if err != nil {
391 return authState{err: err}
392 }
393 s.mu.Lock()
394 last := s.auth
395 s.mu.Unlock()
396 if last.a != nil && bytes.Equal(last.signed, signed) {
397 return last
398 }
399 a, err := export.ReadStoredAuthorization(signed)
400 if err != nil {
401 return authState{signed: signed, err: err}
402 }
403 st := authState{signed: signed, a: a}
404 s.mu.Lock()
405 s.auth = st
406 s.mu.Unlock()
407 return st
408}
409
410// load reads the active generation's export for every request that
411// waits for it. It starts once one of those requests takes a loader slot
412// for it, and runs in a worker of its own, so a request can stop waiting
413// while the load goes on for the others.
414type load struct {
415 // wants counts the requests that wait for the load. cancel is set once
416 // the load has started, and stops its worker. The worker sets opened
417 // and seq once it has opened a generation. All are guarded by the
418 // server's mu.
419 wants int
420 cancel context.CancelFunc
421 opened bool
422 seq int64
423 auth authState
424 // started is closed once the load starts, and done once its worker
425 // ends. err is the worker's error, set before done is closed.
426 started chan struct{}
427 done chan struct{}
428 err error
429}
430
431// request is one request, the generation it serves from, and the
432// response it renders.
433type request struct {
434 s *Server
435 w http.ResponseWriter
436 r *http.Request
437 // ctx is the context the request waits and renders under. It ends
438 // at the request's deadline, or when its reader goes away. git is
439 // the context a source request holds its git slot under: it waits
440 // for its generation's export and runs git under it. git ends
441 // gitTime after the request takes its slot, or with ctx. slot gives
442 // the slot back.
443 ctx context.Context
444 git context.Context
445 slot func()
446 g export.Generation
447 e *export.Export
448 idx *index
449 now time.Time
450 // auth is the stored authorization as the request read it when it
451 // arrived. The request serves what it allows, and its response is
452 // written only if the authorization is the same when it is.
453 auth authState
454
455 // The response: a status and a page, or a redirect. It is written
456 // once the request has given back its generation and git slot, and
457 // the page's pieces are given back to the budget once it is written.
458 // disposition is the Content-Disposition of an archive, and "" for
459 // any other response.
460 status int
461 ctype string
462 disposition string
463 body *body
464 location string
465 permanent bool
466}
467
468// ServeHTTP reads the stored authorization, renders the response under
469// it, and reads it again before the first byte is written. A response the
470// authorization changed under is not written: the request is rendered
471// again under the new one, at most maxRenders times in all, and then
472// answers 503. So every response, a redirect and an error page too, is
473// one the authorization stored when it is written allows.
474func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
475 ctx, cancel := context.WithTimeout(r.Context(), s.timeout)
476 defer cancel()
477 for render := 1; ; render++ {
478 h := w.Header()
479 for k := range h {
480 delete(h, k)
481 }
482 setHeaders(h)
483 q := &request{s: s, w: w, r: r, ctx: ctx, now: s.now(), auth: s.readAuthorization()}
484 q.serve()
485 if s.checked != nil {
486 s.checked()
487 }
488 // The last read and the response's headers happen under the
489 // serving lock, shared, and the receiver renames a new
490 // authorization into place under it, exclusively. A response
491 // whose headers are written after the receiver replies was
492 // checked against the new authorization. The wait ends with the
493 // request's deadline, or when its reader goes away, and then
494 // nothing rendered is written: busy answers 503, or nothing to a
495 // reader that went away.
496 release, err := s.store.HoldServing(ctx)
497 if err != nil {
498 q.discard()
499 if ctx.Err() == nil {
500 q.s.log(fmt.Errorf("taking the serving lock: %w", err))
501 }
502 q.busy()
503 q.write(func() {})
504 return
505 }
506 if s.readAuthorization().same(q.auth) {
507 if s.starting != nil {
508 s.starting()
509 }
510 q.write(release)
511 q.drop()
512 return
513 }
514 release()
515 q.discard()
516 if render == maxRenders {
517 q.busy()
518 q.write(func() {})
519 return
520 }
521 }
522}
523
524// maxRenders is how many times a request is rendered while the stored
525// authorization keeps changing under it.
526const maxRenders = 3
527
528// serve renders the request's response. A source request is admitted
529// first, and holds its git slot until it renders, or until serve returns
530// when it renders nothing. Every request holds its generation until serve
531// returns.
532func (q *request) serve() {
533 if q.r.Method != http.MethodGet && q.r.Method != http.MethodHead {
534 q.w.Header().Set("Allow", "GET, HEAD")
535 q.page(http.StatusMethodNotAllowed, "error", "Method not allowed", errorPage{
536 Heading: "Method not allowed", Text: "This server answers GET and HEAD alone.",
537 })
538 return
539 }
540 if q.auth.a == nil {
541 if !errors.Is(q.auth.err, export.ErrNoAuthorization) {
542 q.s.log(fmt.Errorf("the stored authorization cannot be read, so nothing is served: %w", q.auth.err))
543 }
544 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
545 Heading: "Nothing published yet", Text: "This server holds no authorization to serve anything.",
546 })
547 return
548 }
549 parts, ok := segments(q.r.URL.EscapedPath())
550 wait := q.ctx
551 if ok && runsGit(parts) {
552 done, admitted := q.s.admit(q.ctx)
553 if !admitted {
554 q.busy()
555 return
556 }
557 q.slot = done
558 defer q.giveSlot()
559 var cancel context.CancelFunc
560 q.git, cancel = context.WithTimeout(q.ctx, q.s.gitTime)
561 defer cancel()
562 wait = q.git
563 if q.s.admitted != nil {
564 q.s.admitted()
565 }
566 }
567 g, snap, release, err := q.s.open(wait, q.auth)
568 defer release()
569 switch {
570 case errors.Is(err, export.ErrNoExport):
571 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
572 Heading: "Nothing published yet", Text: "No export has been activated on this server.",
573 })
574 return
575 case errors.Is(err, errLoadsFull), errors.Is(err, errAuthorizationChanged):
576 q.busy()
577 return
578 case err != nil:
579 q.fail(err)
580 return
581 }
582 if q.s.opened != nil {
583 q.s.opened(g)
584 }
585 q.g, q.e, q.idx = g, snap.e, snap.idx
586 q.route(parts, ok)
587}
588
589// runsGit reports whether a path is a source route that reads a
590// repository: a tree, a file, a log or an archive of something that may be
591// a group's project. The redirect to the archive of main's tip reads none,
592// as the redirect to the tree at main's tip reads none. runsGit reads the
593// path's shape alone, before the export is read, so a path through a
594// group's alias that has the shape takes a git slot too, and gives it back
595// when it redirects.
596func runsGit(parts []string) bool {
597 return len(parts) >= 4 && export.ValidName(parts[0]) && export.ValidName(parts[1]) && parts[2] == "source" &&
598 (parts[3] == "tree" || parts[3] == "blob" || parts[3] == "log" ||
599 parts[3] == "archive" && !(len(parts) == 5 && parts[4] == tipArchive))
600}
601
602// giveSlot gives back the request's git slot, when it holds one.
603func (q *request) giveSlot() {
604 if q.slot != nil {
605 q.slot()
606 q.slot = nil
607 }
608}
609
610// admit takes a git slot for a source request. When every slot is taken,
611// it waits for one until ctx is done, unless MaxWaiting requests wait
612// already. done gives the slot back.
613func (s *Server) admit(ctx context.Context) (done func(), ok bool) {
614 give := func() { <-s.slots }
615 select {
616 case s.slots <- struct{}{}:
617 return give, true
618 default:
619 }
620 select {
621 case s.waiting <- struct{}{}:
622 default:
623 return nil, false
624 }
625 defer func() { <-s.waiting }()
626 select {
627 case s.slots <- struct{}{}:
628 return give, true
629 case <-ctx.Done():
630 return nil, false
631 }
632}
633
634// errLoadsFull is open's error for a request that would wait for a load
635// while MaxLoadWaiting requests wait already.
636var errLoadsFull = errors.New("too many requests wait for exports to be read")
637
638// errAuthorizationChanged is open's error for a request whose
639// authorization was replaced while it waited. ServeHTTP renders it again
640// under the new one.
641var errAuthorizationChanged = errors.New("the stored authorization changed")
642
643// open opens the active generation once its snapshot under auth is
644// cached, and returns both. release gives the generation back.
645//
646// A request whose active generation has no snapshot waits for a load,
647// and opens nothing until the load ends. It is admitted among the
648// MaxLoadWaiting requests that may wait before it waits, and it keeps its
649// place until open returns. Once the load ends it looks again, since
650// another generation may have been activated meanwhile.
651func (s *Server) open(ctx context.Context, auth authState) (g export.Generation, snap *snapshot, release func(), err error) {
652 release = func() {}
653 waiting := false
654 defer func() {
655 if waiting {
656 <-s.loadWaiting
657 }
658 }()
659 for {
660 seq, err := s.store.Active()
661 if err != nil {
662 return g, nil, release, err
663 }
664 s.mu.Lock()
665 snap = s.cached
666 s.mu.Unlock()
667 if snap != nil && snap.seq == seq && snap.auth.same(auth) {
668 g, release, err = s.store.Open()
669 if err != nil || g.Sequence == seq {
670 return g, snap, release, err
671 }
672 release() // active moved on since it was read
673 release = func() {}
674 continue
675 }
676 if !waiting {
677 select {
678 case s.loadWaiting <- struct{}{}:
679 waiting = true
680 default:
681 return g, nil, release, errLoadsFull
682 }
683 }
684 if err := s.await(ctx, seq, auth); err != nil {
685 return g, nil, release, err
686 }
687 if !s.readAuthorization().same(auth) {
688 return g, nil, release, errAuthorizationChanged
689 }
690 }
691}
692
693// await waits until a load of generation seq under auth, or of a newer
694// generation, ends, or until ctx is done. It joins a load that will read
695// one of those, since a worker reads whatever generation is active and
696// whatever authorization is stored once it starts, and otherwise makes
697// one.
698//
699// A load starts only once one of its requests takes a loader slot for
700// it. While every slot is taken, each of its requests waits for one, and
701// the first to take one starts the load, so no load is queued that no
702// request waits for. A request that stops waiting leaves the load, and
703// the last to leave stops it.
704func (s *Server) await(ctx context.Context, seq int64, auth authState) error {
705 s.mu.Lock()
706 if c := s.cached; c != nil && (c.seq > seq || c.seq == seq && c.auth.same(auth)) {
707 s.mu.Unlock()
708 return nil
709 }
710 var l *load
711 for m := range s.loads {
712 if !m.opened || m.seq > seq || m.seq == seq && m.auth.same(auth) {
713 l = m
714 break
715 }
716 }
717 if l == nil {
718 l = &load{started: make(chan struct{}), done: make(chan struct{})}
719 s.loads[l] = struct{}{}
720 }
721 l.wants++
722 s.mu.Unlock()
723 select {
724 case <-l.started:
725 case s.loaders <- struct{}{}:
726 if !s.start(l) {
727 <-s.loaders
728 }
729 case <-ctx.Done():
730 s.leave(l)
731 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
732 }
733 select {
734 case <-l.done:
735 return l.err
736 case <-ctx.Done():
737 s.leave(l)
738 return fmt.Errorf("waiting for generation %d's export to be read: %w", seq, ctx.Err())
739 }
740}
741
742// start starts l's worker, for the request that took a loader slot for
743// it. It is false when another request started it already.
744func (s *Server) start(l *load) bool {
745 s.mu.Lock()
746 defer s.mu.Unlock()
747 if l.cancel != nil {
748 return false
749 }
750 ctx, cancel := context.WithCancel(context.Background())
751 l.cancel = cancel
752 close(l.started)
753 go s.run(ctx, l)
754 return true
755}
756
757// leave is a request that stopped waiting for l. Once no request waits for
758// it, no request may join it, and a load that started is stopped.
759func (s *Server) leave(l *load) {
760 s.mu.Lock()
761 defer s.mu.Unlock()
762 if l.wants--; l.wants > 0 {
763 return
764 }
765 delete(s.loads, l)
766 if l.cancel != nil {
767 l.cancel()
768 }
769}
770
771// run is l's worker. It caches the snapshot it reads when the snapshot's
772// generation is newer than the cached one's, or the same generation under
773// another authorization, so a load of an older generation never displaces
774// a newer. A load that was stopped caches nothing: leave stops it under
775// mu, and run looks under mu. The worker gives back its generation before
776// it ends, and then its loader slot.
777func (s *Server) run(ctx context.Context, l *load) {
778 snap, err := s.read(ctx, l)
779 s.mu.Lock()
780 delete(s.loads, l)
781 if snap != nil && ctx.Err() == nil && (s.cached == nil || s.cached.seq < snap.seq ||
782 s.cached.seq == snap.seq && !s.cached.auth.same(snap.auth)) {
783 s.cached = snap
784 }
785 l.err = err
786 s.mu.Unlock()
787 l.cancel()
788 close(l.done)
789 <-s.loaders
790}
791
792// read opens the active generation for l, reads the stored
793// authorization, and holds the generation while it reads and indexes the
794// generation's export under that authorization. It reads nothing when the
795// generation is cached already under that authorization or another load
796// reads the same, and its waiting requests look again. A generation cached
797// under another authorization is not read again: its export is indexed
798// anew. It stops reading once ctx is done.
799func (s *Server) read(ctx context.Context, l *load) (snap *snapshot, err error) {
800 // Cancellation can close the file during any operation. Report the
801 // context error instead of the resulting descriptor error.
802 defer func() {
803 if stopped := ctx.Err(); stopped != nil {
804 snap, err = nil, stopped
805 }
806 }()
807 if err := ctx.Err(); err != nil {
808 return nil, err
809 }
810 g, release, err := s.store.Open()
811 if err != nil {
812 return nil, err
813 }
814 defer release()
815 auth := s.readAuthorization()
816 if auth.a == nil {
817 return nil, nil
818 }
819 s.mu.Lock()
820 cached := s.cached
821 read := cached == nil || cached.seq < g.Sequence || cached.seq == g.Sequence && !cached.auth.same(auth)
822 for m := range s.loads {
823 if m != l && m.opened && m.seq == g.Sequence && m.auth.same(auth) {
824 read = false
825 }
826 }
827 l.opened, l.seq, l.auth = true, g.Sequence, auth
828 s.mu.Unlock()
829 if !read {
830 return nil, nil
831 }
832 if cached != nil && cached.seq == g.Sequence {
833 idx, err := newIndex(ctx, cached.e, visible(cached.e, auth.a, export.Anyone))
834 if err != nil {
835 return nil, err
836 }
837 return &snapshot{seq: g.Sequence, auth: auth, e: cached.e, idx: idx}, nil
838 }
839 if s.loading != nil {
840 s.loading(g)
841 }
842 f, err := os.OpenFile(g.ExportPath(), os.O_RDONLY|syscall.O_NONBLOCK, 0)
843 if err != nil {
844 return nil, err
845 }
846 defer f.Close()
847 // Nonblocking open avoids waiting for a FIFO writer. Go's file poller
848 // waits for reads, and Close wakes a read when the last waiter leaves.
849 stop := context.AfterFunc(ctx, func() { _ = f.Close() })
850 defer stop()
851 info, err := f.Stat()
852 if err != nil {
853 return nil, err
854 }
855 data, err := io.ReadAll(&contextReader{ctx: ctx, r: f, waitForData: info.Mode()&os.ModeNamedPipe != 0})
856 if ctx.Err() != nil {
857 return nil, ctx.Err()
858 }
859 if err != nil {
860 return nil, fmt.Errorf("reading generation %d's export: %w", g.Sequence, err)
861 }
862 e, err := export.DecodeContext(ctx, bytes.NewReader(data))
863 if err != nil {
864 return nil, err
865 }
866 if err := ctx.Err(); err != nil {
867 return nil, err
868 }
869 idx, err := newIndex(ctx, e, visible(e, auth.a, export.Anyone))
870 if err != nil {
871 return nil, err
872 }
873 return &snapshot{seq: g.Sequence, auth: auth, e: e, idx: idx}, nil
874}
875
876// contextReader reads from r until ctx is done.
877type contextReader struct {
878 ctx context.Context
879 r io.Reader
880 waitForData bool
881}
882
883func (c *contextReader) Read(p []byte) (int, error) {
884 for {
885 if err := c.ctx.Err(); err != nil {
886 return 0, err
887 }
888 n, err := c.r.Read(p)
889 if n > 0 {
890 c.waitForData = false
891 }
892 if !c.waitForData || err != io.EOF {
893 return n, err
894 }
895 // A nonblocking FIFO reports EOF before its first writer arrives.
896 // Wait for that writer without holding a blocking open syscall.
897 timer := time.NewTimer(10 * time.Millisecond)
898 select {
899 case <-c.ctx.Done():
900 timer.Stop()
901 return 0, c.ctx.Err()
902 case <-timer.C:
903 }
904 }
905}
906
907// route dispatches on the path's segments, each unescaped on its own, so
908// an escaped slash stays inside its segment. ok is false for a path whose
909// segments do not unescape. The first segment is a group's name or an
910// alias, and under a group's name the second is a project's name.
911func (q *request) route(parts []string, ok bool) {
912 switch {
913 case !ok:
914 q.notFound()
915 case len(parts) == 1 && parts[0] == "":
916 q.landing()
917 case len(parts) == 2 && parts[0] == own && parts[1] == "knots":
918 q.plan()
919 case parts[0] == own:
920 q.notFound()
921 default:
922 if to, ok := q.idx.aliases[parts[0]]; ok {
923 q.moved(to, 1)
924 return
925 }
926 if len(parts) >= 2 {
927 if p := q.idx.groups[parts[0]][parts[1]]; p != nil {
928 q.projectRoute(p.Name, parts[2:])
929 return
930 }
931 if to, ok := q.idx.formers[parts[0]][parts[1]]; ok {
932 q.moved(to, 2)
933 return
934 }
935 }
936 q.notFound()
937 }
938}
939
940// projectRoute dispatches on the segments of a path after its group's and
941// its project's names.
942func (q *request) projectRoute(project string, rest []string) {
943 switch {
944 case len(rest) == 0, len(rest) == 1 && rest[0] == "":
945 q.home(project)
946 case len(rest) == 2 && rest[0] == "knots":
947 q.knot(project, rest[1])
948 case len(rest) >= 1 && rest[0] == "source":
949 q.source(project, rest[1:])
950 default:
951 q.notFound()
952 }
953}
954
955// moved answers a path under an alias or a former name with a permanent
956// redirect to the same path under to, the escaped URL the path's first n
957// segments stand for. The rest of the path after them, and the query,
958// are kept as they were sent, even a query that is a bare "?".
959func (q *request) moved(to string, n int) {
960 esc := strings.Split(strings.TrimPrefix(q.r.URL.EscapedPath(), "/"), "/")
961 rest := ""
962 if len(esc) > n {
963 rest = "/" + strings.Join(esc[n:], "/")
964 }
965 if q.r.URL.RawQuery != "" || q.r.URL.ForceQuery {
966 rest += "?" + q.r.URL.RawQuery
967 }
968 q.location, q.permanent = to+rest, true
969}
970
971// own is the first segment of the server's own paths, /-/. No group's
972// name, and no alias, can be it, or start with it.
973const own = "-"
974
975// knotsURL is the knots page's path, the one page the server serves
976// under /-/.
977const knotsURL = "/" + own + "/knots"
978
979// landing answers / with a redirect to the page of the first project the
980// reader may see, in the index's order: the tree at its published tip.
981// With no project to see, it redirects to the knots page.
982func (q *request) landing() {
983 if len(q.idx.public) == 0 {
984 q.redirect(knotsURL)
985 return
986 }
987 q.home(q.idx.public[0])
988}
989
990// home answers /<group>/<project>/, and /<group>/<project>, with a
991// redirect to the project's page: the tree at its published tip, with its
992// README.
993func (q *request) home(project string) {
994 p, ok := q.project(project)
995 if !ok {
996 q.notFound()
997 return
998 }
999 q.redirect(treeURL(q.idx.bases[p.Name], p.SourceTip, nil))
1000}
1001
1002func segments(escaped string) ([]string, bool) {
1003 rest, ok := strings.CutPrefix(escaped, "/")
1004 if !ok {
1005 return nil, false
1006 }
1007 parts := strings.Split(rest, "/")
1008 for i, p := range parts {
1009 u, err := url.PathUnescape(p)
1010 if err != nil {
1011 return nil, false
1012 }
1013 parts[i] = u
1014 }
1015 return parts, true
1016}
1017
1018// project is the export's project called name, when the export holds it
1019// as public, in a group. Every route that names a project asks here
1020// first, and a project it refuses answers as one that does not exist.
1021func (q *request) project(name string) (*export.Project, bool) { return q.idx.project(name) }
1022
1023func (idx *index) project(name string) (*export.Project, bool) {
1024 p, ok := idx.projects[name]
1025 if _, placed := idx.bases[name]; !ok || !placed {
1026 return nil, false
1027 }
1028 return p, true
1029}
1030
1031// notFound is the one 404 page, whatever was not found. It is made once,
1032// when the server starts, and names nothing of the request or the export,
1033// so a hidden project, a missing one, an unreachable commit and a missing
1034// path all answer alike, byte for byte.
1035func (q *request) notFound() {
1036 q.static(http.StatusNotFound, htmlType, notFoundPage)
1037}
1038
1039// fail logs err and answers with the one 500 page, which says nothing of
1040// the failure. A reader that went away is answered with nothing: git
1041// killed for it fails, and that is no failure of the server's. A request
1042// that ran out of time, or held its git slot past gitTime, answers 503.
1043func (q *request) fail(err error) {
1044 if q.r.Context().Err() != nil {
1045 return
1046 }
1047 if q.ctx.Err() == nil && q.git != nil && q.git.Err() != nil {
1048 err = fmt.Errorf("the request held its git slot past %v: %w", q.s.gitTime, err)
1049 }
1050 q.s.log(err)
1051 if q.ctx.Err() != nil || q.git != nil && q.git.Err() != nil {
1052 q.busy()
1053 return
1054 }
1055 q.page(http.StatusInternalServerError, "error", "Error", errorPage{
1056 Heading: "Something went wrong", Text: "The server could not read this page.",
1057 })
1058}
1059
1060// busy answers a request the server has no room for: a source request it
1061// could not admit, a request that ran out of time, or a page the response
1062// budget has no room for. A reader that went away is answered with
1063// nothing.
1064func (q *request) busy() {
1065 if q.r.Context().Err() != nil {
1066 return
1067 }
1068 q.w.Header().Set("Retry-After", "5")
1069 q.static(http.StatusServiceUnavailable, htmlType, busyPage)
1070}
1071
1072// discard drops the rendered response, a page or a redirect, so that none
1073// of it is written.
1074func (q *request) discard() {
1075 q.drop()
1076 q.status, q.disposition, q.body, q.location, q.permanent = 0, "", nil, "", false
1077}
1078
1079// redirect answers with a redirect to url.
1080func (q *request) redirect(url string) { q.location = url }
1081
1082// write writes the rendered response, or nothing for a reader that went
1083// away. It returns once the response is written, or the connection
1084// failed or timed out. A permanent redirect names its location as it was
1085// made, with no cleaning, so the path it redirects to is the one the
1086// reader sent under another name.
1087//
1088// released is called once the headers are written, and before the body is,
1089// or at once when there is nothing to write.
1090func (q *request) write(released func()) {
1091 defer released()
1092 switch {
1093 case q.location != "" && q.permanent:
1094 q.w.Header().Set("Location", q.location)
1095 q.w.WriteHeader(http.StatusPermanentRedirect)
1096 case q.location != "":
1097 http.Redirect(releasing{q.w, released}, q.r, q.location, http.StatusFound)
1098 case q.status != 0:
1099 h := q.w.Header()
1100 h.Set("Content-Type", q.ctype)
1101 if q.disposition != "" {
1102 h.Set("Content-Disposition", q.disposition)
1103 }
1104 h.Set("Content-Length", strconv.Itoa(q.body.n))
1105 q.w.WriteHeader(q.status)
1106 released()
1107 for _, p := range q.body.pieces {
1108 if _, err := q.w.Write(p); err != nil {
1109 return
1110 }
1111 }
1112 }
1113}
1114
1115// releasing is a response writer that calls released once the headers are
1116// written, before any of the body is, so http.Redirect writes its short
1117// body after the serving lock is let go, as every other response does.
1118type releasing struct {
1119 http.ResponseWriter
1120 released func()
1121}
1122
1123func (w releasing) WriteHeader(status int) {
1124 w.ResponseWriter.WriteHeader(status)
1125 w.released()
1126}
1127
1128// setHeaders sets the headers every response carries.
1129func setHeaders(h http.Header) {
1130 h.Set("Content-Security-Policy", csp)
1131 h.Set("X-Content-Type-Options", "nosniff")
1132 h.Set("X-Frame-Options", "DENY")
1133 h.Set("Referrer-Policy", "no-referrer")
1134 h.Set("Cross-Origin-Opener-Policy", "same-origin")
1135 h.Set("Cross-Origin-Resource-Policy", "same-origin")
1136 h.Set("Cache-Control", "no-cache")
1137}