2013-05-20 18:47:41 -04:00
|
|
|
package ssh
|
|
|
|
|
|
|
|
import (
|
2013-07-17 21:15:42 -04:00
|
|
|
"bufio"
|
2013-05-20 18:47:41 -04:00
|
|
|
"bytes"
|
2013-07-07 15:23:32 -04:00
|
|
|
"errors"
|
2013-05-24 11:23:48 -04:00
|
|
|
"fmt"
|
2013-05-20 18:52:34 -04:00
|
|
|
"io"
|
2013-11-02 04:07:45 -04:00
|
|
|
"io/ioutil"
|
2013-05-20 18:47:41 -04:00
|
|
|
"log"
|
|
|
|
"net"
|
2013-08-24 20:14:15 -04:00
|
|
|
"os"
|
2013-05-24 11:23:48 -04:00
|
|
|
"path/filepath"
|
2015-02-08 20:24:31 -05:00
|
|
|
"strconv"
|
2015-11-02 06:22:52 -05:00
|
|
|
"strings"
|
2015-07-02 06:40:47 -04:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/mitchellh/packer/packer"
|
2015-07-26 19:39:56 -04:00
|
|
|
"github.com/pkg/sftp"
|
2015-07-02 06:40:47 -04:00
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
"golang.org/x/crypto/ssh/agent"
|
2013-05-20 18:47:41 -04:00
|
|
|
)
|
|
|
|
|
2015-07-02 14:58:51 -04:00
|
|
|
// ErrHandshakeTimeout is returned from New() whenever we're unable to establish
|
|
|
|
// an ssh connection within a certain timeframe. By default the handshake time-
|
|
|
|
// out period is 1 minute. You can change it with Config.HandshakeTimeout.
|
2015-07-02 06:40:47 -04:00
|
|
|
var ErrHandshakeTimeout = fmt.Errorf("Timeout during SSH handshake")
|
|
|
|
|
2013-05-20 18:47:41 -04:00
|
|
|
type comm struct {
|
2014-04-10 04:48:55 -04:00
|
|
|
client *ssh.Client
|
|
|
|
config *Config
|
|
|
|
conn net.Conn
|
|
|
|
address string
|
2013-07-14 07:22:41 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Config is the structure used to configure the SSH communicator.
|
|
|
|
type Config struct {
|
|
|
|
// The configuration of the Go SSH connection
|
|
|
|
SSHConfig *ssh.ClientConfig
|
|
|
|
|
|
|
|
// Connection returns a new connection. The current connection
|
|
|
|
// in use will be closed as part of the Close method, or in the
|
|
|
|
// case an error occurs.
|
|
|
|
Connection func() (net.Conn, error)
|
2013-08-27 19:51:05 -04:00
|
|
|
|
2015-02-12 23:18:54 -05:00
|
|
|
// Pty, if true, will request a pty from the remote end.
|
|
|
|
Pty bool
|
2015-06-23 17:52:37 -04:00
|
|
|
|
|
|
|
// DisableAgent, if true, will not forward the SSH agent.
|
|
|
|
DisableAgent bool
|
2015-07-02 06:40:47 -04:00
|
|
|
|
|
|
|
// HandshakeTimeout limits the amount of time we'll wait to handshake before
|
|
|
|
// saying the connection failed.
|
|
|
|
HandshakeTimeout time.Duration
|
2015-07-26 19:39:56 -04:00
|
|
|
|
|
|
|
// UseSftp, if true, sftp will be used instead of scp for file transfers
|
|
|
|
UseSftp bool
|
2013-05-20 18:47:41 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Creates a new packer.Communicator implementation over SSH. This takes
|
|
|
|
// an already existing TCP connection and SSH configuration.
|
2014-04-10 04:48:55 -04:00
|
|
|
func New(address string, config *Config) (result *comm, err error) {
|
2013-07-14 07:22:41 -04:00
|
|
|
// Establish an initial connection and connect
|
|
|
|
result = &comm{
|
2014-04-10 04:48:55 -04:00
|
|
|
config: config,
|
|
|
|
address: address,
|
2013-07-14 07:22:41 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if err = result.reconnect(); err != nil {
|
|
|
|
result = nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-05-20 18:47:41 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-06-03 02:27:01 -04:00
|
|
|
func (c *comm) Start(cmd *packer.RemoteCmd) (err error) {
|
2013-07-14 07:55:02 -04:00
|
|
|
session, err := c.newSession()
|
2013-05-20 18:47:41 -04:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Setup our session
|
2013-06-03 02:27:01 -04:00
|
|
|
session.Stdin = cmd.Stdin
|
|
|
|
session.Stdout = cmd.Stdout
|
|
|
|
session.Stderr = cmd.Stderr
|
2013-05-20 18:47:41 -04:00
|
|
|
|
2015-02-12 23:18:54 -05:00
|
|
|
if c.config.Pty {
|
2013-08-27 19:51:05 -04:00
|
|
|
// Request a PTY
|
|
|
|
termModes := ssh.TerminalModes{
|
|
|
|
ssh.ECHO: 0, // do not echo
|
|
|
|
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
|
|
|
|
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
|
|
|
|
}
|
2013-06-23 20:36:45 -04:00
|
|
|
|
2016-04-06 15:40:19 -04:00
|
|
|
if err = session.RequestPty("xterm", 40, 80, termModes); err != nil {
|
2013-08-27 19:51:05 -04:00
|
|
|
return
|
|
|
|
}
|
2013-06-23 20:36:45 -04:00
|
|
|
}
|
|
|
|
|
2013-06-03 02:27:01 -04:00
|
|
|
log.Printf("starting remote command: %s", cmd.Command)
|
|
|
|
err = session.Start(cmd.Command + "\n")
|
2013-05-20 18:47:41 -04:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start a goroutine to wait for the session to end and set the
|
|
|
|
// exit boolean and status.
|
|
|
|
go func() {
|
|
|
|
defer session.Close()
|
2013-08-28 01:12:21 -04:00
|
|
|
|
2013-05-20 18:47:41 -04:00
|
|
|
err := session.Wait()
|
2013-07-29 15:12:42 -04:00
|
|
|
exitStatus := 0
|
2013-05-20 18:47:41 -04:00
|
|
|
if err != nil {
|
2016-10-05 21:05:01 -04:00
|
|
|
switch err.(type) {
|
|
|
|
case *ssh.ExitError:
|
|
|
|
exitStatus = err.(*ssh.ExitError).ExitStatus()
|
2016-10-06 14:13:30 -04:00
|
|
|
log.Printf("Remote command exited with '%d': %s", exitStatus, cmd.Command)
|
2016-10-05 21:05:01 -04:00
|
|
|
case *ssh.ExitMissingError:
|
2016-10-06 14:13:30 -04:00
|
|
|
log.Printf("Remote command exited without exit status or exit signal.")
|
2016-10-05 21:05:01 -04:00
|
|
|
exitStatus = -1
|
|
|
|
default:
|
2016-10-06 14:13:30 -04:00
|
|
|
log.Printf("Error occurred waiting for ssh session: %s", err.Error())
|
2016-10-05 21:05:01 -04:00
|
|
|
exitStatus = -1
|
2013-05-20 18:47:41 -04:00
|
|
|
}
|
|
|
|
}
|
2013-07-29 15:12:42 -04:00
|
|
|
cmd.SetExited(exitStatus)
|
2013-08-28 01:12:21 -04:00
|
|
|
}()
|
|
|
|
|
2013-05-20 18:47:41 -04:00
|
|
|
return
|
|
|
|
}
|
2013-05-20 18:52:34 -04:00
|
|
|
|
2014-05-10 00:03:35 -04:00
|
|
|
func (c *comm) Upload(path string, input io.Reader, fi *os.FileInfo) error {
|
2015-07-26 19:39:56 -04:00
|
|
|
if c.config.UseSftp {
|
|
|
|
return c.sftpUploadSession(path, input, fi)
|
|
|
|
} else {
|
|
|
|
return c.scpUploadSession(path, input, fi)
|
2013-05-24 12:06:13 -04:00
|
|
|
}
|
2013-05-20 18:52:34 -04:00
|
|
|
}
|
|
|
|
|
2013-08-23 22:31:33 -04:00
|
|
|
func (c *comm) UploadDir(dst string, src string, excl []string) error {
|
2013-08-25 23:47:10 -04:00
|
|
|
log.Printf("Upload dir '%s' to '%s'", src, dst)
|
2015-07-26 19:39:56 -04:00
|
|
|
if c.config.UseSftp {
|
|
|
|
return c.sftpUploadDirSession(dst, src, excl)
|
|
|
|
} else {
|
|
|
|
return c.scpUploadDirSession(dst, src, excl)
|
2013-08-24 20:14:15 -04:00
|
|
|
}
|
2013-08-23 22:31:33 -04:00
|
|
|
}
|
|
|
|
|
2015-11-02 06:22:52 -05:00
|
|
|
func (c *comm) DownloadDir(src string, dst string, excl []string) error {
|
|
|
|
log.Printf("Download dir '%s' to '%s'", src, dst)
|
|
|
|
scpFunc := func(w io.Writer, stdoutR *bufio.Reader) error {
|
2016-09-18 08:46:37 -04:00
|
|
|
dirStack := []string{dst}
|
2015-11-02 06:22:52 -05:00
|
|
|
for {
|
|
|
|
fmt.Fprint(w, "\x00")
|
|
|
|
|
|
|
|
// read file info
|
|
|
|
fi, err := stdoutR.ReadString('\n')
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(fi) < 0 {
|
|
|
|
return fmt.Errorf("empty response from server")
|
|
|
|
}
|
|
|
|
|
|
|
|
switch fi[0] {
|
|
|
|
case '\x01', '\x02':
|
|
|
|
return fmt.Errorf("%s", fi[1:len(fi)])
|
|
|
|
case 'C', 'D':
|
|
|
|
break
|
2016-09-18 08:46:37 -04:00
|
|
|
case 'E':
|
|
|
|
dirStack = dirStack[:len(dirStack)-1]
|
|
|
|
if len(dirStack) == 1 {
|
|
|
|
fmt.Fprint(w, "\x00")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
continue
|
2015-11-02 06:22:52 -05:00
|
|
|
default:
|
|
|
|
return fmt.Errorf("unexpected server response (%x)", fi[0])
|
|
|
|
}
|
|
|
|
|
|
|
|
var mode string
|
|
|
|
var size int64
|
|
|
|
var name string
|
|
|
|
log.Printf("Download dir str:%s", fi)
|
|
|
|
n, err := fmt.Sscanf(fi, "%6s %d %s", &mode, &size, &name)
|
|
|
|
if err != nil || n != 3 {
|
|
|
|
return fmt.Errorf("can't parse server response (%s)", fi)
|
|
|
|
}
|
|
|
|
if size < 0 {
|
|
|
|
return fmt.Errorf("negative file size")
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Download dir mode:%s size:%d name:%s", mode, size, name)
|
2016-09-18 08:46:37 -04:00
|
|
|
|
|
|
|
dst = filepath.Join(dirStack...)
|
2015-11-02 06:22:52 -05:00
|
|
|
switch fi[0] {
|
|
|
|
case 'D':
|
|
|
|
err = os.MkdirAll(filepath.Join(dst, name), os.FileMode(0755))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-09-18 08:46:37 -04:00
|
|
|
dirStack = append(dirStack, name)
|
|
|
|
continue
|
2015-11-02 06:22:52 -05:00
|
|
|
case 'C':
|
|
|
|
fmt.Fprint(w, "\x00")
|
|
|
|
err = scpDownloadFile(filepath.Join(dst, name), stdoutR, size, os.FileMode(0644))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := checkSCPStatus(stdoutR); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return c.scpSession("scp -vrf "+src, scpFunc)
|
|
|
|
}
|
|
|
|
|
2015-02-08 20:24:31 -05:00
|
|
|
func (c *comm) Download(path string, output io.Writer) error {
|
2015-07-26 19:39:56 -04:00
|
|
|
if c.config.UseSftp {
|
|
|
|
return c.sftpDownloadSession(path, output)
|
2015-02-08 20:24:31 -05:00
|
|
|
}
|
2015-11-02 06:22:52 -05:00
|
|
|
return c.scpDownloadSession(path, output)
|
2013-05-20 18:52:34 -04:00
|
|
|
}
|
2013-07-14 07:22:41 -04:00
|
|
|
|
2013-08-12 18:22:31 -04:00
|
|
|
func (c *comm) newSession() (session *ssh.Session, err error) {
|
2013-07-14 07:55:02 -04:00
|
|
|
log.Println("opening new ssh session")
|
2013-08-12 18:22:31 -04:00
|
|
|
if c.client == nil {
|
|
|
|
err = errors.New("client not available")
|
|
|
|
} else {
|
|
|
|
session, err = c.client.NewSession()
|
|
|
|
}
|
|
|
|
|
2013-07-14 07:55:02 -04:00
|
|
|
if err != nil {
|
2013-07-14 08:07:32 -04:00
|
|
|
log.Printf("ssh session open error: '%s', attempting reconnect", err)
|
2013-07-14 07:55:02 -04:00
|
|
|
if err := c.reconnect(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.client.NewSession()
|
|
|
|
}
|
|
|
|
|
|
|
|
return session, nil
|
|
|
|
}
|
|
|
|
|
2013-07-14 07:22:41 -04:00
|
|
|
func (c *comm) reconnect() (err error) {
|
|
|
|
if c.conn != nil {
|
|
|
|
c.conn.Close()
|
|
|
|
}
|
|
|
|
|
2013-08-12 18:22:31 -04:00
|
|
|
// Set the conn and client to nil since we'll recreate it
|
|
|
|
c.conn = nil
|
|
|
|
c.client = nil
|
|
|
|
|
2013-07-14 07:55:02 -04:00
|
|
|
log.Printf("reconnecting to TCP connection for SSH")
|
2013-07-14 07:22:41 -04:00
|
|
|
c.conn, err = c.config.Connection()
|
|
|
|
if err != nil {
|
2013-10-14 04:21:52 -04:00
|
|
|
// Explicitly set this to the REAL nil. Connection() can return
|
|
|
|
// a nil implementation of net.Conn which will make the
|
|
|
|
// "if c.conn == nil" check fail above. Read here for more information
|
|
|
|
// on this psychotic language feature:
|
|
|
|
//
|
|
|
|
// http://golang.org/doc/faq#nil_error
|
|
|
|
c.conn = nil
|
|
|
|
|
2013-07-14 07:55:02 -04:00
|
|
|
log.Printf("reconnection error: %s", err)
|
2013-07-14 07:22:41 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-07-14 07:55:02 -04:00
|
|
|
log.Printf("handshaking with SSH")
|
2015-07-02 06:40:47 -04:00
|
|
|
|
|
|
|
// Default timeout to 1 minute if it wasn't specified (zero value). For
|
|
|
|
// when you need to handshake from low orbit.
|
|
|
|
var duration time.Duration
|
|
|
|
if c.config.HandshakeTimeout == 0 {
|
|
|
|
duration = 1 * time.Minute
|
|
|
|
} else {
|
|
|
|
duration = c.config.HandshakeTimeout
|
|
|
|
}
|
|
|
|
|
2015-07-02 14:58:51 -04:00
|
|
|
connectionEstablished := make(chan struct{}, 1)
|
2015-07-02 06:40:47 -04:00
|
|
|
|
|
|
|
var sshConn ssh.Conn
|
|
|
|
var sshChan <-chan ssh.NewChannel
|
|
|
|
var req <-chan *ssh.Request
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
sshConn, sshChan, req, err = ssh.NewClientConn(c.conn, c.address, c.config.SSHConfig)
|
2015-07-02 14:58:51 -04:00
|
|
|
close(connectionEstablished)
|
2015-07-02 06:40:47 -04:00
|
|
|
}()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-connectionEstablished:
|
|
|
|
// We don't need to do anything here. We just want select to block until
|
|
|
|
// we connect or timeout.
|
2015-07-02 14:58:51 -04:00
|
|
|
case <-time.After(duration):
|
2015-07-02 06:55:18 -04:00
|
|
|
if c.conn != nil {
|
|
|
|
c.conn.Close()
|
|
|
|
}
|
|
|
|
if sshConn != nil {
|
|
|
|
sshConn.Close()
|
|
|
|
}
|
2015-07-02 06:40:47 -04:00
|
|
|
return ErrHandshakeTimeout
|
|
|
|
}
|
|
|
|
|
2013-07-14 07:55:02 -04:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("handshake error: %s", err)
|
2015-07-02 06:40:47 -04:00
|
|
|
return
|
2013-07-14 07:55:02 -04:00
|
|
|
}
|
2015-06-29 14:38:05 -04:00
|
|
|
log.Printf("handshake complete!")
|
2014-04-10 04:48:55 -04:00
|
|
|
if sshConn != nil {
|
|
|
|
c.client = ssh.NewClient(sshConn, sshChan, req)
|
|
|
|
}
|
2015-06-13 20:15:49 -04:00
|
|
|
c.connectToAgent()
|
2013-07-14 07:55:02 -04:00
|
|
|
|
2013-07-14 07:22:41 -04:00
|
|
|
return
|
|
|
|
}
|
2013-07-17 21:15:42 -04:00
|
|
|
|
2015-06-13 20:15:49 -04:00
|
|
|
func (c *comm) connectToAgent() {
|
|
|
|
if c.client == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-06-23 17:52:37 -04:00
|
|
|
if c.config.DisableAgent {
|
2015-06-26 13:52:21 -04:00
|
|
|
log.Printf("[INFO] SSH agent forwarding is disabled.")
|
2015-06-23 17:52:37 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-06-13 20:15:49 -04:00
|
|
|
// open connection to the local agent
|
|
|
|
socketLocation := os.Getenv("SSH_AUTH_SOCK")
|
|
|
|
if socketLocation == "" {
|
2015-06-13 22:00:28 -04:00
|
|
|
log.Printf("[INFO] no local agent socket, will not connect agent")
|
2015-06-13 20:15:49 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
agentConn, err := net.Dial("unix", socketLocation)
|
|
|
|
if err != nil {
|
2015-06-13 22:00:28 -04:00
|
|
|
log.Printf("[ERROR] could not connect to local agent socket: %s", socketLocation)
|
2015-06-13 20:15:49 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// create agent and add in auth
|
|
|
|
forwardingAgent := agent.NewClient(agentConn)
|
|
|
|
if forwardingAgent == nil {
|
2015-06-13 22:00:28 -04:00
|
|
|
log.Printf("[ERROR] Could not create agent client")
|
2015-06-13 20:15:49 -04:00
|
|
|
agentConn.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// add callback for forwarding agent to SSH config
|
|
|
|
// XXX - might want to handle reconnects appending multiple callbacks
|
|
|
|
auth := ssh.PublicKeysCallback(forwardingAgent.Signers)
|
|
|
|
c.config.SSHConfig.Auth = append(c.config.SSHConfig.Auth, auth)
|
|
|
|
agent.ForwardToAgent(c.client, forwardingAgent)
|
|
|
|
|
|
|
|
// Setup a session to request agent forwarding
|
|
|
|
session, err := c.newSession()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer session.Close()
|
|
|
|
|
|
|
|
err = agent.RequestAgentForwarding(session)
|
|
|
|
if err != nil {
|
2015-06-13 22:00:28 -04:00
|
|
|
log.Printf("[ERROR] RequestAgentForwarding: %#v", err)
|
2015-06-13 20:15:49 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-06-13 22:00:28 -04:00
|
|
|
log.Printf("[INFO] agent forwarding enabled")
|
2015-06-13 20:15:49 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-07-26 19:39:56 -04:00
|
|
|
func (c *comm) sftpUploadSession(path string, input io.Reader, fi *os.FileInfo) error {
|
|
|
|
sftpFunc := func(client *sftp.Client) error {
|
|
|
|
return sftpUploadFile(path, input, client, fi)
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.sftpSession(sftpFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
func sftpUploadFile(path string, input io.Reader, client *sftp.Client, fi *os.FileInfo) error {
|
|
|
|
log.Printf("[DEBUG] sftp: uploading %s", path)
|
|
|
|
|
|
|
|
f, err := client.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
if _, err = io.Copy(f, input); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if fi != nil && (*fi).Mode().IsRegular() {
|
|
|
|
mode := (*fi).Mode().Perm()
|
|
|
|
err = client.Chmod(path, mode)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *comm) sftpUploadDirSession(dst string, src string, excl []string) error {
|
|
|
|
sftpFunc := func(client *sftp.Client) error {
|
|
|
|
rootDst := dst
|
|
|
|
if src[len(src)-1] != '/' {
|
|
|
|
log.Printf("No trailing slash, creating the source directory name")
|
|
|
|
rootDst = filepath.Join(dst, filepath.Base(src))
|
|
|
|
}
|
|
|
|
walkFunc := func(path string, info os.FileInfo, err error) error {
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Calculate the final destination using the
|
|
|
|
// base source and root destination
|
|
|
|
relSrc, err := filepath.Rel(src, path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
finalDst := filepath.Join(rootDst, relSrc)
|
|
|
|
|
|
|
|
// In Windows, Join uses backslashes which we don't want to get
|
|
|
|
// to the sftp server
|
|
|
|
finalDst = filepath.ToSlash(finalDst)
|
|
|
|
|
|
|
|
// Skip the creation of the target destination directory since
|
|
|
|
// it should exist and we might not even own it
|
|
|
|
if finalDst == dst {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return sftpVisitFile(finalDst, path, info, client)
|
|
|
|
}
|
|
|
|
|
|
|
|
return filepath.Walk(src, walkFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.sftpSession(sftpFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
func sftpMkdir(path string, client *sftp.Client, fi os.FileInfo) error {
|
|
|
|
log.Printf("[DEBUG] sftp: creating dir %s", path)
|
|
|
|
|
|
|
|
if err := client.Mkdir(path); err != nil {
|
|
|
|
// Do not consider it an error if the directory existed
|
|
|
|
remoteFi, fiErr := client.Lstat(path)
|
|
|
|
if fiErr != nil || !remoteFi.IsDir() {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
mode := fi.Mode().Perm()
|
|
|
|
if err := client.Chmod(path, mode); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func sftpVisitFile(dst string, src string, fi os.FileInfo, client *sftp.Client) error {
|
|
|
|
if !fi.IsDir() {
|
|
|
|
f, err := os.Open(src)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
return sftpUploadFile(dst, f, client, &fi)
|
|
|
|
} else {
|
|
|
|
err := sftpMkdir(dst, client, fi)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *comm) sftpDownloadSession(path string, output io.Writer) error {
|
|
|
|
sftpFunc := func(client *sftp.Client) error {
|
|
|
|
f, err := client.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
if _, err = io.Copy(output, f); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.sftpSession(sftpFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *comm) sftpSession(f func(*sftp.Client) error) error {
|
|
|
|
client, err := c.newSftpClient()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer client.Close()
|
|
|
|
|
|
|
|
return f(client)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *comm) newSftpClient() (*sftp.Client, error) {
|
|
|
|
session, err := c.newSession()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := session.RequestSubsystem("sftp"); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
pw, err := session.StdinPipe()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
pr, err := session.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return sftp.NewClientPipe(pr, pw)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *comm) scpUploadSession(path string, input io.Reader, fi *os.FileInfo) error {
|
|
|
|
|
|
|
|
// The target directory and file for talking the SCP protocol
|
|
|
|
target_dir := filepath.Dir(path)
|
|
|
|
target_file := filepath.Base(path)
|
|
|
|
|
|
|
|
// On windows, filepath.Dir uses backslash seperators (ie. "\tmp").
|
|
|
|
// This does not work when the target host is unix. Switch to forward slash
|
|
|
|
// which works for unix and windows
|
|
|
|
target_dir = filepath.ToSlash(target_dir)
|
|
|
|
|
|
|
|
scpFunc := func(w io.Writer, stdoutR *bufio.Reader) error {
|
|
|
|
return scpUploadFile(target_file, input, w, stdoutR, fi)
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.scpSession("scp -vt "+target_dir, scpFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *comm) scpUploadDirSession(dst string, src string, excl []string) error {
|
|
|
|
scpFunc := func(w io.Writer, r *bufio.Reader) error {
|
|
|
|
uploadEntries := func() error {
|
|
|
|
f, err := os.Open(src)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
entries, err := f.Readdir(-1)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return scpUploadDir(src, entries, w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
if src[len(src)-1] != '/' {
|
|
|
|
log.Printf("No trailing slash, creating the source directory name")
|
|
|
|
fi, err := os.Stat(src)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return scpUploadDirProtocol(filepath.Base(src), w, r, uploadEntries, fi)
|
|
|
|
} else {
|
|
|
|
// Trailing slash, so only upload the contents
|
|
|
|
return uploadEntries()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.scpSession("scp -rvt "+dst, scpFunc)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *comm) scpDownloadSession(path string, output io.Writer) error {
|
|
|
|
scpFunc := func(w io.Writer, stdoutR *bufio.Reader) error {
|
|
|
|
fmt.Fprint(w, "\x00")
|
|
|
|
|
|
|
|
// read file info
|
|
|
|
fi, err := stdoutR.ReadString('\n')
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(fi) < 0 {
|
|
|
|
return fmt.Errorf("empty response from server")
|
|
|
|
}
|
|
|
|
|
|
|
|
switch fi[0] {
|
|
|
|
case '\x01', '\x02':
|
|
|
|
return fmt.Errorf("%s", fi[1:len(fi)])
|
|
|
|
case 'C':
|
|
|
|
case 'D':
|
|
|
|
return fmt.Errorf("remote file is directory")
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("unexpected server response (%x)", fi[0])
|
|
|
|
}
|
|
|
|
|
|
|
|
var mode string
|
|
|
|
var size int64
|
|
|
|
|
|
|
|
n, err := fmt.Sscanf(fi, "%6s %d ", &mode, &size)
|
|
|
|
if err != nil || n != 2 {
|
|
|
|
return fmt.Errorf("can't parse server response (%s)", fi)
|
|
|
|
}
|
|
|
|
if size < 0 {
|
|
|
|
return fmt.Errorf("negative file size")
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprint(w, "\x00")
|
|
|
|
|
|
|
|
if _, err := io.CopyN(output, stdoutR, size); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprint(w, "\x00")
|
|
|
|
|
|
|
|
if err := checkSCPStatus(stdoutR); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-11-02 06:22:52 -05:00
|
|
|
if strings.Index(path, " ") == -1 {
|
|
|
|
return c.scpSession("scp -vf "+path, scpFunc)
|
|
|
|
}
|
2015-07-26 19:39:56 -04:00
|
|
|
return c.scpSession("scp -vf "+strconv.Quote(path), scpFunc)
|
|
|
|
}
|
|
|
|
|
2013-08-23 22:52:02 -04:00
|
|
|
func (c *comm) scpSession(scpCommand string, f func(io.Writer, *bufio.Reader) error) error {
|
|
|
|
session, err := c.newSession()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer session.Close()
|
|
|
|
|
|
|
|
// Get a pipe to stdin so that we can send data down
|
|
|
|
stdinW, err := session.StdinPipe()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// We only want to close once, so we nil w after we close it,
|
|
|
|
// and only close in the defer if it hasn't been closed already.
|
|
|
|
defer func() {
|
|
|
|
if stdinW != nil {
|
|
|
|
stdinW.Close()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Get a pipe to stdout so that we can get responses back
|
|
|
|
stdoutPipe, err := session.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
stdoutR := bufio.NewReader(stdoutPipe)
|
|
|
|
|
|
|
|
// Set stderr to a bytes buffer
|
|
|
|
stderr := new(bytes.Buffer)
|
|
|
|
session.Stderr = stderr
|
|
|
|
|
|
|
|
// Start the sink mode on the other side
|
|
|
|
// TODO(mitchellh): There are probably issues with shell escaping the path
|
2013-09-05 20:22:37 -04:00
|
|
|
log.Println("Starting remote scp process: ", scpCommand)
|
2013-08-23 22:52:02 -04:00
|
|
|
if err := session.Start(scpCommand); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2013-09-05 22:55:09 -04:00
|
|
|
// Call our callback that executes in the context of SCP. We ignore
|
|
|
|
// EOF errors if they occur because it usually means that SCP prematurely
|
|
|
|
// ended on the other side.
|
2013-08-23 22:52:02 -04:00
|
|
|
log.Println("Started SCP session, beginning transfers...")
|
2013-09-05 22:55:09 -04:00
|
|
|
if err := f(stdinW, stdoutR); err != nil && err != io.EOF {
|
2013-08-23 22:52:02 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close the stdin, which sends an EOF, and then set w to nil so that
|
|
|
|
// our defer func doesn't close it again since that is unsafe with
|
|
|
|
// the Go SSH package.
|
|
|
|
log.Println("SCP session complete, closing stdin pipe.")
|
|
|
|
stdinW.Close()
|
|
|
|
stdinW = nil
|
|
|
|
|
|
|
|
// Wait for the SCP connection to close, meaning it has consumed all
|
|
|
|
// our data and has completed. Or has errored.
|
|
|
|
log.Println("Waiting for SSH session to complete.")
|
|
|
|
err = session.Wait()
|
|
|
|
if err != nil {
|
|
|
|
if exitErr, ok := err.(*ssh.ExitError); ok {
|
|
|
|
// Otherwise, we have an ExitErorr, meaning we can just read
|
|
|
|
// the exit status
|
|
|
|
log.Printf("non-zero exit status: %d", exitErr.ExitStatus())
|
|
|
|
|
|
|
|
// If we exited with status 127, it means SCP isn't available.
|
|
|
|
// Return a more descriptive error for that.
|
|
|
|
if exitErr.ExitStatus() == 127 {
|
|
|
|
return errors.New(
|
|
|
|
"SCP failed to start. This usually means that SCP is not\n" +
|
|
|
|
"properly installed on the remote system.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("scp stderr (length %d): %s", stderr.Len(), stderr.String())
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-07-19 14:16:39 -04:00
|
|
|
// checkSCPStatus checks that a prior command sent to SCP completed
|
|
|
|
// successfully. If it did not complete successfully, an error will
|
|
|
|
// be returned.
|
|
|
|
func checkSCPStatus(r *bufio.Reader) error {
|
|
|
|
code, err := r.ReadByte()
|
2013-07-17 21:15:42 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2013-07-19 14:16:39 -04:00
|
|
|
|
|
|
|
if code != 0 {
|
2013-07-17 21:15:42 -04:00
|
|
|
// Treat any non-zero (really 1 and 2) as fatal errors
|
2013-07-19 14:16:39 -04:00
|
|
|
message, _, err := r.ReadLine()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error reading error message: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return errors.New(string(message))
|
2013-07-17 21:15:42 -04:00
|
|
|
}
|
2013-07-19 14:16:39 -04:00
|
|
|
|
2013-07-17 21:15:42 -04:00
|
|
|
return nil
|
|
|
|
}
|
2013-08-24 20:14:15 -04:00
|
|
|
|
2015-11-02 06:22:52 -05:00
|
|
|
func scpDownloadFile(dst string, src io.Reader, size int64, mode os.FileMode) error {
|
|
|
|
f, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
if _, err := io.CopyN(f, src, size); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-05-10 00:03:35 -04:00
|
|
|
func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, fi *os.FileInfo) error {
|
|
|
|
var mode os.FileMode
|
|
|
|
var size int64
|
2013-08-24 20:14:15 -04:00
|
|
|
|
2014-12-15 22:11:28 -05:00
|
|
|
if fi != nil && (*fi).Mode().IsRegular() {
|
2014-05-10 00:03:35 -04:00
|
|
|
mode = (*fi).Mode().Perm()
|
|
|
|
size = (*fi).Size()
|
|
|
|
} else {
|
2014-09-10 17:16:24 -04:00
|
|
|
// Create a temporary file where we can copy the contents of the src
|
|
|
|
// so that we can determine the length, since SCP is length-prefixed.
|
|
|
|
tf, err := ioutil.TempFile("", "packer-upload")
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error creating temporary file for upload: %s", err)
|
|
|
|
}
|
|
|
|
defer os.Remove(tf.Name())
|
|
|
|
defer tf.Close()
|
|
|
|
|
2014-05-10 00:03:35 -04:00
|
|
|
mode = 0644
|
2013-11-02 04:07:45 -04:00
|
|
|
|
2014-05-10 00:03:35 -04:00
|
|
|
log.Println("Copying input data into temporary file so we can read the length")
|
|
|
|
if _, err := io.Copy(tf, src); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2013-11-02 04:07:45 -04:00
|
|
|
|
2014-05-10 00:03:35 -04:00
|
|
|
// Sync the file so that the contents are definitely on disk, then
|
|
|
|
// read the length of it.
|
|
|
|
if err := tf.Sync(); err != nil {
|
|
|
|
return fmt.Errorf("Error creating temporary file for upload: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Seek the file to the beginning so we can re-read all of it
|
|
|
|
if _, err := tf.Seek(0, 0); err != nil {
|
|
|
|
return fmt.Errorf("Error creating temporary file for upload: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
tfi, err := tf.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error creating temporary file for upload: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
size = tfi.Size()
|
2014-09-10 17:16:24 -04:00
|
|
|
src = tf
|
2013-11-02 04:07:45 -04:00
|
|
|
}
|
|
|
|
|
2013-08-24 20:14:15 -04:00
|
|
|
// Start the protocol
|
2014-05-10 00:03:35 -04:00
|
|
|
perms := fmt.Sprintf("C%04o", mode)
|
2015-07-26 19:39:56 -04:00
|
|
|
log.Printf("[DEBUG] scp: Uploading %s: perms=%s size=%d", dst, perms, size)
|
2014-05-10 00:03:35 -04:00
|
|
|
|
|
|
|
fmt.Fprintln(w, perms, size, dst)
|
2013-11-02 04:07:45 -04:00
|
|
|
if err := checkSCPStatus(r); err != nil {
|
2013-08-24 20:14:15 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2014-09-10 17:16:24 -04:00
|
|
|
if _, err := io.CopyN(w, src, size); err != nil {
|
2013-08-24 20:14:15 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprint(w, "\x00")
|
2013-11-02 04:07:45 -04:00
|
|
|
if err := checkSCPStatus(r); err != nil {
|
2013-08-24 20:14:15 -04:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-05-10 00:03:35 -04:00
|
|
|
func scpUploadDirProtocol(name string, w io.Writer, r *bufio.Reader, f func() error, fi os.FileInfo) error {
|
2013-08-25 23:47:10 -04:00
|
|
|
log.Printf("SCP: starting directory upload: %s", name)
|
2014-05-10 00:03:35 -04:00
|
|
|
|
|
|
|
mode := fi.Mode().Perm()
|
|
|
|
|
|
|
|
perms := fmt.Sprintf("D%04o 0", mode)
|
|
|
|
|
|
|
|
fmt.Fprintln(w, perms, name)
|
2013-08-25 23:47:10 -04:00
|
|
|
err := checkSCPStatus(r)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := f(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprintln(w, "E")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-08-24 20:14:15 -04:00
|
|
|
func scpUploadDir(root string, fs []os.FileInfo, w io.Writer, r *bufio.Reader) error {
|
|
|
|
for _, fi := range fs {
|
2013-08-25 23:29:50 -04:00
|
|
|
realPath := filepath.Join(root, fi.Name())
|
|
|
|
|
2013-09-25 04:42:49 -04:00
|
|
|
// Track if this is actually a symlink to a directory. If it is
|
|
|
|
// a symlink to a file we don't do any special behavior because uploading
|
|
|
|
// a file just works. If it is a directory, we need to know so we
|
|
|
|
// treat it as such.
|
|
|
|
isSymlinkToDir := false
|
2013-09-30 14:39:52 -04:00
|
|
|
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
|
2013-09-25 04:42:49 -04:00
|
|
|
symPath, err := filepath.EvalSymlinks(realPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
symFi, err := os.Lstat(symPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
isSymlinkToDir = symFi.IsDir()
|
|
|
|
}
|
|
|
|
|
|
|
|
if !fi.IsDir() && !isSymlinkToDir {
|
|
|
|
// It is a regular file (or symlink to a file), just upload it
|
2013-08-25 23:29:50 -04:00
|
|
|
f, err := os.Open(realPath)
|
2013-08-24 20:14:15 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = func() error {
|
|
|
|
defer f.Close()
|
2014-05-10 00:03:35 -04:00
|
|
|
return scpUploadFile(fi.Name(), f, w, r, &fi)
|
2013-08-24 20:14:15 -04:00
|
|
|
}()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2013-08-25 23:29:50 -04:00
|
|
|
continue
|
|
|
|
}
|
2013-08-24 20:14:15 -04:00
|
|
|
|
2013-08-25 23:29:50 -04:00
|
|
|
// It is a directory, recursively upload
|
2013-08-25 23:47:10 -04:00
|
|
|
err := scpUploadDirProtocol(fi.Name(), w, r, func() error {
|
|
|
|
f, err := os.Open(realPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2013-08-25 23:29:50 -04:00
|
|
|
defer f.Close()
|
2013-08-24 20:14:15 -04:00
|
|
|
|
2013-08-25 23:29:50 -04:00
|
|
|
entries, err := f.Readdir(-1)
|
2013-08-24 20:14:15 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2013-08-25 23:29:50 -04:00
|
|
|
return scpUploadDir(realPath, entries, w, r)
|
2014-05-10 00:03:35 -04:00
|
|
|
}, fi)
|
2013-08-24 20:14:15 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2013-08-25 23:29:50 -04:00
|
|
|
|
|
|
|
return nil
|
2013-08-24 20:14:15 -04:00
|
|
|
}
|