-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh.go
More file actions
418 lines (347 loc) · 9.86 KB
/
Copy pathssh.go
File metadata and controls
418 lines (347 loc) · 9.86 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
package main
import (
"bufio"
"encoding/base64"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
func isPortNumber(s string) bool {
if s == "" {
return false
}
// Check all characters are digits
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
// Parse and validate range (1-65535)
port, err := strconv.ParseUint(s, 10, 16)
if err != nil || port < 1 || port > 65535 {
return false
}
return true
}
func parseSSHTarget(input string) (user, host, port, file string) {
// If input doesn't contain ':', it's a local file
if !strings.Contains(input, ":") {
return "", "", "", input
}
// Split the input by '@' to handle the optional user component
parts := strings.SplitN(input, "@", 2)
if len(parts) == 2 {
user = parts[0]
input = parts[1]
}
// Split by ':' - could be host:port:/path or host:/path or host:port:path (for Windows)
parts = strings.SplitN(input, ":", 3)
if len(parts) < 2 {
Err("invalid format: %s\n", input)
return
}
host = parts[0]
// Check if middle part is a numeric port (format: host:port:/path)
if len(parts) == 3 && isPortNumber(parts[1]) {
port = parts[1]
file = parts[2]
} else {
// No port: host:/path
file = parts[1]
}
return user, host, port, file
}
func waitForReady(stdout io.ReadCloser, isLocal bool) error {
Log("waiting for server..\n")
scanner := bufio.NewScanner(stdout)
ready := false
for scanner.Scan() {
line := scanner.Text()
Log("server-> %s\n", line)
if strings.Contains(line, "READY") {
ready = true
serverType := "remote"
if isLocal {
serverType = "local"
}
Log("%s server is ready\n", serverType)
break
}
}
if err := scanner.Err(); err != nil {
return err
}
if !ready {
return fmt.Errorf("server exited before signalling readiness")
}
return nil
}
func shellQuote(value string) string {
return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"
}
func remoteBinaryCommand(remotePath string, args []string) string {
quotedArgs := make([]string, 0, len(args)+1)
quotedArgs = append(quotedArgs, shellQuote(remotePath))
for _, arg := range args {
quotedArgs = append(quotedArgs, shellQuote(arg))
}
cleanup := "rm -f -- " + shellQuote(remotePath)
return "trap " + shellQuote(cleanup) + " EXIT; " + strings.Join(quotedArgs, " ")
}
func removeRemoteBinary(sshTarget, sshPort, remotePath string) {
args := []string{}
if sshPort != "" {
args = append(args, "-p", sshPort)
}
args = append(args, sshTarget, "rm -f -- "+shellQuote(remotePath))
_ = exec.Command("ssh", args...).Run()
}
func copyBinaryToRemote(sshTarget, sshPort string) (string, error) {
// Get local binary path
localPath, err := os.Executable()
if err != nil {
return "", err
}
// Generate unique remote path
remotePath := fmt.Sprintf("/tmp/bsync-%d-%d", os.Getpid(), time.Now().UnixNano())
// Read local binary
data, err := os.ReadFile(localPath)
if err != nil {
return "", err
}
// Build remote command: decode base64, write to file, make executable
remoteCmd := fmt.Sprintf("base64 -d > %s && chmod +x %s", shellQuote(remotePath), shellQuote(remotePath))
// Build SSH args
sshArgs := []string{"ssh"}
if sshPort != "" {
sshArgs = append(sshArgs, "-p", sshPort)
}
sshArgs = append(sshArgs, sshTarget, remoteCmd)
Log("copying binary to remote via SSH: %s\n", remotePath)
// Run SSH with stdin receiving base64-encoded binary
cmd := exec.Command(sshArgs[0], sshArgs[1:]...)
stdin, err := cmd.StdinPipe()
if err != nil {
return "", err
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return "", err
}
// Write base64-encoded binary to SSH stdin
encoder := base64.NewEncoder(base64.StdEncoding, stdin)
if _, err := encoder.Write(data); err != nil {
cmd.Process.Kill()
cmd.Wait()
return "", err
}
if err := encoder.Close(); err != nil {
cmd.Process.Kill()
cmd.Wait()
return "", err
}
if err := stdin.Close(); err != nil {
cmd.Process.Kill()
cmd.Wait()
return "", err
}
if err := cmd.Wait(); err != nil {
return "", fmt.Errorf("binary transfer failed: %v", err)
}
return remotePath, nil
}
func startRemoteSSH(targetPath, port string, blockSize, skipIdx uint32, quiet bool, noCompress bool) (*exec.Cmd, error) {
// split sshTarget "user@host:/remote/path" -> "user@host" and "/remote/path"
user, host, sshPort, file := parseSSHTarget(targetPath)
// If no host specified, run locally
if host == "" {
Log("run locally: %s\n", file)
// Get the path to the current executable
execPath, err := os.Executable()
if err != nil {
return nil, err
}
// Create command with absolute path to bsync
args := []string{execPath, "-f", file, "-p", port, "-b", strconv.FormatUint(uint64(blockSize), 10), "-s", strconv.FormatUint(uint64(skipIdx), 10)}
if quiet {
args = append(args, "-q")
}
if noCompress {
args = append(args, "-n")
}
// Pass encryption key if enabled
if IsEncryptionEnabled() {
args = append(args, "-K", GetEncryptionKeyHex())
}
cmd := exec.Command(args[0], args[1:]...)
// Set up stdout pipe to capture READY signal
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return nil, err
}
if err := waitForReady(stdout, true); err != nil {
return nil, err
}
cmd.Stdout = os.Stdout
go io.Copy(os.Stdout, stdout) // keeps reading and printing
return cmd, nil
}
if user != "" {
host = user + "@" + host
}
// Copy binary to remote server
remoteBinPath, err := copyBinaryToRemote(host, sshPort)
if err != nil {
return nil, err
}
// run SSH command. Keep all remote arguments in one shell-quoted command:
// ssh servers execute their command through a shell.
args := []string{"ssh"}
// Add custom SSH port if specified
if sshPort != "" {
args = append(args, "-p", sshPort)
}
remoteArgs := []string{"-f", file,
"-p", port,
"-b", strconv.FormatUint(uint64(blockSize), 10),
"-s", strconv.FormatUint(uint64(skipIdx), 10),
"-P", // suppress server-side progress (client shows its own)
}
if quiet {
remoteArgs = append(remoteArgs, "-q")
}
if noCompress {
remoteArgs = append(remoteArgs, "-n")
}
// Pass encryption key if enabled
if IsEncryptionEnabled() {
remoteArgs = append(remoteArgs, "-K", GetEncryptionKeyHex())
}
args = append(args, host, remoteBinaryCommand(remoteBinPath, remoteArgs))
Log("spawning SSH server on %s\n", host)
cmd := exec.Command(args[0], args[1:]...)
stdout, err := cmd.StdoutPipe()
if err != nil {
removeRemoteBinary(host, sshPort, remoteBinPath)
return nil, err
}
// cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr // pass stderr through
if err := cmd.Start(); err != nil {
removeRemoteBinary(host, sshPort, remoteBinPath)
return nil, err
}
if err := waitForReady(stdout, false); err != nil {
cmd.Process.Kill()
cmd.Wait()
removeRemoteBinary(host, sshPort, remoteBinPath)
return nil, err
}
cmd.Stdout = os.Stdout
go io.Copy(os.Stdout, stdout) // keeps reading and printing
return cmd, nil
}
func startRemoteSSHDownload(targetPath, port string, blockSize, skipIdx uint32, quiet bool, noCompress bool, compLevel string) (*exec.Cmd, error) {
// split sshTarget "user@host:/remote/path" -> "user@host" and "/remote/path"
user, host, sshPort, file := parseSSHTarget(targetPath)
// If no host specified, run locally
if host == "" {
Log("run locally for download: %s\n", file)
// Get the path to the current executable
execPath, err := os.Executable()
if err != nil {
return nil, err
}
// Create command with absolute path to bsync with -d flag for download mode
args := []string{execPath, "-f", file, "-p", port, "-b", strconv.FormatUint(uint64(blockSize), 10), "-s", strconv.FormatUint(uint64(skipIdx), 10), "-d", "-L", compLevel}
if quiet {
args = append(args, "-q")
}
if noCompress {
args = append(args, "-n")
}
// Pass encryption key if enabled
if IsEncryptionEnabled() {
args = append(args, "-K", GetEncryptionKeyHex())
}
cmd := exec.Command(args[0], args[1:]...)
// Set up stdout pipe to capture READY signal
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return nil, err
}
if err := waitForReady(stdout, true); err != nil {
return nil, err
}
cmd.Stdout = os.Stdout
go io.Copy(os.Stdout, stdout) // keeps reading and printing
return cmd, nil
}
if user != "" {
host = user + "@" + host
}
// Copy binary to remote server
remoteBinPath, err := copyBinaryToRemote(host, sshPort)
if err != nil {
return nil, err
}
// run SSH command with -d flag for download mode
args := []string{"ssh"}
// Add custom SSH port if specified
if sshPort != "" {
args = append(args, "-p", sshPort)
}
remoteArgs := []string{"-f", file,
"-p", port,
"-b", strconv.FormatUint(uint64(blockSize), 10),
"-s", strconv.FormatUint(uint64(skipIdx), 10),
"-d",
"-L", compLevel,
"-P", // suppress server-side progress (client shows its own)
}
if quiet {
remoteArgs = append(remoteArgs, "-q")
}
if noCompress {
remoteArgs = append(remoteArgs, "-n")
}
// Pass encryption key if enabled
if IsEncryptionEnabled() {
remoteArgs = append(remoteArgs, "-K", GetEncryptionKeyHex())
}
args = append(args, host, remoteBinaryCommand(remoteBinPath, remoteArgs))
Log("spawning SSH download server on %s\n", host)
cmd := exec.Command(args[0], args[1:]...)
stdout, err := cmd.StdoutPipe()
if err != nil {
removeRemoteBinary(host, sshPort, remoteBinPath)
return nil, err
}
cmd.Stderr = os.Stderr // pass stderr through
if err := cmd.Start(); err != nil {
removeRemoteBinary(host, sshPort, remoteBinPath)
return nil, err
}
if err := waitForReady(stdout, false); err != nil {
cmd.Process.Kill()
cmd.Wait()
removeRemoteBinary(host, sshPort, remoteBinPath)
return nil, err
}
cmd.Stdout = os.Stdout
go io.Copy(os.Stdout, stdout) // keeps reading and printing
return cmd, nil
}