Uh oh!
There was an error while loading. Please reload this page.
This repository was archived by the owner on Jan 17, 2021. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathsshcode.go
More file actions
Latest commit
653 lines (562 loc) · 17.4 KB
/
Copy pathsshcode.go
File metadata and controls
653 lines (562 loc) · 17.4 KB
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
package main
import (
"context"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/pkg/browser"
"go.coder.com/flog"
"golang.org/x/xerrors"
)
constcodeServerPath="~/.cache/sshcode/sshcode-server"
const (
sshDirectory="~/.ssh"
sshDirectoryUnsafeModeMask=0022
sshControlPath=sshDirectory+"/control-%h-%p-%r"
)
typeoptionsstruct {
skipSyncbool
syncBackbool
noOpenbool
reuseConnectionbool
bindAddrstring
remotePortstring
sshFlagsstring
uploadCodeServerstring
}
funcsshCode(host, dirstring, ooptions) error {
host, extraSSHFlags, err:=parseHost(host)
iferr!=nil {
returnxerrors.Errorf("failed to parse host IP: %w", err)
}
ifextraSSHFlags!="" {
o.sshFlags=strings.Join([]string{extraSSHFlags, o.sshFlags}, " ")
}
o.bindAddr, err=parseBindAddr(o.bindAddr)
iferr!=nil {
returnxerrors.Errorf("failed to parse bind address: %w", err)
}
ifo.remotePort=="" {
o.remotePort, err=randomPort()
}
iferr!=nil {
returnxerrors.Errorf("failed to find available remote port: %w", err)
}
// Check the SSH directory's permissions and warn the user if it is not safe.
o.reuseConnection=checkSSHDirectory(sshDirectory, o.reuseConnection)
// Start SSH master connection socket. This prevents multiple password prompts from appearing as authentication
// only happens on the initial connection.
ifo.reuseConnection {
flog.Info("starting SSH master connection...")
newSSHFlags, cancel, err:=startSSHMaster(o.sshFlags, sshControlPath, host)
defercancel()
iferr!=nil {
flog.Error("failed to start SSH master connection: %v", err)
o.reuseConnection=false
} else {
o.sshFlags=newSSHFlags
}
}
// Upload local code-server or download code-server from CI server.
ifo.uploadCodeServer!="" {
flog.Info("uploading local code-server binary...")
err=copyCodeServerBinary(o.sshFlags, host, o.uploadCodeServer, codeServerPath)
iferr!=nil {
returnxerrors.Errorf("failed to upload local code-server binary to remote server: %w", err)
}
sshCmdStr:=
fmt.Sprintf("ssh %v %v 'chmod +x %v'",
o.sshFlags, host, codeServerPath,
)
sshCmd:=exec.Command("sh", "-l", "-c", sshCmdStr)
sshCmd.Stdout=os.Stdout
sshCmd.Stderr=os.Stderr
err=sshCmd.Run()
iferr!=nil {
returnxerrors.Errorf("failed to make code-server binary executable:\n---ssh cmd---\n%s: %w",
sshCmdStr,
err,
)
}
} else {
flog.Info("ensuring code-server is updated...")
dlScript:=downloadScript(codeServerPath)
// Downloads the latest code-server and allows it to be executed.
sshCmdStr:=fmt.Sprintf("ssh %v %v '/usr/bin/env bash -l'", o.sshFlags, host)
sshCmd:=exec.Command("sh", "-l", "-c", sshCmdStr)
sshCmd.Stdout=os.Stdout
sshCmd.Stderr=os.Stderr
sshCmd.Stdin=strings.NewReader(dlScript)
err=sshCmd.Run()
iferr!=nil {
returnxerrors.Errorf("failed to update code-server:\n---ssh cmd---\n%s"+
"\n---download script---\n%s: %w",
sshCmdStr,
dlScript,
err,
)
}
}
if!o.skipSync {
start:=time.Now()
flog.Info("syncing settings")
err=syncUserSettings(o.sshFlags, host, false)
iferr!=nil {
returnxerrors.Errorf("failed to sync settings: %w", err)
}
flog.Info("synced settings in %s", time.Since(start))
flog.Info("syncing extensions")
err=syncExtensions(o.sshFlags, host, false)
iferr!=nil {
returnxerrors.Errorf("failed to sync extensions: %w", err)
}
flog.Info("synced extensions in %s", time.Since(start))
}
flog.Info("starting code-server...")
flog.Info("Tunneling remote port %v to %v", o.remotePort, o.bindAddr)
sshCmdStr:=
fmt.Sprintf("ssh -tt -q -L %v:localhost:%v %v %v '%v %v --host 127.0.0.1 --auth none --port=%v'",
o.bindAddr, o.remotePort, o.sshFlags, host, codeServerPath, dir, o.remotePort,
)
// Starts code-server and forwards the remote port.
sshCmd:=exec.Command("sh", "-l", "-c", sshCmdStr)
sshCmd.Stdin=os.Stdin
sshCmd.Stdout=os.Stdout
sshCmd.Stderr=os.Stderr
err=sshCmd.Start()
iferr!=nil {
returnxerrors.Errorf("failed to start code-server: %w", err)
}
url:=fmt.Sprintf("http://%s", o.bindAddr)
ctx, cancel:=context.WithTimeout(context.Background(), 15*time.Second)
defercancel()
client:= http.Client{
Timeout: time.Second*3,
}
for {
ifctx.Err() !=nil {
returnxerrors.Errorf("code-server didn't start in time: %w", ctx.Err())
}
// Waits for code-server to be available before opening the browser.
resp, err:=client.Get(url)
iferr!=nil {
continue
}
resp.Body.Close()
break
}
ctx, cancel=context.WithCancel(context.Background())
if!o.noOpen {
openBrowser(url)
}
gofunc() {
defercancel()
sshCmd.Wait()
}()
c:=make(chan os.Signal)
signal.Notify(c, os.Interrupt)
select {
case<-ctx.Done():
case<-c:
}
flog.Info("shutting down")
if!o.syncBack||o.skipSync {
returnnil
}
flog.Info("synchronizing VS Code back to local")
err=syncExtensions(o.sshFlags, host, true)
iferr!=nil {
returnxerrors.Errorf("failed to sync extensions back: %w", err)
}
err=syncUserSettings(o.sshFlags, host, true)
iferr!=nil {
returnxerrors.Errorf("failed to sync user settings back: %w", err)
}
returnnil
}
// expandPath returns an expanded version of path.
funcexpandPath(pathstring) string {
path=filepath.Clean(os.ExpandEnv(path))
// Replace tilde notation in path with the home directory. You can't replace the first instance of `~` in the
// string with the homedir as having a tilde in the middle of a filename is valid.
homedir:=os.Getenv("HOME")
ifhomedir!="" {
ifpath=="~" {
path=homedir
} elseifstrings.HasPrefix(path, "~/") {
path=filepath.Join(homedir, path[2:])
}
}
returnfilepath.Clean(path)
}
funcparseBindAddr(bindAddrstring) (string, error) {
if!strings.Contains(bindAddr, ":") {
bindAddr+=":"
}
host, port, err:=net.SplitHostPort(bindAddr)
iferr!=nil {
return"", err
}
ifhost=="" {
host="127.0.0.1"
}
ifport=="" {
port, err=randomPort()
}
iferr!=nil {
return"", err
}
returnnet.JoinHostPort(host, port), nil
}
funcopenBrowser(urlstring) {
varopenCmd*exec.Cmd
const (
macPath="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
wslPath="/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"
winPath="C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
)
switch {
casecommandExists("chrome"):
openCmd=exec.Command("chrome", chromeOptions(url)...)
casecommandExists("google-chrome"):
openCmd=exec.Command("google-chrome", chromeOptions(url)...)
casecommandExists("google-chrome-stable"):
openCmd=exec.Command("google-chrome-stable", chromeOptions(url)...)
casecommandExists("chromium"):
openCmd=exec.Command("chromium", chromeOptions(url)...)
casecommandExists("chromium-browser"):
openCmd=exec.Command("chromium-browser", chromeOptions(url)...)
casepathExists(macPath):
openCmd=exec.Command(macPath, chromeOptions(url)...)
casepathExists(wslPath):
openCmd=exec.Command(wslPath, chromeOptions(url)...)
casepathExists(winPath):
openCmd=exec.Command(winPath, chromeOptions(url)...)
default:
err:=browser.OpenURL(url)
iferr!=nil {
flog.Error("failed to open browser: %v", err)
}
return
}
// We do not use CombinedOutput because if there is no chrome instance, this will block
// and become the parent process instead of using an existing chrome instance.
err:=openCmd.Start()
iferr!=nil {
flog.Error("failed to open browser: %v", err)
}
}
funcchromeOptions(urlstring) []string {
return []string{"--app="+url, "--disable-extensions", "--disable-plugins", "--incognito"}
}
// Checks if a command exists locally.
funccommandExists(namestring) bool {
_, err:=exec.LookPath(name)
returnerr==nil
}
funcpathExists(namestring) bool {
_, err:=os.Stat(name)
returnerr==nil
}
// randomPort picks a random port to start code-server on.
funcrandomPort() (string, error) {
const (
minPort=1024
maxPort=65535
maxTries=10
)
fori:=0; i<maxTries; i++ {
port:=rand.Intn(maxPort-minPort+1) +minPort
l, err:=net.Listen("tcp", fmt.Sprintf(":%d", port))
iferr==nil {
_=l.Close()
returnstrconv.Itoa(port), nil
}
flog.Info("port taken: %d", port)
}
return"", xerrors.Errorf("max number of tries exceeded: %d", maxTries)
}
// checkSSHDirectory performs sanity and safety checks on sshDirectory, and
// returns a new value for o.reuseConnection depending on the checks.
funccheckSSHDirectory(sshDirectorystring, reuseConnectionbool) bool {
ifruntime.GOOS=="windows" {
flog.Info("OS is windows, disabling connection reuse feature")
returnfalse
}
sshDirectoryMode, err:=os.Lstat(expandPath(sshDirectory))
iferr!=nil {
ifreuseConnection {
flog.Info("failed to stat %v directory, disabling connection reuse feature: %v", sshDirectory, err)
}
reuseConnection=false
} else {
if!sshDirectoryMode.IsDir() {
ifreuseConnection {
flog.Info("%v is not a directory, disabling connection reuse feature", sshDirectory)
} else {
flog.Info("warning: %v is not a directory", sshDirectory)
}
reuseConnection=false
}
ifsshDirectoryMode.Mode().Perm()&sshDirectoryUnsafeModeMask!=0 {
flog.Info("warning: the %v directory has unsafe permissions, they should only be writable by "+
"the owner (and files inside should be set to 0600)", sshDirectory)
}
}
returnreuseConnection
}
// startSSHMaster starts an SSH master connection and waits for it to be ready.
// It returns a new set of SSH flags for child SSH processes to use.
funcstartSSHMaster(sshFlagsstring, sshControlPathstring, hoststring) (string, func(), error) {
ctx, cancel:=context.WithCancel(context.Background())
newSSHFlags:=fmt.Sprintf(`%v -o "ControlPath=%v"`, sshFlags, sshControlPath)
// -MN means "start a master socket and don't open a session, just connect".
sshCmdStr:=fmt.Sprintf(`exec ssh %v -MNq %v`, newSSHFlags, host)
sshMasterCmd:=exec.CommandContext(ctx, "sh", "-c", sshCmdStr)
sshMasterCmd.Stdin=os.Stdin
sshMasterCmd.Stderr=os.Stderr
// Gracefully stop the SSH master.
stopSSHMaster:=func() {
ifsshMasterCmd.Process!=nil {
ifsshMasterCmd.ProcessState!=nil&&sshMasterCmd.ProcessState.Exited() {
return
}
err:=sshMasterCmd.Process.Signal(syscall.SIGTERM)
iferr!=nil {
flog.Error("failed to send SIGTERM to SSH master process: %v", err)
}
}
cancel()
}
// Start ssh master and wait. Waiting prevents the process from becoming a zombie process if it dies before
// sshcode does, and allows sshMasterCmd.ProcessState to be populated.
err:=sshMasterCmd.Start()
gosshMasterCmd.Wait()
iferr!=nil {
return"", stopSSHMaster, err
}
err=checkSSHMaster(sshMasterCmd, newSSHFlags, host)
iferr!=nil {
stopSSHMaster()
return"", stopSSHMaster, xerrors.Errorf("SSH master wasn't ready on time: %w", err)
}
returnnewSSHFlags, stopSSHMaster, nil
}
// checkSSHMaster polls every second for 30 seconds to check if the SSH master
// is ready.
funccheckSSHMaster(sshMasterCmd*exec.Cmd, sshFlagsstring, hoststring) error {
var (
maxTries=30
sleepDur=time.Second
errerror
)
fori:=0; i<maxTries; i++ {
// Check if the master is running.
ifsshMasterCmd.Process==nil|| (sshMasterCmd.ProcessState!=nil&&sshMasterCmd.ProcessState.Exited()) {
returnxerrors.Errorf("SSH master process is not running")
}
// Check if it's ready.
sshCmdStr:=fmt.Sprintf(`ssh %v -O check %v`, sshFlags, host)
sshCmd:=exec.Command("sh", "-c", sshCmdStr)
err=sshCmd.Run()
iferr==nil {
returnnil
}
time.Sleep(sleepDur)
}
returnxerrors.Errorf("max number of tries exceeded: %d", maxTries)
}
// copyCodeServerBinary copies a code-server binary from local to remote.
funccopyCodeServerBinary(sshFlagsstring, hoststring, localPathstring, remotePathstring) error {
iferr:=validateIsFile(localPath); err!=nil {
returnerr
}
var (
src=localPath
dest=host+":"+remotePath
)
returnrsync(src, dest, sshFlags)
}
funcsyncUserSettings(sshFlagsstring, hoststring, backbool) error {
localConfDir, err:=configDir()
iferr!=nil {
returnerr
}
err=ensureDir(localConfDir)
iferr!=nil {
returnerr
}
varremoteSettingsDir="~/.local/share/code-server/User/"
ifruntime.GOOS=="windows" {
remoteSettingsDir=".local/share/code-server/User/"
}
var (
src=localConfDir+"/"
dest=host+":"+remoteSettingsDir
)
ifback {
dest, src=src, dest
}
// Append "/" to have rsync copy the contents of the dir.
returnrsync(src, dest, sshFlags, "workspaceStorage", "logs", "CachedData")
}
funcsyncExtensions(sshFlagsstring, hoststring, backbool) error {
localExtensionsDir, err:=extensionsDir()
iferr!=nil {
returnerr
}
err=ensureDir(localExtensionsDir)
iferr!=nil {
returnerr
}
varremoteExtensionsDir="~/.local/share/code-server/extensions/"
ifruntime.GOOS=="windows" {
remoteExtensionsDir=".local/share/code-server/extensions/"
}
var (
src=localExtensionsDir+"/"
dest=host+":"+remoteExtensionsDir
)
ifback {
dest, src=src, dest
}
returnrsync(src, dest, sshFlags)
}
funcrsync(srcstring, deststring, sshFlagsstring, excludePaths...string) error {
excludeFlags:=make([]string, len(excludePaths))
fori, path:=rangeexcludePaths {
excludeFlags[i] ="--exclude="+path
}
cmd:=exec.Command("rsync", append(excludeFlags, "-azvr",
"-e", "ssh "+sshFlags,
// Only update newer directories, and sync times
// to keep things simple.
"-u", "--times",
// This is more unsafe, but it's obnoxious having to enter VS Code
// locally in order to properly delete an extension.
"--delete",
"--copy-unsafe-links",
"-zz",
src, dest,
)...,
)
cmd.Stdout=os.Stdout
cmd.Stderr=os.Stderr
err:=cmd.Run()
iferr!=nil {
returnxerrors.Errorf("failed to rsync '%s' to '%s': %w", src, dest, err)
}
returnnil
}
funcdownloadScript(codeServerPathstring) string {
returnfmt.Sprintf(
`set -euxo pipefail || exit 1
[ "$(uname -m)" != "x86_64" ] && echo "Unsupported server architecture $(uname -m). code-server only has releases for x86_64 systems." && exit 1
pkill -f %v || true
mkdir -p $HOME/.local/share/code-server %v
cd %v
curlflags="-o latest-linux"
if [ -f latest-linux ]; then
curlflags="$curlflags -z latest-linux"
fi
curl $curlflags https://codesrv-ci.cdr.sh/latest-linux
[ -f %v ] && rm %v
ln latest-linux %v
chmod +x %v`,
codeServerPath,
filepath.ToSlash(filepath.Dir(codeServerPath)),
filepath.ToSlash(filepath.Dir(codeServerPath)),
codeServerPath,
codeServerPath,
codeServerPath,
codeServerPath,
)
}
// ensureDir creates a directory if it does not exist.
funcensureDir(pathstring) error {
_, err:=os.Stat(path)
ifos.IsNotExist(err) {
// This fixes a issue where Go reads `/c/` as `C:\c\` and creates
// empty directories on the client that don't need to exist.
ifruntime.GOOS=="windows"&&strings.HasPrefix(path, "/c/") {
path="C:"+path[2:]
}
err=os.MkdirAll(path, 0750)
}
iferr!=nil {
returnerr
}
returnnil
}
// validateIsFile tries to stat the specified path and ensure it's a file.
funcvalidateIsFile(pathstring) error {
info, err:=os.Stat(path)
iferr!=nil {
returnerr
}
ifinfo.IsDir() {
returnxerrors.New("path is a directory")
}
returnnil
}
// parseHost parses the host argument. If 'gcp:' is prefixed to the
// host then a lookup is done using gcloud to determine the external IP and any
// additional SSH arguments that should be used for ssh commands. Otherwise, host
// is returned.
funcparseHost(hoststring) (parsedHoststring, additionalFlagsstring, errerror) {
host=strings.TrimSpace(host)
switch {
casestrings.HasPrefix(host, "gcp:"):
instance:=strings.TrimPrefix(host, "gcp:")
returnparseGCPSSHCmd(instance)
default:
returnhost, "", nil
}
}
// parseGCPSSHCmd parses the IP address and flags used by 'gcloud' when
// ssh'ing to an instance.
funcparseGCPSSHCmd(instancestring) (ip, sshFlagsstring, errerror) {
dryRunCmd:=fmt.Sprintf("gcloud compute ssh --dry-run %v", instance)
out, err:=exec.Command("sh", "-l", "-c", dryRunCmd).CombinedOutput()
iferr!=nil {
return"", "", xerrors.Errorf("%s: %w", out, err)
}
toks:=strings.Split(string(out), " ")
iflen(toks) <2 {
return"", "", xerrors.Errorf("unexpected output for '%v' command, %s", dryRunCmd, out)
}
// Slice off the '/usr/bin/ssh' prefix and the '<user>@<ip>' suffix.
sshFlags=strings.Join(toks[1:len(toks)-1], " ")
// E.g. foo@1.2.3.4.
userIP:=toks[len(toks)-1]
returnstrings.TrimSpace(userIP), sshFlags, nil
}
// gitbashWindowsDir strips a the msys2 install directory from the beginning of
// the path. On msys2, if a user provides `/workspace` sshcode will receive
// `C:/msys64/workspace` which won't work on the remote host.
funcgitbashWindowsDir(dirstring) string {
// Don't bother figuring out path if it's relative to home dir.
ifstrings.HasPrefix(dir, "~/") {
ifdir=="~" {
return"~/"
}
returndir
}
mingwPrefix, err:=exec.Command("sh", "-c", "{ cd / && pwd -W; }").Output()
iferr!=nil {
// Default to a sane location.
mingwPrefix= []byte("C:/mingw64")
}
prefix:=strings.TrimSuffix(string(mingwPrefix), "/\n")
returnstrings.TrimPrefix(dir, prefix)
}