gunk-dev/the-valley

server.go

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