mirror of
https://git.ugnet.gay/CrossTalk/azul.git
synced 2026-11-25 08:40:05 +00:00
0.6 final
This commit is contained in:
1 parent
7c0581eb97
commit
b89e1932bb
160 files changed
+20534
-4664
No files matched your search
@@ -0,0 +1 @@
|
||||
from .entry import register
|
||||
@@ -0,0 +1,122 @@
|
||||
import random
|
||||
import struct
|
||||
|
||||
# the V5 scrambling table: V5 packets are encrypted with it, and V3/V4/V5
|
||||
# checkcodes point into it
|
||||
V5_TABLE = bytes((
|
||||
0x59, 0x60, 0x37, 0x6B, 0x65, 0x62, 0x46, 0x48, 0x53, 0x61, 0x4C, 0x59, 0x60, 0x57, 0x5B, 0x3D,
|
||||
0x5E, 0x34, 0x6D, 0x36, 0x50, 0x3F, 0x6F, 0x67, 0x53, 0x61, 0x4C, 0x59, 0x40, 0x47, 0x63, 0x39,
|
||||
0x50, 0x5F, 0x5F, 0x3F, 0x6F, 0x47, 0x43, 0x69, 0x48, 0x33, 0x31, 0x64, 0x35, 0x5A, 0x4A, 0x42,
|
||||
0x56, 0x40, 0x67, 0x53, 0x41, 0x07, 0x6C, 0x49, 0x58, 0x3B, 0x4D, 0x46, 0x68, 0x43, 0x69, 0x48,
|
||||
0x33, 0x31, 0x44, 0x65, 0x62, 0x46, 0x48, 0x53, 0x41, 0x07, 0x6C, 0x69, 0x48, 0x33, 0x51, 0x54,
|
||||
0x5D, 0x4E, 0x6C, 0x49, 0x38, 0x4B, 0x55, 0x4A, 0x62, 0x46, 0x48, 0x33, 0x51, 0x34, 0x6D, 0x36,
|
||||
0x50, 0x5F, 0x5F, 0x5F, 0x3F, 0x6F, 0x47, 0x63, 0x59, 0x40, 0x67, 0x33, 0x31, 0x64, 0x35, 0x5A,
|
||||
0x6A, 0x52, 0x6E, 0x3C, 0x51, 0x34, 0x6D, 0x36, 0x50, 0x5F, 0x5F, 0x3F, 0x4F, 0x37, 0x4B, 0x35,
|
||||
0x5A, 0x4A, 0x62, 0x66, 0x58, 0x3B, 0x4D, 0x66, 0x58, 0x5B, 0x5D, 0x4E, 0x6C, 0x49, 0x58, 0x3B,
|
||||
0x4D, 0x66, 0x58, 0x3B, 0x4D, 0x46, 0x48, 0x53, 0x61, 0x4C, 0x59, 0x40, 0x67, 0x33, 0x31, 0x64,
|
||||
0x55, 0x6A, 0x32, 0x3E, 0x44, 0x45, 0x52, 0x6E, 0x3C, 0x31, 0x64, 0x55, 0x6A, 0x52, 0x4E, 0x6C,
|
||||
0x69, 0x48, 0x53, 0x61, 0x4C, 0x39, 0x30, 0x6F, 0x47, 0x63, 0x59, 0x60, 0x57, 0x5B, 0x3D, 0x3E,
|
||||
0x64, 0x35, 0x3A, 0x3A, 0x5A, 0x6A, 0x52, 0x4E, 0x6C, 0x69, 0x48, 0x53, 0x61, 0x6C, 0x49, 0x58,
|
||||
0x3B, 0x4D, 0x46, 0x68, 0x63, 0x39, 0x50, 0x5F, 0x5F, 0x3F, 0x6F, 0x67, 0x53, 0x41, 0x25, 0x41,
|
||||
0x3C, 0x51, 0x54, 0x3D, 0x5E, 0x54, 0x5D, 0x4E, 0x4C, 0x39, 0x50, 0x5F, 0x5F, 0x5F, 0x3F, 0x6F,
|
||||
0x47, 0x43, 0x69, 0x48, 0x33, 0x51, 0x54, 0x5D, 0x6E, 0x3C, 0x31, 0x64, 0x35, 0x5A, 0x00, 0x00,
|
||||
))
|
||||
|
||||
# the V4 table is the first 256 bytes of the tips text ICQ 98a ships with
|
||||
V4_TABLE = (
|
||||
b'\n[1] You can modify the sounds ICQ makes. Just select "Sounds" from the "preferences/misc" in ICQ or from the '
|
||||
b'"Sounds" in the control panel. Credit: Eran\n[2] Can\'t remember what was said? Double-click on a user to get a '
|
||||
b'dialog of all messages sent incomin'
|
||||
)
|
||||
|
||||
assert len(V5_TABLE) == 256 and len(V4_TABLE) == 256
|
||||
|
||||
# a V5 client packet's checkcode sits at 0x14, a server packet's at 0x11
|
||||
V5_CLIENT_CHECKCODE_OFFSET = 0x14
|
||||
V5_SERVER_CHECKCODE_OFFSET = 0x11
|
||||
# a V4 client packet's checkcode sits at 0x10, after the header it stands in for
|
||||
V4_CLIENT_CHECKCODE_OFFSET = 0x10
|
||||
|
||||
|
||||
def _u32(value: int) -> int:
|
||||
return value & 0xFFFFFFFF
|
||||
|
||||
def _descramble_v5_checkcode(check: int) -> int:
|
||||
# the checkcode's bits are shuffled before it goes into the key
|
||||
a1 = (check & 0x0001F000) >> 0x0C
|
||||
a2 = (check & 0x07C007C0) >> 0x01
|
||||
a3 = _u32((check & 0x003E0001) << 0x0A)
|
||||
a4 = (check & 0xF8000000) >> 0x10
|
||||
a5 = _u32((check & 0x0000083E) << 0x0F)
|
||||
return _u32(a5 + a1 + a2 + a3 + a4)
|
||||
|
||||
def decrypt_v5(packet: bytes) -> bytes:
|
||||
# a V5 client packet is encrypted from 0x0A on with a key made from its length and checkcode; the checkcode itself
|
||||
# (0x14..0x17) is left as it is
|
||||
if len(packet) < 0x18:
|
||||
return packet
|
||||
data = bytearray(packet)
|
||||
length = len(data)
|
||||
check = struct.unpack_from('<L', data, V5_CLIENT_CHECKCODE_OFFSET)[0]
|
||||
key = _u32(length * 0x68656C6C + _descramble_v5_checkcode(check))
|
||||
for i in range(0x0A, length + 3, 4):
|
||||
k = _u32(key + V5_TABLE[i & 0xFF])
|
||||
if i != 0x16:
|
||||
if i < length:
|
||||
data[i] ^= k & 0xFF
|
||||
if i + 1 < length:
|
||||
data[i + 1] ^= (k >> 8) & 0xFF
|
||||
if i != 0x12:
|
||||
if i + 2 < length:
|
||||
data[i + 2] ^= (k >> 16) & 0xFF
|
||||
if i + 3 < length:
|
||||
data[i + 3] ^= (k >> 24) & 0xFF
|
||||
return bytes(data)
|
||||
|
||||
def v5_checkcode(packet: bytes) -> int:
|
||||
# bytes 8, 4, 2 and 6 of the packet, against a random byte of the packet's first 16 and a random table entry
|
||||
b2, b4, b6, b8 = packet[2], packet[4], packet[6], packet[8]
|
||||
number1 = (b8 << 24) | (b4 << 16) | (b2 << 8) | b6
|
||||
x4 = random.randrange(0x10)
|
||||
x3 = packet[x4]
|
||||
x2 = random.randrange(0xFF)
|
||||
x1 = V5_TABLE[x2]
|
||||
number2 = ((x4 << 24) | (x3 << 16) | (x2 << 8) | x1) ^ 0x00FF00FF
|
||||
return _u32(number1 ^ number2)
|
||||
|
||||
def add_v5_server_checkcode(packet: bytearray) -> None:
|
||||
# server packets aren't encrypted, only stamped with a checkcode at 0x11 the client verifies
|
||||
struct.pack_into('<L', packet, V5_SERVER_CHECKCODE_OFFSET, v5_checkcode(bytes(packet)))
|
||||
|
||||
def decrypt_v4(packet: bytes) -> bytes:
|
||||
# V4 only encrypts the first quarter of a packet, a dword at a time with a key made from its length and checkcode; the
|
||||
# checkcode dword (the fifth) is skipped, and the version (never really encrypted) is put back
|
||||
if len(packet) < 0x14:
|
||||
return packet
|
||||
data = bytearray(packet)
|
||||
length = len(data)
|
||||
check = struct.unpack_from('<L', data, V4_CLIENT_CHECKCODE_OFFSET)[0]
|
||||
key = _u32(length * 0x66756B65 + check)
|
||||
count = ((length + 3) // 4 + 3) // 4
|
||||
for i in range(count):
|
||||
if i == 4:
|
||||
continue
|
||||
pos = i * 4
|
||||
if pos >= length:
|
||||
break
|
||||
k = _u32(key + V4_TABLE[pos & 0xFF])
|
||||
for j in range(4):
|
||||
if pos + j < length:
|
||||
data[pos + j] ^= (k >> (j * 8)) & 0xFF
|
||||
data[0:2] = b'\x04\x00'
|
||||
return bytes(data)
|
||||
|
||||
def v3_header_checkcode(header: bytes) -> int:
|
||||
# what a V4 client checks a server packet's V3 header against: bytes 8, 4, 2 and 6 of it, xored with an offset into the
|
||||
# header and the inverse of the byte there, and an offset into the V4 table and the inverse of that entry (the offsets
|
||||
# are the server's to pick; the first byte of seq1 and the first entry)
|
||||
check_a = (header[8] << 24) | (header[4] << 16) | (header[2] << 8) | header[6]
|
||||
packet_offset = 4
|
||||
table_offset = 0
|
||||
check_b = (packet_offset << 24) | ((~header[packet_offset] & 0xFF) << 16) | (table_offset << 8) | (~V4_TABLE[table_offset] & 0xFF)
|
||||
return _u32(check_a ^ check_b)
|
||||
+1075
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,98 @@
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
from core.models import User
|
||||
from util import icq
|
||||
|
||||
from front.oscar.proto.names import uin_of
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.backend import Backend
|
||||
|
||||
# a search hands back at most this many people
|
||||
MAX_RESULTS = 20
|
||||
|
||||
|
||||
def find(backend: 'Backend', uin: int) -> User | None:
|
||||
uuid = backend.util_get_uuid_from_uin(uin)
|
||||
return backend._load_user_record(uuid) if uuid is not None else None
|
||||
|
||||
def listed(user: User, viewer: User | None) -> bool:
|
||||
# the white pages only show someone who listed themselves in the member directory (or themselves, to themselves); the
|
||||
# same rule the OSCAR ICQ frontend goes by
|
||||
return user is viewer or bool(getattr(user, 'show_in_dir', False))
|
||||
|
||||
def _zip_number(text: str) -> int:
|
||||
# the old info packets carry the ZIP code as a number
|
||||
digits = ''.join(ch for ch in text if ch.isdigit())[:9]
|
||||
return int(digits) if digits else 0
|
||||
|
||||
def profile(user: User, viewer: User | None) -> dict[str, Any]:
|
||||
# everything the pre-OSCAR packets can show about `user`, as `viewer` may see it
|
||||
info = icq.basic_info(user)
|
||||
more = icq.more_info(user)
|
||||
work = icq.work_info(user)
|
||||
perms = icq.permissions(user)
|
||||
show = listed(user, viewer)
|
||||
uin = uin_of(user) or 0
|
||||
|
||||
def shown(value: Any, blank: Any = '') -> Any:
|
||||
return value if show else blank
|
||||
|
||||
affiliations = icq.affiliations(user)
|
||||
return {
|
||||
'uin': uin,
|
||||
'nick': info['nick'] or str(uin),
|
||||
'first': shown(info['first']),
|
||||
'last': shown(info['last']),
|
||||
# an e-mail address only ever goes out when its owner published it
|
||||
'email': info['email'] if info['publish_email'] or user is viewer else '',
|
||||
'publish_email': info['publish_email'],
|
||||
'city': shown(info['city']),
|
||||
'state': shown(info['state']),
|
||||
'phone': shown(info['phone']),
|
||||
'fax': shown(info['fax']),
|
||||
'address': shown(info['address']),
|
||||
'cell': shown(info['cell']),
|
||||
'zip': shown(info['zip']),
|
||||
'zip_number': shown(_zip_number(info['zip']), 0),
|
||||
'country': shown(info['country'], 0),
|
||||
'gmt': info['gmt'],
|
||||
'age': shown(icq.age(user), 0),
|
||||
'gender': shown(more['gender'], 0),
|
||||
'homepage': shown(more['homepage']),
|
||||
'birth_year': shown(more['birth_year'], 0),
|
||||
'birth_month': shown(more['birth_month'], 0),
|
||||
'birth_day': shown(more['birth_day'], 0),
|
||||
'lang1': more['lang1'],
|
||||
'lang2': more['lang2'],
|
||||
'lang3': more['lang3'],
|
||||
'notes': shown(icq.notes(user)),
|
||||
'work': { key: (value if show else (0 if isinstance(value, int) else '')) for key, value in work.items() },
|
||||
'work_zip_number': shown(_zip_number(work['zip']), 0),
|
||||
'interests': icq.interests(user) if show else [],
|
||||
'past_affiliations': affiliations['past'] if show else [],
|
||||
'affiliations': affiliations['current'] if show else [],
|
||||
'auth_required': perms['auth_required'],
|
||||
'web_aware': perms['web_aware'],
|
||||
}
|
||||
|
||||
def unknown_profile(uin: int) -> dict[str, Any]:
|
||||
# what the old info replies say about a UIN nobody has: its number for a nick, and nothing else
|
||||
return {
|
||||
'uin': uin, 'nick': str(uin), 'first': '', 'last': '', 'email': '', 'city': '', 'state': '', 'phone': '',
|
||||
'homepage': '', 'notes': '', 'country': 0, 'gmt': 0, 'age': 0, 'gender': 0, 'zip_number': 0, 'auth_required': False,
|
||||
}
|
||||
|
||||
def search(
|
||||
backend: 'Backend', *, email: str = '', first: str = '', last: str = '', nick: str = '',
|
||||
) -> list[User]:
|
||||
# a directory search: only people who listed themselves, and only those an ICQ client can name (by UIN)
|
||||
criteria = { key: value for key, value in (('email', email), ('first_name', first), ('last_name', last), ('nickname', nick)) if value }
|
||||
if not criteria:
|
||||
return []
|
||||
users = []
|
||||
for uuid in backend.user_service.search_uuids(**criteria):
|
||||
user = backend._load_user_record(uuid)
|
||||
if user is not None and uin_of(user) is not None:
|
||||
users.append(user)
|
||||
return users[:MAX_RESULTS]
|
||||
@@ -0,0 +1,139 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
import settings
|
||||
|
||||
from core.backend import Backend
|
||||
from util.misc import DatagramRunner, Logger
|
||||
|
||||
from . import wire
|
||||
from .ctrl import LegacyCtrl, prelogin
|
||||
from .packets import Command, Version
|
||||
|
||||
Address = tuple[str, int]
|
||||
|
||||
# a client that hasn't been heard from in this long is gone (it pings every minute or so)
|
||||
SESSION_TIMEOUT = 120
|
||||
REAP_INTERVAL = 30
|
||||
# how long a passed password check (CMD_GET_DEPS) waits for the login that follows it
|
||||
PREAUTH_LIFETIME = 60
|
||||
|
||||
# what a client sends before it has a session, answered the same whether or not it had one
|
||||
PRELOGIN_COMMANDS = frozenset({
|
||||
Command.Login, Command.GetDeps, Command.FirstLogin, Command.RegRequestInfo, Command.RegNewUser, Command.RegNewUserInfo,
|
||||
})
|
||||
|
||||
|
||||
def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None:
|
||||
# the pre-OSCAR ICQ protocols (V1-V5, ICQ 1.x to ICQ 2000a) are all UDP, on Mirabilis' port 4000
|
||||
port = getattr(settings, 'ICQ_LEGACY_PORT', 4000)
|
||||
backend.add_runner(DatagramRunner('0.0.0.0', port, ListenerICQ, args = ['ICQ', backend], service = 'ICQ'))
|
||||
|
||||
|
||||
class ListenerICQ(asyncio.DatagramProtocol):
|
||||
# one endpoint for every client: each datagram finds its session by the address it came from
|
||||
logger: Logger
|
||||
backend: Backend
|
||||
transport: asyncio.DatagramTransport | None
|
||||
by_addr: dict[Address, LegacyCtrl]
|
||||
by_uin: dict[int, LegacyCtrl]
|
||||
preauth: dict[Address, float]
|
||||
_reaper: asyncio.Task | None
|
||||
|
||||
def __init__(self, logger_prefix: str, backend: Backend) -> None:
|
||||
super().__init__()
|
||||
self.logger = Logger(logger_prefix, self)
|
||||
self.backend = backend
|
||||
self.transport = None
|
||||
self.by_addr = {}
|
||||
self.by_uin = {}
|
||||
self.preauth = {}
|
||||
self._reaper = None
|
||||
|
||||
def connection_made(self, transport: asyncio.BaseTransport) -> None:
|
||||
assert isinstance(transport, asyncio.DatagramTransport)
|
||||
self.transport = transport
|
||||
self._reaper = self.backend.loop.create_task(self._reap())
|
||||
|
||||
def connection_lost(self, exc: Exception | None) -> None:
|
||||
if self._reaper is not None:
|
||||
self._reaper.cancel()
|
||||
self._reaper = None
|
||||
for ctrl in list(self.by_uin.values()):
|
||||
ctrl.close()
|
||||
self.transport = None
|
||||
|
||||
def error_received(self, exc: Exception) -> None:
|
||||
# an ICMP port unreachable from a client that went away; its session times out by itself
|
||||
self.logger.info('UDP error:', str(exc))
|
||||
|
||||
def send(self, packet: bytes, addr: Address) -> None:
|
||||
if self.transport is not None:
|
||||
self.transport.sendto(packet, addr)
|
||||
|
||||
def datagram_received(self, packet: bytes, addr: Address) -> None:
|
||||
if self.backend.maintenance_mode:
|
||||
return
|
||||
try:
|
||||
parsed = wire.parse(packet)
|
||||
if parsed is None:
|
||||
self.logger.info('Dropped a datagram that is no ICQ packet from', addr[0])
|
||||
return
|
||||
header, data = parsed
|
||||
self.logger.debug('[Client]', header, 'from', addr)
|
||||
ctrl = self._find(header, addr)
|
||||
if ctrl is None or header.command in PRELOGIN_COMMANDS:
|
||||
# (a login or the steps before it from an address that already has a session: the client started over)
|
||||
prelogin(self, header, data, addr)
|
||||
else:
|
||||
ctrl.on_packet(header, data)
|
||||
except Exception as ex:
|
||||
self.logger.error(ex)
|
||||
|
||||
def _find(self, header: wire.Header, addr: Address) -> LegacyCtrl | None:
|
||||
ctrl = self.by_addr.get(addr)
|
||||
if ctrl is not None:
|
||||
if ctrl.uin != header.uin and header.uin:
|
||||
return None
|
||||
return ctrl
|
||||
# a client behind NAT can turn up from a new port: the same UIN from the same host (and for V5 the same session)
|
||||
# is the same session
|
||||
ctrl = self.by_uin.get(header.uin) if header.uin else None
|
||||
if ctrl is None or ctrl.addr[0] != addr[0] or ctrl.version != header.version:
|
||||
return None
|
||||
if header.version == Version.V5 and ctrl.session_id != header.session_id:
|
||||
return None
|
||||
self.by_addr.pop(ctrl.addr, None)
|
||||
ctrl.addr = addr
|
||||
self.by_addr[addr] = ctrl
|
||||
return ctrl
|
||||
|
||||
def add(self, ctrl: LegacyCtrl) -> None:
|
||||
self.by_addr[ctrl.addr] = ctrl
|
||||
self.by_uin[ctrl.uin] = ctrl
|
||||
|
||||
def remove(self, ctrl: LegacyCtrl) -> None:
|
||||
if self.by_addr.get(ctrl.addr) is ctrl:
|
||||
del self.by_addr[ctrl.addr]
|
||||
if self.by_uin.get(ctrl.uin) is ctrl:
|
||||
del self.by_uin[ctrl.uin]
|
||||
|
||||
def note_preauth(self, addr: Address) -> None:
|
||||
self.preauth[addr] = time.monotonic()
|
||||
|
||||
def take_preauth(self, addr: Address) -> bool:
|
||||
noted = self.preauth.pop(addr, None)
|
||||
return noted is not None and time.monotonic() - noted < PREAUTH_LIFETIME
|
||||
|
||||
async def _reap(self) -> None:
|
||||
# UDP has no hang-up: a session that stops pinging is signed off
|
||||
while True:
|
||||
await asyncio.sleep(REAP_INTERVAL)
|
||||
now = time.monotonic()
|
||||
for ctrl in list(self.by_uin.values()):
|
||||
if now - ctrl.last_activity > SESSION_TIMEOUT:
|
||||
ctrl.logger.info('Timed out')
|
||||
ctrl.close()
|
||||
for addr, noted in list(self.preauth.items()):
|
||||
if now - noted > PREAUTH_LIFETIME:
|
||||
del self.preauth[addr]
|
||||
@@ -0,0 +1,160 @@
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
from core import event
|
||||
from core.models import Circle, CircleRole, Contact, LoginOption, MessageData, MessageType, OIM, Substatus, TextWithData, User
|
||||
|
||||
from front.oscar.proto.names import uin_of
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.backend import Chat, ChatSession
|
||||
from .ctrl import LegacyCtrl
|
||||
|
||||
|
||||
class BackendEventHandler(event.BackendEventHandler):
|
||||
__slots__ = ('ctrl',)
|
||||
|
||||
ctrl: 'LegacyCtrl'
|
||||
|
||||
def __init__(self, ctrl: 'LegacyCtrl') -> None:
|
||||
self.ctrl = ctrl
|
||||
|
||||
def on_close(self) -> None:
|
||||
self.ctrl.close()
|
||||
|
||||
def on_maintenance_boot(self) -> None:
|
||||
self.ctrl.close()
|
||||
|
||||
def on_presence_notification(
|
||||
self, ctc: Contact, on_contact_add: bool, old_substatus: Substatus, *,
|
||||
trid: str | None = None, update_status: bool = True, update_info_other: bool = True,
|
||||
send_status_on_bl: bool = False, sess_id: int | None = None, updated_phone_info: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
# only the people on the client's own contact list, and only when their status is what changed
|
||||
if not update_status:
|
||||
return
|
||||
try:
|
||||
self.ctrl.on_presence(ctc)
|
||||
except Exception as ex:
|
||||
self.ctrl.logger.error(ex)
|
||||
|
||||
def on_presence_self_notification(self, old_substatus: Substatus, *, update_status: bool = True, update_info: bool = True) -> None:
|
||||
pass
|
||||
|
||||
def on_chat_invite(
|
||||
self, chat: 'Chat', inviter: User, *, circle: bool = False, inviter_id: str | None = None, invite_msg: str = '',
|
||||
) -> None:
|
||||
if chat is None:
|
||||
chat = self.ctrl.backend.chat_create()
|
||||
chat.add_id('icq0', chat.ids['main'])
|
||||
self.ctrl.join_chat(chat, inviter)
|
||||
|
||||
def on_declined_chat_invite(self, chat: 'Chat', circle: bool = False) -> None:
|
||||
pass
|
||||
|
||||
def on_added_me(self, user: User, *, adder_id: str | None = None, message: TextWithData | None = None) -> None:
|
||||
# someone put this account on their (stored) contact list: ICQ's "you were added", unless they're still waiting on
|
||||
# this account's authorization
|
||||
if uin_of(user) is None:
|
||||
return
|
||||
from front.oscar.foodgroups.buddy import buddy_pending
|
||||
if buddy_pending(user, self.ctrl.user):
|
||||
return
|
||||
self.ctrl.on_auth_event('added', user, '')
|
||||
|
||||
def on_removed_me(self, user: User) -> None:
|
||||
pass
|
||||
|
||||
def on_contact_request_denied(self, user_added: User, message: str | None, *, contact_id: str | None = None) -> None:
|
||||
pass
|
||||
|
||||
def on_login_elsewhere(self, option: LoginOption) -> None:
|
||||
self.ctrl.force_offline()
|
||||
|
||||
def on_oim_sent(self, oim: OIM) -> None:
|
||||
self.ctrl.deliver_oim_now(oim)
|
||||
|
||||
def icq_on_auth_event(self, event: str, sender: User, text: str) -> None:
|
||||
# authorization traffic from the OSCAR ICQ frontend's machinery (see `front.oscar.foodgroups.feedbag`)
|
||||
self.ctrl.on_auth_event(event, sender, text)
|
||||
|
||||
def icq_on_message(self, sender: User, msg_type: int, text: str) -> None:
|
||||
# an ICQ-only message (chat/file request, plugin...) relayed from an OSCAR ICQ client
|
||||
uin = uin_of(sender)
|
||||
if uin is not None:
|
||||
self.ctrl.deliver_message(uin, msg_type, text)
|
||||
|
||||
# circles are not a thing in ICQ
|
||||
def on_circle_invite_revoked(self, chat_id: str) -> None:
|
||||
pass
|
||||
|
||||
def on_accepted_circle_invite(self, circle: Circle) -> None:
|
||||
pass
|
||||
|
||||
def on_circle_updated(self, circle: Circle) -> None:
|
||||
pass
|
||||
|
||||
def on_left_circle(self, circle: Circle) -> None:
|
||||
pass
|
||||
|
||||
def on_circle_role_updated(self, chat_id: str, role: CircleRole) -> None:
|
||||
pass
|
||||
|
||||
def on_circle_created(self, circle: Circle) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class ChatEventHandler(event.ChatEventHandler):
|
||||
__slots__ = ('ctrl', 'cs', '_pending')
|
||||
|
||||
ctrl: 'LegacyCtrl'
|
||||
cs: 'ChatSession'
|
||||
_pending: list[tuple[str, MessageData]]
|
||||
|
||||
def __init__(self, ctrl: 'LegacyCtrl') -> None:
|
||||
self.ctrl = ctrl
|
||||
self._pending = []
|
||||
|
||||
def on_participant_joined(self, cs_other: 'ChatSession', first_pop: bool, initial_join: bool) -> None:
|
||||
still_pending = []
|
||||
for target_uuid, data in self._pending:
|
||||
if cs_other.user.uuid == target_uuid:
|
||||
self.cs.send_message_to_user(target_uuid, data)
|
||||
else:
|
||||
still_pending.append((target_uuid, data))
|
||||
self._pending = still_pending
|
||||
|
||||
def on_participant_left(self, cs_other: 'ChatSession', last_pop: bool) -> None:
|
||||
# once the other side is gone this chat can't reach them again (they'd be invited to a new one), so it's let go
|
||||
if any(cs is not self.cs for cs in self.cs.chat.get_roster()):
|
||||
return
|
||||
for uuid, (cs, _) in list(self.ctrl.chats.items()):
|
||||
if cs is self.cs:
|
||||
del self.ctrl.chats[uuid]
|
||||
# (closed once the chat is done telling everyone, since it's still walking its roster)
|
||||
self.ctrl.backend.loop.call_soon(self.cs.close)
|
||||
|
||||
def on_chat_invite_declined(
|
||||
self, chat: 'Chat', invitee: User, *, invitee_id: str | None = None, message: str | None = None, circle: bool = False,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
def on_chat_updated(self) -> None:
|
||||
pass
|
||||
|
||||
def on_chat_roster_updated(self) -> None:
|
||||
pass
|
||||
|
||||
def on_participant_status_updated(self, cs_other: 'ChatSession', first_pop: bool, initial: bool, old_substatus: Substatus) -> None:
|
||||
pass
|
||||
|
||||
def on_message(self, data: MessageData) -> None:
|
||||
# typing notifications and the like have no ICQ form before OSCAR; only messages go through
|
||||
if self.ctrl.bs is None or data.sender is self.ctrl.bs.user or data.type is not MessageType.Chat:
|
||||
return
|
||||
self.ctrl.deliver_chat_message(data)
|
||||
|
||||
def send_when_joined(self, user_uuid: str, data: MessageData) -> None:
|
||||
if any(cs_other.user.uuid == user_uuid for cs_other in self.cs.chat.get_roster()):
|
||||
self.cs.send_message_to_user(user_uuid, data)
|
||||
else:
|
||||
self._pending.append((user_uuid, data))
|
||||
@@ -0,0 +1,709 @@
|
||||
import struct
|
||||
|
||||
from datetime import datetime
|
||||
from enum import IntEnum
|
||||
from typing import Any
|
||||
|
||||
from core.models import OIM, User
|
||||
from util import icq
|
||||
from util.misc import Logger
|
||||
|
||||
from ..proto import names
|
||||
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
|
||||
from ..proto.tlv import TLV, unmarshal_tlvs, find_tlv
|
||||
|
||||
|
||||
class ICQRequest(IntEnum):
|
||||
# ICQ__DB_QUERY request types (the u16 after the UIN in the little-endian envelope)
|
||||
OfflineMessages = 0x003C
|
||||
DeleteOfflineMessages = 0x003E
|
||||
Meta = 0x07D0
|
||||
|
||||
class ICQReply(IntEnum):
|
||||
OfflineMessage = 0x0041
|
||||
OfflineMessagesDone = 0x0042
|
||||
Meta = 0x07DA
|
||||
|
||||
class ICQResult(IntEnum):
|
||||
Ok = 0x0A
|
||||
Fail = 0x32
|
||||
Error = 0x14
|
||||
|
||||
class ICQMeta(IntEnum):
|
||||
# requests
|
||||
SetBasicInfo = 0x03EA
|
||||
SetWorkInfo = 0x03F3
|
||||
SetMoreInfo = 0x03FD
|
||||
SetNotes = 0x0406
|
||||
SetEmails = 0x040B
|
||||
SetInterests = 0x0410
|
||||
SetAffiliations = 0x041A
|
||||
SetPermissions = 0x0424
|
||||
FullInfo = 0x04B2
|
||||
ShortInfo = 0x04BA
|
||||
FullInfo2 = 0x04D0
|
||||
SearchByDetails = 0x0515
|
||||
SearchByUin = 0x051F
|
||||
SearchByEmail = 0x0529
|
||||
SearchWhitePages = 0x0533
|
||||
SearchWhitePages2 = 0x055F
|
||||
SearchByUin2 = 0x0569
|
||||
SearchByEmail3 = 0x0573
|
||||
SetIcqPhone = 0x0654
|
||||
XmlRequest = 0x0898
|
||||
SetFullInfo = 0x0C3A
|
||||
DirectoryQuery = 0x0FA0
|
||||
# replies
|
||||
SetBasicInfoAck = 0x0064
|
||||
SetWorkInfoAck = 0x006E
|
||||
SetMoreInfoAck = 0x0078
|
||||
SetNotesAck = 0x0082
|
||||
SetEmailsAck = 0x0087
|
||||
SetInterestsAck = 0x008C
|
||||
SetAffiliationsAck = 0x0096
|
||||
SetPermissionsAck = 0x00A0
|
||||
BasicInfo = 0x00C8
|
||||
WorkInfo = 0x00D2
|
||||
MoreInfo = 0x00DC
|
||||
Notes = 0x00E6
|
||||
ExtEmails = 0x00EB
|
||||
Interests = 0x00F0
|
||||
Affiliations = 0x00FA
|
||||
ShortInfoReply = 0x0104
|
||||
HomepageCategory = 0x010E
|
||||
UserFound = 0x01A4
|
||||
LastUserFound = 0x01AE
|
||||
SetIcqPhoneAck = 0x031E
|
||||
SetFullInfoAck = 0x0C3F
|
||||
XmlReply = 0x08A2
|
||||
DirectoryResponse = 0x0FB4
|
||||
|
||||
# ICQ__TLV tags for the TLV-based requests (white pages 2, search by UIN 2/e-mail 3, set full info); values little endian
|
||||
class ICQTag(IntEnum):
|
||||
Uin = 0x0136
|
||||
FirstName = 0x0140
|
||||
LastName = 0x014A
|
||||
Nickname = 0x0154
|
||||
Email = 0x015E
|
||||
Gender = 0x017C
|
||||
HomeCity = 0x0190
|
||||
HomeState = 0x019A
|
||||
HomeCountry = 0x01A4
|
||||
WorkCompany = 0x01AE
|
||||
WorkDepartment = 0x01B8
|
||||
WorkPosition = 0x01C2
|
||||
WorkOccupation = 0x01CC
|
||||
HomepageUrl = 0x0213
|
||||
OnlineOnly = 0x0230
|
||||
Birthday = 0x023A
|
||||
Notes = 0x0258
|
||||
HomeAddress = 0x0262
|
||||
HomeZip = 0x026C
|
||||
HomePhone = 0x0276
|
||||
HomeFax = 0x0280
|
||||
HomeCell = 0x028A
|
||||
WorkAddress = 0x0294
|
||||
WorkCity = 0x029E
|
||||
WorkState = 0x02A8
|
||||
WorkCountry = 0x02B2
|
||||
WorkZip = 0x02BC
|
||||
WorkPhone = 0x02C6
|
||||
WorkFax = 0x02D0
|
||||
WorkWebpage = 0x02DA
|
||||
Authorization = 0x02F8
|
||||
WebAware = 0x030C
|
||||
GmtOffset = 0x0316
|
||||
|
||||
# search hits' online status
|
||||
DIR_STATUS_OFFLINE = 0
|
||||
DIR_STATUS_ONLINE = 1
|
||||
DIR_STATUS_HIDDEN = 2
|
||||
|
||||
MAX_SEARCH_RESULTS = 20
|
||||
|
||||
|
||||
class LE:
|
||||
# a little-endian writer, the byte order the ICQ envelope inside foodgroup 0x15 uses
|
||||
__slots__ = ('data',)
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.data = b''
|
||||
|
||||
def u8(self, value: int) -> 'LE':
|
||||
self.data += struct.pack('<B', value & 0xFF)
|
||||
return self
|
||||
|
||||
def u16(self, value: int) -> 'LE':
|
||||
self.data += struct.pack('<H', value & 0xFFFF)
|
||||
return self
|
||||
|
||||
def u32(self, value: int) -> 'LE':
|
||||
self.data += struct.pack('<L', value & 0xFFFFFFFF)
|
||||
return self
|
||||
|
||||
def raw(self, value: bytes) -> 'LE':
|
||||
self.data += value
|
||||
return self
|
||||
|
||||
def string(self, value: str) -> 'LE':
|
||||
# u16 length, then the text and its NUL; an empty string is just a zero length
|
||||
if not value:
|
||||
return self.u16(0)
|
||||
encoded = icq.latin1(value) + b'\x00'
|
||||
return self.u16(len(encoded)).raw(encoded)
|
||||
|
||||
class LEReader:
|
||||
__slots__ = ('data', 'pos')
|
||||
|
||||
def __init__(self, data: bytes) -> None:
|
||||
self.data = data
|
||||
self.pos = 0
|
||||
|
||||
def remaining(self) -> int:
|
||||
return len(self.data) - self.pos
|
||||
|
||||
def _take(self, length: int) -> bytes:
|
||||
if self.pos + length > len(self.data):
|
||||
raise ValueError('truncated ICQ request')
|
||||
chunk = self.data[self.pos:self.pos + length]
|
||||
self.pos += length
|
||||
return chunk
|
||||
|
||||
def u8(self) -> int:
|
||||
return self._take(1)[0]
|
||||
|
||||
def u16(self) -> int:
|
||||
return struct.unpack('<H', self._take(2))[0]
|
||||
|
||||
def u32(self) -> int:
|
||||
return struct.unpack('<L', self._take(4))[0]
|
||||
|
||||
def string(self) -> str:
|
||||
raw = self._take(self.u16())
|
||||
if b'\x00' in raw:
|
||||
raw = raw[:raw.index(b'\x00')]
|
||||
return icq.from_latin1(raw)
|
||||
|
||||
def rest(self) -> bytes:
|
||||
chunk = self.data[self.pos:]
|
||||
self.pos = len(self.data)
|
||||
return chunk
|
||||
|
||||
def parse_le_tlvs(data: bytes) -> list[tuple[int, bytes]]:
|
||||
# the TLV-based ICQ requests use little-endian TLVs
|
||||
tlvs = []
|
||||
reader = LEReader(data)
|
||||
while reader.remaining() >= 4:
|
||||
tag = reader.u16()
|
||||
length = reader.u16()
|
||||
if reader.remaining() < length:
|
||||
break
|
||||
tlvs.append((tag, reader._take(length)))
|
||||
return tlvs
|
||||
|
||||
def tlv_string(value: bytes) -> str:
|
||||
try:
|
||||
return LEReader(value).string()
|
||||
except ValueError:
|
||||
return ''
|
||||
|
||||
def tlv_int(value: bytes) -> int:
|
||||
if len(value) >= 4:
|
||||
return struct.unpack('<L', value[:4])[0]
|
||||
if len(value) >= 2:
|
||||
return struct.unpack('<H', value[:2])[0]
|
||||
return value[0] if value else 0
|
||||
|
||||
|
||||
class ICQContext:
|
||||
# one ICQ__DB_QUERY being answered: who asked, under which SNAC request id and ICQ sequence number
|
||||
__slots__ = ('client', 'context', 'request_id', 'seq', 'uin')
|
||||
|
||||
def __init__(self, client: OSCARClient, context: OSCARContext, request_id: int, seq: int) -> None:
|
||||
self.client = client
|
||||
self.context = context
|
||||
self.request_id = request_id
|
||||
self.seq = seq
|
||||
self.uin = names.uin_of(context.user) or 0
|
||||
|
||||
def reply(self, reply_type: int, body: bytes, *, more: bool = False) -> None:
|
||||
# ICQ__DB_REPLY: TLV 0x01 holding a u16 (LE) length, then u32 UIN, u16 reply type, u16 sequence and the body
|
||||
envelope = LE().u32(self.uin).u16(reply_type).u16(self.seq).raw(body).data
|
||||
msg = SNACMessage(0x0015, 0x0003, 0x0001 if more else 0x0000, self.request_id)
|
||||
msg.write_tlv(TLV(0x0001, LE().u16(len(envelope)).raw(envelope).data))
|
||||
self.client.send_snac(msg)
|
||||
|
||||
def meta(self, subtype: int, result: int, body: bytes = b'', *, more: bool = False) -> None:
|
||||
self.reply(ICQReply.Meta, LE().u16(subtype).u8(result).raw(body if result == ICQResult.Ok else b'').data, more = more)
|
||||
|
||||
|
||||
@Foodgroup(0x0015)
|
||||
class ICQFoodgroup:
|
||||
logger: Logger
|
||||
|
||||
@Subgroup(0x0002)
|
||||
def db_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
|
||||
tlvs = unmarshal_tlvs(message.data)
|
||||
envelope_tlv = find_tlv(tlvs, 0x0001)
|
||||
if envelope_tlv is None or len(envelope_tlv.data) < 2:
|
||||
self.logger.info('[Client] ICQ__DB_QUERY without its envelope')
|
||||
return
|
||||
|
||||
# TLV 0x01: u16 (LE) length, u32 UIN, u16 request type, u16 sequence, [u16 meta subtype], request data
|
||||
reader = LEReader(envelope_tlv.data)
|
||||
try:
|
||||
length = reader.u16()
|
||||
reader = LEReader(reader._take(min(length, reader.remaining())))
|
||||
reader.u32()
|
||||
request_type = reader.u16()
|
||||
seq = reader.u16()
|
||||
except ValueError:
|
||||
self.logger.info('[Client] Truncated ICQ__DB_QUERY')
|
||||
return
|
||||
|
||||
query = ICQContext(client, context, message.request_id, seq)
|
||||
if request_type == ICQRequest.OfflineMessages:
|
||||
self.logger.info('[Client] ICQ__DB_QUERY offline messages')
|
||||
offline_messages(query)
|
||||
elif request_type == ICQRequest.DeleteOfflineMessages:
|
||||
self.logger.info('[Client] ICQ__DB_QUERY delete offline messages')
|
||||
delete_offline_messages(query)
|
||||
elif request_type == ICQRequest.Meta:
|
||||
try:
|
||||
subtype = reader.u16()
|
||||
except ValueError:
|
||||
return
|
||||
self.logger.info('[Client] ICQ__DB_QUERY meta', hex(subtype))
|
||||
handler = META_HANDLERS.get(subtype)
|
||||
if handler is None:
|
||||
self.logger.info('[Client] Unsupported ICQ meta request', hex(subtype))
|
||||
return
|
||||
try:
|
||||
handler(query, reader)
|
||||
except ValueError:
|
||||
self.logger.info('[Client] Malformed ICQ meta request', hex(subtype))
|
||||
else:
|
||||
self.logger.info('[Client] Unknown ICQ__DB_QUERY request type', hex(request_type))
|
||||
|
||||
|
||||
# offline messages
|
||||
|
||||
def offline_messages(query: ICQContext) -> None:
|
||||
# reading the store is file work, done off the event loop
|
||||
query.context.backend.loop.create_task(_offline_messages(query))
|
||||
|
||||
async def _offline_messages(query: ICQContext) -> None:
|
||||
# each stored message from someone with a UIN goes back as an offline message record (0x41); the rest only an ICBM
|
||||
# can carry, since 0x41 has no room for a screen name. 0x42 ends it, and the messages go once the client deletes them
|
||||
context = query.context
|
||||
backend = context.backend
|
||||
bs = context.bs
|
||||
from .icbm import deliver_offline_messages
|
||||
oims = await backend.loop.run_in_executor(None, backend.user_service.get_oim_batch, context.user)
|
||||
if bs.closed:
|
||||
return
|
||||
pending = bs.front_data.setdefault('oscar0_offline_delivered', [])
|
||||
for oim in oims:
|
||||
sender = _oim_sender(backend, oim)
|
||||
uin = names.uin_of(sender) if sender is not None else None
|
||||
if uin is None:
|
||||
deliver_offline_messages(query.client.ctrl, [oim])
|
||||
continue
|
||||
sent = oim.sent if isinstance(oim.sent, datetime) else datetime.utcnow()
|
||||
body = LE().u32(uin).u16(sent.year).u8(sent.month).u8(sent.day).u8(sent.hour).u8(sent.minute)
|
||||
body.u8(0x01).u8(0x00).string((oim.message or '').replace('\r\n', '\n').replace('\n', '\r\n'))
|
||||
query.reply(ICQReply.OfflineMessage, body.data, more = True)
|
||||
pending.append(oim.uuid)
|
||||
query.reply(ICQReply.OfflineMessagesDone, LE().u8(0).data)
|
||||
|
||||
def delete_offline_messages(query: ICQContext) -> None:
|
||||
context = query.context
|
||||
delivered = context.bs.front_data.pop('oscar0_offline_delivered', [])
|
||||
if delivered:
|
||||
from .icbm import delete_stored_messages
|
||||
context.backend.loop.create_task(delete_stored_messages(context.backend, context.user.uuid, delivered))
|
||||
|
||||
def _oim_sender(backend: Any, oim: OIM) -> User | None:
|
||||
uuid = backend.util_get_uuid_from_username(oim.from_username) if oim.from_username else None
|
||||
if uuid is None and oim.from_email:
|
||||
uuid = backend.util_get_uuid_from_email(oim.from_email)
|
||||
return backend._load_user_record(uuid) if uuid is not None else None
|
||||
|
||||
|
||||
# user info
|
||||
|
||||
def _find(backend: Any, uin: int) -> User | None:
|
||||
uuid = backend.util_get_uuid_from_uin(uin)
|
||||
return backend._load_user_record(uuid) if uuid is not None else None
|
||||
|
||||
def _listed(user: User, viewer: User | None = None) -> bool:
|
||||
# the white pages only show someone who listed themselves in the member directory (or themselves, to themselves)
|
||||
return user is viewer or bool(getattr(user, 'show_in_dir', False))
|
||||
|
||||
def _auth_flag(user: User) -> int:
|
||||
# 0 means authorization required, 1 that anyone may add this user
|
||||
return 0 if icq.permissions(user)['auth_required'] else 1
|
||||
|
||||
def basic_info_body(user: User, viewer: User | None = None) -> bytes:
|
||||
info = icq.basic_info(user)
|
||||
perms = icq.permissions(user)
|
||||
listed = _listed(user, viewer)
|
||||
body = LE().string(info['nick'])
|
||||
# real names and contact details only for people listed in the directory
|
||||
for field in ('first', 'last'):
|
||||
body.string(info[field] if listed else '')
|
||||
body.string(info['email'] if info['publish_email'] or user is viewer else '')
|
||||
for field in ('city', 'state', 'phone', 'fax', 'address', 'cell', 'zip'):
|
||||
body.string(info[field] if listed else '')
|
||||
body.u16(info['country'] if listed else 0).u8(info['gmt'])
|
||||
body.u8(_auth_flag(user)).u8(1 if perms['web_aware'] else 0).u8(0)
|
||||
# publish e-mail: 0 yes, 1 no
|
||||
body.u8(0 if info['publish_email'] else 1)
|
||||
return body.data
|
||||
|
||||
def more_info_body(user: User, viewer: User | None = None) -> bytes:
|
||||
more = icq.more_info(user)
|
||||
info = icq.basic_info(user)
|
||||
listed = _listed(user, viewer)
|
||||
body = LE().u16(icq.age(user) if listed else 0).u8(more['gender'] if listed else 0).string(more['homepage'] if listed else '')
|
||||
body.u16(more['birth_year'] if listed else 0).u8(more['birth_month'] if listed else 0).u8(more['birth_day'] if listed else 0)
|
||||
body.u8(more['lang1']).u8(more['lang2']).u8(more['lang3']).u16(0)
|
||||
body.string(info['city'] if listed else '').string(info['state'] if listed else '').u16(info['country'] if listed else 0)
|
||||
body.u8(info['gmt'])
|
||||
# trailing bytes ICQ 5 wants, or it reports "error 117"
|
||||
body.raw(bytes(4))
|
||||
return body.data
|
||||
|
||||
def work_info_body(user: User, viewer: User | None = None) -> bytes:
|
||||
work = icq.work_info(user) if _listed(user, viewer) else { field: '' for field in ('city', 'state', 'phone', 'fax', 'address', 'zip', 'company', 'department', 'position', 'webpage') }
|
||||
body = LE()
|
||||
for field in ('city', 'state', 'phone', 'fax', 'address', 'zip'):
|
||||
body.string(work[field])
|
||||
body.u16(work.get('country', 0) or 0)
|
||||
for field in ('company', 'department', 'position'):
|
||||
body.string(work[field])
|
||||
body.u16(work.get('occupation', 0) or 0).string(work['webpage'])
|
||||
return body.data
|
||||
|
||||
def _pairs_body(pairs: list[list[Any]]) -> LE:
|
||||
body = LE().u8(len(pairs))
|
||||
for code, keyword in pairs:
|
||||
body.u16(int(code)).string(keyword)
|
||||
return body
|
||||
|
||||
def short_info_body(user: User, viewer: User | None = None) -> bytes:
|
||||
info = icq.basic_info(user)
|
||||
listed = _listed(user, viewer)
|
||||
body = LE().string(info['nick']).string(info['first'] if listed else '').string(info['last'] if listed else '')
|
||||
body.string(info['email'] if info['publish_email'] or user is viewer else '').u8(_auth_flag(user)).u8(0)
|
||||
body.u8(icq.more_info(user)['gender'] if listed else 0)
|
||||
return body.data
|
||||
|
||||
def search_record(query: ICQContext, user: User) -> bytes:
|
||||
# a search hit: u16 length, then UIN, nick, first, last, e-mail, auth flag, online status, gender, age
|
||||
info = icq.basic_info(user)
|
||||
listed = _listed(user, query.context.user)
|
||||
record = LE().u32(names.uin_of(user) or 0).string(info['nick'])
|
||||
record.string(info['first'] if listed else '').string(info['last'] if listed else '')
|
||||
record.string(info['email'] if info['publish_email'] else '')
|
||||
record.u8(_auth_flag(user)).u16(_search_status(query, user))
|
||||
record.u8(icq.more_info(user)['gender'] if listed else 0).u16(icq.age(user) if listed else 0)
|
||||
return LE().u16(len(record.data)).raw(record.data).data
|
||||
|
||||
def _search_status(query: ICQContext, user: User) -> int:
|
||||
# someone not "web aware" shows as hidden whether or not they're on
|
||||
if not icq.permissions(user)['web_aware']:
|
||||
return DIR_STATUS_HIDDEN
|
||||
sessions = query.context.backend.util_get_sessions_by_user(user)
|
||||
return DIR_STATUS_ONLINE if sessions and not user.status.is_offlineish() else DIR_STATUS_OFFLINE
|
||||
|
||||
def search_results(query: ICQContext, users: list[User]) -> None:
|
||||
# every hit but the last is "user found" (with the trailing bytes ICQ 5 wants); the last says how many are left
|
||||
users = [user for user in users if names.uin_of(user) is not None][:MAX_SEARCH_RESULTS]
|
||||
if not users:
|
||||
query.meta(ICQMeta.LastUserFound, ICQResult.Fail)
|
||||
return
|
||||
for index, user in enumerate(users):
|
||||
if index < len(users) - 1:
|
||||
query.meta(ICQMeta.UserFound, ICQResult.Ok, search_record(query, user) + bytes(12), more = True)
|
||||
else:
|
||||
query.meta(ICQMeta.LastUserFound, ICQResult.Ok, search_record(query, user) + LE().u32(0).data + bytes(8))
|
||||
|
||||
def _users(backend: Any, uuids: list[str]) -> list[User]:
|
||||
users = []
|
||||
for uuid in uuids:
|
||||
user = backend._load_user_record(uuid)
|
||||
if user is not None:
|
||||
users.append(user)
|
||||
return users
|
||||
|
||||
|
||||
def meta_short_info(query: ICQContext, reader: LEReader) -> None:
|
||||
user = _find(query.context.backend, reader.u32())
|
||||
if user is None:
|
||||
query.meta(ICQMeta.ShortInfoReply, ICQResult.Error)
|
||||
return
|
||||
query.meta(ICQMeta.ShortInfoReply, ICQResult.Ok, short_info_body(user, query.context.user))
|
||||
|
||||
def meta_full_info(query: ICQContext, reader: LEReader) -> None:
|
||||
# basic, more, extra e-mails, homepage category, work, notes, interests, affiliations: each part says more follow
|
||||
user = _find(query.context.backend, reader.u32())
|
||||
if user is None:
|
||||
query.meta(ICQMeta.BasicInfo, ICQResult.Error)
|
||||
return
|
||||
viewer = query.context.user
|
||||
listed = _listed(user, viewer)
|
||||
parts = [
|
||||
(ICQMeta.BasicInfo, basic_info_body(user, viewer)),
|
||||
(ICQMeta.MoreInfo, more_info_body(user, viewer)),
|
||||
(ICQMeta.ExtEmails, LE().u8(0).data),
|
||||
(ICQMeta.HomepageCategory, LE().u8(0).u16(0).string('').u8(0).data),
|
||||
(ICQMeta.WorkInfo, work_info_body(user, viewer)),
|
||||
(ICQMeta.Notes, LE().string(icq.notes(user) if listed else '').data),
|
||||
(ICQMeta.Interests, _pairs_body(icq.interests(user) if listed else []).data),
|
||||
(ICQMeta.Affiliations, (
|
||||
_pairs_body(icq.affiliations(user)['past'] if listed else []).data
|
||||
+ _pairs_body(icq.affiliations(user)['current'] if listed else []).data
|
||||
)),
|
||||
]
|
||||
for index, (subtype, body) in enumerate(parts):
|
||||
query.meta(subtype, ICQResult.Ok, body, more = index < len(parts) - 1)
|
||||
|
||||
def meta_search_by_uin(query: ICQContext, reader: LEReader) -> None:
|
||||
# finding someone by their exact number is how ICQ adds a contact, so it doesn't need a directory listing
|
||||
user = _find(query.context.backend, reader.u32())
|
||||
search_results(query, [user] if user is not None else [])
|
||||
|
||||
def meta_search_by_uin2(query: ICQContext, reader: LEReader) -> None:
|
||||
uin = next((tlv_int(value) for tag, value in parse_le_tlvs(reader.rest()) if tag == ICQTag.Uin), 0)
|
||||
user = _find(query.context.backend, uin) if uin else None
|
||||
search_results(query, [user] if user is not None else [])
|
||||
|
||||
def meta_search_by_email(query: ICQContext, reader: LEReader) -> None:
|
||||
email = reader.string()
|
||||
search_results(query, _users(query.context.backend, query.context.backend.user_service.search_uuids(email = email)))
|
||||
|
||||
def meta_search_by_email3(query: ICQContext, reader: LEReader) -> None:
|
||||
email = next((tlv_string(value) for tag, value in parse_le_tlvs(reader.rest()) if tag == ICQTag.Email), '')
|
||||
search_results(query, _users(query.context.backend, query.context.backend.user_service.search_uuids(email = email)) if email else [])
|
||||
|
||||
def meta_search_by_details(query: ICQContext, reader: LEReader) -> None:
|
||||
first, last, nick = reader.string(), reader.string(), reader.string()
|
||||
uuids = query.context.backend.user_service.search_uuids(first_name = first, last_name = last, nickname = nick)
|
||||
search_results(query, _users(query.context.backend, uuids))
|
||||
|
||||
def meta_search_white_pages(query: ICQContext, reader: LEReader) -> None:
|
||||
# the fixed-layout white pages search: first, last, nick and e-mail lead it, the rest narrows (and isn't kept here)
|
||||
first, last, nick, email = reader.string(), reader.string(), reader.string(), reader.string()
|
||||
uuids = query.context.backend.user_service.search_uuids(email = email, first_name = first, last_name = last, nickname = nick)
|
||||
search_results(query, _users(query.context.backend, uuids))
|
||||
|
||||
def meta_search_white_pages2(query: ICQContext, reader: LEReader) -> None:
|
||||
criteria = {}
|
||||
online_only = False
|
||||
uin = 0
|
||||
for tag, value in parse_le_tlvs(reader.rest()):
|
||||
if tag == ICQTag.Uin:
|
||||
uin = tlv_int(value)
|
||||
elif tag == ICQTag.FirstName:
|
||||
criteria['first_name'] = tlv_string(value)
|
||||
elif tag == ICQTag.LastName:
|
||||
criteria['last_name'] = tlv_string(value)
|
||||
elif tag == ICQTag.Nickname:
|
||||
criteria['nickname'] = tlv_string(value)
|
||||
elif tag == ICQTag.Email:
|
||||
criteria['email'] = tlv_string(value)
|
||||
elif tag == ICQTag.OnlineOnly:
|
||||
online_only = bool(tlv_int(value))
|
||||
backend = query.context.backend
|
||||
if uin:
|
||||
user = _find(backend, uin)
|
||||
users = [user] if user is not None else []
|
||||
else:
|
||||
users = _users(backend, backend.user_service.search_uuids(**{ k: v for k, v in criteria.items() if v }))
|
||||
if online_only:
|
||||
users = [user for user in users if _search_status(query, user) == DIR_STATUS_ONLINE]
|
||||
search_results(query, users)
|
||||
|
||||
def _save(query: ICQContext) -> None:
|
||||
icq.save(query.context.backend, query.context.user)
|
||||
|
||||
def meta_set_basic_info(query: ICQContext, reader: LEReader) -> None:
|
||||
fields = { field: reader.string() for field in ('nick', 'first', 'last', 'email', 'city', 'state', 'phone', 'fax', 'address', 'cell', 'zip') }
|
||||
fields['country'] = reader.u16()
|
||||
fields['gmt'] = reader.u8()
|
||||
# publish e-mail: 0 yes, 1 no
|
||||
fields['publish_email'] = reader.u8() == 0 if reader.remaining() else False
|
||||
_set_nickname(query, fields['nick'])
|
||||
icq.set_basic(query.context.user, fields)
|
||||
_save(query)
|
||||
query.meta(ICQMeta.SetBasicInfoAck, ICQResult.Ok)
|
||||
|
||||
def _set_nickname(query: ICQContext, nick: str) -> None:
|
||||
# the ICQ nickname is what other people see this account as, which elsewhere is its friendly name
|
||||
if nick and nick != query.context.user.status.name:
|
||||
query.context.bs.me_update({ 'name': nick })
|
||||
|
||||
def meta_set_work_info(query: ICQContext, reader: LEReader) -> None:
|
||||
fields: dict[str, Any] = { field: reader.string() for field in ('city', 'state', 'phone', 'fax', 'address', 'zip') }
|
||||
fields['country'] = reader.u16()
|
||||
for field in ('company', 'department', 'position'):
|
||||
fields[field] = reader.string()
|
||||
fields['occupation'] = reader.u16()
|
||||
fields['webpage'] = reader.string()
|
||||
icq.set_work(query.context.user, fields)
|
||||
_save(query)
|
||||
query.meta(ICQMeta.SetWorkInfoAck, ICQResult.Ok)
|
||||
|
||||
def meta_set_more_info(query: ICQContext, reader: LEReader) -> None:
|
||||
# u8 age (worked out from the birth date instead), u16 gender, homepage, u16 year, u8 month, u8 day, three languages
|
||||
reader.u8()
|
||||
fields = { 'gender': reader.u16() & 0xFF, 'homepage': reader.string(), 'birth_year': reader.u16(), 'birth_month': reader.u8() }
|
||||
fields['birth_day'] = reader.u8()
|
||||
for lang in ('lang1', 'lang2', 'lang3'):
|
||||
fields[lang] = reader.u8() if reader.remaining() else 0
|
||||
icq.set_more(query.context.user, fields)
|
||||
_save(query)
|
||||
query.meta(ICQMeta.SetMoreInfoAck, ICQResult.Ok)
|
||||
|
||||
def meta_set_notes(query: ICQContext, reader: LEReader) -> None:
|
||||
icq.set_notes(query.context.user, reader.string())
|
||||
_save(query)
|
||||
query.meta(ICQMeta.SetNotesAck, ICQResult.Ok)
|
||||
|
||||
def meta_set_emails(query: ICQContext, reader: LEReader) -> None:
|
||||
# extra e-mail addresses aren't kept, but the client needs its answer
|
||||
query.meta(ICQMeta.SetEmailsAck, ICQResult.Ok)
|
||||
|
||||
def _read_pairs(reader: LEReader) -> list[list[Any]]:
|
||||
count = reader.u8()
|
||||
return [[reader.u16(), reader.string()] for _ in range(count)]
|
||||
|
||||
def meta_set_interests(query: ICQContext, reader: LEReader) -> None:
|
||||
icq.set_interests(query.context.user, _read_pairs(reader))
|
||||
_save(query)
|
||||
query.meta(ICQMeta.SetInterestsAck, ICQResult.Ok)
|
||||
|
||||
def meta_set_affiliations(query: ICQContext, reader: LEReader) -> None:
|
||||
past = _read_pairs(reader)
|
||||
current = _read_pairs(reader)
|
||||
icq.set_affiliations(query.context.user, past, current)
|
||||
_save(query)
|
||||
query.meta(ICQMeta.SetAffiliationsAck, ICQResult.Ok)
|
||||
|
||||
def meta_set_permissions(query: ICQContext, reader: LEReader) -> None:
|
||||
# u8 authorization (0: required, 1: anyone may add), u8 web aware, u8 direct connection permissions, u8 unknown
|
||||
authorization = reader.u8()
|
||||
web_aware = reader.u8() if reader.remaining() else 0
|
||||
icq.set_permissions(query.context.user, auth_required = authorization == 0, web_aware = web_aware == 1)
|
||||
_save(query)
|
||||
query.meta(ICQMeta.SetPermissionsAck, ICQResult.Ok)
|
||||
|
||||
def meta_set_icq_phone(query: ICQContext, reader: LEReader) -> None:
|
||||
query.meta(ICQMeta.SetIcqPhoneAck, ICQResult.Ok)
|
||||
|
||||
def meta_set_full_info(query: ICQContext, reader: LEReader) -> None:
|
||||
# ICQ Lite's all-in-one update: only the fields it sends change
|
||||
basic: dict[str, Any] = {}
|
||||
more: dict[str, Any] = {}
|
||||
work: dict[str, Any] = {}
|
||||
user = query.context.user
|
||||
strings = {
|
||||
ICQTag.FirstName: (basic, 'first'), ICQTag.LastName: (basic, 'last'), ICQTag.Nickname: (basic, 'nick'),
|
||||
ICQTag.HomeCity: (basic, 'city'), ICQTag.HomeState: (basic, 'state'), ICQTag.HomeAddress: (basic, 'address'),
|
||||
ICQTag.HomePhone: (basic, 'phone'), ICQTag.HomeFax: (basic, 'fax'), ICQTag.HomeCell: (basic, 'cell'),
|
||||
ICQTag.HomepageUrl: (more, 'homepage'), ICQTag.WorkCompany: (work, 'company'), ICQTag.WorkDepartment: (work, 'department'),
|
||||
ICQTag.WorkPosition: (work, 'position'), ICQTag.WorkAddress: (work, 'address'), ICQTag.WorkCity: (work, 'city'),
|
||||
ICQTag.WorkState: (work, 'state'), ICQTag.WorkPhone: (work, 'phone'), ICQTag.WorkFax: (work, 'fax'),
|
||||
ICQTag.WorkWebpage: (work, 'webpage'),
|
||||
}
|
||||
for tag, value in parse_le_tlvs(reader.rest()):
|
||||
if tag in strings:
|
||||
section, field = strings[tag]
|
||||
section[field] = tlv_string(value)
|
||||
elif tag == ICQTag.Email and len(value) >= 2:
|
||||
basic['email'] = tlv_string(value)
|
||||
elif tag == ICQTag.HomeCountry:
|
||||
basic['country'] = tlv_int(value) & 0xFFFF
|
||||
elif tag == ICQTag.WorkCountry:
|
||||
work['country'] = tlv_int(value) & 0xFFFF
|
||||
elif tag == ICQTag.HomeZip:
|
||||
basic['zip'] = str(tlv_int(value))
|
||||
elif tag == ICQTag.WorkZip:
|
||||
work['zip'] = str(tlv_int(value))
|
||||
elif tag == ICQTag.WorkOccupation:
|
||||
work['occupation'] = tlv_int(value) & 0xFFFF
|
||||
elif tag == ICQTag.GmtOffset and value:
|
||||
basic['gmt'] = value[0]
|
||||
elif tag == ICQTag.Gender and value:
|
||||
more['gender'] = value[0]
|
||||
elif tag == ICQTag.Birthday and len(value) >= 6:
|
||||
# u16 year, u16 month, u16 day
|
||||
more['birth_year'], more['birth_month'], more['birth_day'] = struct.unpack('<HHH', value[:6])
|
||||
elif tag == ICQTag.Notes:
|
||||
icq.set_notes(user, tlv_string(value))
|
||||
elif tag == ICQTag.Authorization and value:
|
||||
icq.set_permissions(user, auth_required = value[0] == 0)
|
||||
elif tag == ICQTag.WebAware and value:
|
||||
icq.set_permissions(user, web_aware = value[0] == 1)
|
||||
if 'nick' in basic:
|
||||
_set_nickname(query, basic['nick'])
|
||||
icq.set_basic(user, basic)
|
||||
icq.set_more(user, more)
|
||||
icq.set_work(user, work)
|
||||
_save(query)
|
||||
query.meta(ICQMeta.SetFullInfoAck, ICQResult.Ok)
|
||||
|
||||
def meta_xml_request(query: ICQContext, reader: LEReader) -> None:
|
||||
# server-side XML data (Beacon"what's new" and such) isn't something there is any of
|
||||
query.meta(ICQMeta.XmlReply, ICQResult.Error)
|
||||
|
||||
def meta_directory_query(query: ICQContext, reader: LEReader) -> None:
|
||||
# ICQ 6's directory protocol, a SNAC of its own (family 0x05B9) inside the request; it gets the empty answer Open
|
||||
# OSCAR Server sends for what it doesn't handle: the request's subtype, result 0, nothing found
|
||||
payload = reader.rest()
|
||||
if len(payload) < 2 + 10:
|
||||
return
|
||||
body = payload[2:]
|
||||
subtype, flags = struct.unpack('>HH', body[2:6])
|
||||
versioned = bool(flags & 0x8000)
|
||||
nested = struct.pack('>HHHHH', 0x05B9, subtype, 0x8000 if versioned else 0x0000, 0, 0)
|
||||
if versioned:
|
||||
# the version block the request came with, mirrored: TLV 0x01 = 2
|
||||
version = TLV(0x0001, struct.pack('>H', 0x0002)).marshal()
|
||||
nested += struct.pack('>H', len(version)) + version
|
||||
# u8 result, string16 error message, 10 bytes nothing, [6 more], u32 total, [u16 pages], u16 block count
|
||||
nested += struct.pack('>BH', 0, 0) + bytes(10)
|
||||
if versioned:
|
||||
nested += bytes(6)
|
||||
nested += struct.pack('>L', 0)
|
||||
if versioned:
|
||||
nested += struct.pack('>H', 0)
|
||||
nested += struct.pack('>H', 0)
|
||||
query.reply(ICQReply.Meta, LE().u16(ICQMeta.DirectoryResponse).u8(ICQResult.Ok).u16(len(nested)).raw(nested).data)
|
||||
|
||||
|
||||
META_HANDLERS = {
|
||||
ICQMeta.ShortInfo: meta_short_info,
|
||||
ICQMeta.FullInfo: meta_full_info,
|
||||
ICQMeta.FullInfo2: meta_full_info,
|
||||
ICQMeta.SearchByUin: meta_search_by_uin,
|
||||
ICQMeta.SearchByUin2: meta_search_by_uin2,
|
||||
ICQMeta.SearchByEmail: meta_search_by_email,
|
||||
ICQMeta.SearchByEmail3: meta_search_by_email3,
|
||||
ICQMeta.SearchByDetails: meta_search_by_details,
|
||||
ICQMeta.SearchWhitePages: meta_search_white_pages,
|
||||
ICQMeta.SearchWhitePages2: meta_search_white_pages2,
|
||||
ICQMeta.SetBasicInfo: meta_set_basic_info,
|
||||
ICQMeta.SetWorkInfo: meta_set_work_info,
|
||||
ICQMeta.SetMoreInfo: meta_set_more_info,
|
||||
ICQMeta.SetNotes: meta_set_notes,
|
||||
ICQMeta.SetEmails: meta_set_emails,
|
||||
ICQMeta.SetInterests: meta_set_interests,
|
||||
ICQMeta.SetAffiliations: meta_set_affiliations,
|
||||
ICQMeta.SetPermissions: meta_set_permissions,
|
||||
ICQMeta.SetIcqPhone: meta_set_icq_phone,
|
||||
ICQMeta.SetFullInfo: meta_set_full_info,
|
||||
ICQMeta.XmlRequest: meta_xml_request,
|
||||
ICQMeta.DirectoryQuery: meta_directory_query,
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
from typing import Any, Callable, TYPE_CHECKING
|
||||
|
||||
from core.models import User
|
||||
from util import icq
|
||||
|
||||
from . import directory
|
||||
from .packets import LE, Meta, MetaReply, MetaResult, Reader, Server
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .ctrl import LegacyCtrl
|
||||
from .wire import Header
|
||||
|
||||
|
||||
# META_USER (0x064A), the V5 directory and profile requests: u16 subtype, then its data; every answer is a SRV_META_USER
|
||||
# (0x03DE) of u16 reply subtype, u8 result and the reply's data, under the request's seq2
|
||||
|
||||
def handle(ctrl: 'LegacyCtrl', header: 'Header', data: bytes) -> None:
|
||||
# the ACK echoes both sequence numbers
|
||||
ctrl.ack(header, with_seq2 = True)
|
||||
if len(data) < 2:
|
||||
return
|
||||
reader = Reader(data)
|
||||
subtype = reader.u16()
|
||||
handler = HANDLERS.get(subtype)
|
||||
if handler is None:
|
||||
ctrl.logger.info('[Client] Unhandled META_USER request', hex(subtype))
|
||||
reply(ctrl, header, subtype, MetaResult.Ok)
|
||||
return
|
||||
ctrl.logger.info('[Client] META_USER', hex(subtype))
|
||||
try:
|
||||
handler(ctrl, header, reader)
|
||||
except ValueError:
|
||||
ctrl.logger.info('[Client] Malformed META_USER request', hex(subtype))
|
||||
|
||||
def reply(ctrl: 'LegacyCtrl', header: 'Header', subtype: int, result: int, body: bytes = b'') -> None:
|
||||
ctrl.send(Server.MetaUser, LE().u16(subtype).u8(result).raw(body if result == MetaResult.Ok else b'').bytes(), seq2 = header.seq2)
|
||||
|
||||
def _target(ctrl: 'LegacyCtrl', reader: Reader) -> User | None:
|
||||
return directory.find(ctrl.backend, reader.u32())
|
||||
|
||||
def _meta_auth(info: dict[str, Any]) -> int:
|
||||
# the META replies (like their OSCAR descendants): 0 means authorization required, 1 that anyone may add
|
||||
return 0 if info['auth_required'] else 1
|
||||
|
||||
|
||||
# the info replies
|
||||
|
||||
def _basic_info3(info: dict[str, Any]) -> bytes:
|
||||
# nick, first, last, three e-mail addresses (primary, secondary, old), city, state, phone, fax, street, cell, ZIP,
|
||||
# u16 country, u16 GMT offset, u8 auth, u8 hide e-mail (1: hidden), three zero bytes
|
||||
body = LE().string(info['nick']).string(info['first']).string(info['last']).string(info['email']).string('').string('')
|
||||
for field in ('city', 'state', 'phone', 'fax', 'address', 'cell', 'zip'):
|
||||
body.string(info[field])
|
||||
body.u16(info['country']).u16(info['gmt']).u8(_meta_auth(info)).u8(0 if info['publish_email'] else 1).u8(0).u8(0).u8(0)
|
||||
return body.bytes()
|
||||
|
||||
def _basic_info_old(info: dict[str, Any]) -> bytes:
|
||||
# the older basic info (META_USER_FULLINFO's): u32 UIN, nick, first, last, e-mail, u8 auth
|
||||
return LE().u32(info['uin']).string(info['nick']).string(info['first']).string(info['last']).string(info['email']).u8(_meta_auth(info)).bytes()
|
||||
|
||||
def _more_info(info: dict[str, Any], *, full_year: bool) -> bytes:
|
||||
# u16 age, u8 gender, homepage, birth year (u16, or before ICQ 99b a u8 of the year less 1900), u8 month, u8 day, three
|
||||
# u8 languages
|
||||
body = LE().u16(info['age']).u8(info['gender']).string(info['homepage'])
|
||||
year = info['birth_year']
|
||||
if full_year:
|
||||
body.u16(year)
|
||||
else:
|
||||
body.u8(year - 1900 if year >= 1900 else year)
|
||||
body.u8(info['birth_month']).u8(info['birth_day']).u8(info['lang1']).u8(info['lang2']).u8(info['lang3'])
|
||||
return body.bytes()
|
||||
|
||||
def _homepage_category() -> bytes:
|
||||
# u8 enabled, u16 category, description, u8: nobody has one here
|
||||
return LE().u8(0).u16(0).string('').u8(0).bytes()
|
||||
|
||||
def _work_info(info: dict[str, Any], *, zip_string: bool) -> bytes:
|
||||
# city, state, phone, fax, street, ZIP (a string from ICQ 99b, before that a u32), u16 country, company, department,
|
||||
# position, u16 occupation, webpage
|
||||
work = info['work']
|
||||
body = LE()
|
||||
for field in ('city', 'state', 'phone', 'fax', 'address'):
|
||||
body.string(work[field])
|
||||
if zip_string:
|
||||
body.string(work['zip'])
|
||||
else:
|
||||
body.u32(info['work_zip_number'])
|
||||
body.u16(work['country']).string(work['company']).string(work['department']).string(work['position'])
|
||||
body.u16(work['occupation']).string(work['webpage'])
|
||||
return body.bytes()
|
||||
|
||||
def _pairs(pairs: list[list[Any]]) -> LE:
|
||||
body = LE().u8(len(pairs))
|
||||
for code, keyword in pairs:
|
||||
body.u16(int(code)).string(keyword)
|
||||
return body
|
||||
|
||||
def _padded(pairs: list[list[Any]], slots: int) -> list[list[Any]]:
|
||||
return (list(pairs) + [[0, '']] * slots)[:slots]
|
||||
|
||||
def _affiliations(info: dict[str, Any]) -> bytes:
|
||||
body = _pairs(_padded(info['past_affiliations'], icq.AFFILIATION_SLOTS)).raw(_pairs(_padded(info['affiliations'], icq.AFFILIATION_SLOTS)).bytes())
|
||||
return body.u16(0x0000).u16(0x0001).u8(0).bytes()
|
||||
|
||||
def _full_info(ctrl: 'LegacyCtrl', header: 'Header', user: User, *, newer: bool) -> None:
|
||||
# seven replies: basic, more, homepage category, work, about, interests, affiliations; ICQ 99b's requests (and the
|
||||
# login info) get the newer layouts
|
||||
info = directory.profile(user, ctrl.user)
|
||||
reply(ctrl, header, MetaReply.BasicInfo, MetaResult.Ok, _basic_info3(info) if newer else _basic_info_old(info))
|
||||
reply(ctrl, header, MetaReply.MoreInfo, MetaResult.Ok, _more_info(info, full_year = newer))
|
||||
reply(ctrl, header, MetaReply.HomepageCategory, MetaResult.Ok, _homepage_category())
|
||||
reply(ctrl, header, MetaReply.WorkInfo, MetaResult.Ok, _work_info(info, zip_string = newer))
|
||||
reply(ctrl, header, MetaReply.About, MetaResult.Ok, LE().string(info['notes']).bytes())
|
||||
reply(ctrl, header, MetaReply.Interests, MetaResult.Ok, _pairs(info['interests']).bytes())
|
||||
reply(ctrl, header, MetaReply.Affiliations, MetaResult.Ok, _affiliations(info))
|
||||
|
||||
def meta_login(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# answered with the subtype echoed, then u16 0 and u16 0x46 (no result byte)
|
||||
ctrl.send(Server.MetaUser, LE().u16(Meta.Login).u16(0x0000).u16(0x0046).bytes(), seq2 = header.seq2)
|
||||
|
||||
def meta_login_info(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# the client's own details after signing on (a UIN when it says whose)
|
||||
user = _target(ctrl, reader) if reader.remaining() >= 4 else ctrl.user
|
||||
if user is None:
|
||||
reply(ctrl, header, MetaReply.BasicInfo, MetaResult.Fail)
|
||||
return
|
||||
_full_info(ctrl, header, user, newer = True)
|
||||
|
||||
def meta_full_info(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
user = _target(ctrl, reader)
|
||||
if user is None:
|
||||
reply(ctrl, header, MetaReply.BasicInfo, MetaResult.Fail)
|
||||
return
|
||||
_full_info(ctrl, header, user, newer = False)
|
||||
|
||||
def meta_full_info2(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
user = _target(ctrl, reader)
|
||||
if user is None:
|
||||
reply(ctrl, header, MetaReply.BasicInfo, MetaResult.Fail)
|
||||
return
|
||||
_full_info(ctrl, header, user, newer = True)
|
||||
|
||||
def meta_short_info(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# nick, first, last, e-mail, u8 auth, u8 gender, u8 0
|
||||
user = _target(ctrl, reader)
|
||||
if user is None:
|
||||
reply(ctrl, header, MetaReply.ShortInfo, MetaResult.Fail)
|
||||
return
|
||||
info = directory.profile(user, ctrl.user)
|
||||
body = LE().string(info['nick']).string(info['first']).string(info['last']).string(info['email'])
|
||||
reply(ctrl, header, MetaReply.ShortInfo, MetaResult.Ok, body.u8(_meta_auth(info)).u8(info['gender']).u8(0).bytes())
|
||||
|
||||
|
||||
# searches
|
||||
|
||||
def _record(info: dict[str, Any]) -> LE:
|
||||
# a hit: u32 UIN, nick, first, last, e-mail, u8 auth, u8 web aware
|
||||
record = LE().u32(info['uin']).string(info['nick']).string(info['first']).string(info['last']).string(info['email'])
|
||||
return record.u8(_meta_auth(info)).u8(1 if info['web_aware'] else 0)
|
||||
|
||||
def _search_results(ctrl: 'LegacyCtrl', header: 'Header', users: list[User]) -> None:
|
||||
# every hit but the last is USER_FOUND, the last LAST_USER_FOUND with u32 users left after it (outside its u16 length);
|
||||
# no hits at all is a failed LAST_USER_FOUND
|
||||
if not users:
|
||||
reply(ctrl, header, MetaReply.LastUserFound, MetaResult.Fail)
|
||||
return
|
||||
for index, user in enumerate(users):
|
||||
last = index == len(users) - 1
|
||||
record = _record(directory.profile(user, ctrl.user)).u8(0).bytes()
|
||||
body = LE().u16(len(record)).raw(record)
|
||||
if last:
|
||||
body.u32(0)
|
||||
reply(ctrl, header, MetaReply.LastUserFound if last else MetaReply.UserFound, MetaResult.Ok, body.bytes())
|
||||
|
||||
def _white_results(ctrl: 'LegacyCtrl', header: 'Header', users: list[User], *, length_prefixed: bool) -> None:
|
||||
# white pages hits are WHITE_FOUND/WHITE_LAST_FOUND: the first search's records have no length and only the last has
|
||||
# users left; the second's (0x0533) carry a u16 length and users left on every record
|
||||
if not users:
|
||||
reply_body = LE().u16(MetaReply.WhiteLastFound).u8(MetaResult.Fail).u32(0).bytes()
|
||||
ctrl.send(Server.MetaUser, reply_body, seq2 = header.seq2)
|
||||
return
|
||||
for index, user in enumerate(users):
|
||||
last = index == len(users) - 1
|
||||
record = _record(directory.profile(user, ctrl.user))
|
||||
if length_prefixed:
|
||||
payload = record.u8(0).bytes()
|
||||
body = LE().u16(len(payload)).raw(payload).u32(0)
|
||||
else:
|
||||
body = record
|
||||
if last:
|
||||
body.u32(0)
|
||||
reply(ctrl, header, MetaReply.WhiteLastFound if last else MetaReply.WhiteFound, MetaResult.Ok, body.bytes())
|
||||
|
||||
def meta_search_name(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# nick, first, last
|
||||
nick, first, last = reader.string(), reader.string(), reader.string()
|
||||
_search_results(ctrl, header, directory.search(ctrl.backend, nick = nick, first = first, last = last))
|
||||
|
||||
def meta_search_uin(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# finding someone by their exact number is how ICQ adds a contact, so it doesn't need a directory listing
|
||||
user = _target(ctrl, reader)
|
||||
_search_results(ctrl, header, [user] if user is not None else [])
|
||||
|
||||
def meta_search_email(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
email = reader.string()
|
||||
_search_results(ctrl, header, directory.search(ctrl.backend, email = email))
|
||||
|
||||
def meta_search_white(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# first, last, nick and e-mail lead it; the rest (ages, location, work, interests) narrows and isn't kept here
|
||||
first, last, nick, email = reader.string(), reader.string(), reader.string(), reader.string()
|
||||
users = directory.search(ctrl.backend, email = email, first = first, last = last, nick = nick)
|
||||
_white_results(ctrl, header, users, length_prefixed = False)
|
||||
|
||||
def meta_search_white2(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
first, last, nick, email = reader.string(), reader.string(), reader.string(), reader.string()
|
||||
users = directory.search(ctrl.backend, email = email, first = first, last = last, nick = nick)
|
||||
_white_results(ctrl, header, users, length_prefixed = True)
|
||||
|
||||
|
||||
# profile changes
|
||||
|
||||
def _save(ctrl: 'LegacyCtrl') -> None:
|
||||
icq.save(ctrl.backend, ctrl.user)
|
||||
|
||||
def meta_set_basic(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# nick, first, last, three e-mail addresses (only the primary is kept), city, state, phone, fax, street, cell, ZIP,
|
||||
# u16 country, u8 GMT offset, u8 publish e-mail (0: yes)
|
||||
fields: dict[str, Any] = { field: reader.string() for field in ('nick', 'first', 'last', 'email') }
|
||||
reader.string()
|
||||
reader.string()
|
||||
for field in ('city', 'state', 'phone', 'fax', 'address', 'cell', 'zip'):
|
||||
fields[field] = reader.string()
|
||||
fields['country'] = reader.u16() if reader.remaining() >= 2 else 0
|
||||
fields['gmt'] = reader.u8() if reader.remaining() else 0
|
||||
fields['publish_email'] = (reader.u8() == 0) if reader.remaining() else False
|
||||
ctrl.set_nickname(fields['nick'])
|
||||
icq.set_basic(ctrl.user, fields)
|
||||
_save(ctrl)
|
||||
reply(ctrl, header, MetaReply.SetBasicAck, MetaResult.Ok)
|
||||
|
||||
def meta_set_work(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# city, state, phone, fax, street, ZIP, u16 country, company, department, position, u16 occupation, webpage
|
||||
fields: dict[str, Any] = { field: reader.string() for field in ('city', 'state', 'phone', 'fax', 'address', 'zip') }
|
||||
fields['country'] = reader.u16()
|
||||
for field in ('company', 'department', 'position'):
|
||||
fields[field] = reader.string()
|
||||
fields['occupation'] = reader.u16()
|
||||
fields['webpage'] = reader.string()
|
||||
icq.set_work(ctrl.user, fields)
|
||||
_save(ctrl)
|
||||
reply(ctrl, header, MetaReply.SetWorkAck, MetaResult.Ok)
|
||||
|
||||
def meta_set_more(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# u8 age (worked out from the birth date instead), u16 gender, homepage, u16 year, u8 month, u8 day, three languages
|
||||
reader.u8()
|
||||
fields: dict[str, Any] = { 'gender': reader.u16() & 0xFF, 'homepage': reader.string(), 'birth_year': reader.u16() }
|
||||
fields['birth_month'] = reader.u8()
|
||||
fields['birth_day'] = reader.u8()
|
||||
for lang in ('lang1', 'lang2', 'lang3'):
|
||||
fields[lang] = reader.u8() if reader.remaining() else 0
|
||||
icq.set_more(ctrl.user, fields)
|
||||
_save(ctrl)
|
||||
reply(ctrl, header, MetaReply.SetMoreAck, MetaResult.Ok)
|
||||
|
||||
def meta_set_about(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
icq.set_notes(ctrl.user, reader.string())
|
||||
_save(ctrl)
|
||||
reply(ctrl, header, MetaReply.SetAboutAck, MetaResult.Ok)
|
||||
|
||||
def _read_pairs(reader: Reader) -> list[list[Any]]:
|
||||
count = reader.u8()
|
||||
return [[reader.u16(), reader.string()] for _ in range(count)]
|
||||
|
||||
def meta_set_interests(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
icq.set_interests(ctrl.user, _read_pairs(reader))
|
||||
_save(ctrl)
|
||||
reply(ctrl, header, MetaReply.SetInterestsAck, MetaResult.Ok)
|
||||
|
||||
def meta_set_affiliations(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
past = _read_pairs(reader)
|
||||
current = _read_pairs(reader)
|
||||
icq.set_affiliations(ctrl.user, past, current)
|
||||
_save(ctrl)
|
||||
reply(ctrl, header, MetaReply.SetAffiliationsAck, MetaResult.Ok)
|
||||
|
||||
def meta_set_security(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# u8 authorization (0: required, 1: anyone may add), u8 web aware, u8 direct connection permissions, u8
|
||||
authorization = reader.u8()
|
||||
web_aware = reader.u8() if reader.remaining() else 0
|
||||
icq.set_permissions(ctrl.user, auth_required = authorization == 0, web_aware = web_aware == 1)
|
||||
_save(ctrl)
|
||||
reply(ctrl, header, MetaReply.SetSecurityAck, MetaResult.Ok)
|
||||
|
||||
def meta_set_password(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# every protocol's copy of the password comes from the one set on the website, so it isn't changed from here
|
||||
reply(ctrl, header, MetaReply.SetPasswordAck, MetaResult.Fail)
|
||||
|
||||
def meta_set_homepage_category(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# homepage categories aren't kept (nothing shows them but this client), but the client needs its answer
|
||||
reply(ctrl, header, MetaReply.SetHomepageCategoryAck, MetaResult.Ok)
|
||||
|
||||
def meta_unregister(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None:
|
||||
# the account belongs to the website, which is where it can be closed
|
||||
reply(ctrl, header, MetaReply.UnregisterAck, MetaResult.Fail)
|
||||
|
||||
|
||||
HANDLERS: dict[int, Callable[['LegacyCtrl', 'Header', Reader], None]] = {
|
||||
Meta.Login: meta_login,
|
||||
Meta.LoginInfo: meta_login_info,
|
||||
Meta.LoginInfo2: meta_login_info,
|
||||
Meta.FullInfo: meta_full_info,
|
||||
Meta.FullInfo2: meta_full_info2,
|
||||
Meta.ShortInfo: meta_short_info,
|
||||
Meta.SearchName: meta_search_name,
|
||||
Meta.SearchName2: meta_search_name,
|
||||
Meta.SearchUin: meta_search_uin,
|
||||
Meta.SearchUin2: meta_search_uin,
|
||||
Meta.SearchEmail: meta_search_email,
|
||||
Meta.SearchEmail2: meta_search_email,
|
||||
Meta.SearchWhite: meta_search_white,
|
||||
Meta.SearchWhite2: meta_search_white2,
|
||||
Meta.SetBasic: meta_set_basic,
|
||||
Meta.SetBasic2: meta_set_basic,
|
||||
Meta.SetWork: meta_set_work,
|
||||
Meta.SetWork2: meta_set_work,
|
||||
Meta.SetMore: meta_set_more,
|
||||
Meta.SetMore2: meta_set_more,
|
||||
Meta.SetAbout: meta_set_about,
|
||||
Meta.SetInterests: meta_set_interests,
|
||||
Meta.SetAffiliations: meta_set_affiliations,
|
||||
Meta.SetSecurity: meta_set_security,
|
||||
Meta.SetPassword: meta_set_password,
|
||||
Meta.SetHomepageCategory: meta_set_homepage_category,
|
||||
Meta.Unregister: meta_unregister,
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import struct
|
||||
|
||||
from enum import IntEnum
|
||||
|
||||
from util import icq
|
||||
|
||||
|
||||
class Version(IntEnum):
|
||||
V1 = 0x0001
|
||||
V2 = 0x0002
|
||||
V3 = 0x0003
|
||||
V4 = 0x0004
|
||||
V5 = 0x0005
|
||||
|
||||
class Command(IntEnum):
|
||||
# what clients send (CMD_*)
|
||||
Ack = 0x000A
|
||||
ThruServer = 0x010E
|
||||
Reconnect = 0x015E
|
||||
Login = 0x03E8
|
||||
GetDeps = 0x03F2
|
||||
RegNewUser = 0x03FC
|
||||
ContactList = 0x0406
|
||||
SearchUin = 0x041A
|
||||
SearchUser = 0x0424
|
||||
KeepAlive = 0x042E
|
||||
Logoff = 0x0438
|
||||
SysMsgDoneAck = 0x0442
|
||||
SysMsgReq = 0x044C
|
||||
Authorize = 0x0456
|
||||
InfoReq = 0x0460
|
||||
ExtInfoReq = 0x046A
|
||||
SetPassword = 0x049C
|
||||
UpdateBasic = 0x04A6
|
||||
UpdateDetail = 0x04B0
|
||||
GetExternals = 0x04C4
|
||||
SetStatus = 0x04D8
|
||||
FirstLogin = 0x04EC
|
||||
SetBasicInfo = 0x050A
|
||||
SetAuth = 0x0514
|
||||
KeepAlive2 = 0x051E
|
||||
UserAdd = 0x053C
|
||||
SetWorkInfo = 0x0578
|
||||
SetHomeInfo = 0x0582
|
||||
SetHomeWeb = 0x058C
|
||||
SetNotes = 0x0596
|
||||
GetNotes = 0x05AA
|
||||
SetWorkWeb = 0x05BE
|
||||
SearchStart = 0x05C8
|
||||
RegRequestInfo = 0x05DC
|
||||
RegNewUserInfo = 0x05E6
|
||||
GetDeps1 = 0x05F0
|
||||
UserGetInfo = 0x05FA
|
||||
MetaUser = 0x064A
|
||||
InvisibleList = 0x06A4
|
||||
VisibleList = 0x06AE
|
||||
ChangeVILists = 0x06B8
|
||||
|
||||
class Server(IntEnum):
|
||||
# what the server sends (SRV_*)
|
||||
Ack = 0x000A
|
||||
SetOffline = 0x0028
|
||||
DepsList = 0x0032
|
||||
Hello = 0x005A
|
||||
WrongPassword = 0x0064
|
||||
UserOnline = 0x006E
|
||||
UserOffline = 0x0078
|
||||
SearchFound = 0x008C
|
||||
SearchDone = 0x00A0
|
||||
UpdatedBasic = 0x00B4
|
||||
UpdateBasicFail = 0x00BE
|
||||
UpdatedDetail = 0x00C8
|
||||
UpdateDetailFail = 0x00D2
|
||||
SysMsgOffline = 0x00DC
|
||||
SysMsgDone = 0x00E6
|
||||
NotConnected = 0x00F0
|
||||
Busy = 0x00FA
|
||||
SysMsgOnline = 0x0104
|
||||
InfoReply = 0x0118
|
||||
ExtInfoReply = 0x0122
|
||||
InvalidUin = 0x012C
|
||||
UserStatus = 0x01A4
|
||||
UpdatedBasicV4 = 0x01E0
|
||||
UpdateBasicFailV4 = 0x01EA
|
||||
UserListDone = 0x021C
|
||||
MetaUser = 0x03DE
|
||||
|
||||
class Meta(IntEnum):
|
||||
# META_USER (0x064A) requests: the u16 that leads the data
|
||||
SetBasic = 0x03E8
|
||||
SetBasic2 = 0x03E9
|
||||
SetWork = 0x03F2
|
||||
SetWork2 = 0x03F3
|
||||
SetMore = 0x03FC
|
||||
SetMore2 = 0x03FD
|
||||
SetAbout = 0x0406
|
||||
SetInterests = 0x0410
|
||||
SetAffiliations = 0x041A
|
||||
SetSecurity = 0x0424
|
||||
SetPassword = 0x042E
|
||||
SetHomepageCategory = 0x0442
|
||||
FullInfo = 0x04B0
|
||||
FullInfo2 = 0x04B1
|
||||
ShortInfo = 0x04BA
|
||||
Unregister = 0x04C4
|
||||
LoginInfo = 0x04CE
|
||||
LoginInfo2 = 0x04CF
|
||||
SearchName = 0x0514
|
||||
SearchName2 = 0x0515
|
||||
SearchUin = 0x051E
|
||||
SearchUin2 = 0x051F
|
||||
SearchEmail = 0x0528
|
||||
SearchEmail2 = 0x0529
|
||||
SearchWhite = 0x0532
|
||||
SearchWhite2 = 0x0533
|
||||
UsageStats = 0x06B8
|
||||
Login = 0x07D0
|
||||
|
||||
class MetaReply(IntEnum):
|
||||
# SRV_META_USER (0x03DE) replies: the u16 that leads the data, then a u8 result
|
||||
SetBasicAck = 0x0064
|
||||
SetWorkAck = 0x006E
|
||||
SetMoreAck = 0x0078
|
||||
SetAboutAck = 0x0082
|
||||
SetInterestsAck = 0x008C
|
||||
SetAffiliationsAck = 0x0096
|
||||
SetSecurityAck = 0x00A0
|
||||
SetPasswordAck = 0x00AA
|
||||
UnregisterAck = 0x00B4
|
||||
SetHomepageCategoryAck = 0x00BE
|
||||
BasicInfo = 0x00C8
|
||||
WorkInfo = 0x00D2
|
||||
MoreInfo = 0x00DC
|
||||
About = 0x00E6
|
||||
Interests = 0x00F0
|
||||
Affiliations = 0x00FA
|
||||
ShortInfo = 0x0104
|
||||
HomepageCategory = 0x010E
|
||||
UserFound = 0x0190
|
||||
LastUserFound = 0x019A
|
||||
WhiteFound = 0x01A4
|
||||
WhiteLastFound = 0x01AE
|
||||
|
||||
class MetaResult(IntEnum):
|
||||
Ok = 0x0A
|
||||
Fail = 0x32
|
||||
|
||||
class MessageType(IntEnum):
|
||||
# the low byte of a message's type
|
||||
Text = 0x01
|
||||
Chat = 0x02
|
||||
File = 0x03
|
||||
Url = 0x04
|
||||
AuthRequest = 0x06
|
||||
AuthDeny = 0x07
|
||||
AuthGrant = 0x08
|
||||
Server = 0x09
|
||||
Added = 0x0C
|
||||
WebPager = 0x0D
|
||||
EmailPager = 0x0E
|
||||
Contacts = 0x13
|
||||
Plugin = 0x1A
|
||||
AutoAway = 0xE8
|
||||
AutoOccupied = 0xE9
|
||||
AutoNotAvailable = 0xEA
|
||||
AutoDnd = 0xEB
|
||||
AutoFreeForChat = 0xEC
|
||||
|
||||
# what the client's fixed-size buffers take
|
||||
MAX_NICK = 20
|
||||
MAX_NAME = 64
|
||||
MAX_PHONE = 30
|
||||
MAX_HOMEPAGE = 127
|
||||
MAX_ABOUT = 450
|
||||
# the longest password a client sends; the rest of the packet isn't trusted past it
|
||||
MAX_PASSWORD = 20
|
||||
|
||||
|
||||
class LE:
|
||||
# a little-endian writer, the only byte order the pre-OSCAR protocol has
|
||||
__slots__ = ('data',)
|
||||
|
||||
data: bytearray
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.data = bytearray()
|
||||
|
||||
def u8(self, value: int) -> 'LE':
|
||||
self.data += struct.pack('<B', value & 0xFF)
|
||||
return self
|
||||
|
||||
def u16(self, value: int) -> 'LE':
|
||||
self.data += struct.pack('<H', value & 0xFFFF)
|
||||
return self
|
||||
|
||||
def u32(self, value: int) -> 'LE':
|
||||
self.data += struct.pack('<L', value & 0xFFFFFFFF)
|
||||
return self
|
||||
|
||||
def raw(self, value: bytes) -> 'LE':
|
||||
self.data += value
|
||||
return self
|
||||
|
||||
def string(self, value: str, limit: int = 0) -> 'LE':
|
||||
# u16 length counting the NUL, the text, the NUL; an empty string is still a length of 1 and its NUL
|
||||
encoded = icq.latin1(value)
|
||||
if limit:
|
||||
encoded = encoded[:limit]
|
||||
return self.u16(len(encoded) + 1).raw(encoded).u8(0)
|
||||
|
||||
def bytes(self) -> bytes:
|
||||
return bytes(self.data)
|
||||
|
||||
class Reader:
|
||||
__slots__ = ('data', 'pos')
|
||||
|
||||
data: bytes
|
||||
pos: int
|
||||
|
||||
def __init__(self, data: bytes) -> None:
|
||||
self.data = data
|
||||
self.pos = 0
|
||||
|
||||
def remaining(self) -> int:
|
||||
return len(self.data) - self.pos
|
||||
|
||||
def take(self, length: int) -> bytes:
|
||||
if length < 0 or self.pos + length > len(self.data):
|
||||
raise ValueError('truncated ICQ packet')
|
||||
chunk = self.data[self.pos:self.pos + length]
|
||||
self.pos += length
|
||||
return chunk
|
||||
|
||||
def skip(self, length: int) -> None:
|
||||
self.take(length)
|
||||
|
||||
def u8(self) -> int:
|
||||
return self.take(1)[0]
|
||||
|
||||
def u16(self) -> int:
|
||||
return struct.unpack('<H', self.take(2))[0]
|
||||
|
||||
def u32(self) -> int:
|
||||
return struct.unpack('<L', self.take(4))[0]
|
||||
|
||||
def raw_string(self, limit: int = 0) -> bytes:
|
||||
# u16 length, then that many bytes ending in a NUL; a client's own length is trusted only up to `limit`
|
||||
length = self.u16()
|
||||
if limit and length > limit + 1:
|
||||
raw = self.take(length)[:limit]
|
||||
else:
|
||||
raw = self.take(length)
|
||||
if b'\x00' in raw:
|
||||
raw = raw[:raw.index(b'\x00')]
|
||||
return raw
|
||||
|
||||
def string(self) -> str:
|
||||
return icq.from_latin1(self.raw_string())
|
||||
|
||||
def rest(self) -> bytes:
|
||||
chunk = self.data[self.pos:]
|
||||
self.pos = len(self.data)
|
||||
return chunk
|
||||
|
||||
def uin_list(data: bytes) -> list[int]:
|
||||
# u8 count, then that many u32 UINs (contact, visible and invisible lists); a short packet ends the list early
|
||||
reader = Reader(data)
|
||||
uins = []
|
||||
try:
|
||||
count = reader.u8()
|
||||
for _ in range(count):
|
||||
uins.append(reader.u32())
|
||||
except ValueError:
|
||||
pass
|
||||
return uins
|
||||
@@ -0,0 +1,91 @@
|
||||
import struct
|
||||
|
||||
from .crypt import add_v5_server_checkcode, decrypt_v4, decrypt_v5, v3_header_checkcode
|
||||
from .packets import Command, Version
|
||||
|
||||
|
||||
class Header:
|
||||
# what every version's client packet header comes down to (the fields a version doesn't have stay 0)
|
||||
__slots__ = ('version', 'command', 'seq1', 'seq2', 'uin', 'session_id')
|
||||
|
||||
version: int
|
||||
command: int
|
||||
seq1: int
|
||||
seq2: int
|
||||
uin: int
|
||||
session_id: int
|
||||
|
||||
def __init__(self, version: int, command: int, seq1: int, seq2: int, uin: int, session_id: int = 0) -> None:
|
||||
self.version = version
|
||||
self.command = command
|
||||
self.seq1 = seq1
|
||||
self.seq2 = seq2
|
||||
self.uin = uin
|
||||
self.session_id = session_id
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return '<V{} cmd 0x{:04X} seq {}/{} uin {}>'.format(self.version, self.command, self.seq1, self.seq2, self.uin)
|
||||
|
||||
def version_of(packet: bytes) -> int | None:
|
||||
if len(packet) < 2:
|
||||
return None
|
||||
return struct.unpack_from('<H', packet)[0]
|
||||
|
||||
def parse(packet: bytes) -> tuple[Header, bytes] | None:
|
||||
# client packet -> (header, data); None for anything too short to be one
|
||||
version = version_of(packet)
|
||||
if version == Version.V5:
|
||||
# u16 version, u32 zero, u32 UIN, then (encrypted) u32 session ID, u16 command, u16 seq1, u16 seq2, u32 checkcode
|
||||
if len(packet) < 24:
|
||||
return None
|
||||
plain = decrypt_v5(packet)
|
||||
uin, session_id, command, seq1, seq2 = struct.unpack_from('<LLHHH', plain, 6)
|
||||
return Header(version, command, seq1, seq2, uin, session_id), plain[24:]
|
||||
if version == Version.V4:
|
||||
# u16 version, u16 random, then (a quarter of it encrypted) u16 zero, u16 command, u16 seq1, u16 seq2, u32 UIN,
|
||||
# u32 checkcode
|
||||
if len(packet) < 20:
|
||||
return None
|
||||
plain = decrypt_v4(packet)
|
||||
command, seq1, seq2, uin = struct.unpack_from('<HHHL', plain, 6)
|
||||
return Header(version, command, seq1, seq2, uin), plain[20:]
|
||||
if version == Version.V3:
|
||||
# u16 version, u16 command, u16 seq1, u16 seq2, u32 UIN, u32 checkcode
|
||||
if len(packet) < 16:
|
||||
return None
|
||||
command, seq1, seq2, uin = struct.unpack_from('<HHHL', packet, 2)
|
||||
return Header(version, command, seq1, seq2, uin), packet[16:]
|
||||
if version in (Version.V1, Version.V2):
|
||||
# u16 version, u16 command, u16 seq, u32 UIN; the commands sent before there's a UIN to put in it leave it out
|
||||
if len(packet) < 6:
|
||||
return None
|
||||
command, seq = struct.unpack_from('<HH', packet, 2)
|
||||
if command in (Command.FirstLogin, Command.RegNewUser):
|
||||
return Header(version, command, seq, 0, 0), packet[6:]
|
||||
if command == Command.GetDeps and version == Version.V2:
|
||||
# a V2 client sends its pre-login check with a V3 layout: u16 seq1, u16 seq2, u32 UIN
|
||||
if len(packet) < 12:
|
||||
return None
|
||||
seq1, seq2, uin = struct.unpack_from('<HHL', packet, 4)
|
||||
return Header(version, command, seq1, seq2, uin), packet[12:]
|
||||
if len(packet) < 10:
|
||||
return Header(version, command, seq, 0, 0), packet[6:]
|
||||
uin = struct.unpack_from('<L', packet, 6)[0]
|
||||
return Header(version, command, seq, 0, uin), packet[10:]
|
||||
return None
|
||||
|
||||
def build(version: int, command: int, data: bytes = b'', *, seq1: int = 0, seq2: int = 0, uin: int = 0, session_id: int = 0) -> bytes:
|
||||
# server packet for a client of `version`
|
||||
if version == Version.V5:
|
||||
# u16 version, u8 zero, u32 session ID, u16 command, u16 seq1, u16 seq2, u32 UIN, u32 checkcode; not encrypted
|
||||
packet = bytearray(struct.pack('<HBLHHHL', Version.V5, 0, session_id, command, seq1 & 0xFFFF, seq2 & 0xFFFF, uin) + bytes(4) + data)
|
||||
add_v5_server_checkcode(packet)
|
||||
return bytes(packet)
|
||||
if version in (Version.V3, Version.V4):
|
||||
# V3 and V4 clients both get the V3 header (u16 version 3, u16 command, u16 seq1, u16 seq2, u32 UIN, u32), and a
|
||||
# V4 client a checkcode in its last field
|
||||
header = struct.pack('<HHHHL', Version.V3, command, seq1 & 0xFFFF, seq2 & 0xFFFF, uin)
|
||||
check = v3_header_checkcode(header) if version == Version.V4 else 0
|
||||
return header + struct.pack('<L', check) + data
|
||||
# V1 and V2: u16 version, u16 command, u16 seq
|
||||
return struct.pack('<HHH', version, command, seq1 & 0xFFFF) + data
|
||||
Reference in new issue
Block a user