gunk-dev/the-valley

server.go

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