cmd/gitbay/ssh.go
320 lines · 9913 bytes
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "golang.org/x/term"
7 "io"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "regexp"
12 "slices"
13 "strconv"
14 "strings"
15 "syscall"
16
17 "gitbay.org/gitbay/internal/cliconfig"
18 "gitbay.org/gitbay/internal/protocol"
19 "gitbay.org/gitbay/internal/toolpath"
20 "github.com/spf13/cobra"
21)
22
23// context is the resolved target for a command: which instance to talk to
24// and, when run inside a clone of a forge repo, which repository.
25type target struct {
26 inst cliconfig.Instance
27 repo string // owner/name, "" when not inferable
28}
29
30// resolveTarget picks the instance and repo. An origin remote matching a
31// CONFIGURED instance wins and carries repo inference; otherwise the
32// default instance is used with no inference — a clone from some other
33// host (github, a different forge) must never hijack the command. The
34// raw origin serves as an ad-hoc instance only when nothing is configured
35// at all.
36func resolveTarget() (target, error) {
37 cfg, err := cliconfig.Load()
38 if err != nil {
39 return target{}, err
40 }
41
42 parsed, repo, originOK := cliconfig.ParseRemoteURL(originURL())
43 if originOK {
44 norm := func(p int) int {
45 if p == 0 {
46 return 22
47 }
48 return p
49 }
50 for _, inst := range cfg.Instances {
51 if inst.Host == parsed.Host && norm(inst.Port) == norm(parsed.Port) {
52 return target{inst: inst, repo: repo}, nil
53 }
54 }
55 }
56
57 if inst, _, err := cfg.DefaultInstance(); err == nil {
58 return target{inst: inst}, nil
59 }
60 if originOK {
61 return target{inst: parsed, repo: repo}, nil
62 }
63 return target{}, fmt.Errorf("no gitbay instance configured; run: gitbay remote add <name> <host>")
64}
65
66func originURL() string {
67 out, err := exec.Command(toolpath.Look("git"), "remote", "get-url", "origin").Output()
68 if err != nil {
69 return ""
70 }
71 return strings.TrimSpace(string(out))
72}
73
74// bareWord matches arguments that need no quoting for the server-side
75// POSIX tokenizer.
76var bareWord = regexp.MustCompile(`^[A-Za-z0-9@%+=:,./_!-]+$`)
77
78// shellQuote quotes one argument for the SSH command string; the server
79// tokenizes with POSIX rules and no expansion.
80func shellQuote(arg string) string {
81 if arg != "" && bareWord.MatchString(arg) {
82 return arg
83 }
84 return "'" + strings.ReplaceAll(arg, "'", `'\''`) + "'"
85}
86
87// sshArgs is every argument before the destination: the port, connection
88// multiplexing, and the profile's own options last so they win.
89//
90// Multiplexing is what makes a CLI over SSH usable: without it every
91// command pays a full handshake, seconds on a distant instance, and with
92// it the second command in five minutes rides the first's connection
93// (#94). The control socket lives under ~/.ssh, which ssh requires to be
94// private; a profile can set no_multiplex = true to opt out.
95func sshArgs(inst cliconfig.Instance) []string {
96 args := []string{}
97 if inst.Port != 0 && inst.Port != 22 {
98 args = append(args, "-p", strconv.Itoa(inst.Port))
99 }
100 if !inst.NoMultiplex {
101 if home, err := os.UserHomeDir(); err == nil {
102 if st, err := os.Stat(filepath.Join(home, ".ssh")); err == nil && st.IsDir() {
103 args = append(args,
104 "-o", "ControlMaster=auto",
105 "-o", "ControlPath="+filepath.Join(home, ".ssh", "gitbay-%C"),
106 "-o", "ControlPersist=300")
107 }
108 }
109 }
110 return append(args, inst.SSHOptions...)
111}
112
113// noColor is --no-color, stripped from argv in main.
114var noColor bool
115
116// termValue is GITBAY_TERM for this invocation: the terminal's width,
117// and whether colour is wanted. Empty when stdout is not a terminal,
118// so piped output stays the rows stock ssh prints, and when GITBAY_TERM
119// is "off", for an instance older than --term.
120func termValue(isTerminal bool, cols int, env func(string) string) string {
121 if !isTerminal || cols < 40 || env("GITBAY_TERM") == "off" {
122 return ""
123 }
124 v := strconv.Itoa(cols)
125 if !noColor && env("NO_COLOR") == "" && env("TERM") != "dumb" {
126 v += ",color"
127 }
128 return v
129}
130
131// stripNoColor removes --no-color wherever it appears.
132func stripNoColor(args []string) ([]string, bool) {
133 out := args[:0:0]
134 found := false
135 for _, a := range args {
136 if a == "--no-color" {
137 found = true
138 continue
139 }
140 out = append(out, a)
141 }
142 return out, found
143}
144
145// pagerArgv is the pager to run long output through: GITBAY_PAGER, then
146// PAGER, then less. An empty GITBAY_PAGER turns paging off.
147func pagerArgv(env func(string) (string, bool)) []string {
148 if v, ok := env("GITBAY_PAGER"); ok {
149 return strings.Fields(v)
150 }
151 if v, ok := env("PAGER"); ok && v != "" {
152 return strings.Fields(v)
153 }
154 return []string{"less"}
155}
156
157// pages reports whether a command's output goes through the pager at a
158// terminal: views, diffs and logs, never a follow or JSON.
159func pages(server, args []string) bool {
160 if len(server) == 0 || slices.Contains(args, "--json") || slices.Contains(args, "--follow") {
161 return false
162 }
163 switch server[len(server)-1] {
164 case "show", "diff", "log":
165 return true
166 }
167 return false
168}
169
170// cliPathOf is the path a cobra command was reached by, without the
171// root's name: "auth keys remove".
172func cliPathOf(cmd *cobra.Command) string {
173 return strings.TrimPrefix(cmd.CommandPath(), "gitbay ")
174}
175
176// withCLIPath prepends --path=<cliPath> to a server command line when the
177// CLI path is set and differs from the server path it dispatches, so
178// usage and help print a command the caller can run (#267). Dispatch
179// strips it before Lookup, as it does --term=.
180func withCLIPath(cliPath, server string, argv []string) []string {
181 if cliPath == "" || cliPath == server {
182 return argv
183 }
184 return append([]string{"--path=" + cliPath}, argv...)
185}
186
187// runSSH executes the server command over the system ssh binary, wiring
188// stdio through, with no pager. It returns the remote exit code.
189func runSSH(t target, serverArgv []string, stdin io.Reader) int {
190 return runSSHPaged(t, serverArgv, stdin, false)
191}
192
193// runSSHPaged is runSSH with output optionally run through the pager when
194// stdout is a terminal and page is true. It returns the remote exit code.
195func runSSHPaged(t target, serverArgv []string, stdin io.Reader, page bool) int {
196 args := sshArgs(t.inst)
197
198 fd := int(os.Stdout.Fd())
199 cols := 0
200 isTTY := term.IsTerminal(fd)
201 if isTTY {
202 cols, _, _ = term.GetSize(fd)
203 }
204 if v := termValue(isTTY, cols, os.Getenv); v != "" && !slices.Contains(serverArgv, "--json") {
205 serverArgv = append([]string{"--term=" + v}, serverArgv...)
206 }
207
208 quoted := make([]string, len(serverArgv))
209 for i, a := range serverArgv {
210 quoted[i] = shellQuote(a)
211 }
212 args = append(args, t.inst.SSHUser()+"@"+t.inst.Host, "--", strings.Join(quoted, " "))
213
214 cmd := exec.Command(toolpath.Look("ssh"), args...)
215 cmd.Stdin = stdin
216 cmd.Stdout = os.Stdout
217 cmd.Stderr = os.Stderr
218
219 var pager *exec.Cmd
220 var pw io.WriteCloser
221 if page && isTTY {
222 if argv := pagerArgv(os.LookupEnv); len(argv) > 0 {
223 pager = exec.Command(toolpath.Look(argv[0]), argv[1:]...)
224 pager.Stdout, pager.Stderr = os.Stdout, os.Stderr
225 if _, ok := os.LookupEnv("LESS"); !ok {
226 pager.Env = append(os.Environ(), "LESS=FRX")
227 }
228 if w, err := pager.StdinPipe(); err == nil && pager.Start() == nil {
229 pw = w
230 cmd.Stdout = pw
231 } else {
232 pager = nil
233 }
234 }
235 }
236
237 err := cmd.Run()
238 if pager != nil {
239 pw.Close()
240 pager.Wait()
241 }
242 if err == nil {
243 return 0
244 }
245 if ee, ok := err.(*exec.ExitError); ok {
246 if pager != nil {
247 if ws, ok := ee.Sys().(syscall.WaitStatus); ok && ws.Signaled() && ws.Signal() == syscall.SIGPIPE {
248 // The user quit the pager before ssh finished writing;
249 // that is not a failure of the command itself.
250 return 0
251 }
252 }
253 code := ee.ExitCode()
254 if code == 255 { // ssh-level failure (connection, auth, host key)
255 fmt.Fprintln(os.Stderr, "gitbay: ssh could not connect or authenticate; if this worked a moment ago,"+
256 " the instance may be rate-limiting authentication after a burst of connections: wait a minute and retry")
257 return protocol.ExitProtocol
258 }
259 return code
260 }
261 fmt.Fprintln(os.Stderr, "gitbay: running ssh:", err)
262 return protocol.ExitProtocol
263}
264
265// sshCapture runs a server command and returns its stdout, discarding
266// stderr. Used for quiet metadata fetches like issue templates.
267func sshCapture(t target, serverArgv []string) (string, int) {
268 args := sshArgs(t.inst)
269 quoted := make([]string, len(serverArgv))
270 for i, a := range serverArgv {
271 quoted[i] = shellQuote(a)
272 }
273 args = append(args, t.inst.SSHUser()+"@"+t.inst.Host, "--", strings.Join(quoted, " "))
274 out, err := exec.Command(toolpath.Look("ssh"), args...).Output()
275 if err != nil {
276 code := protocol.ExitProtocol
277 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() != 255 {
278 code = ee.ExitCode()
279 }
280 return "", code
281 }
282 return string(out), 0
283}
284
285// fetchIssueTemplate returns the repo's default issue template body, or ""
286// when there is none (or anything fails — prefill is best-effort).
287func fetchIssueTemplate(t target, repoPath string) string {
288 out, code := sshCapture(t, []string{"issue", "templates", repoPath, "--json"})
289 if code != 0 {
290 return ""
291 }
292 var env struct {
293 Data []struct {
294 Name string `json:"name"`
295 Body string `json:"body"`
296 } `json:"data"`
297 }
298 if json.Unmarshal([]byte(out), &env) != nil || len(env.Data) == 0 {
299 return ""
300 }
301 for _, tpl := range env.Data {
302 if tpl.Name == "issue-template.md" {
303 return tpl.Body
304 }
305 }
306 return env.Data[0].Body
307}
308
309// withRepo prepends the repo path to args unless the user already gave one
310// explicitly (a first argument containing '/'). Commands' server parsers
311// accept the path at any position, so the front is always safe.
312func withRepo(t target, args []string) ([]string, error) {
313 if len(args) > 0 && !strings.HasPrefix(args[0], "-") && strings.Contains(args[0], "/") {
314 return args, nil // explicit owner/name
315 }
316 if t.repo == "" {
317 return nil, fmt.Errorf("no repository given and none inferable: pass <owner/name> or run inside a clone of a gitbay repository")
318 }
319 return append([]string{t.repo}, args...), nil
320}