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