mirror.py-rsync-server 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,709 @@
1
+ """mirror.py event plug-in that generates rsyncd.conf and rsyncd.secrets.
2
+
3
+ Reads its own configuration from rsync.json located next to mirror.py's
4
+ config.json (mirror.config.CONFIG_PATH.parent / "rsync.json"), and regenerates
5
+ both rsyncd files when the daemon starts and on every config reload.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import os
12
+ import re
13
+ import stat
14
+ import tempfile
15
+ import threading
16
+ from pathlib import Path
17
+ from typing import Any, Iterable
18
+
19
+ import mirror
20
+ import mirror.config
21
+ import mirror.event
22
+ import mirror.plugin
23
+
24
+ NAME = "rsync-server"
25
+ RSYNC_CONFIG_FILENAME = "rsync.json"
26
+ CONF_HEADER = "# WARNING: DO NOT EDIT!! Generated by the mirror.py rsync-server plugin."
27
+ PRIVATE_COMMENT_TEMPLATE = "private module for {name} without connection limits for authorized mirrors"
28
+ DEFAULT_PRIVATE_MODULES: dict[str, Any] = {
29
+ "enabled": True,
30
+ "auth_users": "*",
31
+ "list": False,
32
+ "lock_file": "/var/run/rsyncd-private.lock",
33
+ }
34
+ DEFAULT_RSYNCD_CONF = "/etc/rsyncd.conf"
35
+ DEFAULT_SECRETS_FILE = "/etc/rsyncd.secrets"
36
+ MODULE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]*$")
37
+
38
+ log = logging.getLogger("mirror")
39
+ _generate_lock = threading.Lock()
40
+
41
+ # --- Config layer ---
42
+
43
+ _ALLOWED_TOP_LEVEL_KEYS = frozenset({"rsyncd_conf", "secrets_file", "users", "global", "private_modules"})
44
+ _ALLOWED_PRIVATE_MODULES_KEYS = frozenset({"enabled", "auth_users", "list", "lock_file"})
45
+
46
+
47
+ def resolve_rsync_config_path() -> Path:
48
+ """Return the expected path to rsync.json next to mirror.py's config.json.
49
+
50
+ Args:
51
+ (none)
52
+
53
+ Return:
54
+ path(Path): mirror.config.CONFIG_PATH.parent / RSYNC_CONFIG_FILENAME.
55
+ """
56
+ return mirror.config.CONFIG_PATH.parent / RSYNC_CONFIG_FILENAME
57
+
58
+
59
+ def load_rsync_config(path: Path) -> dict:
60
+ """Read, parse, and validate the rsync.json configuration file.
61
+
62
+ Args:
63
+ path(Path): Filesystem path to the rsync.json file.
64
+
65
+ Return:
66
+ config(dict): Normalized configuration dict with all keys present.
67
+
68
+ Raises:
69
+ ValueError: If the file cannot be read, contains invalid JSON, or
70
+ fails validation. The message includes the path but never file contents.
71
+ """
72
+ try:
73
+ text = path.read_text(encoding="utf-8")
74
+ except OSError as exc:
75
+ raise ValueError(f"Cannot read rsync config at {path}: {exc}") from exc
76
+
77
+ try:
78
+ raw = json.loads(text)
79
+ except json.JSONDecodeError as exc:
80
+ raise ValueError(f"Invalid JSON in rsync config at {path}: {exc}") from exc
81
+
82
+ return validate_rsync_config(raw)
83
+
84
+
85
+ def _is_control_char(ch: str) -> bool:
86
+ """Return True if ch is a C0 (ord < 32), DEL (0x7f), or C1 (0x80-0x9f) control character."""
87
+ code = ord(ch)
88
+ return code < 32 or 0x7F <= code <= 0x9F
89
+
90
+
91
+ def _has_control_chars(value: str) -> bool:
92
+ """Return True if value contains any C0, DEL, or C1 control character."""
93
+ return any(_is_control_char(ch) for ch in value)
94
+
95
+
96
+ def _validate_absolute_clean_path(value: object, field: str) -> str:
97
+ """Validate that value is a str, absolute path, and contains no control chars.
98
+
99
+ Args:
100
+ value(object): The value to check.
101
+ field(str): Field name for error messages.
102
+
103
+ Return:
104
+ path(str): The validated path string.
105
+ """
106
+ if not isinstance(value, str):
107
+ raise ValueError(f"{field!r} must be a str, got {type(value).__name__}")
108
+ if not os.path.isabs(value):
109
+ raise ValueError(f"{field!r} must be an absolute path, got {value!r}")
110
+ if _has_control_chars(value):
111
+ raise ValueError(f"{field!r} must not contain control characters")
112
+ return value
113
+
114
+
115
+ def validate_rsync_config(raw: dict) -> dict:
116
+ """Validate and normalize a parsed rsync.json dict.
117
+
118
+ Applies defaults for all optional keys, rejects unknown keys and any
119
+ value that could enable injection into rsyncd.conf.
120
+
121
+ Args:
122
+ raw(dict): Parsed JSON object from rsync.json.
123
+
124
+ Return:
125
+ config(dict): Normalized dict with keys: rsyncd_conf, secrets_file,
126
+ users, global, private_modules. All have validated values and
127
+ defaults applied where keys were absent.
128
+
129
+ Raises:
130
+ ValueError: On any structural or content violation.
131
+ """
132
+ if not isinstance(raw, dict):
133
+ raise ValueError(f"rsync.json root must be a dict, got {type(raw).__name__}")
134
+
135
+ for key in raw:
136
+ if key not in _ALLOWED_TOP_LEVEL_KEYS:
137
+ raise ValueError(f"Unknown key in rsync.json: {key!r}")
138
+
139
+ rsyncd_conf = _validate_absolute_clean_path(
140
+ raw.get("rsyncd_conf", DEFAULT_RSYNCD_CONF), "rsyncd_conf"
141
+ )
142
+ secrets_file = _validate_absolute_clean_path(
143
+ raw.get("secrets_file", DEFAULT_SECRETS_FILE), "secrets_file"
144
+ )
145
+
146
+ users = raw.get("users", {})
147
+ if not isinstance(users, dict):
148
+ raise ValueError(f"'users' must be a dict, got {type(users).__name__}")
149
+ validate_users(users)
150
+
151
+ global_params = raw.get("global", {})
152
+ if not isinstance(global_params, dict):
153
+ raise ValueError(f"'global' must be a dict, got {type(global_params).__name__}")
154
+ _validate_global_params(global_params)
155
+
156
+ private_modules_input = raw.get("private_modules", {})
157
+ if not isinstance(private_modules_input, dict):
158
+ raise ValueError(f"'private_modules' must be a dict, got {type(private_modules_input).__name__}")
159
+ private_modules = _validate_private_modules(private_modules_input)
160
+
161
+ return {
162
+ "rsyncd_conf": rsyncd_conf,
163
+ "secrets_file": secrets_file,
164
+ "users": users,
165
+ "global": global_params,
166
+ "private_modules": private_modules,
167
+ }
168
+
169
+
170
+ def _validate_global_params(global_params: dict) -> None:
171
+ """Validate all keys and values in the global rsyncd parameter dict."""
172
+ for key, value in global_params.items():
173
+ if not isinstance(key, str) or not key:
174
+ raise ValueError(f"'global' keys must be non-empty strings, got {key!r}")
175
+ if _has_control_chars(key):
176
+ raise ValueError(f"'global' key {key!r} must not contain control characters")
177
+ if "=" in key:
178
+ raise ValueError(f"'global' key {key!r} must not contain '='")
179
+ if key.lstrip().startswith("["):
180
+ raise ValueError(f"'global' key {key!r} must not start with '['")
181
+ if key.strip().lower() == "secrets file":
182
+ raise ValueError(
183
+ f"'global' key {key!r} is reserved; use the top-level 'secrets_file' key instead"
184
+ )
185
+ if not isinstance(value, (str, int, bool)):
186
+ raise ValueError(
187
+ f"'global' value for key {key!r} must be str, int, or bool, got {type(value).__name__}"
188
+ )
189
+ if isinstance(value, str) and _has_control_chars(value):
190
+ raise ValueError(f"'global' value for key {key!r} must not contain control characters")
191
+
192
+
193
+ def _validate_private_modules(provided: dict) -> dict:
194
+ """Validate private_modules overrides and merge with defaults.
195
+
196
+ Args:
197
+ provided(dict): Partial or full private_modules dict from rsync.json.
198
+
199
+ Return:
200
+ merged(dict): Defaults merged with validated provided values.
201
+ """
202
+ for key in provided:
203
+ if key not in _ALLOWED_PRIVATE_MODULES_KEYS:
204
+ raise ValueError(f"Unknown key in 'private_modules': {key!r}")
205
+
206
+ merged = dict(DEFAULT_PRIVATE_MODULES)
207
+ merged.update(provided)
208
+
209
+ if not isinstance(merged["enabled"], bool):
210
+ raise ValueError(f"'private_modules.enabled' must be bool, got {type(merged['enabled']).__name__}")
211
+ if not isinstance(merged["list"], bool):
212
+ raise ValueError(f"'private_modules.list' must be bool, got {type(merged['list']).__name__}")
213
+
214
+ auth_users = merged["auth_users"]
215
+ if not isinstance(auth_users, str):
216
+ raise ValueError(f"'private_modules.auth_users' must be str, got {type(auth_users).__name__}")
217
+ if _has_control_chars(auth_users):
218
+ raise ValueError("'private_modules.auth_users' must not contain control characters")
219
+
220
+ _validate_absolute_clean_path(merged["lock_file"], "private_modules.lock_file")
221
+
222
+ return merged
223
+
224
+
225
+ def validate_users(users: dict) -> None:
226
+ """Validate every username/password entry in the users dict.
227
+
228
+ Args:
229
+ users(dict): Mapping of username to password strings from rsync.json.
230
+
231
+ Return:
232
+ None
233
+
234
+ Raises:
235
+ ValueError: If any username is empty, contains ':' / whitespace /
236
+ control characters, or starts with '@' or '#'; or if any password
237
+ is not a non-empty string or contains any control character
238
+ (including CR/LF/TAB/DEL/C1). The message may name the offending
239
+ username but never contains the password value.
240
+ """
241
+ for username, password in users.items():
242
+ if not isinstance(username, str) or not username:
243
+ raise ValueError(f"Username must be a non-empty string, got {username!r}")
244
+ if ":" in username:
245
+ raise ValueError(f"Username {username!r} must not contain ':'")
246
+ if any(ch.isspace() for ch in username):
247
+ raise ValueError(f"Username {username!r} must not contain whitespace")
248
+ if _has_control_chars(username):
249
+ raise ValueError(f"Username {username!r} must not contain control characters")
250
+ if username[0] in ("@", "#"):
251
+ raise ValueError(f"Username {username!r} must not start with '@' or '#'")
252
+
253
+ if not isinstance(password, str) or not password:
254
+ raise ValueError(f"Invalid password for user {username!r}: must be a non-empty string")
255
+ if _has_control_chars(password):
256
+ raise ValueError(f"Invalid password for user {username!r}: must not contain control characters")
257
+
258
+
259
+ def check_config_permissions(path: Path) -> None:
260
+ """Warn if rsync.json is readable by group or other.
261
+
262
+ The file holds plaintext passwords, so group/other read access is a
263
+ security concern. This function only logs a warning; it never raises and
264
+ never logs the file contents.
265
+
266
+ Args:
267
+ path(Path): Filesystem path to the rsync.json file.
268
+
269
+ Return:
270
+ None
271
+ """
272
+ try:
273
+ result = os.stat(path)
274
+ if result.st_mode & 0o077:
275
+ log.warning(
276
+ "rsync.json at %s is group/other-readable; recommend chmod 600 "
277
+ "as it contains plaintext passwords",
278
+ path,
279
+ )
280
+ except OSError as exc:
281
+ log.debug("Could not stat rsync.json at %s: %s", path, exc)
282
+
283
+
284
+ # --- Pure text builders ---
285
+
286
+
287
+ def validate_module_name(name: str) -> bool:
288
+ """Return True iff name is a valid rsyncd module name.
289
+
290
+ A valid name must match MODULE_NAME_RE and must not equal "global"
291
+ case-insensitively (reserved section name in rsync >= 3.2).
292
+
293
+ Args:
294
+ name(str): The candidate module name to validate.
295
+
296
+ Return:
297
+ valid(bool): True if name passes all checks, False otherwise.
298
+ """
299
+ if not isinstance(name, str):
300
+ return False
301
+ if not MODULE_NAME_RE.match(name):
302
+ return False
303
+ if name.lower() == "global":
304
+ return False
305
+ return True
306
+
307
+
308
+ def sanitize_comment_value(value: str) -> str:
309
+ """Strip control characters and surrounding whitespace from value.
310
+
311
+ rsyncd.conf has no value escaping, so a newline in a comment value
312
+ would inject a new config line. This function removes all characters
313
+ with ord < 32 and strips leading/trailing whitespace.
314
+
315
+ Args:
316
+ value(str): The raw string to sanitize (e.g. pkg.settings.src).
317
+
318
+ Return:
319
+ cleaned(str): Single-line string with control chars removed and
320
+ surrounding whitespace stripped.
321
+ """
322
+ cleaned = "".join(ch for ch in value if not _is_control_char(ch))
323
+ return cleaned.strip()
324
+
325
+
326
+ def format_param(key: str, value: object) -> str:
327
+ """Render a single rsyncd.conf parameter line as 'key = value'.
328
+
329
+ Booleans are rendered as lowercase 'true' or 'false'. All other types
330
+ are converted via str(). Control characters are stripped from the
331
+ rendered value as defense in depth.
332
+
333
+ Args:
334
+ key(str): The rsyncd parameter name (e.g. 'max connections').
335
+ value(object): The parameter value. bool, int, or str.
336
+
337
+ Return:
338
+ line(str): A 'key = value' string with no indentation or trailing
339
+ newline.
340
+ """
341
+ if isinstance(value, bool):
342
+ rendered = "true" if value else "false"
343
+ else:
344
+ rendered = str(value)
345
+ rendered = "".join(ch for ch in rendered if not _is_control_char(ch))
346
+ return f"{key} = {rendered}"
347
+
348
+
349
+ def select_visible_packages(packages: Iterable) -> list:
350
+ """Filter and sort packages for emission into rsyncd.conf.
351
+
352
+ Applies the following rules in order:
353
+ - Packages where getattr(pkg.settings, 'hidden', False) is truthy are
354
+ silently skipped (hidden is intentional, no warning).
355
+ - Packages with an invalid module name (validate_module_name returns
356
+ False) are skipped with a log.warning.
357
+ - Packages with an empty, non-absolute, or control-char dst are skipped
358
+ with a log.warning.
359
+ - Among remaining packages, case-insensitive duplicate names are
360
+ resolved by keeping the first occurrence in sorted order and skipping
361
+ later duplicates with a log.warning naming both pkgids.
362
+
363
+ Args:
364
+ packages(Iterable): Iterable of package objects with attributes
365
+ pkgid (str), name (str), and settings with hidden (bool),
366
+ src (str), and dst (str).
367
+
368
+ Return:
369
+ visible(list): Packages that passed all checks, sorted by name
370
+ (case-sensitive).
371
+ """
372
+ # Sort first to make dedup deterministic (first in sorted order wins).
373
+ sorted_pkgs = sorted(packages, key=lambda p: p.name)
374
+
375
+ candidates = []
376
+ for pkg in sorted_pkgs:
377
+ if getattr(pkg.settings, "hidden", False):
378
+ continue
379
+
380
+ if not validate_module_name(pkg.name):
381
+ log.warning(
382
+ "Package %r has invalid module name %r; skipping",
383
+ pkg.pkgid,
384
+ pkg.name,
385
+ )
386
+ continue
387
+
388
+ dst = getattr(pkg.settings, "dst", "")
389
+ if not dst:
390
+ log.warning(
391
+ "Package %r has empty dst; skipping",
392
+ pkg.pkgid,
393
+ )
394
+ continue
395
+ if not os.path.isabs(dst):
396
+ log.warning(
397
+ "Package %r has non-absolute dst %r; skipping",
398
+ pkg.pkgid,
399
+ dst,
400
+ )
401
+ continue
402
+ if _has_control_chars(dst):
403
+ log.warning(
404
+ "Package %r has control characters in dst; skipping",
405
+ pkg.pkgid,
406
+ )
407
+ continue
408
+
409
+ candidates.append(pkg)
410
+
411
+ # Deduplicate by case-insensitive name; first occurrence (already sorted) wins.
412
+ seen: dict[str, str] = {}
413
+ visible = []
414
+ for pkg in candidates:
415
+ lower_name = pkg.name.lower()
416
+ if lower_name in seen:
417
+ log.warning(
418
+ "Package %r has duplicate module name (case-insensitive) with %r; skipping",
419
+ pkg.pkgid,
420
+ seen[lower_name],
421
+ )
422
+ continue
423
+ seen[lower_name] = pkg.pkgid
424
+ visible.append(pkg)
425
+
426
+ return visible
427
+
428
+
429
+ def build_global_section(global_params: dict, secrets_file: str) -> str:
430
+ """Build the global section of rsyncd.conf as a string.
431
+
432
+ The section starts with CONF_HEADER, followed by one 'key = value' line
433
+ per entry in global_params (insertion order preserved), then a blank
434
+ line, then 'secrets file = <secrets_file>'.
435
+
436
+ Args:
437
+ global_params(dict): Ordered dict of global rsyncd parameters.
438
+ secrets_file(str): Absolute path to the rsyncd.secrets file.
439
+
440
+ Return:
441
+ section(str): The global section text ending without a trailing
442
+ newline (caller adds separating blank lines as needed).
443
+ """
444
+ lines = [CONF_HEADER]
445
+ for key, value in global_params.items():
446
+ lines.append(format_param(key, value))
447
+ lines.append("")
448
+ lines.append(format_param("secrets file", secrets_file))
449
+ return "\n".join(lines)
450
+
451
+
452
+ def build_public_module(pkg: Any) -> str:
453
+ """Build the public module block for a package.
454
+
455
+ The block has no surrounding blank lines. Format:
456
+ [<pkg.name>]
457
+ path = <pkg.settings.dst>
458
+ comment = from <sanitized pkg.settings.src> (omitted if src is empty)
459
+
460
+ Args:
461
+ pkg: Package object with name (str) and settings.dst (str) and
462
+ settings.src (str).
463
+
464
+ Return:
465
+ block(str): The module block text with no trailing newline.
466
+ """
467
+ lines = [f"[{pkg.name}]"]
468
+ lines.append(f" {format_param('path', pkg.settings.dst)}")
469
+ src = getattr(pkg.settings, "src", "")
470
+ if src:
471
+ sanitized = sanitize_comment_value(src)
472
+ lines.append(f" {format_param('comment', f'from {sanitized}')}")
473
+ return "\n".join(lines)
474
+
475
+
476
+ def build_private_module(pkg: Any, private_modules: dict) -> str:
477
+ """Build the private module block for a package.
478
+
479
+ The block has no surrounding blank lines. Format:
480
+ [.<pkg.name>]
481
+ path = <pkg.settings.dst>
482
+ comment = private module for <pkg.name> without connection limits for authorized mirrors
483
+ auth users = <auth_users>
484
+ list = <list as true/false>
485
+ lock file = <lock_file>
486
+
487
+ Args:
488
+ pkg: Package object with name (str) and settings.dst (str).
489
+ private_modules(dict): Private module config with keys auth_users
490
+ (str), list (bool), and lock_file (str).
491
+
492
+ Return:
493
+ block(str): The private module block text with no trailing newline.
494
+ """
495
+ comment = PRIVATE_COMMENT_TEMPLATE.format(name=pkg.name)
496
+ lines = [
497
+ f"[.{pkg.name}]",
498
+ f" {format_param('path', pkg.settings.dst)}",
499
+ f" {format_param('comment', comment)}",
500
+ f" {format_param('auth users', private_modules['auth_users'])}",
501
+ f" {format_param('list', private_modules['list'])}",
502
+ f" {format_param('lock file', private_modules['lock_file'])}",
503
+ ]
504
+ return "\n".join(lines)
505
+
506
+
507
+ def build_rsyncd_conf(packages: Iterable, config: dict) -> str:
508
+ """Build the complete rsyncd.conf content as a string.
509
+
510
+ Structure: global section, then for each visible package a blank line
511
+ followed by the public module block; if private_modules is enabled,
512
+ a blank line followed by the private module block. The document ends
513
+ with exactly one trailing newline.
514
+
515
+ Args:
516
+ packages(Iterable): All packages; select_visible_packages filters
517
+ and sorts them before use.
518
+ config(dict): Validated config dict with keys 'global',
519
+ 'secrets_file', and 'private_modules'.
520
+
521
+ Return:
522
+ content(str): Complete rsyncd.conf content ending with a single
523
+ newline character.
524
+ """
525
+ parts = [build_global_section(config["global"], config["secrets_file"])]
526
+
527
+ visible = select_visible_packages(packages)
528
+ private_enabled = config["private_modules"]["enabled"]
529
+
530
+ for pkg in visible:
531
+ parts.append("")
532
+ parts.append(build_public_module(pkg))
533
+ if private_enabled:
534
+ parts.append("")
535
+ parts.append(build_private_module(pkg, config["private_modules"]))
536
+
537
+ return "\n".join(parts) + "\n"
538
+
539
+
540
+ def build_rsyncd_secrets(users: dict) -> str:
541
+ """Build the complete rsyncd.secrets content as a string.
542
+
543
+ One 'username:password\\n' line per entry in insertion order. Returns
544
+ an empty string when users is empty. No header is emitted; rsyncd
545
+ secrets files are plain user:pass lines.
546
+
547
+ Args:
548
+ users(dict): Mapping of username to password strings.
549
+
550
+ Return:
551
+ content(str): The secrets file content, or '' if users is empty.
552
+ """
553
+ if not users:
554
+ return ""
555
+ return "".join(f"{username}:{password}\n" for username, password in users.items())
556
+
557
+
558
+ # --- I/O layer ---
559
+
560
+
561
+ def write_file_atomic(path: Path, content: str, mode: int) -> bool:
562
+ """Write content to path atomically, skipping the write if content is unchanged.
563
+
564
+ If the target file already exists and its content equals the provided
565
+ content, the file is not rewritten. However, if the existing file mode
566
+ differs from mode, os.chmod is called to repair it. Returns False in
567
+ that case.
568
+
569
+ Otherwise, creates parent directories as needed, writes content to a
570
+ temporary file in the same directory (created via tempfile.mkstemp at
571
+ mode 0600 so secret content is never transiently world-readable), sets
572
+ the target mode on the temp file, then atomically replaces the target.
573
+ On any failure, the temp file is removed (best-effort) and the exception
574
+ is re-raised. Returns True when a write occurred.
575
+
576
+ Args:
577
+ path(Path): Destination file path.
578
+ content(str): UTF-8 text content to write.
579
+ mode(int): Target file permission bits (e.g. 0o600 or 0o644).
580
+
581
+ Return:
582
+ written(bool): True if the file was (re)written, False if content
583
+ was identical and only a possible mode repair was performed.
584
+ """
585
+ try:
586
+ existing = path.read_text(encoding="utf-8")
587
+ except OSError:
588
+ existing = None
589
+
590
+ if existing is not None and existing == content:
591
+ current_mode = stat.S_IMODE(os.stat(path).st_mode)
592
+ if current_mode != mode:
593
+ os.chmod(path, mode)
594
+ return False
595
+
596
+ path.parent.mkdir(parents=True, exist_ok=True)
597
+ fd, tmp_name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
598
+ try:
599
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
600
+ fh.write(content)
601
+ os.chmod(tmp_name, mode)
602
+ os.replace(tmp_name, path)
603
+ except Exception:
604
+ try:
605
+ os.unlink(tmp_name)
606
+ except OSError:
607
+ pass
608
+ raise
609
+ return True
610
+
611
+
612
+ def regenerate_rsync_files(packages: Iterable, config: dict) -> None:
613
+ """Write rsyncd.secrets and rsyncd.conf from the current package list and config.
614
+
615
+ Secrets are written first because rsyncd.conf references the secrets
616
+ path; the referenced file must be current before the conf lands so that
617
+ a partial failure (e.g. disk full after writing secrets) leaves the
618
+ previous conf intact rather than pointing at a stale secrets file.
619
+
620
+ Args:
621
+ packages(Iterable): Iterable of package objects passed to
622
+ build_rsyncd_conf via select_visible_packages.
623
+ config(dict): Validated config dict with keys 'users',
624
+ 'secrets_file', 'rsyncd_conf', 'global', and 'private_modules'.
625
+
626
+ Return:
627
+ None
628
+ """
629
+ secrets_text = build_rsyncd_secrets(config["users"])
630
+ write_file_atomic(Path(config["secrets_file"]), secrets_text, 0o600)
631
+
632
+ conf_text = build_rsyncd_conf(packages, config)
633
+ write_file_atomic(Path(config["rsyncd_conf"]), conf_text, 0o644)
634
+
635
+
636
+ # --- Event / lifecycle layer ---
637
+
638
+
639
+ def handle_regenerate_event(*args: object, **kwargs: object) -> None:
640
+ """Regenerate rsyncd.conf and rsyncd.secrets in response to a mirror event.
641
+
642
+ Intended as a listener for MASTER.INIT.POST and MASTER.CONFIG_RELOAD.POST.
643
+ The signature accepts arbitrary positional and keyword arguments because
644
+ the event payload format is not finalized; all arguments are ignored.
645
+
646
+ Reads mirror.packages and the rsync.json config path fresh at event time
647
+ (never cached). The entire body runs under _generate_lock so concurrent
648
+ event firings are serialized. All exceptions are caught and logged; the
649
+ function never re-raises so a generation failure cannot disturb other
650
+ listeners or the daemon, and previously generated files are left intact.
651
+
652
+ Args:
653
+ *args: Ignored event payload positional arguments.
654
+ **kwargs: Ignored event payload keyword arguments.
655
+
656
+ Return:
657
+ None
658
+ """
659
+ with _generate_lock:
660
+ try:
661
+ path = resolve_rsync_config_path()
662
+ config = load_rsync_config(path)
663
+ check_config_permissions(path)
664
+ packages = getattr(mirror, "packages", None)
665
+ if packages is None:
666
+ log.warning("mirror.packages is not available; skipping rsync file generation")
667
+ return
668
+ regenerate_rsync_files(list(packages.values()), config)
669
+ except Exception as exc:
670
+ log.error(
671
+ "rsync-server plugin: failed to regenerate files: %s: %s",
672
+ type(exc).__name__,
673
+ exc,
674
+ )
675
+
676
+
677
+ def setup() -> None:
678
+ """Register handle_regenerate_event for daemon start and config reload events.
679
+
680
+ Registers the listener for both MASTER.INIT.POST (daemon start) and
681
+ MASTER.CONFIG_RELOAD.POST (config reload). This function performs no I/O;
682
+ it only wires up listeners so it is safe to call in every process
683
+ (including short-lived CLI runs).
684
+
685
+ Args:
686
+ (none)
687
+
688
+ Return:
689
+ None
690
+ """
691
+ mirror.event.on("MASTER.INIT.POST", handle_regenerate_event)
692
+ mirror.event.on("MASTER.CONFIG_RELOAD.POST", handle_regenerate_event)
693
+
694
+
695
+ def plugin() -> "mirror.plugin.PluginRecord":
696
+ """Return the mirror.py event plugin record for the rsync-server plugin.
697
+
698
+ Uses a lazy import of mirror.plugin.event_plugin to match the pattern
699
+ established by the mirror-plugin-echo example.
700
+
701
+ Args:
702
+ (none)
703
+
704
+ Return:
705
+ record(mirror.plugin.PluginRecord): Plugin record with name 'rsync-server',
706
+ type 'event', and setup pointing to the setup function.
707
+ """
708
+ from mirror.plugin import event_plugin
709
+ return event_plugin(name=NAME, setup=setup)
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: mirror.py-rsync-server
3
+ Version: 1.0.0
4
+ Summary: mirror.py event plug-in that generates rsyncd.conf and rsyncd.secrets from the package list.
5
+ Author: SPARCS KAIST
6
+ License-Expression: Apache-2.0
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: mirror.py>=1.0.0
11
+ Dynamic: license-file
12
+
13
+ # mirror.py rsync-server plugin
14
+
15
+ An event plugin for [mirror.py](https://github.com/sparcs-kaist/mirror.py) that generates
16
+ `rsyncd.conf` and `rsyncd.secrets` from the live mirror package list plus a sidecar
17
+ `rsync.json` configuration file. The plugin regenerates both files automatically when the
18
+ mirror daemon starts (`MASTER.INIT.POST`) and whenever the package set changes via
19
+ `mirror config reload` (`MASTER.CONFIG_RELOAD.POST`).
20
+
21
+
22
+ ## How it works
23
+
24
+ The plugin listens on two mirror.py events:
25
+
26
+ - `MASTER.INIT.POST` — fires once when the master daemon finishes starting up.
27
+ - `MASTER.CONFIG_RELOAD.POST` — fires after `mirror config reload` has loaded a new
28
+ configuration. Until the mirror.py core ships this event, regeneration happens at
29
+ daemon start only; the listener signature accepts `(*args, **kwargs)` so it is
30
+ forward-compatible.
31
+
32
+ **File generation only.** The plugin writes `rsyncd.conf` and `rsyncd.secrets`; it does
33
+ not start, stop, or signal the rsyncd process. This is intentional: rsyncd re-reads
34
+ `rsyncd.conf` and the secrets file on every incoming client connection, so adding or
35
+ removing mirror modules takes effect immediately with no reload signal needed.
36
+
37
+ Writes are atomic (via a temporary file in the same directory followed by `os.replace`).
38
+ If the generated content is identical to what is already on disk, the file is not
39
+ rewritten. Regeneration runs under a module-level lock so concurrent event firings do not
40
+ race.
41
+
42
+ Packages with `settings.hidden: true` are completely excluded — they appear in neither
43
+ the public nor the private module list.
44
+
45
+
46
+ ## Installation
47
+
48
+ Install the plugin into the same Python environment as mirror.py:
49
+
50
+ ```
51
+ pip install -e .
52
+ ```
53
+
54
+ Enable the plugin in mirror.py's `config.json`:
55
+
56
+ ```json
57
+ "plugins": { "rsync-server": { "enabled": true } }
58
+ ```
59
+
60
+ The plugin's own settings live in `rsync.json`, **not** in the `plugins` block of
61
+ `config.json`. See the Configuration section below.
62
+
63
+
64
+ ## Configuration
65
+
66
+ `rsync.json` must live in the same directory as mirror.py's `config.json` (default path:
67
+ `/etc/mirror/rsync.json`).
68
+
69
+ See [`rsync.json.example`](rsync.json.example) for a complete, realistic example.
70
+
71
+ All keys are optional and fall back to the defaults listed below.
72
+
73
+ | Key | Type | Default | Description |
74
+ |-----|------|---------|-------------|
75
+ | `rsyncd_conf` | string (absolute path) | `/etc/rsyncd.conf` | Destination path for the generated `rsyncd.conf`. |
76
+ | `secrets_file` | string (absolute path) | `/etc/rsyncd.secrets` | Destination path for the generated secrets file. Also emitted as `secrets file` in the global section of `rsyncd.conf`. |
77
+ | `users` | object | `{}` | Map of `username` to `password`. Written to the secrets file in insertion order. |
78
+ | `global` | object | `{}` | Raw rsyncd parameter passthrough. Keys and values are emitted in insertion order as `key = value` lines in the global section. Values may be strings, integers, or booleans (booleans render as `true`/`false`). The key `secrets file` is managed by the plugin and is rejected if placed here. |
79
+ | `private_modules.enabled` | boolean | `true` | When `false`, no `[.Name]` private module sections are generated. |
80
+ | `private_modules.auth_users` | string | `*` | Value written to `auth users` in every private module section. |
81
+ | `private_modules.list` | boolean | `false` | Value written to `list` in every private module section. |
82
+ | `private_modules.lock_file` | string (absolute path) | `/var/run/rsyncd-private.lock` | Value written to `lock file` in every private module section. The private modules share this lock file, giving them a separate max-connections accounting pool independent of the public modules. |
83
+
84
+ Unknown top-level keys and unknown `private_modules` keys are rejected with a `ValueError`
85
+ at load time (typo protection). Any validation failure leaves previously generated files
86
+ untouched.
87
+
88
+ **SECURITY NOTE:** `rsync.json` contains plaintext passwords. Restrict its permissions:
89
+
90
+ ```
91
+ chmod 600 /etc/mirror/rsync.json
92
+ ```
93
+
94
+ The plugin logs a warning if `rsync.json` is group- or other-readable. The generated
95
+ `rsyncd.secrets` file is always written with mode `0600`, as required by rsyncd's strict
96
+ modes.
97
+
98
+
99
+ ## Generated output
100
+
101
+ Given a package named `ArchLinux` with `src = rsync://rsync.archlinux.org/ftp_tier1` and
102
+ `dst = /mirror/ftp/ArchLinux`, and the global settings from `rsync.json.example`, the
103
+ plugin produces:
104
+
105
+ ```
106
+ # WARNING: DO NOT EDIT!! Generated by the mirror.py rsync-server plugin.
107
+ uid = rsync
108
+ gid = nogroup
109
+ use chroot = no
110
+ max connections = 20
111
+ motd file = /mirror/etc/motd
112
+ log file = /var/log/geoul/rsyncd/all.log
113
+ transfer logging = yes
114
+ log format = %o %a - %u [%t] "%P/%f" - %l
115
+ pid file = /var/run/rsyncd.pid
116
+ exclude = .~tmp~
117
+
118
+ secrets file = /mirror/etc/rsyncd.secrets
119
+
120
+ [ArchLinux]
121
+ path = /mirror/ftp/ArchLinux
122
+ comment = from rsync://rsync.archlinux.org/ftp_tier1
123
+
124
+ [.ArchLinux]
125
+ path = /mirror/ftp/ArchLinux
126
+ comment = private module for ArchLinux without connection limits for authorized mirrors
127
+ auth users = *
128
+ list = false
129
+ lock file = /var/run/rsyncd-private.lock
130
+ ```
131
+
132
+ Each package produces a public/private module pair:
133
+
134
+ - `[Name]` is the public module. It is visible in `rsync host::` listings and carries a
135
+ `comment = from <upstream src>` line. The comment line is omitted when a package has
136
+ no upstream `src` (for example, locally synced packages).
137
+ - `[.Name]` is the authenticated, unlisted private twin. The leading dot hides it from
138
+ `rsync host::` listings. Access is gated by `auth users` and the secrets file. This
139
+ module has its own lock file, so its connection accounting is independent of the public
140
+ module's `max connections` limit.
141
+
142
+ Modules are sorted by package name. The static header contains no timestamp so that
143
+ identical content is detected and the file is not rewritten unnecessarily.
144
+
145
+ The secrets file (`rsyncd.secrets`) contains one `username:password` line per entry in
146
+ `users`, written in insertion order, with no header line.
147
+
148
+
149
+ ## Running rsyncd
150
+
151
+ Point rsyncd at the generated configuration file:
152
+
153
+ ```
154
+ rsync --daemon --config=/etc/rsyncd.conf
155
+ ```
156
+
157
+
158
+ ## Operational notes
159
+
160
+ **Changing users or rsync settings.** Edit `rsync.json`, then run:
161
+
162
+ ```
163
+ mirror config reload
164
+ ```
165
+
166
+ No daemon restart is needed for module or authentication changes. rsyncd picks up the
167
+ new `rsyncd.conf` and `rsyncd.secrets` on the next incoming client connection.
168
+
169
+ **Parameters that require an rsyncd restart.** Daemon-socket parameters such as `port`,
170
+ `address`, and `pid file` are read by rsyncd only at startup. Changing them in `rsync.json`
171
+ and running `mirror config reload` will update the generated file, but rsyncd itself must
172
+ be restarted for these to take effect. Module-level parameters (path, auth, comment, etc.)
173
+ apply per connection and do not require a restart.
174
+
175
+ **Private module connection accounting.** The private modules share the lock file
176
+ specified by `private_modules.lock_file`. This gives them a separate max-connections pool
177
+ rather than unlimited connections — the pool size is controlled by rsyncd's global
178
+ `max connections` parameter applied against that lock file independently from the public
179
+ modules' lock file.
180
+
181
+
182
+ ## Development
183
+
184
+ Set up a virtual environment and install the plugin alongside mirror.py:
185
+
186
+ ```
187
+ uv venv
188
+ uv pip install -e /path/to/mirror.py -e . pytest
189
+ ```
190
+
191
+ Run the test suite:
192
+
193
+ ```
194
+ uv run pytest
195
+ ```
196
+
197
+
198
+ ## License
199
+
200
+ Apache-2.0
@@ -0,0 +1,7 @@
1
+ mirror_plugin_rsync_server/__init__.py,sha256=TPEzzFqC9L9iucw2DEoYkj2ARP3k547L1bx2Wdq3XJE,25497
2
+ mirror_py_rsync_server-1.0.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
3
+ mirror_py_rsync_server-1.0.0.dist-info/METADATA,sha256=kk2yxiu6TSQbdp7zHwiHiActyOI3XPGtzDi7kx6DvUI,7753
4
+ mirror_py_rsync_server-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
5
+ mirror_py_rsync_server-1.0.0.dist-info/entry_points.txt,sha256=Q1CthoVj78o0FpA37gSO21Fn3yZyujCT6prXTspmQkI,64
6
+ mirror_py_rsync_server-1.0.0.dist-info/top_level.txt,sha256=5EV53MtYI9Nf9LFEfoLkATAHCkK3koIwagqpA5d6he4,27
7
+ mirror_py_rsync_server-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [mirror.event]
2
+ rsync-server = mirror_plugin_rsync_server:plugin
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ mirror_plugin_rsync_server