diff --git a/README.md b/README.md index 37175ca..5cd8b51 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,9 @@ sshTermy ist eine schlanke Terminal-Anwendung (TUI, eine einzige Datei, ~9 MB, k - **Verbindungs-Manager** mit verschlüsseltem Store (AES-256-GCM, Argon2id, unter Windows zusätzlich DPAPI) - **echtem SSH-Terminal** (xterm-256color, Truecolor, vim/htop/tmux, Scrollback, Tabs, Jump-Host) +- **Auto-Reconnect**: reißt die Leitung ab (WLAN, VPN, Standby), verbindet sshTermy die Sitzung von selbst neu, startet laufende Tunnel wieder und hängt tmux/screen wieder an (abschaltbar über die Palette) +- **Schnellverbinden**: `user@host:port` oder `ssh -p 2222 user@host` in die Palette tippen, ohne die Verbindung anzulegen (Agent/Standard-Keys, sonst Passwort) +- **Statuszeile pro Sitzung**: Verbindungsdauer, Latenz, Zeichensatz, Warnung bei root; Produktiv-Hosts (Gruppe/Tag „Produktion“, „prod“, „live“) bekommen eine rote Zeile - **Dateien (F5)**: SFTP über dieselbe Verbindung, links lokal, rechts Server, Dateien und Ordner hoch- und herunterladen - **Tunnel-Manager**: `-L`, `-R`, `-D` (SOCKS5) und One-Click-Web-Services mit lokaler URL - **KI-Copilot** für jeden OpenAI-kompatiblen Endpunkt (`/v1/chat/completions`: OpenAI, vLLM, SGLang, Ollama, LiteLLM, LocalAI) diff --git a/internal/domain/model.go b/internal/domain/model.go index 1084d87..d6cb77e 100644 --- a/internal/domain/model.go +++ b/internal/domain/model.go @@ -36,6 +36,9 @@ const ( AuthPassword AuthMethod = "password" // Passwort (verschlüsselt im Store) AuthKeyFile AuthMethod = "keyfile" // Private Key, als Pfad oder eingebettet (verschlüsselt) AuthAgent AuthMethod = "agent" // ssh-agent / Windows OpenSSH-Agent / Pageant-kompatibel + // AuthAuto: wie das ssh-Kommando: erst Agent und Standard-Keys + // (~/.ssh/id_*), dann Passwort-Abfrage. Für Schnellverbindungen. + AuthAuto AuthMethod = "auto" ) // DeviceKind: was am anderen Ende hängt. Netzwerkgeräte (Switches, Router, @@ -191,6 +194,8 @@ type Settings struct { LockAfterMin int `json:"lock_after_min"` // 0 = nie automatisch sperren Language string `json:"language"` // "de" | "en" NoMouse bool `json:"no_mouse,omitempty"` // Maus nicht einfangen (Terminalfenster markiert selbst) + // NoAutoReconnect: abgerissene Sitzungen nicht von selbst neu verbinden. + NoAutoReconnect bool `json:"no_auto_reconnect,omitempty"` } // SyncBackend: wohin die verschlüsselte Sync-Datei geschrieben wird. diff --git a/internal/sshx/auth.go b/internal/sshx/auth.go index ebaecf3..4f1c661 100644 --- a/internal/sshx/auth.go +++ b/internal/sshx/auth.go @@ -92,10 +92,65 @@ func authMethods(c domain.Connection, o Options) ([]ssh.AuthMethod, error) { } // Der Agent hält die Private Keys; sshtermy sieht sie nie. return []ssh.AuthMethod{ssh.PublicKeysCallback(agent.NewClient(conn).Signers)}, nil + + case domain.AuthAuto: + return autoMethods(c, o), nil } return nil, fmt.Errorf("unbekannte Auth-Methode %q", c.Auth) } +// autoMethods: Agent + unverschlüsselte Standard-Keys, danach Passwort und +// keyboard-interactive mit Rückfrage. Höchstens 5 Keys, sonst bricht OpenSSH +// mit "Too many authentication failures" ab, bevor das Passwort drankommt. +func autoMethods(c domain.Connection, o Options) []ssh.AuthMethod { + var m []ssh.AuthMethod + signers := func() ([]ssh.Signer, error) { + var out []ssh.Signer + if conn, err := dialAgent(); err == nil { + if ss, err := agent.NewClient(conn).Signers(); err == nil { + out = append(out, ss...) + } + } + home, _ := os.UserHomeDir() + for _, n := range []string{"id_ed25519", "id_ecdsa", "id_rsa"} { + b, err := os.ReadFile(filepath.Join(home, ".ssh", n)) + if err != nil { + continue + } + if s, err := ssh.ParsePrivateKey(b); err == nil { + out = append(out, s) + } + } + if len(out) > 5 { + out = out[:5] + } + return out, nil + } + m = append(m, ssh.PublicKeysCallback(signers)) + if o.AskSecret == nil { + return m + } + m = append(m, ssh.PasswordCallback(func() (string, error) { + return o.AskSecret("Passwort für " + c.Username + "@" + c.Host) + })) + m = append(m, ssh.KeyboardInteractive(func(_, _ string, qs []string, _ []bool) ([]string, error) { + ans := make([]string, len(qs)) + for i, q := range qs { + label := strings.TrimSpace(q) + if strings.Contains(strings.ToLower(q), "pass") { + label = "Passwort für " + c.Username + "@" + c.Host // gleiche Frage wie oben, nur einmal + } + a, err := o.AskSecret(label) + if err != nil { + return nil, err + } + ans[i] = a + } + return ans, nil + })) + return m +} + func loadSigner(c domain.Connection, o Options) (ssh.Signer, error) { var pem []byte if c.KeyPEM.IsSet() { diff --git a/internal/sshx/client.go b/internal/sshx/client.go index 521cc37..533a9e2 100644 --- a/internal/sshx/client.go +++ b/internal/sshx/client.go @@ -12,6 +12,7 @@ import ( "net" "strings" "sync" + "sync/atomic" "time" "golang.org/x/crypto/ssh" @@ -35,6 +36,12 @@ type Client struct { // starb nach der Systemabfrage). Die UI merkt sich das in der Verbindung. Learned bool cancel context.CancelFunc + + // Zustand der Leitung (Statuszeile, Auto-Reconnect) + latency atomic.Int64 // letzte Rundreise in ns, 0 = noch keine + answered atomic.Bool // Gegenstelle beantwortet Keepalives + byUs atomic.Bool // Close() aufgerufen + dead chan struct{} // geschlossen, sobald die Verbindung weg ist } // RemoteInfo: was wir über das Zielsystem wissen (Kontext fürs LLM). @@ -42,6 +49,32 @@ type RemoteInfo struct { OS string // z. B. "Ubuntu 24.04.1 LTS" Kernel string // uname -srm Shell string // $SHELL + Locale string // LC_ALL/LC_CTYPE/LANG, z. B. "de_DE.UTF-8" +} + +// Encoding: Zeichensatz aus der Locale ("UTF-8", "ISO-8859-1" …), leer wenn unbekannt. +func (r RemoteInfo) Encoding() string { + l := r.Locale + if l == "" { + return "" + } + if i := strings.IndexByte(l, '.'); i >= 0 { + l = l[i+1:] + if j := strings.IndexByte(l, '@'); j >= 0 { + l = l[:j] + } + } else if l == "C" || l == "POSIX" { + return "ASCII" + } + switch strings.ToLower(strings.ReplaceAll(l, "-", "")) { + case "utf8": + return "UTF-8" + case "iso88591": + return "ISO-8859-1" + case "iso885915": + return "ISO-8859-15" + } + return l } func (r RemoteInfo) String() string { @@ -211,7 +244,8 @@ func dial(ctx context.Context, c domain.Connection, o Options) (*Client, error) _ = raw.SetDeadline(time.Time{}) kctx, cancel := context.WithCancel(context.Background()) - cl := &Client{Client: ssh.NewClient(sc, chans, reqs), Conn: c, jump: jump, cancel: cancel} + cl := &Client{Client: ssh.NewClient(sc, chans, reqs), Conn: c, jump: jump, cancel: cancel, dead: make(chan struct{})} + go func() { _ = cl.Client.Wait(); close(cl.dead) }() banner := string(sc.ServerVersion()) switch { case o.forceNet || c.Device == domain.DeviceNetwork: @@ -294,6 +328,7 @@ func rememberSecrets(ask SecretPrompt) SecretPrompt { // Close schließt Ziel und Jump-Host. func (c *Client) Close() error { + c.byUs.Store(true) c.cancel() err := c.Client.Close() if c.jump != nil { @@ -302,18 +337,81 @@ func (c *Client) Close() error { return err } -func (c *Client) keepAlive(ctx context.Context, sec int) { - if sec <= 0 { - sec = 30 +// Latency: Dauer der letzten Keepalive-Rundreise (0 = noch nicht gemessen +// oder die Gegenstelle antwortet nicht auf Keepalives). +func (c *Client) Latency() time.Duration { return time.Duration(c.latency.Load()) } + +// Dropped: Die Verbindung ist weg, ohne dass sshTermy sie geschlossen hat +// (Netz weg, VPN getrennt, Server neu gestartet, Keepalive ohne Antwort). +func (c *Client) Dropped() bool { + select { + case <-c.dead: + return !c.byUs.Load() + default: + return false } - t := time.NewTicker(time.Duration(sec) * time.Second) +} + +// WaitDropped wartet höchstens d darauf, dass die Verbindung wegbricht. Die +// Shell meldet ihr Ende oft einen Moment bevor die Leitung als tot gilt. +func (c *Client) WaitDropped(d time.Duration) bool { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-c.dead: + case <-t.C: + } + return c.Dropped() +} + +// keepAlive hält die Verbindung offen, misst die Latenz und erkennt eine +// tote Leitung. Ohne Netz würde TCP sonst minutenlang still hängen. Als tot +// gilt die Verbindung nur, wenn die Gegenstelle schon einmal geantwortet hat +// (manche Switches beantworten Keepalives nie, die würden sonst getrennt). +func (c *Client) keepAlive(ctx context.Context, sec int) { + every := time.Duration(sec) * time.Second + if sec <= 0 { + every = 30 * time.Second + } + ping := min(every, 10*time.Second) // Latenz in der Statuszeile aktuell halten + deadAfter := max(every, 30*time.Second) // so lange ohne Antwort = Leitung tot + c.keepAliveLoop(ctx, ping, deadAfter) +} + +func (c *Client) keepAliveLoop(ctx context.Context, ping, deadAfter time.Duration) { + res := make(chan error, 1) + inflight := false + var sent time.Time + send := func() { + inflight, sent = true, time.Now() + go func() { + _, _, err := c.SendRequest("keepalive@openssh.com", true, nil) + res <- err + }() + } + send() + t := time.NewTicker(ping) defer t.Stop() for { select { case <-ctx.Done(): return + case <-c.dead: + return + case err := <-res: + inflight = false + if err != nil { + return // Leitung schon zu, Wait() meldet das + } + c.latency.Store(int64(time.Since(sent))) + c.answered.Store(true) case <-t.C: - if _, _, err := c.SendRequest("keepalive@openssh.com", true, nil); err != nil { + if !inflight { + send() + continue + } + if c.answered.Load() && time.Since(sent) >= deadAfter { + _ = c.Client.Close() // nicht byUs: zählt als Abbruch → Auto-Reconnect return } } @@ -328,7 +426,7 @@ func (c *Client) probe() RemoteInfo { return RemoteInfo{} } defer s.Close() - const cmd = `(. /etc/os-release 2>/dev/null && echo "$PRETTY_NAME") || sw_vers -productName 2>/dev/null || echo; uname -srm 2>/dev/null || echo; echo "$SHELL"` + const cmd = `(. /etc/os-release 2>/dev/null && echo "$PRETTY_NAME") || sw_vers -productName 2>/dev/null || echo; uname -srm 2>/dev/null || echo; echo "$SHELL"; echo "${LC_ALL:-${LC_CTYPE:-$LANG}}"` done := make(chan []byte, 1) go func() { out, _ := s.Output(cmd); done <- out }() select { @@ -340,7 +438,7 @@ func (c *Client) probe() RemoteInfo { } return "" } - ri := RemoteInfo{OS: get(0), Kernel: get(1), Shell: get(2)} + ri := RemoteInfo{OS: get(0), Kernel: get(1), Shell: get(2), Locale: get(3)} if ri.OS == "" && ri.Kernel == "" { ri.OS = "Windows (OpenSSH) oder unbekannt" } @@ -349,3 +447,28 @@ func (c *Client) probe() RemoteInfo { return RemoteInfo{} } } + +// Output führt einen Befehl in einer eigenen Exec-Sitzung aus (unsichtbar +// fürs Terminal). Nicht für Netzwerkgeräte: dort beendet Exec die Verbindung. +func (c *Client) Output(cmd string, d time.Duration) (string, error) { + if c.NetDevice { + return "", errors.New("keine Exec-Befehle auf Netzwerkgeräten") + } + s, err := c.NewSession() + if err != nil { + return "", err + } + defer s.Close() + type res struct { + out []byte + err error + } + done := make(chan res, 1) + go func() { out, err := s.Output(cmd); done <- res{out, err} }() + select { + case r := <-done: + return string(r.out), r.err + case <-time.After(d): + return "", errors.New("Zeitüberschreitung") + } +} diff --git a/internal/sshx/drop_test.go b/internal/sshx/drop_test.go new file mode 100644 index 0000000..ea5c785 --- /dev/null +++ b/internal/sshx/drop_test.go @@ -0,0 +1,146 @@ +package sshx + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "net" + "path/filepath" + "strconv" + "sync/atomic" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/db9979/sshtermy/internal/domain" +) + +// stallServer beantwortet die ersten answer Keepalives und dann keine mehr +// (wie eine Leitung, die mitten in der Sitzung stumm wird). +type stallServer struct { + addr string + answer int32 + seen atomic.Int32 + conns chan net.Conn + openTCP chan net.Conn +} + +func startStallServer(t *testing.T, answer int32) *stallServer { + t.Helper() + _, priv, _ := ed25519.GenerateKey(rand.Reader) + signer, _ := ssh.NewSignerFromKey(priv) + cfg := &ssh.ServerConfig{ + PasswordCallback: func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error) { return nil, nil }, + ServerVersion: "SSH-2.0-OpenSSH_9.6", + } + cfg.AddHostKey(signer) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + s := &stallServer{addr: ln.Addr().String(), answer: answer, openTCP: make(chan net.Conn, 4)} + go func() { + for { + nc, err := ln.Accept() + if err != nil { + return + } + s.openTCP <- nc + go func() { + sc, chans, reqs, err := ssh.NewServerConn(nc, cfg) + if err != nil { + return + } + defer sc.Close() + go func() { + for r := range reqs { + if s.seen.Add(1) <= s.answer && r.WantReply { + r.Reply(false, nil) + } + } + }() + for nch := range chans { + nch.Reject(ssh.Prohibited, "nein") + } + }() + } + }() + return s +} + +func dialStall(t *testing.T, s *stallServer) *Client { + t.Helper() + hs, _ := NewHostKeyStore(filepath.Join(t.TempDir(), "known_hosts")) + host, port, _ := net.SplitHostPort(s.addr) + p, _ := strconv.Atoi(port) + c := domain.Connection{Alias: "x", Host: host, Port: p, Username: "u", Auth: domain.AuthPassword, + Password: "x", Device: domain.DeviceServer} + cl, err := Dial(context.Background(), c, Options{HostKeys: hs, Prompt: func(string, string, string) bool { return true }, Timeout: 5 * time.Second}) + if err != nil { + t.Fatal(err) + } + return cl +} + +func TestDroppedWhenPeerGoesAway(t *testing.T) { + s := startStallServer(t, 100) + cl := dialStall(t, s) + defer cl.Close() + if cl.Dropped() { + t.Fatal("frische Verbindung gilt als abgebrochen") + } + (<-s.openTCP).Close() // Server/Netz weg + if !cl.WaitDropped(3 * time.Second) { + t.Fatal("Abbruch nicht erkannt") + } +} + +func TestCloseIsNotADrop(t *testing.T) { + s := startStallServer(t, 100) + cl := dialStall(t, s) + cl.Close() + if cl.WaitDropped(500 * time.Millisecond) { + t.Fatal("eigenes Close darf nicht als Abbruch zählen") + } +} + +func TestKeepAliveDetectsSilentLine(t *testing.T) { + s := startStallServer(t, 1) + cl := dialStall(t, s) + defer cl.Close() + cl.cancel() // Standard-Keepalive (10 s) stoppen, schnelle Variante testen + time.Sleep(50 * time.Millisecond) + s.seen.Store(0) + go cl.keepAliveLoop(context.Background(), 30*time.Millisecond, 300*time.Millisecond) + if !cl.WaitDropped(3 * time.Second) { + t.Fatal("stumme Leitung nicht erkannt") + } + if cl.Latency() <= 0 { + t.Fatal("Latenz der ersten Antwort fehlt") + } +} + +func TestKeepAliveKeepsNeverAnsweringDevice(t *testing.T) { + // Gegenstelle antwortet nie auf Keepalives (manche Switches): nicht trennen. + s := startStallServer(t, 0) + cl := dialStall(t, s) + defer cl.Close() + cl.cancel() + go cl.keepAliveLoop(context.Background(), 20*time.Millisecond, 100*time.Millisecond) + if cl.WaitDropped(600 * time.Millisecond) { + t.Fatal("Verbindung ohne Keepalive-Antworten wurde getrennt") + } +} + +func TestEncoding(t *testing.T) { + for in, want := range map[string]string{ + "de_DE.UTF-8": "UTF-8", "en_US.utf8": "UTF-8", "C": "ASCII", "": "", + "de_DE.ISO-8859-1": "ISO-8859-1", "de_DE.UTF-8@euro": "UTF-8", "C.UTF-8": "UTF-8", + } { + if got := (RemoteInfo{Locale: in}).Encoding(); got != want { + t.Errorf("%q: %q, want %q", in, got, want) + } + } +} diff --git a/internal/ui/app.go b/internal/ui/app.go index 7388998..de1ae61 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -168,6 +168,7 @@ func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case connectedMsg: if s := a.byID(m.sid); s != nil { s.client, s.shell, s.state = m.client, m.shell, stConnected + s.connectedAt = time.Now() s.tunnels = sshx.NewTunnelManager(m.client) a.st.Touch(s.conn.ID) if m.client.Learned { @@ -180,18 +181,29 @@ func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } } } + var cmd tea.Cmd + if s.rc.active { + cmd = a.onReconnected(s) + } a.resize(s) + return a, cmd } return a, nil + case muxProbeMsg: + a.onMuxProbe(m) + return a, nil case connectErrMsg: if s := a.byID(m.sid); s != nil { - s.state, s.err = stClosed, m.err.Error() + if s.rc.active { + a.onReconnectErr(s, m.err) + } else { + s.state, s.err = stClosed, m.err.Error() + } } return a, nil case shellClosedMsg: if s := a.byID(m.sid); s != nil { - s.close() - s.err = "Sitzung beendet" + a.onShellClosed(s, m) } return a, a.listen() @@ -305,6 +317,9 @@ func (a *App) onTick() tea.Cmd { if c := a.goalTick(s); c != nil { cmds = append(cmds, c) } + if c := a.reconnectTick(s); c != nil { + cmds = append(cmds, c) + } } return tea.Batch(cmds...) } diff --git a/internal/ui/help.go b/internal/ui/help.go index b547e67..90d5da3 100644 --- a/internal/ui/help.go +++ b/internal/ui/help.go @@ -68,6 +68,7 @@ var helpSections = []helpSection{ {"F5", "Dateien (SFTP)"}, {"F7 / F8", "Tab wechseln"}, {"F10", "zum Manager"}, + {"Abbruch", "verbindet neu (⏎ / Esc)"}, }}, {hcGoal, "◎", "Ziel-Modus", "F2", true, [][2]string{ {"⏎", "Ziel starten / ausführen"}, @@ -106,6 +107,7 @@ var helpSections = []helpSection{ }}, {hcPalette, "❯", "Befehlspalette", "Strg+Space", false, [][2]string{ {"tippen", "filtern / Ziel / Frage"}, + {"user@host", "schnell verbinden"}, {"⏎", "ausführen"}, {"Tab", "KI fragen"}, {"Esc", "schließen"}, diff --git a/internal/ui/palette.go b/internal/ui/palette.go index 1e79baa..7617d81 100644 --- a/internal/ui/palette.go +++ b/internal/ui/palette.go @@ -49,7 +49,7 @@ type palette struct { func isPaletteKey(k string) bool { return k == "ctrl+space" || k == "ctrl+@" } func (a *App) openPalette() tea.Cmd { - in := newAIInput("Ziel, Frage, Befehl, Tunnel oder Verbindung …") + in := newAIInput("Ziel, Frage, Befehl, Tunnel, Verbindung oder user@host:port …") in.MaxHeight = 4 a.pal = &palette{in: in, armed: -1} return a.pal.in.Focus() @@ -61,6 +61,10 @@ func (a *App) paletteItems() []palItem { s := a.current() inTerm := a.scr == scrTerminal && s != nil && s.state == stConnected var items []palItem + quick, quickFirst := a.quickItems(q) + if quickFirst { + items = append(items, quick...) // user@host:port: Verbinden ist gemeint + } if q != "" && inTerm { items = append(items, palItem{group: pgAI, icon: "◎", label: "Als Ziel starten: „" + trunc(oneLine(q), 50) + "“", hint: "⏎", @@ -122,21 +126,16 @@ func (a *App) paletteItems() []palItem { }}) } } + if !quickFirst { + items = append(items, quick...) + } for _, c := range a.st.Connections() { c := c if !match(c.Alias + " " + c.Host + " " + c.Group) { continue } items = append(items, palItem{group: pgConnect, icon: "▸", label: c.Alias, hint: c.Username + "@" + c.Host, - run: func() tea.Cmd { - for i, x := range a.sessions { - if x.conn.ID == c.ID && x.state != stClosed { - a.cur, a.scr = i, scrTerminal - return nil - } - } - return a.connect(c) - }}) + run: func() tea.Cmd { return a.openOrConnect(c) }}) } actions := []palItem{ {icon: "◎", label: "Ziel-Modus öffnen", hint: "F2", run: func() tea.Cmd { @@ -161,6 +160,7 @@ func (a *App) paletteItems() []palItem { {icon: "?", label: "Tastenkürzel", hint: "F1", run: func() tea.Cmd { a.modal = a.helpModal(); return nil }}, {icon: "i", label: "Über sshTermy / Update", hint: "F12", run: func() tea.Cmd { a.modal = a.aboutModal(); return nil }}, {icon: "↖", label: mouseLabel(a.mouseEnabled()), hint: "Maus", run: func() tea.Cmd { return a.toggleMouse() }}, + {icon: "⟳", label: reconnectLabel(a.autoReconnect()), hint: "Reconnect", run: func() tea.Cmd { return a.toggleAutoReconnect() }}, } if a.st.SyncConfig().Enabled() { actions = append(actions, palItem{icon: "⇅", label: "Jetzt synchronisieren", hint: "Sync", run: func() tea.Cmd { diff --git a/internal/ui/quickconnect.go b/internal/ui/quickconnect.go new file mode 100644 index 0000000..ef4b813 --- /dev/null +++ b/internal/ui/quickconnect.go @@ -0,0 +1,187 @@ +package ui + +import ( + "net" + "os" + "os/user" + "strconv" + "strings" + + tea "charm.land/bubbletea/v2" + + "github.com/db9979/sshtermy/internal/domain" +) + +// Schnellverbinden: In der Palette user@host:port (oder ein ganzes +// „ssh -p 2222 user@host“) tippen und sofort verbinden, ohne die Verbindung +// vorher anzulegen. Angemeldet wird wie beim ssh-Kommando: erst SSH-Agent und +// Standard-Keys, dann Passwort-Abfrage. Gespeichert wird nichts, außer man +// wählt „Als Verbindung speichern“. + +// parseQuick erkennt ein SSH-Ziel. strong: eindeutig gemeint (mit @, Port, +// „ssh“ davor oder IP-Adresse), dann steht der Eintrag in der Palette oben. +func parseQuick(q string) (c domain.Connection, strong, ok bool) { + f := strings.Fields(strings.TrimSpace(q)) + if len(f) == 0 { + return c, false, false + } + if f[0] == "ssh" { + strong = true + f = f[1:] + } + port, userName, target := 0, "", "" + for i := 0; i < len(f); i++ { + switch a := f[i]; { + case a == "-p" && i+1 < len(f): + p, err := strconv.Atoi(f[i+1]) + if err != nil { + return c, false, false + } + port, strong = p, true + i++ + case strings.HasPrefix(a, "-p") && len(a) > 2: + p, err := strconv.Atoi(a[2:]) + if err != nil { + return c, false, false + } + port, strong = p, true + case a == "-l" && i+1 < len(f): + userName = f[i+1] + i++ + case strings.HasPrefix(a, "-"): + return c, false, false // andere ssh-Schalter: lieber nicht raten + default: + if target != "" { + return c, false, false // mehrere Wörter: Ziel oder Frage, kein Host + } + target = a + } + } + if target == "" { + return c, false, false + } + target = strings.TrimPrefix(target, "ssh://") + if at := strings.LastIndex(target, "@"); at >= 0 { + userName, target = target[:at], target[at+1:] + strong = true + if userName == "" { + return c, false, false + } + } + host := target + switch { + case strings.HasPrefix(target, "["): // [IPv6]:port + end := strings.Index(target, "]") + if end < 0 { + return c, false, false + } + host = target[1:end] + if rest := target[end+1:]; rest != "" { + if !strings.HasPrefix(rest, ":") { + return c, false, false + } + p, err := strconv.Atoi(rest[1:]) + if err != nil { + return c, false, false + } + port = p + } + strong = true + case strings.Count(target, ":") == 1: + h, ps, _ := strings.Cut(target, ":") + p, err := strconv.Atoi(ps) + if err != nil { + return c, false, false + } + host, port, strong = h, p, true + case strings.Count(target, ":") > 1: // nacktes IPv6 + if net.ParseIP(target) == nil { + return c, false, false + } + } + if host == "" || !validHost(host) || port < 0 || port > 65535 { + return c, false, false + } + if net.ParseIP(host) != nil { + strong = true + } else if !strong && !strings.Contains(host, ".") { + return c, false, false // einzelnes Wort: eher Suche nach Alias + } + if port == 0 { + port = 22 + } + if userName == "" { + userName = localUser() + } + alias := userName + "@" + host + if port != 22 { + alias += ":" + strconv.Itoa(port) + } + c = domain.Connection{ + ID: "quick:" + alias, Alias: alias, Host: host, Port: port, Username: userName, + Auth: domain.AuthAuto, + } + return c, strong, true +} + +func validHost(h string) bool { + for _, r := range h { + ok := r == '.' || r == '-' || r == '_' || r == ':' || r == '%' || + (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') + if !ok { + return false + } + } + return !strings.HasPrefix(h, "-") && !strings.HasPrefix(h, ".") && !strings.HasSuffix(h, ".") +} + +// localUser: Anmeldename wie beim ssh-Kommando (ohne Windows-Domäne). +func localUser() string { + name := "" + if u, err := user.Current(); err == nil { + name = u.Username + } + if name == "" { + name = os.Getenv("USER") + } + if name == "" { + name = os.Getenv("USERNAME") + } + if i := strings.LastIndex(name, `\`); i >= 0 { + name = name[i+1:] + } + if name == "" { + name = "root" + } + return strings.ToLower(name) +} + +// quickItems: Palette-Einträge für ein getipptes SSH-Ziel. +func (a *App) quickItems(q string) (items []palItem, strong bool) { + c, strong, ok := parseQuick(q) + if !ok { + return nil, false + } + hint := "Key/Passwort" + items = append(items, + palItem{group: pgConnect, icon: "⚡", label: "Schnell verbinden: " + c.Alias, hint: hint, + run: func() tea.Cmd { return a.openOrConnect(c) }}, + palItem{group: pgConnect, icon: "+", label: "Als Verbindung speichern: " + c.Alias, hint: "anlegen", + run: func() tea.Cmd { + n := newConnDefaults() + n.Host, n.Port, n.Username, n.Alias = c.Host, c.Port, c.Username, c.Host + return a.openConnForm(n) + }}) + return items, strong +} + +// openOrConnect: zu einem offenen Tab derselben Verbindung wechseln, sonst verbinden. +func (a *App) openOrConnect(c domain.Connection) tea.Cmd { + for i, x := range a.sessions { + if x.conn.ID == c.ID && x.state != stClosed { + a.cur, a.scr = i, scrTerminal + return nil + } + } + return a.connect(c) +} diff --git a/internal/ui/reconnect.go b/internal/ui/reconnect.go new file mode 100644 index 0000000..c336aff --- /dev/null +++ b/internal/ui/reconnect.go @@ -0,0 +1,514 @@ +package ui + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/sshx" +) + +// Auto-Reconnect: Reißt die Leitung ab (WLAN, VPN, Standby, Server-Neustart), +// verbindet sshTermy die Sitzung von selbst neu, mit wachsenden Pausen. Der +// Verlauf im Terminal bleibt stehen, laufende Tunnel starten wieder, und +// war tmux oder screen offen, wird die Sitzung wieder angehängt. +// +// Kein Neuverbinden, wenn die Sitzung gewollt endet: exit/logout/Strg+D, +// Exit-Status vom Server, oder Esc während des Wartens. +// +// Netzwerkgeräte (Aruba & Co.): keine Systemabfrage und kein tmux; der +// Switch braucht nach einem Abbruch ein paar Sekunden, bis er wieder +// annimmt, deshalb startet der erste Versuch dort später. + +// reconnectWaits: Pause vor Versuch 1, 2, … (insgesamt gut drei Minuten). +var reconnectWaits = []time.Duration{ + 1 * time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 15 * time.Second, + 30 * time.Second, 30 * time.Second, 30 * time.Second, 30 * time.Second, 30 * time.Second, +} + +const netDeviceFirstWait = 4 * time.Second // Switch gibt die alte Sitzung erst frei + +type reconnState struct { + active bool + dialing bool + attempts int // gestartete Versuche seit dem Abbruch + due time.Time // nächster Versuch + since time.Time // Abbruch + cause string // warum die Leitung weg ist + lastErr string // Fehler des letzten Versuchs + tunnels []string // Tunnel, die vor dem Abbruch liefen + netDev bool + alt bool // Alt-Screen war an (tmux/screen/vim) +} + +// muxState: tmux oder screen, in dem der Nutzer zuletzt war. +type muxState struct { + kind string // "tmux" | "screen" | "" + name string // Sitzungsname, leer = zuletzt benutzte +} + +func (m muxState) attachCmd() string { + switch m.kind { + case "tmux": + if m.name != "" { + return "tmux attach -d -t " + shellQuote(m.name) + } + return "tmux attach -d" + case "screen": + if m.name != "" { + return "screen -d -r " + shellQuote(m.name) + } + return "screen -d -r" + } + return "" +} + +func (m muxState) label() string { + if m.name != "" { + return m.kind + "-Sitzung „" + m.name + "“" + } + return m.kind + "-Sitzung" +} + +func shellQuote(s string) string { + if s != "" && strings.Trim(s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-:") == "" { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + +// parseMux erkennt tmux-/screen-Aufrufe in einem getippten Befehl. ok=false: +// kein Start/Anhängen (z. B. "tmux ls", "screen -ls"). +func parseMux(cmd string) (m muxState, ok bool) { + f := strings.Fields(cmd) + if len(f) == 0 { + return m, false + } + switch f[0] { + case "tmux": + m.kind = "tmux" + args := f[1:] + // globale Schalter vor dem Unterbefehl überspringen (-2, -u, -L x, -S x, -f x) + for len(args) > 0 && strings.HasPrefix(args[0], "-") { + if (args[0] == "-L" || args[0] == "-S" || args[0] == "-f") && len(args) > 1 { + args = args[1:] + } + args = args[1:] + } + if len(args) == 0 { + return m, true // "tmux" = neue Sitzung + } + var flag string + switch args[0] { + case "new", "new-session", "new-s": + flag = "-s" + case "a", "at", "att", "attach", "attach-session": + flag = "-t" + default: + return muxState{}, false + } + for i := 1; i < len(args); i++ { + if args[i] == flag && i+1 < len(args) { + m.name = args[i+1] + } else if strings.HasPrefix(args[i], flag) && len(args[i]) > 2 { + m.name = args[i][2:] + } + } + return m, true + case "screen": + m.kind = "screen" + args := f[1:] + for i := 0; i < len(args); i++ { + a := args[i] + switch { + case a == "-ls" || a == "-list" || a == "-wipe" || a == "-v" || a == "-h" || a == "--help": + return muxState{}, false + case a == "-S" && i+1 < len(args): + m.name = args[i+1] + i++ + case strings.HasPrefix(a, "-") && strings.ContainsAny(a[1:], "rRxD") && !strings.HasPrefix(a, "--"): + if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") { + m.name = args[i+1] + i++ + } + case !strings.HasPrefix(a, "-"): + return m, true // ab hier Befehl, der in screen läuft + } + } + return m, true + } + return m, false +} + +// isQuitCommand: Befehle, mit denen man eine Sitzung absichtlich verlässt. +func isQuitCommand(cmd string) bool { + f := strings.Fields(strings.ToLower(cmd)) + if len(f) == 0 { + return false + } + switch f[0] { + case "exit", "logout", "logoff", "quit", "bye", "disconnect", "lo", "q", "reboot", "shutdown", "poweroff", "halt": + return true + } + return false +} + +// noteCommand wertet einen abgeschickten Befehl aus: gewolltes Ende, +// tmux/screen gestartet oder verlassen. +func (s *session) noteCommand(cmd string) { + if isQuitCommand(cmd) { + s.quitAt = time.Now() + } + if s.term != nil { + scr := s.term.PlainLines(6) + if strings.Contains(scr, "[detached") || strings.Contains(scr, "[exited]") || strings.Contains(scr, "[screen is terminating]") { + s.mux = muxState{} + } + } + if m, ok := parseMux(cmd); ok { + s.mux = m + } +} + +// wantedEnd: hat der Nutzer die Sitzung eben selbst beendet? +func (s *session) wantedEnd() bool { return time.Since(s.quitAt) < 20*time.Second } + +func (a *App) autoReconnect() bool { return !a.st.Settings().NoAutoReconnect } + +func (a *App) toggleAutoReconnect() tea.Cmd { + on := !a.autoReconnect() + if err := a.st.UpdateSettings(func(s *domain.Settings) { s.NoAutoReconnect = !on }); err != nil { + a.flash("Einstellung nicht gespeichert: " + err.Error()) + return nil + } + if on { + a.flash("Auto-Reconnect an: abgerissene Sitzungen verbinden sich neu.") + } else { + a.flash("Auto-Reconnect aus: nach einem Abbruch ⏎ zum Neuverbinden.") + } + return nil +} + +func reconnectLabel(on bool) string { + if on { + return "Auto-Reconnect aus" + } + return "Auto-Reconnect an (Sitzung nach Abbruch neu verbinden)" +} + +// onShellClosed entscheidet: neu verbinden oder Sitzung beenden. +func (a *App) onShellClosed(s *session, m shellClosedMsg) { + if m.shell != nil && s.shell != m.shell { + return // alte Shell, Sitzung ist schon weiter + } + if m.dropped && a.autoReconnect() && !s.wantedEnd() { + cause := "Verbindung verloren" + if m.err != nil && !errors.Is(m.err, context.Canceled) { + if e := strings.TrimSpace(m.err.Error()); e != "" && !strings.Contains(e, "without exit status") { + cause += " (" + e + ")" + } + } + a.beginReconnect(s, cause) + return + } + s.close() + s.err = "Sitzung beendet" + if m.dropped { + s.err = "Verbindung verloren" + } +} + +func (a *App) beginReconnect(s *session, cause string) { + if !s.rc.active { + if time.Since(s.connectedAt) > time.Minute { + s.rc.attempts = 0 // lief eine Weile stabil: neue Runde + } + s.rc.since = time.Now() + } + if s.rc.attempts >= len(reconnectWaits) { + s.close() + s.err = cause + " · mehrmals hintereinander abgebrochen, ⏎ verbindet neu" + s.rc = reconnState{} + return + } + s.rc.active, s.rc.dialing, s.rc.cause, s.rc.lastErr = true, false, cause, "" + if s.client != nil { + s.rc.netDev = s.client.NetDevice + } + if s.tunnels != nil { + s.rc.tunnels = s.rc.tunnels[:0] + for _, t := range s.tunnels.List() { + s.rc.tunnels = append(s.rc.tunnels, t.Spec.ID) + } + } + if s.term != nil { + s.rc.alt = s.term.AltScreen() + } + s.suspend() + wait := reconnectWaits[s.rc.attempts] + if s.rc.netDev && s.rc.attempts == 0 { + wait = netDeviceFirstWait + } + s.rc.due = time.Now().Add(wait) + s.state = stReconnect + if s.term != nil { + // Programme der alten Sitzung (tmux, vim, htop) sind weg: Alt-Screen, + // Maus und Bracketed Paste zurücksetzen, dann eine Trennlinie. + _, _ = s.term.Write([]byte("\x1b[?1049l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?1l\x1b[?25h\x1b[0m" + + "\r\n\x1b[33m── " + cause + " · " + time.Now().Format("15:04:05") + " · sshTermy verbindet neu ──\x1b[0m\r\n")) + } +} + +// suspend schließt die tote Verbindung, behält aber Terminal und Verlauf. +func (s *session) suspend() { + if s.ghostCancel != nil { + s.ghostCancel() + } + s.ghost, s.chips = "", nil + s.goal.cancel() + s.ask.cancel() + if s.tunnels != nil { + s.tunnels.StopAll() + s.tunnels = nil + } + if s.files.xfer != nil { + s.files.xfer.cancel() + } + if s.files.remote != nil { + s.files.remote.Close() + s.files.remote = nil + } + s.files.open, s.panelFocus = false, false + if s.shell != nil { + s.shell.Close() + s.shell = nil + } + if s.client != nil { + s.client.Close() // Zeiger bleibt für Anzeige (Remote-Info) bis zur neuen Verbindung + } +} + +// reconnectTick startet fällige Versuche (aus onTick, einmal pro Sekunde). +func (a *App) reconnectTick(s *session) tea.Cmd { + if s.state == stConnected { + return a.resumeMux(s) + } + if s.state != stReconnect || s.rc.dialing || time.Now().Before(s.rc.due) { + return nil + } + s.rc.dialing = true + s.rc.attempts++ + return a.connectCmd(s) +} + +// reconnectNow: ⏎ im Wartebild. +func (a *App) reconnectNow(s *session) tea.Cmd { + if s.rc.dialing { + return nil + } + s.rc.due = time.Now() + return a.reconnectTick(s) +} + +// cancelReconnect: Esc im Wartebild. +func (a *App) cancelReconnect(s *session) { + s.rc = reconnState{} + s.close() + s.err = "Neuverbinden abgebrochen" +} + +// onReconnectErr: Versuch fehlgeschlagen → nächsten planen oder aufgeben. +func (a *App) onReconnectErr(s *session, err error) { + s.rc.dialing = false + s.rc.lastErr = err.Error() + if !retryable(err) || s.rc.attempts >= len(reconnectWaits) { + msg := s.rc.cause + " · Neuverbinden fehlgeschlagen: " + err.Error() + s.rc = reconnState{} + s.close() + s.err = msg + return + } + s.rc.due = time.Now().Add(reconnectWaits[s.rc.attempts]) +} + +// onReconnected: Tunnel wieder starten, tmux/screen anhängen. +func (a *App) onReconnected(s *session) tea.Cmd { + down := time.Since(s.rc.since).Round(time.Second) + for _, id := range s.rc.tunnels { + t, ok := a.tunnelByID(s.conn.ID, id) + if !ok || t.AutoStart || s.tunnels.Get(id) != nil { + continue // AutoStart-Tunnel startet connectedMsg schon + } + if _, err := s.tunnels.Start(t); err != nil { + a.flash("Tunnel " + t.Name + ": " + err.Error()) + } + } + msg := fmt.Sprintf("%s wieder verbunden (%s getrennt)", s.conn.Alias, down) + var probe tea.Cmd + if s.mux.kind == "" && s.rc.alt && !s.client.NetDevice { + // Vollbild lief, aber kein tmux-Aufruf gesehen (z. B. tmux startet aus + // .bashrc): fragen, ob genau eine tmux-Sitzung noch angehängt ist. + probe = probeMux(s.id, s.client) + } + if s.mux.kind != "" && !s.client.NetDevice { + s.rc.active, s.rc.dialing = false, false + s.rc.tunnels = nil + s.muxPending = true + msg += ", hänge " + s.mux.label() + " wieder an …" + } else { + s.rc = reconnState{attempts: s.rc.attempts} + } + if s.term != nil { + _, _ = s.term.Write([]byte("\x1b[32m── wieder verbunden · " + time.Now().Format("15:04:05") + " ──\x1b[0m\r\n")) + } + a.flash(msg) + return probe +} + +type muxProbeMsg struct { + sid int + m muxState +} + +func probeMux(sid int, c *sshx.Client) tea.Cmd { + return func() tea.Msg { + out, err := c.Output(`tmux list-sessions -F '#{session_attached} #{session_name}' 2>/dev/null`, 4*time.Second) + if err != nil && out == "" { + return muxProbeMsg{sid: sid} + } + return muxProbeMsg{sid, pickAttachedTmux(out)} + } +} + +// pickAttachedTmux: Nach einem Abbruch hält der Server die alte Verbindung +// oft noch für angehängt. Genau eine solche Sitzung = die des Nutzers. +func pickAttachedTmux(out string) muxState { + var found []string + for _, l := range strings.Split(strings.TrimSpace(out), "\n") { + n, name, ok := strings.Cut(strings.TrimSpace(l), " ") + if ok && n != "0" && name != "" { + found = append(found, name) + } + } + if len(found) != 1 { + return muxState{} + } + return muxState{kind: "tmux", name: found[0]} +} + +func (a *App) onMuxProbe(m muxProbeMsg) { + s := a.byID(m.sid) + if s == nil || m.m.kind == "" || s.state != stConnected || s.mux.kind != "" { + return + } + s.mux, s.muxPending = m.m, true + a.flash("Hänge " + m.m.label() + " wieder an …") +} + +// resumeMux schickt den Befehl zum Anhängen, sobald der Prompt steht. +func (a *App) resumeMux(s *session) tea.Cmd { + if !s.muxPending || s.term == nil || s.shell == nil { + return nil + } + ready := s.term.AtIdlePrompt() && time.Since(s.lastOutput) > 400*time.Millisecond + if !ready && time.Since(s.connectedAt) < 6*time.Second { + return nil + } + s.muxPending = false + s.term.SendText(s.mux.attachCmd() + "\r") + return nil +} + +func (a *App) tunnelByID(connID, id string) (domain.Tunnel, bool) { + for _, t := range a.st.Tunnels(connID) { + if t.ID == id { + return t, true + } + } + return domain.Tunnel{}, false +} + +// retryable: Lohnt ein weiterer Versuch? Falsches Passwort, abgelehnter oder +// geänderter Host-Key und abgebrochene Rückfragen nicht. +func retryable(err error) bool { + if errors.Is(err, context.Canceled) || errors.Is(err, sshx.ErrHostKeyChanged) || isAuthFailure(err) { + return false + } + m := err.Error() + return !strings.Contains(m, "Host-Key") && !strings.Contains(m, "Keyfile") && !strings.Contains(m, "passphrase") +} + +func isAuthFailure(err error) bool { + return err != nil && strings.Contains(err.Error(), "unable to authenticate") +} + +// secretCache merkt sich Antworten auf Rückfragen (Passwort, Passphrase) für +// die Lebensdauer der Sitzung, damit das Neuverbinden ohne Nachfrage klappt. +// Nur im Arbeitsspeicher, nie im Store. +type secretCache struct { + mu sync.Mutex + seen map[string]string +} + +func (c *secretCache) wrap(ask sshx.SecretPrompt) sshx.SecretPrompt { + return func(label string) (string, error) { + c.mu.Lock() + v, ok := c.seen[label] + c.mu.Unlock() + if ok { + return v, nil + } + v, err := ask(label) + if err == nil { + c.mu.Lock() + if c.seen == nil { + c.seen = map[string]string{} + } + c.seen[label] = v + c.mu.Unlock() + } + return v, err + } +} + +func (c *secretCache) forget() { + c.mu.Lock() + c.seen = nil + c.mu.Unlock() +} + +// reconnectView: Wartebild mit Countdown. +func (a *App) reconnectView(s *session) string { + st := a.s + r := s.rc + where := s.conn.Alias + if !strings.Contains(where, s.conn.Host) { + where += " (" + s.conn.Addr() + ")" + } + head := st.Warn.Render("⟳ " + r.cause + ": " + where) + var line string + if r.dialing { + line = st.AI.Render(fmt.Sprintf("Verbinde neu … (Versuch %d von %d)", r.attempts, len(reconnectWaits))) + } else { + left := max(0, int(time.Until(r.due).Round(time.Second)/time.Second)) + line = st.Text.Render(fmt.Sprintf("Neuer Versuch in %d s (Versuch %d von %d)", left, r.attempts+1, len(reconnectWaits))) + } + out := head + "\n\n" + line + if r.lastErr != "" { + out += "\n" + st.Muted.Render("Letzter Fehler: "+trunc(r.lastErr, 70)) + } + if s.mux.kind != "" && !r.netDev { + out += "\n" + st.OK.Render("Danach wird die "+s.mux.label()+" wieder angehängt.") + } + if n := len(r.tunnels); n > 0 { + out += "\n" + st.Muted.Render(plural(n, "Tunnel startet", "Tunnel starten")+" wieder.") + } + return out + "\n\n" + a.keyZone("⏎", st.Muted.Render("⏎ jetzt versuchen")) + st.Muted.Render(" · ") + + a.keyZone("Esc", st.Muted.Render("Esc abbrechen")) + st.Muted.Render(" · x Tab schließen · F10 Manager") +} diff --git a/internal/ui/reconnect_test.go b/internal/ui/reconnect_test.go new file mode 100644 index 0000000..2694f02 --- /dev/null +++ b/internal/ui/reconnect_test.go @@ -0,0 +1,128 @@ +package ui + +import ( + "testing" + "time" + + "github.com/db9979/sshtermy/internal/domain" +) + +func TestParseQuick(t *testing.T) { + cases := []struct { + in string + ok, strong bool + user, host string + port int + }{ + {"root@10.0.0.5", true, true, "root", "10.0.0.5", 22}, + {"admin@sw-core:2222", true, true, "admin", "sw-core", 2222}, + {"ssh -p 2200 dominik@spark.local", true, true, "dominik", "spark.local", 2200}, + {"ssh -l pi raspi", true, true, "pi", "raspi", 22}, + {"u@[fe80::1]:22", true, true, "u", "fe80::1", 22}, + {"u@fe80::1", true, true, "u", "fe80::1", 22}, + {"192.168.1.1", true, true, "", "192.168.1.1", 22}, + {"server.example.com", true, false, "", "server.example.com", 22}, + {"web", false, false, "", "", 0}, + {"installiere nginx auf web01", false, false, "", "", 0}, + {"u@host:abc", false, false, "", "", 0}, + {"ssh -i key u@h", false, false, "", "", 0}, + {"@host", false, false, "", "", 0}, + {"u@-oProxyCommand=x", false, false, "", "", 0}, + } + for _, c := range cases { + conn, strong, ok := parseQuick(c.in) + if ok != c.ok || (ok && strong != c.strong) { + t.Errorf("%q: ok=%v strong=%v, want %v %v", c.in, ok, strong, c.ok, c.strong) + continue + } + if !ok { + continue + } + if c.user != "" && conn.Username != c.user || conn.Host != c.host || conn.Port != c.port { + t.Errorf("%q: %s@%s:%d", c.in, conn.Username, conn.Host, conn.Port) + } + if conn.Auth != domain.AuthAuto || conn.ID == "" || conn.Username == "" { + t.Errorf("%q: unvollständig %+v", c.in, conn) + } + } +} + +func TestParseMux(t *testing.T) { + cases := map[string]muxState{ + "tmux": {kind: "tmux"}, + "tmux new -s work": {kind: "tmux", name: "work"}, + "tmux new-session -swork": {kind: "tmux", name: "work"}, + "tmux a -t 3": {kind: "tmux", name: "3"}, + "tmux -2 attach -t x": {kind: "tmux", name: "x"}, + "screen": {kind: "screen"}, + "screen -S build": {kind: "screen", name: "build"}, + "screen -dr build": {kind: "screen", name: "build"}, + "screen -r": {kind: "screen"}, + } + for in, want := range cases { + got, ok := parseMux(in) + if !ok || got != want { + t.Errorf("%q: %+v %v, want %+v", in, got, ok, want) + } + } + for _, in := range []string{"tmux ls", "tmux kill-server", "screen -ls", "ls", "vim tmux.conf"} { + if _, ok := parseMux(in); ok { + t.Errorf("%q darf kein Anhängen sein", in) + } + } + if c := (muxState{kind: "tmux", name: "a b"}).attachCmd(); c != "tmux attach -d -t 'a b'" { + t.Errorf("Quoting: %s", c) + } +} + +func TestPickAttachedTmux(t *testing.T) { + if m := pickAttachedTmux("0 alt\n1 work\n"); m.name != "work" { + t.Errorf("got %+v", m) + } + if m := pickAttachedTmux("1 a\n1 b\n"); m.kind != "" { + t.Errorf("zwei angehängte: nicht raten, got %+v", m) + } + if m := pickAttachedTmux(""); m.kind != "" { + t.Errorf("leer: %+v", m) + } +} + +func TestQuitIntent(t *testing.T) { + s := &session{} + s.noteCommand("ls -la") + if s.wantedEnd() { + t.Fatal("ls ist kein Abmelden") + } + s.noteCommand("logout") + if !s.wantedEnd() { + t.Fatal("logout nicht erkannt") + } + s.quitAt = time.Now().Add(-time.Minute) + if s.wantedEnd() { + t.Fatal("altes exit darf späteren Abbruch nicht blockieren") + } +} + +func TestIsProduction(t *testing.T) { + yes := []domain.Connection{{Group: "Produktion"}, {Tags: []string{"live"}}, {Alias: "db-prod-1"}, {Tags: []string{"PROD"}}} + no := []domain.Connection{{Group: "Homelab"}, {Alias: "olive"}, {Tags: []string{"test"}}} + for _, c := range yes { + if !isProduction(c) { + t.Errorf("%+v sollte produktiv sein", c) + } + } + for _, c := range no { + if isProduction(c) { + t.Errorf("%+v ist nicht produktiv", c) + } + } +} + +func TestFmtDuration(t *testing.T) { + if got := fmtDuration(83 * time.Second); got != "1:23" { + t.Error(got) + } + if got := fmtDuration(3723 * time.Second); got != "1:02:03" { + t.Error(got) + } +} diff --git a/internal/ui/session.go b/internal/ui/session.go index 8bfae74..d27eed5 100644 --- a/internal/ui/session.go +++ b/internal/ui/session.go @@ -19,6 +19,7 @@ const ( stConnecting sessState = iota stConnected stClosed + stReconnect // Verbindung abgerissen, sshTermy verbindet gleich neu ) type panelKind int @@ -42,6 +43,14 @@ type session struct { err string started time.Time + connectedAt time.Time // letzter erfolgreicher Aufbau (Statuszeile: Dauer) + quitAt time.Time // exit/logout getippt: Ende ist gewollt, kein Auto-Reconnect + rc reconnState // Auto-Reconnect + mux muxState // tmux/screen, das nach dem Neuverbinden wieder angehängt wird + secrets *secretCache // Antworten auf Passwort-Rückfragen, nur im Speicher + muxPending bool // tmux/screen nach dem Neuverbinden anhängen + rootPrompt bool // letzter Prompt endete auf „#“ + pending atomic.Bool // Ausgabe-Nachricht unterwegs (Koaleszieren) lastOutput time.Time @@ -104,8 +113,10 @@ type connectErrMsg struct { err error } type shellClosedMsg struct { - sid int - err error + sid int + shell *sshx.Shell + err error + dropped bool // Leitung weggebrochen (nicht exit/logout) } // hostKeyAskMsg / secretAskMsg: der Verbindungsaufbau wartet auf die Antwort. @@ -123,6 +134,11 @@ func (a *App) connectCmd(s *session) tea.Cmd { hk := a.hostKeys st := a.st cols, rows := a.termSize(s) + if s.secrets == nil { + s.secrets = &secretCache{} + } + sc := s.secrets + keepTerm := s.term != nil // Neuverbindung: Verlauf bleibt stehen return func() tea.Msg { opts := sshx.Options{ HostKeys: hk, @@ -132,7 +148,7 @@ func (a *App) connectCmd(s *session) tea.Cmd { ev <- hostKeyAskMsg{host, fp, typ, r} return <-r }, - AskSecret: func(label string) (string, error) { + AskSecret: sc.wrap(func(label string) (string, error) { r := make(chan string, 1) ev <- secretAskMsg{label, r} v := <-r @@ -140,21 +156,32 @@ func (a *App) connectCmd(s *session) tea.Cmd { return "", context.Canceled } return v, nil - }, + }), } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() c, err := sshx.Dial(ctx, s.conn, opts) if err != nil { + if isAuthFailure(err) { + sc.forget() // falsches Passwort nicht beim nächsten Versuch wiederholen + } return connectErrMsg{s.id, err} } - s.term = termemu.New(cols, rows, shellWriter{s}) + if !keepTerm { + s.term = termemu.New(cols, rows, shellWriter{s}) + } sh, err := c.OpenShell(cols, rows, outWriter{s, ev}) if err != nil { c.Close() return connectErrMsg{s.id, err} } - go func() { err := <-sh.Done; ev <- shellClosedMsg{s.id, err} }() + go func() { + err := <-sh.Done + // exit/logout endet mit Exit-Status; ohne Status (oder mit Fehler) + // prüfen, ob die ganze Leitung weg ist → Auto-Reconnect. + dropped := err != nil && c.WaitDropped(1500*time.Millisecond) + ev <- shellClosedMsg{s.id, sh, err, dropped} + }() return connectedMsg{s.id, c, sh} } } diff --git a/internal/ui/statusline.go b/internal/ui/statusline.go new file mode 100644 index 0000000..5ad4a00 --- /dev/null +++ b/internal/ui/statusline.go @@ -0,0 +1,140 @@ +package ui + +import ( + "fmt" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/db9979/sshtermy/internal/domain" +) + +// Statuszeile pro Sitzung (zweite Zeile im Terminal): wer@wo und System +// links, rechts Verbindungsdauer, Latenz, Zeichensatz, Ziel/Tunnel/KI. +// Auf Produktiv-Hosts (Gruppe, Tag oder Alias mit „prod“, Tag „live“) ist +// die Zeile rot, und als root gibt es immer eine deutliche Warnung. + +// isProduction: Verbindung gehört zu einem Produktivsystem. +func isProduction(c domain.Connection) bool { + has := func(s string) bool { + l := strings.ToLower(s) + return strings.Contains(l, "prod") || l == "live" + } + if has(c.Group) || strings.Contains(strings.ToLower(c.Alias), "prod") { + return true + } + for _, t := range c.Tags { + if has(t) { + return true + } + } + return false +} + +// rootNow: arbeitet der Nutzer gerade als root? Anmeldename root, oder der +// Prompt endet auf „#“ (sudo -i, su -). Bei Netzwerkgeräten heißt „#“ nur +// Konfigurationsmodus, dort zählt nur der Anmeldename. +func (s *session) rootNow() bool { + if s.conn.Username == "root" { + return true + } + if s.term == nil || (s.client != nil && s.client.NetDevice) { + return false + } + if s.term.AtIdlePrompt() { + s.rootPrompt = strings.HasSuffix(strings.TrimRight(s.term.CursorLine(), " "), "#") + } + return s.rootPrompt // in vim/htop den letzten Stand behalten +} + +func fmtDuration(d time.Duration) string { + d = d.Truncate(time.Second) + h, m, sec := int(d.Hours()), int(d.Minutes())%60, int(d.Seconds())%60 + if h > 0 { + return fmt.Sprintf("%d:%02d:%02d", h, m, sec) + } + return fmt.Sprintf("%d:%02d", m, sec) +} + +func (a *App) sessionBar(s *session) string { + st := a.s + prod := isProduction(s.conn) + bg := st.Header + if prod { + bg = lipgloss.NewStyle().Background(st.T.Danger).Foreground(st.T.Bg).Bold(true) + } + + // links: Warnungen + wer@wo + var left strings.Builder + if prod { + left.WriteString(lipgloss.NewStyle().Background(st.T.Bg).Foreground(st.T.Danger).Bold(true).Padding(0, 1).Render("PRODUKTIV")) + } + if s.state == stConnected && s.rootNow() { + left.WriteString(st.ChipDanger.Bold(true).Render("⚠ root")) + } + info := s.conn.Username + "@" + s.conn.Addr() + if s.client != nil { + info = s.conn.Username + "@" + s.conn.Host + " · " + s.client.Remote.String() + } + + // rechts: Leitung + var line []string + if s.state == stConnected && s.client != nil { + line = append(line, st.Badge.Foreground(st.T.Text).Render("⏱ "+fmtDuration(time.Since(s.connectedAt)))) + if l := s.client.Latency(); l > 0 { + c := st.T.OK + switch { + case l >= 250*time.Millisecond: + c = st.T.Danger + case l >= 80*time.Millisecond: + c = st.T.Warn + } + ms := l.Milliseconds() + txt := fmt.Sprintf("↯ %d ms", ms) + if ms == 0 { + txt = "↯ <1 ms" + } + line = append(line, st.Badge.Foreground(c).Render(txt)) + } + if enc := s.client.Remote.Encoding(); enc != "" { + c := st.T.Muted + if enc != "UTF-8" { + c = st.T.Warn // Umlaute können falsch ankommen + } + line = append(line, st.Badge.Foreground(c).Render(enc)) + } + } + + nT := 0 + if s.tunnels != nil { + nT = len(s.tunnels.List()) + } + cfg := a.st.LLM() + ai := st.BadgeAI.Render("✦ " + trunc(cfg.Model, 22)) + if !cfg.SuggestEnabled { + ai = st.Badge.Foreground(st.T.Muted).Render("✦ aus") + } + ai = a.z.click(ai, func(tea.Mouse, bool) tea.Cmd { a.returnToTerminal = true; return a.openSettings() }) + tun := a.keyZone("F4", st.Badge.Render("⇄ "+plural(nT, "Tunnel", "Tunnel"))) + goal := "" + if s.goal.active { + goal = a.keyZone("F2", st.Badge.Foreground(st.T.AI).Render("◎ Ziel aktiv")) + } + if s.scroll > 0 { + goal = a.z.click(st.Badge.Foreground(st.T.Warn).Render(fmt.Sprintf("⇡ Verlauf −%d · Esc", s.scroll)), + func(tea.Mouse, bool) tea.Cmd { s.scroll, s.sel = 0, nil; return nil }) + " " + goal + } + right := strings.Join(line, "") + " " + goal + " " + tun + " " + ai + if lw := lipgloss.Width(left.String()); a.w-lw-lipgloss.Width(right) < 24 && len(line) > 0 { + right = goal + " " + tun + " " + ai // schmales Fenster: Leitung weglassen + } + l := left.String() + room := a.w - lipgloss.Width(l) - lipgloss.Width(right) - 3 + text := " " + trunc(info, max(0, room)) + gap := max(1, a.w-lipgloss.Width(l)-lipgloss.Width(text)-lipgloss.Width(right)) + bar := l + bg.Render(text+strings.Repeat(" ", gap)) + right + return ansi.Truncate(bar, a.w, "") +} diff --git a/internal/ui/terminal.go b/internal/ui/terminal.go index 3266d49..9ac63a4 100644 --- a/internal/ui/terminal.go +++ b/internal/ui/terminal.go @@ -140,6 +140,17 @@ func (a *App) updateTerminal(msg tea.Msg) tea.Cmd { if s.panelFocus { return a.panelMsg(s, msg) } + if s.state == stReconnect { + switch key { + case "enter", "r": + return a.reconnectNow(s) + case "esc": + a.cancelReconnect(s) + case "x": + a.closeTab(s) + } + return nil + } if s.state != stConnected { switch key { case "enter", "r": @@ -207,6 +218,7 @@ func (a *App) terminalKey(s *session, k tea.KeyPressMsg) tea.Cmd { if key == "enter" { if typed, ok := s.term.TypedInput(); ok && strings.TrimSpace(typed) != "" { s.history = append(s.history, strings.TrimSpace(typed)) + s.noteCommand(strings.TrimSpace(typed)) if len(s.history) > 200 { s.history = s.history[len(s.history)-200:] } @@ -219,6 +231,9 @@ func (a *App) terminalKey(s *session, k tea.KeyPressMsg) tea.Cmd { s.goal.startWait() } } + if key == "ctrl+d" && s.term.AtIdlePrompt() { + s.quitAt = time.Now() // Strg+D am leeren Prompt = abmelden + } s.term.SendKey(uv.KeyPressEvent(k)) if key == "enter" || key == "ctrl+c" { return nil @@ -314,7 +329,7 @@ func (a *App) viewTerminal() (string, *tea.Cursor) { // Tabs rechts in der Kopfzeile var tabs strings.Builder for i, x := range a.sessions { - dot := map[sessState]string{stConnecting: st.Warn.Render("◌"), stConnected: st.OK.Render("●"), stClosed: st.Danger.Render("○")}[x.state] + dot := map[sessState]string{stConnecting: st.Warn.Render("◌"), stConnected: st.OK.Render("●"), stClosed: st.Danger.Render("○"), stReconnect: st.Warn.Render("⟳")}[x.state] label := " " + trunc(x.conn.Alias, 16) + " " tab := st.Tab.Render(dot + label) if i == a.cur { @@ -331,36 +346,8 @@ func (a *App) viewTerminal() (string, *tea.Cursor) { } top := a.header(tabs.String()) - // Sitzungszeile - info := "" - if s.client != nil { - info = s.conn.Username + "@" + s.conn.Host + " · " + s.client.Remote.String() - } else { - info = s.conn.Username + "@" + s.conn.Addr() - } - nT := 0 - if s.tunnels != nil { - nT = len(s.tunnels.List()) - } - cfg := a.st.LLM() - ai := st.BadgeAI.Render("✦ " + trunc(cfg.Model, 22)) - if !cfg.SuggestEnabled { - ai = st.Badge.Foreground(st.T.Muted).Render("✦ aus") - } - ai = a.z.click(ai, func(tea.Mouse, bool) tea.Cmd { a.returnToTerminal = true; return a.openSettings() }) - tun := a.keyZone("F4", st.Badge.Render("⇄ "+plural(nT, "Tunnel", "Tunnel"))) - goal := "" - if s.goal.active { - goal = a.keyZone("F2", st.Badge.Foreground(st.T.AI).Render("◎ Ziel aktiv")) - } - if s.scroll > 0 { - goal = a.z.click(st.Badge.Foreground(st.T.Warn).Render(fmt.Sprintf("⇡ Verlauf −%d · Esc", s.scroll)), - func(tea.Mouse, bool) tea.Cmd { s.scroll, s.sel = 0, nil; return nil }) + " " + goal - } - right := goal + " " + tun + " " + ai - gap := max(1, a.w-lipgloss.Width(info)-lipgloss.Width(right)-1) - bar := st.Header.Render(" "+trunc(info, a.w-lipgloss.Width(right)-3)+strings.Repeat(" ", gap)) + right - bar = ansi.Truncate(bar, a.w, "") + // Sitzungszeile (statusline.go) + bar := a.sessionBar(s) // Terminalfläche cols, rows := a.termSize(s) @@ -370,6 +357,8 @@ func (a *App) viewTerminal() (string, *tea.Cursor) { case s.state == stConnecting: body = lipgloss.Place(cols, rows, lipgloss.Center, lipgloss.Center, st.AI.Render("⠿ Verbinde mit "+s.conn.Alias+" ("+s.conn.Addr()+") …")) + case s.state == stReconnect: + body = lipgloss.Place(cols, rows, lipgloss.Center, lipgloss.Center, a.reconnectView(s)) case s.state == stClosed: msg := st.Danger.Render("✗ " + orDefault(s.err, "getrennt")) body = lipgloss.Place(cols, rows, lipgloss.Center, lipgloss.Center,