package main import ( "context" "errors" "flag" "fmt" "log/slog" "net" "net/http" "os" "os/signal" "path/filepath" "syscall" "time" "git.stinnesbeck.com/nils/allmende/internal/api" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/inbox" "git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/message" "git.stinnesbeck.com/nils/allmende/internal/p2p" "git.stinnesbeck.com/nils/allmende/internal/store" ) const ( announceFirst = 10 * time.Second announceInterval = 30 * time.Minute certWarnBefore = 30 * 24 * time.Hour ) func cmdRun(args []string) error { fs := flag.NewFlagSet("run", flag.ExitOnError) data := dataFlag(fs) var regions, bootstrap, listen listFlag fs.Var(®ions, "region", "geohash region (3 characters, e.g. u1x) to replicate; repeatable") fs.Var(&bootstrap, "bootstrap", "multiaddr of a known peer (…/p2p/); repeatable") fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)") httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API") noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network") difficulty := fs.Int("difficulty", listing.DefaultDifficulty, "proof-of-work bits for listings; must match the rest of the network") msgDifficulty := fs.Int("message-difficulty", message.DefaultDifficulty, "proof-of-work bits for messages; must match the rest of the network") maxNewThreads := fs.Int("max-new-threads", inbox.DefaultMaxNewThreads, "how many new conversations each of your listings can start per day") fs.Parse(args) if len(regions) == 0 { return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)") } dev, err := identity.LoadDevice(*data) if err != nil { if errors.Is(err, os.ErrNotExist) { return fmt.Errorf("%s is not set up yet: run 'node init' first", *data) } return err } until := time.Until(time.Unix(dev.Cert.ExpiresAt, 0)) if until <= 0 { return errors.New("this device's certificate has expired; run 'node recover' to renew it") } log := slog.New(slog.NewTextHandler(os.Stderr, nil)) if until < certWarnBefore { log.Warn("device certificate expires soon; run 'node recover' to renew it", "expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02")) } st, err := store.Open(filepath.Join(*data, dbFile), store.Options{ Difficulty: *difficulty, MessageDifficulty: *msgDifficulty, }) if err != nil { return err } defer st.Close() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() node, err := p2p.New(ctx, p2p.Config{ Device: dev, Store: st, ListenAddrs: listen, Bootstrap: bootstrap, Regions: regions, MDNS: !*noMDNS, Difficulty: *difficulty, Logger: log, MessageDifficulty: *msgDifficulty, }) if err != nil { return err } defer node.Close() token := readToken(*data) if token == "" { log.Warn("no admin token found; publishing through the API is disabled") } handler := api.New(api.Config{ Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty, MessageDifficulty: *msgDifficulty, Inbox: &inbox.Inbox{ Store: st, Device: dev, Publisher: node, Difficulty: *msgDifficulty, MaxNewThreads: *maxNewThreads, }, }) ln, err := net.Listen("tcp", *httpAddr) if err != nil { return err } srv := &http.Server{ Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 60 * time.Second, // publishing mines proof-of-work IdleTimeout: 2 * time.Minute, } go func() { if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Error("http server", "err", err) stop() } }() log.Info("node running", "peer_id", node.ID().String(), "identity", dev.Cert.Author[:12]+"…", "regions", []string(regions), "http", ln.Addr().String()) for _, a := range node.Addrs() { log.Info("listening", "addr", a) } if host, _, _ := net.SplitHostPort(ln.Addr().String()); host != "127.0.0.1" && host != "::1" { log.Warn("the HTTP API is reachable from other machines; put it behind TLS if it is public") } if token != "" { // Printed to the terminal, not logged: the token must not end up in a // log file. It sits in the URL fragment, which a browser never sends to // a server; the page moves it into sessionStorage and removes it. fmt.Fprintf(os.Stderr, "\nOwner login (answer your inbox in the browser):\n %s\n\n", loginURL(ln.Addr().String(), token)) } go announce(ctx, log, node, st, dev.Cert.Author) <-ctx.Done() log.Info("shutting down") shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() return srv.Shutdown(shutdown) } // announce periodically re-gossips this identity's revocations and live // listings. Gossip only reaches peers connected at that moment; this makes // sure newcomers hear about them without waiting for a sync. func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.Store, author string) { timer := time.NewTimer(announceFirst) defer timer.Stop() for { select { case <-ctx.Done(): return case <-timer.C: } if revs, err := st.Revocations(ctx); err == nil { for _, r := range revs { if r.Author == author { if err := node.PublishRevocation(ctx, r); err != nil { log.Debug("announce revocation", "err", err) } } } } if own, err := st.ByAuthor(ctx, author); err == nil { for _, l := range own { if err := node.Publish(ctx, l); err != nil { log.Debug("announce listing", "id", l.ID, "err", err) } } } timer.Reset(announceInterval) } } // loginURL is the link that signs the owner in to the web UI. func loginURL(listenAddr, token string) string { host, port, err := net.SplitHostPort(listenAddr) if err != nil { return "http://" + listenAddr + "/#/login/" + token } // A wildcard address (0.0.0.0, ::) is not something a browser can open. if ip := net.ParseIP(host); ip == nil || ip.IsUnspecified() { host = "127.0.0.1" } // JoinHostPort brackets IPv6 addresses. return "http://" + net.JoinHostPort(host, port) + "/#/login/" + token }