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

+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