gunk-dev/the-valley

main.go

sourcecc72d5a3fbc9main's published tip history
6.3 KiB
1// Command valley-web serves a receiver's store to its readers, as the
2// store's authorization allows: the active export's plan, its knots, and a
3// source browser over the main of each project the reader may read.
4//
5// valley-web --state FILE --listen ADDR [--origin URL]
6//
7// It opens the store with export.OpenReadOnly, which writes nothing to
8// it, so it may run as a user that can only read the receiver's store. It
9// serves it with package server until it is sent SIGINT or SIGTERM. It
10// logs to standard error, and prints the address it listens on once it
11// does.
12//
13// With --origin, valley-web also signs readers in with the read links the
14// host issues. It keeps the links redeemed and their sessions in browser/
15// beside the store's descriptor, which the deployment makes for its user
16// alone (package readerstate). That directory is the one place it writes.
17// It first makes its process non-dumpable (package nodump), so no link a
18// reader posts and no session token reaches a core dump or another
19// process of its user. Without --origin, it reads every request as anyone.
20package main
21
22import (
23 "context"
24 "errors"
25 "flag"
26 "fmt"
27 "io"
28 "log"
29 "net"
30 "net/http"
31 "net/url"
32 "os"
33 "os/signal"
34 "path/filepath"
35 "strings"
36 "syscall"
37 "time"
38
39 "the-valley/web/export"
40 "the-valley/web/nodump"
41 "the-valley/web/readerstate"
42 "the-valley/web/server"
43)
44
45const usage = `usage: valley-web --state FILE --listen ADDR [--origin URL]
46
47Serve the active export of a web export receiver's store to its readers,
48as the store's authorization allows: the plan page, each knot, and a
49source browser over main for each project the reader may read.
50
51 --state FILE the receiver's existing store descriptor, such as
52 /var/lib/valley-web/store; valley-web opens the store
53 read-only and writes nothing there
54 --listen ADDR the TCP address to listen on, such as 127.0.0.1:8080;
55 port 0 picks a free port
56 --origin URL the public HTTPS origin readers reach, such as
57 https://example.org: a scheme and a host, with a port
58 only when it is not 443. With it, readers sign in with
59 the host's read links, and valley-web keeps their
60 sessions in browser/ beside the store's descriptor,
61 which must exist, owned by valley-web's user, mode 0700,
62 and the process makes itself non-dumpable, which needs
63 Linux. Without it, every request is read as anyone.
64
65valley-web prints "valley-web: listening on ADDR" once it listens, and
66stops on SIGINT or SIGTERM.
67`
68
69// readerOptions are the options the browser state is opened with. Tests
70// set its fault hook.
71var readerOptions readerstate.Options
72
73func main() {
74 ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
75 defer stop()
76 err := run(ctx, os.Args[1:], os.Stderr)
77 var bad usageError
78 switch {
79 case errors.As(err, &bad):
80 fmt.Fprintf(os.Stderr, "valley-web: %v\n\n%s", err, usage)
81 os.Exit(2)
82 case err != nil:
83 fmt.Fprintf(os.Stderr, "valley-web: %v\n", err)
84 os.Exit(1)
85 }
86}
87
88// usageError is a command line valley-web cannot run with.
89type usageError struct{ error }
90
91// run serves until ctx is done, then shuts the server down, letting
92// requests in flight finish for a few seconds.
93func run(ctx context.Context, args []string, stderr io.Writer) error {
94 flags := flag.NewFlagSet("valley-web", flag.ContinueOnError)
95 flags.SetOutput(io.Discard)
96 state := flags.String("state", "", "")
97 listen := flags.String("listen", "", "")
98 origin := flags.String("origin", "", "")
99 if err := flags.Parse(args); errors.Is(err, flag.ErrHelp) {
100 fmt.Fprint(stderr, usage)
101 return nil
102 } else if err != nil {
103 return usageError{err}
104 }
105 switch {
106 case flags.NArg() > 0:
107 return usageError{fmt.Errorf("unexpected argument %q", flags.Arg(0))}
108 case *state == "":
109 return usageError{errors.New("--state is required")}
110 case *listen == "":
111 return usageError{errors.New("--listen is required")}
112 case *origin != "" && !validOrigin(*origin):
113 return usageError{fmt.Errorf("--origin %q is not an HTTPS origin: https:// and a lowercase host, with a port only when it is not 443, and nothing after", *origin)}
114 }
115
116 logger := log.New(stderr, "valley-web: ", log.LstdFlags)
117 store, err := export.OpenReadOnly(*state)
118 if err != nil {
119 return err
120 }
121 c := server.Config{Store: store, Origin: *origin, Log: func(err error) { logger.Print(err) }}
122 if *origin != "" {
123 if err := nodump.Set(); err != nil {
124 return fmt.Errorf("could not keep readers' links and sessions out of a core dump: %w", err)
125 }
126 abs, err := filepath.Abs(*state)
127 if err != nil {
128 return err
129 }
130 if c.Readers, err = readerstate.Open(filepath.Join(filepath.Dir(abs), "browser"), readerOptions); err != nil {
131 return fmt.Errorf("opening the browser state: %w", err)
132 }
133 defer c.Readers.Close()
134 if err := c.Readers.Err(); err != nil {
135 logger.Printf("the browser state is unavailable until valley-web restarts, so no reader signs in and anyone is served: %v", err)
136 }
137 }
138 handler := server.New(c)
139 handler.Prepare(ctx)
140 ln, err := net.Listen("tcp", *listen)
141 if err != nil {
142 return err
143 }
144 srv := &http.Server{
145 Handler: handler,
146 ReadHeaderTimeout: 10 * time.Second,
147 ReadTimeout: 30 * time.Second,
148 WriteTimeout: 60 * time.Second,
149 IdleTimeout: 120 * time.Second,
150 MaxHeaderBytes: 64 << 10,
151 ErrorLog: logger,
152 }
153 fmt.Fprintf(stderr, "valley-web: listening on %s\n", ln.Addr())
154 served := make(chan error, 1)
155 go func() { served <- srv.Serve(ln) }()
156 select {
157 case err := <-served:
158 return err
159 case <-ctx.Done():
160 }
161 shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
162 defer cancel()
163 if err := srv.Shutdown(shutdown); err != nil {
164 return err
165 }
166 if err := <-served; !errors.Is(err, http.ErrServerClosed) {
167 return err
168 }
169 return nil
170}
171
172// validOrigin reports whether s is an HTTPS origin as a browser sends it
173// in an Origin header: https://, a lowercase host, a port only when it is
174// not 443, and no path, query or anything else.
175func validOrigin(s string) bool {
176 u, err := url.Parse(s)
177 return err == nil && u.Scheme == "https" && u.Opaque == "" && u.User == nil && u.Host != "" &&
178 u.Host == strings.ToLower(u.Host) && u.Port() != "443" && !strings.HasSuffix(u.Host, ":") &&
179 s == "https://"+u.Host
180}