devbox/cmd/devbox-hub/tailscale.go

110 lines
3 KiB
Go

package main
import (
"context"
"fmt"
"log"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"tailscale.com/ipn/ipnstate"
"tailscale.com/tsnet"
)
type tailnetOptions struct {
Enabled bool
Hostname string
StateDir string
StartupTimeout time.Duration
}
type tailnetServer interface {
Up(context.Context) (*ipnstate.Status, error)
Listen(string, string) (net.Listener, error)
Close() error
}
// tailnetPort restricts embedded listeners to this node's own tailnet addresses.
func tailnetPort(address string) (string, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return "", fmt.Errorf("Tailscale listen address: %w", err)
}
if host != "" && host != "0.0.0.0" && host != "::" {
return "", fmt.Errorf("--tailscale requires --listen :PORT, not an explicit host")
}
n, err := strconv.Atoi(port)
if err != nil || n < 1 || n > 65535 {
return "", fmt.Errorf("invalid Tailscale listen port %q", port)
}
return port, nil
}
// listenHub opens either an ordinary TCP listener or a userspace Tailscale
// listener. Embedded mode never opens an API listener on the host network.
func listenHub(ctx context.Context, address, data string, opts tailnetOptions) (net.Listener, func(), string, error) {
return listenHubWithNode(ctx, address, data, opts, func(s *tsnet.Server) tailnetServer { return s })
}
func listenHubWithNode(ctx context.Context, address, data string, opts tailnetOptions, newNode func(*tsnet.Server) tailnetServer) (net.Listener, func(), string, error) {
if !opts.Enabled {
ln, err := net.Listen("tcp", address)
return ln, func() {}, address, err
}
port, err := tailnetPort(address)
if err != nil {
return nil, nil, "", err
}
if opts.StartupTimeout <= 0 {
return nil, nil, "", fmt.Errorf("--tailscale-start-timeout must be positive")
}
stateDir := opts.StateDir
if stateDir == "" {
stateDir = filepath.Join(data, "tailscale")
}
stateDir, err = filepath.Abs(stateDir)
if err != nil {
return nil, nil, "", err
}
if err := os.MkdirAll(stateDir, 0o700); err != nil {
return nil, nil, "", err
}
if err := os.Chmod(stateDir, 0o700); err != nil {
return nil, nil, "", err
}
node := newNode(&tsnet.Server{
Dir: stateDir, Hostname: opts.Hostname,
UserLogf: log.Printf,
Logf: func(string, ...any) {},
})
cleanup := func() { _ = node.Close() }
upCtx, cancel := context.WithTimeout(ctx, opts.StartupTimeout)
defer cancel()
status, err := node.Up(upCtx)
if err != nil {
cleanup()
return nil, nil, "", fmt.Errorf("start embedded Tailscale: %w (authenticate using the logged URL or TS_AUTHKEY)", err)
}
ln, err := node.Listen("tcp", ":"+port)
if err != nil {
cleanup()
return nil, nil, "", err
}
host := ""
if status.Self != nil {
host = strings.TrimSuffix(status.Self.DNSName, ".")
}
if host == "" && len(status.TailscaleIPs) > 0 {
host = status.TailscaleIPs[0].String()
}
if host == "" {
ln.Close()
cleanup()
return nil, nil, "", fmt.Errorf("embedded Tailscale has no node address")
}
return ln, cleanup, "http://" + net.JoinHostPort(host, port), nil
}