| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "archive/tar" |
| 5 | "bufio" |
| 6 | "bytes" |
| 7 | "compress/gzip" |
| 8 | "context" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "net/http" |
| 13 | "slices" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "the-valley/web/export" |
| 19 | ) |
| 20 | |
| 21 | // archiveSuffix ends the last segment of an archive's route. |
| 22 | const archiveSuffix = ".tar.gz" |
| 23 | |
| 24 | // tipArchive is the last segment of the route that redirects to the |
| 25 | // archive of main's tip. main is the one name an archive's route takes in |
| 26 | // place of a full commit ID. |
| 27 | const tipArchive = "main" + archiveSuffix |
| 28 | |
| 29 | // archiveLevel is the level the server gzips an archive at. It is fixed, so |
| 30 | // one commit's archive is the same bytes on every request to one build. |
| 31 | const archiveLevel = gzip.DefaultCompression |
| 32 | |
| 33 | // archiveType is an archive's Content-Type. |
| 34 | const archiveType = "application/gzip" |
| 35 | |
| 36 | // maxLinkTarget is the longest target of a symbolic link an archive holds: |
| 37 | // the longest path Linux takes, PATH_MAX. A link with a longer target fails |
| 38 | // its archive. |
| 39 | const maxLinkTarget = 4096 |
| 40 | |
| 41 | // archiveURL is the gzipped tar archive of commit, under its project's base. |
| 42 | func archiveURL(base, commit string) string { |
| 43 | return base + "/source/archive/" + commit + archiveSuffix |
| 44 | } |
| 45 | |
| 46 | // archive answers with commit's tree as a gzipped tar archive, every entry |
| 47 | // under one directory named for the project's web name and the commit's |
| 48 | // first 12 hex digits. It holds the commit's tree and nothing else: no |
| 49 | // history, and every file byte for byte as the tree holds it. |
| 50 | // |
| 51 | // The server writes the tar itself, from git ls-tree's listing of the tree |
| 52 | // and the blobs one git cat-file --batch prints. Neither reads an |
| 53 | // attribute, so export-ignore and export-subst are not applied, and no |
| 54 | // configuration or filter touches a file. Every entry carries the commit's |
| 55 | // committer time, so the archive's bytes depend on the commit and the |
| 56 | // build alone. |
| 57 | // |
| 58 | // The listing is read first, at most MaxRead bytes of it. A tree whose |
| 59 | // files add up to more than MaxArchiveInput, or that holds more than |
| 60 | // MaxArchiveEntries entries, is refused before any file is read. The |
| 61 | // files are then streamed through the tar and gzip writers into a body |
| 62 | // like any page's: from the response budget, at most the server's |
| 63 | // maxResponse bytes, and under the request's git slot. So the server |
| 64 | // holds no file whole, only the gzipped archive. An archive refused, or |
| 65 | // one whose gzipped bytes would pass maxResponse, answers with the short |
| 66 | // page that says the page is too large, never with part of the archive. |
| 67 | func (q *request) archive(ctx context.Context, p *export.Project, repo, commit string) error { |
| 68 | tree, ok, err := commitTree(ctx, p, repo, commit) |
| 69 | if err != nil || !ok { |
| 70 | q.missing(err) |
| 71 | return nil |
| 72 | } |
| 73 | when, err := commitTime(ctx, repo, commit) |
| 74 | if err != nil { |
| 75 | return err |
| 76 | } |
| 77 | entries, refused, err := listArchive(ctx, repo, tree) |
| 78 | if err != nil { |
| 79 | return err |
| 80 | } |
| 81 | if refused != "" { |
| 82 | q.s.log(fmt.Errorf("serving %q: the archive is larger than the server sends: %s", q.r.URL.EscapedPath(), refused)) |
| 83 | q.static(http.StatusInternalServerError, htmlType, tooLargePage) |
| 84 | return nil |
| 85 | } |
| 86 | name := p.WebName + "-" + commit[:12] |
| 87 | q.drop() |
| 88 | b := &body{s: q.s, ctx: q.ctx} |
| 89 | if err := writeArchive(ctx, repo, b, name+"/", when, entries); err != nil { |
| 90 | b.free() |
| 91 | switch { |
| 92 | case errors.Is(err, errNoBudget): |
| 93 | q.busy() |
| 94 | return nil |
| 95 | case errors.Is(err, errTooLarge): |
| 96 | q.tooLarge() |
| 97 | return nil |
| 98 | } |
| 99 | return err |
| 100 | } |
| 101 | q.giveSlot() |
| 102 | q.status, q.ctype, q.body = http.StatusOK, archiveType, b |
| 103 | q.disposition = `attachment; filename="` + name + archiveSuffix + `"` |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | // commitTime is commit's committer time, which every entry of its archive |
| 108 | // carries as its modification time. |
| 109 | func commitTime(ctx context.Context, repo, commit string) (time.Time, error) { |
| 110 | out, err := export.Git(ctx, repo, maxLine, "log", "-1", "--format=%ct", commit) |
| 111 | if err != nil { |
| 112 | return time.Time{}, err |
| 113 | } |
| 114 | sec, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64) |
| 115 | if err != nil { |
| 116 | return time.Time{}, fmt.Errorf("git log gave %q for the time of %s", out, commit) |
| 117 | } |
| 118 | return time.Unix(sec, 0), nil |
| 119 | } |
| 120 | |
| 121 | // listArchive is every entry of tree, at every depth, in git's order, |
| 122 | // which puts each directory before what it holds. Each entry's Name is its |
| 123 | // path in the tree. refused says why an archive of tree passes the bounds |
| 124 | // on one: its listing is longer than MaxRead, it holds more than |
| 125 | // MaxArchiveEntries entries, or its files add up to more than |
| 126 | // MaxArchiveInput bytes. The listing stops there, and entries is then |
| 127 | // incomplete. |
| 128 | func listArchive(ctx context.Context, repo, tree string) (entries []entry, refused string, err error) { |
| 129 | var total int64 |
| 130 | err = export.GitStream(ctx, repo, MaxRead, func(r io.Reader) error { |
| 131 | recs := newRecords(r, 0, maxEntryRecord) |
| 132 | for { |
| 133 | rec, cut, err := recs.next() |
| 134 | switch { |
| 135 | case err == io.EOF: |
| 136 | return nil |
| 137 | case errors.Is(err, export.ErrOutputLimit): |
| 138 | refused = fmt.Sprintf("the listing of its tree is longer than %d bytes", MaxRead) |
| 139 | return nil |
| 140 | case err != nil: |
| 141 | return err |
| 142 | case cut: |
| 143 | return fmt.Errorf("the tree %s holds a path longer than %d bytes", tree, maxEntryRecord) |
| 144 | } |
| 145 | e, err := parseEntry(rec, false, true) |
| 146 | if err != nil { |
| 147 | return err |
| 148 | } |
| 149 | if err := archivable(e); err != nil { |
| 150 | return fmt.Errorf("the tree %s holds %q: %w", tree, e.Name, err) |
| 151 | } |
| 152 | if len(entries) == MaxArchiveEntries { |
| 153 | refused = fmt.Sprintf("its tree holds more than %d entries", MaxArchiveEntries) |
| 154 | return nil |
| 155 | } |
| 156 | if e.Type == "blob" { |
| 157 | if e.Size > MaxArchiveInput-total { |
| 158 | refused = fmt.Sprintf("its files are larger than %d bytes", MaxArchiveInput) |
| 159 | return nil |
| 160 | } |
| 161 | total += e.Size |
| 162 | } |
| 163 | entries = append(entries, e) |
| 164 | } |
| 165 | }, "ls-tree", "-r", "-t", "-l", "-z", tree) |
| 166 | return entries, refused, err |
| 167 | } |
| 168 | |
| 169 | // archivable fails for an entry an archive cannot hold as it is: one of a |
| 170 | // mode git does not give, a path with an empty, "." or ".." segment, or |
| 171 | // a symbolic link whose target is longer than maxLinkTarget. |
| 172 | func archivable(e entry) error { |
| 173 | switch { |
| 174 | case slices.ContainsFunc(strings.Split(e.Name, "/"), func(s string) bool { return s == "" || s == "." || s == ".." }): |
| 175 | return errors.New("the path has an empty, \".\" or \"..\" segment") |
| 176 | case e.Type == "tree" && e.Mode == "040000", e.Type == "commit" && e.Mode == modeSubmodule: |
| 177 | return nil |
| 178 | case e.Type != "blob" || e.Size < 0: |
| 179 | return fmt.Errorf("git ls-tree gave it the type %s and the size %d", e.Type, e.Size) |
| 180 | case e.Mode == modeSymlink && e.Size > maxLinkTarget: |
| 181 | return fmt.Errorf("a symbolic link to a target of %d bytes, longer than %d", e.Size, maxLinkTarget) |
| 182 | case e.Mode == modeSymlink, e.Mode == "100644", e.Mode == "100755": |
| 183 | return nil |
| 184 | } |
| 185 | return fmt.Errorf("git ls-tree gave it the mode %s", e.Mode) |
| 186 | } |
| 187 | |
| 188 | // writeArchive writes entries to w as a gzipped tar: the directory dir, |
| 189 | // then each entry under it, in order. A blob's content comes from one git |
| 190 | // cat-file --batch, given every blob's ID in order, and is copied into the |
| 191 | // tar as git prints it. Every entry carries when as its time, uid and gid |
| 192 | // 0, and no user or group name. A file is 0644, or 0755 when git gives it |
| 193 | // mode 100755, and a symbolic link is a link to its blob's content. A |
| 194 | // directory is a directory entry, 0755, and a submodule is one too, with |
| 195 | // nothing under it. Each header is the USTAR format when its name and |
| 196 | // target fit, and PAX when they do not. |
| 197 | func writeArchive(ctx context.Context, repo string, w io.Writer, dir string, when time.Time, entries []entry) error { |
| 198 | zw, err := gzip.NewWriterLevel(w, archiveLevel) |
| 199 | if err != nil { |
| 200 | return err |
| 201 | } |
| 202 | tw := tar.NewWriter(zw) |
| 203 | var ids bytes.Buffer |
| 204 | var printed int64 // what git cat-file prints for every blob |
| 205 | for _, e := range entries { |
| 206 | if e.Type == "blob" { |
| 207 | ids.WriteString(e.OID + "\n") |
| 208 | printed += int64(len(blobHeader(e))) + e.Size + 1 |
| 209 | } |
| 210 | } |
| 211 | write := func(blobs *bufio.Reader) error { |
| 212 | if err := tw.WriteHeader(archiveDir(dir, when)); err != nil { |
| 213 | return err |
| 214 | } |
| 215 | for _, e := range entries { |
| 216 | var err error |
| 217 | if e.Type == "blob" { |
| 218 | err = writeBlob(tw, blobs, dir, when, e) |
| 219 | } else { |
| 220 | err = tw.WriteHeader(archiveDir(dir+e.Name+"/", when)) |
| 221 | } |
| 222 | if err != nil { |
| 223 | return err |
| 224 | } |
| 225 | } |
| 226 | if blobs != nil { |
| 227 | if _, err := blobs.ReadByte(); err != io.EOF { |
| 228 | return fmt.Errorf("git cat-file printed more than the blobs asked for: %v", err) |
| 229 | } |
| 230 | } |
| 231 | if err := tw.Close(); err != nil { |
| 232 | return err |
| 233 | } |
| 234 | return zw.Close() |
| 235 | } |
| 236 | if ids.Len() == 0 { |
| 237 | return write(nil) |
| 238 | } |
| 239 | return export.GitStreamInput(ctx, repo, ids.Bytes(), printed, func(r io.Reader) error { |
| 240 | return write(bufio.NewReaderSize(r, pieceSize)) |
| 241 | }, "cat-file", "--batch") |
| 242 | } |
| 243 | |
| 244 | // archiveDir is the header of a directory at name, which ends in "/". |
| 245 | func archiveDir(name string, when time.Time) *tar.Header { |
| 246 | return &tar.Header{Typeflag: tar.TypeDir, Name: name, Mode: 0o755, ModTime: when} |
| 247 | } |
| 248 | |
| 249 | // blobHeader is the line git cat-file --batch prints before e's content. |
| 250 | func blobHeader(e entry) string { |
| 251 | return e.OID + " blob " + strconv.FormatInt(e.Size, 10) + "\n" |
| 252 | } |
| 253 | |
| 254 | // writeBlob reads e's blob from blobs, where git cat-file --batch prints |
| 255 | // it next, and writes it to tw under dir. The blob must be e's ID and |
| 256 | // size, as the listing gave them. |
| 257 | func writeBlob(tw *tar.Writer, blobs *bufio.Reader, dir string, when time.Time, e entry) error { |
| 258 | line, err := blobs.ReadSlice('\n') |
| 259 | if err != nil { |
| 260 | return fmt.Errorf("git cat-file ended before %s: %w", e.OID, err) |
| 261 | } |
| 262 | if string(line) != blobHeader(e) { |
| 263 | return fmt.Errorf("git cat-file gave %q for the blob %s of %d bytes", line, e.OID, e.Size) |
| 264 | } |
| 265 | hdr := &tar.Header{Typeflag: tar.TypeReg, Name: dir + e.Name, Mode: 0o644, Size: e.Size, ModTime: when} |
| 266 | switch e.Mode { |
| 267 | case "100755": |
| 268 | hdr.Mode = 0o755 |
| 269 | case modeSymlink: |
| 270 | target := make([]byte, e.Size) |
| 271 | if _, err := io.ReadFull(blobs, target); err != nil { |
| 272 | return fmt.Errorf("git cat-file ended within %s: %w", e.OID, err) |
| 273 | } |
| 274 | if bytes.IndexByte(target, 0) >= 0 { |
| 275 | return fmt.Errorf("the symbolic link %q has a target with a NUL byte, which tar cannot hold", e.Name) |
| 276 | } |
| 277 | hdr.Typeflag, hdr.Mode, hdr.Size, hdr.Linkname = tar.TypeSymlink, 0o777, 0, string(target) |
| 278 | } |
| 279 | if err := tw.WriteHeader(hdr); err != nil { |
| 280 | return err |
| 281 | } |
| 282 | if hdr.Typeflag == tar.TypeReg { |
| 283 | if _, err := io.CopyN(tw, blobs, e.Size); err != nil { |
| 284 | return fmt.Errorf("copying %s into the archive: %w", e.OID, err) |
| 285 | } |
| 286 | } |
| 287 | if end, err := blobs.ReadByte(); err != nil || end != '\n' { |
| 288 | return fmt.Errorf("git cat-file did not end %s with a newline: %v", e.OID, err) |
| 289 | } |
| 290 | return nil |
| 291 | } |