gunk-dev/the-valley

body.go

source9f64ac954238main's published tip history
3.8 KiB
1package export
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "os"
12 "path/filepath"
13)
14
15// StageBody streams one upload body into dir, the upload's staging
16// directory, and keeps it only once it verified. It refuses a body
17// declared larger than limit before reading any of it, and a body sent
18// with a Content-Encoding, or with a Content-Length other than its
19// declared size. It hashes the body while it reads, reads at most one
20// byte past the declared size, and writes nothing outside dir: a
21// temporary file while it reads, renamed to the body's SHA-256 once the
22// size and hash match. A body already staged under that name has
23// verified, and is kept as it is.
24//
25// StageBody stops reading once the request's context is done, and keeps
26// nothing. Its error then wraps the context's cause, such as the refusal
27// Store.Writer gives a writer whose upload was discarded. Ending a read
28// that waits on the client is the caller's, as by the connection's read
29// deadline. StageBody removes its temporary file before it returns.
30//
31// It returns the staged file's path. Every refusal is an *Error.
32func StageBody(dir string, want Body, limit int64, req *http.Request) (string, error) {
33 if len(want.SHA256) != 64 || !isHex(want.SHA256) {
34 return "", refuse(CodeBadManifest, "%q is not a SHA-256 in lowercase hex", want.SHA256)
35 }
36 if want.Size > limit {
37 return "", refuse(CodeTooLarge, "%s declares %d bytes, more than this receiver's cap of %d", want.Name, want.Size, limit)
38 }
39 if len(req.Header.Values("Content-Encoding")) > 0 {
40 return "", refuse(CodeEncoding, "a body is sent as it is, with no Content-Encoding")
41 }
42 if req.ContentLength >= 0 && req.ContentLength != want.Size {
43 return "", refuse(CodeSizeMismatch, "%s is sent with Content-Length %d; the manifest declares %d", want.Name, req.ContentLength, want.Size)
44 }
45 path := filepath.Join(dir, want.SHA256)
46 if _, err := os.Lstat(path); err == nil {
47 return path, nil
48 } else if !errors.Is(err, os.ErrNotExist) {
49 return "", err
50 }
51
52 // Readable by the receiver alone, in a staging directory that is its
53 // own too. Activation makes export.json readable by others.
54 f, err := os.OpenFile(filepath.Join(dir, ".partial-"+random()), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600)
55 if err != nil {
56 return "", err
57 }
58 kept := false
59 defer func() {
60 if !kept {
61 f.Close()
62 os.Remove(f.Name())
63 }
64 }()
65 ctx := req.Context()
66 h := sha256.New()
67 n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(contextReader{ctx, req.Body}, want.Size+1))
68 if cause := context.Cause(ctx); cause != nil {
69 return "", fmt.Errorf("%s was not staged: %w", want.Name, cause)
70 }
71 if err != nil {
72 return "", refuse(CodeUnreadable, "%s could not be read: %v", want.Name, err)
73 }
74 if n > want.Size {
75 return "", refuse(CodeSizeMismatch, "%s is longer than the %d bytes the manifest declares", want.Name, want.Size)
76 }
77 if n < want.Size {
78 return "", refuse(CodeSizeMismatch, "%s is %d bytes; the manifest declares %d", want.Name, n, want.Size)
79 }
80 if got := hex.EncodeToString(h.Sum(nil)); got != want.SHA256 {
81 return "", refuse(CodeHashMismatch, "%s has SHA-256 %s; the manifest declares %s", want.Name, got, want.SHA256)
82 }
83 if err := f.Sync(); err != nil {
84 return "", err
85 }
86 if err := f.Close(); err != nil {
87 return "", err
88 }
89 if cause := context.Cause(ctx); cause != nil {
90 return "", fmt.Errorf("%s was not staged: %w", want.Name, cause)
91 }
92 if err := os.Rename(f.Name(), path); err != nil {
93 os.Remove(f.Name())
94 return "", err
95 }
96 kept = true
97 return path, nil
98}
99
100// contextReader reads r until ctx is done, and then fails with ctx's
101// cause.
102type contextReader struct {
103 ctx context.Context
104 r io.Reader
105}
106
107func (c contextReader) Read(p []byte) (int, error) {
108 if cause := context.Cause(c.ctx); cause != nil {
109 return 0, cause
110 }
111 return c.r.Read(p)
112}