Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
385 lines
15 KiB
Go
385 lines
15 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"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/places"
|
|
"git.stinnesbeck.com/nils/allmende/internal/store"
|
|
"git.stinnesbeck.com/nils/allmende/web"
|
|
)
|
|
|
|
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", "region to replicate: a 3-character geohash (u1x) or a place name (\"Bonn\", \"Köln\"); repeatable")
|
|
fs.Var(&bootstrap, "bootstrap", "extra bootstrap peer: …/p2p/<id> or /dnsaddr/<name>; repeatable")
|
|
noDefaultBootstrap := fs.Bool("no-default-bootstrap", false,
|
|
"do not use the built-in bootstrap name "+p2p.DefaultBootstrap)
|
|
logLevel := fs.String("log-level", "info",
|
|
"how much to log: debug (every listing that arrives and where from), info, warn or error")
|
|
noDHT := fs.Bool("no-dht", false, "do not look for peers through the DHT")
|
|
public := fs.Bool("public", false,
|
|
"this node is reachable from the internet: serve the DHT and relay for nodes behind a NAT (for bootstrap nodes)")
|
|
maxConns := fs.Int("max-conns", 0,
|
|
fmt.Sprintf("inbound connections to accept (0: %d for --public nodes, libp2p's default, which scales with memory, for others; -1: libp2p's default always)", p2p.DefaultPublicConns))
|
|
var announceAddrs listFlag
|
|
fs.Var(&announceAddrs, "announce",
|
|
"address others should dial, when this node sits behind a router or in a container, e.g. /dns4/node.example.org/tcp/4001; 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")
|
|
metricsAddr := fs.String("metrics", "",
|
|
"serve metrics for Prometheus on this address, e.g. 127.0.0.1:9090 (off by default; it shows the node's internals and has no login, so keep it off the public network)")
|
|
noLoginLink := fs.Bool("no-login-link", false,
|
|
"do not print the owner sign-in link (it holds the admin token); use where the terminal is a log, e.g. in a container")
|
|
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")
|
|
var trustReporters listFlag
|
|
fs.Var(&trustReporters, "trust-reporter",
|
|
"identity key (64 hex) of a node operator whose abuse reports count here; repeatable. Your own reports always hide a listing on your node")
|
|
hideAfter := fs.Int("hide-after", store.DefaultHideThreshold,
|
|
"how many trusted operators must report a listing as a scam before your node hides it (one report of illegal content is enough)")
|
|
maxPerAuthor := fs.Int("max-per-author", store.DefaultMaxPerAuthor,
|
|
"most unexpired listings this node keeps for one author; more are neither stored nor passed on (-1: no limit)")
|
|
maxConnsPerIP := fs.Int("max-conns-per-ip", p2p.DefaultConnsPerIP,
|
|
"inbound connections accepted from one public IP address (IPv6: one /64); local and private addresses are exempt (-1: no limit)")
|
|
requestsPerMinute := fs.Int("requests-per-minute", 0,
|
|
"API requests one client address may make per minute (0: 600; -1: no limit); the node's own machine is exempt")
|
|
var trustedProxies listFlag
|
|
fs.Var(&trustedProxies, "trusted-proxy",
|
|
"address or network (10.0.0.0/8) of a reverse proxy in front of the HTTP API, whose X-Forwarded-For names the real client; repeatable. Without one, every client behind a proxy shares one allowance")
|
|
fs.Parse(args)
|
|
proxies, err := api.ParseProxies(trustedProxies)
|
|
if err != nil {
|
|
return fmt.Errorf("--trusted-proxy: %w", err)
|
|
}
|
|
for _, k := range trustReporters {
|
|
if !validKey(k) {
|
|
return fmt.Errorf("--trust-reporter %q: want an identity key of 64 hex characters (the \"author\" in a node's /api/v1/status)", k)
|
|
}
|
|
}
|
|
if *hideAfter < 1 {
|
|
return errors.New("--hide-after must be at least 1")
|
|
}
|
|
|
|
// Place names become region codes; say what each one turned into.
|
|
codes, notes, err := resolveRegions(regions, func() ([]places.Place, error) { return places.Load(web.Files()) })
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, n := range notes {
|
|
fmt.Fprintln(os.Stderr, n)
|
|
}
|
|
regions = codes
|
|
|
|
// Regions the owner chose in the browser win over --region, which then only
|
|
// says where a node starts the first time.
|
|
saved, ok, err := loadRegions(*data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if ok {
|
|
if len(regions) > 0 && !slices.Equal(regions, saved) {
|
|
slog.Info("using the regions chosen in the browser, not --region; delete "+regionsFile+" to use --region again",
|
|
"regions", saved)
|
|
}
|
|
regions = saved
|
|
}
|
|
// Without a region the node only helps others connect, until the owner
|
|
// chooses one in the browser (see the sign-in hint printed below).
|
|
if !*noDefaultBootstrap {
|
|
bootstrap = append(bootstrap, p2p.DefaultBootstrap)
|
|
}
|
|
|
|
dev, err := identity.LoadDevice(*data)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return fmt.Errorf("%s is not set up yet: run 'allmende init' first", *data)
|
|
}
|
|
return err
|
|
}
|
|
until := time.Until(time.Unix(dev.Cert.ExpiresAt, 0))
|
|
// An expired certificate stops the node, so the browser is out of reach
|
|
// then and only 'recover' helps; before that the owner can renew in the browser.
|
|
renewExpired := "run 'allmende recover' to renew it"
|
|
renewSoon := "renew it in the browser (sign in, then \"Renew certificate\" on your listings page) or run 'allmende recover'"
|
|
if _, err := os.Stat(filepath.Join(*data, noRecoveryFile)); err == nil {
|
|
renewExpired = "this identity has no recovery phrase, so it cannot be renewed: start over with 'allmende init --no-phrase' on an empty data directory (a new identity, so update any DNS records that name this node)"
|
|
renewSoon = renewExpired
|
|
}
|
|
if until <= 0 {
|
|
return errors.New("this device's certificate has expired; " + renewExpired)
|
|
}
|
|
level, err := parseLogLevel(*logLevel)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level}))
|
|
if until < certWarnBefore {
|
|
log.Warn("device certificate expires soon; "+renewSoon,
|
|
"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, MaxPerAuthor: *maxPerAuthor,
|
|
Trust: store.Trust{Self: dev.Cert.Author, Reporters: trustReporters, Threshold: *hideAfter},
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer st.Close()
|
|
|
|
// SIGTERM is what Kubernetes and 'docker stop' send; SIGHUP arrives when the
|
|
// terminal is closed. All three shut the node down in an orderly way.
|
|
ctx, stop := signal.NotifyContext(context.Background(), shutdownSignals...)
|
|
defer stop()
|
|
|
|
node, err := p2p.New(ctx, p2p.Config{
|
|
Device: dev,
|
|
Store: st,
|
|
ListenAddrs: listen,
|
|
Bootstrap: bootstrap,
|
|
Regions: regions,
|
|
MDNS: !*noMDNS,
|
|
DHT: !*noDHT,
|
|
Public: *public,
|
|
MaxConns: *maxConns,
|
|
MaxConnsPerIP: *maxConnsPerIP,
|
|
Announce: announceAddrs,
|
|
PeerCache: filepath.Join(*data, peersFile),
|
|
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")
|
|
}
|
|
in := &inbox.Inbox{
|
|
Store: st, Device: dev, Publisher: node,
|
|
Difficulty: *msgDifficulty, MaxNewThreads: *maxNewThreads,
|
|
}
|
|
handler := api.New(api.Config{
|
|
Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty,
|
|
MessageDifficulty: *msgDifficulty,
|
|
RequestsPerMinute: *requestsPerMinute,
|
|
TrustedProxies: proxies,
|
|
Inbox: in,
|
|
RegionKeeper: ®ionKeeper{node: node, dir: *data},
|
|
CertKeeper: &certKeeper{dev: dev, dir: *data, store: st, node: node, difficulty: *difficulty, clock: time.Now},
|
|
})
|
|
|
|
ln, err := net.Listen("tcp", *httpAddr)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Set before anything can call Collect (the server and the watcher below).
|
|
in.OnArrivals = arrivalNotice(ctx, log, st, ln.Addr().String())
|
|
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()
|
|
}
|
|
}()
|
|
|
|
if *metricsAddr != "" {
|
|
mln, err := net.Listen("tcp", *metricsAddr)
|
|
if err != nil {
|
|
return fmt.Errorf("--metrics: %w", err)
|
|
}
|
|
msrv := &http.Server{
|
|
Handler: api.MetricsHandler(node, st, version, time.Now()),
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
WriteTimeout: 10 * time.Second,
|
|
}
|
|
go func() {
|
|
if err := msrv.Serve(mln); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Error("metrics server", "err", err)
|
|
}
|
|
}()
|
|
defer msrv.Close()
|
|
log.Info("metrics", "addr", mln.Addr().String())
|
|
if host, _, _ := net.SplitHostPort(mln.Addr().String()); host != "127.0.0.1" && host != "::1" {
|
|
log.Warn("the metrics are reachable from other machines and have no login; keep this port off the public network")
|
|
}
|
|
}
|
|
|
|
log.Info("node running", "version", version,
|
|
"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 *public {
|
|
name := strings.TrimPrefix(p2p.DefaultBootstrap, "/dnsaddr/")
|
|
if recs := bootstrapRecords(node.Addrs()); len(recs) > 0 {
|
|
fmt.Fprintf(os.Stderr, "\nBootstrap node. For fresh nodes to find it, publish these TXT records at _dnsaddr.%s:\n", name)
|
|
for _, r := range recs {
|
|
fmt.Fprintf(os.Stderr, " %s\n", r)
|
|
}
|
|
fmt.Fprintln(os.Stderr)
|
|
} else {
|
|
log.Warn(noPublicAddressWarning(len(announceAddrs) > 0),
|
|
"peer_id", node.ID().String(), "announce", []string(announceAddrs))
|
|
}
|
|
}
|
|
|
|
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.Fprint(os.Stderr, loginNotice(ln.Addr().String(), token, *noLoginLink, len(regions) == 0 && !*public, *data))
|
|
} else if len(regions) == 0 && !*public {
|
|
log.Warn("this node follows no region and has no admin token, so nobody can choose one: pass --region")
|
|
}
|
|
|
|
go announce(ctx, log, node, st, dev.Cert.Author)
|
|
go watchInbox(ctx, log, in)
|
|
go remindExpiring(ctx, log, st, dev.Cert.Author, ln.Addr().String())
|
|
|
|
<-ctx.Done()
|
|
log.Info("shutting down")
|
|
forceExitOnSecondSignal(log, shutdownDeadline, os.Exit)
|
|
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
return srv.Shutdown(shutdown)
|
|
}
|
|
|
|
// shutdownSignals end the node in an orderly way.
|
|
var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP}
|
|
|
|
// shutdownDeadline is how long an orderly shutdown may take. It stays below
|
|
// the 30 seconds Kubernetes waits by default before it kills the pod.
|
|
const shutdownDeadline = 20 * time.Second
|
|
|
|
// forceExitOnSecondSignal makes a stuck shutdown end anyway: on another signal
|
|
// (a second Ctrl+C) or when the deadline passes, the process exits with 1.
|
|
func forceExitOnSecondSignal(log *slog.Logger, deadline time.Duration, exit func(int)) {
|
|
sig := make(chan os.Signal, 1)
|
|
signal.Notify(sig, shutdownSignals...)
|
|
go func() {
|
|
defer signal.Stop(sig)
|
|
select {
|
|
case <-sig:
|
|
log.Warn("second signal: stopping now")
|
|
case <-time.After(deadline):
|
|
log.Warn("shutdown is taking too long: stopping now", "after", deadline)
|
|
}
|
|
exit(1)
|
|
}()
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|
|
|
|
// loginNotice is what the node prints about signing in. With hide set (for a
|
|
// node whose terminal is a log, e.g. in a container) the link is left out and
|
|
// the notice only says where the token is.
|
|
func loginNotice(listenAddr, token string, hide, noRegions bool, dataDir string) string {
|
|
if hide {
|
|
return fmt.Sprintf("\nOwner login link not shown (--no-login-link). The token is in %s\n\n",
|
|
filepath.Join(dataDir, tokenFile))
|
|
}
|
|
s := fmt.Sprintf("\nOwner login (answer your inbox in the browser):\n %s\n\n", loginURL(listenAddr, token))
|
|
if noRegions {
|
|
s += "This node follows no region yet. Open the link above and choose where you want\nlistings from (and to publish) under \"My listings\" > \"Regions\".\n\n"
|
|
}
|
|
return s
|
|
}
|
|
|
|
// loginURL is the link that signs the owner in to the web UI.
|
|
func loginURL(listenAddr, token string) string {
|
|
return uiURL(listenAddr, "/login/"+token)
|
|
}
|
|
|
|
// uiURL is the address of a page of the web UI (route is the part after "#")
|
|
// as a browser on this machine can open it.
|
|
func uiURL(listenAddr, route string) string {
|
|
host, port, err := net.SplitHostPort(listenAddr)
|
|
if err != nil {
|
|
return "http://" + listenAddr + "/#" + route
|
|
}
|
|
// 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) + "/#" + route
|
|
}
|