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