| 1 | // Command valley-web-receive is the web export receiver. It takes the |
| 2 | // publisher's signed authorizations and uploads into a store, by the |
| 3 | // protocol package export defines, and valley-web serves what it activates |
| 4 | // as the newest authorization allows. |
| 5 | // |
| 6 | // valley-web-receive --state FILE --listen ADDR --instance NAME |
| 7 | // --destination NAME --verifiers FILE --token-file FILE |
| 8 | // [--max-body SIZE] [--max-upload SIZE] |
| 9 | // [--max-storage SIZE] |
| 10 | // |
| 11 | // It opens the store with export.OpenStore, which creates its layout and |
| 12 | // finishes an activation a crash interrupted, and it is the store's one |
| 13 | // writer. valley-web runs beside it as a process of its own, as another |
| 14 | // user, and opens the same store with export.OpenReadOnly. The two share |
| 15 | // nothing but the store: each has its own listener, its own limits and its |
| 16 | // own memory, so a saturated upload leaves valley-web serving. |
| 17 | // |
| 18 | // Every request must carry the token in --token-file. A request without |
| 19 | // it is refused as unauthenticated before anything else of it is read, |
| 20 | // and takes none of the receiver's request slots. The receiver serves |
| 21 | // until it is sent SIGINT or SIGTERM. It logs to standard error, and |
| 22 | // prints the address it listens on once it does. |
| 23 | package main |
| 24 | |
| 25 | import ( |
| 26 | "context" |
| 27 | "errors" |
| 28 | "flag" |
| 29 | "fmt" |
| 30 | "io" |
| 31 | "log" |
| 32 | "math" |
| 33 | "net" |
| 34 | "net/http" |
| 35 | "os" |
| 36 | "os/signal" |
| 37 | "strconv" |
| 38 | "strings" |
| 39 | "sync" |
| 40 | "syscall" |
| 41 | "time" |
| 42 | |
| 43 | "the-valley/note" |
| 44 | "the-valley/web/export" |
| 45 | ) |
| 46 | |
| 47 | const usage = `usage: valley-web-receive --state FILE --listen ADDR --instance NAME |
| 48 | --destination NAME --verifiers FILE --token-file FILE |
| 49 | [--max-body SIZE] [--max-upload SIZE] |
| 50 | [--max-storage SIZE] |
| 51 | |
| 52 | Receive signed authorizations and web export uploads from |
| 53 | valley-web-publish into a store that valley-web serves. |
| 54 | |
| 55 | --state FILE the store's descriptor file, such as |
| 56 | /var/lib/valley-web/store; when FILE does not |
| 57 | exist, the receiver creates it and the payload |
| 58 | directory v2 beside it; the receiver is the store's |
| 59 | only writer, and refuses a directory |
| 60 | --listen ADDR TCP address to listen on, such as 127.0.0.1:8081; |
| 61 | port 0 picks a free port |
| 62 | --instance NAME instance name required in every manifest |
| 63 | --destination NAME destination name required in every manifest (this |
| 64 | receiver's name) |
| 65 | --verifiers FILE file of publisher verifier lines, one per line, as |
| 66 | written to <state>/verifier; every manifest must |
| 67 | verify under one of them |
| 68 | --token-file FILE file holding the bearer token required in every |
| 69 | request's Authorization header: one line of 32 to |
| 70 | 256 visible ASCII characters, matching the file |
| 71 | passed to the publisher's --receiver-token |
| 72 | --max-body SIZE maximum declared byte size of a single body |
| 73 | (default 1G) |
| 74 | --max-upload SIZE maximum total declared byte size of the unique |
| 75 | bodies in one manifest, each SHA-256 counted once |
| 76 | (default 2G) |
| 77 | --max-storage SIZE best-effort cap on the disk space used by the |
| 78 | store's payload directory, including held |
| 79 | generations, staged bodies, and built repositories |
| 80 | (default 8G) |
| 81 | |
| 82 | A SIZE is a positive byte count, optionally suffixed with K, M, G, or T |
| 83 | for KiB, MiB, GiB, or TiB. |
| 84 | |
| 85 | valley-web-receive prints "valley-web-receive: listening on ADDR" once it |
| 86 | listens, and stops on SIGINT or SIGTERM. |
| 87 | ` |
| 88 | |
| 89 | // How many requests and connections the receiver takes at once. An |
| 90 | // authenticated upload request past maxRequests, or authorization request |
| 91 | // past maxAuthorizations, is answered 503 with no refusal, which the |
| 92 | // publisher retries after a pause. The two are counted apart, so uploads |
| 93 | // that fill their slots leave an authorization room. A connection past |
| 94 | // maxConns waits in the listen queue until another closes. |
| 95 | const ( |
| 96 | maxRequests = 4 |
| 97 | maxAuthorizations = 2 |
| 98 | maxConns = 32 |
| 99 | ) |
| 100 | |
| 101 | // How long a request may take, from when its headers have been read. A |
| 102 | // commit fetches and checks every bundle it was sent. A stop gives the |
| 103 | // requests in flight stopTimeout to finish, and then ends them and waits |
| 104 | // drainTimeout more for them, and the git they run, to stop. |
| 105 | const ( |
| 106 | headerTimeout = 10 * time.Second |
| 107 | shortTimeout = 10 * time.Second |
| 108 | authorizationTimeout = 30 * time.Second |
| 109 | manifestTimeout = time.Minute |
| 110 | // pruneTimeout bounds how long a prune after an authorization waits |
| 111 | // for the readers of the active generation. |
| 112 | pruneTimeout = 5 * time.Minute |
| 113 | bodyTimeout = 30 * time.Minute |
| 114 | commitTimeout = 30 * time.Minute |
| 115 | idleTimeout = time.Minute |
| 116 | stopTimeout = 10 * time.Second |
| 117 | drainTimeout = 5 * time.Second |
| 118 | ) |
| 119 | |
| 120 | func main() { |
| 121 | ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) |
| 122 | defer stop() |
| 123 | err := run(ctx, os.Args[1:], os.Stderr) |
| 124 | var bad usageError |
| 125 | switch { |
| 126 | case errors.As(err, &bad): |
| 127 | fmt.Fprintf(os.Stderr, "valley-web-receive: %v\n\n%s", err, usage) |
| 128 | os.Exit(2) |
| 129 | case err != nil: |
| 130 | fmt.Fprintf(os.Stderr, "valley-web-receive: %v\n", err) |
| 131 | os.Exit(1) |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | // usageError is a command line valley-web-receive cannot run with. |
| 136 | type usageError struct{ error } |
| 137 | |
| 138 | // run receives until ctx is done, then shuts the server down, letting |
| 139 | // requests in flight finish for a few seconds. It then ends the requests |
| 140 | // still running, and waits a few seconds more for them and the git they |
| 141 | // run to stop. A commit stopped part way leaves the active export as it |
| 142 | // was, as a crash does. |
| 143 | func run(ctx context.Context, args []string, stderr io.Writer) error { |
| 144 | flags := flag.NewFlagSet("valley-web-receive", flag.ContinueOnError) |
| 145 | flags.SetOutput(io.Discard) |
| 146 | state := flags.String("state", "", "") |
| 147 | listen := flags.String("listen", "", "") |
| 148 | instance := flags.String("instance", "", "") |
| 149 | destination := flags.String("destination", "", "") |
| 150 | verifiers := flags.String("verifiers", "", "") |
| 151 | tokenFile := flags.String("token-file", "", "") |
| 152 | maxBody, maxUpload, maxStorage := byteSize(1<<30), byteSize(2<<30), byteSize(8<<30) |
| 153 | flags.Var(&maxBody, "max-body", "") |
| 154 | flags.Var(&maxUpload, "max-upload", "") |
| 155 | flags.Var(&maxStorage, "max-storage", "") |
| 156 | if err := flags.Parse(args); errors.Is(err, flag.ErrHelp) { |
| 157 | fmt.Fprint(stderr, usage) |
| 158 | return nil |
| 159 | } else if err != nil { |
| 160 | return usageError{err} |
| 161 | } |
| 162 | switch { |
| 163 | case flags.NArg() > 0: |
| 164 | return usageError{fmt.Errorf("unexpected argument %q", flags.Arg(0))} |
| 165 | case *state == "": |
| 166 | return usageError{errors.New("--state is required")} |
| 167 | case *listen == "": |
| 168 | return usageError{errors.New("--listen is required")} |
| 169 | case !export.ValidName(*instance): |
| 170 | return usageError{fmt.Errorf("--instance %q must be 1 to 64 ASCII letters, digits, dots, dashes, or underscores, starting with a letter or digit", *instance)} |
| 171 | case !export.ValidName(*destination): |
| 172 | return usageError{fmt.Errorf("--destination %q must be 1 to 64 ASCII letters, digits, dots, dashes, or underscores, starting with a letter or digit", *destination)} |
| 173 | case *verifiers == "": |
| 174 | return usageError{errors.New("--verifiers is required")} |
| 175 | case *tokenFile == "": |
| 176 | return usageError{errors.New("--token-file is required")} |
| 177 | } |
| 178 | |
| 179 | token, err := export.ReadToken(*tokenFile) |
| 180 | if err != nil { |
| 181 | return err |
| 182 | } |
| 183 | data, err := os.ReadFile(*verifiers) |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | keys, err := note.ParseVerifierKeys(data) |
| 188 | if err != nil { |
| 189 | // The parser's error quotes the line, which would print a token |
| 190 | // given here by mistake. |
| 191 | return fmt.Errorf("cannot parse verifier lines in %s", *verifiers) |
| 192 | } |
| 193 | if len(keys) == 0 { |
| 194 | return fmt.Errorf("%s contains no verifier lines", *verifiers) |
| 195 | } |
| 196 | |
| 197 | logger := log.New(stderr, "valley-web-receive: ", log.LstdFlags) |
| 198 | store, err := export.OpenStore(*state, func(err error) { logger.Print(err) }) |
| 199 | if err != nil { |
| 200 | return err |
| 201 | } |
| 202 | store.MaxStorage = int64(maxStorage) |
| 203 | ln, err := net.Listen("tcp", *listen) |
| 204 | if err != nil { |
| 205 | return err |
| 206 | } |
| 207 | rv := &receiver{ |
| 208 | store: store, verifiers: keys, instance: *instance, destination: *destination, token: token, |
| 209 | maxBody: int64(maxBody), maxUpload: int64(maxUpload), |
| 210 | log: logger, slots: make(chan struct{}, maxRequests), authSlots: make(chan struct{}, maxAuthorizations), |
| 211 | pruneDelay: 100 * time.Millisecond, |
| 212 | } |
| 213 | srv := &http.Server{ |
| 214 | Handler: rv, |
| 215 | // The server's own handler for OPTIONS * reads the body before |
| 216 | // any check, with no deadline. Every request goes to rv instead, |
| 217 | // which refuses one without the token before it reads anything. |
| 218 | DisableGeneralOptionsHandler: true, |
| 219 | ReadHeaderTimeout: headerTimeout, |
| 220 | IdleTimeout: idleTimeout, |
| 221 | MaxHeaderBytes: 16 << 10, |
| 222 | ErrorLog: logger, |
| 223 | } |
| 224 | fmt.Fprintf(stderr, "valley-web-receive: listening on %s\n", ln.Addr()) |
| 225 | served := make(chan error, 1) |
| 226 | go func() { served <- srv.Serve(limitListener(ln, maxConns)) }() |
| 227 | select { |
| 228 | case err := <-served: |
| 229 | return err |
| 230 | case <-ctx.Done(): |
| 231 | } |
| 232 | shutdown, cancel := context.WithTimeout(context.Background(), stopTimeout) |
| 233 | defer cancel() |
| 234 | if err := srv.Shutdown(shutdown); err != nil { |
| 235 | // Requests still running are ended: closing their connections |
| 236 | // cancels their contexts, which kills the process group of the |
| 237 | // git a commit runs. |
| 238 | // Close returns without waiting for them, and a process that |
| 239 | // exited first could leave that git running. |
| 240 | srv.Close() |
| 241 | drained, cancel := context.WithTimeout(context.Background(), drainTimeout) |
| 242 | defer cancel() |
| 243 | if !rv.drain(drained) { |
| 244 | logger.Printf("requests were still running %v after connections were closed", drainTimeout) |
| 245 | } |
| 246 | } |
| 247 | if err := <-served; !errors.Is(err, http.ErrServerClosed) { |
| 248 | return err |
| 249 | } |
| 250 | return nil |
| 251 | } |
| 252 | |
| 253 | // limitListener accepts at most n connections at once. Accept waits for |
| 254 | // one to close before it takes another, or for the listener to be closed. |
| 255 | func limitListener(ln net.Listener, n int) net.Listener { |
| 256 | return &limited{Listener: ln, slots: make(chan struct{}, n), closed: make(chan struct{})} |
| 257 | } |
| 258 | |
| 259 | type limited struct { |
| 260 | net.Listener |
| 261 | slots chan struct{} |
| 262 | closed chan struct{} |
| 263 | once sync.Once |
| 264 | } |
| 265 | |
| 266 | // Accept returns net.ErrClosed once the listener is closed, even while it |
| 267 | // waits for a slot. Server.Shutdown and Server.Close wait for Accept to |
| 268 | // return, so a wait that closing the listener did not end would hold up |
| 269 | // the stop for as long as every connection stayed open. |
| 270 | func (l *limited) Accept() (net.Conn, error) { |
| 271 | select { |
| 272 | case l.slots <- struct{}{}: |
| 273 | case <-l.closed: |
| 274 | return nil, net.ErrClosed |
| 275 | } |
| 276 | c, err := l.Listener.Accept() |
| 277 | if err != nil { |
| 278 | <-l.slots |
| 279 | return nil, err |
| 280 | } |
| 281 | return &limitedConn{Conn: c, release: sync.OnceFunc(func() { <-l.slots })}, nil |
| 282 | } |
| 283 | |
| 284 | func (l *limited) Close() error { |
| 285 | l.once.Do(func() { close(l.closed) }) |
| 286 | return l.Listener.Close() |
| 287 | } |
| 288 | |
| 289 | type limitedConn struct { |
| 290 | net.Conn |
| 291 | release func() |
| 292 | } |
| 293 | |
| 294 | func (c *limitedConn) Close() error { |
| 295 | err := c.Conn.Close() |
| 296 | c.release() |
| 297 | return err |
| 298 | } |
| 299 | |
| 300 | // byteSize is a size flag's value in bytes. It is set from a number, or a |
| 301 | // number with K, M, G or T for 1024 to the first to fourth power, as |
| 302 | // systemd reads a size and the publisher reads its own. |
| 303 | type byteSize int64 |
| 304 | |
| 305 | func (b *byteSize) Set(v string) error { |
| 306 | number, unit := v, int64(1) |
| 307 | if n := len(v); n > 1 { |
| 308 | if i := strings.IndexByte("KMGT", v[n-1]); i >= 0 { |
| 309 | number, unit = v[:n-1], 1<<(10*(i+1)) |
| 310 | } |
| 311 | } |
| 312 | x, err := strconv.ParseInt(number, 10, 64) |
| 313 | if err != nil || x <= 0 || x > math.MaxInt64/unit { |
| 314 | return fmt.Errorf("invalid size %q: must be a positive byte count, optionally suffixed with K, M, G, or T", v) |
| 315 | } |
| 316 | *b = byteSize(x * unit) |
| 317 | return nil |
| 318 | } |
| 319 | |
| 320 | func (b *byteSize) String() string { return strconv.FormatInt(int64(*b), 10) } |