package main import ( "bufio" "context" "errors" "fmt" "io" "os" "sort" "strconv" "strings" "time" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh" ) // dnsSuggestion is a host that owns an address the queried name resolves to. type dnsSuggestion struct { target string // host selector, e.g. prod/web07 reason string // e.g. "203.0.113.5 on eth0 (NetBox)" } // dnsMatch is what a DNS lookup of an unknown name found. type dnsMatch struct { name string // the DNS name that resolved, e.g. mx123.webseite.de addresses []string // its addresses suggestions []dnsSuggestion } // offerLinkFunc is offerLink; link add replaces it to avoid a second question. // The first argument is dns.save_link. var offerLinkFunc = offerLink // promptInput is replaced in tests. var promptInput io.Reader = os.Stdin // promptReader buffers promptInput once, so that consecutive questions do // not lose answers that a previous reader had already buffered. var ( promptReader *bufio.Reader promptSource io.Reader ) func readAnswer() (string, error) { if promptReader == nil || promptSource != promptInput { promptReader, promptSource = bufio.NewReader(promptInput), promptInput } line, err := promptReader.ReadString('\n') if err != nil && err != io.EOF { return "", err } return strings.TrimSpace(line), nil } // dnsNames lists the DNS names to try for query, following dns.domains. func dnsNames(cfg *config.Config, query string) []string { if !plainName(query) { return nil } return cfg.DNS.Names(query) } // lookupDNS resolves the first of names that has addresses. func lookupDNS(ctx context.Context, names []string) (string, []string) { for _, name := range names { addresses, err := lookupHost(ctx, name) if err == nil && len(addresses) > 0 { return name, addresses } } return "", nil } // findDNSMatch resolves query through DNS and finds the hosts in NetBox and // the cache that own the addresses. It returns nil when DNS knows no address. func findDNSMatch(ctx context.Context, cfg *config.Config, query string) *dnsMatch { if source, _ := netbox.SplitTarget(query); source != "" { return nil } name, addresses := lookupDNS(ctx, dnsNames(cfg, query)) if name == "" { return nil } match := &dnsMatch{name: name, addresses: addresses} seen := map[string]bool{} add := func(target, reason string) { if target != "" && !seen[strings.ToLower(target)] { seen[strings.ToLower(target)] = true match.suggestions = append(match.suggestions, dnsSuggestion{target: target, reason: reason}) } } if cfg.HasNetBox() { client := newNetBoxClient(cfg) for _, address := range addresses { owners, err := client.LookupIP(ctx, address) if err != nil { fmt.Fprintf(os.Stderr, "netssh: warning: %v\n", err) } for _, owner := range owners { reason := address if owner.Interface != "" { reason += " on " + owner.Interface } add(owner.Target(), reason+" (NetBox)") } } } c := newCache(cfg) _ = c.Load() entries := c.All() sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name }) for _, address := range addresses { for _, e := range entries { if e.IP == address { source := "cache" if e.Static { source = "static host" } add(e.Name, address+" ("+source+")") } } } return match } // resolveOrSuggest resolves host like resolveTargetE. When neither NetBox nor // the cache know it, the name is resolved through DNS and the hosts owning // its address are offered, in a terminal, together with a direct connection // to the DNS name. Without a terminal the suggestion is part of the error. func resolveOrSuggest(cfg *config.Config, host string, record bool) (resolvedHost, error) { resolved, err := resolveTargetE(cfg, host, record) if err == nil || !errors.Is(err, netbox.ErrHostNotFound) || cfg.DNS.SuggestMode() == config.DNSNever { return resolved, err } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() match := findDNSMatch(ctx, cfg, host) if match == nil { return resolved, err } var ( choice string ok bool promptErr error ) switch { case cfg.DNS.SuggestMode() == config.DNSAlways: choice, ok = match.first(host) case !stdinIsTerminal(): return resolved, fmt.Errorf("%w\n%s", err, match.describe()) default: choice, ok, promptErr = chooseDNSSuggestion(host, match) } if promptErr != nil { return resolved, promptErr } if !ok { return resolved, errors.New("cancelled") } if choice == "" { if !internalssh.ValidAddress(match.name) { return resolved, fmt.Errorf("refusing DNS name %q", match.name) } return resolvedHost{Name: host, Kind: "dns", IP: match.name, Origin: "dns"}, nil } resolved, err = resolveTargetE(cfg, choice, record) if err != nil { return resolved, err } offerLinkFunc(cfg.DNS.SaveLinkMode(), host, resolved.Name) return resolved, nil } // first takes the first suggestion for dns.suggest: always, or the DNS name // itself when no host owns the address. func (m *dnsMatch) first(query string) (string, bool) { if len(m.suggestions) == 0 { fmt.Fprintf(os.Stderr, "netssh: %s → %s (%s), no host owns it; connecting directly (dns.suggest: always)\n", query, m.name, strings.Join(m.addresses, ", ")) return "", true } s := m.suggestions[0] fmt.Fprintf(os.Stderr, "netssh: %s → %s, %s: connecting to %s (dns.suggest: always)\n", query, m.name, s.reason, s.target) return s.target, true } // describe renders the DNS result and the owning hosts for an error message. func (m *dnsMatch) describe() string { var b strings.Builder fmt.Fprintf(&b, "DNS: %s → %s", m.name, strings.Join(m.addresses, ", ")) if len(m.suggestions) == 0 { fmt.Fprintf(&b, "; no host in NetBox or the cache has this address") return b.String() } for _, s := range m.suggestions { fmt.Fprintf(&b, "\n netssh %s # %s", s.target, s.reason) } return b.String() } // chooseDNSSuggestion asks which host to connect to. It returns the chosen // target, "" for a direct connection to the DNS name, and false on cancel. func chooseDNSSuggestion(query string, m *dnsMatch) (string, bool, error) { fmt.Fprintf(os.Stderr, "netssh: %q is not in NetBox or the cache. DNS: %s → %s\n", query, m.name, strings.Join(m.addresses, ", ")) if len(m.suggestions) == 0 { fmt.Fprintln(os.Stderr, "No host in NetBox or the cache has this address.") } for i, s := range m.suggestions { fmt.Fprintf(os.Stderr, " %d) %s %s\n", i+1, s.target, s.reason) } direct := len(m.suggestions) + 1 fmt.Fprintf(os.Stderr, " %d) connect directly to %s\n", direct, m.name) fmt.Fprintf(os.Stderr, "Choose [1-%d, Enter = 1, q = cancel]: ", direct) answer, err := readAnswer() if err != nil { return "", false, err } switch { case answer == "": answer = "1" case strings.EqualFold(answer, "q"): return "", false, nil } n, convErr := strconv.Atoi(answer) if convErr != nil || n < 1 || n > direct { return "", false, fmt.Errorf("invalid choice %q", answer) } if n == direct { return "", true, nil } return m.suggestions[n-1].target, true, nil } // linkName proposes a link name for what the user typed: the first label of // a DNS name ("mx123" for mx123.webseite.de), else the input. func linkName(query string) string { if first, _, ok := strings.Cut(query, "."); ok && first != "" { return strings.ToLower(first) } return strings.ToLower(query) } // offerLink asks whether to save query as a link to target, so that the next // netssh NAME (and the shell alias NAME) connects without asking. func offerLink(mode, query, target string) { name := linkName(query) if strings.EqualFold(name, target) || mode == config.DNSNever { return } if mode == config.DNSAlways { if err := saveLink(name, target); err != nil { fmt.Fprintf(os.Stderr, "netssh: shortcut not saved: %v\n", err) return } fmt.Fprintf(os.Stderr, "netssh: saved shortcut %s → %s (dns.save_link: always)\n", name, target) return } if !stdinIsTerminal() { return } fmt.Fprintf(os.Stderr, "Save shortcut %q → %s (netssh %s, shell alias %s)? [y/N or another name]: ", name, target, name, name) answer, err := readAnswer() if err != nil { return } switch strings.ToLower(answer) { case "", "n", "no": return case "y", "yes", "j", "ja": default: name = strings.ToLower(answer) } if err := saveLink(name, target); err != nil { fmt.Fprintf(os.Stderr, "netssh: shortcut not saved: %v\n", err) return } fmt.Fprintf(os.Stderr, "netssh: saved; netssh %s now connects to %s (new shells also get the alias %s).\n", name, target, name) } // saveLink adds a link to the config file and regenerates the shell aliases. var saveLink = func(name, target string) error { cfg, err := config.Load() if err != nil { return err } if cfg.Links == nil { cfg.Links = map[string]string{} } for key := range cfg.Links { if strings.EqualFold(key, name) { delete(cfg.Links, key) } } cfg.Links[name] = target if err := cfg.ValidateLinks(); err != nil { return err } return saveHostsTo(cfg, os.Stderr) }