diff --git a/verify_nzb.py b/verify_nzb.py index 953dccd..355169f 100644 --- a/verify_nzb.py +++ b/verify_nzb.py @@ -115,19 +115,29 @@ def _parse_yenc_attrs(line: bytes) -> dict[str, str]: return attrs +_YENC_UNSHIFT_TABLE = bytes((i - 42) % 256 for i in range(256)) + + def _decode_yenc_lines(lines: Iterable[bytes]) -> bytes: decoded = bytearray() for line in lines: - index = 0 - while index < len(line): - byte = line[index] - if byte == 61: - index += 1 - if index >= len(line): - raise ValueError("dangling yEnc escape") - byte = (line[index] - 64) % 256 - decoded.append((byte - 42) % 256) - index += 1 + pos = 0 + line_len = len(line) + while True: + esc_pos = line.find(b"=", pos) + if esc_pos == -1: + decoded.extend(line[pos:].translate(_YENC_UNSHIFT_TABLE)) + break + + decoded.extend(line[pos:esc_pos].translate(_YENC_UNSHIFT_TABLE)) + + if esc_pos + 1 >= line_len: + raise ValueError("dangling yEnc escape") + + escaped_char = line[esc_pos + 1] + decoded.append((escaped_char - 106) % 256) + + pos = esc_pos + 2 return bytes(decoded)