|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +"""yEnc Codec - yEnc content encoding. |
| 3 | +
|
| 4 | +yEnc is a binary-to-text encoding designed for Usenet. Each byte is shifted by 42 (modulo 256) and only the critical |
| 5 | + characters are escaped with "=" followed by the character shifted by 64 more: NUL, LF, CR and "=", as well as TAB and |
| 6 | + SPACE at the beginning or the end of a line and "." at the beginning of a line. |
| 7 | +
|
| 8 | +Three forms are supported: |
| 9 | +- raw (default): the encoded data on a single line |
| 10 | +- wrapped: the encoded data in lines of the given length (a line ending with an escape may be one character longer) |
| 11 | +- full: the wrapped data framed by the "=ybegin" header and the "=yend" trailer holding its size and CRC32 |
| 12 | +
|
| 13 | +When decoding, the header and the trailer are detected (the size and the CRC32 being checked) and line breaks are |
| 14 | + ignored, so that every form is decoded. |
| 15 | +
|
| 16 | +This codec: |
| 17 | +- en/decodes strings from str to str |
| 18 | +- en/decodes strings from bytes to bytes |
| 19 | +- decodes file content to str (read) |
| 20 | +- encodes file content from str to bytes (write) |
| 21 | +
|
| 22 | +Reference: http://www.yenc.org/yenc-draft.1.3.txt |
| 23 | +""" |
| 24 | +from zlib import crc32 |
| 25 | + |
| 26 | +from ..__common__ import * |
| 27 | + |
| 28 | + |
| 29 | +__examples__ = { |
| 30 | + 'enc(yenc|y-enc|y_enc)': {'Hello': "r\x8f\x96\x96\x99", '\xd6\xe0\xe3\x13': "=@=J=M=}"}, |
| 31 | + 'enc(yenc)': {'\xf6\x04\xf6': "=`.=`", '\x04\xf6\x04': "=n .", '\xdf\xdf': "=I=I"}, |
| 32 | + 'enc(yenc-4)': {'\xf6\xf6\xf6\xf6\xf6': "=` =`\r\n=`=`"}, |
| 33 | + 'enc(yenc-full)': {'Hello': "=ybegin line=128 size=5 name=-\r\nr\x8f\x96\x96\x99\r\n" |
| 34 | + "=yend size=5 crc32=f7d18982\r\n"}, |
| 35 | + 'dec(yenc)': {'r\x8f\r\n\x96\x96\x99': "Hello", 'r=': None, 'Ā': None}, |
| 36 | + 'dec(yenc-full)': {'junk\n=ybegin part=1 line=128 size=5 name=hello.txt\n=ypart begin=1 end=5\nr\x8f\x96\x96' |
| 37 | + '\x99\n=yend size=5 part=1 pcrc32=f7d18982\njunk': "Hello", |
| 38 | + '=ybegin line=128 size=5 name=-\nr\x8f\x96\x96\x99\n=yend size=5 crc32=00000000': None, |
| 39 | + '=ybegin line=128 size=5 name=-\nr\x8f\x96\x96\x99\n=yend size=4': None, |
| 40 | + '=ybegin line=128 size=5 name=-\nr\x8f\x96\x96\x99': None}, |
| 41 | + 'enc-dec(yenc|yenc-1|yenc-2|yenc-128|yenc-full|yenc-3-full)': ["", "Hello, World!", "\x00\n\r=\t .", |
| 42 | + "@random{512,1024,2048}"], |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +CRITICAL, WHITESPACES = (0, 10, 13, 61), (9, 32) |
| 47 | + |
| 48 | + |
| 49 | +def yenc_encode(line=None, full=None): |
| 50 | + line = line or (128 if full else 0) |
| 51 | + def encode(text, errors="strict"): |
| 52 | + data, lines, cur = b(text), [], "" |
| 53 | + for i, x in enumerate(data): |
| 54 | + o = (x + 42) % 256 |
| 55 | + last = i == len(data) - 1 or line and len(cur) + 1 >= line |
| 56 | + if o in CRITICAL or not cur and o in WHITESPACES + (46, ) or last and o in WHITESPACES: |
| 57 | + cur += "=" + chr((o + 64) % 256) |
| 58 | + else: |
| 59 | + cur += chr(o) |
| 60 | + # an escape sequence is never split, hence a line may be one character longer |
| 61 | + if line and len(cur) >= line: |
| 62 | + lines.append(cur) |
| 63 | + cur = "" |
| 64 | + if cur: |
| 65 | + lines.append(cur) |
| 66 | + r = "\r\n".join(lines) |
| 67 | + if full: |
| 68 | + r = f"=ybegin line={line} size={len(data)} name=-\r\n" + (r + "\r\n" if r else "") + \ |
| 69 | + f"=yend size={len(data)} crc32={crc32(data):08x}\r\n" |
| 70 | + return r, len(r) |
| 71 | + return encode |
| 72 | + |
| 73 | + |
| 74 | +def yenc_decode(line=None, full=None): |
| 75 | + def decode(text, errors="strict"): |
| 76 | + text, _h = ensure_str(text), handle_error("yenc", errors, decode=True) |
| 77 | + lines, start, end = text.split("\n"), None, None |
| 78 | + # the data is framed if a header line is found ; then, lines out of the frame are ignored |
| 79 | + for i, l in enumerate(lines): |
| 80 | + if start is None and l.startswith("=ybegin "): |
| 81 | + start = i |
| 82 | + elif start is not None and l.startswith("=yend"): |
| 83 | + end = i |
| 84 | + break |
| 85 | + if start is not None: |
| 86 | + header, trailer = __fields(lines[start]), __fields(lines[end]) if end is not None else {} |
| 87 | + data = lines[start+1:end] |
| 88 | + if len(data) > 0 and data[0].startswith("=ypart "): |
| 89 | + data = data[1:] |
| 90 | + text = "\n".join(data) |
| 91 | + r = [] |
| 92 | + # tokens: an escaped character, a trailing escape character (error) or a plain character |
| 93 | + for m in re.finditer(r"=(.)|(=)\Z|(.)", text.replace("\r", "").replace("\n", ""), re.S): |
| 94 | + c = m.group(1) or m.group(2) or m.group(3) |
| 95 | + if m.group(2) or ord(c) > 255: |
| 96 | + r.extend(b(_h(c, m.start()))) |
| 97 | + else: |
| 98 | + r.append((ord(c) - 64 * bool(m.group(1)) - 42) % 256) |
| 99 | + r = bytes(r) |
| 100 | + if start is not None and errors == "strict": |
| 101 | + _f = handle_error("yenc", errors, decode=True, kind="field", item="line") |
| 102 | + if end is None: |
| 103 | + _f("=yend", len(lines)) |
| 104 | + size, crc = trailer.get("size", header.get("size")), trailer.get("pcrc32") |
| 105 | + if crc is None and "part" not in header: |
| 106 | + crc = trailer.get("crc32") |
| 107 | + if size is not None and size != str(len(r)): |
| 108 | + _f(f"size={size}", end) |
| 109 | + if crc is not None and crc.lower().zfill(8) != f"{crc32(r):08x}": |
| 110 | + _f(f"crc32={crc}", end) |
| 111 | + return r, len(r) |
| 112 | + return decode |
| 113 | + |
| 114 | + |
| 115 | +def __fields(line): |
| 116 | + """ Parse the keyword=value fields of a header or trailer line (the name, possibly holding spaces, comes last). """ |
| 117 | + return {k: v for k, v in re.findall(r"(\w+)=(\S*)", line.split(" name=")[0])} |
| 118 | + |
| 119 | + |
| 120 | +add("yenc", yenc_encode, yenc_decode, r"^y[-_]?enc(?:[-_]([1-9][0-9]*))?([-_]full)?$", |
| 121 | + bonus_func=lambda o, *a: re.search(r"^=ybegin .*\n(?:.*\n)*=yend ", ensure_str(o.text), re.M)) |
0 commit comments