| 1 |
|
| 2 |
"""Minimal pure-Python implementation of the rsync *client/sender* side of the |
| 3 |
daemon protocol -- enough to push a (possibly malformed) file list to a real |
| 4 |
rsync daemon receiver over a TCP socket. |
| 5 |
|
| 6 |
Why this exists |
| 7 |
--------------- |
| 8 |
Several rsync security fixes are for crashes the receiver hits while parsing a |
| 9 |
file list that no cooperating sender would ever produce. The historical way to |
| 10 |
test them was build_patched_rsync(): copy the source, string-replace a line in |
| 11 |
the sender, recompile. That is slow (a full rsync rebuild per test) and brittle |
| 12 |
(it breaks when the patched line is refactored). This module replaces that with |
| 13 |
a declarative wire-format speaker: encode a normal file entry, then flip one |
| 14 |
field. |
| 15 |
|
| 16 |
Design notes / scope |
| 17 |
-------------------- |
| 18 |
* It is pinned to protocol 30 and advertises NO optional client capabilities |
| 19 |
(no 'i' => no inc_recurse, no 'v' => byte/short flist flags and no string |
| 20 |
negotiation), which keeps the encoding surface small. Per send_file_entry() |
| 21 |
/ setup_protocol() in the C source. If the on-wire protocol changes, the |
| 22 |
constants and encoders here must be regenerated -- this is deliberately a |
| 23 |
second implementation kept tiny for that reason. |
| 24 |
* The integer encoders are byte-for-byte ports of io.c (write_varint / |
| 25 |
write_varlong / read_varint / read_int), so the bytes match the C exactly. |
| 26 |
* It is structured as a fuzzing substrate: FileEntry holds each field |
| 27 |
separately and every field (or the whole entry) can be overridden with raw |
| 28 |
bytes, so a future fuzzer can mutate one field at a time. |
| 29 |
|
| 30 |
This is test-only code; it is not built or shipped. |
| 31 |
""" |
| 32 |
|
| 33 |
import socket |
| 34 |
import struct |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
MPLEX_BASE = 7 |
| 40 |
MSG_DATA = 0 |
| 41 |
MSG_ERROR_XFER = 1 |
| 42 |
MSG_INFO = 2 |
| 43 |
MSG_ERROR = 3 |
| 44 |
MSG_WARNING = 4 |
| 45 |
MSG_DELETED = 101 |
| 46 |
MSG_NO_SEND = 102 |
| 47 |
|
| 48 |
|
| 49 |
XMIT_TOP_DIR = 1 << 0 |
| 50 |
XMIT_SAME_MODE = 1 << 1 |
| 51 |
XMIT_EXTENDED_FLAGS = 1 << 2 |
| 52 |
XMIT_SAME_UID = 1 << 3 |
| 53 |
XMIT_SAME_GID = 1 << 4 |
| 54 |
XMIT_SAME_NAME = 1 << 5 |
| 55 |
XMIT_LONG_NAME = 1 << 6 |
| 56 |
XMIT_SAME_TIME = 1 << 7 |
| 57 |
XMIT_SAME_RDEV_MAJOR = 1 << 8 |
| 58 |
XMIT_NO_CONTENT_DIR = 1 << 8 |
| 59 |
XMIT_HLINKED = 1 << 9 |
| 60 |
XMIT_USER_NAME_FOLLOWS = 1 << 10 |
| 61 |
XMIT_GROUP_NAME_FOLLOWS = 1 << 11 |
| 62 |
XMIT_HLINK_FIRST = 1 << 12 |
| 63 |
XMIT_MOD_NSEC = 1 << 13 |
| 64 |
|
| 65 |
|
| 66 |
S_IFREG = 0o100000 |
| 67 |
S_IFDIR = 0o040000 |
| 68 |
S_IFLNK = 0o120000 |
| 69 |
S_IFMT = 0o170000 |
| 70 |
|
| 71 |
|
| 72 |
def S_ISREG(m): |
| 73 |
return (m & S_IFMT) == S_IFREG |
| 74 |
|
| 75 |
|
| 76 |
def S_ISDIR(m): |
| 77 |
return (m & S_IFMT) == S_IFDIR |
| 78 |
|
| 79 |
|
| 80 |
def S_ISLNK(m): |
| 81 |
return (m & S_IFMT) == S_IFLNK |
| 82 |
|
| 83 |
|
| 84 |
DEFAULT_PROTOCOL = 30 |
| 85 |
|
| 86 |
NDX_DONE = -1 |
| 87 |
NDX_FLIST_EOF = -2 |
| 88 |
NDX_FLIST_OFFSET = -101 |
| 89 |
|
| 90 |
|
| 91 |
ITEM_BASIS_TYPE_FOLLOWS = 1 << 11 |
| 92 |
ITEM_XNAME_FOLLOWS = 1 << 12 |
| 93 |
ITEM_IS_NEW = 1 << 13 |
| 94 |
ITEM_TRANSFER = 1 << 15 |
| 95 |
FNAMECMP_FNAME = 0x80 |
| 96 |
FNAMECMP_FUZZY = 0x83 |
| 97 |
|
| 98 |
CHUNK_SIZE = 32 * 1024 |
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
def w_byte(x): |
| 105 |
return bytes([x & 0xFF]) |
| 106 |
|
| 107 |
|
| 108 |
def w_shortint(x): |
| 109 |
return struct.pack('<H', x & 0xFFFF) |
| 110 |
|
| 111 |
|
| 112 |
def w_int(x): |
| 113 |
return struct.pack('<i', _s32(x)) |
| 114 |
|
| 115 |
|
| 116 |
def _s32(x): |
| 117 |
x &= 0xFFFFFFFF |
| 118 |
return x - (1 << 32) if x & 0x80000000 else x |
| 119 |
|
| 120 |
|
| 121 |
def w_varint(x): |
| 122 |
"""Port of io.c write_varint(): SIVAL the value into b[1..4] (little-endian), |
| 123 |
then pack the high bits / extra-byte count into the leading byte b[0].""" |
| 124 |
b = bytearray(5) |
| 125 |
v = x & 0xFFFFFFFF |
| 126 |
b[1] = v & 0xFF |
| 127 |
b[2] = (v >> 8) & 0xFF |
| 128 |
b[3] = (v >> 16) & 0xFF |
| 129 |
b[4] = (v >> 24) & 0xFF |
| 130 |
cnt = 4 |
| 131 |
while cnt > 1 and b[cnt] == 0: |
| 132 |
cnt -= 1 |
| 133 |
bit = 1 << (7 - cnt + 1) |
| 134 |
if b[cnt] >= bit: |
| 135 |
cnt += 1 |
| 136 |
b[0] = (~(bit - 1)) & 0xFF |
| 137 |
elif cnt > 1: |
| 138 |
b[0] = (b[cnt] | ((~(bit * 2 - 1)) & 0xFF)) & 0xFF |
| 139 |
else: |
| 140 |
b[0] = b[1] |
| 141 |
return bytes(b[:cnt]) |
| 142 |
|
| 143 |
|
| 144 |
def w_varlong(x, min_bytes): |
| 145 |
"""Port of io.c write_varlong().""" |
| 146 |
b = bytearray(9) |
| 147 |
v = x & ((1 << 64) - 1) |
| 148 |
for i in range(8): |
| 149 |
b[1 + i] = (v >> (8 * i)) & 0xFF |
| 150 |
cnt = 8 |
| 151 |
while cnt > min_bytes and b[cnt] == 0: |
| 152 |
cnt -= 1 |
| 153 |
bit = 1 << (7 - cnt + min_bytes) |
| 154 |
if b[cnt] >= bit: |
| 155 |
cnt += 1 |
| 156 |
b[0] = (~(bit - 1)) & 0xFF |
| 157 |
elif cnt > min_bytes: |
| 158 |
b[0] = (b[cnt] | ((~(bit * 2 - 1)) & 0xFF)) & 0xFF |
| 159 |
else: |
| 160 |
b[0] = b[cnt] |
| 161 |
return bytes(b[:cnt]) |
| 162 |
|
| 163 |
|
| 164 |
def w_varint30(x, protocol=DEFAULT_PROTOCOL): |
| 165 |
|
| 166 |
return w_varint(x) if protocol >= 30 else w_int(x) |
| 167 |
|
| 168 |
|
| 169 |
def w_varlong30(x, min_bytes, protocol=DEFAULT_PROTOCOL): |
| 170 |
return w_varlong(x, min_bytes) if protocol >= 30 else w_int(x) |
| 171 |
|
| 172 |
|
| 173 |
_INT_BYTE_EXTRA = ([0] * 32) + ([1] * 16) + ([2] * 8) + ([3] * 4) + ([4] * 2) + [5, 6] |
| 174 |
|
| 175 |
|
| 176 |
def to_wire_mode(mode): |
| 177 |
|
| 178 |
return mode |
| 179 |
|
| 180 |
|
| 181 |
def w_sum_head(count, blength, s2length, remainder): |
| 182 |
"""io.c write_sum_head() at protocol >= 27: 4 ints.""" |
| 183 |
return w_int(count) + w_int(blength) + w_int(s2length) + w_int(remainder) |
| 184 |
|
| 185 |
|
| 186 |
def get_checksum1(buf): |
| 187 |
"""Port of checksum.c get_checksum1() (CHAR_OFFSET == 0): rsync's rolling |
| 188 |
block checksum (sum1). `buf` is bytes; the bytes are signed-char and the |
| 189 |
accumulators are uint32 (wrapping), matching the C exactly.""" |
| 190 |
if isinstance(buf, str): |
| 191 |
buf = buf.encode() |
| 192 |
sb = [c - 256 if c >= 128 else c for c in buf] |
| 193 |
n = len(sb) |
| 194 |
s1 = s2 = 0 |
| 195 |
i = 0 |
| 196 |
while i < n - 4: |
| 197 |
s2 = (s2 + 4 * (s1 + sb[i]) + 3 * sb[i + 1] + 2 * sb[i + 2] + sb[i + 3]) & 0xFFFFFFFF |
| 198 |
s1 = (s1 + sb[i] + sb[i + 1] + sb[i + 2] + sb[i + 3]) & 0xFFFFFFFF |
| 199 |
i += 4 |
| 200 |
while i < n: |
| 201 |
s1 = (s1 + sb[i]) & 0xFFFFFFFF |
| 202 |
s2 = (s2 + s1) & 0xFFFFFFFF |
| 203 |
i += 1 |
| 204 |
return ((s1 & 0xFFFF) + ((s2 & 0xFFFF) << 16)) & 0xFFFFFFFF |
| 205 |
|
| 206 |
|
| 207 |
def w_vstring(s): |
| 208 |
"""io.c write_vstring(): a 1- or 2-byte length prefix then the bytes.""" |
| 209 |
if isinstance(s, str): |
| 210 |
s = s.encode() |
| 211 |
n = len(s) |
| 212 |
if n > 0x7F: |
| 213 |
return bytes([n // 0x100 + 0x80, n & 0xFF]) + s |
| 214 |
return bytes([n]) + s |
| 215 |
|
| 216 |
|
| 217 |
_PERM_BITS = [ |
| 218 |
(S_IFDIR, 'd'), (S_IFLNK, 'l'), (0o020000, 'c'), (0o060000, 'b'), |
| 219 |
(0o010000, 'p'), (0o140000, 's'), |
| 220 |
] |
| 221 |
|
| 222 |
|
| 223 |
def sort_key(entry): |
| 224 |
"""Approximate rsync's f_name_cmp ordering: bytewise on the name, with a |
| 225 |
directory keyed as if it had a trailing '/' so it sorts immediately before |
| 226 |
its contents (and a file foo.txt before a dir foo). Good for flat lists and |
| 227 |
simple trees; not the full path-state machine.""" |
| 228 |
return entry.name + (b'/' if entry.is_dir else b'') |
| 229 |
|
| 230 |
|
| 231 |
def sort_entries(entries): |
| 232 |
"""rsync sorts the received file list before indexing it, so the transfer |
| 233 |
ndx is the sorted position, not the wire position. Return entries in that |
| 234 |
order.""" |
| 235 |
return sorted(entries, key=sort_key) |
| 236 |
|
| 237 |
|
| 238 |
def mode_to_perms(mode): |
| 239 |
"""An ls-style permission string, e.g. '-rw-r--r--' / 'drwxr-xr-x'.""" |
| 240 |
typ = '-' |
| 241 |
for bits, ch in _PERM_BITS: |
| 242 |
if (mode & S_IFMT) == bits: |
| 243 |
typ = ch |
| 244 |
break |
| 245 |
out = [typ] |
| 246 |
for who in (6, 3, 0): |
| 247 |
out.append('r' if mode & (4 << who) else '-') |
| 248 |
out.append('w' if mode & (2 << who) else '-') |
| 249 |
out.append('x' if mode & (1 << who) else '-') |
| 250 |
return ''.join(out) |
| 251 |
|
| 252 |
|
| 253 |
def xattr_list_wire(items): |
| 254 |
"""xattrs.c send_xattr() wire bytes for a NEW xattr list -- the form a |
| 255 |
sender appends to a file-list entry under -X. The leading 0 (ndx+1 with |
| 256 |
ndx=-1) means 'literal data follows'. `items` is a list of (name, |
| 257 |
datum_len, datum): `name` includes any namespace prefix and a trailing NUL, |
| 258 |
`datum_len` is the declared value length (need not match `datum`), and |
| 259 |
`datum` is the literal trailing bytes. A peer exercising the receiver's |
| 260 |
datum_len cap can pass an empty `datum` since receive_xattr() validates |
| 261 |
datum_len before it reads the value.""" |
| 262 |
out = bytearray(w_varint(0) + w_varint(len(items))) |
| 263 |
for name, datum_len, datum in items: |
| 264 |
if isinstance(name, str): |
| 265 |
name = name.encode() |
| 266 |
out += w_varint(len(name)) + w_varint(datum_len) + name + datum |
| 267 |
return bytes(out) |
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
class FileEntry: |
| 275 |
"""One flat (non-inc-recurse) file-list entry. |
| 276 |
|
| 277 |
Set the fields you care about; encode() emits the exact wire bytes for |
| 278 |
protocol 30 with byte/short flags. For malformed-input testing, set |
| 279 |
extra_flags to OR bits into the computed xflags, or set raw= to emit a |
| 280 |
fully hand-built byte string instead. |
| 281 |
""" |
| 282 |
|
| 283 |
def __init__(self, name, *, mode=S_IFREG | 0o644, length=0, modtime=1700000000, |
| 284 |
csum=None, extra_flags=0, protocol=DEFAULT_PROTOCOL, raw=None, |
| 285 |
hlink_ndx=None, uid=None, user_name=None): |
| 286 |
self.name = name.encode() if isinstance(name, str) else name |
| 287 |
self.mode = mode |
| 288 |
self.length = length |
| 289 |
self.modtime = modtime |
| 290 |
self.csum = csum |
| 291 |
self.extra_flags = extra_flags |
| 292 |
self.protocol = protocol |
| 293 |
self.raw = raw |
| 294 |
|
| 295 |
|
| 296 |
self.hlink_ndx = hlink_ndx |
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
self.uid = uid |
| 302 |
self.user_name = (user_name.encode() if isinstance(user_name, str) |
| 303 |
else user_name) |
| 304 |
|
| 305 |
def encode(self): |
| 306 |
if self.raw is not None: |
| 307 |
return self.raw |
| 308 |
|
| 309 |
is_reg = (self.mode & 0o170000) == S_IFREG |
| 310 |
is_dir = (self.mode & 0o170000) == S_IFDIR |
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
xflags = XMIT_SAME_UID | XMIT_SAME_GID |
| 315 |
xflags |= self.extra_flags |
| 316 |
if self.hlink_ndx is not None: |
| 317 |
xflags |= XMIT_HLINKED |
| 318 |
if self.uid is not None: |
| 319 |
xflags &= ~XMIT_SAME_UID |
| 320 |
if self.user_name is not None: |
| 321 |
xflags |= XMIT_USER_NAME_FOLLOWS |
| 322 |
|
| 323 |
out = bytearray() |
| 324 |
|
| 325 |
|
| 326 |
if not xflags and not is_dir: |
| 327 |
xflags |= XMIT_TOP_DIR |
| 328 |
if (xflags & 0xFF00) or not xflags: |
| 329 |
xflags |= XMIT_EXTENDED_FLAGS |
| 330 |
out += w_shortint(xflags) |
| 331 |
else: |
| 332 |
out += w_byte(xflags) |
| 333 |
|
| 334 |
|
| 335 |
l2 = len(self.name) |
| 336 |
if xflags & XMIT_LONG_NAME: |
| 337 |
out += w_varint30(l2, self.protocol) |
| 338 |
else: |
| 339 |
out += w_byte(l2) |
| 340 |
out += self.name |
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
if self.hlink_ndx is not None: |
| 349 |
out += w_varint(self.hlink_ndx) |
| 350 |
|
| 351 |
out += w_varlong30(self.length, 3, self.protocol) |
| 352 |
if not (xflags & XMIT_SAME_TIME): |
| 353 |
out += w_varlong(self.modtime, 4) if self.protocol >= 30 else w_int(self.modtime) |
| 354 |
if not (xflags & XMIT_SAME_MODE): |
| 355 |
out += w_int(to_wire_mode(self.mode)) |
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
if self.uid is not None: |
| 360 |
out += w_varint(self.uid) |
| 361 |
if self.user_name is not None: |
| 362 |
out += w_byte(len(self.user_name)) + self.user_name |
| 363 |
|
| 364 |
|
| 365 |
if self.csum is not None: |
| 366 |
out += self.csum |
| 367 |
|
| 368 |
return bytes(out) |
| 369 |
|
| 370 |
|
| 371 |
def end_of_flist(io_error=0, protocol=DEFAULT_PROTOCOL): |
| 372 |
"""Trailing marker after the last entry. In byte-flags mode (no |
| 373 |
CF_VARINT_FLIST_FLAGS, i.e. no 'v' advertised) recv_file_list() ends the |
| 374 |
list on a single 0 flag byte and reads NO io_error after it -- the io_error |
| 375 |
varint exists only in the varint-flags path. Sending an extra byte here |
| 376 |
leaves a stray 0x00 that the receiver then reads as NDX_DONE (freeing the |
| 377 |
flist), which broke inc_recurse sub-flist sequencing.""" |
| 378 |
return w_byte(0) |
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
class ProtocolError(Exception): |
| 393 |
pass |
| 394 |
|
| 395 |
|
| 396 |
class ParsedEntry: |
| 397 |
"""A file-list entry decoded from the wire (the read side of FileEntry).""" |
| 398 |
|
| 399 |
__slots__ = ('name', 'mode', 'length', 'mtime', 'link_target') |
| 400 |
|
| 401 |
def __init__(self, name, mode, length, mtime, link_target=None): |
| 402 |
self.name = name |
| 403 |
self.mode = mode |
| 404 |
self.length = length |
| 405 |
self.mtime = mtime |
| 406 |
self.link_target = link_target |
| 407 |
|
| 408 |
@property |
| 409 |
def is_reg(self): |
| 410 |
return S_ISREG(self.mode) |
| 411 |
|
| 412 |
@property |
| 413 |
def is_dir(self): |
| 414 |
return S_ISDIR(self.mode) |
| 415 |
|
| 416 |
@property |
| 417 |
def is_link(self): |
| 418 |
return S_ISLNK(self.mode) |
| 419 |
|
| 420 |
def __repr__(self): |
| 421 |
return f"ParsedEntry({self.name!r}, mode={self.mode:o}, length={self.length})" |
| 422 |
|
| 423 |
|
| 424 |
class DaemonClient: |
| 425 |
"""A client that connects to an rsync daemon: runs the @RSYNCD handshake + |
| 426 |
protocol setup, then drives either role depending on the server args -- push |
| 427 |
(send a file list + deltas, as a sender) or pull/list (receive + parse the |
| 428 |
file list, request and receive files, as a receiver). The protocol steps |
| 429 |
are small overridable methods so a test can swap one behaviour (e.g. the sum |
| 430 |
header or an flist entry) while reusing the rest -- see xrsync.py.""" |
| 431 |
|
| 432 |
def __init__(self, host, port, timeout=10): |
| 433 |
self.sock = socket.create_connection((host, port), timeout=timeout) |
| 434 |
self.sock.settimeout(timeout) |
| 435 |
self.protocol = DEFAULT_PROTOCOL |
| 436 |
self.compat_flags = None |
| 437 |
self.seed = None |
| 438 |
self.xfer_sum_len = 16 |
| 439 |
self._rbuf = b'' |
| 440 |
self._ndx_prev_positive = -1 |
| 441 |
self._ndx_prev_negative = 1 |
| 442 |
self._mux_in = b'' |
| 443 |
self._r_ndx_prev_positive = -1 |
| 444 |
self._r_ndx_prev_negative = 1 |
| 445 |
self.messages = [] |
| 446 |
|
| 447 |
|
| 448 |
def _recv_exact(self, n): |
| 449 |
data = b'' |
| 450 |
while len(data) < n: |
| 451 |
if self._rbuf: |
| 452 |
take = self._rbuf[:n - len(data)] |
| 453 |
self._rbuf = self._rbuf[len(take):] |
| 454 |
data += take |
| 455 |
continue |
| 456 |
chunk = self.sock.recv(n - len(data)) |
| 457 |
if not chunk: |
| 458 |
raise ProtocolError(f"EOF after {len(data)}/{n} bytes") |
| 459 |
data += chunk |
| 460 |
return data |
| 461 |
|
| 462 |
def _readline(self): |
| 463 |
line = b'' |
| 464 |
while not line.endswith(b'\n'): |
| 465 |
if self._rbuf: |
| 466 |
c, self._rbuf = self._rbuf[:1], self._rbuf[1:] |
| 467 |
else: |
| 468 |
c = self.sock.recv(1) |
| 469 |
if not c: |
| 470 |
raise ProtocolError("EOF reading a line") |
| 471 |
line += c |
| 472 |
return line.decode('latin-1').rstrip('\n') |
| 473 |
|
| 474 |
def _r_int(self): |
| 475 |
return _s32(int.from_bytes(self._recv_exact(4), 'little')) |
| 476 |
|
| 477 |
def _r_varint(self): |
| 478 |
ch = self._recv_exact(1)[0] |
| 479 |
extra = _INT_BYTE_EXTRA[ch >> 2] |
| 480 |
b = bytearray(5) |
| 481 |
if extra: |
| 482 |
bit = 1 << (8 - extra) |
| 483 |
b[0:extra] = self._recv_exact(extra) |
| 484 |
b[extra] = ch & (bit - 1) |
| 485 |
else: |
| 486 |
b[0] = ch |
| 487 |
return b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24) |
| 488 |
|
| 489 |
|
| 490 |
def _read_data(self, n): |
| 491 |
"""Read n bytes from the de-multiplexed sender input, dispatching any |
| 492 |
non-MSG_DATA frames (MSG_INFO/MSG_ERROR/keepalive/redo/...) into |
| 493 |
self.messages and discarding them.""" |
| 494 |
while len(self._mux_in) < n: |
| 495 |
val = int.from_bytes(self._recv_exact(4), 'little') |
| 496 |
tag = (val >> 24) - MPLEX_BASE |
| 497 |
ln = val & 0xFFFFFF |
| 498 |
payload = self._recv_exact(ln) if ln else b'' |
| 499 |
if tag == MSG_DATA: |
| 500 |
self._mux_in += payload |
| 501 |
else: |
| 502 |
self.messages.append((tag, payload)) |
| 503 |
out, self._mux_in = self._mux_in[:n], self._mux_in[n:] |
| 504 |
return out |
| 505 |
|
| 506 |
def r_int(self): |
| 507 |
return _s32(int.from_bytes(self._read_data(4), 'little')) |
| 508 |
|
| 509 |
def r_byte(self): |
| 510 |
return self._read_data(1)[0] |
| 511 |
|
| 512 |
def r_shortint(self): |
| 513 |
return int.from_bytes(self._read_data(2), 'little') |
| 514 |
|
| 515 |
def r_buf(self, n): |
| 516 |
return self._read_data(n) |
| 517 |
|
| 518 |
def r_vstring(self): |
| 519 |
n = self._read_data(1)[0] |
| 520 |
if n & 0x80: |
| 521 |
n = (n & 0x7F) * 0x100 + self._read_data(1)[0] |
| 522 |
return self._read_data(n) if n else b'' |
| 523 |
|
| 524 |
def r_ndx(self): |
| 525 |
"""Port of io.c read_ndx() at protocol >= 30.""" |
| 526 |
b0 = self._read_data(1)[0] |
| 527 |
if b0 == 0xFF: |
| 528 |
b0 = self._read_data(1)[0] |
| 529 |
neg = True |
| 530 |
elif b0 == 0: |
| 531 |
return NDX_DONE |
| 532 |
else: |
| 533 |
neg = False |
| 534 |
prev = self._r_ndx_prev_negative if neg else self._r_ndx_prev_positive |
| 535 |
if b0 == 0xFE: |
| 536 |
b = self._read_data(2) |
| 537 |
if b[0] & 0x80: |
| 538 |
rest = self._read_data(2) |
| 539 |
num = ((b[0] & 0x7F) << 24) | b[1] | (rest[0] << 8) | (rest[1] << 16) |
| 540 |
else: |
| 541 |
num = (b[0] << 8) + b[1] + prev |
| 542 |
else: |
| 543 |
num = b0 + prev |
| 544 |
if neg: |
| 545 |
self._r_ndx_prev_negative = num |
| 546 |
return -num |
| 547 |
self._r_ndx_prev_positive = num |
| 548 |
return num |
| 549 |
|
| 550 |
def r_sum_head(self): |
| 551 |
"""io.c read_sum_head(): count, blength, s2length, remainder.""" |
| 552 |
return (self.r_int(), self.r_int(), self.r_int(), self.r_int()) |
| 553 |
|
| 554 |
def r_varint(self): |
| 555 |
"""io.c read_varint() on the de-multiplexed stream.""" |
| 556 |
ch = self._read_data(1)[0] |
| 557 |
extra = _INT_BYTE_EXTRA[ch >> 2] |
| 558 |
b = bytearray(5) |
| 559 |
if extra: |
| 560 |
bit = 1 << (8 - extra) |
| 561 |
b[0:extra] = self._read_data(extra) |
| 562 |
b[extra] = ch & (bit - 1) |
| 563 |
else: |
| 564 |
b[0] = ch |
| 565 |
return b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24) |
| 566 |
|
| 567 |
def r_varlong(self, min_bytes): |
| 568 |
"""io.c read_varlong() on the de-multiplexed stream.""" |
| 569 |
b2 = self._read_data(min_bytes) |
| 570 |
u = bytearray(9) |
| 571 |
u[0:min_bytes - 1] = b2[1:min_bytes] |
| 572 |
extra = _INT_BYTE_EXTRA[b2[0] >> 2] |
| 573 |
if extra: |
| 574 |
bit = 1 << (8 - extra) |
| 575 |
u[min_bytes - 1:min_bytes - 1 + extra] = self._read_data(extra) |
| 576 |
u[min_bytes + extra - 1] = b2[0] & (bit - 1) |
| 577 |
else: |
| 578 |
u[min_bytes - 1] = b2[0] |
| 579 |
x = 0 |
| 580 |
for i in range(8): |
| 581 |
x |= u[i] << (8 * i) |
| 582 |
return x |
| 583 |
|
| 584 |
def r_varint30(self): |
| 585 |
return self.r_varint() if self.protocol >= 30 else self.r_int() |
| 586 |
|
| 587 |
def r_varlong30(self, min_bytes): |
| 588 |
return self.r_varlong(min_bytes) if self.protocol >= 30 else self.r_int() |
| 589 |
|
| 590 |
|
| 591 |
def handshake(self, module, server_args, greeting_version=30): |
| 592 |
"""Run the @RSYNCD handshake for `module` and send `server_args` |
| 593 |
(the daemon-side argv). Returns once protocol setup is done and the |
| 594 |
stream is multiplexed in both directions.""" |
| 595 |
greeting = self._readline() |
| 596 |
if not greeting.startswith('@RSYNCD:'): |
| 597 |
raise ProtocolError(f"bad greeting: {greeting!r}") |
| 598 |
|
| 599 |
|
| 600 |
self._send_raw(f"@RSYNCD: {greeting_version}.0\n".encode()) |
| 601 |
self._send_raw(module.encode() + b"\n") |
| 602 |
resp = self._readline() |
| 603 |
if 'OK' not in resp: |
| 604 |
raise ProtocolError(f"daemon did not send OK (got {resp!r}); " |
| 605 |
"module may require auth or be unknown") |
| 606 |
|
| 607 |
payload = b''.join(a.encode() + b"\0" for a in server_args) + b"\0" |
| 608 |
self._send_raw(payload) |
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
|
| 613 |
self.compat_flags = self._r_varint() |
| 614 |
self.seed = self._r_int() |
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
def _send_raw(self, data): |
| 619 |
self.sock.sendall(data) |
| 620 |
|
| 621 |
def _frame(self, code, payload): |
| 622 |
hdr = struct.pack('<I', ((MPLEX_BASE + code) << 24) | len(payload)) |
| 623 |
return hdr + payload |
| 624 |
|
| 625 |
def send_data(self, payload): |
| 626 |
"""Send `payload` as one MSG_DATA frame (the normal sender stream: |
| 627 |
filter list, file list, file data).""" |
| 628 |
self._send_raw(self._frame(MSG_DATA, payload)) |
| 629 |
|
| 630 |
def send_message(self, code, payload): |
| 631 |
"""Send a non-data message frame (e.g. MSG_INFO) to the receiver.""" |
| 632 |
self._send_raw(self._frame(code, payload)) |
| 633 |
|
| 634 |
|
| 635 |
def send_flat_flist(self, entries, io_error=0): |
| 636 |
"""Send `entries` followed by the end marker, in one MSG_DATA frame. |
| 637 |
No filter list is sent (see the note above empty-filter handling).""" |
| 638 |
buf = bytearray() |
| 639 |
for e in entries: |
| 640 |
buf += e.encode() |
| 641 |
buf += end_of_flist(io_error, self.protocol) |
| 642 |
self.send_data(bytes(buf)) |
| 643 |
|
| 644 |
def w_ndx(self, ndx): |
| 645 |
"""Full port of io.c write_ndx() at protocol >= 30: NDX_DONE -> a single |
| 646 |
0 byte; negatives -> a leading 0xFF then a delta against prev_negative; |
| 647 |
non-negatives -> a delta against prev_positive.""" |
| 648 |
if ndx == NDX_DONE: |
| 649 |
return b'\x00' |
| 650 |
b = bytearray() |
| 651 |
if ndx >= 0: |
| 652 |
diff = ndx - self._ndx_prev_positive |
| 653 |
self._ndx_prev_positive = ndx |
| 654 |
absndx = ndx |
| 655 |
else: |
| 656 |
b.append(0xFF) |
| 657 |
absndx = -ndx |
| 658 |
diff = absndx - self._ndx_prev_negative |
| 659 |
self._ndx_prev_negative = absndx |
| 660 |
if 0 < diff < 0xFE: |
| 661 |
b.append(diff) |
| 662 |
elif diff < 0 or diff > 0x7FFF: |
| 663 |
b += bytes([0xFE, ((absndx >> 24) | 0x80) & 0xFF, absndx & 0xFF, |
| 664 |
(absndx >> 8) & 0xFF, (absndx >> 16) & 0xFF]) |
| 665 |
else: |
| 666 |
b += bytes([0xFE, (diff >> 8) & 0xFF, diff & 0xFF]) |
| 667 |
return bytes(b) |
| 668 |
|
| 669 |
def send_transfer_ndx(self, ndx, iflags=0): |
| 670 |
"""Transfer-phase token: a write_ndx() index followed by the shortint |
| 671 |
iflags read by read_ndx_and_attrs() (protocol >= 29).""" |
| 672 |
self.send_data(self.w_ndx(ndx) + w_shortint(iflags)) |
| 673 |
|
| 674 |
def send_ndx_done(self): |
| 675 |
"""Send NDX_DONE (a single 0 byte in the ndx stream).""" |
| 676 |
self.send_data(self.w_ndx(NDX_DONE)) |
| 677 |
|
| 678 |
def send_subflist_marker(self, dir_ndx): |
| 679 |
"""Announce an inc_recurse sub-flist for dir_ndx: write_ndx of |
| 680 |
NDX_FLIST_OFFSET - dir_ndx (a negative index).""" |
| 681 |
self.send_data(self.w_ndx(NDX_FLIST_OFFSET - dir_ndx)) |
| 682 |
|
| 683 |
def run_forged_transfer(self, forged_type, xname, literal_tail=b'', |
| 684 |
file_csum_len=16, max_phase=2): |
| 685 |
"""Drive the sender side of the transfer phase, FORGING fnamecmp_type on |
| 686 |
every file the generator requests (the chroot-basis attack): for each |
| 687 |
request, read its iflags / basis-type / xname / sum header + block sums, |
| 688 |
then send back the ndx with our forged basis type + xname, the echoed sum |
| 689 |
header, a delta that MATCHES block 0 of the (forged) basis plus the given |
| 690 |
literal tail, and a deliberately wrong whole-file checksum (so the |
| 691 |
receiver -- if it opened the forged basis -- reconstructs the wrong bytes |
| 692 |
and logs 'failed verification'). Loops through both transfer phases (the |
| 693 |
checksum-mismatch redo) until NDX_DONE has advanced past max_phase. |
| 694 |
|
| 695 |
Stops early (returns) if the receiver drops the connection mid-transfer |
| 696 |
-- e.g. a confined receiver that refuses the forged basis and exits with |
| 697 |
'got a block match with no basis file'.""" |
| 698 |
try: |
| 699 |
self._forged_transfer_loop(forged_type, xname, literal_tail, |
| 700 |
file_csum_len, max_phase) |
| 701 |
except (ProtocolError, socket.timeout, OSError): |
| 702 |
pass |
| 703 |
|
| 704 |
def _forged_transfer_loop(self, forged_type, xname, literal_tail, |
| 705 |
file_csum_len, max_phase): |
| 706 |
phase = 0 |
| 707 |
while True: |
| 708 |
ndx = self.r_ndx() |
| 709 |
if ndx == NDX_DONE: |
| 710 |
self.send_data(self.w_ndx(NDX_DONE)) |
| 711 |
phase += 1 |
| 712 |
if phase > max_phase: |
| 713 |
break |
| 714 |
continue |
| 715 |
iflags = self.r_shortint() |
| 716 |
if iflags & ITEM_BASIS_TYPE_FOLLOWS: |
| 717 |
self.r_byte() |
| 718 |
if iflags & ITEM_XNAME_FOLLOWS: |
| 719 |
self.r_vstring() |
| 720 |
count, blength, s2length, remainder = self.r_sum_head() |
| 721 |
for _ in range(count): |
| 722 |
self.r_int() |
| 723 |
self.r_buf(s2length) |
| 724 |
out = bytearray() |
| 725 |
out += self.w_ndx(ndx) |
| 726 |
out += w_shortint(iflags | ITEM_BASIS_TYPE_FOLLOWS | ITEM_XNAME_FOLLOWS) |
| 727 |
out += w_byte(forged_type) |
| 728 |
out += w_vstring(xname) |
| 729 |
out += w_sum_head(count, blength, s2length, remainder) |
| 730 |
if count > 0: |
| 731 |
out += w_int(-1) |
| 732 |
if literal_tail: |
| 733 |
out += w_int(len(literal_tail)) + literal_tail |
| 734 |
out += w_int(0) |
| 735 |
out += b'\x00' * file_csum_len |
| 736 |
self.send_data(bytes(out)) |
| 737 |
|
| 738 |
|
| 739 |
def recv_flist(self, preserve_links=True): |
| 740 |
"""Send the (empty) filter list the sender expects, then read + parse |
| 741 |
the daemon's file list. Returns a list of ParsedEntry. Decodes the |
| 742 |
-lt subset (no uid/gid/devices); override for more. This is a natural |
| 743 |
hook point: a test can subclass and tamper with what it returns.""" |
| 744 |
self.send_data(w_int(0)) |
| 745 |
entries = [] |
| 746 |
prev_name = b'' |
| 747 |
prev_mode = 0 |
| 748 |
prev_mtime = 0 |
| 749 |
while True: |
| 750 |
flags = self.r_byte() |
| 751 |
if flags & XMIT_EXTENDED_FLAGS: |
| 752 |
flags |= self.r_byte() << 8 |
| 753 |
if flags == 0: |
| 754 |
break |
| 755 |
l1 = self.r_byte() if flags & XMIT_SAME_NAME else 0 |
| 756 |
l2 = self.r_varint30() if flags & XMIT_LONG_NAME else self.r_byte() |
| 757 |
name = prev_name[:l1] + self.r_buf(l2) |
| 758 |
prev_name = name |
| 759 |
length = self.r_varlong30(3) |
| 760 |
if not (flags & XMIT_SAME_TIME): |
| 761 |
prev_mtime = self.r_varlong30(4) |
| 762 |
mtime = prev_mtime |
| 763 |
if flags & XMIT_MOD_NSEC: |
| 764 |
self.r_varint() |
| 765 |
if not (flags & XMIT_SAME_MODE): |
| 766 |
prev_mode = self.r_int() |
| 767 |
mode = prev_mode |
| 768 |
link_target = None |
| 769 |
if preserve_links and S_ISLNK(mode): |
| 770 |
link_target = self.r_buf(self.r_varint30()) |
| 771 |
entries.append(ParsedEntry(name, mode, length, mtime, link_target)) |
| 772 |
return entries |
| 773 |
|
| 774 |
def make_request(self, ndx): |
| 775 |
"""Generator request for a whole-file transfer of `ndx`: the ndx, the |
| 776 |
item flags, and a count=0 sum header (no local basis). Overridable |
| 777 |
hook -- a test can return a malformed request here.""" |
| 778 |
return (self.w_ndx(ndx) + w_shortint(ITEM_TRANSFER) |
| 779 |
+ w_sum_head(0, 0, 0, 0)) |
| 780 |
|
| 781 |
def recv_file_transfer(self, ndx): |
| 782 |
"""Read one file the sender sends in reply to make_request(): item |
| 783 |
flags, optional basis type / xname, the echoed sum header, the literal |
| 784 |
token stream, and the whole-file checksum. Returns the file bytes.""" |
| 785 |
iflags = self.r_shortint() |
| 786 |
if iflags & ITEM_BASIS_TYPE_FOLLOWS: |
| 787 |
self.r_byte() |
| 788 |
if iflags & ITEM_XNAME_FOLLOWS: |
| 789 |
self.r_vstring() |
| 790 |
self.r_sum_head() |
| 791 |
data = bytearray() |
| 792 |
while True: |
| 793 |
tok = self.r_int() |
| 794 |
if tok == 0: |
| 795 |
break |
| 796 |
if tok > 0: |
| 797 |
data += self.r_buf(tok) |
| 798 |
else: |
| 799 |
raise ProtocolError(f"unexpected block match token {tok} " |
| 800 |
"(no basis was offered)") |
| 801 |
self.r_buf(self.xfer_sum_len) |
| 802 |
return bytes(data) |
| 803 |
|
| 804 |
def pull(self, dest_dir, verbose=False, preserve_times=True, |
| 805 |
preserve_perms=True): |
| 806 |
"""Receive the file list and materialise it under dest_dir: make |
| 807 |
directories, create symlinks, and download regular files (whole-file |
| 808 |
requests). Returns the parsed file list.""" |
| 809 |
import os |
| 810 |
|
| 811 |
|
| 812 |
entries = sort_entries(self.recv_flist()) |
| 813 |
reg = [] |
| 814 |
for ndx, e in enumerate(entries): |
| 815 |
rel = e.name.decode('utf-8', 'surrogateescape') |
| 816 |
if rel in ('.', ''): |
| 817 |
continue |
| 818 |
path = os.path.join(dest_dir, rel) |
| 819 |
if e.is_dir: |
| 820 |
os.makedirs(path, exist_ok=True) |
| 821 |
elif e.is_link and e.link_target is not None: |
| 822 |
tgt = e.link_target.decode('utf-8', 'surrogateescape') |
| 823 |
if os.path.lexists(path): |
| 824 |
os.unlink(path) |
| 825 |
os.symlink(tgt, path) |
| 826 |
elif e.is_reg: |
| 827 |
reg.append((ndx, e, path)) |
| 828 |
if verbose: |
| 829 |
print(rel) |
| 830 |
|
| 831 |
for ndx, e, path in reg: |
| 832 |
self.send_data(self.make_request(ndx)) |
| 833 |
self.send_data(self.w_ndx(NDX_DONE)) |
| 834 |
|
| 835 |
got = {} |
| 836 |
phase = 1 |
| 837 |
while True: |
| 838 |
ndx = self.r_ndx() |
| 839 |
if ndx == NDX_DONE: |
| 840 |
phase += 1 |
| 841 |
if phase > 2: |
| 842 |
break |
| 843 |
self.send_data(self.w_ndx(NDX_DONE)) |
| 844 |
continue |
| 845 |
got[ndx] = self.recv_file_transfer(ndx) |
| 846 |
for ndx, e, path in reg: |
| 847 |
if ndx not in got: |
| 848 |
continue |
| 849 |
with open(path, 'wb') as fh: |
| 850 |
fh.write(got[ndx]) |
| 851 |
if preserve_perms: |
| 852 |
os.chmod(path, e.mode & 0o7777) |
| 853 |
if preserve_times: |
| 854 |
os.utime(path, (e.mtime, e.mtime)) |
| 855 |
return entries |
| 856 |
|
| 857 |
def finish_no_transfer(self): |
| 858 |
"""Walk the per-phase NDX_DONE handshake with no files requested -- used |
| 859 |
after --list-only so the daemon shuts down cleanly.""" |
| 860 |
self.send_data(self.w_ndx(NDX_DONE)) |
| 861 |
phase = 1 |
| 862 |
try: |
| 863 |
while True: |
| 864 |
if self.r_ndx() == NDX_DONE: |
| 865 |
phase += 1 |
| 866 |
if phase > 2: |
| 867 |
break |
| 868 |
self.send_data(self.w_ndx(NDX_DONE)) |
| 869 |
except (ProtocolError, socket.timeout, OSError): |
| 870 |
pass |
| 871 |
|
| 872 |
|
| 873 |
def push(self, files, modtime=1700000000): |
| 874 |
"""Basic upload: `files` is a list of (name, content) regular files. |
| 875 |
Send the file list, then satisfy the receiver's whole-file requests with |
| 876 |
the literal content + its md5 (the proto-30 whole-file digest is plain |
| 877 |
md5, no seed). Overridable pieces: make_file_token_stream().""" |
| 878 |
import hashlib |
| 879 |
names = [n.encode() if isinstance(n, str) else n for n, _ in files] |
| 880 |
entries = [FileEntry(n, mode=S_IFREG | 0o644, length=len(c), |
| 881 |
modtime=modtime, protocol=self.protocol) |
| 882 |
for n, (_, c) in zip(names, files)] |
| 883 |
self.send_flat_flist(entries) |
| 884 |
|
| 885 |
order = sorted(range(len(files)), key=lambda i: names[i]) |
| 886 |
content_by_ndx = {ndx: files[i][1] for ndx, i in enumerate(order)} |
| 887 |
phase = 0 |
| 888 |
while True: |
| 889 |
ndx = self.r_ndx() |
| 890 |
if ndx == NDX_DONE: |
| 891 |
self.send_data(self.w_ndx(NDX_DONE)) |
| 892 |
phase += 1 |
| 893 |
if phase > 2: |
| 894 |
break |
| 895 |
continue |
| 896 |
iflags = self.r_shortint() |
| 897 |
if iflags & ITEM_BASIS_TYPE_FOLLOWS: |
| 898 |
self.r_byte() |
| 899 |
if iflags & ITEM_XNAME_FOLLOWS: |
| 900 |
self.r_vstring() |
| 901 |
count, blength, s2length, remainder = self.r_sum_head() |
| 902 |
for _ in range(count): |
| 903 |
self.r_int() |
| 904 |
self.r_buf(s2length) |
| 905 |
content = content_by_ndx.get(ndx, b'') |
| 906 |
out = bytearray() |
| 907 |
out += self.w_ndx(ndx) |
| 908 |
out += w_shortint(ITEM_TRANSFER) |
| 909 |
out += w_sum_head(0, 0, 0, 0) |
| 910 |
out += self.make_file_token_stream(content) |
| 911 |
out += hashlib.md5(content).digest() |
| 912 |
self.send_data(bytes(out)) |
| 913 |
|
| 914 |
def make_file_token_stream(self, content): |
| 915 |
"""Whole-file literal token stream (token.c simple_send_token, no -z): |
| 916 |
CHUNK_SIZE-sized literal runs then a 0 end token. Overridable hook.""" |
| 917 |
out = bytearray() |
| 918 |
for off in range(0, len(content), CHUNK_SIZE): |
| 919 |
chunk = content[off:off + CHUNK_SIZE] |
| 920 |
out += w_int(len(chunk)) + chunk |
| 921 |
out += w_int(0) |
| 922 |
return bytes(out) |
| 923 |
|
| 924 |
def drain(self, timeout=3.0): |
| 925 |
"""Read whatever the daemon sends back until EOF/timeout. Returns the |
| 926 |
raw bytes (mux frames undecoded); used only to detect a dropped |
| 927 |
connection (crash) vs an orderly close.""" |
| 928 |
self.sock.settimeout(timeout) |
| 929 |
out = b'' |
| 930 |
try: |
| 931 |
while True: |
| 932 |
chunk = self.sock.recv(65536) |
| 933 |
if not chunk: |
| 934 |
break |
| 935 |
out += chunk |
| 936 |
except socket.timeout: |
| 937 |
pass |
| 938 |
return out |
| 939 |
|
| 940 |
def close(self): |
| 941 |
try: |
| 942 |
self.sock.close() |
| 943 |
except OSError: |
| 944 |
pass |
| 945 |
|
| 946 |
|
| 947 |
|
| 948 |
DaemonSender = DaemonClient |
| 949 |
|
| 950 |
|
| 951 |
class DaemonReceiver: |
| 952 |
"""The SERVER side of the daemon protocol -- the inverse of DaemonSender. |
| 953 |
Accepts a real rsync client and runs the @RSYNCD handshake + protocol-30 |
| 954 |
setup as the daemon. The @RSYNCD handshake is direction-agnostic, so after |
| 955 |
setup this can drive either role: when the client PUSHES (client = sender) |
| 956 |
we act as the receiver/generator and send transfer requests (e.g. malformed |
| 957 |
sum headers); when the client PULLS (client = receiver) we act as the sender |
| 958 |
and send a file list (e.g. one carrying an oversized xattr datum). Both are |
| 959 |
things rsync_proto's client/sender role cannot do. |
| 960 |
|
| 961 |
The two stream directions are independent, so we never need to parse the |
| 962 |
client's file list: we just send a request for an index the client's flist |
| 963 |
is known to contain (index 0 for a single pushed file) and let the client's |
| 964 |
send_files() read it. After sending we drain the client's stream so its |
| 965 |
flist writes don't block while it reaches the request and errors out.""" |
| 966 |
|
| 967 |
def __init__(self, sock, greeting_version=30, protocol=DEFAULT_PROTOCOL): |
| 968 |
self.sock = sock |
| 969 |
self.protocol = protocol |
| 970 |
self.greeting_version = greeting_version |
| 971 |
self._rbuf = b'' |
| 972 |
self._ndx_prev_positive = -1 |
| 973 |
self._ndx_prev_negative = 1 |
| 974 |
|
| 975 |
|
| 976 |
def _send_raw(self, data): |
| 977 |
self.sock.sendall(data) |
| 978 |
|
| 979 |
def _recv_exact(self, n): |
| 980 |
data = b'' |
| 981 |
while len(data) < n: |
| 982 |
if self._rbuf: |
| 983 |
take = self._rbuf[:n - len(data)] |
| 984 |
self._rbuf = self._rbuf[len(take):] |
| 985 |
data += take |
| 986 |
continue |
| 987 |
chunk = self.sock.recv(n - len(data)) |
| 988 |
if not chunk: |
| 989 |
raise ProtocolError(f"EOF after {len(data)}/{n} bytes") |
| 990 |
data += chunk |
| 991 |
return data |
| 992 |
|
| 993 |
def _readline(self): |
| 994 |
line = b'' |
| 995 |
while not line.endswith(b'\n'): |
| 996 |
if self._rbuf: |
| 997 |
c, self._rbuf = self._rbuf[:1], self._rbuf[1:] |
| 998 |
else: |
| 999 |
c = self.sock.recv(1) |
| 1000 |
if not c: |
| 1001 |
raise ProtocolError("EOF reading a line") |
| 1002 |
line += c |
| 1003 |
return line.decode('latin-1').rstrip('\n') |
| 1004 |
|
| 1005 |
def _frame(self, code, payload): |
| 1006 |
hdr = struct.pack('<I', ((MPLEX_BASE + code) << 24) | len(payload)) |
| 1007 |
return hdr + payload |
| 1008 |
|
| 1009 |
def send_data(self, payload): |
| 1010 |
self._send_raw(self._frame(MSG_DATA, payload)) |
| 1011 |
|
| 1012 |
def w_ndx(self, ndx): |
| 1013 |
|
| 1014 |
if ndx == NDX_DONE: |
| 1015 |
return b'\x00' |
| 1016 |
b = bytearray() |
| 1017 |
if ndx >= 0: |
| 1018 |
diff = ndx - self._ndx_prev_positive |
| 1019 |
self._ndx_prev_positive = ndx |
| 1020 |
absndx = ndx |
| 1021 |
else: |
| 1022 |
b.append(0xFF) |
| 1023 |
absndx = -ndx |
| 1024 |
diff = absndx - self._ndx_prev_negative |
| 1025 |
self._ndx_prev_negative = absndx |
| 1026 |
if 0 < diff < 0xFE: |
| 1027 |
b.append(diff) |
| 1028 |
elif diff < 0 or diff > 0x7FFF: |
| 1029 |
b += bytes([0xFE, ((absndx >> 24) | 0x80) & 0xFF, absndx & 0xFF, |
| 1030 |
(absndx >> 8) & 0xFF, (absndx >> 16) & 0xFF]) |
| 1031 |
else: |
| 1032 |
b += bytes([0xFE, (diff >> 8) & 0xFF, diff & 0xFF]) |
| 1033 |
return bytes(b) |
| 1034 |
|
| 1035 |
|
| 1036 |
def handshake(self, compat_flags=0, seed=0): |
| 1037 |
"""Send the daemon greeting, read the client's greeting + module line, |
| 1038 |
send '@RSYNCD: OK', then write the protocol-30 setup (compat flags + |
| 1039 |
checksum seed). We don't read the client's NUL-separated args: it sends |
| 1040 |
them after reading our OK and reads our compat/seed afterwards, and the |
| 1041 |
directions are independent.""" |
| 1042 |
self._send_raw(f"@RSYNCD: {self.greeting_version}.0\n".encode()) |
| 1043 |
self._readline() |
| 1044 |
self._readline() |
| 1045 |
self._send_raw(b"@RSYNCD: OK\n") |
| 1046 |
self._send_raw(w_varint(compat_flags) + w_int(seed)) |
| 1047 |
|
| 1048 |
|
| 1049 |
|
| 1050 |
def send_sum_request(self, ndx, count, blength, s2length, remainder, |
| 1051 |
iflags=ITEM_TRANSFER): |
| 1052 |
"""As the generator, request a transfer of file `ndx` with the given |
| 1053 |
(possibly malformed) sum header -- ndx + iflags + write_sum_head(), the |
| 1054 |
bytes the client's send_files()/receive_sums() read.""" |
| 1055 |
buf = (self.w_ndx(ndx) + w_shortint(iflags) |
| 1056 |
+ w_sum_head(count, blength, s2length, remainder)) |
| 1057 |
self.send_data(buf) |
| 1058 |
|
| 1059 |
def drain(self, timeout=5.0): |
| 1060 |
"""Read and discard the client's stream until it closes (it pushes its |
| 1061 |
file list, reaches our request, errors, and disconnects).""" |
| 1062 |
self.sock.settimeout(timeout) |
| 1063 |
try: |
| 1064 |
while self.sock.recv(65536): |
| 1065 |
pass |
| 1066 |
except (OSError, ProtocolError): |
| 1067 |
pass |
| 1068 |
|
| 1069 |
def close(self): |
| 1070 |
try: |
| 1071 |
self.sock.close() |
| 1072 |
except OSError: |
| 1073 |
pass |