// Package attach reaches a daemon on another host for as long as one view of // it is open: a local port forwarded over the host's ssh ControlMaster, and // that daemon's token read over the same master into memory. package attach import ( "bytes" "context" "encoding/json" "errors" "fmt" "net" "os" "os/exec" "path/filepath" "strconv" "strings" "time" "albedo/cli/internal/daemon" ) const ( // connectTimeout is how long ssh may take to reach the host. connectTimeout = 10 readTimeout = 20 * time.Second forwardTimeout = 10 * time.Second attachTimeout = 15 * time.Second cancelTimeout = 5 * time.Second ) // Runner runs ssh with args and returns its stdout, or an error carrying // what it said on stderr. type Runner func(ctx context.Context, args ...string) ([]byte, error) // Connector attaches to the daemon behind a forwarded port. type Connector func(ctx context.Context, snapshot daemon.ConnectionSnapshot) (*daemon.Connection, error) // Options replace how ssh runs and how the daemon is attached; the zero value // runs ssh from PATH and daemon.Attach. type Options struct { Run Runner Connect Connector // Config answers `ssh -G host`; nil runs it. Config Runner } // Attachment is a connection to a daemon on another host. Close ends the // forward; the token lives only in the connection. type Attachment struct { run Runner Conn *daemon.Connection Host string spec string base []string } // Open forwards a local port to the daemon on host and attaches to it. home // is that daemon's albedo home there, "" for ~/.albedo. func Open(ctx context.Context, host, home string, options Options) (*Attachment, error) { if options.Run == nil { options.Run = runSSH } if options.Config == nil { options.Config = runSSH } if options.Connect == nil { options.Connect = func(ctx context.Context, snapshot daemon.ConnectionSnapshot) (*daemon.Connection, error) { return daemon.Attach(ctx, snapshot, nil) } } base := baseArgs(ctx, host, options.Config) readCtx, cancel := context.WithTimeout(ctx, readTimeout) out, err := options.Run(readCtx, append(base, host, "cat "+daemonFile(home))...) cancel() if err != nil { return nil, fmt.Errorf("could not read the daemon address on %s: %w", host, err) } var endpoint struct { Token string `json:"token"` Port int `json:"port"` } if json.Unmarshal(out, &endpoint) != nil || endpoint.Port < 1 || endpoint.Port > 65535 || endpoint.Token == "" { return nil, fmt.Errorf("no albedo daemon is running on %s (%s has no port and token)", host, daemonFile(home)) } local, err := freePort() if err != nil { return nil, err } a := &Attachment{Host: host, run: options.Run, base: base, spec: fmt.Sprintf("127.0.0.1:%d:127.0.0.1:%d", local, endpoint.Port)} forwardCtx, cancel := context.WithTimeout(ctx, forwardTimeout) _, err = options.Run(forwardCtx, append(base, "-O", "forward", "-L", a.spec, host)...) cancel() if err != nil { return nil, fmt.Errorf("could not forward a port to %s: %w", host, err) } connectCtx, cancel := context.WithTimeout(ctx, attachTimeout) a.Conn, err = options.Connect(connectCtx, daemon.ConnectionSnapshot{Port: local, Token: endpoint.Token}) cancel() if err != nil { a.cancel() return nil, fmt.Errorf("the daemon on %s did not answer: %w", host, err) } return a, nil } // Close drops the connection and cancels the forward; the master stays for // whatever else rides it. func (a *Attachment) Close() { if a == nil { return } if a.Conn != nil { a.Conn.HTTPClient().CloseIdleConnections() a.Conn = nil } a.cancel() } func (a *Attachment) cancel() { if a.spec == "" { return } ctx, cancel := context.WithTimeout(context.Background(), cancelTimeout) defer cancel() _, _ = a.run(ctx, append(a.base, "-O", "cancel", "-L", a.spec, a.Host)...) a.spec = "" } // daemonFile is the remote shell's path to the daemon's address file. func daemonFile(home string) string { if home == "" { return "~/.albedo/daemon.json" } return "'" + strings.ReplaceAll(home, "'", `'\''`) + "/daemon.json'" } // baseArgs are the options that ride host's ControlMaster, by the rules the // daemon's own ssh layer (priv/python/albedo_ssh.py) follows, so both share // one master: the user's ControlPath when their config names one, else // albedo's under /tmp. func baseArgs(ctx context.Context, host string, config Runner) []string { control, persist := filepath.Join(controlDir(), "%C"), "600" configCtx, cancel := context.WithTimeout(ctx, 5*time.Second) out, err := config(configCtx, "-G", host) cancel() settings := map[string]string{} if err == nil { for line := range strings.SplitSeq(string(out), "\n") { key, value, _ := strings.Cut(strings.TrimSpace(line), " ") settings[key] = value } } if path := settings["controlpath"]; path != "" && path != "none" { // -G expanded the path's tokens; a % left in it is literal control = strings.ReplaceAll(path, "%", "%%") if p := settings["controlpersist"]; p != "" && p != "no" && p != "0" { persist = p } } else { _ = os.MkdirAll(controlDir(), 0o700) } return []string{ "-o", "BatchMode=yes", "-o", "ConnectTimeout=" + strconv.Itoa(connectTimeout), "-o", "StrictHostKeyChecking=accept-new", "-o", "ControlMaster=auto", "-o", "ControlPath=" + control, "-o", "ControlPersist=" + persist, } } // controlDir is under /tmp when the socket path fits (macOS caps unix socket // paths near 104 bytes and %C adds 40), else the temp dir. func controlDir() string { dir := "/tmp/albedo-ssh-cm" if len(dir)+42 > 104 { dir = filepath.Join(os.TempDir(), "albedo-ssh-cm") } return dir } func freePort() (int, error) { listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return 0, err } defer listener.Close() return listener.Addr().(*net.TCPAddr).Port, nil } func runSSH(ctx context.Context, args ...string) ([]byte, error) { cmd := exec.CommandContext(ctx, "ssh", args...) // a master ssh leaves running may hold its pipes open past its exit cmd.WaitDelay = time.Second var stderr bytes.Buffer cmd.Stderr = &stderr out, err := cmd.Output() if err != nil { if said := strings.TrimSpace(stderr.String()); said != "" { return out, errors.New(said) } if ctx.Err() != nil { return out, errors.New("ssh did not answer in time") } } return out, err }