github.com/puellanivis/breton@v0.2.16/lib/files/sftpfiles/agent.go (about)

     1  package sftpfiles
     2  
     3  import (
     4  	"net"
     5  	"os"
     6  
     7  	"golang.org/x/crypto/ssh/agent"
     8  )
     9  
    10  // Agent defines a connection to an ssh-agent through net.Conn.
    11  type Agent struct {
    12  	conn net.Conn
    13  	agent.Agent
    14  }
    15  
    16  // Close implements io.Closer
    17  func (a *Agent) Close() error {
    18  	return a.conn.Close()
    19  }
    20  
    21  // GetAgent looks up the SSH_AUTH_SOCK environment variable, and creates a connection to it.
    22  //
    23  // If SSH_AUTH_SOCK is not set, then this returns both a nil Agent, and a nil error,
    24  // as this is not an error condition.
    25  //
    26  // If SSH_AUTH_SOCK is set, any error attempting to connect to it will return an error, and a nil Agent.
    27  func GetAgent() (*Agent, error) {
    28  	sock := os.Getenv("SSH_AUTH_SOCK")
    29  	if sock == "" {
    30  		// No agent setup, so return no agent and not error.
    31  		return nil, nil
    32  	}
    33  
    34  	raddr, err := net.ResolveUnixAddr("unix", sock)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	conn, err := net.DialUnix("unix", nil, raddr)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	return &Agent{
    45  		conn:  conn,
    46  		Agent: agent.NewClient(conn),
    47  	}, nil
    48  }