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