1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // Session implements an interactive session described in
8 // "RFC 4254, section 6".
22 // POSIX signals as listed in RFC 4254 Section 6.10.
24 SIGABRT Signal = "ABRT"
25 SIGALRM Signal = "ALRM"
30 SIGKILL Signal = "KILL"
31 SIGPIPE Signal = "PIPE"
32 SIGQUIT Signal = "QUIT"
33 SIGSEGV Signal = "SEGV"
34 SIGTERM Signal = "TERM"
35 SIGUSR1 Signal = "USR1"
36 SIGUSR2 Signal = "USR2"
39 var signals = map[Signal]int{
53 type TerminalModes map[uint8]uint32
55 // POSIX terminal mode flags as listed in RFC 4254 Section 8.
115 // A Session represents a connection to a remote command or shell.
116 type Session struct {
117 // Stdin specifies the remote process's standard input.
118 // If Stdin is nil, the remote process reads from an empty
122 // Stdout and Stderr specify the remote process's standard
125 // If either is nil, Run connects the corresponding file
126 // descriptor to an instance of ioutil.Discard. There is a
127 // fixed amount of buffering that is shared for the two streams.
128 // If either blocks it may eventually cause the remote
133 ch Channel // the channel backing this session
134 started bool // true once Start, Run or Shell is invoked.
135 copyFuncs []func() error
136 errors chan error // one send per copyFunc
138 // true if pipe method is active
139 stdinpipe, stdoutpipe, stderrpipe bool
141 // stdinPipeWriter is non-nil if StdinPipe has not been called
142 // and Stdin was specified by the user; it is the write end of
143 // a pipe connecting Session.Stdin to the stdin channel.
144 stdinPipeWriter io.WriteCloser
146 exitStatus chan error
149 // SendRequest sends an out-of-band channel request on the SSH channel
150 // underlying the session.
151 func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error) {
152 return s.ch.SendRequest(name, wantReply, payload)
155 func (s *Session) Close() error {
159 // RFC 4254 Section 6.4.
160 type setenvRequest struct {
165 // Setenv sets an environment variable that will be applied to any
166 // command executed by Shell or Run.
167 func (s *Session) Setenv(name, value string) error {
168 msg := setenvRequest{
172 ok, err := s.ch.SendRequest("env", true, Marshal(&msg))
173 if err == nil && !ok {
174 err = errors.New("ssh: setenv failed")
179 // RFC 4254 Section 6.2.
180 type ptyRequestMsg struct {
189 // RequestPty requests the association of a pty with the session on the remote host.
190 func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error {
192 for k, v := range termmodes {
198 tm = append(tm, Marshal(&kv)...)
200 tm = append(tm, tty_OP_END)
201 req := ptyRequestMsg{
205 Width: uint32(w * 8),
206 Height: uint32(h * 8),
207 Modelist: string(tm),
209 ok, err := s.ch.SendRequest("pty-req", true, Marshal(&req))
210 if err == nil && !ok {
211 err = errors.New("ssh: pty-req failed")
216 // RFC 4254 Section 6.5.
217 type subsystemRequestMsg struct {
221 // RequestSubsystem requests the association of a subsystem with the session on the remote host.
222 // A subsystem is a predefined command that runs in the background when the ssh session is initiated
223 func (s *Session) RequestSubsystem(subsystem string) error {
224 msg := subsystemRequestMsg{
225 Subsystem: subsystem,
227 ok, err := s.ch.SendRequest("subsystem", true, Marshal(&msg))
228 if err == nil && !ok {
229 err = errors.New("ssh: subsystem request failed")
234 // RFC 4254 Section 6.9.
235 type signalMsg struct {
239 // Signal sends the given signal to the remote process.
240 // sig is one of the SIG* constants.
241 func (s *Session) Signal(sig Signal) error {
246 _, err := s.ch.SendRequest("signal", false, Marshal(&msg))
250 // RFC 4254 Section 6.5.
251 type execMsg struct {
255 // Start runs cmd on the remote host. Typically, the remote
256 // server passes cmd to the shell for interpretation.
257 // A Session only accepts one call to Run, Start or Shell.
258 func (s *Session) Start(cmd string) error {
260 return errors.New("ssh: session already started")
266 ok, err := s.ch.SendRequest("exec", true, Marshal(&req))
267 if err == nil && !ok {
268 err = fmt.Errorf("ssh: command %v failed", cmd)
276 // Run runs cmd on the remote host. Typically, the remote
277 // server passes cmd to the shell for interpretation.
278 // A Session only accepts one call to Run, Start, Shell, Output,
279 // or CombinedOutput.
281 // The returned error is nil if the command runs, has no problems
282 // copying stdin, stdout, and stderr, and exits with a zero exit
285 // If the remote server does not send an exit status, an error of type
286 // *ExitMissingError is returned. If the command completes
287 // unsuccessfully or is interrupted by a signal, the error is of type
288 // *ExitError. Other error types may be returned for I/O problems.
289 func (s *Session) Run(cmd string) error {
297 // Output runs cmd on the remote host and returns its standard output.
298 func (s *Session) Output(cmd string) ([]byte, error) {
300 return nil, errors.New("ssh: Stdout already set")
305 return b.Bytes(), err
308 type singleWriter struct {
313 func (w *singleWriter) Write(p []byte) (int, error) {
319 // CombinedOutput runs cmd on the remote host and returns its combined
320 // standard output and standard error.
321 func (s *Session) CombinedOutput(cmd string) ([]byte, error) {
323 return nil, errors.New("ssh: Stdout already set")
326 return nil, errors.New("ssh: Stderr already set")
332 return b.b.Bytes(), err
335 // Shell starts a login shell on the remote host. A Session only
336 // accepts one call to Run, Start, Shell, Output, or CombinedOutput.
337 func (s *Session) Shell() error {
339 return errors.New("ssh: session already started")
342 ok, err := s.ch.SendRequest("shell", true, nil)
343 if err == nil && !ok {
344 return errors.New("ssh: could not start shell")
352 func (s *Session) start() error {
355 type F func(*Session)
356 for _, setupFd := range []F{(*Session).stdin, (*Session).stdout, (*Session).stderr} {
360 s.errors = make(chan error, len(s.copyFuncs))
361 for _, fn := range s.copyFuncs {
362 go func(fn func() error) {
369 // Wait waits for the remote command to exit.
371 // The returned error is nil if the command runs, has no problems
372 // copying stdin, stdout, and stderr, and exits with a zero exit
375 // If the remote server does not send an exit status, an error of type
376 // *ExitMissingError is returned. If the command completes
377 // unsuccessfully or is interrupted by a signal, the error is of type
378 // *ExitError. Other error types may be returned for I/O problems.
379 func (s *Session) Wait() error {
381 return errors.New("ssh: session not started")
383 waitErr := <-s.exitStatus
385 if s.stdinPipeWriter != nil {
386 s.stdinPipeWriter.Close()
389 for _ = range s.copyFuncs {
390 if err := <-s.errors; err != nil && copyError == nil {
400 func (s *Session) wait(reqs <-chan *Request) error {
401 wm := Waitmsg{status: -1}
402 // Wait for msg channel to be closed before returning.
403 for msg := range reqs {
406 wm.status = int(binary.BigEndian.Uint32(msg.Payload))
414 if err := Unmarshal(msg.Payload, &sigval); err != nil {
418 // Must sanitize strings?
419 wm.signal = sigval.Signal
420 wm.msg = sigval.Error
421 wm.lang = sigval.Lang
423 // This handles keepalives and matches
424 // OpenSSH's behaviour.
426 msg.Reply(false, nil)
434 // exit-status was never sent from server
436 // signal was not sent either. RFC 4254
437 // section 6.10 recommends against this
438 // behavior, but it is allowed, so we let
439 // clients handle it.
440 return &ExitMissingError{}
443 if _, ok := signals[Signal(wm.signal)]; ok {
444 wm.status += signals[Signal(wm.signal)]
448 return &ExitError{wm}
451 // ExitMissingError is returned if a session is torn down cleanly, but
452 // the server sends no confirmation of the exit status.
453 type ExitMissingError struct{}
455 func (e *ExitMissingError) Error() string {
456 return "wait: remote command exited without exit status or exit signal"
459 func (s *Session) stdin() {
465 stdin = new(bytes.Buffer)
469 _, err := io.Copy(w, s.Stdin)
470 w.CloseWithError(err)
472 stdin, s.stdinPipeWriter = r, w
474 s.copyFuncs = append(s.copyFuncs, func() error {
475 _, err := io.Copy(s.ch, stdin)
476 if err1 := s.ch.CloseWrite(); err == nil && err1 != io.EOF {
483 func (s *Session) stdout() {
488 s.Stdout = ioutil.Discard
490 s.copyFuncs = append(s.copyFuncs, func() error {
491 _, err := io.Copy(s.Stdout, s.ch)
496 func (s *Session) stderr() {
501 s.Stderr = ioutil.Discard
503 s.copyFuncs = append(s.copyFuncs, func() error {
504 _, err := io.Copy(s.Stderr, s.ch.Stderr())
509 // sessionStdin reroutes Close to CloseWrite.
510 type sessionStdin struct {
515 func (s *sessionStdin) Close() error {
516 return s.ch.CloseWrite()
519 // StdinPipe returns a pipe that will be connected to the
520 // remote command's standard input when the command starts.
521 func (s *Session) StdinPipe() (io.WriteCloser, error) {
523 return nil, errors.New("ssh: Stdin already set")
526 return nil, errors.New("ssh: StdinPipe after process started")
529 return &sessionStdin{s.ch, s.ch}, nil
532 // StdoutPipe returns a pipe that will be connected to the
533 // remote command's standard output when the command starts.
534 // There is a fixed amount of buffering that is shared between
535 // stdout and stderr streams. If the StdoutPipe reader is
536 // not serviced fast enough it may eventually cause the
537 // remote command to block.
538 func (s *Session) StdoutPipe() (io.Reader, error) {
540 return nil, errors.New("ssh: Stdout already set")
543 return nil, errors.New("ssh: StdoutPipe after process started")
549 // StderrPipe returns a pipe that will be connected to the
550 // remote command's standard error when the command starts.
551 // There is a fixed amount of buffering that is shared between
552 // stdout and stderr streams. If the StderrPipe reader is
553 // not serviced fast enough it may eventually cause the
554 // remote command to block.
555 func (s *Session) StderrPipe() (io.Reader, error) {
557 return nil, errors.New("ssh: Stderr already set")
560 return nil, errors.New("ssh: StderrPipe after process started")
563 return s.ch.Stderr(), nil
566 // newSession returns a new interactive session on the remote host.
567 func newSession(ch Channel, reqs <-chan *Request) (*Session, error) {
571 s.exitStatus = make(chan error, 1)
573 s.exitStatus <- s.wait(reqs)
579 // An ExitError reports unsuccessful completion of a remote command.
580 type ExitError struct {
584 func (e *ExitError) Error() string {
585 return e.Waitmsg.String()
588 // Waitmsg stores the information about an exited remote command
589 // as reported by Wait.
590 type Waitmsg struct {
597 // ExitStatus returns the exit status of the remote command.
598 func (w Waitmsg) ExitStatus() int {
602 // Signal returns the exit signal of the remote command if
603 // it was terminated violently.
604 func (w Waitmsg) Signal() string {
608 // Msg returns the exit message given by the remote command
609 func (w Waitmsg) Msg() string {
613 // Lang returns the language tag. See RFC 3066
614 func (w Waitmsg) Lang() string {
618 func (w Waitmsg) String() string {
619 str := fmt.Sprintf("Process exited with status %v", w.status)
621 str += fmt.Sprintf(" from signal %v", w.signal)
624 str += fmt.Sprintf(". Reason was: %v", w.msg)