gunk-dev/the-valley

server.go

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