Debian Codegraph @

internal/maincmd/clientmaincmd.go

raw symbols SCIP
1 package maincmd
2
3 import (
4 "bufio"
5 "context"
6 "fmt"
7 "io"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "runtime"
12 "strings"
13 "time"
14
15 "github.com/gokrazy/rsync"
16 "github.com/gokrazy/rsync/internal/progress"
17 "github.com/gokrazy/rsync/internal/receiver"
18 "github.com/gokrazy/rsync/internal/restrict"
19 "github.com/gokrazy/rsync/internal/rsyncopts"
20 "github.com/gokrazy/rsync/internal/rsyncos"
21 "github.com/gokrazy/rsync/internal/rsyncstats"
22 "github.com/gokrazy/rsync/internal/rsyncwire"
23 "github.com/gokrazy/rsync/internal/sender"
24 "github.com/google/shlex"
25 )
26
27 // rsync/main.c:start_client
28 func rsyncMain(ctx context.Context, osenv *rsyncos.Env, opts *rsyncopts.Options, sources []string, dest string) (*rsyncstats.TransferStats, error) {
29 if opts.Verbose() {
30 osenv.Logf("dest: %q, sources: %q", dest, sources)
31 osenv.Logf("opts: %+v", opts)
32 }
33 // Guaranteed to be non-empty by caller of rsyncMain().
34 src := sources[0]
35
36 if opts.Verbose() {
37 osenv.Logf("processing src=%s", src)
38 }
39 daemonConnection := 0 // no daemon
40 host, path, port, err := checkForHostspec(src)
41 if opts.Verbose() {
42 osenv.Logf("host=%q, path=%q, port=%d, err=%v", host, path, port, err)
43 }
44 if err != nil {
45 // source is local, check dest arg
46 opts.SetSender()
47 // TODO: remote_argv == "."?
48 host, path, port, err = checkForHostspec(dest)
49 if opts.Verbose() {
50 osenv.Logf("host=%q, path=%q, port=%d, err=%v", host, path, port, err)
51 }
52 if path == "" {
53 if opts.Verbose() {
54 osenv.Logf("source and dest are both local!")
55 }
56 host = ""
57 port = 0
58 path = dest
59 opts.SetLocalServer()
60 } else {
61 // dest is remote
62 if port != 0 {
63 if opts.ShellCommand() != "" {
64 daemonConnection = 1 // daemon via remote shell
65 } else {
66 daemonConnection = -1 // daemon via socket
67 }
68 }
69 }
70 } else {
71 // source is remote
72 if port != 0 {
73 if opts.ShellCommand() != "" {
74 daemonConnection = 1 // daemon via remote shell
75 } else {
76 daemonConnection = -1 // daemon via socket
77 }
78 }
79 }
80
81 // TODO: if opts.AmSender(), verify extra source args have no hostspec
82 var roDirs, rwDirs []string
83 other := dest
84 if other != "" {
85 if !opts.Sender() || opts.LocalServer() {
86 // dest is local
87 if err := os.MkdirAll(other, 0755); err != nil {
88 return nil, err
89 }
90 }
91 }
92 paths := []string{other}
93 if opts.Sender() {
94 // source is local
95 // other = src
96 paths = sources
97 roDirs = sources
98 if opts.LocalServer() {
99 // source and dest are both local
100 rwDirs = []string{dest}
101 }
102 } else {
103 if other != "" {
104 rwDirs = paths
105 }
106 }
107
108 if daemonConnection < 0 {
109 stats, err := socketClient(ctx, osenv, opts, host, path, port, paths, roDirs, rwDirs)
110 if err != nil {
111 return nil, err
112 }
113 return stats, nil
114 }
115
116 machine := host
117 user := ""
118 if idx := strings.IndexByte(machine, '@'); idx > -1 {
119 user = machine[:idx]
120 machine = machine[idx+1:]
121 }
122 rc, wc, err := doCmd(osenv, opts, machine, user, path, daemonConnection)
123 if err != nil {
124 return nil, err
125 }
126 defer rc.Close()
127 defer wc.Close()
128 conn := &readWriteCloser{
129 r: rc,
130 w: wc,
131 }
132
133 if osenv.Restrict() {
134 if err := restrict.MaybeFileSystem(roDirs, rwDirs); err != nil {
135 return nil, err
136 }
137 }
138
139 negotiate := true
140 if daemonConnection != 0 {
141 done, err := StartInbandExchange(osenv, opts, conn, path)
142 if err != nil {
143 return nil, err
144 }
145 if done {
146 return nil, nil
147 }
148 negotiate = false // already done
149 }
150 stats, err := ClientRun(osenv, opts, conn, paths, negotiate)
151 if err != nil {
152 return nil, err
153 }
154 return stats, nil
155 }
156
157 // rsync/main.c:do_cmd
158 func doCmd(osenv *rsyncos.Env, opts *rsyncopts.Options, machine, user, path string, daemonConnection int) (io.ReadCloser, io.WriteCloser, error) {
159 if opts.Verbose() {
160 osenv.Logf("doCmd(machine=%q, user=%q, path=%q, daemonConnection=%d)",
161 machine, user, path, daemonConnection)
162 }
163 var args []string
164 if !opts.LocalServer() {
165 cmd := opts.ShellCommand()
166 if cmd == "" {
167 cmd = "ssh"
168 if e := os.Getenv("RSYNC_RSH"); e != "" {
169 cmd = e
170 }
171 }
172
173 // We use shlex.Split(), whereas rsync implements its own shell-style-like
174 // parsing. The nuances likely don’t matter to any users, and if so, users
175 // might prefer shell-style parsing.
176 //
177 // On Windows, double the backslashes first: shlex treats "\" as an escape
178 // character, which would otherwise mangle a native "-e C:\path\rsync.exe"
179 // into "C:pathrsync.exe".
180 if runtime.GOOS == "windows" {
181 cmd = strings.ReplaceAll(cmd, `\`, `\\`)
182 }
183 var err error
184 args, err = shlex.Split(cmd)
185 if err != nil {
186 return nil, nil, err
187 }
188
189 if user != "" && daemonConnection == 0 /* && !dashlset */ {
190 args = append(args, "-l", user)
191 }
192
193 args = append(args, machine)
194
195 args = append(args, "rsync") // TODO: flag
196 } else {
197 // NOTE: tridge rsync will fork and run child_main(), we call Main() in
198 // a separate goroutine below.
199 args = append(args, os.Args[0])
200 }
201
202 if daemonConnection > 0 {
203 args = append(args, "--server", "--daemon")
204 } else {
205 args = append(args, opts.ServerOptions()...)
206 }
207 args = append(args, ".")
208
209 if daemonConnection == 0 {
210 args = append(args, path)
211 }
212
213 if opts.Verbose() {
214 osenv.Logf("args: %q", args)
215 }
216
217 if opts.LocalServer() {
218 stdinrd, stdinwr := io.Pipe()
219 stdoutrd, stdoutwr := io.Pipe()
220 go func() {
221 defer stdinrd.Close()
222 defer stdoutwr.Close()
223 osenv := &rsyncos.Env{
224 Stdin: stdinrd,
225 Stdout: stdoutwr,
226 Stderr: os.Stderr,
227 // If this transfer restricts file system access, all goroutines
228 // (including the other end of the connection) are affected.
229 DontRestrict: true,
230 }
231 _, err := Main(context.Background(), osenv, args, nil)
232 if err != nil {
233 osenv.Logf("Main(): %v", err)
234 }
235 }()
236 return stdoutrd, stdinwr, nil
237 }
238
239 ssh := exec.Command(args[0], args[1:]...)
240 wc, err := ssh.StdinPipe()
241 if err != nil {
242 return nil, nil, err
243 }
244 rc, err := ssh.StdoutPipe()
245 if err != nil {
246 return nil, nil, err
247 }
248 ssh.Stderr = osenv.Stderr
249 if err := ssh.Start(); err != nil {
250 return nil, nil, err
251 }
252
253 go func() {
254 // TODO: correctly terminate the main process when the underlying SSH
255 // process exits.
256 if err := ssh.Wait(); err != nil {
257 osenv.Logf("remote shell exited: %v", err)
258 }
259 }()
260
261 return rc, wc, nil
262 }
263
264 // rsync/main.c:client_run
265 func ClientRun(osenv *rsyncos.Env, opts *rsyncopts.Options, conn io.ReadWriteCloser, paths []string, negotiate bool) (*rsyncstats.TransferStats, error) {
266 crd := &rsyncwire.CountingReader{R: conn}
267 cwr := &rsyncwire.CountingWriter{W: conn}
268 c := &rsyncwire.Conn{
269 Reader: crd,
270 Writer: cwr,
271 }
272
273 if negotiate {
274 if err := c.WriteInt32(rsync.ProtocolVersion); err != nil {
275 return nil, err
276 }
277 remoteProtocol, err := c.ReadInt32()
278 if err != nil {
279 return nil, err
280 }
281 if opts.Verbose() {
282 osenv.Logf("remote protocol: %d", remoteProtocol)
283 }
284 }
285
286 seed, err := c.ReadInt32()
287 if err != nil {
288 return nil, fmt.Errorf("reading seed: %v", err)
289 }
290
291 mrd := &rsyncwire.MultiplexReader{
292 Env: osenv,
293 Reader: conn,
294 }
295 // TODO: rearchitect such that our buffer can be smaller than the largest
296 // rsync message size
297 rd := bufio.NewReaderSize(mrd, 256*1024)
298 // Update crd to track the multiplexed reader,
299 // but copy the number of bytes read.
300 crd = &rsyncwire.CountingReader{
301 R: struct {
302 io.Reader
303 io.Closer
304 }{
305 Reader: rd,
306 Closer: conn,
307 },
308 BytesRead: crd.BytesRead,
309 }
310 c.Reader = crd
311
312 if opts.Sender() {
313 st := &sender.Transfer{
314 Logger: osenv.Logger(),
315 Opts: opts,
316 Conn: c,
317 Seed: seed,
318 Env: osenv,
319 Progress: progress.NewPrinter(osenv.Stdout, time.Now),
320 }
321 if opts.Verbose() {
322 osenv.Logf("sender(paths=%q)", paths)
323 }
324
325 // Turn relative paths like ./gcexportdata or bin/gcexportdata
326 // into absolute paths so that we can call Transfer.Do()
327 // with modPath="/" below.
328 for idx, path := range paths {
329 // Trailing slashes are meaningful to rsync,
330 // so preserve a trailing slash across filepath.Abs.
331 hasTrailingSlash := strings.HasSuffix(path, "/")
332 abs, err := filepath.Abs(path)
333 if err != nil {
334 return nil, err
335 }
336 paths[idx] = abs
337 if hasTrailingSlash {
338 paths[idx] += "/"
339 }
340 }
341
342 stats, err := st.Do(crd, cwr, rsync.FileSystemRoot, paths, nil)
343 if err != nil {
344 return nil, err
345 }
346 return stats, nil
347 }
348
349 if len(paths) != 1 {
350 return nil, fmt.Errorf("BUG: expected exactly one path, got %q", paths)
351 }
352
353 rt := &receiver.Transfer{
354 Logger: osenv.Logger(),
355 Opts: &receiver.TransferOpts{
356 Verbose: opts.Verbose(),
357 DryRun: opts.DryRun(),
358 Progress: opts.Progress(),
359
360 DeleteMode: opts.DeleteMode(),
361 PreserveGid: opts.PreserveGid(),
362 PreserveUid: opts.PreserveUid(),
363 PreserveLinks: opts.PreserveLinks(),
364 PreservePerms: opts.PreservePerms(),
365 PreserveDevices: opts.PreserveDevices(),
366 PreserveSpecials: opts.PreserveSpecials(),
367 PreserveTimes: opts.PreserveMTimes(),
368 PreserveHardlinks: opts.PreserveHardLinks(),
369 IgnoreTimes: opts.IgnoreTimes(),
370 AlwaysChecksum: opts.AlwaysChecksum(),
371 DoFsync: opts.DoFsync(),
372
373 InfoGTE: opts.InfoGTE,
374 DebugGTE: opts.DebugGTE,
375 },
376 Dest: paths[0],
377 Env: osenv,
378 Conn: c,
379 Seed: seed,
380 Progress: progress.NewPrinter(osenv.Stdout, time.Now),
381 }
382 if opts.Verbose() {
383 osenv.Logf("receiving to dest=%s", rt.Dest)
384 }
385 if rt.Dest == "" {
386 // just listing modules, not transferring anything
387 } else {
388 if err := os.MkdirAll(rt.Dest, 0755); err != nil {
389 return nil, fmt.Errorf("MkdirAll(dest=%s): %v", rt.Dest, err)
390 }
391 rt.DestRoot, err = os.OpenRoot(rt.Dest)
392 if err != nil {
393 return nil, fmt.Errorf("OpenRoot(dest=%s): %v", rt.Dest, err)
394 }
395 defer rt.DestRoot.Close()
396 if osenv.Restrict() {
397 if err := restrict.MaybeFileSystem(nil, []string{rt.Dest}); err != nil {
398 return nil, fmt.Errorf("landlock: %v", err)
399 }
400 }
401 }
402
403 for _, rule := range opts.FilterRules() {
404 c.WriteInt32(int32(len(rule)))
405 c.WriteString(rule)
406 }
407 const exclusionListEnd = 0
408 if err := c.WriteInt32(exclusionListEnd); err != nil {
409 return nil, err
410 }
411
412 if opts.DebugGTE(rsyncopts.DEBUG_RECV, 1) {
413 osenv.Logf("exclusion list sent")
414 }
415
416 // receive file list
417 if opts.DebugGTE(rsyncopts.DEBUG_FLIST, 1) {
418 osenv.Logf("receiving file list")
419 }
420 fileList, err := rt.ReceiveFileList()
421 if err != nil {
422 return nil, err
423 }
424 if opts.DebugGTE(rsyncopts.DEBUG_FLIST, 2) {
425 osenv.Logf("received %d names", len(fileList))
426 }
427
428 return rt.Do(c, fileList, false)
429 }
430
431 func clientMain(ctx context.Context, osenv *rsyncos.Env, opts *rsyncopts.Options, remaining []string) (*rsyncstats.TransferStats, error) {
432 if len(remaining) == 0 {
433 // help goes to stderr when no arguments were specified
434 fmt.Fprintln(osenv.Stderr, opts.Help())
435 return nil, fmt.Errorf("rsync error: syntax or usage error")
436 }
437 if len(remaining) == 1 {
438 // Usages with just one SRC arg and no DEST arg list the source files
439 // instead of copying.
440 dest := ""
441 sources := remaining
442 return rsyncMain(ctx, osenv, opts, sources, dest)
443 }
444 dest := remaining[len(remaining)-1]
445 sources := remaining[:len(remaining)-1]
446 return rsyncMain(ctx, osenv, opts, sources, dest)
447 }