|
| 1 | +from __future__ import absolute_import |
| 2 | +import base64 |
| 3 | +import struct |
| 4 | + |
| 5 | +import six |
| 6 | + |
| 7 | + |
| 8 | +SIZE = 37*8 |
| 9 | +IS_PATH = False |
| 10 | + |
| 11 | + |
| 12 | +def to_bytes(proto, string): |
| 13 | + addr = string.split(":") |
| 14 | + if len(addr) != 2: |
| 15 | + raise ValueError("Does not contain a port number") |
| 16 | + |
| 17 | + # onion3 address without the ".onion" substring |
| 18 | + if len(addr[0]) != 56: |
| 19 | + raise ValueError("Invalid onion3 host address length (must be 56 characters)") |
| 20 | + try: |
| 21 | + onion3_host_bytes = base64.b32decode(addr[0].upper()) |
| 22 | + except Exception as exc: |
| 23 | + six.raise_from(ValueError("Cannot decode {0!r} as base32: {1}".format(addr[0], exc)), exc) |
| 24 | + |
| 25 | + # onion3 port number |
| 26 | + try: |
| 27 | + port = int(addr[1], 10) |
| 28 | + except ValueError as exc: |
| 29 | + six.raise_from(ValueError("Port number is not a base 10 integer"), exc) |
| 30 | + if port not in range(1, 65536): |
| 31 | + raise ValueError("Port number is not in range(1, 65536)") |
| 32 | + |
| 33 | + return b''.join((onion3_host_bytes, struct.pack('>H', port))) |
| 34 | + |
| 35 | + |
| 36 | +def to_string(proto, buf): |
| 37 | + addr_bytes, port_bytes = (buf[:-2], buf[-2:]) |
| 38 | + addr = base64.b32encode(addr_bytes).decode('ascii').lower() |
| 39 | + port = six.text_type(struct.unpack('>H', port_bytes)[0]) |
| 40 | + return u':'.join([addr, port]) |
0 commit comments