-
Notifications
You must be signed in to change notification settings - Fork 8
/
agent.go
executable file
·101 lines (80 loc) · 1.83 KB
/
agent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// +build !windows
//Agent platform code for Linux and macOS
//Listens to a unix socket
package main
import (
"fmt"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/jawher/mow.cli"
)
var (
sshAgent *SshAgent
sockPath *string
sockDir string
noFork *bool
)
func SetupPlatformOpts(app *cli.Cli) {
app.Spec = app.Spec + "[-a][-n]"
sockPath = app.StringOpt("a address", "", "Bind to this socket address")
noFork = app.BoolOpt("n no-fork", false, "Do not fork in background, use this with systemd")
}
func RunAgent() {
//parse/create socket path
if *sockPath == "" {
//create socket path
sockDir, err := ioutil.TempDir("/tmp", "moolticute-ssh-agent")
if err != nil {
log.Fatal(err)
}
*sockPath = sockDir + "/agent.sock"
}
if !*noFork {
args := append(os.Args[1:], "--no-fork", "--address="+*sockPath)
cmd := exec.Command(os.Args[0], args...)
cmd.Start()
echoSocket(*sockPath)
return
}
log.Println("Starting Moolticute SSH agent")
sshAgent = NewSshAgent()
l, err := net.Listen("unix", *sockPath)
if err != nil {
log.Fatal("listen error:", err)
}
//cleanly shutdown in case a signal has been received
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt, os.Kill, syscall.SIGTERM)
go func(c chan os.Signal) {
sig := <-c
fmt.Printf("Caught signal %s: shutting down.\n", sig)
// Stop listening and unlink the socket:
l.Close()
os.RemoveAll(sockDir) // clean up
os.Exit(0)
}(sigc)
echoSocket(*sockPath)
for {
fd, err := l.Accept()
if err != nil {
log.Fatal("accept error:", err)
}
go handleClient(fd)
}
}
func handleClient(fd net.Conn) {
for {
if err := sshAgent.ProcessRequest(fd); err != nil {
log.Println("Failed:", err)
break
}
}
}
func echoSocket(p string) {
fmt.Printf("SSH_AUTH_SOCK=%s; export SSH_AUTH_SOCK;\n", p)
}