gunk-dev/the-valley

body.go

source8e6da50db59amain's published tip history
2.7 KiB
1package export
2
3import (
4 "crypto/sha256"
5 "encoding/hex"
6 "errors"
7 "io"
8 "net/http"
9 "os"
10 "path/filepath"
11)
12
13// StageBody streams one upload body into dir, the upload's staging
14// directory, and keeps it only once it verified. It refuses a body
15// declared larger than limit before reading any of it, and a body sent
16// with a Content-Encoding, or with a Content-Length other than its
17// declared size. It hashes the body while it reads, reads at most one
18// byte past the declared size, and writes nothing outside dir: a
19// temporary file while it reads, renamed to the body's SHA-256 once the
20// size and hash match. A body already staged under that name has
21// verified, and is kept as it is.
22//
23// It returns the staged file's path. Every refusal is an *Error.
24func StageBody(dir string, want Body, limit int64, req *http.Request) (string, error) {
25 if len(want.SHA256) != 64 || !isHex(want.SHA256) {
26 return "", refuse(CodeBadManifest, "%q is not a SHA-256 in lowercase hex", want.SHA256)
27 }
28 if want.Size > limit {
29 return "", refuse(CodeTooLarge, "%s declares %d bytes, more than this receiver's cap of %d", want.Name, want.Size, limit)
30 }
31 if len(req.Header.Values("Content-Encoding")) > 0 {
32 return "", refuse(CodeEncoding, "a body is sent as it is, with no Content-Encoding")
33 }
34 if req.ContentLength >= 0 && req.ContentLength != want.Size {
35 return "", refuse(CodeSizeMismatch, "%s is sent with Content-Length %d; the manifest declares %d", want.Name, req.ContentLength, want.Size)
36 }
37 path := filepath.Join(dir, want.SHA256)
38 if _, err := os.Lstat(path); err == nil {
39 return path, nil
40 } else if !errors.Is(err, os.ErrNotExist) {
41 return "", err
42 }
43
44 f, err := os.CreateTemp(dir, ".partial-")
45 if err != nil {
46 return "", err
47 }
48 kept := false
49 defer func() {
50 if !kept {
51 f.Close()
52 os.Remove(f.Name())
53 }
54 }()
55 h := sha256.New()
56 n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(req.Body, want.Size+1))
57 if err != nil {
58 return "", refuse(CodeUnreadable, "%s could not be read: %v", want.Name, err)
59 }
60 if n > want.Size {
61 return "", refuse(CodeSizeMismatch, "%s is longer than the %d bytes the manifest declares", want.Name, want.Size)
62 }
63 if n < want.Size {
64 return "", refuse(CodeSizeMismatch, "%s is %d bytes; the manifest declares %d", want.Name, n, want.Size)
65 }
66 if got := hex.EncodeToString(h.Sum(nil)); got != want.SHA256 {
67 return "", refuse(CodeHashMismatch, "%s has SHA-256 %s; the manifest declares %s", want.Name, got, want.SHA256)
68 }
69 if err := f.Sync(); err != nil {
70 return "", err
71 }
72 if err := f.Close(); err != nil {
73 return "", err
74 }
75 if err := os.Rename(f.Name(), path); err != nil {
76 os.Remove(f.Name())
77 return "", err
78 }
79 kept = true
80 return path, nil
81}