| 1 | // Package rsyncd implements an rsync server (only), but note that gokrazy/rsync |
| 2 | // contains a native Go rsync implementation that supports sending and receiving |
| 3 | // files as client or server, compatible with the original tridge rsync (from |
| 4 | // the samba project) or openrsync (used on OpenBSD and macOS 15+). |
| 5 | package rsyncd |
| 6 | |
| 7 | import ( |
| 8 | "bufio" |
| 9 | "context" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "io/fs" |
| 14 | "net" |
| 15 | "os" |
| 16 | "path/filepath" |
| 17 | "strings" |
| 18 | "time" |
| 19 | |
| 20 | "github.com/gokrazy/rsync" |
| 21 | "github.com/gokrazy/rsync/internal/log" |
| 22 | "github.com/gokrazy/rsync/internal/progress" |
| 23 | "github.com/gokrazy/rsync/internal/receiver" |
| 24 | "github.com/gokrazy/rsync/internal/rsyncopts" |
| 25 | "github.com/gokrazy/rsync/internal/rsyncos" |
| 26 | "github.com/gokrazy/rsync/internal/rsyncwire" |
| 27 | "github.com/gokrazy/rsync/internal/sender" |
| 28 | ) |
| 29 | |
| 30 | type Module struct { |
| 31 | Name string `toml:"name"` |
| 32 | Path string `toml:"path"` // If empty, FS must be non-nil |
| 33 | FS fs.FS `toml:"-"` // If set, serve from this instead of Path |
| 34 | ACL []string `toml:"acl"` |
| 35 | Writable bool `toml:"writable"` // Must be false if FS is set |
| 36 | } |
| 37 | |
| 38 | // Option specifies the server options. |
| 39 | type Option interface { |
| 40 | applyServer(*Server) |
| 41 | } |
| 42 | |
| 43 | type serverOptionFunc func(server *Server) |
| 44 | |
| 45 | func (f serverOptionFunc) applyServer(s *Server) { |
| 46 | f(s) |
| 47 | } |
| 48 | |
| 49 | // WithLogger specifies the logger to use for the server. |
| 50 | // It also sets the global logger used by the rsync package. |
| 51 | func WithLogger(logger log.Logger) Option { |
| 52 | return serverOptionFunc(func(s *Server) { |
| 53 | s.logger = logger |
| 54 | }) |
| 55 | } |
| 56 | |
| 57 | func WithStderr(stderr io.WriteCloser) Option { |
| 58 | return serverOptionFunc(func(s *Server) { |
| 59 | s.stderr = stderr |
| 60 | }) |
| 61 | } |
| 62 | |
| 63 | func DontRestrict() Option { |
| 64 | return serverOptionFunc(func(s *Server) { |
| 65 | s.dontRestrict = true |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | func NewServer(modules []Module, opts ...Option) (*Server, error) { |
| 70 | for _, mod := range modules { |
| 71 | if err := validateModule(mod); err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | server := &Server{ |
| 77 | modules: modules, |
| 78 | } |
| 79 | |
| 80 | for _, opt := range opts { |
| 81 | opt.applyServer(server) |
| 82 | } |
| 83 | |
| 84 | // Default to os.Stderr if no stderr was specified. |
| 85 | // Explicitly use io.Discard if you do not want stderr. |
| 86 | if server.stderr == nil { |
| 87 | server.stderr = os.Stderr |
| 88 | } |
| 89 | |
| 90 | if server.logger == nil { |
| 91 | // TODO: use the logger in a *rsyncos.Env instead |
| 92 | server.logger = log.New(server.stderr) |
| 93 | } |
| 94 | |
| 95 | // An empty module list means this server is a sender |
| 96 | // (e.g. started in command mode with --server --sender), |
| 97 | // in which case restrict.MaybeFileSystem() will be called |
| 98 | // by the caller of NewServer(). |
| 99 | if !server.dontRestrict && len(server.modules) > 0 { |
| 100 | if err := restrictToModules(server.modules); err != nil { |
| 101 | return nil, err |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | return server, nil |
| 106 | } |
| 107 | |
| 108 | type Server struct { |
| 109 | stderr io.WriteCloser |
| 110 | logger log.Logger |
| 111 | dontRestrict bool |
| 112 | |
| 113 | modules []Module |
| 114 | } |
| 115 | |
| 116 | func (s *Server) getModule(requestedModule string) (Module, error) { |
| 117 | for _, mod := range s.modules { |
| 118 | if mod.Name == requestedModule { |
| 119 | return mod, nil |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | return Module{}, fmt.Errorf("no such module: %s", requestedModule) |
| 124 | } |
| 125 | |
| 126 | func (s *Server) formatModuleList() string { |
| 127 | if len(s.modules) == 0 { |
| 128 | return "" |
| 129 | } |
| 130 | var list strings.Builder |
| 131 | for _, mod := range s.modules { |
| 132 | comment := mod.Name // for now |
| 133 | fmt.Fprintf(&list, "%s\t%s\n", |
| 134 | mod.Name, |
| 135 | comment) |
| 136 | } |
| 137 | return list.String() |
| 138 | } |
| 139 | |
| 140 | func checkACL(acls []string, remoteAddr string) error { |
| 141 | if len(acls) == 0 { |
| 142 | return nil |
| 143 | } |
| 144 | host, _, err := net.SplitHostPort(remoteAddr) |
| 145 | if err != nil { |
| 146 | return fmt.Errorf("BUG: invalid remote address %q", remoteAddr) |
| 147 | } |
| 148 | remoteIP := net.ParseIP(host) |
| 149 | if remoteIP == nil { |
| 150 | return fmt.Errorf("BUG: invalid remote host %q", host) |
| 151 | } |
| 152 | for _, acl := range acls { |
| 153 | // TODO(performance): move ACL parsing to config-time to make ACL checks |
| 154 | // less expensive |
| 155 | i := strings.Index(acl, " ") |
| 156 | if i < 0 { |
| 157 | return fmt.Errorf("invalid acl: %q (no space found)", acl) |
| 158 | } |
| 159 | action, who := acl[:i], acl[i+len(" "):] |
| 160 | if action != "allow" && action != "deny" { |
| 161 | return fmt.Errorf("invalid acl: %q (syntax: allow|deny <all|ipnet>)", acl) |
| 162 | } |
| 163 | if who == "all" { |
| 164 | // The all keyword matches any remote IP address |
| 165 | } else { |
| 166 | _, net, err := net.ParseCIDR(who) |
| 167 | if err != nil { |
| 168 | return fmt.Errorf("invalid acl: %q (syntax: allow|deny <all|ipnet>)", acl) |
| 169 | } |
| 170 | if !net.Contains(remoteIP) { |
| 171 | // Skip this instruction, the remote IP does not match |
| 172 | continue |
| 173 | } |
| 174 | } |
| 175 | switch action { |
| 176 | case "allow": |
| 177 | return nil |
| 178 | case "deny": |
| 179 | return fmt.Errorf("access denied (acl %q)", acl) |
| 180 | default: |
| 181 | return fmt.Errorf("invalid acl: %q (syntax: allow|deny <all|ipnet>)", acl) |
| 182 | } |
| 183 | } |
| 184 | return nil |
| 185 | } |
| 186 | |
| 187 | // FIXME: context cancellation not yet implemented |
| 188 | func (s *Server) HandleDaemonConn(ctx context.Context, conn *Conn) (err error) { |
| 189 | _ = ctx // not implemented. what would be the best thing to do? wrap conn's reader part with cancelable reader? |
| 190 | |
| 191 | const terminationCommand = "@RSYNCD: OK\n" |
| 192 | cwr := conn.cwr |
| 193 | rd := conn.rd |
| 194 | // send server greeting |
| 195 | |
| 196 | fmt.Fprintf(cwr, "@RSYNCD: %d\n", rsync.ProtocolVersion) |
| 197 | |
| 198 | // read client greeting |
| 199 | clientGreeting, err := rd.ReadString('\n') |
| 200 | if err != nil { |
| 201 | return err |
| 202 | } |
| 203 | if !strings.HasPrefix(clientGreeting, "@RSYNCD: ") { |
| 204 | return fmt.Errorf("invalid client greeting: got %q", clientGreeting) |
| 205 | } |
| 206 | // TODO: protocol negotiation |
| 207 | |
| 208 | // read requested module(s), if any |
| 209 | requestedModule, err := rd.ReadString('\n') |
| 210 | if err != nil { |
| 211 | return err |
| 212 | } |
| 213 | requestedModule = strings.TrimSpace(requestedModule) |
| 214 | if requestedModule == "" || requestedModule == "#list" { |
| 215 | s.logger.Printf("client %v requested rsync module listing", conn.name) |
| 216 | io.WriteString(cwr, s.formatModuleList()) |
| 217 | io.WriteString(cwr, "@RSYNCD: EXIT\n") |
| 218 | return nil |
| 219 | } |
| 220 | s.logger.Printf("client %v requested rsync module %q", conn.name, requestedModule) |
| 221 | module, err := s.getModule(requestedModule) |
| 222 | if err != nil { |
| 223 | fmt.Fprintf(cwr, "@ERROR: Unknown module %q\n", requestedModule) |
| 224 | return err |
| 225 | } |
| 226 | |
| 227 | if err := checkACL(module.ACL, conn.name); err != nil { |
| 228 | fmt.Fprintf(cwr, "@ERROR: %v\n", err) |
| 229 | return err |
| 230 | } |
| 231 | |
| 232 | io.WriteString(cwr, terminationCommand) |
| 233 | |
| 234 | // read requested flags |
| 235 | var flags []string |
| 236 | for { |
| 237 | flag, err := rd.ReadString('\n') |
| 238 | if err != nil { |
| 239 | return err |
| 240 | } |
| 241 | flag = strings.TrimSpace(flag) |
| 242 | s.logger.Printf("client sent: %q", flag) |
| 243 | if flag == "" { |
| 244 | break |
| 245 | } |
| 246 | flags = append(flags, flag) |
| 247 | } |
| 248 | |
| 249 | s.logger.Printf("flags: %+v", flags) |
| 250 | osenv := &rsyncos.Env{Stderr: s.stderr} |
| 251 | pc := rsyncopts.NewContext(rsyncopts.NewOptionsWithGokrazyDefaults(osenv)) |
| 252 | if err := pc.ParseArguments(osenv, flags); err != nil { |
| 253 | err = fmt.Errorf("parsing server args: %v", err) |
| 254 | |
| 255 | // terminate connection with an error about which flag is not supported |
| 256 | c := &rsyncwire.Conn{ |
| 257 | Reader: io.NopCloser(rd), |
| 258 | Writer: cwr, |
| 259 | } |
| 260 | |
| 261 | const errorSeed = 0xee |
| 262 | if err := c.WriteInt32(errorSeed); err != nil { |
| 263 | return err |
| 264 | } |
| 265 | |
| 266 | // Switch to multiplexing protocol, but only for server-side transmissions. |
| 267 | // Transmissions received from the client are not multiplexed. |
| 268 | mpx := &rsyncwire.MultiplexWriter{Writer: c.Writer} |
| 269 | mpx.WriteMsg(rsyncwire.MsgError, fmt.Appendf(nil, "gokr-rsync [sender]: %v\n", err)) |
| 270 | |
| 271 | return err |
| 272 | } |
| 273 | remaining := pc.RemainingArgs |
| 274 | s.logger.Printf("remaining: %q", remaining) |
| 275 | // remaining[0] is always "." |
| 276 | // remaining[1] is the first directory |
| 277 | if len(remaining) < 2 { |
| 278 | return fmt.Errorf("invalid args: at least one directory required") |
| 279 | } |
| 280 | if got, want := remaining[0], "."; got != want { |
| 281 | return fmt.Errorf("protocol error: got %q, expected %q", got, want) |
| 282 | } |
| 283 | paths := remaining[1:] |
| 284 | s.logger.Printf("paths: %q", paths) |
| 285 | |
| 286 | // Strip the module_name/ prefix out of the paths, |
| 287 | // see rsync/io.c:read_args, glob_expand_module(). |
| 288 | for idx, path := range pc.RemainingArgs { |
| 289 | if idx == 0 { |
| 290 | // skip pc.RemainingArgs[0], only strip RemainingArgs[1:] |
| 291 | continue |
| 292 | } |
| 293 | trimmed := strings.TrimPrefix(path, module.Name) |
| 294 | if trimmed == "" { |
| 295 | trimmed = "." |
| 296 | } |
| 297 | pc.RemainingArgs[idx] = trimmed |
| 298 | } |
| 299 | |
| 300 | s.logger.Printf("trimmed paths: %q", pc.RemainingArgs[1:]) |
| 301 | |
| 302 | return s.handleConn(ctx, conn, &module, pc, false) |
| 303 | } |
| 304 | |
| 305 | type Conn struct { |
| 306 | name string |
| 307 | crd *rsyncwire.CountingReader |
| 308 | cwr *rsyncwire.CountingWriter |
| 309 | rd *bufio.Reader |
| 310 | closer io.Closer |
| 311 | } |
| 312 | |
| 313 | func NewConnection(r io.ReadCloser, w io.WriteCloser, name string) *Conn { |
| 314 | crd, cwr := rsyncwire.CounterPair(r, w) |
| 315 | rd := bufio.NewReader(crd) |
| 316 | return &Conn{ |
| 317 | name: name, |
| 318 | crd: crd, |
| 319 | cwr: cwr, |
| 320 | rd: rd, |
| 321 | closer: &rsync.BothCloser{ |
| 322 | ReadCloser: r, |
| 323 | WriteCloser: w, |
| 324 | }, |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | // This method is only exported until we refactor; use HandleConnArgs() instead |
| 329 | func (s *Server) InternalHandleConn(ctx context.Context, conn *Conn, module *Module, pc *rsyncopts.Context) error { |
| 330 | return s.handleConn(ctx, conn, module, pc, true /* negotiate */) |
| 331 | } |
| 332 | |
| 333 | func (s *Server) HandleConnArgs(ctx context.Context, conn *Conn, module *Module, args []string) error { |
| 334 | osenv := &rsyncos.Env{Stderr: s.stderr} |
| 335 | pc := rsyncopts.NewContext(rsyncopts.NewOptionsWithGokrazyDefaults(osenv)) |
| 336 | if err := pc.ParseArguments(osenv, args); err != nil { |
| 337 | return fmt.Errorf("parsing server args: %v", err) |
| 338 | } |
| 339 | return s.handleConn(ctx, conn, module, pc, true /* negotiate */) |
| 340 | } |
| 341 | |
| 342 | // handleConn is equivalent to rsync/main.c:start_server |
| 343 | func (s *Server) handleConn(ctx context.Context, conn *Conn, module *Module, pc *rsyncopts.Context, negotiate bool) (err error) { |
| 344 | rd := conn.rd |
| 345 | crd := conn.crd |
| 346 | cwr := conn.cwr |
| 347 | opts := pc.Options |
| 348 | paths := pc.RemainingArgs[1:] |
| 349 | |
| 350 | // “SHOULD be unique to each connection” as per |
| 351 | // https://github.com/JohannesBuchner/Jarsync/blob/master/jarsync/rsync.txt |
| 352 | // |
| 353 | // Computed the same way that tridge rsync does it, but the details do not |
| 354 | // matter. The goal is to have a checksum seed each time. |
| 355 | sessionChecksumSeed := int32(time.Now().Unix()) ^ (int32(os.Getpid()) << 6) |
| 356 | |
| 357 | c := &rsyncwire.Conn{ |
| 358 | Reader: struct { |
| 359 | io.Reader |
| 360 | io.Closer |
| 361 | }{ |
| 362 | Reader: rd, |
| 363 | Closer: conn.closer, |
| 364 | }, |
| 365 | Writer: cwr, |
| 366 | } |
| 367 | |
| 368 | if negotiate { |
| 369 | remoteProtocol, err := c.ReadInt32() |
| 370 | if err != nil { |
| 371 | return err |
| 372 | } |
| 373 | if opts.DebugGTE(rsyncopts.DEBUG_PROTO, 1) { |
| 374 | s.logger.Printf("remote protocol: %d", remoteProtocol) |
| 375 | } |
| 376 | if err := c.WriteInt32(rsync.ProtocolVersion); err != nil { |
| 377 | return err |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | if err := c.WriteInt32(sessionChecksumSeed); err != nil { |
| 382 | return err |
| 383 | } |
| 384 | |
| 385 | // Switch to multiplexing protocol, but only for server-side transmissions. |
| 386 | // Transmissions received from the client are not multiplexed. |
| 387 | mpx := &rsyncwire.MultiplexWriter{Writer: c.Writer} |
| 388 | // Update cwr to track the multiplexed writer, |
| 389 | // but copy the number of bytes written. |
| 390 | cwr = &rsyncwire.CountingWriter{ |
| 391 | W: mpx, |
| 392 | BytesWritten: cwr.BytesWritten, |
| 393 | } |
| 394 | c.Writer = cwr |
| 395 | |
| 396 | if opts.Sender() { |
| 397 | // If returning an error, send the error to the client for display, too: |
| 398 | defer func() { |
| 399 | if err != nil { |
| 400 | mpx.WriteMsg(rsyncwire.MsgError, fmt.Appendf(nil, "gokr-rsync [sender]: %v\n", err)) |
| 401 | } |
| 402 | }() |
| 403 | |
| 404 | return s.handleConnSender(module, crd, cwr, paths, opts, false, c, sessionChecksumSeed) |
| 405 | } |
| 406 | |
| 407 | // If returning an error, send the error to the client for display, too: |
| 408 | defer func() { |
| 409 | if err != nil { |
| 410 | mpx.WriteMsg(rsyncwire.MsgError, fmt.Appendf(nil, "gokr-rsync [receiver]: %v\n", err)) |
| 411 | } |
| 412 | }() |
| 413 | return s.handleConnReceiver(module, crd, cwr, paths, opts, false, c, sessionChecksumSeed) |
| 414 | } |
| 415 | |
| 416 | // handleConnReceiver is equivalent to rsync/main.c:do_server_recv |
| 417 | func (s *Server) handleConnReceiver(module *Module, crd *rsyncwire.CountingReader, cwr *rsyncwire.CountingWriter, paths []string, opts *rsyncopts.Options, negotiate bool, c *rsyncwire.Conn, sessionChecksumSeed int32) (err error) { |
| 418 | var destPath string |
| 419 | implicitModule := module == nil |
| 420 | if implicitModule { |
| 421 | if len(paths) != 1 { |
| 422 | return fmt.Errorf("precisely one destination path required, got %q", paths) |
| 423 | } |
| 424 | module = &Module{ |
| 425 | Name: "implicit", |
| 426 | Path: paths[0], |
| 427 | Writable: true, |
| 428 | } |
| 429 | destPath = module.Path |
| 430 | } |
| 431 | if opts.Verbose() { |
| 432 | s.logger.Printf("handleConnReceiver(module=%+v, destPath=%q)", module, destPath) |
| 433 | } |
| 434 | |
| 435 | if !module.Writable { |
| 436 | return fmt.Errorf("ERROR: module is read only") |
| 437 | } |
| 438 | |
| 439 | rt := &receiver.Transfer{ |
| 440 | Logger: s.logger, |
| 441 | Opts: &receiver.TransferOpts{ |
| 442 | DryRun: opts.DryRun(), |
| 443 | Server: opts.Server(), |
| 444 | Verbose: opts.Verbose(), |
| 445 | Progress: opts.Progress(), |
| 446 | |
| 447 | DeleteMode: opts.DeleteMode(), |
| 448 | PreserveGid: opts.PreserveGid(), |
| 449 | PreserveUid: opts.PreserveUid(), |
| 450 | PreserveLinks: opts.PreserveLinks(), |
| 451 | PreservePerms: opts.PreservePerms(), |
| 452 | PreserveDevices: opts.PreserveDevices(), |
| 453 | PreserveSpecials: opts.PreserveSpecials(), |
| 454 | PreserveTimes: opts.PreserveMTimes(), |
| 455 | // TODO: PreserveHardlinks: opts.PreserveHardlinks, |
| 456 | IgnoreTimes: opts.IgnoreTimes(), |
| 457 | AlwaysChecksum: opts.AlwaysChecksum(), |
| 458 | DoFsync: opts.DoFsync(), |
| 459 | |
| 460 | InfoGTE: opts.InfoGTE, |
| 461 | DebugGTE: opts.DebugGTE, |
| 462 | }, |
| 463 | Dest: module.Path, |
| 464 | Env: &rsyncos.Env{ |
| 465 | Stderr: s.stderr, |
| 466 | }, |
| 467 | Conn: c, |
| 468 | Seed: sessionChecksumSeed, |
| 469 | Progress: progress.NewPrinter(io.Discard, time.Now), |
| 470 | } |
| 471 | if err := os.MkdirAll(rt.Dest, 0755); err != nil { |
| 472 | return fmt.Errorf("MkdirAll(dest=%s): %v", rt.Dest, err) |
| 473 | } |
| 474 | rt.DestRoot, err = os.OpenRoot(rt.Dest) |
| 475 | if err != nil { |
| 476 | return fmt.Errorf("OpenRoot(dest=%s): %v", rt.Dest, err) |
| 477 | } |
| 478 | defer rt.DestRoot.Close() |
| 479 | |
| 480 | if !implicitModule { |
| 481 | if len(paths) > 1 { |
| 482 | return fmt.Errorf("module is available, and at most one destination path is allowed, got %q", paths) |
| 483 | } |
| 484 | // Descend into subdirectory (if requested), |
| 485 | // using the os.OpenRoot traversal-safe API. |
| 486 | if len(paths) == 1 && paths[0] != "/" { |
| 487 | // Trim leading and trailing slash: |
| 488 | // (*os.Root).MkdirAll("foo/") was a security issue: |
| 489 | // https://go.dev/issue/79005, so no longer works. |
| 490 | subdir := strings.Trim(paths[0], "/") |
| 491 | subRoot, err := rt.DestRoot.OpenRoot(subdir) |
| 492 | if err != nil { |
| 493 | if os.IsNotExist(err) { |
| 494 | if err := rt.DestRoot.MkdirAll(subdir, 0755); err != nil { |
| 495 | return fmt.Errorf("MkdirAll(%s): %v", subdir, err) |
| 496 | } |
| 497 | subRoot, err = rt.DestRoot.OpenRoot(subdir) |
| 498 | } |
| 499 | if err != nil { |
| 500 | return fmt.Errorf("OpenRoot(%s): %v", subdir, err) |
| 501 | } |
| 502 | } |
| 503 | if name := subRoot.Name(); filepath.IsAbs(name) { |
| 504 | rt.Dest = name |
| 505 | } else { |
| 506 | // Go changed behavior: In Go 1.25, subRoot.Name() |
| 507 | // did not return an absolute path: |
| 508 | // https://go.googlesource.com/go/+/ed7f804 |
| 509 | rt.Dest = filepath.Join(rt.Dest, name) |
| 510 | } |
| 511 | rt.DestRoot = subRoot |
| 512 | if opts.Verbose() { |
| 513 | s.logger.Printf("opened subdirectory %q", rt.Dest) |
| 514 | } |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | if opts.PreserveHardLinks() { |
| 519 | return fmt.Errorf("support for hard links not yet implemented") |
| 520 | } |
| 521 | |
| 522 | if opts.DeleteMode() { |
| 523 | // receive the exclusion list (openrsync’s is always empty) |
| 524 | exclusionList, err := sender.RecvFilterList(c) |
| 525 | if err != nil { |
| 526 | return err |
| 527 | } |
| 528 | s.logger.Printf("exclusion list read (entries: %d)", len(exclusionList.Filters)) |
| 529 | } |
| 530 | |
| 531 | // receive file list |
| 532 | if opts.InfoGTE(rsyncopts.INFO_FLIST, 1) { |
| 533 | s.logger.Printf("receiving file list") |
| 534 | } |
| 535 | fileList, err := rt.ReceiveFileList() |
| 536 | if err != nil { |
| 537 | return err |
| 538 | } |
| 539 | if opts.InfoGTE(rsyncopts.INFO_FLIST, 1) { |
| 540 | s.logger.Printf("received %d names", len(fileList)) |
| 541 | } |
| 542 | stats, err := rt.Do(c, fileList, true) |
| 543 | if err != nil { |
| 544 | return err |
| 545 | } |
| 546 | if opts.InfoGTE(rsyncopts.INFO_STATS, 1) { |
| 547 | s.logger.Printf("stats: %+v", stats) |
| 548 | } |
| 549 | return nil |
| 550 | } |
| 551 | |
| 552 | // handleConnSender is equivalent to rsync/main.c:do_server_sender |
| 553 | func (s *Server) handleConnSender(module *Module, crd *rsyncwire.CountingReader, cwr *rsyncwire.CountingWriter, paths []string, opts *rsyncopts.Options, negotiate bool, c *rsyncwire.Conn, sessionChecksumSeed int32) (err error) { |
| 554 | if module == nil { |
| 555 | module = &Module{ |
| 556 | Name: "implicit", |
| 557 | Path: rsync.FileSystemRoot, |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | st := &sender.Transfer{ |
| 562 | Logger: s.logger, |
| 563 | Opts: opts, |
| 564 | Conn: c, |
| 565 | Seed: sessionChecksumSeed, |
| 566 | Env: &rsyncos.Env{ |
| 567 | Stderr: s.stderr, |
| 568 | }, |
| 569 | Progress: progress.NewPrinter(io.Discard, time.Now), |
| 570 | } |
| 571 | // receive the exclusion list (openrsync’s is always empty) |
| 572 | |
| 573 | if module.FS != nil { |
| 574 | st.Source = sender.NewFSSource(module.FS) |
| 575 | } |
| 576 | |
| 577 | exclusionList, err := sender.RecvFilterList(st.Conn) |
| 578 | if err != nil { |
| 579 | return err |
| 580 | } |
| 581 | st.Logger.Printf("exclusion list read (entries: %d)", len(exclusionList.Filters)) |
| 582 | |
| 583 | stats, err := st.Do(crd, cwr, module.Path, paths, exclusionList) |
| 584 | if err != nil { |
| 585 | return err |
| 586 | } |
| 587 | |
| 588 | s.logger.Printf("handleConnSender done. stats: %+v", stats) |
| 589 | |
| 590 | return nil |
| 591 | } |
| 592 | |
| 593 | func (s *Server) Serve(ctx context.Context, ln net.Listener) error { |
| 594 | go func() { |
| 595 | <-ctx.Done() |
| 596 | ln.Close() // unblocks Accept() |
| 597 | }() |
| 598 | |
| 599 | for { |
| 600 | conn, err := ln.Accept() |
| 601 | if err != nil { |
| 602 | select { |
| 603 | case <-ctx.Done(): |
| 604 | return nil // ignore expected 'use of closed network connection' error on context cancel |
| 605 | default: |
| 606 | return err |
| 607 | } |
| 608 | } |
| 609 | remoteAddr := conn.RemoteAddr() |
| 610 | s.logger.Printf("remote connection from %s", remoteAddr) |
| 611 | go func() { |
| 612 | defer conn.Close() |
| 613 | c := NewConnection(conn, conn, remoteAddr.String()) |
| 614 | if err := s.HandleDaemonConn(ctx, c); err != nil { |
| 615 | s.logger.Printf("[%s] handle: %v", remoteAddr, err) |
| 616 | } |
| 617 | }() |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | func validateModule(mod Module) error { |
| 622 | if mod.Name == "" { |
| 623 | return errors.New("module has no name") |
| 624 | } |
| 625 | if mod.FS != nil { |
| 626 | if mod.Writable { |
| 627 | return fmt.Errorf("module %q: FS modules cannot be writable", mod.Name) |
| 628 | } |
| 629 | if mod.Path != "" { |
| 630 | return fmt.Errorf("module %q: cannot specify both Path and FS", mod.Name) |
| 631 | } |
| 632 | } else { |
| 633 | if mod.Path == "" { |
| 634 | return fmt.Errorf("module %q has empty path", mod.Name) |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | return nil |
| 639 | } |