Debian Codegraph @

core/shell_transport_ssh_bin.go

raw
1 package core
2
3 import (
4 "bufio"
5 "fmt"
6 "io"
7 "os/exec"
8 "strings"
9 "time"
10
11 "github.com/dimonomid/nerdlog/log"
12 "github.com/juju/errors"
13 )
14
15 const echoMarkerConnected = "__CONNECTED__"
16
17 // ShellTransportSSHBin is an implementation of ShellTransport that opens an
18 // ssh session using external ssh binary.
19 type ShellTransportSSHBin struct {
20 params ShellTransportSSHBinParams
21 }
22
23 type ShellTransportSSHBinParams struct {
24 Host string
25 User string
26 Port string
27
28 Logger *log.Logger
29 }
30
31 // NewShellTransportSSHBin creates a new ShellTransportSSHBin with the given shell command.
32 func NewShellTransportSSHBin(params ShellTransportSSHBinParams) *ShellTransportSSHBin {
33 params.Logger = params.Logger.WithNamespaceAppended("TransportSSHBin")
34
35 return &ShellTransportSSHBin{
36 params: params,
37 }
38 }
39
40 // Connect starts the local shell and sends the result to the provided channel.
41 func (s *ShellTransportSSHBin) Connect(resCh chan<- ShellConnUpdate) {
42 go s.doConnect(resCh)
43 }
44
45 func (s *ShellTransportSSHBin) doConnect(
46 resCh chan<- ShellConnUpdate,
47 ) (res ShellConnResult) {
48 logger := s.params.Logger
49
50 defer func() {
51 if res.Err != nil {
52 logger.Errorf("Connection failed: %s", res.Err)
53 }
54 resCh <- ShellConnUpdate{
55 Result: &res,
56 }
57 }()
58
59 var sshArgs []string
60 if s.params.Port != "" {
61 sshArgs = append(sshArgs, "-p", s.params.Port)
62 }
63
64 // We can't easily intercept any prompts for passwords etc, because ssh
65 // interacts directly with the terminal, not stdin/stdout, and so we don't
66 // even try, and instruct ssh to fail instead of prompting.
67 //
68 // We might, in theory, use a PTY like https://github.com/creack/pty, but
69 // it's not gonna be very robust and smells like it might open a can of
70 // worms, so not for now.
71 sshArgs = append(sshArgs, "-o", "BatchMode=yes")
72
73 dest := s.params.Host
74 if s.params.User != "" {
75 dest = fmt.Sprintf("%s@%s", s.params.User, dest)
76 }
77 sshArgs = append(sshArgs, dest, "/bin/sh")
78
79 var sshCmdDebugBuilder strings.Builder
80 sshCmdDebugBuilder.WriteString("ssh")
81 for _, v := range sshArgs {
82 sshCmdDebugBuilder.WriteString(" ")
83 sshCmdDebugBuilder.WriteString(shellQuote(v))
84 }
85 sshCmdDebug := sshCmdDebugBuilder.String()
86
87 resCh <- ShellConnUpdate{
88 DebugInfo: s.makeDebugInfo(fmt.Sprintf(
89 "Trying to connect using external command: %q", sshCmdDebug,
90 )),
91 }
92 logger.Infof("Executing external ssh command: %q", sshCmdDebug)
93
94 cmd := exec.Command("ssh", sshArgs...)
95 stdin, err := cmd.StdinPipe()
96 if err != nil {
97 res.Err = errors.Annotatef(err, "getting stdin pipe")
98 return res
99 }
100 rawStdout, err := cmd.StdoutPipe()
101 if err != nil {
102 res.Err = errors.Annotatef(err, "getting stdout pipe")
103 return res
104 }
105 stderr, err := cmd.StderrPipe()
106 if err != nil {
107 res.Err = errors.Annotatef(err, "getting stderr pipe")
108 return res
109 }
110
111 if err := cmd.Start(); err != nil {
112 res.Err = errors.Annotatef(err, "starting shell")
113 return res
114 }
115
116 // To make sure we were able to connect, we just write "echo __CONNECTED__"
117 // to stdin, and wait for it to show up in the stdout.
118
119 resCh <- ShellConnUpdate{
120 DebugInfo: s.makeDebugInfo(fmt.Sprintf(
121 "Command started, writing \"echo %s\", waiting for it in stdout", echoMarkerConnected,
122 )),
123 }
124
125 _, err = fmt.Fprintf(stdin, "echo %s\n", echoMarkerConnected)
126 if err != nil {
127 res.Err = errors.Annotatef(err, "writing connection marker")
128 return res
129 }
130
131 clientStdoutR, clientStdoutW := io.Pipe()
132 scanner := bufio.NewScanner(rawStdout)
133 connErrCh := make(chan error)
134 go func() {
135 defer clientStdoutW.Close()
136 for scanner.Scan() {
137 line := scanner.Text()
138 logger.Verbose3f("Got line while looking for connected marker: %s", line)
139 if line == echoMarkerConnected {
140 logger.Verbose3f("Got the marker, switching to raw passthrough for stdout")
141 // Done waiting, switch to raw passthrough
142 connErrCh <- nil
143 io.Copy(clientStdoutW, rawStdout)
144 return
145 }
146 }
147 if err := scanner.Err(); err != nil {
148 logger.Errorf("Got scanner error while waiting for connection marker: %s", err.Error())
149 connErrCh <- errors.Annotatef(err, "reading from stdout while waiting for connection marker")
150 } else {
151 // Got EOF while waiting for the marker; apparently ssh failed to connect,
152 // so just read up all stderr (which likely contains the actual error message),
153 // and return it as an error.
154 stderrBytes, _ := io.ReadAll(stderr)
155 connErrCh <- errors.Errorf(
156 "failed to connect using external command \"%s\": %s",
157 sshCmdDebug, string(stderrBytes),
158 )
159 }
160 }()
161
162 // Wait for the marker to show up in output.
163 select {
164 case err := <-connErrCh:
165 if err != nil {
166 res.Err = errors.Trace(err)
167 return res
168 }
169
170 resCh <- ShellConnUpdate{
171 DebugInfo: s.makeDebugInfo("Got the marker, connected successfully"),
172 }
173
174 // Got the marker, so we're done.
175 res.Conn = &ShellConnSSHBin{
176 cmd: cmd,
177 stdin: stdin,
178 stdout: clientStdoutR,
179 stderr: stderr,
180 }
181 return res
182
183 case <-time.After(connectionTimeout):
184 res.Err = errors.New("timeout waiting for SSH connection marker")
185 return res
186 }
187 }
188
189 func (s *ShellTransportSSHBin) makeDebugInfo(message string) *ShellConnDebugInfo {
190 return &ShellConnDebugInfo{
191 Message: message,
192 }
193 }
194
195 type ShellConnSSHBin struct {
196 cmd *exec.Cmd
197
198 stdin io.WriteCloser
199 stdout io.Reader
200 stderr io.Reader
201 }
202
203 func (s *ShellConnSSHBin) Stdin() io.Writer {
204 return s.stdin
205 }
206
207 func (s *ShellConnSSHBin) Stdout() io.Reader {
208 return s.stdout
209 }
210
211 func (s *ShellConnSSHBin) Stderr() io.Reader {
212 return s.stderr
213 }
214
215 func (s *ShellConnSSHBin) Close() {
216 s.stdin.Close()
217 }