-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathconfig.go
249 lines (217 loc) · 5.5 KB
/
config.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
)
type config struct {
socketPath string
powershellPath string
pipeName string
format string
foreground bool
verbose bool
stop bool
logFile string
version bool
}
var version = "(development version)"
var logOutput io.Writer
func defaultSocketPath() string {
home, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
return filepath.Join(home, ".ssh", "wsl2-ssh-agent.sock")
}
func powershellPath() string {
path, err := exec.LookPath("powershell.exe")
if err != nil {
path := "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"
_, err := os.Stat(path)
if err == nil {
return path
} else {
return ""
}
}
return path
}
func newConfig() *config {
c := &config{}
flag.StringVar(&c.socketPath, "socket", defaultSocketPath(), "a path of UNIX domain socket to listen")
flag.StringVar(&c.powershellPath, "powershell-path", powershellPath(), "a path of Windows PowerShell")
flag.StringVar(&c.pipeName, "pipename", "openssh-ssh-agent", "a name of pipe to connect")
flag.BoolVar(&c.foreground, "foreground", false, "run in foreground mode")
flag.BoolVar(&c.verbose, "verbose", false, "verbose mode")
flag.StringVar(&c.logFile, "log", "", "a file path to write the log")
flag.StringVar(&c.format, "format", "auto", "an output format: auto, bash, zsh, csh, tcsh, or fish")
flag.BoolVar(&c.stop, "stop", false, "stop the daemon and exit")
flag.BoolVar(&c.version, "version", false, "print version and exit")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "usage: wsl2-ssh-agent\n")
flag.PrintDefaults()
}
flag.Parse()
if c.powershellPath == "" {
fmt.Fprintln(os.Stderr, "powershell.exe not found, use the -powershell-path to customize the path.")
os.Exit(1)
}
return c
}
func getOutputFormat(format string) string {
if format == "auto" {
shell := os.Getenv("SHELL")
if strings.HasSuffix(shell, "fish") {
format = "fish"
} else if strings.HasSuffix(shell, "csh") {
format = "csh"
} else {
format = "sh"
}
}
switch format {
case "sh", "bash", "zsh":
return "SSH_AUTH_SOCK=%s; export SSH_AUTH_SOCK;"
case "csh", "tcsh":
return "setenv SSH_AUTH_SOCK %s"
case "fish":
return "set -x SSH_AUTH_SOCK %s"
default:
fmt.Printf("output format must be auto, bash, zsh, csh, tcsh, or fish\n")
os.Exit(1)
return ""
}
}
func (c *config) start() context.Context {
if c.version {
fmt.Printf("wsl2-ssh-agent %s\n", version)
os.Exit(0)
}
// check if this process is a child or not
parent := checkDaemonMode()
// script output
output := fmt.Sprintf(getOutputFormat(c.format), c.socketPath)
// set up the log file
c.setupLogFile()
// check if wsl2-ssl-agent is already running
serverPid := findRunningServerPid(c.socketPath)
// --stop option
if c.stop {
if serverPid == -1 {
log.Fatal(fmt.Errorf("failed to find wsl2-ssh-agent"))
}
log.Printf("kill wsl2-ssh-agent (pid: %d)", serverPid)
stopService(serverPid)
os.Exit(0)
}
// avoid multiple start
if serverPid != -1 {
log.Printf("wsl2-ssh-agent (pid: %d) is already running; exit", serverPid)
fmt.Println(output)
os.Exit(0)
}
// daemonize
if !c.foreground {
if parent {
log.Printf("daemonize: start")
args := []string{"-socket", c.socketPath}
if c.logFile != "" {
args = append(args, "-log", c.logFile)
}
startDaemonizing(args...)
} else {
completeDaemonizing(output)
log.Printf("daemonize: completed")
}
}
// set up signal handlers
signal.Ignore(syscall.SIGPIPE)
ctx, _ := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
return ctx
}
func (c *config) setupLogFile() {
var logFile *os.File
if c.logFile != "" {
f, err := os.OpenFile(c.logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(fmt.Errorf("failed to open a log file: %s", err))
}
logFile = f
}
if logFile != nil {
if c.verbose {
logOutput = io.MultiWriter(logFile, os.Stdout)
} else {
logOutput = logFile
}
} else {
if c.verbose {
logOutput = os.Stdout
} else {
logOutput = io.Discard
}
}
log.SetOutput(logOutput)
log.SetPrefix("[L] ")
}
// find the existing server by getsockopt
func findRunningServerPid(path string) int {
// try to connect to the existing server via UNIX domain socket
conn, err := net.Dial("unix", path)
if err != nil {
// failed to connect
if errors.Is(err, syscall.ENOENT) {
// no UNIX domain socket; cannot find the server
return -1
}
if errors.Is(err, syscall.ECONNREFUSED) {
// presumably the existing server has already aborted;
// remove the UNIX domain socket
err = os.Remove(path)
if err != nil {
log.Fatal(fmt.Errorf("failed to remove %s: %s", path, err))
}
return -1
}
log.Fatal(fmt.Errorf("failed to connect to %s: %s", path, err))
}
// connected
defer conn.Close()
// identify the pid of the existing server
file, err := conn.(*net.UnixConn).File()
if err != nil {
log.Fatal(err)
}
defer file.Close()
cred, err := syscall.GetsockoptUcred(int(file.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
if err != nil {
log.Fatal(err)
}
return int(cred.Pid)
}
// stop the running server
func stopService(pid int) {
process, err := os.FindProcess(pid)
if err != nil {
log.Fatal(err)
}
err = process.Signal(syscall.SIGTERM)
if err != nil {
log.Fatal(err)
}
_, err = process.Wait()
if err != nil {
log.Fatal(err)
}
}