-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdevices.go
409 lines (343 loc) · 10.4 KB
/
devices.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Devices, sets of devices, and connections.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
type Connection struct {
dev *Device
cmd *exec.Cmd
forwarded bool
}
type Device struct {
// Note that some fields in the JSON device database are ignored.
Serial string `json:"serial"`
ID string `json:"id"`
User string `json:"user"`
offset int
port int
Location string `json:"allocation"`
Comment string `json:"notes"`
parent *DeviceSet
tunnelCmd *exec.Cmd
Hidden bool `json:"hidden"`
mounted bool
}
type DeviceSet struct {
deviceList []*Device
devicesBySerial map[string]*Device
tunnelFinish chan *Device
connectionFinish chan *Connection
connections map[*Connection]bool
unlockHidden bool
}
func sshVerbose() string {
if config.Verbose {
return "-v"
}
return ""
}
func (dev *Device) getLoopbackAddr() string {
if config.UseLoopbackAddrs {
// Return a loopback address in the space 127.x.x.x using
// values 0..99 for the 3 trailing octets.
high := (dev.offset / 10000) % 100
mid := (dev.offset / 100) % 100
low := dev.offset % 100
return fmt.Sprintf("127.%d.%d.%d", high, mid, low)
} else {
return "localhost"
}
}
func (dev *Device) ConnectCommand(addForwards bool) []string {
forwards := ""
if addForwards {
if config.UseLoopbackAddrs {
forwards += strings.ReplaceAll(config.Forwards, "-L", fmt.Sprintf("-L%s:", dev.getLoopbackAddr()))
} else {
forwards = config.Forwards
}
vncPort := dev.port - config.PortOffset + 5900
vncForward := fmt.Sprintf("%s:%d", dev.getLoopbackAddr(), vncPort)
forwards += fmt.Sprintf(" -L%s:localhost:%d", vncForward, vncPort)
fmt.Printf("VNC server at %s\n", vncForward)
}
// Pass along AWS env vars, if set. Only implemented in Linux and macOS for now.
env_vars := ""
if runtime.GOOS == "linux" || runtime.GOOS == "darwin" {
for _, aws_var := range []string{"AWS_SECRET_ACCESS_KEY", "AWS_ACCESS_KEY_ID", "AWS_SESSION_TOKEN"} {
if value := os.Getenv(aws_var); value != "" {
env_vars += fmt.Sprintf(" %s=%s", aws_var, value)
}
}
}
// Pass along git user and email, if they can be ascertained.
gitArgs := strings.Fields("git config --global -l")
cmd := exec.Command(gitArgs[0], gitArgs[1:]...)
var outBuffer bytes.Buffer
cmd.Stdout = &outBuffer
err := cmd.Run()
if err == nil {
for _, line := range strings.Split(outBuffer.String(), "\n") {
if keyValue := strings.SplitN(strings.TrimSpace(line), "=", 2); len(keyValue) == 2 {
switch keyValue[0] {
case "user.email":
email := keyValue[1]
env_vars += fmt.Sprintf(" GIT_COMMITTER_EMAIL=%s", email)
env_vars += fmt.Sprintf(" GIT_AUTHOR_EMAIL=%s", email)
case "user.name":
name := strings.Replace(keyValue[1], " ", ".", -1)
env_vars += fmt.Sprintf(" GIT_COMMITTER_NAME=%s", name)
env_vars += fmt.Sprintf(" GIT_AUTHOR_NAME=%s", name)
}
}
}
}
// The ssh command should be the same across all platforms.
ssh_command := fmt.Sprintf("ssh -A %s -o StrictHostKeychecking=no -o UserKnownHostsFile=/dev/null -t -p %d %s %s@localhost %s bash -l",
config.sshOptions(), dev.port, forwards, dev.User, env_vars)
if config.Verbose {
fmt.Println(ssh_command)
}
// Always show sftp access method.
fmt.Printf("\nFor file transfers to device %s:\nsftp -o StrictHostKeychecking=no -o UserKnownHostsFile=/dev/null -P %d %s@localhost\n",
dev.Serial, dev.port, dev.User)
// And the ssh-copy-id command.
fmt.Printf("\nTo install your default pubkey on device %s:\nssh-copy-id -o StrictHostKeychecking=no -o UserKnownHostsFile=/dev/null -p %d %s@localhost\n\n", dev.Serial, dev.port, dev.User)
// Return os-specific command to connect to device.
if runtime.GOOS == "windows" {
return strings.Fields(fmt.Sprintf("cmd.exe /c start /wait %s", ssh_command))
} else if runtime.GOOS == "darwin" {
return darwinConnectCommand(ssh_command)
} else {
// Linux
if _, err := exec.LookPath("xterm"); err == nil {
return strings.Fields(fmt.Sprintf("xterm -title %s -e %s", dev.Serial, ssh_command))
} else {
return strings.Fields(fmt.Sprintf("gnome-terminal --disable-factory -- %s", ssh_command))
}
}
}
func (dev *Device) tunnelSetup() {
var err error
var sshTunnelKeyFile string
if dev.tunnelCmd != nil {
return
}
// If the key is on S3, make a temporary local copy, with deferred removal.
if strings.HasPrefix(config.TunnelKeyPath, "s3://") {
sshTunnelKeyFile = ".tunnel_key"
if err = s3Download(config.TunnelKeyPath, sshTunnelKeyFile); err != nil {
return
}
os.Chmod(sshTunnelKeyFile, 0600)
defer os.Remove(sshTunnelKeyFile)
} else {
sshTunnelKeyFile = config.TunnelKeyPath
}
tunnelArgs := strings.Fields(fmt.Sprintf("ssh -i %s %s -o StrictHostKeyChecking=accept-new -L%d:localhost:%d -N %s",
sshTunnelKeyFile, config.sshOptions(), dev.port, dev.port, config.TunnelNameAddr))
fmt.Println(tunnelArgs)
// Start the tunnel command.
dev.tunnelCmd = exec.Command(tunnelArgs[0], tunnelArgs[1:]...)
dev.tunnelCmd.Stderr = os.Stderr
if err = dev.tunnelCmd.Start(); err != nil {
fmt.Println(err)
dev.tunnelCmd = nil
return
}
go func() {
dev.tunnelCmd.Wait()
fmt.Println("tunnel exited")
dev.tunnelCmd = nil
}()
// Wait for tunnel port to be available.
for {
if conn, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", dev.port), 1*time.Second); err == nil {
// Tunnel ready and forwarding.
conn.Close()
break
}
if dev.tunnelCmd == nil {
// Tunnel exited for some reason.
break
}
time.Sleep(250 * time.Millisecond)
}
}
func (dev *Device) connect() {
var err error
dev.tunnelSetup()
if dev.tunnelCmd == nil {
return
}
// Test if the first forwarded port is already being listened on.
// If not, enable all the forwards.
firstForwardedPort := -1
re := regexp.MustCompile(`-L(\d+):`)
match := re.FindStringSubmatch(config.Forwards)
if len(match) >= 2 {
firstForwardedPort = atoi(match[1])
}
if firstForwardedPort != -1 {
testAddr := fmt.Sprintf("%s:%d", dev.getLoopbackAddr(), firstForwardedPort)
if conn, err := net.DialTimeout("tcp", testAddr, 1*time.Second); err == nil {
conn.Close()
firstForwardedPort = -1
fmt.Printf("*** %s already in use, not forwarding\n", testAddr)
} else {
fmt.Printf("+++ using %s forwards\n", dev.getLoopbackAddr())
}
}
if config.UseLoopbackAddrs {
if err = enableLoopbackAddr(dev.getLoopbackAddr()); err != nil {
fmt.Println(err)
return
}
}
addForwards := (firstForwardedPort != -1)
connectArgs := dev.ConnectCommand(addForwards)
cmd := exec.Command(connectArgs[0], connectArgs[1:]...)
if err = cmd.Start(); err != nil {
fmt.Println(err)
return
}
con := &Connection{dev, cmd, addForwards}
dev.parent.connections[con] = true
go func() {
cmd.Wait()
dev.parent.connectionFinish <- con
}()
}
// mount sets up an sshfs mount of the remote device filesystem to the local
// system.
func (dev *Device) mount() {
var err error
if runtime.GOOS == "windows" {
return
}
if dev.Hidden {
fmt.Println("sshfs not allowed on hidden devices")
return
}
if dev.mounted {
fmt.Println("already mounted")
return
}
dev.tunnelSetup()
if dev.tunnelCmd == nil {
return
}
mountArgs := strings.Fields(fmt.Sprintf("sshfs -f %s -o BatchMode=yes -o StrictHostKeychecking=no -o UserKnownHostsFile=/dev/null -o port=%d %s@%s:/",
config.sshOptions(), dev.port, dev.User, dev.getLoopbackAddr()))
mountPoint := fmt.Sprintf("%s/sshfs/%s", os.Getenv("HOME"), dev.Serial)
os.MkdirAll(mountPoint, 0700)
mountArgs = append(mountArgs, mountPoint)
fmt.Println(mountArgs)
cmd := exec.Command(mountArgs[0], mountArgs[1:]...)
var errBuffer bytes.Buffer
cmd.Stderr = &errBuffer
if err = cmd.Start(); err != nil {
fmt.Println(err)
return
}
con := &Connection{dev, cmd, false}
dev.parent.connections[con] = true
dev.mounted = true
go func() {
cmd.Wait()
dev.parent.connectionFinish <- con
dev.mounted = false
// Dump stderr for diagnostics.
fmt.Println(errBuffer.String())
if runtime.GOOS == "darwin" {
// Some extra cleanup is required.
exec.Command("diskutil", "umount", mountPoint).Run()
}
}()
}
func (dset *DeviceSet) add(d *Device) {
dset.deviceList = append(dset.deviceList, d)
dset.devicesBySerial[d.Serial] = d
}
func (dset *DeviceSet) list() {
fmt.Print("\nAvailable devices:\n")
fmt.Printf("serial, id, location, (comment)\n")
for _, device := range dset.deviceList {
if device.Hidden && !dset.unlockHidden {
continue
}
fmt.Printf("%s, %4d, %s, (%s)\n", device.Serial, device.offset, device.Location, device.Comment)
}
}
func (dset *DeviceSet) find(s string) *Device {
for _, device := range dset.deviceList {
if s == device.Serial || atoi(s) == device.offset {
if device.Hidden && !dset.unlockHidden {
return nil
} else {
return device
}
}
}
// If a tunnel port number with "!" was provided, create an anonymous device and return it.
if s[len(s)-1] == '!' {
if port, err := strconv.Atoi(s[0 : len(s)-1]); err == nil {
serial := fmt.Sprintf("anonymous-%d", port)
if device, ok := dset.devicesBySerial[serial]; ok {
return device
} else {
newDevice := &Device{Serial: serial,
offset: port - config.PortOffset,
port: port,
Location: "dev",
User: config.AnonUser,
Comment: fmt.Sprintf("anonymous device - port %d", port),
parent: dset}
dset.add(newDevice)
return newDevice
}
}
}
return nil
}
// Load device database, return a DeviceSet.
func loadDevices() *DeviceSet {
fmt.Printf("Device database: %s\n", config.DevicesPath)
if strings.HasPrefix(config.DevicesPath, "s3://") {
if result, err := s3Get(config.DevicesPath); err == nil {
device_database = string(result)
} else {
fmt.Printf("*** AWS: failed to get %s from S3\n", config.DevicesPath)
fmt.Println("*** AWS: Try refreshing your credentials and environment variables")
os.Exit(1)
}
}
dset := &DeviceSet{tunnelFinish: make(chan *Device), connectionFinish: make(chan *Connection),
devicesBySerial: make(map[string]*Device),
connections: make(map[*Connection]bool)}
var devices []*Device
err := json.Unmarshal([]byte(device_database), &devices)
if err != nil {
fmt.Println("Error parsing JSON:", err)
} else {
for _, d := range devices {
if d.ID != "" {
d.offset = atoi(d.ID)
d.port = d.offset + config.PortOffset
d.parent = dset
dset.add(d)
}
}
}
return dset
}