0.6 final

This commit is contained in:
Athena Funderburg committed 2026-11-04 14:03:18 +00:00
1 parent 7c0581eb97
commit b89e1932bb
160 files changed
+20534 -4664

No files matched your search

+178 -67
View File
@@ -1,19 +1,25 @@
import asyncio
import random
import struct
import time
from core import error
from core.backend import Backend, BackendSession, Chat, ChatSession
from core.client import Client
from core.models import LoginOption, ContactList
from core.models import LoginOption, ContactList, User, _is_blocking
from itertools import cycle
from typing import Optional, Callable, Tuple
from util.misc import Logger
from typing import Any, Dict, Optional, Callable, Tuple, List
from util.icq import from_latin1
from util.misc import Logger, is_valid_oscar_screenname
from .proto.backend import BackendEventHandler, FOODGROUP_VERSIONS, login, LoginError, bos_cookies
from .proto import names
from .proto.backend import (
BackendEventHandler, FOODGROUP_VERSIONS, SERVICE_FOODGROUPS, SERVICE_BOS, login, LoginError, bos_cookies, take_cookie,
)
from .proto.buffer import Buffer
from .proto.chat import ChatEventHandler
from .proto.snac import OSCARClient, OSCARContext, SNACMessage, foodgroups
from .proto.tlv import unmarshal_tlvs, find_tlv
from .proto.tlv import TLV, marshal_tlvs, unmarshal_tlvs, find_tlv
ROASTING_CHARS = b'\xF3\x26\x81\xC4\x39\x86\xDB\x92\x71\xA3\xB9\xE6\x53\x7A\x95\x7C'
@@ -24,6 +30,35 @@ def roast(password: bytes) -> bytes:
return bytes(byte ^ next(chars) for byte in password)
def client_version(tlvs: List[TLV]) -> str:
# the login request's client major/minor/build TLVs (0x17, 0x18, 0x1A), as "major.minor.build"
parts = []
for tag in (0x0017, 0x0018, 0x001A):
tlv = find_tlv(tlvs, tag)
parts.append(struct.unpack('>H', tlv.data[:2])[0] if tlv is not None and len(tlv.data) >= 2 else 0)
return '{}.{}.{}'.format(*parts)
def multi_conn_flag(tlvs: List[TLV]) -> Optional[int]:
# TLV 0x4A: a client that sends it knows about multiple sessions and takes a signoff frame with a reason in it
tlv = find_tlv(tlvs, 0x004A)
return tlv.data[0] if tlv is not None and tlv.data else None
def authenticate(backend: Backend, screen_name: str, check: Callable[[str], bool]) -> Tuple[Optional[str], bool, Optional[int]]:
# a login name may be a screen name or a UIN; every account it could mean is tried, so a numeric screen name and
# somebody else's UIN can both still sign on. returns the account, whether it signed on by UIN, and an error code
candidates = backend.util_get_uuids_for_login(screen_name) if names.valid_name(screen_name) else []
icq_name = names.is_uin(screen_name.replace(' ', ''))
if not candidates:
return None, icq_name, (LoginError.ICQUserError if icq_name else LoginError.UnregisteredScreenname)
for uuid in candidates:
if not check(uuid):
continue
user = backend._load_user_record(uuid)
icq = icq_name and user is not None and names.uin_of(user) == int(screen_name.replace(' ', ''))
return uuid, icq, None
return candidates[0], icq_name, LoginError.IncorrectPassword
# TODO(subpurple): as the foodgroups are no longer handled just in this file, might want to combine this and entry
class OSCARCtrl:
logger: Logger
@@ -39,7 +74,14 @@ class OSCARCtrl:
oscarClient: OSCARClient
context: OSCARContext
sequence: int = random.randint(0x0000, 0xFFFF)
sequence: int
# a service connection (BART, chat, ...) borrows the BOS connection's session instead of having one of its own
is_service: bool
service: int
room: Optional[Any]
multi_conn: Optional[int]
versions: Dict[int, int]
def __init__(self, logger: Logger, via: str, backend: Backend) -> None:
self.logger = logger
@@ -55,7 +97,19 @@ class OSCARCtrl:
self.context = OSCARContext(self.backend, self.client)
self.oscarClient = OSCARClient(self)
# FLAP sequence numbers start at a random value, per connection
self.sequence = random.randint(0x0000, 0xFFFF)
self.is_service = False
self.service = SERVICE_BOS
self.room = None
self.multi_conn = None
# what the client said it speaks (OSERVICE__CLIENT_VERSIONS), per connection
self.versions = {}
def send_specific_frame(self, frame: int, data: bytes) -> None:
if self.transport is None or self.transport.is_closing():
return
if self.sequence == 0xFFFF:
self.sequence = 0x0000
else:
@@ -71,6 +125,27 @@ class OSCARCtrl:
def send_snac(self, msg: SNACMessage) -> None:
self.send_specific_frame(0x02, msg.marshal())
def send_snac_error(self, foodgroup: int, request_id: int, code: int, subcode: Optional[int] = None) -> None:
# SNAC(xx,01): u16 error code, then TLV 0x08 with a foodgroup specific subcode when there is one
msg = SNACMessage(foodgroup, 0x0001, 0x0000, request_id)
msg.write_u16(code)
if subcode is not None:
msg.write_tlv(TLV(0x0008, struct.pack('>H', subcode)))
self.send_snac(msg)
def signoff(self, reason: Optional[int] = None) -> None:
# clients that never sent TLV 0x4A only know a bare signoff header (no length field); newer ones take a reason
if self.transport is None or self.transport.is_closing():
return
if self.multi_conn is None or reason is None:
self.sequence = (self.sequence + 1) & 0xFFFF
self.transport.write(struct.pack('>BBH', 0x2A, 0x04, self.sequence))
return
self.send_specific_frame(0x04, marshal_tlvs([
TLV(0x0009, struct.pack('>H', reason)),
TLV(0x000B, 'https://crosstalk.im/'),
]))
def on_connect(self) -> None:
self.send_specific_frame(0x01, struct.pack('>L', 1))
@@ -82,41 +157,37 @@ class OSCARCtrl:
found = False
is_service_connection = False
for i, d in enumerate(bos_cookies):
for cookie in d.items():
if cookie[0] == cookie_tlv.data:
self.logger.info('found BOS cookie')
entry = take_cookie(cookie_tlv.data)
if entry is not None and (entry.bs is None or not entry.bs.closed):
self.logger.info('found BOS cookie')
self.multi_conn = entry.multi_conn
if hasattr(cookie[1], 'user') and getattr(cookie[1].user, 'uuid', None) is not None:
# cookie maps to an existing BackendSession (placed there by OSERVICE__SERVICE_REQUEST)
# reuse it directly so the main session is not booted and its substatus is preserved
self.context.bs = cookie[1]
self.context.user = cookie[1].user
self.bs = cookie[1]
is_service_connection = True
else:
if isinstance(cookie[1], dict):
uuid = cookie[1].get('uuid')
version = cookie[1].get('version', '?')
self.client = Client('aim', version, self.client.via)
self.context.client = self.client
elif getattr(cookie[1], 'uuid', None) is not None:
uuid = cookie[1].uuid
else:
uuid = cookie[1]
if entry.bs is not None:
# cookie maps to an existing BackendSession (placed there by OSERVICE__SERVICE_REQUEST)
# reuse it directly so the main session is not booted and its substatus is preserved
self.context.bs = entry.bs
self.context.user = entry.bs.user
self.client = entry.bs.client
self.context.client = self.client
self.bs = entry.bs
self.is_service = True
self.service = entry.service
self.room = entry.room
is_service_connection = True
entry.bs.front_data.setdefault('oscar0_services', set()).add(self)
found = True
else:
self.client = Client(entry.program, entry.version, self.client.via)
self.context.client = self.client
self.context.bs = self.backend.login(uuid,
self.client,
BackendEventHandler(self),
option=LoginOption.BootOthers)
self.context.user = self.context.bs.user
self.bs = self.context.bs
bos_cookies.pop(i)
self.context.bs = self.backend.login(entry.uuid,
self.client,
BackendEventHandler(self),
option=LoginOption.BootOthers)
if self.context.bs is not None:
self.context.user = self.context.bs.user
self.bs = self.context.bs
found = True
break
if found:
break
if found:
# NINA also sends OSERVICE__WELL_KNOWN_URLS right after (should we?)
@@ -124,7 +195,7 @@ class OSCARCtrl:
msg = SNACMessage(0x0001, 0x0003)
for foodgroup in FOODGROUP_VERSIONS.keys():
for foodgroup in SERVICE_FOODGROUPS.get(self.service, SERVICE_FOODGROUPS[SERVICE_BOS]):
msg.write_u16(foodgroup)
self.send_snac(msg)
@@ -134,39 +205,43 @@ class OSCARCtrl:
# so other service connections don't wipe the chat state built up so far
self.bs.front_data['oscar0'] = True
self.bs.front_data['oscar0_chats'] = {}
self.bs.front_data['oscar0_signon'] = int(time.time())
self.bs.front_data['oscar0_sn'] = entry.screen_name or self.bs.user.username
self.bs.front_data['oscar0_icq'] = entry.icq
self.bs.front_data['oscar0_client_id'] = entry.client_id
else:
self.logger.info('invalid BOS cookie given')
self.close()
else:
elif find_tlv(tlvs, 0x0001) is not None:
self.logger.info('Using FLAP-level authentication')
screen_name_tlv = find_tlv(tlvs, 0x0001)
roasted_pw_tlv = find_tlv(tlvs, 0x0002)
screen_name = screen_name_tlv.data.decode()
roasted_pw = roasted_pw_tlv.data
screen_name = screen_name_tlv.data.decode('latin-1')
roasted_pw = roasted_pw_tlv.data if roasted_pw_tlv is not None else b''
self.logger.info('Screen Name (client-given):', screen_name)
self.logger.info('Password (roasted):', roasted_pw.hex())
context = self.context
error_code = None
if (uuid := context.backend.util_get_uuid_from_username(screen_name)) is None:
error_code = LoginError.UnregisteredScreenname
version = client_version(tlvs)
password = from_latin1(roast(roasted_pw))
uuid, icq, error_code = authenticate(
context.backend, screen_name, lambda uuid: context.backend.user_service.login_with_uuid(uuid, password) is not None,
)
if error_code in (LoginError.UnregisteredScreenname, LoginError.ICQUserError):
self.logger.info('Unregistered screenname')
else:
unroasted_pw = roast(roasted_pw)
elif error_code == LoginError.IncorrectPassword:
self.logger.info('Incorrect password')
if context.backend.user_service.login_with_username(screen_name, unroasted_pw.decode()) is None:
error_code = LoginError.IncorrectPassword
self.logger.info('Incorrect password')
self.bs.front_data['oscar0'] = True
self.bs.front_data['oscar0_chats'] = {}
self.send_specific_frame(0x04, login(self.logger, self.context, tlvs, uuid, error_code))
self.client = Client('icq' if icq else 'aim', version, self.client.via)
context.client = self.client
self.send_specific_frame(0x04, login(
self.logger, self.context, tlvs, uuid, error_code, icq = icq, multi_conn = multi_conn_flag(tlvs),
))
def on_data_frame(self, message: SNACMessage) -> None:
found = False
@@ -178,24 +253,31 @@ class OSCARCtrl:
for value, cls in foodgroups.items():
if value == message.foodgroup:
if not hasattr(cls, 'logger'):
cls.logger = self.logger
# the foodgroup handlers are shared, so they log through whichever connection the SNAC came in on
cls.logger = self.logger
if message.subgroup in cls.subgroups:
found = True
func = cls.subgroups[message.subgroup]
func(cls, self.oscarClient, self.context, message)
try:
func(cls, self.oscarClient, self.context, message)
except Exception as ex:
self.logger.error(ex)
if not found:
self.logger.info(f'[Client] Unknown SNAC({hex(message.foodgroup)},{hex(message.subgroup)})')
self.logger.info('[Client]', message.data.hex())
# an unanswered request leaves the client waiting on it, so it gets told the SNAC isn't one we know
if message.subgroup != 0x0001:
self.send_snac_error(message.foodgroup, message.request_id, 0x0001)
def on_error_frame(self, data: bytes) -> None:
self.logger.info('[Client] Recieved error frame with:', data.hex())
def on_signoff_frame(self, data: bytes) -> None:
self.logger.info('[Client] Recieved signoff frame')
self.close()
def close(self) -> None:
if self.closed:
@@ -205,8 +287,25 @@ class OSCARCtrl:
if self.close_callback:
self.close_callback()
if self.room is not None:
from .foodgroups.chat import leave_room
leave_room(self)
if self.bs:
self.bs.close()
if self.is_service:
# a service connection going away leaves the session it borrowed alone
self.bs.front_data.get('oscar0_services', set()).discard(self)
else:
for service_ctrl in list(self.bs.front_data.get('oscar0_services', ())):
service_ctrl.close()
self.bs.close()
def _temp_permitted(self, target: User, sender: User) -> bool:
# PD__ADD_TEMP_PERMIT_LIST_ENTRIES lets a name bypass the target's permit/deny settings for as long as their session lasts
for bs_target in self.backend.util_get_sessions_by_user(target):
if sender.uuid in bs_target.front_data.get('oscar0_temp_permits', ()):
return True
return False
def _get_private_chat_with(self, other_user_uuid: str) -> Tuple[ChatSession, 'ChatEventHandler']:
bs = self.bs
@@ -214,27 +313,39 @@ class OSCARCtrl:
user = bs.user
detail = user.detail
assert detail is not None
other_user = self.backend._load_user_record(other_user_uuid)
if other_user is None:
if other_user is None or not names.representable(other_user):
raise error.ContactNotOnContactList()
other_user_ctc = detail.contacts.get(other_user.uuid)
if other_user_ctc is not None and other_user_ctc.lists & ContactList.BL:
raise error.ContactNotOnContactList()
if other_user_uuid not in bs.front_data['oscar0_chats']:
chats = bs.front_data.setdefault('oscar0_chats', {})
# a chat whose other side has gone (they signed off, or picked up a newer one) can't carry anything any more
existing = chats.get(other_user_uuid)
if existing is not None and existing[0].closed:
del chats[other_user_uuid]
if other_user_uuid not in chats:
other_user_detail = self.backend._load_detail(other_user)
if other_user_detail is None: raise error.ContactNotOnline()
ctc_self = other_user_detail.contacts.get(user.uuid)
if ctc_self is not None:
if ctc_self.lists & ContactList.BL: raise error.ContactNotOnline()
# the target's permit/deny mode decides whether we may reach them at all, unless we hold a temp permit
if other_user.detail is not None and _is_blocking(other_user, user) and not self._temp_permitted(other_user, user):
raise error.ContactNotOnline()
chat = self.backend.chat_create()
chat.front_data['oscar0'] = True
# `user` joins
evt = ChatEventHandler(self.backend.loop, self, bs)
cs = chat.join('icbm', bs, evt)
bs.front_data['oscar0_chats'][other_user_uuid] = (cs, evt)
cs.invite(other_user)
try:
cs.invite(other_user)
except error.ClientError:
cs.close()
raise
chats[other_user_uuid] = (cs, evt)
elif other_user.status.is_offlineish():
raise error.ContactNotOnline()
return bs.front_data['oscar0_chats'].get(other_user_uuid)
return chats.get(other_user_uuid)
+54 -33
View File
@@ -13,6 +13,10 @@ from .proto.snac import SNACMessage
def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None:
backend.add_runner(ProtocolRunner('0.0.0.0', 5190, ListenerOSCAR, args=['OSCAR', backend, OSCARCtrl], service = 'OSCAR'))
# once someone's avatar has been turned into a buddy icon, OSCAR clients watching them get an arrival that carries it
from .proto.bart import set_refresh_hook
from .foodgroups.buddy import refresh_contact
set_refresh_hook(lambda user: refresh_contact(backend, user))
class ListenerOSCAR(asyncio.Protocol):
logger: Logger
@@ -33,8 +37,10 @@ class ListenerOSCAR(asyncio.Protocol):
self.controller = controller_factory(self.logger, 'direct', backend)
self.controller.close_callback = self._on_close
self.transport = None
self.buffer = b''
def connection_made(self, transport: asyncio.BaseTransport) -> None:
self.transport = transport
self.controller.transport = transport
self.controller.on_connect()
self.logger.log_connect()
@@ -57,10 +63,18 @@ class ListenerOSCAR(asyncio.Protocol):
self.buffer = b''
break
if self.buffer[0] != 0x2A:
# a FLAP header is 6 bytes (u8 0x2A, u8 frame, u16 sequence, u16 length); TCP can hand it over in pieces
if len(self.buffer) < 6:
break
# TODO(subpurple): Bufferize this?
if self.buffer[0] != 0x2A:
# without the marker there's no telling where the next frame starts, so the stream can't be recovered
self.logger.info('Recieved data without a FLAP start marker, closing connection')
self.buffer = b''
self.controller.close()
break
# TODO: bufferize this?
frame, sequence, length = struct.unpack('>BHH', self.buffer[1:6])
if len(self.buffer) < length + 6:
@@ -68,41 +82,48 @@ class ListenerOSCAR(asyncio.Protocol):
if len(self.buffer) >= length + 6:
data = self.buffer[6:length + 6]
match frame:
# SIGNON
case 0x01:
self.controller.on_signon_frame(data)
# DATA (always contains a SNAC)
case 0x02:
if len(data) < 10:
return
msg = SNACMessage()
msg.unmarshal(data)
self.controller.on_data_frame(msg)
# ERROR
case 0x03:
self.controller.on_error_frame(data)
# SIGNOFF
case 0x04:
self.controller.on_signoff_frame(data)
# KEEP_ALIVE
case 0x05:
pass
case _:
self.logger.info('Recieved unknown frame:', str(frame), 'with data:', data.hex())
# the frame is consumed before it's handled, so nothing a handler does can leave it in the buffer
self.buffer = self.buffer[length + 6:]
try:
self._handle_frame(frame, data)
except Exception as ex:
self.logger.error(ex)
if len(self.buffer) < 6:
break
def _handle_frame(self, frame: int, data: bytes) -> None:
match frame:
# SIGNON
case 0x01:
self.controller.on_signon_frame(data)
# DATA (always contains a SNAC)
case 0x02:
if len(data) < 10:
self.logger.info('Recieved a DATA frame too short to hold a SNAC:', data.hex())
return
msg = SNACMessage()
msg.unmarshal(data)
self.controller.on_data_frame(msg)
# ERROR
case 0x03:
self.controller.on_error_frame(data)
# SIGNOFF
case 0x04:
self.controller.on_signoff_frame(data)
# KEEP_ALIVE
case 0x05:
pass
case _:
self.logger.info('Recieved unknown frame:', str(frame), 'with data:', data.hex())
def _on_close(self) -> None:
if self.transport is not None:
self.transport.close()
self.transport.close()
+10 -1
View File
@@ -7,5 +7,14 @@ __all__ = [
'stats',
'feedbag',
'popup',
'bucp'
'bucp',
'directory',
'email',
'icq',
'admin',
'bart',
'chat',
'chatnav',
'user_lookup',
'invite'
]
+109
View File
@@ -0,0 +1,109 @@
import struct
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
ADMIN_TLV_SCREEN_NAME = 0x0001
ADMIN_TLV_NEW_PASSWORD = 0x0002
ADMIN_TLV_URL = 0x0004
ADMIN_TLV_ERROR = 0x0008
ADMIN_TLV_EMAIL = 0x0011
ADMIN_TLV_OLD_PASSWORD = 0x0012
ADMIN_TLV_REG_STATUS = 0x0013
ADMIN_PERMISSIONS = 0x0003
ADMIN_ERROR_VALIDATE_NICKNAME = 0x0001
ADMIN_ERROR_INVALID_REG_PREFERENCE = 0x0009
ADMIN_ERROR_READ_ONLY_FIELD = 0x0010
CONFIRM_EMAIL_SENT = 0x0000
CONFIRM_ALREADY_CONFIRMED = 0x001E
CONFIRM_SERVER_ERROR = 0x0023
# registration status (how much of the account's e-mail the directory may give out): none, limited, full
REG_STATUSES = (0x0001, 0x0002, 0x0003)
AIM_REG_KEY = 'AIM_REG'
def _reply(subgroup: int, request_id: int, tlvs: list) -> SNACMessage:
# ADMIN__INFO_REPLY and ADMIN__INFO_CHANGE_REPLY: u16 permissions, then a counted TLV block
msg = SNACMessage(0x0007, subgroup, 0x0000, request_id)
msg.write_u16(ADMIN_PERMISSIONS)
msg.write_tlv_block(tlvs)
return msg
def _error(subgroup: int, request_id: int, tag: int, code: int) -> SNACMessage:
# a failed change carries the error code and a (blank) URL; a password change echoes the empty new password TLV first
if tag == ADMIN_TLV_NEW_PASSWORD:
return _reply(subgroup, request_id, [TLV(ADMIN_TLV_NEW_PASSWORD, b''), TLV(ADMIN_TLV_ERROR, struct.pack('>H', code))])
return _reply(subgroup, request_id, [TLV(ADMIN_TLV_ERROR, struct.pack('>H', code)), TLV(ADMIN_TLV_URL, '')])
@Foodgroup(0x0007)
class AdminFoodgroup:
logger: Logger
@Subgroup(0x0002)
def info_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] ADMIN__INFO_QUERY')
user = context.user
tlvs = unmarshal_tlvs(message.data)
if find_tlv(tlvs, ADMIN_TLV_REG_STATUS) is not None:
status = int(user.settings.get(AIM_REG_KEY, 0x0003))
client.send_snac(_reply(0x0003, message.request_id, [TLV(ADMIN_TLV_REG_STATUS, struct.pack('>H', status))]))
elif find_tlv(tlvs, ADMIN_TLV_EMAIL) is not None:
client.send_snac(_reply(0x0003, message.request_id, [TLV(ADMIN_TLV_EMAIL, user.email or '')]))
elif find_tlv(tlvs, ADMIN_TLV_SCREEN_NAME) is not None:
client.send_snac(_reply(0x0003, message.request_id, [TLV(ADMIN_TLV_SCREEN_NAME, names.self_name(context.bs))]))
else:
client.ctrl.send_snac_error(0x0007, message.request_id, 0x0008)
@Subgroup(0x0004)
def info_change_request(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] ADMIN__INFO_CHANGE_REQUEST')
user = context.user
tlvs = unmarshal_tlvs(message.data)
if (sn_tlv := find_tlv(tlvs, ADMIN_TLV_SCREEN_NAME)) is not None:
proposed = sn_tlv.data.decode('latin-1')
# the screen name is the account's username, which is only changed from the website; asking for it as it is
# already succeeds
if names.normalize(proposed) != user.username.lower():
client.send_snac(_error(0x0005, message.request_id, ADMIN_TLV_SCREEN_NAME, ADMIN_ERROR_VALIDATE_NICKNAME))
elif proposed != user.username:
client.send_snac(_error(0x0005, message.request_id, ADMIN_TLV_SCREEN_NAME, ADMIN_ERROR_READ_ONLY_FIELD))
else:
client.send_snac(_reply(0x0005, message.request_id, [TLV(ADMIN_TLV_SCREEN_NAME, user.username)]))
elif find_tlv(tlvs, ADMIN_TLV_EMAIL) is not None:
# the e-mail address belongs to the account, managed from the website
client.send_snac(_error(0x0005, message.request_id, ADMIN_TLV_EMAIL, ADMIN_ERROR_READ_ONLY_FIELD))
elif (reg_tlv := find_tlv(tlvs, ADMIN_TLV_REG_STATUS)) is not None and len(reg_tlv.data) >= 2:
status = struct.unpack('>H', reg_tlv.data[:2])[0]
if status not in REG_STATUSES:
client.send_snac(_error(0x0005, message.request_id, ADMIN_TLV_REG_STATUS, ADMIN_ERROR_INVALID_REG_PREFERENCE))
return
user.settings[AIM_REG_KEY] = status
context.backend._mark_modified(user)
client.send_snac(_reply(0x0005, message.request_id, [TLV(ADMIN_TLV_REG_STATUS, struct.pack('>H', status))]))
elif find_tlv(tlvs, ADMIN_TLV_NEW_PASSWORD) is not None:
# so is the password: every protocol's copy of it is derived from the one set on the website
client.send_snac(_error(0x0005, message.request_id, ADMIN_TLV_NEW_PASSWORD, ADMIN_ERROR_READ_ONLY_FIELD))
else:
client.ctrl.send_snac_error(0x0007, message.request_id, 0x0008)
@Subgroup(0x0006)
def account_confirm_request(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] ADMIN__ACCT_CONFIRM_REQUEST')
# ADMIN__ACCT_CONFIRM_REPLY: u16 status, then a TLV (empty here); confirmation mails come from the website
status = CONFIRM_ALREADY_CONFIRMED if getattr(context.user, 'account_verified', False) else CONFIRM_SERVER_ERROR
reply = SNACMessage(0x0007, 0x0007, 0x0000, message.request_id)
reply.write_u16(status)
reply.write_tlv(TLV(0x0000, b''))
client.send_snac(reply)
+114
View File
@@ -0,0 +1,114 @@
import struct
from util.misc import Logger
from ..proto import bart as bart_store
from ..proto import names
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
# the largest upload taken; AIM keeps icons well under this
MAX_UPLOAD_BYTES = 0x8000
def _string08(value: str) -> bytes:
encoded = value.encode('latin-1', errors = 'replace')
return struct.pack('>B', len(encoded)) + encoded
def _read_bart_ids(data: bytes, count: int) -> list[tuple[int, int, bytes]]:
ids = []
for _ in range(count):
parsed = bart_store.parse_bart_id(data)
if parsed is None:
break
bart_type, flags, hash, data = parsed
ids.append((bart_type, flags, hash))
return ids
@Foodgroup(0x0010)
class BARTFoodgroup:
logger: Logger
@Subgroup(0x0002)
def upload_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# BART__UPLOAD_QUERY: u16 type, u16 length, the item
self.logger.info('[Client] BART__UPLOAD_QUERY')
bart_type = message.read_u16()
data = message.read_bytes(message.read_u16())
client.ctrl.backend.loop.create_task(_upload(client, context, message.request_id, bart_type, data))
@Subgroup(0x0004)
def download_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# BART__DOWNLOAD_QUERY: string08 whose, u8 command, then the BART ID
self.logger.info('[Client] BART__DOWNLOAD_QUERY')
name = message.read_bytes(message.read_u8()).decode('latin-1')
message.read_u8()
ids = _read_bart_ids(message.data, 1)
if not ids:
return
client.ctrl.backend.loop.create_task(_download(client, message.request_id, name, ids[0]))
@Subgroup(0x0006)
def download2_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# BART__DOWNLOAD2_QUERY: string08 whose, u8 count, then that many BART IDs
self.logger.info('[Client] BART__DOWNLOAD2_QUERY')
name = message.read_bytes(message.read_u8()).decode('latin-1')
count = message.read_u8()
ids = _read_bart_ids(message.data, count)
client.ctrl.backend.loop.create_task(_download2(client, message.request_id, name, ids))
async def _upload(client: OSCARClient, context: OSCARContext, request_id: int, bart_type: int, data: bytes) -> None:
# BART__UPLOAD_REPLY: u8 result, then the BART ID the item is filed under
reply = SNACMessage(0x0010, 0x0003, 0x0000, request_id)
if not data:
reply.write_u8(bart_store.BARTReplyCode.TooSmall)
reply.write_bytes(bart_store.build_bart_id(bart_type, 0, b''))
client.send_snac(reply)
return
if len(data) > MAX_UPLOAD_BYTES:
reply.write_u8(bart_store.BARTReplyCode.TooBig)
reply.write_bytes(bart_store.build_bart_id(bart_type, 0, b''))
client.send_snac(reply)
return
hash = await bart_store.store_item(data)
bs = context.bs
icon = bs.front_data.get('oscar0_bart_icon')
flags = bart_store.BARTFlags.Custom
if icon is not None and icon[1] == hash:
# the icon the feedbag said the client was using is here now, so it can go on show
flags = icon[0] & ~bart_store.BARTFlags.Unknown
bs.front_data['oscar0_bart_icon'] = (flags, hash)
reply.write_u8(bart_store.BARTReplyCode.Success)
reply.write_bytes(bart_store.build_bart_id(bart_type, flags, hash))
client.send_snac(reply)
if icon is not None and icon[1] == hash and not bs.closed:
from .buddy import refresh_contact
refresh_contact(context.backend, context.user)
async def _download(client: OSCARClient, request_id: int, name: str, bart_id: tuple[int, int, bytes]) -> None:
# BART__DOWNLOAD_REPLY: string08 whose, the BART ID, u16 length and the item (empty when there's no such item)
bart_type, flags, hash = bart_id
data = await bart_store.get_item(hash) or b''
reply = SNACMessage(0x0010, 0x0005, 0x0000, request_id)
reply.write_bytes(_string08(name))
reply.write_bytes(bart_store.build_bart_id(bart_type, flags, hash))
reply.write_u16(len(data))
reply.write_bytes(data)
client.send_snac(reply)
async def _download2(client: OSCARClient, request_id: int, name: str, ids: list[tuple[int, int, bytes]]) -> None:
# BART__DOWNLOAD2_REPLY, one per item: string08 whose, the query's BART ID, u8 code (0 found), the reply's BART ID, data
for bart_type, flags, hash in ids:
data = await bart_store.get_item(hash)
reply = SNACMessage(0x0010, 0x0007, 0x0000, request_id)
reply.write_bytes(_string08(name))
reply.write_bytes(bart_store.build_bart_id(bart_type, flags, hash))
reply.write_u8(0x00 if data is not None else bart_store.BARTReplyCode.NotFound)
reply.write_bytes(bart_store.build_bart_id(bart_type, flags, hash))
reply.write_u16(len(data or b''))
reply.write_bytes(data or b'')
client.send_snac(reply)
+6 -4
View File
@@ -2,19 +2,22 @@ import struct
from util.misc import Logger
from .pd import PDHandlers
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import TLV
@Foodgroup(0x0009)
class BOSFoodgroup:
class BOSFoodgroup(PDHandlers):
logger: Logger
subgroups = dict(PDHandlers.subgroups)
@Subgroup(0x0002)
def rights_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] BOS__RIGHTS_QUERY')
response_msg = SNACMessage(0x0009, 0x0003)
response_msg = SNACMessage(0x0009, 0x0003, 0x0000, message.request_id)
response_msg.write_tlvs([
TLV(0x0001, struct.pack('>H', 1000)), # max permits user is allowed
TLV(0x0002, struct.pack('>H', 1000)), # max deny entries user is allowed
@@ -22,5 +25,4 @@ class BOSFoodgroup:
])
self.logger.info('[Server] BOS__RIGHTS_REPLY')
client.send_snac(response_msg)
client.send_snac(response_msg)
+38 -33
View File
@@ -2,6 +2,7 @@ from core.client import Client
from util.misc import Logger
from util.hash import gen_salt
from ..proto import names
from ..proto.backend import login, LoginError
from ..proto.buffer import Buffer
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
@@ -20,15 +21,20 @@ class BUCPFoodgroup:
tlvs = unmarshal_tlvs(message.data)
screen_name_tlv = find_tlv(tlvs, 0x0001)
screen_name = screen_name_tlv.data.decode()
screen_name = screen_name_tlv.data.decode('latin-1') if screen_name_tlv is not None else ''
salt = context.backend.user_service.aim_get_md5_salt(screen_name)
# ICQ signs on with its UIN, AIM with a screen name; the salt is the account's, whichever one the name means
salt = None
for uuid in (context.backend.util_get_uuids_for_login(screen_name) if names.valid_name(screen_name) else []):
salt = context.backend.user_service.aim_get_md5_salt_by_uuid(uuid)
if salt is not None:
break
if salt is None:
# screen name doesn't exist or user did not enable OSCAR
salt = gen_salt()
response_msg = SNACMessage(0x0001, 0x0007)
response_msg = SNACMessage(0x0017, 0x0007, 0x0000, message.request_id)
response_msg.write_u16(len(salt))
response_msg.write_string(salt)
@@ -39,50 +45,49 @@ class BUCPFoodgroup:
def login_request(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] BUCP__LOGIN_REQUEST')
from ..ctrl import authenticate, client_version, multi_conn_flag
tlvs = unmarshal_tlvs(message.data)
screen_name_tlv = find_tlv(tlvs, 0x0001)
hashed_pw_tlv = find_tlv(tlvs, 0x0025)
screen_name = screen_name_tlv.data.decode()
screen_name = screen_name_tlv.data.decode('latin-1') if screen_name_tlv is not None else ''
client_hash = hashed_pw_tlv.data if hashed_pw_tlv is not None else b''
major_tlv = find_tlv(tlvs, 0x0017)
minor_tlv = find_tlv(tlvs, 0x0018)
build_tlv = find_tlv(tlvs, 0x001A)
major = Buffer(major_tlv.data).read_u16() if major_tlv else 0
minor = Buffer(minor_tlv.data).read_u16() if minor_tlv else 0
build = Buffer(build_tlv.data).read_u16() if build_tlv else 0
version_str = '{}.{}.{}'.format(major, minor, build)
context.client = Client('aim', version_str, context.client.via)
version_str = client_version(tlvs)
self.logger.info('Screen Name (client-given):', screen_name)
self.logger.info('Client version:', version_str)
self.logger.info('Password (hashed):', hashed_pw_tlv.data)
self.logger.info('Password (hashed):', client_hash)
response_msg = SNACMessage(0x0017, 0x0003)
response_msg = SNACMessage(0x0017, 0x0003, 0x0000, message.request_id)
error_code = None
uuid = None
user_service = context.backend.user_service
matched = {}
if (uuid := context.backend.util_get_uuid_from_username(screen_name)) is None:
error_code = LoginError.UnregisteredScreenname
def check(uuid: str) -> bool:
pw_bucp1 = user_service.aim_get_md5_password_by_uuid(uuid)
pw_bucp2 = user_service.aim_get_md5_password_bucp2_by_uuid(uuid)
if pw_bucp2 is not None and pw_bucp2 and pw_bucp2 == client_hash:
matched[uuid] = 'AIM5.x'
return True
if pw_bucp1 is not None and pw_bucp1 and pw_bucp1 == client_hash:
matched[uuid] = 'AIM3.5-4.8'
return True
return False
uuid, icq, error_code = authenticate(context.backend, screen_name, check)
if error_code in (LoginError.UnregisteredScreenname, LoginError.ICQUserError):
self.logger.info('Unregistered screenname')
elif error_code == LoginError.IncorrectPassword:
self.logger.info('Incorrect password')
else:
client_hash = hashed_pw_tlv.data
self.logger.info('Authenticated via', matched.get(uuid))
pw_bucp1 = context.backend.user_service.aim_get_md5_password(screen_name)
pw_bucp2 = context.backend.user_service.aim_get_md5_password_bucp2(screen_name)
context.client = Client('icq' if icq else 'aim', version_str, context.client.via)
client.ctrl.client = context.client
auth_ok = (pw_bucp1 is not None and pw_bucp1 == client_hash) or (pw_bucp2 is not None and pw_bucp2 == client_hash)
response_msg.write_bytes(login(self.logger, context, tlvs, uuid, error_code, icq = icq, multi_conn = multi_conn_flag(tlvs)))
if not auth_ok:
error_code = LoginError.IncorrectPassword
self.logger.info('Incorrect password')
else:
self.logger.info('Authenticated via', 'AIM5.x' if (pw_bucp2 == client_hash) else 'AIM3.5-4.8')
response_msg.write_bytes(login(self.logger, context, tlvs, uuid, error_code))
client.send_snac(response_msg)
client.send_snac(response_msg)
+176 -47
View File
@@ -1,15 +1,45 @@
import struct
import time
from core.models import Contact
from typing import Any, List, Optional, TYPE_CHECKING
from core.models import AIM_SSI_KEY, Contact, ContactList, Substatus, User
from util.icq import requires_authorization
from util.misc import Logger
from ..proto import names
from ..proto.delivery import oscar_sessions
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import TLV, unmarshal_tlvs
from ..proto.tlv import TLV
from ..proto.userinfo import build_userinfo, pick_session
if TYPE_CHECKING:
from core.backend import Backend, BackendSession
PENDING_ATTRIBUTE = 0x0066
# should be piped to .ctrl.send_snac()
def build_presence_notif(contact: Contact) -> SNACMessage:
def buddy_pending(viewer: User, contact: User) -> bool:
# whether `viewer`'s feedbag still marks `contact` as waiting on authorization (stored like feedbag.py keeps it)
store = viewer.settings.get(AIM_SSI_KEY)
if not isinstance(store, dict):
return False
suffix = ':' + contact.username.lower()
for key, attrs in (store.get('battrs') or {}).items():
if key.endswith(suffix) and any(tag == PENDING_ATTRIBUTE for tag, _ in attrs):
return True
return False
def watching(bs: 'BackendSession', contact: User) -> bool:
# whether this session's client has `contact` on its buddy list: the stored one for feedbag clients, its own otherwise
if contact.uuid in bs.backend.util_get_watched(bs):
return True
if not bs.front_data.get('oscar0_feedbag'):
return False
detail = bs.user.detail
ctc = detail.contacts.get(contact.uuid) if detail is not None else None
return ctc is not None and bool(ctc.lists & ContactList.FL)
def build_presence_notif(contact: Contact, backend: Any = None, viewer: Optional['BackendSession'] = None) -> SNACMessage:
# Packet dump from NINA's servers when a contact goes online:
# ===
# 0000 04 64 6b 61 79 00 00 00 07 00 30 00 04 67 19 67 .dkay.....0..g.g
@@ -42,55 +72,132 @@ def build_presence_notif(contact: Contact) -> SNACMessage:
# - TLV 0x0005: account creation time (value = 1652325069, in UNIX time)
#
msg = SNACMessage(0x0003, 0x000B if not contact.status.is_offlineish() else 0x000C)
offline = contact.status.is_offlineish()
msg.write_string_u8(contact.head.username)
msg.write_u16(0)
if not offline and backend is not None and not backend.util_get_sessions_by_user(contact.head):
offline = True
contact.status.substatus = Substatus.Offline
if contact.status.is_offlineish():
msg.write_tlv(TLV(0x0001, struct.pack('>L', 0x0008))) # User class (bitfield)
else:
capabilities = [
"{09461345-4C7F-11D1-8222-444553540000}", # Direct ICBM
"{094601FF-4C7F-11D1-8222-444553540000}", # Smart caps
"{748F2420-6287-11D1-8222-444553540000}", # Chat
"{09461343-4C7F-11D1-8222-444553540000}", # File transfer
"{09461341-4C7F-11D1-8222-444553540000}", # Voice chat
"{09460104-4C7F-11D1-8222-444553540000}", # RTC audio
"{09460105-4C7F-11D1-8222-444553540000}", # Unknown
"{09460102-4C7F-11D1-8222-444553540000}", # Camera
"{09460103-4C7F-11D1-8222-444553540000}", # Microphone
"{09460101-4C7F-11D1-8222-444553540000}", # RTC video
"{0946134A-4C7F-11D1-8222-444553540000}", # Games
"{09461346-4C7F-11D1-8222-444553540000}" # BART
]
capabilities_bytes = b''
# a buddy whose authorization the viewer is still waiting on stays offline to them until it's granted
if not offline and viewer is not None and buddy_pending(viewer.user, contact.head):
offline = True
for capability in capabilities:
capabilities_bytes += bytes.fromhex(capability
.lstrip('{')
.rstrip('}')
.replace('-', ''))
# each client gets the name it knows the buddy by (a UIN for ICQ, a screen name for AIM)
name = names.name_for(viewer, contact.head)
msg = SNACMessage(0x0003, 0x000B if not offline else 0x000C)
date_created_unix = int(time.mktime(contact.head.date_created.timetuple()))
date_login_unix = int(time.mktime(contact.head.date_login.timetuple())) if contact.head.date_login else 0
if offline:
# BUDDY__DEPARTED: an OSERVICE__USERINFO with its TLV count; ICQ only takes it with a (zero) user class inside
msg.write_string_u8(name)
msg.write_u16(0)
msg.write_tlv_block([TLV(0x0001, struct.pack('>H', 0x0000))]) # User class (bitfield)
return msg
# usually would include 0x001D (BART info), but since CrossTalk doesn't support
# it rn I've decided to omit it
msg.write_tlv_block([
TLV(0x3000, struct.pack('>L', 0x6719674C)), # Unknown
TLV(0x000D, capabilities_bytes), # Capability info
TLV(0x0001, struct.pack('>H', 0x0008)), # User class (bitfield)
TLV(0x0003, struct.pack('>L', date_login_unix)), # Account signon time (unix time_t)
TLV(0x000F, struct.pack('>L', 0)), # Session length
TLV(0x0005, struct.pack('>L', date_created_unix)), # Account creation time (unix time_t)
])
print('Subgroup:', hex(msg.subgroup))
print('TLVs:', unmarshal_tlvs(msg.data))
bs = pick_session(backend, contact.head) if backend is not None else None
msg.write_bytes(build_userinfo(
contact.head, bs, substatus = contact.status.substatus, name = name, viewer_icq = names.is_icq_session(viewer),
))
return msg
def push_presence(bs: 'BackendSession', contact_user: User) -> None:
# tell one session where `contact_user` stands right now (the arrival a buddy list add or a sign-on needs)
from core.backend import _watch_contact
ctrl = getattr(bs.evt, 'ctrl', None)
if ctrl is None or contact_user is bs.user or not names.representable(contact_user):
return
detail = bs.user.detail
ctc = detail.contacts.get(contact_user.uuid) if detail is not None else None
if ctc is None or not ctc.lists & ContactList.FL:
ctc = _watch_contact(contact_user, bs.user)
else:
ctc.compute_visible_status(bs.user)
if ctc.status.is_offlineish():
return
ctrl.send_snac(build_presence_notif(ctc, bs.backend, bs))
def push_buddy_list(bs: 'BackendSession') -> None:
# everyone on the client's buddy list who's online, at sign-on: the stored list for feedbag clients, the client's own
# (BUDDY__ADD_BUDDIES) otherwise
backend = bs.backend
seen = set()
if bs.front_data.get('oscar0_feedbag') and bs.user.detail is not None:
for ctc in bs.user.detail.get_contacts_by_list(ContactList.FL):
seen.add(ctc.head.uuid)
push_presence(bs, ctc.head)
for uuid in backend.util_get_watched(bs):
if uuid in seen:
continue
contact_user = backend._load_user_record(uuid)
if contact_user is not None:
push_presence(bs, contact_user)
def refresh_contact(backend: 'Backend', user: User) -> None:
# something only OSCAR shows (a buddy icon) changed for `user`: OSCAR sessions with them on their list get a new arrival
detail = user.detail
viewers = []
if detail is not None:
for ctc in detail.contacts.values():
if ctc.lists & ContactList.RL:
viewers.extend(oscar_sessions(backend, ctc.head))
viewers.extend(bs for bs in backend.util_get_watchers(user.uuid) if bs.front_data.get('oscar0'))
for bs in set(viewers):
if bs.front_data.get('oscar0_ready') and watching(bs, user):
push_presence(bs, user)
for bs in oscar_sessions(backend, user):
ctrl = getattr(bs.evt, 'ctrl', None)
if ctrl is not None and bs.front_data.get('oscar0_ready'):
from .oservice import build_self_info
ctrl.send_snac(build_self_info(bs))
def _read_buddies(message: SNACMessage) -> List[str]:
# BUDDY__ADD_BUDDIES and friends: string08 names, one after another until the SNAC runs out
buddies = []
while len(message) > 0:
try:
length = message.read_u8()
buddies.append(message.read_bytes(length).decode('latin-1'))
except struct.error:
break
return buddies
def add_buddies(client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
bs = context.bs
backend = context.backend
rejected = []
for name in _read_buddies(message):
contact_user = names.resolve_user(backend, name)
if contact_user is None or contact_user is bs.user:
rejected.append(name)
continue
# a client-side list can't take part in ICQ authorization, so whoever asks to be asked first can't go on one
if requires_authorization(contact_user, bs.user):
rejected.append(name)
continue
names.remember(bs, contact_user, name)
backend.util_watch(bs, contact_user.uuid)
# before OSERVICE__CLIENT_READY the client would drop arrivals, so those wait for the sign-on push
if bs.front_data.get('oscar0_ready'):
push_presence(bs, contact_user)
if rejected:
# BUDDY__REJECT_NOTIFICATION: the names that didn't make it onto the list
reply = SNACMessage(0x0003, 0x000A, 0x0000, message.request_id)
for name in rejected:
encoded = name.encode('latin-1', errors = 'replace')
reply.write_u8(len(encoded))
reply.write_bytes(encoded)
client.send_snac(reply)
def del_buddies(client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
bs = context.bs
backend = context.backend
for name in _read_buddies(message):
uuid = names.resolve(backend, name)
if uuid is not None:
backend.util_unwatch(bs, uuid)
@Foodgroup(0x0003)
class BuddyFoodgroup:
@@ -100,12 +207,34 @@ class BuddyFoodgroup:
def rights_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] BUDDY_RIGHTS_QUERY')
response_msg = SNACMessage(0x0003, 0x0003)
response_msg = SNACMessage(0x0003, 0x0003, 0x0000, message.request_id)
response_msg.write_tlvs([
TLV(0x0001, struct.pack('>H', 1000)), # max buddies
TLV(0x0002, struct.pack('>H', 3000)), # max watchers
TLV(0x0003, struct.pack('>H', 1000)), # max ICQ broadcast recipients
TLV(0x0004, struct.pack('>H', 160)) # max temp buddies
])
self.logger.info('[Server] BUDDY_RIGHTS_REPLY')
client.send_snac(response_msg)
@Subgroup(0x0004)
def add_buddies(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] BUDDY__ADD_BUDDIES')
add_buddies(client, context, message)
@Subgroup(0x0005)
def del_buddies(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] BUDDY__DEL_BUDDIES')
del_buddies(client, context, message)
@Subgroup(0x000F)
def add_temp_buddies(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# temp buddies only ever last the session, which is all a client-side buddy is here anyway
self.logger.info('[Client] BUDDY__ADD_TEMP_BUDDIES')
add_buddies(client, context, message)
@Subgroup(0x0010)
def del_temp_buddies(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] BUDDY__DEL_TEMP_BUDDIES')
del_buddies(client, context, message)
+221
View File
@@ -0,0 +1,221 @@
import struct
import time
from typing import Any
from util.misc import Logger
from ..proto import names
from ..proto.buffer import Buffer
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import TLV, unmarshal_tlvs, marshal_tlvs, find_tlv
from ..proto.userinfo import build_userinfo
EXCHANGE_PRIVATE = 0x0004
EXCHANGE_PUBLIC = 0x0005
ROOM_FULLY_QUALIFIED_NAME = 0x006A
ROOM_FLAGS = 0x00C9
ROOM_CREATE_TIME = 0x00CA
ROOM_MAX_MESSAGE_LENGTH = 0x00D1
ROOM_MAX_OCCUPANCY = 0x00D2
ROOM_NAME = 0x00D3
ROOM_CREATE_PERMISSIONS = 0x00D5
ROOM_MAX_VISIBLE_MESSAGE_LENGTH = 0x00DA
CHAT_TLV_PUBLIC_WHISPER = 0x0001
CHAT_TLV_WHISPER_TO = 0x0002
CHAT_TLV_SENDER = 0x0003
CHAT_TLV_MESSAGE = 0x0005
CHAT_TLV_REFLECT = 0x0006
MESSAGE_TEXT = 0x0001
MESSAGE_ENCODING = 0x0002
MESSAGE_LANGUAGE = 0x0003
class Room:
__slots__ = ('exchange', 'name', 'cookie', 'created', 'members')
exchange: int
name: str
cookie: str
created: int
# the chat service connections in the room, in the order they joined
members: dict[Any, None]
def __init__(self, exchange: int, name: str) -> None:
self.exchange = exchange
self.name = name
# exchange-instance-name, the layout clients (Pidgin, at least) take the room name back out of
self.cookie = '{}-{}-{}'.format(exchange, 0, name)
self.created = int(time.time())
self.members = {}
_rooms: dict[str, Room] = {}
_rooms_by_name: dict[tuple[int, str], Room] = {}
def find_room(cookie: str) -> Room | None:
return _rooms.get(cookie)
def create_room(exchange: int, name: str, *, create: bool = True) -> Room | None:
# a room exists while anyone is in it (or about to join), and is found again by name
key = (exchange, name.lower())
room = _rooms_by_name.get(key)
if room is not None or not create:
return room
# rooms made but never joined don't hang around
now = time.time()
for stale in [other for other in _rooms.values() if not other.members and now - other.created > 300]:
_drop_room(stale)
room = Room(exchange, name)
_rooms[room.cookie] = room
_rooms_by_name[key] = room
return room
def _drop_room(room: Room) -> None:
_rooms.pop(room.cookie, None)
_rooms_by_name.pop((room.exchange, room.name.lower()), None)
def room_tlvs(room: Room) -> list[TLV]:
encoded = room.name.encode('utf-8')
return [
TLV(ROOM_FLAGS, struct.pack('>H', 15)),
TLV(ROOM_CREATE_TIME, struct.pack('>L', room.created)),
TLV(ROOM_MAX_MESSAGE_LENGTH, struct.pack('>H', 1024)),
TLV(ROOM_MAX_OCCUPANCY, struct.pack('>H', 100)),
TLV(ROOM_CREATE_PERMISSIONS, struct.pack('>B', 2)),
TLV(ROOM_FULLY_QUALIFIED_NAME, encoded),
TLV(ROOM_NAME, encoded),
TLV(ROOM_MAX_VISIBLE_MESSAGE_LENGTH, struct.pack('>H', 1024)),
]
def room_info_update(room: Room) -> bytes:
# u16 exchange, string08 cookie, u16 instance, u8 detail level (Pidgin expects 2), counted TLV block
cookie = room.cookie.encode('utf-8')
buf = Buffer()
buf.write_u16(room.exchange)
buf.write_u8(len(cookie))
buf.write_bytes(cookie)
buf.write_u16(0)
buf.write_u8(0x02)
buf.write_tlv_block(room_tlvs(room))
return buf.data
def parse_room_info(data: bytes) -> dict[str, Any] | None:
# u16 exchange, string08 cookie, u16 instance (what OSERVICE__SERVICE_REQUEST and CHAT_NAV name a room by)
if len(data) < 3 or len(data) < 3 + data[2]:
return None
exchange = struct.unpack('>H', data[:2])[0]
cookie = data[3:3 + data[2]].decode('utf-8', errors = 'replace')
instance = struct.unpack('>H', data[3 + data[2]:5 + data[2]])[0] if len(data) >= 5 + data[2] else 0
return { 'exchange': exchange, 'cookie': cookie, 'instance': instance }
def _userinfo(member: Any, viewer: Any) -> bytes:
return build_userinfo(
member.bs.user, member.bs, name = names.name_for(viewer.bs, member.bs.user), viewer_icq = names.is_icq_session(viewer.bs),
)
def _users_snac(subgroup: int, members: list[Any], viewer: Any) -> SNACMessage:
# CHAT__USERS_JOINED / CHAT__USERS_LEFT: USERINFOs back to back
msg = SNACMessage(0x000E, subgroup)
for member in members:
msg.write_bytes(_userinfo(member, viewer))
return msg
def join_room(ctrl: Any) -> None:
# on the chat connection's OSERVICE__CLIENT_READY, in the order the macOS 4.0.9 client needs (or it drops the room
# seconds later): who's in it, the room's info, then everyone else hears about the newcomer
info = ctrl.room
room = find_room(info['cookie']) if info is not None else None
if room is None:
ctrl.close()
return
room.members[ctrl] = None
members = list(room.members)
ctrl.send_snac(_users_snac(0x0003, members, ctrl))
update = SNACMessage(0x000E, 0x0002)
update.write_bytes(room_info_update(room))
ctrl.send_snac(update)
for other in members:
if other is not ctrl:
other.send_snac(_users_snac(0x0003, [ctrl], other))
def leave_room(ctrl: Any) -> None:
info = ctrl.room
ctrl.room = None
room = find_room(info['cookie']) if info is not None else None
if room is None or ctrl not in room.members:
return
del room.members[ctrl]
for other in list(room.members):
other.send_snac(_users_snac(0x0004, [ctrl], other))
if not room.members:
_drop_room(room)
@Foodgroup(0x000E)
class ChatFoodgroup:
logger: Logger
@Subgroup(0x0005)
def channel_msg_tohost(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] CHAT__CHANNEL_MSG_TOHOST')
ctrl = client.ctrl
info = ctrl.room
room = find_room(info['cookie']) if info is not None else None
if room is None or ctrl not in room.members:
return
# cookie, u16 channel, TLVs
cookie = message.read_bytes(8)
channel = message.read_u16()
tlvs = unmarshal_tlvs(message.data)
if channel == 0xFFFF:
# the macOS 4.0.9 client sends a broken channel; it means the MIME channel
channel = 0x0003
message_tlv = find_tlv(tlvs, CHAT_TLV_MESSAGE)
if message_tlv is None:
return
# only the text, its encoding and language get passed on: extra TLVs from newer clients (AIM 5.9's) crash older
# ones (macOS AIM 2.x)
parts = []
for tlv in unmarshal_tlvs(message_tlv.data):
if tlv.type == MESSAGE_ENCODING and tlv.data == b'ISO 8859':
# Kopete's encoding name leaves the message blank in Windows AIM
tlv = TLV(MESSAGE_ENCODING, 'ISO-8859-1')
if tlv.type in (MESSAGE_TEXT, MESSAGE_ENCODING, MESSAGE_LANGUAGE):
parts.append(tlv)
public_whisper = find_tlv(tlvs, CHAT_TLV_PUBLIC_WHISPER) is not None
whisper_tlv = find_tlv(tlvs, CHAT_TLV_WHISPER_TO)
def build(viewer: Any) -> SNACMessage:
# CHAT__CHANNEL_MSG_TOCLIENT: cookie, channel, then (in this order, or AIM 2.x loses the names) the sender,
# the public whisper flag, the message
out = SNACMessage(0x000E, 0x0006)
out.write_bytes(cookie)
out.write_u16(channel)
out_tlvs = [TLV(CHAT_TLV_SENDER, _userinfo(ctrl, viewer))]
if public_whisper:
out_tlvs.append(TLV(CHAT_TLV_PUBLIC_WHISPER))
out_tlvs.append(TLV(CHAT_TLV_MESSAGE, marshal_tlvs(parts)))
out.write_tlvs(out_tlvs)
return out
if whisper_tlv is not None and not public_whisper:
# a whisper goes to just the one person
target = names.resolve(context.backend, whisper_tlv.data.decode('latin-1'))
for member in room.members:
if member is not ctrl and member.bs is not None and member.bs.user.uuid == target:
member.send_snac(build(member))
else:
for member in room.members:
if member is not ctrl:
member.send_snac(build(member))
if find_tlv(tlvs, CHAT_TLV_REFLECT) is not None:
reflected = build(ctrl)
reflected.request_id = message.request_id
ctrl.send_snac(reflected)
+106
View File
@@ -0,0 +1,106 @@
import struct
from util.misc import Logger
from ..proto.buffer import Buffer
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import TLV, unmarshal_tlvs, find_tlv
from .chat import (
EXCHANGE_PRIVATE, EXCHANGE_PUBLIC, ROOM_NAME, create_room, find_room, parse_room_info, room_info_update,
)
NAV_TLV_MAX_CONCURRENT_ROOMS = 0x0002
NAV_TLV_EXCHANGE_INFO = 0x0003
NAV_TLV_ROOM_INFO = 0x0004
NAV_ERROR_NOT_SUPPORTED = 0x0008
NAV_ERROR_NO_MATCH = 0x0014
MAX_CONCURRENT_ROOMS = 10
def exchange_info(exchange: int) -> bytes:
# an exchange's description: u16 id, then a counted TLV block of its settings
buf = Buffer()
buf.write_u16(exchange)
buf.write_tlv_block([
TLV(0x0003, struct.pack('>B', MAX_CONCURRENT_ROOMS)), # max concurrent rooms (aim 2.x-3.x want it)
TLV(0x0002, struct.pack('>H', 0x0010)), # class permissions
TLV(0x0004, struct.pack('>H', 100)), # max room name length
TLV(0x00C9, struct.pack('>H', 15)), # flags: evilable, nav only, instancing, occupant peek
TLV(0x00D5, struct.pack('>B', 2)), # who may create rooms
TLV(0x00D6, 'us-ascii'),
TLV(0x00D7, 'en'),
TLV(0x00D8, 'us-ascii'),
TLV(0x00D9, 'en'),
])
return buf.data
def nav_info(request_id: int, tlvs: list) -> SNACMessage:
# CHAT_NAV__NAV_INFO: TLVs, no count
msg = SNACMessage(0x000D, 0x0009, 0x0000, request_id)
msg.write_tlvs(tlvs)
return msg
@Foodgroup(0x000D)
class ChatNavFoodgroup:
logger: Logger
@Subgroup(0x0002)
def request_chat_rights(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] CHAT_NAV__REQUEST_CHAT_RIGHTS')
client.send_snac(nav_info(message.request_id, [
TLV(NAV_TLV_MAX_CONCURRENT_ROOMS, struct.pack('>B', MAX_CONCURRENT_ROOMS)),
TLV(NAV_TLV_EXCHANGE_INFO, exchange_info(EXCHANGE_PRIVATE)),
TLV(NAV_TLV_EXCHANGE_INFO, exchange_info(EXCHANGE_PUBLIC)),
]))
@Subgroup(0x0003)
def request_exchange_info(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] CHAT_NAV__REQUEST_EXCHANGE_INFO')
exchange = message.read_u16()
if exchange not in (EXCHANGE_PRIVATE, EXCHANGE_PUBLIC):
client.ctrl.send_snac_error(0x000D, message.request_id, NAV_ERROR_NOT_SUPPORTED)
return
client.send_snac(nav_info(message.request_id, [
TLV(NAV_TLV_MAX_CONCURRENT_ROOMS, struct.pack('>B', MAX_CONCURRENT_ROOMS)),
TLV(NAV_TLV_EXCHANGE_INFO, exchange_info(exchange)),
]))
@Subgroup(0x0004)
def request_room_info(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# u16 exchange, string08 cookie, u16 instance, u8 detail level
self.logger.info('[Client] CHAT_NAV__REQUEST_ROOM_INFO')
info = parse_room_info(message.data)
room = find_room(info['cookie']) if info is not None else None
if room is None or room.exchange != info['exchange']:
client.ctrl.send_snac_error(0x000D, message.request_id, NAV_ERROR_NO_MATCH)
return
client.send_snac(nav_info(message.request_id, [TLV(NAV_TLV_ROOM_INFO, room_info_update(room))]))
@Subgroup(0x0008)
def create_room(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# a CHAT__ROOM_INFO_UPDATE layout: u16 exchange, string08 cookie ("create"), u16 instance, u8 detail, TLV block
self.logger.info('[Client] CHAT_NAV__CREATE_ROOM')
buf = Buffer(message.data)
try:
exchange = buf.read_u16()
buf.read_bytes(buf.read_u8())
buf.read_u16()
buf.read_u8()
tlvs = buf.read_tlv_block()
except (struct.error, AssertionError):
client.ctrl.send_snac_error(0x000D, message.request_id, NAV_ERROR_NOT_SUPPORTED)
return
name_tlv = find_tlv(tlvs, ROOM_NAME)
if exchange not in (EXCHANGE_PRIVATE, EXCHANGE_PUBLIC) or name_tlv is None or not name_tlv.data:
client.ctrl.send_snac_error(0x000D, message.request_id, NAV_ERROR_NOT_SUPPORTED)
return
name = name_tlv.data.decode('utf-8', errors = 'replace')
room = create_room(exchange, name, create = exchange == EXCHANGE_PRIVATE)
if room is None:
# public rooms are the operator's to make; there are none to join by name
client.ctrl.send_snac_error(0x000D, message.request_id, NAV_ERROR_NO_MATCH)
return
client.send_snac(nav_info(message.request_id, [TLV(NAV_TLV_ROOM_INFO, room_info_update(room))]))
+94
View File
@@ -0,0 +1,94 @@
import struct
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
ODIR_FIRST_NAME = 0x0001
ODIR_LAST_NAME = 0x0002
ODIR_EMAIL = 0x0005
ODIR_COUNTRY = 0x0006
ODIR_STATE = 0x0007
ODIR_CITY = 0x0008
ODIR_SCREEN_NAME = 0x0009
ODIR_INTEREST = 0x000B
ODIR_NICKNAME = 0x000C
SEARCH_NAME_MISSING = 0x0004
SEARCH_OK = 0x0005
MAX_RESULTS = 20
@Foodgroup(0x000F)
class DirectoryFoodgroup:
logger: Logger
@Subgroup(0x0002)
def info_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] DIRECTORY__INFO_QUERY')
# the search kind follows from the TLVs:
# an e-mail address, an interest keyword, or a first or last name
tlvs = unmarshal_tlvs(message.data)
backend = context.backend
def text(tag: int) -> str:
tlv = find_tlv(tlvs, tag)
return tlv.data.decode('latin-1') if tlv is not None else ''
reply = SNACMessage(0x000F, 0x0003, 0x0000, message.request_id)
if find_tlv(tlvs, ODIR_EMAIL) is not None:
uuids = backend.user_service.search_uuids(email = text(ODIR_EMAIL), limit = MAX_RESULTS)
elif find_tlv(tlvs, ODIR_INTEREST) is not None:
uuids = []
elif find_tlv(tlvs, ODIR_FIRST_NAME) is not None or find_tlv(tlvs, ODIR_LAST_NAME) is not None:
uuids = backend.user_service.search_uuids(
first_name = text(ODIR_FIRST_NAME), last_name = text(ODIR_LAST_NAME), nickname = text(ODIR_NICKNAME),
limit = MAX_RESULTS,
)
else:
# ODIR__INFO_REPLY: u16 status, u16 unknown, and with this status nothing else
reply.write_u16(SEARCH_NAME_MISSING)
reply.write_u16(0)
self.logger.info('[Server] DIRECTORY__INFO_REPLY')
client.send_snac(reply)
return
from .locate import dir_tlvs
results = []
for uuid in uuids:
user = backend._load_user_record(uuid)
if user is None or not names.representable(user):
continue
fields = { tlv.type: tlv for tlv in dir_tlvs(user) }
results.append([
fields.get(ODIR_FIRST_NAME, TLV(ODIR_FIRST_NAME, b'')),
fields.get(ODIR_LAST_NAME, TLV(ODIR_LAST_NAME, b'')),
fields.get(ODIR_STATE, TLV(ODIR_STATE, b'')),
fields.get(ODIR_CITY, TLV(ODIR_CITY, b'')),
fields.get(ODIR_COUNTRY, TLV(ODIR_COUNTRY, b'')),
TLV(ODIR_SCREEN_NAME, names.name_for(context.bs, user)),
])
# u16 status, u16 unknown, u16 result count, each result a counted TLV block
reply.write_u16(SEARCH_OK)
reply.write_u16(0)
reply.write_u16(len(results))
for result in results:
reply.write_tlv_block(result)
self.logger.info('[Server] DIRECTORY__INFO_REPLY')
client.send_snac(reply)
@Subgroup(0x0004)
def interests_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] DIRECTORY__INTERESTS_QUERY')
# we don't yet have an interests directory, so the count stays zero.
response_msg = SNACMessage(0x000F, 0x0005, 0x0000, message.request_id)
response_msg.write_u16(1)
response_msg.write_u16(0)
self.logger.info('[Server] DIRECTORY__INTERESTS_LIST')
client.send_snac(response_msg)
+19
View File
@@ -0,0 +1,19 @@
from util.misc import Logger
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
@Foodgroup(0x0018)
class EmailFoodgroup:
logger: Logger
@Subgroup(0x0006)
def status_request(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] EMAIL__STATUS_REQUEST')
# unread count. no mail yet, so it stays zero
# 0x06 is ALERT__NOTIFY_CAPABILITIES, which takes no reply; answering it with an
# ALERT__NOTIFY nobody asked for is what used to go back here
self.logger.info('[Client] Alert capabilities:', message.data.hex())
@Subgroup(0x0016)
def activate(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] EMAIL__ACTIVATE (no reply expected)')
File diff suppressed because it is too large. Load diff
+591 -74
View File
@@ -1,14 +1,24 @@
import asyncio
import ipaddress
import os
import time, struct
import re
from html import unescape
from html import escape, unescape
from enum import IntEnum
from typing import Any, Callable, Dict, List, Optional, Tuple
from util.misc import Logger
from core.models import MessageData, MessageType, User
from util.icq import from_latin1, latin1
from util.misc import Logger, gen_uuid
from core import error
from core.models import MessageData, MessageType, OIM, User, _is_blocking
from ..proto import names
from ..proto.buffer import Buffer
from ..proto.delivery import oscar_sessions
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import find_tlv, unmarshal_tlvs, marshal_tlvs, TLV
from ..proto.userinfo import build_userinfo, pick_session
class ICBMChannel(IntEnum):
@@ -19,11 +29,55 @@ class ICBMChannel(IntEnum):
CoBrowser = 0x0005
class ICBMEvent(IntEnum):
Finished = 0x0000
Finished = 0x0000
Typed = 0x0001
Typing = 0x0002
Closed = 0x000F
class ICBMTag(IntEnum):
ImData = 0x0002
RequestHostAck = 0x0003
AutoResponse = 0x0004
Data = 0x0005
Store = 0x0006
WantEvents = 0x000B
SendTime = 0x0016
class ICBMCharset(IntEnum):
Ascii = 0x0000
Unicode = 0x0002
Latin1 = 0x0003
class ICQMessageType(IntEnum):
Plain = 0x01
Chat = 0x02
File = 0x03
Url = 0x04
AuthRequest = 0x06
AuthDeny = 0x07
AuthGrant = 0x08
Server = 0x09
Added = 0x0C
WebPager = 0x0D
EmailExpress = 0x0E
Contacts = 0x13
Plugin = 0x1A
class ICBMError(IntEnum):
RateToHost = 0x0002
NotLoggedOn = 0x0004
NotSupportedByHost = 0x0008
NotSupportedByClient = 0x0009
RequestDenied = 0x000D
InLocalPermitDeny = 0x0010
UNICODE_CAPABILITY = bytes.fromhex('0946134E4C7F11D18222444553540000')
from core.abuse import (
EVIL_DELTA, EVIL_DELTA_ANONYMOUS, EVIL_DECAY, EVIL_DECAY_INTERVAL, EVIL_MAX, CONVERSATION_WINDOW,
)
@Foodgroup(0x0004)
class ICBMFoodgroup:
logger: Logger
@@ -37,7 +91,7 @@ class ICBMFoodgroup:
def parameter_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] ICBM__PARAMENTER_QUERY')
response_msg = SNACMessage(0x0004, 0x0005)
response_msg = SNACMessage(0x0004, 0x0005, 0x0000, message.request_id)
# Response from NINA's servers:
# ==
@@ -48,12 +102,12 @@ class ICBMFoodgroup:
# The response data are not TLVs and are instead WORD/DWORDs so I cannot fit
# the names below the hex data. See https://ninawiki.preloading.dev/wiki/Protocols/OSCAR/SNAC/ICBM_PARAMETER_REPLY and
# https://ninawiki.preloading.dev/wiki/Protocols/OSCAR/SNAC/ICBM_ADD_PARAMETERS for more information.
response_msg.write_u16(5) # maxSlots
response_msg.write_u16(100) # maxSlots
response_msg.write_u32(0x00003) # icbmFlags (default)
response_msg.write_u16(512) # maxIncomingICBMLen
response_msg.write_u16(999) # maxSourceEvil
response_msg.write_u16(999) # maxDestinationEvil
response_msg.write_u32(1000) # minInterICBMInterval
response_msg.write_u32(0) # minInterICBMInterval
self.logger.info('[Server] ICBM__PARAMENTER_REPLY')
client.send_snac(response_msg)
@@ -62,7 +116,7 @@ class ICBMFoodgroup:
def channel_msg_tohost(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
cookie = message.read_bytes(8)
channel = message.read_u16()
receiver = message.read_string_u8()
receiver = message.read_bytes(message.read_u8()).decode('latin-1')
tlvs = unmarshal_tlvs(message.data)
self.logger.info('[Client] ICBM__CHANNEL_MSG_TOHOST')
@@ -73,53 +127,127 @@ class ICBMFoodgroup:
for tlv in tlvs:
self.logger.info('[Client] TLV', hex(tlv.type), '-', tlv.data)
if channel != ICBMChannel.AOLIM:
self.logger.info('[Client] Unsupported channel:', hex(channel))
return
send = _Send(client, context, message, cookie, channel, receiver, tlvs)
im_data_tlv = find_tlv(tlvs, 0x0002)
if im_data_tlv is None:
self.logger.info('[Client] Missing IM data TLV')
return
im_tlvs = unmarshal_tlvs(im_data_tlv.data)
im_text_tlv = find_tlv(im_tlvs, 0x0101)
if im_text_tlv is None:
self.logger.info('[Client] Missing IM text TLV inside IM data')
return
text = im_text_tlv.data[4:].decode('ascii', errors='replace')
self.logger.info('[Client] Message text:', text)
receiver_uuid = context.backend.util_get_uuid_from_username(receiver)
if receiver_uuid is None:
target = names.resolve_user(context.backend, receiver)
if target is None or not names.representable(target):
self.logger.info('[Client] Unknown receiver:', receiver)
send.error(ICBMError.NotLoggedOn)
return
names.remember(context.bs, target, receiver)
send.target = target
# the sender blocking the receiver is a local refusal; the receiver blocking the sender just looks like they're away
if _blocks(context.backend, context.user, target):
send.error(ICBMError.InLocalPermitDeny)
return
if _blocks(context.backend, target, context.user) and not client.ctrl._temp_permitted(target, context.user):
send.error(ICBMError.NotLoggedOn)
return
try:
cs, evt = client.ctrl._get_private_chat_with(receiver_uuid)
except Exception as ex:
self.logger.info('[Client] Could not create private chat:', str(ex))
if channel == ICBMChannel.AOLIM:
im_data_tlv = find_tlv(tlvs, ICBMTag.ImData)
if im_data_tlv is None:
self.logger.info('[Client] Missing IM data TLV')
return
text = parse_im_text(im_data_tlv.data)
if text is None:
self.logger.info('[Client] Missing IM text TLV inside IM data')
return
self.logger.info('[Client] Message text:', text)
if names.is_icq_session(context.bs) and not looks_like_html(text):
# ICQ sends plain text, where AIM sends HTML
send.text(text, plain_to_html(text))
else:
send.text(strip_html_tags(text), text)
elif channel == ICBMChannel.Rendezvous:
send.rendezvous()
elif channel == ICBMChannel.ICQ:
data_tlv = find_tlv(tlvs, ICBMTag.Data)
parsed = parse_icq_message(data_tlv.data) if data_tlv is not None else None
if parsed is None:
self.logger.info('[Client] Malformed channel 4 message')
return
send.icq(*parsed)
else:
self.logger.info('[Client] Unsupported channel:', hex(channel))
send.error(ICBMError.NotSupportedByHost)
@Subgroup(0x0008)
def evil_request(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] ICBM__EVIL_REQUEST')
# u16 send as (0: as yourself, 1: anonymously), string08 who
send_as = message.read_u16()
name = message.read_bytes(message.read_u8()).decode('latin-1')
ctrl = client.ctrl
backend = context.backend
user = context.user
target = names.resolve_user(backend, name)
if target is user:
# warning yourself puts AIM in a bad state
ctrl.send_snac_error(0x0004, message.request_id, ICBMError.NotSupportedByHost)
return
if target is None or _blocks(backend, user, target) or _blocks(backend, target, user):
ctrl.send_snac_error(0x0004, message.request_id, ICBMError.NotLoggedOn)
return
if not backend.util_get_sessions_by_user(target) or target.status.is_offlineish():
ctrl.send_snac_error(0x0004, message.request_id, ICBMError.NotLoggedOn)
return
level = _warning_level(target)
if level >= EVIL_MAX:
ctrl.send_snac_error(0x0004, message.request_id, ICBMError.RequestDenied)
return
ack = SNACMessage(0x0004, 0x000C)
ack.request_id = message.request_id
ack.write_bytes(cookie)
ack.write_u16(channel)
ack.write_string_u8(receiver)
self.logger.info('[Server] ICBM__HOST_ACK')
client.send_snac(ack)
# the shared core checks the warner may (`_may_warn`), raises the level, starts it wearing off and tells every
# session of the target, whatever it's signed on with (OSCAR gets OSERVICE__EVIL_NOTIFICATION, `build_evil_notification`)
result = backend.abuse.warn(user, target, anonymous = (send_as == 1))
if result is None:
ctrl.send_snac_error(0x0004, message.request_id, ICBMError.RequestDenied)
return
delta, new_level = result
md = MessageData(sender=context.user, type=MessageType.Chat, text=strip_html_tags(text))
md.front_cache['icbm_cookie'] = cookie
md.front_cache['icbm_html'] = text
evt._send_when_user_joins(receiver_uuid, md)
reply = SNACMessage(0x0004, 0x0009, 0x0000, message.request_id)
reply.write_u16(delta)
reply.write_u16(new_level)
self.logger.info('[Server] ICBM__EVIL_REPLY')
client.send_snac(reply)
@Subgroup(0x000B)
def client_err(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# ICBM__CLIENT_ERR: cookie, u16 channel, string08 who, u16 code, then code specific data; ICQ also acks channel
# 2 messages (and answers away message requests) this way. it's passed on as is, from us
cookie = message.read_bytes(8)
channel = message.read_u16()
name = message.read_bytes(message.read_u8()).decode('latin-1')
rest = message.data
self.logger.info('[Client] ICBM__CLIENT_ERR to', name)
target = names.resolve_user(context.backend, name)
if target is None or _blocks(context.backend, target, context.user):
return
for bs_target in oscar_sessions(context.backend, target):
relay = SNACMessage(0x0004, 0x000B)
relay.write_bytes(cookie)
relay.write_u16(channel)
sender = names.name_for(bs_target, context.user).encode('latin-1', errors = 'replace')
relay.write_u8(len(sender))
relay.write_bytes(sender)
relay.write_bytes(rest)
bs_target.evt.oscar_on_icbm(relay)
@Subgroup(0x0010)
def offline_retrieve(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] ICBM__OFFLINE_RETRIEVE')
# ICBM__OFFLINE_RETRIEVE_REPLY ends the batch; it has no body
deliver_stored_messages(client.ctrl, then = lambda: client.send_snac(SNACMessage(0x0004, 0x0017, 0x0000, message.request_id)))
@Subgroup(0x0014)
def client_event(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
cookie = message.read_bytes(8)
channel = message.read_u16()
receiver = message.read_string_u8()
receiver = message.read_bytes(message.read_u8()).decode('latin-1')
event = message.read_u16()
self.logger.info('[Client] ICBM__CLIENT_EVENT')
@@ -129,10 +257,11 @@ class ICBMFoodgroup:
self.logger.info('[Client] Unsupported channel:', hex(channel))
return
receiver_uuid = context.backend.util_get_uuid_from_username(receiver)
if receiver_uuid is None:
receiver_user = names.resolve_user(context.backend, receiver)
if receiver_user is None:
self.logger.info('[Client] Unknown receiver:', receiver)
return
receiver_uuid = receiver_user.uuid
# map OSCAR events to respective MessageTypes
if event == ICBMEvent.Typing:
@@ -143,22 +272,328 @@ class ICBMFoodgroup:
self.logger.info('[Client] Unknown event type:', hex(event))
return
try:
cs, evt = client.ctrl._get_private_chat_with(receiver_uuid)
except Exception as ex:
self.logger.info('[Client] Could not get private chat:', str(ex))
# a typing notification only goes to a conversation that's already there
existing = context.bs.front_data.get('oscar0_chats', {}).get(receiver_uuid)
if existing is None:
return
cs, evt = existing
md = MessageData(sender=context.user, type=msg_type, text='')
md.front_cache['icbm_cookie'] = cookie
md.front_cache['icbm_event'] = event
if evt._user_in_chat(receiver_uuid):
cs.send_message_to_user(receiver_uuid, md)
class _Send:
# one ICBM__CHANNEL_MSG_TOHOST on its way: where it goes, and how the sender hears back about it
__slots__ = ('client', 'context', 'message', 'cookie', 'channel', 'receiver', 'tlvs', 'target')
def __init__(
self, client: OSCARClient, context: OSCARContext, message: SNACMessage, cookie: bytes, channel: int, receiver: str,
tlvs: List[TLV],
) -> None:
self.client = client
self.context = context
self.message = message
self.cookie = cookie
self.channel = channel
self.receiver = receiver
self.tlvs = tlvs
self.target: Optional[User] = None
def error(self, code: int) -> None:
self.client.ctrl.send_snac_error(0x0004, self.message.request_id, code)
def ack(self) -> None:
# ICBM__HOST_ACK only goes back when the client asked for one (TLV 0x03)
if find_tlv(self.tlvs, ICBMTag.RequestHostAck) is None:
return
ack = SNACMessage(0x0004, 0x000C)
ack.request_id = self.message.request_id
ack.write_bytes(self.cookie)
ack.write_u16(self.channel)
receiver = self.receiver.encode('latin-1', errors = 'replace')
ack.write_u8(len(receiver))
ack.write_bytes(receiver)
self.client.ctrl.logger.info('[Server] ICBM__HOST_ACK')
self.client.send_snac(ack)
def text(self, plain: str, html: str, *, icq: Optional[Tuple[int, int, str]] = None) -> None:
# an IM, the one kind of message every frontend understands, goes through the chat machinery like theirs do
ctrl = self.client.ctrl
context = self.context
target = self.target
assert target is not None
auto = find_tlv(self.tlvs, ICBMTag.AutoResponse) is not None
md = MessageData(sender=context.user, type=MessageType.Chat, text=plain)
md.front_cache['icbm_cookie'] = self.cookie
md.front_cache['icbm_html'] = html
if auto:
md.front_cache['icbm_auto'] = True
md.front_cache['away_response'] = True
if icq is not None:
md.front_cache['icbm_icq'] = icq
try:
cs, evt = ctrl._get_private_chat_with(target.uuid)
except (error.ContactNotOnline, error.ContactNotOnContactList):
# TLV 0x06 asks for the message to be stored if it can't be delivered; an auto response never is
if find_tlv(self.tlvs, ICBMTag.Store) is not None and not auto:
self._store(plain)
return
self.error(ICBMError.NotLoggedOn)
return
except Exception as ex:
ctrl.logger.info('[Client] Could not create private chat:', str(ex))
self.error(ICBMError.NotLoggedOn)
return
# the core counts the message for warnings and checks the sender's rate, every frontend the same
if not context.backend.util_message_allowed(context.user, md):
self.error(ICBMError.RateToHost)
return
evt._send_when_user_joins(target.uuid, md)
self.ack()
def _store(self, plain: str) -> None:
context = self.context
target = self.target
assert target is not None
try:
ip = self.client.get_ip()
except Exception:
ip = ''
context.backend.user_service.save_oim(
context.bs, target.uuid, gen_uuid(), ip, plain, True, from_friendly = context.user.status.name,
)
self.ack()
def rendezvous(self) -> None:
# channel 2 (file transfers, direct IM, chat invitations, ICQ's advanced messages) only means something to
# another OSCAR client, so it goes straight to the receiver's OSCAR sessions
context = self.context
target = self.target
assert target is not None
sessions = oscar_sessions(context.backend, target)
if not sessions:
online = bool(context.backend.util_get_sessions_by_user(target))
self.error(ICBMError.NotSupportedByClient if online else ICBMError.NotLoggedOn)
return
tlvs = []
for tlv in self.tlvs:
# the ack request and store flag are for the server, and only the server may stamp a send time
if tlv.type in (ICBMTag.RequestHostAck, ICBMTag.Store, ICBMTag.SendTime):
continue
if tlv.type == ICBMTag.Data:
tlv = TLV(tlv.type, add_external_ip(tlv.data, self.client))
tlvs.append(tlv)
relay_icbm(context.backend, context.user, target, self.cookie, self.channel, marshal_tlvs(tlvs), sessions = sessions)
self.ack()
def icq(self, uin: int, msg_type: int, flags: int, text: str) -> None:
# channel 4: ICQ's own messages (text, URLs, contacts, authorization requests and answers...)
context = self.context
target = self.target
assert target is not None
kind = msg_type & 0xFF
if kind in (ICQMessageType.AuthRequest, ICQMessageType.AuthDeny, ICQMessageType.AuthGrant, ICQMessageType.Added):
from .feedbag import auth_event_from_icq_message
auth_event_from_icq_message(context.backend, context.user, target, kind, text)
self.ack()
return
plain = icq_message_text(kind, text)
if plain is not None:
self.text(plain, plain_to_html(plain), icq = (msg_type, flags, text))
return
# anything else (file and chat requests, plugins) only an ICQ client can make sense of: one on OSCAR gets the ICBM,
# a pre-OSCAR one the message
sessions = [bs for bs in oscar_sessions(context.backend, target) if names.is_icq_session(bs)]
legacy = [
bs for bs in context.backend.util_get_sessions_by_user(target) if hasattr(bs.evt, 'icq_on_message') and not bs.closed
]
if not sessions and not legacy:
self.error(ICBMError.NotSupportedByClient if context.backend.util_get_sessions_by_user(target) else ICBMError.NotLoggedOn)
return
for bs in legacy:
bs.evt.icq_on_message(context.user, msg_type, text)
if sessions:
tlvs = [tlv for tlv in self.tlvs if tlv.type not in (ICBMTag.RequestHostAck, ICBMTag.Store, ICBMTag.SendTime)]
relay_icbm(context.backend, context.user, target, self.cookie, self.channel, marshal_tlvs(tlvs), sessions = sessions)
self.ack()
def _blocks(backend: Any, blocker: User, blockee: User) -> bool:
# `_is_blocking` needs the blocker's contact list loaded; someone offline can still have an explicit block on file
if blocker.detail is not None:
return _is_blocking(blocker, blockee)
detail = backend._load_detail(blocker)
ctc = detail.contacts.get(blockee.uuid) if detail is not None else None
return ctc is not None and bool(ctc.lists & 0x04)
def strip_html_tags(text: str) -> str:
return unescape(re.compile(r'<[^>]+>').sub('', text))
def messagedata_to_icbm(cookie: bytes, data: MessageData, user: User) -> SNACMessage:
_BR_RE = re.compile(r'<br\s*/?>', re.IGNORECASE)
def html_to_plain(text: str) -> str:
# line breaks survive, the rest of the markup doesn't
return strip_html_tags(_BR_RE.sub('\n', text))
def plain_to_html(text: str) -> str:
# AIM renders whatever it gets as HTML, so text from anywhere else has to be escaped for it
return escape(text, quote = False).replace('\r\n', '\n').replace('\n', '<BR>')
def looks_like_html(text: str) -> bool:
return text[:6].lower() == '<html>' or text[:5].lower() == '<html'
def supports_unicode(bs: Any) -> bool:
# UCS-2 text for clients that say they take it, and AIM 5 and up, which all do; everyone else gets Windows-1252
if bs is None:
return False
if UNICODE_CAPABILITY in (bs.front_data.get('oscar0_caps') or ()):
return True
if names.is_icq_session(bs):
return False
try:
return int(bs.client.version.split('.')[0]) >= 5
except (ValueError, IndexError):
return False
def decode_im_text(charset: int, raw: bytes) -> str:
if charset == ICBMCharset.Unicode:
return raw.decode('utf-16-be', errors = 'replace')
# "ASCII" from a Windows client is whatever its codepage was, which in practice is Windows-1252
return from_latin1(raw)
def encode_im_text(text: str, unicode_ok: bool) -> Tuple[int, bytes]:
if all(ord(c) < 0x80 for c in text):
return ICBMCharset.Ascii, text.encode('ascii')
if unicode_ok:
return ICBMCharset.Unicode, text.encode('utf-16-be', errors = 'replace')
if all(ord(c) < 0x100 for c in text):
return ICBMCharset.Latin1, text.encode('latin-1')
return ICBMCharset.Ascii, latin1(text)
def parse_im_text(data: bytes) -> Optional[str]:
# TLV 0x02 holds message fragments: u8 id, u8 version, u16 length, data. id 5 lists capabilities, id 1 is text
# (u16 charset, u16 language, then the text), and a message can be split over several text fragments
parts = []
found = False
while len(data) >= 4:
frag_id, _, length = struct.unpack('>BBH', data[:4])
payload = data[4:4 + length]
data = data[4 + length:]
if frag_id != 0x01 or len(payload) < 4:
continue
found = True
charset, _ = struct.unpack('>HH', payload[:4])
parts.append(decode_im_text(charset, payload[4:]))
return ''.join(parts) if found else None
def build_im_data(text: str, unicode_ok: bool) -> bytes:
# the fragment list for TLV 0x02: capabilities (text, plus Unicode when it's used), then the text
charset, encoded = encode_im_text(text, unicode_ok)
caps = b'\x01\x06' if charset == ICBMCharset.Unicode else b'\x01\x01\x02'
# (the capability bytes are the ones AIM 5 sends, with Unicode's when the text needs it; the encoding is ASCII, Latin-1
# or UCS-2 by what the text holds and what the client takes)
return b''.join([
struct.pack('>BBH', 0x05, 0x01, len(caps)), caps, # capabilities: plain text (1 byte)
struct.pack('>BBH', 0x01, 0x01, len(encoded) + 4), struct.pack('>HH', charset, 0x0000), encoded, # encoding=ASCII, language=0, text
])
def parse_icq_message(data: bytes) -> Optional[Tuple[int, int, int, str]]:
# a channel 4 message is little endian: u32 sender UIN, u8 type, u8 flags, u16 length, null-terminated text
if len(data) < 8:
return None
uin, msg_type, flags, length = struct.unpack('<LBBH', data[:8])
raw = data[8:8 + length]
if b'\x00' in raw:
raw = raw[:raw.index(b'\x00')]
return uin, msg_type, flags, from_latin1(raw)
def build_icq_message(uin: int, msg_type: int, flags: int, text: str) -> bytes:
raw = latin1(text) + b'\x00'
return struct.pack('<LBBH', uin, msg_type, flags, len(raw)) + raw
def icq_message_text(kind: int, text: str) -> Optional[str]:
# the ICQ message types that come down to text anyone can read (fields are split by 0xFE)
fields = text.split('\xfe')
if kind == ICQMessageType.Plain:
return text
if kind == ICQMessageType.Url:
# description, then the URL
description = fields[0] if fields else ''
url = fields[1] if len(fields) > 1 else ''
return '{}\r\n{}'.format(description, url).strip()
if kind in (ICQMessageType.WebPager, ICQMessageType.EmailExpress):
# nick, (empty), (empty), e-mail, (empty), text
return fields[-1] if fields else text
if kind == ICQMessageType.Contacts:
# count, then UIN and nick for each contact
entries = fields[1:]
pairs = ['{} ({})'.format(entries[i], entries[i + 1]) for i in range(0, len(entries) - 1, 2) if entries[i]]
return 'Contacts: ' + ', '.join(pairs) if pairs else None
return None
def add_external_ip(data: bytes, client: OSCARClient) -> bytes:
# a rendezvous proposal (u16 type 0, 8 byte cookie, 16 byte capability, TLVs) gets the address the server sees it
# coming from in place of whatever LAN address the client put in, plus the verified-IP TLV peers check it against
if len(data) < 26 or struct.unpack('>H', data[:2])[0] != 0x0000:
return data
tlvs = unmarshal_tlvs(data[26:])
if find_tlv(tlvs, 0x0003) is None:
return data
try:
address = ipaddress.ip_address(client.get_ip())
except Exception:
return data
if not isinstance(address, ipaddress.IPv4Address):
ipv4 = getattr(address, 'ipv4_mapped', None)
if ipv4 is None:
return data
address = ipv4
packed = address.packed
tlvs = [TLV(0x0003, packed) if tlv.type == 0x0003 else tlv for tlv in tlvs]
tlvs.append(TLV(0x0004, packed))
return data[:26] + marshal_tlvs(tlvs)
def sender_userinfo(backend: Any, sender: User, viewer: Any) -> bytes:
return build_userinfo(
sender, pick_session(backend, sender), name = names.name_for(viewer, sender), viewer_icq = names.is_icq_session(viewer),
)
def build_icbm_to_client(backend: Any, sender: User, viewer: Any, cookie: bytes, channel: int, tlvs: bytes) -> SNACMessage:
# ICBM__CHANNEL_MSG_TOCLIENT: cookie, u16 channel, the sender's USERINFO (as this viewer knows them), TLVs
msg = SNACMessage(0x0004, 0x0007)
msg.write_bytes(cookie)
msg.write_u16(channel)
msg.write_bytes(sender_userinfo(backend, sender, viewer))
msg.write_bytes(tlvs)
return msg
def relay_icbm(
backend: Any, sender: User, target: User, cookie: bytes, channel: int, tlvs: bytes, *, sessions: Optional[List[Any]] = None,
) -> None:
for bs_target in (sessions if sessions is not None else oscar_sessions(backend, target)):
bs_target.evt.oscar_on_icbm(build_icbm_to_client(backend, sender, bs_target, cookie, channel, tlvs))
def send_icq_system_message(ctrl: Any, sender: User, kind: int, text: str) -> None:
# a channel 4 message as if from `sender` (how a client without a feedbag hears about authorization and adds)
uin = names.uin_of(sender) or 0
tlvs = marshal_tlvs([TLV(ICBMTag.Data, build_icq_message(uin, kind, 0x00, text))])
ctrl.send_snac(build_icbm_to_client(ctrl.backend, sender, ctrl.bs, gen_cookie(), ICBMChannel.ICQ, tlvs))
def gen_cookie() -> bytes:
# ICBM cookies are opaque 8 byte message ids; clients drop a message whose cookie they've just seen
return os.urandom(8)
def messagedata_to_icbm(cookie: bytes, data: MessageData, viewer: Any) -> SNACMessage:
# cookie - 8 bytes, chat sess cookie
# channel - u16, 0x0001 for plain text IM
# sender - string08 (u8 length prefix), sender's screen name
@@ -172,47 +607,129 @@ def messagedata_to_icbm(cookie: bytes, data: MessageData, user: User) -> SNACMes
# TLV(0x0501) capabilities (1 byte = 0x01 for plain text)
# TLV(0x0101) text: u16 encoding + u16 language + bytes
sender = data.sender
text = data.front_cache.get('icbm_html', data.text or '')
backend = viewer.backend
viewer_icq = names.is_icq_session(viewer)
date_created_unix = int(time.mktime(sender.date_created.timetuple()))
date_login_unix = int(time.mktime(sender.date_login.timetuple())) if sender.date_login else 0
# an ICQ client gets ICQ messages (URLs, contacts...) back as channel 4, from someone it knows by UIN
icq = data.front_cache.get('icbm_icq')
if viewer_icq and icq is not None and names.uin_of(sender) is not None:
msg_type, flags, text = icq
tlvs = marshal_tlvs([TLV(ICBMTag.Data, build_icq_message(names.uin_of(sender), msg_type, flags, text))])
return build_icbm_to_client(backend, sender, viewer, cookie, ICBMChannel.ICQ, tlvs)
# ICQ shows text as it is, AIM renders HTML
if viewer_icq:
text = (data.text or '').replace('\r\n', '\n').replace('\n', '\r\n')
else:
text = data.front_cache.get('icbm_html') or plain_to_html(data.text or '')
msg = SNACMessage(0x0004, 0x0007)
msg.write_bytes(cookie)
msg.write_u16(ICBMChannel.AOLIM)
msg.write_string_u8(sender.username)
msg.write_u16(0) # warning level
# count-prefixed userinfo TLV block
# sender, warning level and the userinfo TLV block, all as one OSERVICE__USERINFO
# usually would include TLV(0x001D) (BART info), but we don't support that yet
msg.write_tlv_block([
TLV(0x0001, struct.pack('>H', 0x0008)), # user class
TLV(0x0003, struct.pack('>L', date_login_unix)), # account signon time
TLV(0x000F, struct.pack('>L', 0)), # session length
TLV(0x0005, struct.pack('>L', date_created_unix)), # account creation time
])
im_text = (text or '').encode('ascii', errors='replace')
msg.write_bytes(sender_userinfo(backend, sender, viewer))
# IM data: TLV(0x0002) wrapping nested capability + text TLVs
im_data = marshal_tlvs([
TLV(0x0501, b'\x01'), # capabilities: plain text (1 byte)
TLV(0x0101, struct.pack('>HH', 0, 0) + im_text), # encoding=ASCII, language=0, text
])
msg.write_tlv(TLV(0x0002, im_data))
tlvs = [TLV(ICBMTag.ImData, build_im_data(text, supports_unicode(viewer)))]
if data.front_cache.get('icbm_auto'):
tlvs.append(TLV(ICBMTag.AutoResponse))
if data.front_cache.get('icbm_sent') is not None:
tlvs.append(TLV(ICBMTag.SendTime, struct.pack('>L', int(data.front_cache['icbm_sent']))))
msg.write_tlvs(tlvs)
return msg
def messagedata_to_icbm_event(data: MessageData, receiver: User) -> SNACMessage:
def messagedata_to_icbm_event(data: MessageData, viewer: Any) -> SNACMessage:
if data.type is MessageType.Typing:
event = ICBMEvent.Typing
else:
event = ICBMEvent.Finished
event = data.front_cache.get('icbm_event', ICBMEvent.Finished)
msg = SNACMessage(0x0004, 0x0014)
msg.write_bytes(b'\x00' * 8)
msg.write_bytes(data.front_cache.get('icbm_cookie') or b'\x00' * 8)
msg.write_u16(ICBMChannel.AOLIM)
msg.write_string_u8(data.sender.username)
sender = names.name_for(viewer, data.sender).encode('latin-1', errors = 'replace')
msg.write_u8(len(sender))
msg.write_bytes(sender)
msg.write_u16(event)
return msg
return msg
def deliver_stored_messages(ctrl: Any, *, then: Optional[Callable[[], None]] = None) -> None:
# everything stored for the account; reading the store is file work, done off the event loop
ctrl.backend.loop.create_task(_deliver_stored_messages(ctrl, then))
async def _deliver_stored_messages(ctrl: Any, then: Optional[Callable[[], None]]) -> None:
bs = ctrl.bs
if bs is None:
return
oims = await ctrl.backend.loop.run_in_executor(None, ctrl.backend.user_service.get_oim_batch, bs.user)
if bs.closed:
return
deliver_offline_messages(ctrl, oims)
if then is not None:
then()
async def delete_stored_messages(backend: Any, recipient_uuid: str, uuids: List[str]) -> None:
for uuid in uuids:
await backend.loop.run_in_executor(None, backend.user_service.delete_oim, recipient_uuid, uuid)
def deliver_offline_messages(ctrl: Any, oims: List[OIM]) -> None:
# stored messages (from any frontend) go to an AIM client as IMs stamped with when they were sent (TLV 0x16)
bs = ctrl.bs
if bs is None:
return
backend = ctrl.backend
delivered = []
for oim in oims:
sender = None
if oim.from_username:
uuid = backend.util_get_uuid_from_username(oim.from_username)
sender = backend._load_user_record(uuid) if uuid is not None else None
if sender is None:
uuid = backend.util_get_uuid_from_email(oim.from_email)
sender = backend._load_user_record(uuid) if uuid is not None else None
if sender is not None:
md = MessageData(sender = sender, type = MessageType.Chat, text = oim.message or '')
md.front_cache['icbm_sent'] = int(oim.sent.timestamp())
ctrl.send_snac(messagedata_to_icbm(gen_cookie(), md, bs))
delivered.append(oim.uuid)
if delivered:
backend.loop.create_task(delete_stored_messages(backend, bs.user.uuid, delivered))
def _track_conversation(sender: User, recipient: User, backend: Any = None) -> None:
# (every message sent through a chat is counted by the core, `ChatSession.send_message_to_everyone`; this is for messages
# that don't go through one)
if backend is not None:
backend.abuse.track_message(sender, recipient)
def _may_warn(warner: User, warnee: User, backend: Any) -> bool:
# only someone who has messaged you can be warned, at most once for each message, three times an hour
return bool(backend.abuse.may_warn(warner, warnee))
def _warning_level(user: User) -> int:
return max(0, min(EVIL_MAX, int(user.evil_permanent or 0) + int(user.evil_temporary or 0)))
def _announce_warning(backend: Any, user: User) -> None:
# the warning level is in every USERINFO, so buddies get a fresh arrival and the user an update of their own
backend.abuse.announce(user, None)
def _start_decay(backend: Any, user: User) -> None:
backend.abuse._start_decay(user)
async def _decay_warnings(backend: Any) -> None:
await backend.abuse._decay_warnings()
def build_evil_notification(bs_target: Any, level: int, warner: Optional[User]) -> SNACMessage:
# OSERVICE__EVIL_NOTIFICATION: u16 new level, then who did it (unless it was anonymous)
notif = SNACMessage(0x0001, 0x0010)
notif.write_u16(level)
if warner is not None:
name = names.name_for(bs_target, warner).encode('latin-1', errors = 'replace')
notif.write_u8(len(name))
notif.write_bytes(name)
notif.write_u16(_warning_level(warner))
notif.write_u16(0)
return notif
+706
View File
@@ -0,0 +1,706 @@
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):
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):
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
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 (ICQ's "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,
}
+13
View File
@@ -0,0 +1,13 @@
from util.misc import Logger
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
@Foodgroup(0x0006)
class InviteFoodgroup:
logger: Logger
@Subgroup(0x0002)
def request_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# "invite a friend to AIM" (an e-mail address and a message); nothing is sent out
self.logger.info('[Client] INVITE__REQUEST_QUERY (not sent)')
+209 -9
View File
@@ -1,9 +1,116 @@
import struct
from html import escape
from typing import Any, Dict, List, Optional, Tuple
from core.models import Substatus, User
from util.misc import Logger
from ..proto import names
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import TLV
from ..proto.tlv import TLV, unmarshal_tlvs, find_tlv
from ..proto.userinfo import build_userinfo, pick_session, AWAY_SUBSTATUSES
LOCATE_TYPE_PROFILE = 0x0001
LOCATE_TYPE_AWAY = 0x0002
LOCATE_TYPE_CAPABILITIES = 0x0004
OMITTED_CAPS = frozenset(bytes.fromhex(cap.replace('-', '')) for cap in (
'0946134A-4C7F-11D1-8222-444553540000',
'0946134D-4C7F-11D1-8222-444553540000',
'09461341-4C7F-11D1-8222-444553540000',
))
AIM_DIR_KEY = 'AIM_DIR'
DIR_FIELDS = (0x0001, 0x0002, 0x0003, 0x0004, 0x0006, 0x0007, 0x0008, 0x000C, 0x000D, 0x0021)
DIR_INTEREST = 0x000B
MAX_INTERESTS = 5
DEFAULT_MIME = 'text/aolrtf; charset="us-ascii"'
def dir_info(user: User) -> Dict[str, Any]:
store = user.settings.get(AIM_DIR_KEY)
if not isinstance(store, dict):
store = {}
user.settings[AIM_DIR_KEY] = store
return store
def dir_tlvs(user: User) -> List[TLV]:
# what the directory shows for someone: what they set over OSCAR, else their account's own name and location
store = dir_info(user)
profile = user.profile
fallback = {
0x0001: user.first_name or '',
0x0002: user.last_name or '',
0x0006: (profile.country if profile is not None else None) or '',
0x0007: (profile.state if profile is not None else None) or '',
0x0008: (profile.city if profile is not None else None) or '',
0x000D: str(profile.zip) if profile is not None and profile.zip else '',
}
tlvs = []
for tag in DIR_FIELDS:
value = store.get(str(tag), fallback.get(tag, ''))
tlvs.append(TLV(tag, str(value).encode('latin-1', errors = 'replace')))
return tlvs
def profile_of(user: User, bs: Any) -> Tuple[str, str]:
# the profile an OSCAR client set this session, else the account's bio, else its status message
stored = bs.front_data.get('oscar0_profile') if bs is not None else None
if stored is not None:
return stored
bio = user.profile.bio if user.profile is not None else None
return DEFAULT_MIME, escape(bio or user.status.message or '', quote = False).replace('\n', '<BR>')
def away_message_of(user: User, bs: Any) -> Optional[Tuple[str, str]]:
if user.status.substatus not in AWAY_SUBSTATUSES:
return None
if bs is not None and bs.front_data.get('oscar0_away') is not None:
return bs.front_data.get('oscar0_away_mime') or DEFAULT_MIME, bs.front_data['oscar0_away']
return DEFAULT_MIME, escape(user.status.message or '', quote = False)
def user_info_reply(client: OSCARClient, context: OSCARContext, message: SNACMessage, query_type: int, name: str) -> None:
# LOCATE__USER_INFO_REPLY: the USERINFO, then the profile/away message/capabilities TLVs that were asked for
backend = context.backend
viewer = context.bs
target = names.resolve_user(backend, name)
if target is None:
client.ctrl.send_snac_error(0x0002, message.request_id, 0x0004)
return
if target is not viewer.user:
from .icbm import _blocks
if _blocks(backend, target, viewer.user) or _blocks(backend, viewer.user, target):
client.ctrl.send_snac_error(0x0002, message.request_id, 0x0004)
return
if not backend.util_get_sessions_by_user(target) or target.status.is_offlineish():
client.ctrl.send_snac_error(0x0002, message.request_id, 0x0004)
return
bs_target = viewer if target is viewer.user else pick_session(backend, target)
reply = SNACMessage(0x0002, 0x0006, 0x0000, message.request_id)
reply.write_bytes(build_userinfo(
target, bs_target, name = names.name_for(viewer, target), viewer_icq = names.is_icq_session(viewer),
))
tlvs = []
if query_type & LOCATE_TYPE_PROFILE:
mime, text = profile_of(target, bs_target)
tlvs.append(TLV(0x0001, mime))
tlvs.append(TLV(0x0002, text))
if query_type & LOCATE_TYPE_AWAY:
away = away_message_of(target, bs_target)
if away is not None:
tlvs.append(TLV(0x0003, away[0]))
tlvs.append(TLV(0x0004, away[1]))
if query_type & LOCATE_TYPE_CAPABILITIES:
caps = bs_target.front_data.get('oscar0_caps') if bs_target is not None else None
if caps:
tlvs.append(TLV(0x0005, b''.join(caps)))
reply.write_tlvs(tlvs)
client.send_snac(reply)
@Foodgroup(0x0002)
class LocateFoodgroup:
@@ -13,7 +120,7 @@ class LocateFoodgroup:
def client_versions(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] LOCATE__RIGHTS_QUERY')
response_msg = SNACMessage(0x0002, 0x0003)
response_msg = SNACMessage(0x0002, 0x0003, 0x0000, message.request_id)
# Response from NINA's servers:
# ==
@@ -43,14 +150,89 @@ class LocateFoodgroup:
@Subgroup(0x0004)
def set_info(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] LOCATE__SET_INFO (not implemented)')
self.logger.info('[Client]', message.data.hex())
self.logger.info('[Client] LOCATE__SET_INFO')
bs = context.bs
tlvs = unmarshal_tlvs(message.data)
profile_tlv = find_tlv(tlvs, 0x0002) # user profile (HTML)
away_tlv = find_tlv(tlvs, 0x0004) # away message (HTML), present while away
caps_tlv = find_tlv(tlvs, 0x0005) # capability block, 16 bytes per capability
profile_mime_tlv = find_tlv(tlvs, 0x0001)
away_mime_tlv = find_tlv(tlvs, 0x0003)
ready = bool(bs.front_data.get('oscar0_ready'))
fields = {}
if profile_tlv is not None:
fields['message'] = profile_tlv.data.decode('utf-8', 'replace')
mime = profile_mime_tlv.data.decode('latin-1') if profile_mime_tlv is not None else DEFAULT_MIME
bs.front_data['oscar0_profile'] = (mime, fields['message'])
# a tag with no data clears the thing it sets, a tag that isn't there changes nothing
if caps_tlv is not None:
caps = [
caps_tlv.data[i:i + 16] for i in range(0, len(caps_tlv.data) - 15, 16)
]
caps = [cap for cap in caps if cap not in OMITTED_CAPS]
if caps != bs.front_data.get('oscar0_caps') and ready:
fields['needs_notify'] = True
fields['notify_status'] = True
bs.front_data['oscar0_caps'] = caps
if away_tlv is not None:
if away_tlv.data:
bs.front_data['oscar0_away'] = away_tlv.data.decode('utf-8', 'replace')
bs.front_data['oscar0_away_mime'] = away_mime_tlv.data.decode('latin-1') if away_mime_tlv is not None else DEFAULT_MIME
fields['substatus'] = Substatus.Away
else:
bs.front_data.pop('oscar0_away', None)
if context.user.status.substatus is Substatus.Away:
fields['substatus'] = Substatus.Online
# before OSERVICE__CLIENT_READY the client is only saying how it wants to come online
if not ready:
fields.pop('substatus', None)
if fields:
bs.me_update(fields)
@Subgroup(0x0005)
def user_info_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# u16 type (LOCATE_TYPE_*), string08 who
query_type = message.read_u16()
name = message.read_bytes(message.read_u8()).decode('latin-1')
self.logger.info('[Client] LOCATE__USER_INFO_QUERY for', name, '(type', hex(query_type) + ')')
user_info_reply(client, context, message, query_type, name)
@Subgroup(0x0015)
def user_info_query2(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# the same query with a u32 type
query_type = message.read_u32()
name = message.read_bytes(message.read_u8()).decode('latin-1')
self.logger.info('[Client] LOCATE__USER_INFO_QUERY2 for', name, '(type', hex(query_type) + ')')
user_info_reply(client, context, message, query_type & 0xFFFF, name)
@Subgroup(0x0009)
def set_dir_info(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] LOCATE__SET_DIR_INFO')
# a TLV per ODIR field; whatever is sent replaces what was there
store = dir_info(context.user)
for tlv in unmarshal_tlvs(message.data):
if tlv.type in DIR_FIELDS:
store[str(tlv.type)] = tlv.data.decode('latin-1')
context.backend._mark_modified(context.user)
# LOCATE__SET_DIR_REPLY: u16 result, 1 for success
reply = SNACMessage(0x0002, 0x000A, 0x0000, message.request_id)
reply.write_u16(0x0001)
self.logger.info('[Server] LOCATE__SET_DIR_REPLY')
client.send_snac(reply)
@Subgroup(0x000B)
def get_dir_info(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] LOCATE__GET_DIR_INFO')
screen_name = message.read_string_u8()
screen_name = message.read_bytes(message.read_u8()).decode('latin-1')
self.logger.info('[Client] Getting info for:', screen_name)
# Response from NINA's servers:
@@ -62,11 +244,29 @@ class LocateFoodgroup:
#
# I have no idea what any of the values in the SNAC body mean, and the lack of documentation on NINA's wiki
# don't help either: https://ninawiki.preloading.dev/wiki/Protocols/OSCAR/SNAC/LOCATE_GET_DIR_REPLY
response_msg = SNACMessage(0x0002, 0x000C)
# (it's u16 status 1 (found), then a counted TLV block of ODIR fields; TLV 0x1C is the region/charset)
response_msg = SNACMessage(0x0002, 0x000C, 0x0000, message.request_id)
target = names.resolve_user(context.backend, screen_name)
response_msg.write_u16(0x0001)
response_msg.write_u16(0x0001)
response_msg.write_u16(0x001C)
response_msg.write_string_u16('us-ascii')
tlvs = [TLV(0x001C, 'us-ascii')]
if target is not None:
tlvs = dir_tlvs(target) + tlvs
response_msg.write_tlv_block(tlvs)
self.logger.info('[Server] LOCATE__GET_DIR_REPLY')
client.send_snac(response_msg)
@Subgroup(0x000F)
def set_keyword_info(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] LOCATE__SET_KEYWORD_INFO')
# up to five interests, TLV 0x0B each
interests = [tlv.data.decode('latin-1') for tlv in unmarshal_tlvs(message.data) if tlv.type == DIR_INTEREST]
dir_info(context.user)['interests'] = interests[:MAX_INTERESTS]
context.backend._mark_modified(context.user)
# LOCATE__SET_KEYWORD_REPLY: u16, 1
reply = SNACMessage(0x0002, 0x0010, 0x0000, message.request_id)
reply.write_u16(0x0001)
self.logger.info('[Server] LOCATE__SET_KEYWORD_REPLY')
client.send_snac(reply)
+233 -92
View File
@@ -1,15 +1,105 @@
import os
import calendar
import struct
import time
import settings
from datetime import datetime, timezone
from util.misc import Logger
from core.models import ContactList, Substatus
from util.misc import Logger, is_valid_oscar_screenname
from ..proto.backend import FOODGROUP_VERSIONS, bos_cookies
from ..proto import names
from ..proto.backend import FOODGROUP_VERSIONS, SERVICE_FOODGROUPS, ServiceCookie, issue_cookie, bos_cookies
from ..proto.buffer import Buffer
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import TLV, unmarshal_tlvs
from ..proto.tlv import TLV, unmarshal_tlvs, find_tlv
from ..proto.userinfo import build_userinfo, substatus_from_icq_status, ICQ_DC_INFO_EMPTY
from .buddy import build_presence_notif, push_buddy_list
RATE_CLASSES = (
(1, 80, 2500, 2000, 1500, 800, 6000),
(2, 80, 3000, 2000, 1500, 1000, 6000),
(3, 20, 5100, 5000, 4000, 3000, 6000),
(4, 20, 5500, 5300, 4200, 3000, 8000),
(5, 10, 5500, 5300, 4200, 3000, 8000),
)
RATE_GROUPS = {
0x0001: (0x0023, {}),
0x0002: (0x0015, {0x0005: 3, 0x0009: 4, 0x000B: 4}),
0x0003: (0x0010, {0x0004: 2, 0x0005: 2}),
0x0004: (0x0014, {0x0006: 3}),
0x0005: (0x0003, {}),
0x0006: (0x0003, {}),
0x0007: (0x0009, {}),
0x0008: (0x0002, {}),
0x0009: (0x000B, {0x0005: 2, 0x0006: 2, 0x0007: 2, 0x0008: 2}),
0x000A: (0x0003, {}),
0x000B: (0x0004, {}),
0x000C: (0x0003, {}),
0x000D: (0x0009, {}),
0x000E: (0x0009, {0x0005: 2}),
0x000F: (0x0004, {}),
0x0010: (0x0006, {}),
0x0013: (0x0028, {}),
0x0015: (0x0003, {}),
0x0017: (0x000C, {}),
0x0018: (0x0017, {}),
}
RATE_GROUP_GAPS = {
0x0003: (0x000D, 0x000E),
0x0010: (0x0003, 0x0005),
0x0017: (0x0003, 0x0005, 0x0007, 0x0009, 0x000B),
0x0018: (0x0003, 0x0005, 0x0009, 0x000B, 0x000C, 0x0013, 0x0014),
}
MIN_STATS_REPORT_INTERVAL = 1200
REQUESTABLE_SERVICES = frozenset({0x0007, 0x000D, 0x000E, 0x000F, 0x0010, 0x0018})
def build_rate_params(oservice_version: int) -> bytes:
buf = Buffer()
buf.write_u16(len(RATE_CLASSES))
now = int(time.time())
for ident, window, clear, alert, limit, disconnect, max_level in RATE_CLASSES:
buf.write_u16(ident)
for value in (window, clear, alert, limit, disconnect, max_level, max_level):
buf.write_u32(value)
# OSERVICE v2 and up add when the last SNAC came in and whether SNACs are being dropped
if oservice_version > 1:
buf.write_u32(now - 1)
buf.write_u8(0)
for ident, *_ in RATE_CLASSES:
pairs = []
for foodgroup, (last, exceptions) in RATE_GROUPS.items():
gaps = RATE_GROUP_GAPS.get(foodgroup, ())
for subgroup in range(0x0001, last + 1):
if subgroup in gaps:
continue
if exceptions.get(subgroup, 1) == ident:
pairs.append((foodgroup, subgroup))
buf.write_u16(ident)
buf.write_u16(len(pairs))
for foodgroup, subgroup in pairs:
buf.write_u16(foodgroup)
buf.write_u16(subgroup)
return buf.data
def build_self_info(bs) -> SNACMessage:
# OSERVICE__USER_INFO_UPDATE, under the name the client signed on with
msg = SNACMessage(0x0001, 0x000F)
msg.write_bytes(build_userinfo(bs.user, bs, name = names.self_name(bs), viewer_icq = names.is_icq_session(bs)))
return msg
def initial_substatus(bs) -> Substatus:
# what a client asked for before it was ready: an ICQ status (SNAC(01,1E)), an away message (LOCATE__SET_INFO)
raw = bs.front_data.get('oscar0_icq_status')
if raw is not None:
return substatus_from_icq_status(raw)
if bs.front_data.get('oscar0_away'):
return Substatus.Away
return Substatus.Online
@Foodgroup(0x0001)
@@ -20,79 +110,84 @@ class OSERVICEFoodgroup:
def client_versions(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] OSERVICE__CLIENT_VERSIONS')
response_msg = SNACMessage(0x0001, 0x0018, 0x0000, 0x0000)
for foodgroup, version in FOODGROUP_VERSIONS.items():
versions = {}
while len(message) >= 4:
foodgroup = message.read_u16()
version = message.read_u16()
versions[foodgroup] = version
client.ctrl.versions = versions
response_msg = SNACMessage(0x0001, 0x0018, 0x0000, message.request_id)
for foodgroup, version in versions.items():
response_msg.write_u16(foodgroup)
response_msg.write_u16(version)
self.logger.info('[Server] OSERVICE__HOST_VERSIONS')
client.send_snac(response_msg)
if getattr(settings, 'OSCAR_MOTD_ENABLED', False):
# OSERVICE__MOTD: u16 message type (4: the message of the day), then TLV 0x0B with its text
motd = SNACMessage(0x0001, 0x0013)
motd.write_u16(0x0004)
motd.write_tlv(TLV(0x000B, getattr(settings, 'OSCAR_MOTD_TEXT', 'Welcome to CrossTalk!')))
self.logger.info('[Server] OSERVICE__MOTD')
client.send_snac(motd)
@Subgroup(0x0002)
def client_ready(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] OSERVICE__CLIENT_READY')
ctrl = client.ctrl
if ctrl.is_service:
# a chat room connection is where the room is joined; the other services have nothing more to do
if ctrl.service == 0x000E:
from .chat import join_room
join_room(ctrl)
return
bs = context.bs
if bs.front_data.get('oscar0_ready'):
return
bs.front_data['oscar0_ready'] = True
detail = context.backend._load_detail(context.user)
if detail is None:
return
# the client is signed on now: going online is what tells everyone with it on their list
bs.me_update({ 'substatus': initial_substatus(bs) })
# cached statuses can lag behind, so recompute before deciding who is online
push_buddy_list(bs)
# This SNAC as seen from NINA's servers:
# ==
# 0000 2a 02 00 0e 00 0e 00 0b 00 02 00 00 e7 19 67 3c *.............g
# [FLAP Header....] [SNAC Header................]
# 0010 00 01 00 00 ....
# ^^^^^^^^^^^
msg = SNACMessage(0x000B, 0x0002)
msg.write_u16(MIN_STATS_REPORT_INTERVAL)
self.logger.info('[Server] STATS__SET_MIN_REPORT_INTERVAL')
client.send_snac(msg)
# authorization requests and answers that came in while this account wasn't on ICQ
from .feedbag import deliver_queued_auth_events
deliver_queued_auth_events(client.ctrl)
# AIM before 6.0 never asks for its offline IMs (ICBM__OFFLINE_RETRIEVE), so they're handed over now; ICQ asks
# through its own foodgroup once it's ready for them
if not names.is_icq_session(bs):
from .icbm import deliver_stored_messages
deliver_stored_messages(client.ctrl)
@Subgroup(0x0006)
def rate_params_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] OSERVICE__RATE_PARAMS_QUERY')
hex = """
00 05 00 01 00 00 00 50 00 00 09 C4 00 00 07 D0
00 00 05 DC 00 00 03 20 00 00 0D 69 00 00 17 70
00 00 00 00 00 00 02 00 00 00 50 00 00 0B B8 00
00 07 D0 00 00 05 DC 00 00 03 E8 00 00 17 70 00
00 17 70 00 00 F9 0B 00 00 03 00 00 00 14 00 00
13 EC 00 00 13 88 00 00 0F A0 00 00 0B B8 00 00
11 47 00 00 17 70 00 00 5C D8 00 00 04 00 00 00
14 00 00 15 7C 00 00 14 B4 00 00 10 68 00 00 0B
B8 00 00 17 70 00 00 1F 40 00 00 F9 0B 00 00 05
00 00 00 0A 00 00 15 7C 00 00 14 B4 00 00 10 68
00 00 0B B8 00 00 17 70 00 00 1F 40 00 00 F9 0B
00 00 01 00 91 00 01 00 01 00 01 00 02 00 01 00
03 00 01 00 04 00 01 00 05 00 01 00 06 00 01 00
07 00 01 00 08 00 01 00 09 00 01 00 0A 00 01 00
0B 00 01 00 0C 00 01 00 0D 00 01 00 0E 00 01 00
0F 00 01 00 10 00 01 00 11 00 01 00 12 00 01 00
13 00 01 00 14 00 01 00 15 00 01 00 16 00 01 00
17 00 01 00 18 00 01 00 19 00 01 00 1A 00 01 00
1B 00 01 00 1C 00 01 00 1D 00 01 00 1E 00 01 00
1F 00 01 00 20 00 01 00 21 00 02 00 01 00 02 00
02 00 02 00 03 00 02 00 04 00 02 00 06 00 02 00
07 00 02 00 08 00 02 00 0A 00 02 00 0C 00 02 00
0D 00 02 00 0E 00 02 00 0F 00 02 00 10 00 02 00
11 00 02 00 12 00 02 00 13 00 02 00 14 00 02 00
15 00 03 00 01 00 03 00 02 00 03 00 03 00 03 00
06 00 03 00 07 00 03 00 08 00 03 00 09 00 03 00
0A 00 03 00 0B 00 03 00 0C 00 04 00 01 00 04 00
02 00 04 00 03 00 04 00 04 00 04 00 05 00 04 00
07 00 04 00 08 00 04 00 09 00 04 00 0A 00 04 00
0B 00 04 00 0C 00 04 00 0D 00 04 00 0E 00 04 00
0F 00 04 00 10 00 04 00 11 00 04 00 12 00 04 00
13 00 04 00 14 00 06 00 01 00 06 00 02 00 06 00
03 00 08 00 01 00 08 00 02 00 09 00 01 00 09 00
02 00 09 00 03 00 09 00 04 00 09 00 09 00 09 00
0A 00 09 00 0B 00 0A 00 01 00 0A 00 02 00 0A 00
03 00 0B 00 01 00 0B 00 02 00 0B 00 03 00 0B 00
04 00 0C 00 01 00 0C 00 02 00 0C 00 03 00 13 00
01 00 13 00 02 00 13 00 03 00 13 00 04 00 13 00
05 00 13 00 06 00 13 00 07 00 13 00 08 00 13 00
09 00 13 00 0A 00 13 00 0B 00 13 00 0C 00 13 00
0D 00 13 00 0E 00 13 00 0F 00 13 00 10 00 13 00
11 00 13 00 12 00 13 00 13 00 13 00 14 00 13 00
15 00 13 00 16 00 13 00 17 00 13 00 18 00 13 00
19 00 13 00 1A 00 13 00 1B 00 13 00 1C 00 13 00
1D 00 13 00 1E 00 13 00 1F 00 13 00 20 00 13 00
21 00 13 00 22 00 13 00 23 00 13 00 24 00 13 00
25 00 13 00 26 00 13 00 27 00 13 00 28 00 15 00
01 00 15 00 02 00 15 00 03 00 02 00 06 00 03 00
04 00 03 00 05 00 09 00 05 00 09 00 06 00 09 00
07 00 09 00 08 00 03 00 02 00 02 00 05 00 04 00
06 00 04 00 02 00 02 00 09 00 02 00 0B 00 05 00
00
"""
cleaned_hex = (hex
.strip()
.replace(" ", "")
.replace("\r\n", "\n")
.replace("\n", ""))
response_msg = SNACMessage(0x0001, 0x0007, 0x0000, 0x0000, bytes.fromhex(cleaned_hex))
oservice_version = getattr(client.ctrl, 'versions', {}).get(0x0001, 1)
response_msg = SNACMessage(0x0001, 0x0007, 0x0000, message.request_id, build_rate_params(oservice_version))
self.logger.info('[Server] OSERVICE__RATE_PARAMS_REPLY')
client.send_snac(response_msg)
@@ -107,10 +202,6 @@ class OSERVICEFoodgroup:
def user_info_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] OSERVICE__USER_INFO_QUERY')
response_msg = SNACMessage(0x0001, 0x000F)
response_msg.write_string_u8(context.bs.user.username) # Screen name
response_msg.write_u16(0) # Warning level
date_created = context.bs.user.date_created
date_login = context.bs.user.date_login
now = datetime.now(tz=timezone.utc)
@@ -129,12 +220,9 @@ class OSERVICEFoodgroup:
self.logger.info('Client IP:', client.get_ip())
response_msg.write_tlv_block([
TLV(0x0001, struct.pack('>L', 0x0100)), # User class (bitfield)
TLV(0x0003, struct.pack('>L', date_login_unix)), # Account signon time (unix time_t)
TLV(0x0005, struct.pack('>L', date_created_unix)), # Accout creation time (unix time_t)
TLV(0x000F, struct.pack('>L', session_len)) # Session length
])
# OSERVICE__USERINFO: displayId, warning level, then the OSERVICE__USER_INFO_TAGS block
response_msg = build_self_info(context.bs)
response_msg.request_id = message.request_id
self.logger.info('[Server] OSERVICE__USER_INFO_UPDATE')
client.send_snac(response_msg)
@@ -154,40 +242,93 @@ class OSERVICEFoodgroup:
idle_time = message.read_u32()
if idle_time == 0:
self.logger.info(context.bs.user.username, 'is no longer idle')
context.bs.front_data.pop('oscar0_idle_since', None)
else:
self.logger.info(context.bs.user.username, 'has been idle for', str(idle_time), 'seconds')
context.bs.front_data['oscar0_idle_since'] = time.time() - idle_time
# This SNAC as seen from NINA's servers:
# ==
# 0000 2a 02 00 0e 00 0e 00 0b 00 02 00 00 e7 19 67 3c *.............g<
# [FLAP Header....] [SNAC Header................]
# 0010 00 01 00 00 ....
# ^^^^^^^^^^^
msg = SNACMessage(0x000B, 0x0002)
msg.write_u32(0x010000)
# contacts need a fresh arrival so the idle time in the userinfo gets refreshed on their end
context.bs.me_update({
'needs_notify': True,
'notify_status': True,
})
self.logger.info('[Server] STATS__SET_MIN_REPORT_INTERVAL')
client.send_snac(msg)
@Subgroup(0x0014)
def set_privacy_flags(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# u32 flags: 0x01 lets others see idle time, 0x02 the member since date; nothing here hides either yet
flags = message.read_u32() if len(message) >= 4 else 0
self.logger.info('[Client] OSERVICE__SET_PRIVACY_FLAGS', hex(flags))
@Subgroup(0x0016)
def noop(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# a keep-alive; there is no reply
self.logger.info('[Client] OSERVICE__NOOP')
@Subgroup(0x001E)
def set_user_info_fields(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] OSERVICE__SET_USERINFO_FIELDS')
bs = context.bs
tlvs = unmarshal_tlvs(message.data)
# TLV 0x0C: ICQ direct connection info, passed on in this user's arrivals so ICQ peers can connect directly
if (dc_tlv := find_tlv(tlvs, 0x000C)) is not None and len(dc_tlv.data) >= len(ICQ_DC_INFO_EMPTY):
bs.front_data['oscar0_icq_dc'] = dc_tlv.data[:len(ICQ_DC_INFO_EMPTY)]
# TLV 0x06: u32 status (the low word is the ICQ status, the high word flags like web aware)
if (status_tlv := find_tlv(tlvs, 0x0006)) is not None and len(status_tlv.data) >= 4:
status = struct.unpack('>L', status_tlv.data[:4])[0]
bs.front_data['oscar0_icq_status'] = status
self.logger.info('[Client] Status:', hex(status))
# before OSERVICE__CLIENT_READY this is only what the client wants to come online as
if bs.front_data.get('oscar0_ready'):
substatus = substatus_from_icq_status(status)
if substatus is context.user.status.substatus:
bs.me_update({ 'needs_notify': True, 'notify_status': True })
else:
bs.me_update({ 'substatus': substatus })
client.send_snac(build_self_info(bs))
@Subgroup(0x001F)
def probe_request(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
# some ICQ clients probe a connection before using it; OSERVICE__PROBE_ACK has no body
self.logger.info('[Client] OSERVICE__PROBE_REQ')
client.send_snac(SNACMessage(0x0001, 0x0020, 0x0000, message.request_id))
@Subgroup(0x0004)
def service_request(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] OSERVICE__SERVICE_REQUEST')
foodgroup = message.read_u16()
tlvs = unmarshal_tlvs(message.data)
self.logger.info('[Client] Foodgroup:', hex(foodgroup))
if foodgroup not in REQUESTABLE_SERVICES:
# OSERVICE__ERR, service unavailable
client.ctrl.send_snac_error(0x0001, message.request_id, 0x0005)
return
room = None
if foodgroup == 0x000E:
# TLV 0x01: the room to connect to (u16 exchange, string08 cookie, u16 instance)
from .chat import parse_room_info, find_room
room_tlv = find_tlv(tlvs, 0x0001)
room = parse_room_info(room_tlv.data) if room_tlv is not None else None
if room is None or find_room(room['cookie']) is None:
client.ctrl.send_snac_error(0x0001, message.request_id, 0x0005)
return
# generate BOS cookie and add it to array
bos_cookie = os.urandom(256)
bos_cookies.append({
bos_cookie: context.bs
})
bos_cookie = issue_cookie(ServiceCookie(
bs = context.bs, service = foodgroup, room = room, multi_conn = client.ctrl.multi_conn,
))
response_msg = SNACMessage(0x0001, 0x0005, 0x0000, message.request_id)
response_msg.write_tlvs([
TLV(0x0001, struct.pack('>H', 3)),
TLV(0x000D, struct.pack('>H', foodgroup)),
TLV(0x0005, f'{settings.TARGET_IP}:5190'),
TLV(0x0006, bos_cookie),
TLV(0x000D, struct.pack('>H', foodgroup)),
TLV(0x008E, struct.pack('>B', 0))
])
+238
View File
@@ -0,0 +1,238 @@
import struct
from core import error
from core.models import AIM_PD_KEY, AIM_SSI_KEY, ContactList, User
from enum import IntEnum
from typing import Optional
from util.misc import Logger, is_valid_oscar_screenname
from ..proto import names
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Subgroup
class PDMode(IntEnum):
PermitAll = 0x01
DenyAll = 0x02
PermitSome = 0x03
DenySome = 0x04
PermitOnList = 0x05
class PDStatus(IntEnum):
# values deliberately match FEEDBAG__STATUS_CODES, since the same list logic answers FEEDBAG permit/deny items
Success = 0x0000
NotFound = 0x0002
AlreadyExists = 0x0003
BadRequest = 0x000A
OverLimit = 0x000C
BadLoginID = 0x0010
MAX_PERMITS = 1000
MAX_DENIES = 1000
MAX_TEMP_PERMITS = 1000
PD_MODES = frozenset(int(m) for m in PDMode)
def _permit_names(user: User) -> list[str]:
# explicit permits live in the same settings blob the feedbag keeps its extras in, so both frontends of the list agree
store = user.settings.get(AIM_SSI_KEY)
if not isinstance(store, dict):
store = {}
user.settings[AIM_SSI_KEY] = store
return store.setdefault('permits', [])
def apply_pd_info(context: OSCARContext, mode: Optional[int], mask: Optional[int]) -> None:
# the mode drives the permit/deny rules in core.models, and BLP is kept in step with it
settings = context.user.settings
pd = dict(settings.get(AIM_PD_KEY) or {})
if mode is not None and mode in PD_MODES:
blp = 'AL' if mode in (PDMode.PermitAll, PDMode.DenySome) else 'BL'
settings['BLP'] = blp
pd['mode'] = mode
pd['blp'] = blp
if mask is not None:
pd['mask'] = mask
if pd:
settings[AIM_PD_KEY] = pd
def set_pd_mask(context: OSCARContext, mask: int) -> None:
# PD__SET_GROUP_PERMIT_MASK; a mask without a mode still needs one to be enforced, so the one BLP implies is filled in
user = context.user
blp = user.settings.get('BLP', 'AL')
pd = dict(user.settings.get(AIM_PD_KEY) or {})
if pd.get('mode') not in PD_MODES or pd.get('blp') != blp:
pd['mode'] = int(PDMode.DenySome if blp == 'AL' else PDMode.PermitOnList)
pd['blp'] = blp
pd['mask'] = mask
user.settings[AIM_PD_KEY] = pd
def pd_add(context: OSCARContext, name: str, *, permit: bool) -> PDStatus:
# shared by FEEDBAG permit/deny items and PD__ADD_PERM/DENY_LIST_ENTRIES
bs = context.bs
detail = context.user.detail
lst = ContactList.AL if permit else ContactList.BL
permits = _permit_names(context.user)
if not name or not names.valid_name(name):
return PDStatus.BadLoginID
contact_uuid = names.resolve(context.backend, name)
if contact_uuid is None:
return PDStatus.BadLoginID
contact_user = context.backend._load_user_record(contact_uuid)
if contact_user is None:
return PDStatus.BadLoginID
# permits are kept by screen name whichever way the client named them (a UIN, say), since that's what the
# permit/deny rules in core.models compare against
name = contact_user.username
contact = detail.contacts.get(contact_uuid)
if contact is not None and contact.lists & lst:
# a buddy is implicitly allowed, so an explicit permit for one is not a duplicate
if not (permit and contact.lists & ContactList.FL and name.lower() not in permits):
return PDStatus.AlreadyExists
if permit:
explicit = [c for c in detail.get_contacts_by_list(ContactList.AL) if not c.lists & ContactList.FL or c.head.username.lower() in permits]
if len(explicit) >= MAX_PERMITS:
return PDStatus.OverLimit
elif len(detail.get_contacts_by_list(ContactList.BL)) >= MAX_DENIES:
return PDStatus.OverLimit
try:
if contact is None or not contact.lists & lst:
bs.me_contact_add(contact_uuid, lst)
if permit:
permits.append(name.lower())
except error.ContactListIsFull:
return PDStatus.OverLimit
except Exception:
return PDStatus.BadRequest
return PDStatus.Success
def pd_remove(context: OSCARContext, name: str, *, permit: bool) -> PDStatus:
bs = context.bs
detail = context.user.detail
lst = ContactList.AL if permit else ContactList.BL
if not name or not names.valid_name(name):
return PDStatus.BadLoginID
contact_uuid = names.resolve(context.backend, name)
if contact_uuid is None:
return PDStatus.BadLoginID
contact_user = context.backend._load_user_record(contact_uuid)
if contact_user is None:
return PDStatus.BadLoginID
name = contact_user.username
contact = detail.contacts.get(contact_uuid)
if contact is None or not (contact.lists & lst):
return PDStatus.NotFound
try:
if permit:
permits = _permit_names(context.user)
if name.lower() in permits:
permits.remove(name.lower())
# a buddy keeps the AL it was inserted with
if not contact.lists & ContactList.FL:
bs.me_contact_remove(contact_uuid, lst)
else:
bs.me_contact_remove(contact_uuid, lst)
except Exception:
return PDStatus.BadRequest
return PDStatus.Success
def _read_entries(message: SNACMessage) -> list[str]:
# Class: PD Entries; u8 length + string, repeated until the SNAC runs out
entries = []
while len(message) > 0:
try:
entries.append(message.read_bytes(message.read_u8()).decode('latin-1'))
except (struct.error, UnicodeDecodeError):
break
return entries
def _apply_entries(context: OSCARContext, message: SNACMessage, *, permit: bool, add: bool) -> None:
bs = context.bs
before = bs.me_visibility_snapshot()
entries = _read_entries(message)
if add:
if len(entries) == 1 and names.resolve(context.backend, entries[0]) == context.user.uuid:
apply_pd_info(context, PDMode.DenyAll if permit else PDMode.PermitAll, None)
entries = []
elif entries:
apply_pd_info(context, PDMode.PermitSome if permit else PDMode.DenySome, None)
for name in entries:
if not names.valid_name(name):
continue
if add:
pd_add(context, name, permit = permit)
else:
pd_remove(context, name, permit = permit)
context.backend._mark_modified(context.user)
bs.me_visibility_changed(before)
# not registered as a foodgroup on its own; 0x0009 is registered once, in bos.py, which inherits these handlers
class PDHandlers:
logger: Logger
@Subgroup(0x0004)
def set_group_permit_mask(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] PD__SET_GROUP_PERMIT_MASK')
# xx xx xx xx dword group permission mask
mask = message.read_u32()
self.logger.info('[Client] Mask:', hex(mask))
before = context.bs.me_visibility_snapshot()
set_pd_mask(context, mask)
context.backend._mark_modified(context.user)
context.bs.me_visibility_changed(before)
@Subgroup(0x0005)
def add_perm_list_entries(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] PD__ADD_PERM_LIST_ENTRIES')
_apply_entries(context, message, permit = True, add = True)
@Subgroup(0x0006)
def del_perm_list_entries(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] PD__DEL_PERM_LIST_ENTRIES')
_apply_entries(context, message, permit = True, add = False)
@Subgroup(0x0007)
def add_deny_list_entries(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] PD__ADD_DENY_LIST_ENTRIES')
_apply_entries(context, message, permit = False, add = True)
@Subgroup(0x0008)
def del_deny_list_entries(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] PD__DEL_DENY_LIST_ENTRIES')
_apply_entries(context, message, permit = False, add = False)
@Subgroup(0x000A)
def add_temp_permit_list_entries(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] PD__ADD_TEMP_PERMIT_LIST_ENTRIES')
# temp permits only live as long as the session, so they stay out of the persisted lists
temp_permits = context.bs.front_data.setdefault('oscar0_temp_permits', set())
for name in _read_entries(message):
uuid = names.resolve(context.backend, name)
if uuid is not None and len(temp_permits) < MAX_TEMP_PERMITS:
temp_permits.add(uuid)
@Subgroup(0x000B)
def del_temp_permit_list_entries(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] PD__DEL_TEMP_PERMIT_LIST_ENTRIES')
temp_permits = context.bs.front_data.setdefault('oscar0_temp_permits', set())
for name in _read_entries(message):
uuid = names.resolve(context.backend, name)
if uuid is not None:
temp_permits.discard(uuid)
+1 -1
View File
@@ -11,7 +11,7 @@ def popup_display(self, alert_url: Optional[str], alert_txt: str):
response_msg = SNACMessage(0x0008, 0x0002, 0x0000, 0x00000000)
response_msg.write_bytes(system_message(alert_url, alert_txt))
# TODO(HIDEN): pipe to ctrl.send_snac()
# TODO: pipe to ctrl.send_snac()
print('TLVs:', unmarshal_tlvs(response_msg.data))
#client.send_snac(response_msg)
return response_msg
+39
View File
@@ -0,0 +1,39 @@
import struct
from util.misc import Logger
from ..proto import names
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import TLV
LOOKUP_TLV_SCREEN_NAME = 0x0001
LOOKUP_ERROR_NO_MATCH = 0x0014
@Foodgroup(0x000A)
class UserLookupFoodgroup:
logger: Logger
@Subgroup(0x0002)
def find_by_email(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
self.logger.info('[Client] USER_LOOKUP__FIND_BY_EMAIL')
# the SNAC body is the address itself; only people listed in the member directory can be found by it
email = message.data.decode('latin-1').strip('\x00').strip()
users = []
for uuid in (context.backend.user_service.search_uuids(email = email) if email else []):
user = context.backend._load_user_record(uuid)
if user is not None and names.representable(user):
users.append(user)
if not users:
msg = SNACMessage(0x000A, 0x0001, 0x0000, message.request_id)
msg.write_u16(LOOKUP_ERROR_NO_MATCH)
self.logger.info('[Server] USER_LOOKUP__ERR')
client.send_snac(msg)
return
reply = SNACMessage(0x000A, 0x0003, 0x0000, message.request_id)
reply.write_tlvs([TLV(LOOKUP_TLV_SCREEN_NAME, names.name_for(context.bs, user)) for user in users])
self.logger.info('[Server] USER_LOOKUP__FIND_REPLY')
client.send_snac(reply)
+142 -29
View File
@@ -1,24 +1,29 @@
import os
import struct
import time
import settings
from array import array
from core import event
from core.backend import Chat, ChatSession, BackendSession
from core.models import Contact, Substatus, Circle, CircleRole, User, TextWithData, OIM, LoginOption
from core.alerts import Alert
from dataclasses import dataclass, field
from enum import IntEnum
from util.misc import Logger
from util.misc import Logger, is_valid_oscar_screenname
from urllib.parse import quote
from typing import Optional, Any, Dict
from typing import Optional, Any, Dict, List
from ..foodgroups.buddy import build_presence_notif
from ..foodgroups.buddy import build_presence_notif, watching
from ..foodgroups.feedbag import build_buddy_added_notif
from ..foodgroups.popup import popup_display
from ..proto.snac import OSCARContext
from ..proto.tlv import TLV, marshal_tlvs, find_tlv
from ..proto.chat import ChatEventHandler
from . import names
from .delivery import oscar_sessions
# TODO(subpurple): move this to a config of some sort
# TODO: move this to a config of some sort
FOODGROUP_VERSIONS: {int, int} = {
0x0001: 4, # OSERVICE
0x0002: 1, # LOCATE
@@ -30,25 +35,73 @@ FOODGROUP_VERSIONS: {int, int} = {
0x000A: 1, # USER_LOOKUP
0x000B: 1, # STATS
0x000C: 1, # TRANSLATE
0x000F: 1, # DIRECTORY
0x0013: 6, # FEEDBAG
0x0015: 2, # ICQ
0x0018: 1, # EMAIL
0x0022: 1, # PLUGIN
0x0024: 1, # UNNAMED (possibly NACHOS?)
0x0025: 1 # MDIR
}
SERVICE_BOS = 0x0000
SERVICE_FOODGROUPS: Dict[int, List[int]] = {
SERVICE_BOS: [0x0018, 0x0010, 0x0003, 0x0013, 0x0004, 0x0015, 0x0002, 0x0001, 0x0009, 0x000A, 0x0006, 0x0008, 0x000B],
0x0007: [0x0001, 0x0007], # ADMIN
0x000D: [0x000D, 0x0001], # CHAT_NAV
0x000E: [0x0001, 0x000E], # CHAT
0x000F: [0x000F, 0x0001], # ODIR
0x0010: [0x0010, 0x0001], # BART
0x0018: [0x0018, 0x0001], # ALERT
}
ERROR_URLS: {int, str} = {
0x0001: 'http://www.aim.aol.com/errors/UNREGISTERED_SCREENNAME.html', # Unregistered screen name
0x0005: 'http://www.aim.aol.com/errors/MISMATCH_PASSWD.html', # Incorrect password
0x0009: '', # Not a tester (inaccurate)
0x0011: 'http://www.aim.aol.com/errors/SUSPENDED.html', # Suspended
0x0006: '' # Unverified E-mail (inaccurate)
0x0006: '', # Unverified E-mail (inaccurate)
0x0008: '', # ICQ user doesn't exist
}
PW_CHANGE_URL_FORMAT = 'http://aim.aol.com/redirects/password/change_password.adp?ScreenName={}&ccode={}&lang={}'
DISCONNECT_NEW_LOGIN = 0x0001
bos_cookies: array[{bytes, OSCARContext}] = []
COOKIE_LIFETIME = 300
@dataclass
class ServiceCookie:
uuid: Optional[str] = None
version: str = '?'
program: str = 'aim'
screen_name: Optional[str] = None
icq: bool = False
client_id: str = ''
multi_conn: Optional[int] = None
bs: Optional[BackendSession] = None
service: int = SERVICE_BOS
room: Optional[Dict[str, Any]] = None
issued: float = field(default_factory = time.time)
bos_cookies: Dict[bytes, ServiceCookie] = {}
def issue_cookie(entry: ServiceCookie) -> bytes:
now = time.time()
for stale in [cookie for cookie, other in bos_cookies.items() if now - other.issued > COOKIE_LIFETIME]:
del bos_cookies[stale]
cookie = os.urandom(256)
bos_cookies[cookie] = entry
return cookie
def take_cookie(cookie: bytes) -> Optional[ServiceCookie]:
entry = bos_cookies.pop(cookie, None)
if entry is None or time.time() - entry.issued > COOKIE_LIFETIME:
return None
return entry
class BackendEventHandler(event.BackendEventHandler):
@@ -61,20 +114,33 @@ class BackendEventHandler(event.BackendEventHandler):
def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None:
self.ctrl.logger.info("on_maintenance message dispatched")
message = "CrossTalk will be down for maintenance soon. Now is a good time to wrap up any conversations."
if args[1] is not None and args[1] > 0:
message = """CrossTalk will be down for maintenance in around {} minute(s). \
Now is a good time to wrap up any conversations.""".format(args[1])
self.ctrl.send_snac(popup_display(self, "https://crosstalk.im/maintenance", message))
def on_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None:
def on_client_alert(self, alert: Alert) -> bool:
self.ctrl.logger.info("on_client_alert dispatched")
self.ctrl.send_snac(popup_display(self, url, message))
self.ctrl.send_snac(popup_display(self, alert.url or '', alert.plain()))
return True
def on_maintenance_boot(self) -> None:
# TODO(HIDEN): can we pass an informative message to the user?
self.ctrl.close()
return
def on_warning_level_changed(self, level: int, warner: Optional[User]) -> None:
# a warning (from AIM, TOC or an MSN spam report) gets OSERVICE__EVIL_NOTIFICATION; any change, wearing off too, a
# fresh OSERVICE__USER_INFO_UPDATE, since the level is part of the user's own info
from ..foodgroups.icbm import build_evil_notification
from ..foodgroups.oservice import build_self_info
previous = self.bs.front_data.get('oscar0_evil', 0)
self.bs.front_data['oscar0_evil'] = level
if level > previous:
self.ctrl.send_snac(build_evil_notification(self.bs, level, warner))
self.ctrl.send_snac(build_self_info(self.bs))
def on_presence_notification(
self, ctc: Contact, on_contact_add: bool, old_substatus: Substatus, *,
trid: Optional[str] = None, update_status: bool = True, update_info_other: bool = True,
@@ -86,18 +152,27 @@ Now is a good time to wrap up any conversations.""".format(args[1])
self.ctrl.logger.info('update_info_other:', update_info_other)
self.ctrl.logger.info('status:', ctc.status.substatus.name)
# don't want updates from users with invalid usernames
if not names.representable(ctc.head):
return
# don't want any non-status updates
if not update_status:
self.ctrl.logger.info('fell into update_status check')
return
# for now, we only send presence notifications if the buddy changing status is offline(-ish) or online
if not ctc.status.is_offlineish() and ctc.status.substatus != Substatus.Online:
self.ctrl.logger.info('fell into status check')
# presence only starts flowing once the client says it's ready for it (OSERVICE__CLIENT_READY), and only for
# people on the buddy list the client actually runs on (its own one, unless it uses the feedbag)
if not self.bs.front_data.get('oscar0_ready') or not watching(self.bs, ctc.head):
return
self.ctrl.logger.info('sending presence notif')
self.ctrl.send_snac(build_presence_notif(ctc))
try:
ctc.compute_visible_status(self.bs.user)
self.ctrl.logger.info('sending presence notif')
self.ctrl.send_snac(build_presence_notif(ctc, self.ctrl.backend, self.bs))
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:
@@ -110,12 +185,17 @@ Now is a good time to wrap up any conversations.""".format(args[1])
) -> None:
self.ctrl.logger.info('on_chat_invite')
if chat is None:
chat = self.backend.chat_create()
chat = self.ctrl.backend.chat_create()
chat.add_id('oscar0', chat.ids['main'])
chats = self.bs.front_data.setdefault('oscar0_chats', {})
# a conversation with the same person moves to the newest chat they started
previous = chats.pop(inviter.uuid, None)
if previous is not None and previous[0].chat is not chat:
previous[0].close()
evt = ChatEventHandler(self.ctrl.backend.loop, self.ctrl, self.bs)
cs = chat.join('oscar0', self.bs, evt)
chat.send_participant_joined(cs)
self.bs.front_data['oscar0_chats'][inviter.uuid] = (cs, evt)
chats[inviter.uuid] = (cs, evt)
return
def on_declined_chat_invite(self, chat: Chat, circle: bool = False) -> None:
@@ -126,7 +206,20 @@ Now is a good time to wrap up any conversations.""".format(args[1])
message: Optional[TextWithData] = None) -> None:
self.ctrl.logger.info('on_added_me')
self.ctrl.send_snac(build_buddy_added_notif(user.username))
if not names.representable(user):
return
# an add still waiting on our authorization isn't announced until it's granted
from ..foodgroups.buddy import buddy_pending
if buddy_pending(user, self.bs.user):
return
from ..foodgroups.icbm import send_icq_system_message, ICQMessageType
if self.bs.front_data.get('oscar0_feedbag'):
self.ctrl.send_snac(build_buddy_added_notif(names.name_for(self.bs, user)))
elif names.is_icq_session(self.bs):
# ICQ clients without a feedbag only learn this from a "you were added" message (MSG_TYPE_ADDED)
send_icq_system_message(self.ctrl, user, ICQMessageType.Added, '')
def on_removed_me(self, user: User) -> None:
self.ctrl.logger.info('on_removed_me')
@@ -139,13 +232,25 @@ Now is a good time to wrap up any conversations.""".format(args[1])
def on_oim_sent(self, oim: OIM) -> None:
self.ctrl.logger.info('on_oim_sent')
pass
# an offline message only gets stored while its recipient can't be reached, so a session that hears about one
# (signed on invisible, say) gets it straight away, like the YMSG frontend does
from ..foodgroups.icbm import deliver_offline_messages
deliver_offline_messages(self.ctrl, [oim])
def on_login_elsewhere(self, option: LoginOption) -> None:
self.ctrl.logger.info('on_login_elsewhere')
self.ctrl.signoff(DISCONNECT_NEW_LOGIN)
self.ctrl.close()
return
def oscar_on_icbm(self, msg: Any) -> None:
# an ICBM (rendezvous, ICQ message, client error/ack) passed straight between OSCAR clients, bypassing the chat
# machinery the other frontends message through
self.ctrl.send_snac(msg)
def oscar_on_snac(self, msg: Any) -> None:
self.ctrl.send_snac(msg)
# circles are not a thing in AIM
def on_circle_invite_revoked(self, chat_id: str) -> None:
pass
@@ -174,52 +279,60 @@ class LoginError(IntEnum):
NotATester = 0x0009,
Suspended = 0x0011,
EmailNotVerified = 0x0006
ICQUserError = 0x0008
def login(logger: Logger,
context: OSCARContext,
tlvs: array[TLV],
uuid: Optional[str],
error_code: Optional[int]) -> bytes:
error_code: Optional[int],
*,
icq: bool = False,
multi_conn: Optional[int] = None) -> bytes:
# get user if found
user = context.backend.user_service.get(uuid) if uuid else None
# find screen name TLV and use it if not found in DB
screen_name_tlv = find_tlv(tlvs, 0x0001)
screen_name = user.username if user else screen_name_tlv.data.decode()
given_name = screen_name_tlv.data.decode('latin-1') if screen_name_tlv else ''
# an ICQ client gets its UIN back, an AIM one the screen name's own formatting
screen_name = (given_name.replace(' ', '') if icq else user.username) if user else given_name
# additionally check if user is suspended here
if error_code is None and user.suspended:
error_code = LoginError.Suspended
logger.info(screen_name, 'tried to sign on but is suspended!')
# and check if the user has verified their e-mail address
#if error_code is None and not user.verified_to_login:
# error_code = LoginError.EmailNotVerified
#
# logger.info(screen_name, 'tried to sign on but has not verified their e-mail address!')
if error_code is None:
logger.info(screen_name, 'signed on successfully!')
# generate BOS cookie and add it to array
bos_cookie = os.urandom(256)
bos_cookies.append({
bos_cookie: {'uuid': uuid, 'version': context.client.version}
})
client_id_tlv = find_tlv(tlvs, 0x0003)
bos_cookie = issue_cookie(ServiceCookie(
uuid = uuid, version = context.client.version, program = 'icq' if icq else 'aim',
screen_name = screen_name, icq = icq,
client_id = client_id_tlv.data.decode('latin-1') if client_id_tlv else '', multi_conn = multi_conn,
))
# get user email
email = user.email
# find client's country TLV for use in password change URL
country_tlv = find_tlv(tlvs, 0x000E)
country = country_tlv.data if country_tlv else 'us'
country = country_tlv.data.decode('latin-1') if country_tlv else 'us'
# find client's language TLV for use in password change URL
language_tlv = find_tlv(tlvs, 0x000F)
language = language_tlv.data if language_tlv else 'en'
language = language_tlv.data.decode('latin-1') if language_tlv else 'en'
# format password change URL with found client country and language
pw_change_url = PW_CHANGE_URL_FORMAT.format(
@@ -241,5 +354,5 @@ def login(logger: Logger,
return marshal_tlvs([
TLV(0x0001, screen_name), # Screen name
TLV(0x0008, struct.pack('>H', error_code)), # Error code
TLV(0x0004, ERROR_URLS[error_code]), # Error URL
])
TLV(0x0004, ERROR_URLS.get(int(error_code), '')), # Error URL
])
+210
View File
@@ -0,0 +1,210 @@
import asyncio
import hashlib
import struct
from enum import IntEnum, IntFlag
from io import BytesIO
from pathlib import Path
from typing import Callable, TYPE_CHECKING
from core.models import User
from util.avatar import get_avatar_data
if TYPE_CHECKING:
from core.backend import BackendSession
class BARTType(IntEnum):
BuddyIconSmall = 0x0000
BuddyIcon = 0x0001
StatusStr = 0x0002
ArriveSound = 0x0003
RichName = 0x0004
SuperIcon = 0x0005
BuddyIconBig = 0x000C
class BARTFlags(IntFlag):
Known = 0x00
Custom = 0x01
Url = 0x02
Data = 0x04
Unknown = 0x40
Redirect = 0x80
class BARTReplyCode(IntEnum):
Success = 0x00
Invalid = 0x01
NoCustom = 0x02
TooSmall = 0x03
TooBig = 0x04
InvalidType = 0x05
Banned = 0x06
NotFound = 0x07
CLEAR_ICON_HASH = bytes.fromhex('0201d20472')
BLANK_GIF = bytes([
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x32, 0x00, 0x32, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
0x32, 0x00, 0x32, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b,
])
ICON_SIZE = (48, 48)
MAX_ICON_BYTES = 7168
BART_STORAGE = Path('storage/bart')
_stored: set[bytes] = set()
_items: dict[bytes, bytes] = {}
_MAX_CACHED_ITEMS = 512
_avatar_icons: dict[tuple[str, str], tuple[bytes, bytes]] = {}
_avatar_by_hash: dict[bytes, tuple[str, str]] = {}
_preparing: set[tuple[str, str]] = set()
_refresh_hook: Callable[[User], None] | None = None
def _load_index() -> None:
try:
if BART_STORAGE.is_dir():
for path in BART_STORAGE.iterdir():
try:
_stored.add(bytes.fromhex(path.name))
except ValueError:
continue
except OSError:
pass
_load_index()
def set_refresh_hook(hook: Callable[[User], None]) -> None:
global _refresh_hook
_refresh_hook = hook
def build_bart_id(type: int, flags: int, hash: bytes) -> bytes:
# BART_ID: u16 type, u8 flags, u8 length, then the hash (a BART_INFO behind the type)
return struct.pack('>HBB', type, flags, len(hash)) + hash
def parse_bart_info(data: bytes) -> tuple[int, bytes] | None:
# BART_INFO: u8 flags, u8 length, hash
if len(data) < 2 or len(data) < 2 + data[1]:
return None
return data[0], data[2:2 + data[1]]
def parse_bart_id(data: bytes) -> tuple[int, int, bytes, bytes] | None:
# returns type, flags, hash and whatever follows the BART_ID
if len(data) < 4:
return None
type, flags, length = struct.unpack('>HBB', data[:4])
if len(data) < 4 + length:
return None
return type, flags, data[4:4 + length], data[4 + length:]
def is_known(hash: bytes) -> bool:
return hash == CLEAR_ICON_HASH or hash in _stored or hash in _items or hash in _avatar_by_hash
def _remember(hash: bytes, data: bytes) -> None:
if len(_items) >= _MAX_CACHED_ITEMS:
_items.pop(next(iter(_items)))
_items[hash] = data
def bart_info(user: User, bs: 'BackendSession | None' = None) -> bytes | None:
# OSERVICE__USERINFO TLV 0x1D: the icon an OSCAR client set this session, else the account's avatar
icon = bs.front_data.get('oscar0_bart_icon') if bs is not None else None
if icon is not None:
flags, hash = icon
# a cleared icon shows nothing, and one still waiting to be uploaded can't be fetched yet
if hash == CLEAR_ICON_HASH or flags & BARTFlags.Unknown:
return None
return build_bart_id(BARTType.BuddyIcon, flags, hash)
entry = _avatar_icon(user)
if entry is None:
return None
return build_bart_id(BARTType.BuddyIcon, BARTFlags.Custom, entry[0])
def _avatar_icon(user: User) -> tuple[bytes, bytes] | None:
if not user.avatar:
return None
key = (user.uuid, user.avatar)
entry = _avatar_icons.get(key)
if entry is not None or key in _preparing:
return entry
# reading and scaling the image is file work, so it happens off the event loop and shows up on the next update
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return None
_preparing.add(key)
loop.create_task(_prepare_avatar(user, key))
return None
async def _prepare_avatar(user: User, key: tuple[str, str]) -> None:
try:
icon = await asyncio.get_running_loop().run_in_executor(None, _load_avatar_icon, key[0], key[1])
finally:
_preparing.discard(key)
if icon is None:
return
hash = hashlib.md5(icon).digest()
_avatar_icons[key] = (hash, icon)
_avatar_by_hash[hash] = key
if _refresh_hook is not None and user.avatar == key[1]:
_refresh_hook(user)
def _load_avatar_icon(uuid: str, avatar: str) -> bytes | None:
found = get_avatar_data(uuid, avatar)
if found is None:
return None
return to_icon(found[0])
def to_icon(data: bytes) -> bytes | None:
# AIM 4.x/5.x take GIF, JPEG and BMP icons of up to 48x48; anything else gets scaled down into a GIF
try:
from PIL import Image
except ImportError:
return data if data[:6] in (b'GIF87a', b'GIF89a') and len(data) <= MAX_ICON_BYTES else None
try:
img = Image.open(BytesIO(data))
img = img.convert('RGBA')
img.thumbnail(ICON_SIZE)
out = BytesIO()
img.convert('RGB').convert('P', palette = Image.ADAPTIVE).save(out, format = 'GIF')
icon = out.getvalue()
except Exception:
return None
return icon if len(icon) <= MAX_ICON_BYTES else None
async def get_item(hash: bytes) -> bytes | None:
# BART__DOWNLOAD: whatever image has this hash, from memory, the converted avatars or the BART store on disk
if hash == CLEAR_ICON_HASH:
return BLANK_GIF
data = _items.get(hash)
if data is not None:
return data
key = _avatar_by_hash.get(hash)
if key is not None and key in _avatar_icons:
return _avatar_icons[key][1]
if hash not in _stored:
return None
data = await asyncio.get_running_loop().run_in_executor(None, _read_item, hash)
if data is not None:
_remember(hash, data)
return data
def _read_item(hash: bytes) -> bytes | None:
try:
return (BART_STORAGE / hash.hex()).read_bytes()
except OSError:
return None
async def store_item(data: bytes) -> bytes:
# BART__UPLOAD: filed by MD5, which is the hash every client computes for an icon
hash = hashlib.md5(data).digest()
_remember(hash, data)
if hash not in _stored:
await asyncio.get_running_loop().run_in_executor(None, _write_item, hash, data)
_stored.add(hash)
return hash
def _write_item(hash: bytes, data: bytes) -> None:
BART_STORAGE.mkdir(parents = True, exist_ok = True)
(BART_STORAGE / hash.hex()).write_bytes(data)
+20 -7
View File
@@ -7,7 +7,7 @@ from core.models import User, Substatus, MessageData, MessageType
from ..proto.snac import SNACMessage
from ..proto.tlv import TLV
from ..proto.buffer import Buffer
from ..foodgroups.icbm import ICBMChannel, messagedata_to_icbm, messagedata_to_icbm_event
from ..foodgroups.icbm import ICBMChannel, gen_cookie, messagedata_to_icbm, messagedata_to_icbm_event
class ChatEventHandler(event.ChatEventHandler):
__slots__ = ('loop', 'ctrl', 'bs', 'cs', 'cookie', '_pending')
@@ -37,6 +37,15 @@ class ChatEventHandler(event.ChatEventHandler):
def on_participant_left(self, cs_other: 'ChatSession', last_pop: bool) -> None:
self.ctrl.logger.info('on_participant_left')
# 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
chats = self.bs.front_data.get('oscar0_chats', {})
for uuid, (cs, _) in list(chats.items()):
if cs is self.cs:
del chats[uuid]
# (closed once the chat is done telling everyone, since it's still walking its roster)
self.loop.call_soon(self.cs.close)
def on_chat_invite_declined(self, chat: 'Chat', invitee: User, *, invitee_id: Optional[str] = None,
message: Optional[str] = None, circle: bool = False) -> None:
@@ -56,16 +65,20 @@ class ChatEventHandler(event.ChatEventHandler):
if data.sender is self.bs.user:
if data.front_cache.get('icbm_echo'):
original_cookie = data.front_cache.get('icbm_cookie', self.cookie)
self.ctrl.send_snac(messagedata_to_icbm(original_cookie, data, self.bs.user))
self.ctrl.send_snac(messagedata_to_icbm(original_cookie, data, self.bs))
return
if data.type in (MessageType.Typing, MessageType.TypingDone):
self.ctrl.send_snac(messagedata_to_icbm_event(data, self.bs.user))
self.ctrl.send_snac(messagedata_to_icbm_event(data, self.bs))
return
self.ctrl.logger.info('Got a message from', data.sender.username, 'saying:')
self.ctrl.logger.info(data.text.encode())
self.ctrl.send_snac(messagedata_to_icbm(self.cookie, data, self.bs.user))
elif data.type is MessageType.Chat:
self.ctrl.logger.info('Got a message from', data.sender.username, 'saying:')
self.ctrl.logger.info((data.text or '').encode())
# an OSCAR sender's own message cookie travels with the message, so acks and replies line up on both ends; anything
# else gets a fresh one, since clients take a repeated cookie for a repeated message
self.ctrl.send_snac(messagedata_to_icbm(data.front_cache.get('icbm_cookie') or gen_cookie(), data, self.bs))
else:
pass
def _send_when_user_joins(self, user_uuid: str, data: MessageData) -> None:
if self._user_in_chat(user_uuid):
+38
View File
@@ -0,0 +1,38 @@
from typing import Any, Callable, TYPE_CHECKING
from core.models import User
from .snac import SNACMessage
if TYPE_CHECKING:
from core.backend import Backend, BackendSession
def oscar_sessions(backend: 'Backend', user: User) -> list['BackendSession']:
# the BOS sessions of `user` that an OSCAR client is behind (the event handler is how SNACs reach its connection)
return [
bs for bs in backend.util_get_sessions_by_user(user)
if bs.front_data.get('oscar0') and hasattr(bs.evt, 'oscar_on_snac') and not bs.closed
]
def send_to_user(backend: 'Backend', user: User, build: Callable[['BackendSession'], SNACMessage | None]) -> int:
# hand a SNAC (built per viewer, since names and formatting depend on who receives it) to each OSCAR session of `user`
sent = 0
for bs in oscar_sessions(backend, user):
msg = build(bs)
if msg is None:
continue
bs.evt.oscar_on_snac(msg)
sent += 1
return sent
def feedbag_sessions(backend: 'Backend', user: User) -> list['BackendSession']:
# the OSCAR sessions that run on a server-side buddy list (they sent FEEDBAG__USE)
return [bs for bs in oscar_sessions(backend, user) if bs.front_data.get('oscar0_feedbag')]
def any_session(backend: 'Backend', user: User) -> 'BackendSession | None':
sessions = oscar_sessions(backend, user)
return sessions[0] if sessions else None
def ctrl_of(bs: 'BackendSession') -> Any:
return getattr(bs.evt, 'ctrl', None)
+117
View File
@@ -0,0 +1,117 @@
import re
from typing import Any, TYPE_CHECKING
from core.models import AIM_SSI_KEY, User
from util.misc import is_valid_oscar_screenname
if TYPE_CHECKING:
from core.backend import Backend, BackendSession
# ICQ numbers are plain decimal and fit in a u32
_UIN_RE = re.compile(r'^[0-9]{1,10}$')
def is_uin(name: str) -> bool:
return _UIN_RE.match(name) is not None and 0 < int(name) <= 0xFFFFFFFF
def normalize(name: str) -> str:
# OSCAR compares screen names without spaces or case ("Joe Smith" and "joesmith" are the same account)
return name.replace(' ', '').lower()
def valid_name(name: str) -> bool:
# what a client may name an account by: a screen name, or an ICQ number (which is one too)
return bool(name) and is_valid_oscar_screenname(name.replace(' ', ''))
def uin_of(user: User) -> int | None:
uin = getattr(user, 'uin', None)
if not uin or int(uin) <= 0 or int(uin) > 0xFFFFFFFF:
return None
return int(uin)
def resolve(backend: 'Backend', name: str) -> str | None:
# both an account's screen name and its UIN reach it
if not valid_name(name):
return None
return backend.util_get_uuid_from_screenname(name)
def resolve_user(backend: 'Backend', name: str) -> User | None:
uuid = resolve(backend, name)
if uuid is None:
return None
return backend._load_user_record(uuid)
def is_icq_session(bs: 'BackendSession | None') -> bool:
return bool(bs is not None and bs.front_data.get('oscar0_icq'))
def self_name(bs: 'BackendSession') -> str:
# the name the client signed on with comes back to it in everything about itself
return bs.front_data.get('oscar0_sn') or bs.user.username
def representable(user: User) -> bool:
# a screen name OSCAR can carry, or a UIN to stand in for one
return is_valid_oscar_screenname(user.username) or uin_of(user) is not None
def matches(form: str, user: User) -> bool:
uin = uin_of(user)
if uin is not None and is_uin(form) and int(form) == uin:
return True
return normalize(form) == user.username.lower()
def default_name(bs: 'BackendSession | None', user: User) -> str:
# ICQ sessions know people by number wherever there is one, AIM sessions by screen name
uin = uin_of(user)
if is_icq_session(bs) and uin is not None:
return str(uin)
if is_valid_oscar_screenname(user.username):
return user.username
if uin is not None:
return str(uin)
return user.username
def _aliases(user: User) -> dict[str, Any]:
store = user.settings.get(AIM_SSI_KEY)
if not isinstance(store, dict):
store = {}
user.settings[AIM_SSI_KEY] = store
names = store.get('names')
if not isinstance(names, dict):
names = {}
store['names'] = names
return names
def name_for(bs: 'BackendSession | None', user: User) -> str:
# the form `bs`'s client knows `user` by: what it named them by this session, what it stored them as, or the default
if bs is not None:
if user is bs.user:
return self_name(bs)
form = bs.front_data.get('oscar0_names', {}).get(user.uuid)
if form is not None and matches(form, user):
return form
store = bs.user.settings.get(AIM_SSI_KEY)
alias = ((store.get('names') or {}) if isinstance(store, dict) else {}).get(user.uuid)
if isinstance(alias, str) and matches(alias, user):
return alias
return default_name(bs, user)
def remember(bs: 'BackendSession', user: User, form: str) -> None:
# a client keeps its own spelling of a name; replies about that account have to use it or the client won't match them up
if user is bs.user or not matches(form, user):
return
bs.front_data.setdefault('oscar0_names', {})[user.uuid] = form
def store_alias(bs: 'BackendSession', user: User, form: str) -> bool:
# a feedbag buddy keeps the form it was added by across sign-ons; returns whether anything changed
if not matches(form, user):
return False
names = _aliases(bs.user)
if normalize(form) == normalize(default_name(bs, user)):
return names.pop(user.uuid, None) is not None
if names.get(user.uuid) == form:
return False
names[user.uuid] = form
return True
def drop_alias(bs: 'BackendSession', uuid: str) -> None:
_aliases(bs.user).pop(uuid, None)
bs.front_data.get('oscar0_names', {}).pop(uuid, None)
+1 -1
View File
@@ -101,7 +101,7 @@ class Subgroup:
class OSCARClient:
__slots__ = 'ctrl'
ctrl: Any # Any because of circular imports - TODO(subpurple): make this less hacky
ctrl: Any # Any because of circular imports - TODO: make this less hacky
def __init__(self, ctrl: Any) -> None:
self.ctrl = ctrl
+2 -2
View File
@@ -36,7 +36,7 @@ def unmarshal_tlvs(data: bytes) -> list[TLV]:
buf = buffer.Buffer(data)
tlvs = []
while len(buf) > 4:
while len(buf) >= 4:
type = buf.read_u16()
length = buf.read_u16()
value = buf.read_bytes(length)
@@ -51,4 +51,4 @@ def find_tlv(tlvs: list[TLV], type: int) -> Optional[TLV]:
if tlv.type == type:
return tlv
return None
return None
+235
View File
@@ -0,0 +1,235 @@
import calendar
import struct
import time
from enum import IntEnum, IntFlag
from typing import Optional, TYPE_CHECKING
from core.models import Substatus, User
from .bart import bart_info
from .buffer import Buffer
from .names import is_uin
from .tlv import TLV
if TYPE_CHECKING:
from core.backend import Backend, BackendSession
class UserFlags(IntFlag):
DamnedTransient = 0x0001
Administrator = 0x0002
Aol = 0x0004
OscarPay = 0x0008
OscarFree = 0x0010
Unavailable = 0x0020
Icq = 0x0040
Wireless = 0x0080
Internal = 0x0100
Fish = 0x0200
Bot = 0x0400
Beast = 0x0800
OneWayWireless = 0x1000
Official = 0x2000
BuddyMatchDirect = 0x10000
BuddyMatchIndirect = 0x20000
NoKnockKnock = 0x40000
ForwardMobile = 0x80000
class UserInfoTag(IntEnum):
UserFlags = 0x01
SignonTod = 0x03
IdleTime = 0x04
MemberSince = 0x05
Status = 0x06
IcqDcInfo = 0x0C
OscarCaps = 0x0D
OscarOt = 0x0F
BartInfo = 0x1D
UserFlags2 = 0x1F
class ICQStatus(IntFlag):
# OSERVICE__USER_STATUS: the low word is the ICQ status, ICQ clients send the "away" bit along with the stronger ones
Online = 0x0000
Away = 0x0001
Dnd = 0x0002
NotAvailable = 0x0004
Occupied = 0x0010
FreeForChat = 0x0020
Invisible = 0x0100
WebAware = 0x00010000
HideIp = 0x00020000
Birthday = 0x00080000
DirectRequireAuth = 0x10000000
# the part of the status dword that says how available someone is (the rest are flags)
ICQ_STATUS_MASK = 0x0000FFFF
# ICQ direct connection info (SNAC(01,1E) TLV 0x0C), zeroed: no direct connections, but ICQ needs the TLV to take an arrival
# u32 ip, u32 port, u8 dc type, u16 dc protocol version, u32 dc cookie, u32 web port, u32 client features, u32 x3 timestamps, u16
ICQ_DC_INFO_EMPTY = bytes(37)
MAX_WARNING = 999
# anything that isn't online, idle, or offline-ish is an "away" state as far as AIM is concerned
AWAY_SUBSTATUSES = frozenset({
Substatus.Busy, Substatus.Away, Substatus.BRB, Substatus.OnPhone, Substatus.OutToLunch, Substatus.NotAtHome,
Substatus.NotAtDesk, Substatus.NotInOffice, Substatus.OnVacation, Substatus.SteppedOut,
})
# used for sessions that never sent a capability block (i.e. users on other frontends)
DEFAULT_CAPS = [bytes.fromhex(cap.replace('-', '')) for cap in (
"09461345-4C7F-11D1-8222-444553540000",
"094601FF-4C7F-11D1-8222-444553540000",
"748F2420-6287-11D1-8222-444553540000",
"09461343-4C7F-11D1-8222-444553540000",
"09461341-4C7F-11D1-8222-444553540000",
"09460104-4C7F-11D1-8222-444553540000",
"09460105-4C7F-11D1-8222-444553540000",
"09460102-4C7F-11D1-8222-444553540000",
"09460103-4C7F-11D1-8222-444553540000",
"09460101-4C7F-11D1-8222-444553540000",
"0946134A-4C7F-11D1-8222-444553540000",
"09461346-4C7F-11D1-8222-444553540000",
)]
def pick_session(backend: 'Backend', user: User) -> Optional['BackendSession']:
sessions = backend.util_get_sessions_by_user(user)
for bs in sessions:
if bs.front_data.get('oscar0'):
return bs
return sessions[0] if sessions else None
def user_flags(substatus: Substatus) -> UserFlags:
flags = UserFlags.OscarFree
if substatus in AWAY_SUBSTATUSES:
flags |= UserFlags.Unavailable
return flags
def _unix(dt: object) -> Optional[int]:
if dt is None:
return None
return int(calendar.timegm(dt.timetuple())) # type: ignore
# what an ICQ client reads out of a substatus, for people who aren't on ICQ themselves
_ICQ_STATUS_BY_SUBSTATUS = {
Substatus.Online: ICQStatus.Online,
Substatus.Idle: ICQStatus.Online,
Substatus.Away: ICQStatus.Away,
Substatus.BRB: ICQStatus.Away,
Substatus.OutToLunch: ICQStatus.Away,
Substatus.SteppedOut: ICQStatus.Away,
Substatus.NotAtDesk: ICQStatus.Away,
Substatus.NotAtHome: ICQStatus.NotAvailable | ICQStatus.Away,
Substatus.NotInOffice: ICQStatus.NotAvailable | ICQStatus.Away,
Substatus.OnVacation: ICQStatus.NotAvailable | ICQStatus.Away,
Substatus.Busy: ICQStatus.Occupied | ICQStatus.Away,
Substatus.OnPhone: ICQStatus.Occupied | ICQStatus.Away,
Substatus.Invisible: ICQStatus.Invisible,
}
def icq_status_from_substatus(substatus: Substatus) -> int:
return int(_ICQ_STATUS_BY_SUBSTATUS.get(substatus, ICQStatus.Online))
def substatus_from_icq_status(status: int) -> Substatus:
# the strongest bit wins: DND (0x13) and occupied (0x11) carry the away bit, N/A (0x05) does too
status &= ICQ_STATUS_MASK
if status & ICQStatus.Invisible:
return Substatus.Invisible
if status & (ICQStatus.Dnd | ICQStatus.Occupied):
return Substatus.Busy
if status & ICQStatus.NotAvailable:
return Substatus.NotAtHome
if status & ICQStatus.Away:
return Substatus.Away
return Substatus.Online
def icq_status_for(user: User, bs: Optional['BackendSession'], substatus: Optional[Substatus] = None) -> int:
# an ICQ client's own status word (DND rather than occupied, free for chat, web aware...) is passed on while it still holds
if substatus is None:
substatus = user.status.substatus
raw = None
if bs is not None:
raw = bs.front_data.get('oscar0_icq_status')
if raw is None:
# a pre-OSCAR ICQ client's status dword, kept the same way by that frontend
raw = bs.front_data.get('icq0_status')
if raw is not None and substatus_from_icq_status(raw) is substatus:
return int(raw)
return icq_status_from_substatus(substatus)
def build_departure(name: str, *, with_flags: bool = True) -> bytes:
# BUDDY__DEPARTED holds a bare OSERVICE__USERINFO: the TLV count is always there, and ICQ only takes a departure that
# carries a (zero) user class in it
buf = Buffer()
buf.write_string_u8(name)
buf.write_u16(0)
buf.write_tlv_block([TLV(UserInfoTag.UserFlags, struct.pack('>H', 0))] if with_flags else [])
return buf.data
def build_userinfo(
user: User, bs: Optional['BackendSession'] = None, *,
substatus: Optional[Substatus] = None, departed: bool = False, name: Optional[str] = None, viewer_icq: bool = False,
) -> bytes:
# OSERVICE__USERINFO: string08 displayId, u16 warning level, tlvBlock of OSERVICE__USER_INFO_TAGS
if substatus is None:
substatus = user.status.substatus
if name is None:
name = user.username
# whoever is shown by UIN is an ICQ user to the client: it wants the ICQ user class, a status word and DC info for them
icq = is_uin(name)
now = time.time()
flags = int(user_flags(substatus))
if icq:
flags |= UserFlags.Icq
tlvs = [TLV(UserInfoTag.UserFlags, struct.pack('>H', flags & 0xFFFF))]
# the upper bytes of the flags only get sent when something in them is set
if flags >> 16:
tlvs.append(TLV(UserInfoTag.UserFlags2, (flags >> 16).to_bytes(2, 'big')))
if not departed:
member_since = _unix(user.date_created)
if member_since is not None:
tlvs.append(TLV(UserInfoTag.MemberSince, struct.pack('>L', member_since)))
signon = None # type: Optional[int]
if bs is not None and bs.front_data.get('oscar0_signon') is not None:
signon = int(bs.front_data['oscar0_signon'])
else:
signon = _unix(user.date_login)
if signon is not None:
tlvs.append(TLV(UserInfoTag.SignonTod, struct.pack('>L', signon)))
tlvs.append(TLV(UserInfoTag.OscarOt, struct.pack('>L', max(0, int(now) - signon))))
# idle time is in minutes
idle_since = bs.front_data.get('oscar0_idle_since') if bs is not None else None
if idle_since is not None:
tlvs.append(TLV(UserInfoTag.IdleTime, struct.pack('>H', min(0xFFFF, max(1, int((now - idle_since) // 60))))))
elif substatus is Substatus.Idle:
tlvs.append(TLV(UserInfoTag.IdleTime, struct.pack('>H', 1)))
caps = bs.front_data.get('oscar0_caps') if bs is not None else None
if caps is None and not viewer_icq:
caps = DEFAULT_CAPS
# ICQ reads capabilities as what the other side's client can do peer to peer; non-OSCAR users can't do any of it
if caps is not None:
tlvs.append(TLV(UserInfoTag.OscarCaps, b''.join(caps)))
if icq or viewer_icq:
tlvs.append(TLV(UserInfoTag.Status, struct.pack('>L', icq_status_for(user, bs, substatus))))
if icq:
dc_info = bs.front_data.get('oscar0_icq_dc') if bs is not None else None
tlvs.append(TLV(UserInfoTag.IcqDcInfo, dc_info if dc_info is not None else ICQ_DC_INFO_EMPTY))
bart = bart_info(user, bs)
if bart is not None:
tlvs.append(TLV(UserInfoTag.BartInfo, bart))
buf = Buffer()
buf.write_string_u8(name)
buf.write_u16(max(0, min(MAX_WARNING, int(user.evil_permanent or 0) + int(user.evil_temporary or 0))))
buf.write_tlv_block(tlvs)
return buf.data