diff --git a/.gitignore b/.gitignore index d182586..6057b9e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,12 +3,6 @@ __pycache__ .mypy_cache *.sqlite settings_local.py -etc/Caddyfile -dev/cert -tmp -hosts.lnk -storage -front/ymsg/todo .mypy_cache .brutus_cache *.old @@ -16,8 +10,9 @@ front/ymsg/todo .vs/ .*_cache .DS_Store -core/static/sounds/user/ Thumbs.db .idea *.swp *.pem +config/ins/ +storage/ \ No newline at end of file diff --git a/README.md b/README.md index a21fc42..f9ee52e 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,9 @@ Currently, MSNP2 through MSNP18 are fully implemented, with an MSNP19 - MSNP21 i - If you want to log in to MSN Messenger < 4.7.2009, an MD5-encoded password hash must be stored -- Circles/Groups for Windows Live Messenger 2009 are fully implemented, however, managing members is expected to be done from the CrossTalk website. You can use `script/managecircle.py` to perform a few actions on a Circle and its users (run `python script/managecircle.py -h` to see instructions) +- Circles/Groups for Windows Live Messenger 2009 are fully implemented, however, managing members is expected to be done from the CrossTalk website. You can usethe admin panel to perform a few actions on a Circle and its users -- Windows Live Messenger 2011/2012 supports authentication, viewing your contacts list, presence updates, and MsgrConfig, and instant messaging. Most other functionality is either unimplemented or untested. Peer-to-peer functionality (display picture syncing, file transfers, activites/games etc) currently does not interop between 2011/2012 and older versions; it only works with other 2011/2012 users. +- Most peer-to-peer functionality (display picture syncing, file transfers, activites/games etc) currently does not interop properly between 2011/2012 and older versions; it only works with other 2011/2012 users. This will be fixed in a future update. ### YMSG (used by Yahoo! Messenger) @@ -28,11 +28,20 @@ As of now, YMSG9 through YMSG15 are implemented, with some caveats: ### IRC -IRC is going to be completely reworked with the introduction of chatrooms, but as it stands, it's fairly basic. It offers the ability to create, join, invite people to, leave, and list other people in temporary chats, and to set your nickname, view the MOTD, and set an away message. It also requires `USER`-based login with your account credentials, however, IRC-only guest logins are planned. +IRC is going to be completely reworked in the future with the introduction of chatrooms, but as it stands, it's fairly basic. It offers the ability to create, join, invite people to, leave, and list other people in temporary chats, and to set your nickname, view the MOTD, and set an away message. It also requires `USER`-based login with your account credentials, however, IRC-only guest logins are planned. ### OSCAR (used by AOL Instant Messenger and ICQ 2000 - 8) -OSCAR is basic, but functional. Right now, messaging and buddy list management is implemented. The FLAP and BUCP authentication methods are implemented. AIM 1.0 - 5.9 are supported, but 4.x and 5.x are where most testing is done, so older versions may be hit or miss. AIM 6.x - 7.x, TOC/TOC2, WebAPI, and ICQ are not supported yet, but support for them is planned and will come in the future. Not sure about AIM 8 because of NINA getting exploded. +- If you want to log in, an MD5-encoded password hash must be stored +- AIM: client-side and server-side (feedbag) buddy lists with permit/deny, profiles and away messages, buddy icons (BART), chat rooms (made by users, exchange 4), warnings, typing notifications, offline IMs (stored when the sender asks, handed over at sign-on), the member directory, and rendezvous (file transfers, direct IM) between OSCAR clients. Buddies can be added by screen name or by ICQ number. +- ICQ 2000b and later sign on with their UIN (or, like AIM, with the username), and get ICQ statuses (away, N/A, occupied, DND, free for chat, invisible), the white pages (`ICQ__DB_QUERY` info and searches, which only show members listed in the directory), offline messages and authorization requests. +- An all-digit screen name is tried as a UIN first, then as a username, so neither kind of account gets in the way of the other. + +### ICQ (the pre-OSCAR Mirabilis protocol, ICQ 1.x - 2000a) + +The original UDP protocol, versions 1 - 5, on UDP port `ICQ_LEGACY_PORT` (4000 by default; `ENABLE_FRONT_ICQ = False` turns it off): V5 is ICQ 98b - 2000a, V4 ICQ 98a, V3 ICQ Groupware, V2 ICQ 1.111 and CenterICQ, V1 ICQ 1.02. Point the client at the server with "For admin use" in its registration wizard, then choose to sign on as an existing user. Signing on takes the UIN and the account's password (the client's own limit on password length applies). + +Contact list presence, statuses, messages and URLs (to and from every other protocol), offline messages, the white pages (`META_USER` for V5, the older info and search packets before it), profile changes and authorization requests work. New accounts can't be made from the client; they come from the website. Direct connections (file transfers, chat) are only possible with `ICQ_DIRECT_CONNECTIONS = True`, which hands V5 clients each other's IP address. ## Developers diff --git a/config/bannerimages.json b/config/bannerimages.json index d99a6f8..48f46c3 100644 --- a/config/bannerimages.json +++ b/config/bannerimages.json @@ -21,72 +21,52 @@ }, { "id": 5, - "image": "banner/cobbclub.png", - "link": "http://cobb.club" - }, - { - "id": 6, "image": "banner/maymundere.gif", "link": "https://maymundere.org" }, { - "id": 7, - "image": "banner/macsecret.png", - "link": "http://macsecret.com" - }, - { - "id": 8, + "id": 6, "image": "banner/leefy.png", "link": "https://leefymoons-room.net" }, { - "id": 9, - "image": "banner/srcfreak.jpg", - "link": "http://srcfreaks.ddns.net" - }, - { - "id": 10, + "id": 7, "image": "banner/kakworm.gif", "link": "https://fusionstrike.neocities.org" }, { - "id": 11, + "id": 8, "image": "banner/gdsk.gif", "link": "https://gdsk.retrosite.org" }, { - "id": 12, + "id": 9, "image": "banner/kooper.png", "link": "http://kooper.online" }, { - "id": 13, - "image": "banner/imsnp.png", - "link": "http://kooper.online/blog/pages/imsnp.html" - }, - { - "id": 14, + "id": 10, "image": "banner/aomeix.jpg", "link": "http://aomeix.eu.org" }, - { - "id": 15, + { + "id": 11, "image": "banner/bluebrixhq.gif", "link": "https://brix.neocities.org" - }, + }, { - "id": 16, - "image": "banner/thebrothers.png", - "link": "https://the-brothers.neocities.org" - }, - { - "id": 17, + "id": 12, "image": "banner/action97.gif", "link": "https://bloxy97.nekoweb.org" - }, + }, { - "id": 18, + "id": 13, "image": "banner/barco.gif", "link": "https://barcohot.nekoweb.org" - } + }, + { + "id": 14, + "image": "banner/pentralink.gif", + "link": "https://pentalink.yooco.org/" + } ] diff --git a/config/restricted-emails.json b/config/restricted-emails.json index c3f06a3..8d135c7 100644 --- a/config/restricted-emails.json +++ b/config/restricted-emails.json @@ -1,10 +1,10 @@ [ - "crosstalk.im", - "ct.chat", - "crosstalk.chat", - "crosstalk.com", - "gamening.com", - "escargot.chat", - "escargot.com", - "nina.chat" + "crosstalk.im", + "ct.chat", + "crosstalk.chat", + "crosstalk.com", + "gamening.com", + "escargot.chat", + "escargot.com", + "nina.chat" ] \ No newline at end of file diff --git a/config/tabs.json b/config/tabs.json index a611ce8..f9703fa 100644 --- a/config/tabs.json +++ b/config/tabs.json @@ -2,19 +2,19 @@ { "id": 1, "url": "http://wiby.me/", - "image": "http://static.ugnet.gay/svc/tab/wiby.png", + "image": "http://static.ugnet.xyz/svc/tab/wiby.png", "tooltip": "Wiby" }, { "id": 2, "url": "http://theoldnet.com", - "image": "http://static.ugnet.gay/svc/tab/theoldnet.png", + "image": "http://static.ugnet.xyz/svc/tab/theoldnet.png", "tooltip": "TheOldNet" }, { "id": 3, "url": "http://classicconnect.net", - "image": "http://static.ugnet.gay/svc/tab/classicconnect.png", + "image": "http://static.ugnet.xyz/svc/tab/classicconnect.png", "tooltip": "ClassicConnect" } ] \ No newline at end of file diff --git a/config/textads.json b/config/textads.json index 7459bfe..7f31cfc 100644 --- a/config/textads.json +++ b/config/textads.json @@ -19,10 +19,6 @@ "caption": "Wiby - The search engine for the classic web.", "url": "http://wiby.me" }, - { - "caption": "Mac Secret - The worst kept secret in Macintosh archiving.", - "url": "http://macsecret.com" - }, { "caption": "Arch Linux - A simple, lightweight Linux distribution.", "url": "https://archlinux.org" @@ -31,14 +27,6 @@ "caption": "Gentoo - A highly flexible, source-based Linux distribution.", "url": "https://www.gentoo.org" }, - { - "caption": "NixOS - Reproducible, declarative, and reliable.", - "url": "https://nixos.org/" - }, - { - "caption": "Debian - The universal operating system.", - "url": "https://debian.org" - }, { "caption": "WebTV Redialed allows you to surf the web the fun way - on your TV. It's a replacement to the original WebTV service, and our sister project!", "url": "http://webtv.zone" @@ -87,10 +75,6 @@ "caption": "GrapheneOS is a private and secure Android-based operating system.", "url": "https://grapheneos.org/" }, - { - "caption": "BitView - Express Yourself.", - "url": "https://www.bitview.net/" - }, { "caption": "SpaceHey - a space for friends.", "url": "https://spacehey.com" diff --git a/config/whatsnew.json b/config/whatsnew.json deleted file mode 100644 index 468a9d6..0000000 --- a/config/whatsnew.json +++ /dev/null @@ -1,7 +0,0 @@ -[{ - "date": "2026-06-22T12:22:30Z", - "url": "https://crosstalk.im", - "title": "Update your e-mail if needed", - "appName": "CrossTalk News", - "content": "Any accounts using a blacklisted email address (such as @crosstalk.im, @escargot.chat, @webtv.zone etc) must change their email address to a real one by July 20, 2026 or your account will be deleted. We are preparing for 0.6’s release and this needs to be done to prevent issues with the upcoming aliasing system." -}] \ No newline at end of file diff --git a/core/abuse.py b/core/abuse.py new file mode 100644 index 0000000..577a7cc --- /dev/null +++ b/core/abuse.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +import asyncio, time + +from .models import User, MessageType + +if TYPE_CHECKING: + from .backend import Backend, BackendSession + +EVIL_DELTA = 100 +EVIL_DELTA_ANONYMOUS = 30 +EVIL_DECAY = 50 +EVIL_DECAY_INTERVAL = 300 +EVIL_MAX = 999 +CONVERSATION_WINDOW = 3600 + +RATED_MESSAGE_TYPES = frozenset({ MessageType.Chat, MessageType.Nudge, MessageType.Ink }) + +RATE_WINDOW = 20 +RATE_MAX = 6000 +RATE_LIMIT = 500 +RATE_CLEAR = 1500 +RATE_WARNING_SCALE = 250 + +class _RateState: + __slots__ = ('level', 'last', 'limited') + + level: float + last: float + limited: bool + + def __init__(self, now: float) -> None: + self.level = float(RATE_MAX) + self.last = now + self.limited = False + +class AbuseService: + __slots__ = ('backend', '_conversations', '_warnings', '_warned', '_rates', '_decay_task') + + backend: Backend + _conversations: dict[str, dict[str, list[float]]] + _warnings: dict[str, dict[str, list[float]]] + _warned: dict[str, User] + _rates: dict[str, _RateState] + _decay_task: asyncio.Task[None] | None + + def __init__(self, backend: Backend) -> None: + self.backend = backend + self._conversations = {} + self._warnings = {} + self._warned = {} + self._rates = {} + self._decay_task = None + + def warning_level(self, user: User) -> int: + return max(0, min(EVIL_MAX, int(user.evil_permanent or 0) + int(user.evil_temporary or 0))) + + def track_message(self, sender: User, recipient: User, *, now: float | None = None) -> None: + if sender is recipient: return + now = (time.time() if now is None else now) + times = self._conversations.setdefault(sender.uuid, {}).setdefault(recipient.uuid, []) + times.append(now) + del times[:-3] + + def may_warn(self, warner: User, warnee: User, *, now: float | None = None) -> bool: + if warner is warnee: return False + now = (time.time() if now is None else now) + received = [t for t in self._conversations.get(warnee.uuid, {}).get(warner.uuid, []) if now - t < CONVERSATION_WINDOW] + warns = self._warnings.setdefault(warner.uuid, {}).setdefault(warnee.uuid, []) + warns[:] = [t for t in warns if now - t < CONVERSATION_WINDOW] + if len(received) <= len(warns): + return False + warns.append(now) + return True + + def warn(self, warner: User, warnee: User, *, anonymous: bool, delta: int | None = None) -> tuple[int, int] | None: + level = self.warning_level(warnee) + if level >= EVIL_MAX or not self.may_warn(warner, warnee): + return None + if delta is None: + delta = (EVIL_DELTA_ANONYMOUS if anonymous else EVIL_DELTA) + delta = min(delta, EVIL_MAX - level) + warnee.evil_temporary = int(warnee.evil_temporary or 0) + delta + new_level = self.warning_level(warnee) + print(f"[Abuse] {warnee.username} ({warnee.email}) was warned ({'anonymously' if anonymous else 'by ' + warner.username}); their warning level is now {new_level}") + self._start_decay(warnee) + self.announce(warnee, (None if anonymous else warner)) + return delta, new_level + + def announce(self, user: User, warner: User | None) -> None: + level = self.warning_level(user) + sessions: list[BackendSession] = list(self.backend.util_get_sessions_by_user(user)) + for bs in sessions: + try: + bs.evt.on_warning_level_changed(level, warner) + except Exception: + import traceback + traceback.print_exc() + for bs in sessions: + if bs.closed: continue + bs.me_update({ 'needs_notify': True, 'notify_status': True }) + break + + def allow_message(self, user: User, *, now: float | None = None) -> bool: + now = (time.time() if now is None else now) + level = self.warning_level(user) + if level >= EVIL_MAX: + return False + state = self._rates.get(user.uuid) + if state is None: + state = self._rates[user.uuid] = _RateState(now) + return True + delta_ms = max(0.0, (now - state.last) * 1000) + state.last = now + state.level = min(float(RATE_MAX), ((RATE_WINDOW - 1) * state.level + delta_ms) / RATE_WINDOW) + scale = 1 + level / RATE_WARNING_SCALE + limit = RATE_LIMIT * scale + clear = min(RATE_CLEAR * scale, RATE_MAX * 0.95) + if state.limited: + if state.level < clear: + return False + state.limited = False + if state.level < limit: + state.limited = True + print(f"[Abuse] {user.username} ({user.email}) is sending messages too fast and is being rate limited") + return False + return True + + def is_rate_limited(self, user: User) -> bool: + state = self._rates.get(user.uuid) + return self.warning_level(user) >= EVIL_MAX or (state is not None and state.limited) + + def _start_decay(self, user: User) -> None: + self._warned[user.uuid] = user + if self._decay_task is None or self._decay_task.done(): + try: + self._decay_task = self.backend.loop.create_task(self._decay_warnings()) + except RuntimeError: + self._decay_task = None + + async def _decay_warnings(self) -> None: + while self._warned: + await asyncio.sleep(EVIL_DECAY_INTERVAL) + self.decay_once() + + def decay_once(self) -> None: + for uuid, user in list(self._warned.items()): + temporary = int(user.evil_temporary or 0) + user.evil_temporary = max(0, temporary - EVIL_DECAY) + if user.evil_temporary == 0: + del self._warned[uuid] + if user.evil_temporary != temporary and self.backend.util_get_sessions_by_user(user): + self.announce(user, None) diff --git a/core/alerts.py b/core/alerts.py new file mode 100644 index 0000000..9459d89 --- /dev/null +++ b/core/alerts.py @@ -0,0 +1,243 @@ +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import urlsplit +from xml.sax.saxutils import escape, quoteattr +import itertools, re, time + +import settings + +SITE_IDS = { 'stocks': 0, 'calendar': 1, 'bell': 2 } +ALIGNMENTS = ('left', 'center', 'right') +AGENTS = ('email', 'messenger', 'mobile') +MAX_BODY = 1024 +MAX_TEXT = 1000 +MSNP_NOT = 5 +MSNP_TEXTX = 9 + +Run = Tuple[str, bool, bool] +Line = List[Run] +Paragraph = List[Line] + +_next_id = itertools.count(int(time.time()) % 0xFFFFFFFF) + +def new_alert_id() -> int: + return next(_next_id) % 0x100000000 + +class AlertError(ValueError): + field: str + + def __init__(self, field: str, message: str) -> None: + super().__init__(message) + self.field = field + +def parse_rich(markup: str) -> List[Paragraph]: + paragraphs: list[Paragraph] = [] + text = markup.replace('\r\n', '\n').replace('\r', '\n').strip() + for block in re.split(r'\n[ \t]*\n\s*', text): + if not block.strip(): + continue + bold = italic = False + lines: list[Line] = [] + for raw in block.split('\n'): + runs: Line = [] + buf = '' + i = 0 + while i < len(raw): + ch = raw[i] + if ch == '\\' and i + 1 < len(raw): + buf += raw[i + 1] + i += 2 + continue + if ch == '*': + if buf: + runs.append((buf, bold, italic)) + buf = '' + if raw.startswith('**', i): + bold = not bold + i += 2 + else: + italic = not italic + i += 1 + continue + buf += ch + i += 1 + if buf: + runs.append((buf, bold, italic)) + lines.append(runs) + paragraphs.append(lines) + return paragraphs + +def plain_text(paragraphs: List[Paragraph]) -> str: + return '\n\n'.join('\n'.join(''.join(run[0] for run in line) for line in para) for para in paragraphs) + +def textx_document(paragraphs: List[Paragraph], align: str = 'left') -> str: + attrs = '' if align == 'left' else ' align="{}"'.format(align) + out = [] + for para in paragraphs: + lines = [] + for line in para: + parts = [] + for text, bold, italic in line: + part = escape(text) + if italic: + part = '' + part + '' + if bold: + part = '' + part + '' + parts.append(part) + lines.append(''.join(parts)) + out.append('{}

'.format(attrs, '
'.join(lines))) + return ''.join(out) + +def irc_lines(paragraphs: List[Paragraph]) -> List[str]: + out = [] + for para in paragraphs: + for line in para: + parts = [] + bold = italic = False + for text, run_bold, run_italic in line: + if run_bold != bold: + parts.append('\x02') + bold = run_bold + if run_italic != italic: + parts.append('\x1d') + italic = run_italic + parts.append(text) + if bold or italic: + parts.append('\x0f') + if ''.join(parts).strip(): + out.append(''.join(parts)) + return out + +def _origin(url: str) -> Optional[str]: + parts = urlsplit(url) + if parts.scheme not in ('http', 'https') or not parts.netloc: + return None + return '{}://{}'.format(parts.scheme, parts.netloc) + +def check_url(url: str, field: str) -> str: + url = url.strip() + if url and _origin(url) is None: + raise AlertError(field, 'Links have to be full http:// or https:// addresses.') + if len(url) > 500: + raise AlertError(field, 'That address is too long.') + return url + +@dataclass +class Alert: + text: str + rich: Optional[str] = None + align: str = 'left' + url: str = '' + subscr_url: str = '' + icon: str = '' + kind: str = 'bell' + lang: int = 1033 + priority: int = 1 + message_id: int = 0 + via: Optional[str] = None + email_text: Optional[str] = None + id: int = field(default_factory = new_alert_id) + + def __post_init__(self) -> None: + self.text = (self.text or '').strip() + self.rich = (self.rich or '').strip() or None + if self.rich and not self.text: + self.text = plain_text(parse_rich(self.rich)) + + def check(self, *, emailed: bool = False) -> 'Alert': + if not self.text: + raise AlertError('text', 'Write the alert first.') + if len(self.text) > MAX_TEXT: + raise AlertError('text', 'Alerts can be at most {} characters.'.format(MAX_TEXT)) + if self.align not in ALIGNMENTS: + raise AlertError('align', 'Alignment is left, center or right.') + if self.kind not in SITE_IDS: + raise AlertError('kind', 'The icon is bell, stocks or calendar (or a custom icon).') + if self.via is not None and self.via not in AGENTS: + raise AlertError('via', 'An alert comes from e-mail, messenger or mobile.') + if not (0 < self.lang < 0x10000): + raise AlertError('lang', 'The language is a Windows LCID, like 1033 for English (United States).') + if not (0 <= self.priority <= 0xFFFFFFFF and 0 <= self.message_id <= 0xFFFFFFFF): + raise AlertError('priority', 'Priority and message ID are 32-bit numbers.') + self.url = check_url(self.url, 'url') + self.subscr_url = check_url(self.subscr_url, 'subscr_url') + self.icon = check_url(self.icon, 'icon') + size = len(self._body(self.locations()[3], MSNP_TEXTX, emailed).replace('\n', '\r\n').encode('utf-8')) + if size > MAX_BODY: + raise AlertError('rich' if self.rich else 'text', 'That\'s too long for Messenger: an alert\'s body can be at most {} bytes, and this one is {}.'.format(MAX_BODY, size)) + return self + + @property + def paragraphs(self) -> List[Paragraph]: + return parse_rich(self.rich) if self.rich else [[[(line, False, False)] for line in para.split('\n')] for para in re.split(r'\n\s*\n', self.text)] + + @property + def site_id(self) -> int: + return SITE_IDS[self.kind] + + @property + def link(self) -> str: + return self.url or settings.ALERT_SITE_URL + + def plain(self) -> str: + return plain_text(parse_rich(self.rich)) if self.rich else self.text + + def plain_with_link(self) -> str: + return self.plain() + ('\n' + self.url if self.url else '') + + def locations(self) -> Tuple[str, str, str, str]: + action = self.link + subscr = self.subscr_url or action + icon = self.icon + urls = [u for u in (action, subscr, icon) if u] + origins = { _origin(u) for u in urls } + if len(origins) == 1 and None not in origins: + origin = origins.pop() + assert origin is not None + rel = lambda u: u[len(origin) + 1:] if u else '' + return (origin + '/', rel(action), rel(subscr), rel(icon)) + return ('', action, subscr, icon) + + def _body(self, icon: str, dialect: int, emailed: bool) -> str: + attrs = ' lang="{}"'.format(self.lang) + if icon: + attrs += ' icon={}'.format(quoteattr(icon)) + parts = ['{}'.format(escape(self.text))] + if emailed and self.email_text: + parts.append('{}'.format(escape(self.email_text))) + if dialect >= MSNP_TEXTX and (self.rich or self.align != 'left'): + parts.append('{}'.format(escape(textx_document(self.paragraphs, self.align)))) + return '\n\t\t\t{}\n\t\t'.format(attrs, '\n\t\t\t'.join(parts)) + + def notification(self, *, pid: str, name: str, dialect: int, email: Optional[str] = None) -> bytes: + siteurl, action, subscr, icon = self.locations() + to_attrs = 'pid={} name={}'.format(quoteattr(pid), quoteattr(name)) + if email: + to_attrs += ' email={}'.format(quoteattr(email)) + if self.via: + to = '\n\t\t\n\t'.format(to_attrs, quoteattr(self.via)) + else: + to = ''.format(to_attrs) + doc = ( + '\n' + '\t{to}\n' + '\t\n' + '\t\t\n' + '\t\t\n' + '\t\t{body}\n' + '\t\n' + '' + ).format( + id = self.id, siteid = self.site_id, siteurl = quoteattr(siteurl), to = to, pri = self.priority, mid = self.message_id, + action = quoteattr(action), subscr = quoteattr(subscr), body = self._body(icon, dialect, bool(email)), + ) + return doc.replace('\n', '\r\n').encode('utf-8') + + def summary(self) -> Dict[str, Any]: + return { + 'id': self.id, 'text': self.text, 'rich': self.rich, 'align': self.align, 'url': self.url, 'subscr_url': self.subscr_url, + 'icon': self.icon, 'kind': self.kind, 'lang': self.lang, 'priority': self.priority, 'via': self.via, + } + +def puid(high: int, low: int) -> str: + return '0x{:08x}:0x{:08x}'.format(high, low) diff --git a/core/backend.py b/core/backend.py index caa3323..cda4dd5 100644 --- a/core/backend.py +++ b/core/backend.py @@ -1,7 +1,8 @@ -from typing import Dict, List, Set, Any, Tuple, Optional, Iterable +from typing import Dict, List, Set, Any, Tuple, Optional, Iterable, Callable from abc import ABCMeta, abstractmethod -import asyncio, traceback, settings, smtplib, pprint -from collections import defaultdict +from datetime import datetime +import asyncio, traceback, settings, smtplib, pprint, re +from collections import defaultdict, deque from enum import IntFlag from util.misc import gen_uuid, first_in_iterable, run_loop, Runner, server_temp_cleanup @@ -10,11 +11,13 @@ from .user import UserService from .auth import AuthService, LoginAuthService, GenTokenStr from .stats import Stats from .client import Client +from .abuse import AbuseService, RATED_MESSAGE_TYPES from .models import ( User, UserDetail, Group, ContactList, OIM, Contact, ContactDetail, Circle, CircleRole, CircleState, CircleMembership, Chatroom, UserStatus, TextWithData, MessageData, MessageType, Substatus, LoginOption, _is_blocking, ) from . import error, event +from .alerts import Alert class Ack(IntFlag): Zero = 0 @@ -26,7 +29,8 @@ class Backend: __slots__ = ( 'user_service', 'auth_service', 'login_auth_service', 'loop', 'notify_maintenance', 'maintenance_mode', 'maintenance_mins', '_stats', '_sc', '_chats_by_id', '_cses_by_bs_by_circle_id', '_user_by_uuid', '_worklist_sync_db', '_worklist_sync_circles', - '_worklist_notify', '_worklist_notify_self', '_runners', '_linked', '_dev', + '_worklist_notify', '_worklist_notify_self', '_runners', '_linked', '_dev', 'recent_alerts', 'on_user_deleted', + '_watches', 'abuse', ) user_service: UserService @@ -48,7 +52,11 @@ class Backend: _runners: List[Runner] _linked: bool _dev: Optional[Any] - + recent_alerts: 'deque[Dict[str, Any]]' + on_user_deleted: Optional[Callable[[str, str], None]] + _watches: '_WatchRegistry' + abuse: AbuseService + def __init__(self, loop: asyncio.AbstractEventLoop, *, user_service: UserService, login_auth_service: LoginAuthService, auth_service: AuthService, stats_service: Stats, @@ -72,7 +80,11 @@ class Backend: self._runners = [] self._linked = False self._dev = None - + self.recent_alerts = deque(maxlen = 50) + self.on_user_deleted = None + self._watches = _WatchRegistry() + self.abuse = AbuseService(self) + server_temp_cleanup() for circle in self.user_service.get_all_circles(): self.chat_create(circle = circle) @@ -85,11 +97,15 @@ class Backend: loop.create_task(self._worker_sync_stats()) loop.create_task(self._worker_notify()) loop.create_task(self._worker_notify_self()) + loop.create_task(self._worker_purge_suspended()) - def push_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None: + def push_client_alert(self, alert: Alert) -> int: print(f"[Backend] Pushing system alert") + delivered = 0 for bs in self._sc.iter_sessions(): - bs.evt.on_client_alert(icon_url, url, message) + if bs.evt.on_client_alert(alert): + delivered += 1 + return delivered def push_maintenance_message(self, *args: Any, **kwargs: Any) -> None: print(f"[Backend] Server going down for maintenance in {args[1]} minutes. Pushing system alert") @@ -124,6 +140,8 @@ class Backend: old_substatus = user.status.substatus self._stats.on_logout() self._sc.remove_session(sess) + # a closed session's client-side buddy list goes with it + self._watches.remove_session(sess) print(f"[Presence] BackendSession {str(id(sess))} belonging to {user.username} ({user.email}) has been closed") if self._sc.get_sessions_by_user(user): # There are still other people logged in as this user, @@ -162,6 +180,7 @@ class Backend: self._stats.on_login() self._stats.on_user_active(user, client) self._sc.add_session(bs) + self._stats.on_online(self._sc.session_count()) user.detail = self._load_detail(user) print(f"[Presence] {user.username} ({user.email}) has logged in with BackendSession ID {str(id(bs))}") print(f"[Presence] They are using {client.program.upper()} {client.version} via {client.via}") @@ -177,6 +196,8 @@ class Backend: def _load_detail(self, user: User) -> UserDetail: if user.detail: return user.detail + pending = self._worklist_sync_db.get(user) + if pending is not None: return pending detail = self.user_service.get_detail(user.uuid) assert detail is not None return detail @@ -239,6 +260,20 @@ class Backend: def _notify_self(self, bs: 'BackendSession', old_substatus: Substatus, *, update_status: bool = True, update_info: bool = True) -> None: self._worklist_notify_self.append((bs, old_substatus, update_status, update_info)) + def notify_whats_new(self, user: User) -> None: + # `user` has a new "What's New" activity: their own places and every contact watching them get to refetch it + for bs in self._sc.get_sessions_by_user(user): + bs.evt.msn_on_whats_new(user) + detail = self._load_detail(user) + for ctc in detail.contacts.values(): + if ctc.lists & ContactList.BL: continue + for bs_other in self._sc.get_sessions_by_user(ctc.head): + detail_other = bs_other.user.detail + if detail_other is None: continue + ctc_me = detail_other.contacts.get(user.uuid) + if ctc_me is None or not ctc_me.lists & ContactList.FL: continue + bs_other.evt.msn_on_whats_new(user) + def _mark_modified(self, user: User, *, detail: Optional[UserDetail] = None) -> None: ud = user.detail or detail if detail: assert ud is detail @@ -263,6 +298,54 @@ class Backend: def util_get_uuid_from_user_id(self, uid: int) -> Optional[str]: return self.user_service.get_uuid_user_id(uid) + def util_get_uuid_from_uin(self, uin: int) -> Optional[str]: + return self.user_service.get_uuid_uin(uin) + + def util_get_uuid_from_screenname(self, name: str) -> Optional[str]: + # OSCAR and ICQ name an account by its screen name or by its UIN; an all-digit name is tried as a UIN first, + # falling back to a screen name that happens to be all digits + name = name.replace(' ', '') + if _UIN_RE.match(name) is not None: + uuid = self.util_get_uuid_from_uin(int(name)) + if uuid is not None: + return uuid + return self.util_get_uuid_from_username(name) + + def util_get_uuids_for_login(self, name: str) -> List[str]: + # every account a login name could mean, so a numeric screen name and someone else's UIN can both still sign on + name = name.replace(' ', '') + uuids = [] # type: List[str] + if _UIN_RE.match(name) is not None: + uuid = self.util_get_uuid_from_uin(int(name)) + if uuid is not None: + uuids.append(uuid) + uuid = self.util_get_uuid_from_username(name) + if uuid is not None and uuid not in uuids: + uuids.append(uuid) + return uuids + + def util_watch(self, bs: 'BackendSession', uuid: str) -> None: + # a session-only interest in someone's presence (OSCAR's client-side buddy list), kept out of the stored contact list + self._watches.add(bs, uuid) + + def util_unwatch(self, bs: 'BackendSession', uuid: str) -> None: + self._watches.remove(bs, uuid) + + def util_unwatch_all(self, bs: 'BackendSession') -> None: + self._watches.remove_session(bs) + + def util_get_watched(self, bs: 'BackendSession') -> Set[str]: + return self._watches.watched_by(bs) + + def util_get_watchers(self, uuid: str) -> List['BackendSession']: + return self._watches.watchers_of(uuid) + + def util_message_allowed(self, user: User, data: MessageData) -> bool: + if data.type not in RATED_MESSAGE_TYPES: return True + if 'abuse_allowed' not in data.front_cache: + data.front_cache['abuse_allowed'] = self.abuse.allow_message(user) + return bool(data.front_cache['abuse_allowed']) + def util_set_sess_token(self, sess: 'BackendSession', token: str) -> None: self._sc.set_nc_by_token(sess, token) @@ -272,6 +355,177 @@ class Backend: def util_get_sessions_by_user(self, user: User) -> List['BackendSession']: return self._sc.get_sessions_by_user(user) + def util_contact_groups(self, user: User) -> List[Group]: + detail = self._load_detail(user) + return sorted(detail._groups_by_id.values(), key = lambda group: (not group.is_favorite, group.name.lower())) + + def util_add_contact( + self, user: User, contact_uuid: str, *, group_id: Optional[str] = None, new_group: Optional[str] = None, + ) -> Tuple[bool, Optional[Group]]: + detail = self._load_detail(user) + group = None + if group_id is not None: + group = detail.get_group_by_id(group_id) + if group is None: + raise error.GroupDoesNotExist() + old_ctc = detail.contacts.get(contact_uuid) + already = old_ctc is not None and bool(old_ctc.lists & ContactList.FL) and bool(old_ctc.lists & ContactList.AL) + if group is not None and old_ctc is not None and old_ctc.lists & ContactList.FL and old_ctc.group_in_entry(group): + group = None + if already and group is None and new_group is None: + return False, None + sessions = self._sc.get_sessions_by_user(user) + if sessions: + session = sessions[0] # type: Any + else: + session = _OfflineSessionShim(self, user) + user.detail = detail + try: + if new_group is not None: + group = BackendSession.me_group_add(session, new_group) + if not already: + BackendSession.me_contact_add(session, contact_uuid, ContactList.FL | ContactList.AL, needs_notify = True) + if group is not None: + BackendSession.me_group_contact_add(session, group.id, contact_uuid) + finally: + if not sessions: + user.detail = None + for bs in sessions: + bs.evt.msn_on_notify_ab() + return not already, group + + def util_add_group(self, user: User, name: str) -> Group: + detail = self._load_detail(user) + sessions = self._sc.get_sessions_by_user(user) + if sessions: + session = sessions[0] # type: Any + else: + session = _OfflineSessionShim(self, user) + user.detail = detail + try: + group = BackendSession.me_group_add(session, name) + finally: + if not sessions: + user.detail = None + for bs in sessions: + bs.evt.msn_on_notify_ab() + return group + + def util_contact_states(self, user: User, uuids: Iterable[str]) -> Dict[str, str]: + detail = self._load_detail(user) + states: dict[str, str] = {} + for uuid in uuids: + if uuid == user.uuid: + states[uuid] = 'self' + continue + ctc = detail.contacts.get(uuid) + if ctc is None or not ctc.lists & ContactList.FL: + states[uuid] = 'none' + elif ctc.lists & ContactList.BL: + states[uuid] = 'blocked' + else: + states[uuid] = 'contact' + return states + + def util_delete_circle(self, circle: Circle) -> List[User]: + members = [membership.head for membership in circle.memberships.values() if membership.state != CircleState.Empty] + chat = self.chat_get('persistent', circle.chat_id) + if chat is not None: + for cs in list(chat.get_roster()): + cs.close() + for scope, chat_id in list(chat.ids.items()): + self._chats_by_id.pop((scope, chat_id), None) + self._cses_by_bs_by_circle_id.pop(circle.chat_id, None) + self._worklist_sync_circles.pop(circle.chat_id, None) + self.user_service.delete_circle(circle.chat_id) + for user in members: + for bs in self.util_get_sessions_by_user(user): + bs.evt.on_left_circle(circle) + print(f'[Circle] {circle.name} (ID: {circle.chat_id}) has been deleted') + return members + + def util_delete_user(self, uuid: str) -> Optional[User]: + user = self._load_user_record(uuid) + if user is None: + return None + for bs in self.util_get_sessions_by_user(user): + try: + bs.close() + except Exception: + traceback.print_exc() + for other in list(self._user_by_uuid.values()): + if other is not user and other.detail is not None: + other.detail.contacts.pop(uuid, None) + for pending in self._worklist_sync_db.values(): + if pending is not None: + pending.contacts.pop(uuid, None) + self._worklist_sync_db.pop(user, None) + + new_owners: dict[str, Circle] = {} + for circle in self.user_service.get_all_circles(): + membership = circle.memberships.get(uuid) + if membership is None and circle.owner_uuid != uuid: + continue + others = sorted(( + m for m in circle.memberships.values() + if m.head.uuid != uuid and m.state == CircleState.Accepted and CircleRole.Admin <= m.role <= CircleRole.Member + ), key = lambda m: int(m.role)) + admins_left = [m for m in others if m.role == CircleRole.Admin] + was_admin = membership is not None and membership.role == CircleRole.Admin and membership.state != CircleState.Empty + if circle.owner_uuid == uuid or (was_admin and not admins_left): + if not others: + self.util_delete_circle(circle) + continue + successor = others[0] + successor.role = CircleRole.Admin + if circle.owner_uuid == uuid: + circle.owner_id = successor.head.id + circle.owner_uuid = successor.head.uuid + circle.owner_friendly = successor.head.status.name or successor.head.email + new_owners[circle.chat_id] = circle + print(f"[Circle] {successor.head.username} ({successor.head.email}) now runs {circle.name} (ID: {circle.chat_id})") + circle.memberships.pop(uuid, None) + chat = self.chat_get('persistent', circle.chat_id) + if chat is not None: + for cs_other in chat.get_roster(): + if cs_other.user is not user: + cs_other.bs.evt.on_circle_updated(circle) + self._mark_circle_modified(circle) + + if not self.user_service.delete_user(uuid, new_owners): + return None + self._user_by_uuid.pop(uuid, None) + return user + + def util_purge_suspended(self, now: Optional[datetime] = None) -> List[str]: + days = getattr(settings, 'SUSPENDED_ACCOUNT_DAYS', None) + if days is None: + return [] + deleted = [] + for uuid in self.user_service.expired_suspensions(int(days), now): + try: + user = self.util_delete_user(uuid) + except Exception: + traceback.print_exc() + continue + if user is None: + continue + print(f"[Backend] {user.username} ({user.email}) was suspended over {days} days ago and has been deleted") + deleted.append(uuid) + if self.on_user_deleted is not None: + self.on_user_deleted(uuid, 'suspended') + return deleted + + def util_contact_state(self, user: User, contact: User) -> str: + if user.uuid == contact.uuid: + return 'self' + ctc = self._load_detail(user).contacts.get(contact.uuid) + if ctc is None or not ctc.lists & ContactList.FL: + return 'none' + if ctc.lists & ContactList.BL: + return 'blocked' + return 'contact' + def util_get_circle_memberships_by_role(self, circle: Circle, role: CircleRole) -> Iterable[CircleMembership]: return [membership for membership in circle.memberships.values() if membership.role == role] @@ -350,6 +604,7 @@ class Backend: membership.role = CircleRole.Member membership.state = CircleState.Empty + membership_inviter_email = membership.inviter_email if membership.inviter_uuid is not None: membership.inviter_uuid = None if membership.inviter_email is not None: @@ -361,7 +616,7 @@ class Backend: for bs_other in self.util_get_sessions_by_user(user): print(f"[Circle] {user.username} ({user.email})'s invitation to {circle.name} (ID: {circle.chat_id}) has been revoked") - if membership_inviter_email is not None: print(f"[Circle] It was sent by {membership.inviter_email}") + if membership_inviter_email is not None: print(f"[Circle] It was sent by {membership_inviter_email}") bs_other.evt.on_circle_invite_revoked(circle.chat_id) if chat is not None: @@ -483,6 +738,15 @@ class Backend: except: traceback.print_exc() + async def _worker_purge_suspended(self) -> None: + await asyncio.sleep(60) + while True: + try: + self.util_purge_suspended() + except Exception: + traceback.print_exc() + await asyncio.sleep(3600) + async def _worker_sync_circles(self) -> None: while True: await asyncio.sleep(0.04) @@ -520,7 +784,7 @@ class Backend: while True: await asyncio.sleep(60) try: - self._stats.flush() + self._stats.flush(online = self._sc.session_count()) except: traceback.print_exc() @@ -539,8 +803,7 @@ class Backend: for bs, sess_id, on_contact_add, old_substatus, updated_phone_info, update_status, update_info_other, for_logout in worklist: user = bs.user detail = user.detail - assert detail is not None - for ctc in detail.contacts.values(): + for ctc in (detail.contacts.values() if detail is not None else ()): for bs_other in self._sc.get_sessions_by_user(ctc.head): if bs_other.user is user: continue detail_other = bs_other.user.detail @@ -554,6 +817,15 @@ class Backend: ctc_me, on_contact_add, old_substatus, sess_id = sess_id, updated_phone_info = updated_phone_info, update_status = update_status, update_info_other = update_info_other, ) + # sessions that only watch `user` through a client-side buddy list, and weren't told above + for bs_other in self._watches.watchers_of(user.uuid): + if bs_other.user is user: continue + if detail is not None: + if _sees_through_list(user, detail, bs_other.user) or _is_blocking(user, bs_other.user): continue + bs_other.evt.on_presence_notification( + _watch_contact(user, bs_other.user), on_contact_add, old_substatus, sess_id = sess_id, + updated_phone_info = updated_phone_info, update_status = update_status, update_info_other = update_info_other, + ) for circle in self.user_service.get_circle_batch(user): if circle.chat_id not in self._cses_by_bs_by_circle_id: continue if bs not in self._cses_by_bs_by_circle_id[circle.chat_id]: continue @@ -599,6 +871,19 @@ class Session(metaclass = ABCMeta): @abstractmethod def _on_close(self, **kwargs: Any) -> None: pass +class _OfflineSessionShim: + __slots__ = ('backend', 'user') + + backend: Backend + user: User + + def __init__(self, backend: Backend, user: User) -> None: + self.backend = backend + self.user = user + + def _add_to_list(self, *args: Any, **kwargs: Any) -> Contact: + return BackendSession._add_to_list(self, *args, **kwargs) # type: ignore + class BackendSession(Session): __slots__ = ('backend', 'user', 'client', 'chat_enabled', 'evt', 'front_data') @@ -733,7 +1018,44 @@ class BackendSession(Session): ) if notify_self: self.backend._notify_self(self, old_substatus, update_status = notify_status, update_info = notify_info_other) + + def me_visibility_snapshot(self) -> Dict[str, bool]: + # which of the contacts that have us on their list can currently see us + user = self.user + detail = user.detail + if detail is None: return {} + snapshot = {} # type: Dict[str, bool] + for ctc in detail.contacts.values(): + if not ctc.lists & ContactList.RL: continue + snapshot[ctc.head.uuid] = not _is_blocking(user, ctc.head) + # client-side buddy lists can see us too, without any list linking us + for bs_other in self.backend._watches.watchers_of(user.uuid): + if bs_other.user is user or bs_other.user.uuid in snapshot: continue + snapshot[bs_other.user.uuid] = not _is_blocking(user, bs_other.user) + return snapshot + def me_visibility_changed(self, before: Dict[str, bool]) -> None: + # push an arrival/departure to every contact whose view of us changed since `before` was taken + backend = self.backend + user = self.user + detail = user.detail + if detail is None or user.status.substatus is Substatus.Offline: return + after = self.me_visibility_snapshot() + backend._sync_contact_statuses(user) + for uuid, visible in after.items(): + if before.get(uuid) == visible: continue + ctc = detail.contacts.get(uuid) + if ctc is not None: + for sess_other in backend._sc.get_sessions_by_user(ctc.head): + detail_other = sess_other.user.detail + if detail_other is None: continue + ctc_me = detail_other.contacts.get(user.uuid) + if ctc_me is None or not ctc_me.lists & ContactList.FL: continue + sess_other.evt.on_presence_notification(ctc_me, False, user.status.substatus) + for sess_other in backend._watches.watchers_of(user.uuid): + if sess_other.user.uuid != uuid or _sees_through_list(user, detail, sess_other.user): continue + sess_other.evt.on_presence_notification(_watch_contact(user, sess_other.user), False, user.status.substatus) + def me_group_add(self, name: str, *, is_favorite: Optional[bool] = None) -> Group: if len(name) > MAX_GROUP_NAME_LENGTH: raise error.GroupNameTooLong() @@ -1043,7 +1365,7 @@ class BackendSession(Session): invite_msg = f"""\ Subject: {sender_email} wants to talk to you using CrossTalk! To: {email} -From: undergr0und network administration +From: CrossTalk network administration This e-mail was sent to you because {sender_info} wants to chat with you using the CrossTalk service, and you don't have an account. @@ -1066,7 +1388,7 @@ They've attached this message, as well: with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) as server: server.starttls() server.login(settings.SMTP_USERNAME, settings.SMTP_PASSWORD) - server.sendmail("administration@ugnet.gay", email, invite_msg) + server.sendmail("administration@ugnet.xyz", email, invite_msg) else: print(f"[Mailer] {sender_email} already has an account. Not sending an invitation e-mail.") @@ -1302,6 +1624,9 @@ class _SessionCollection: def iter_sessions(self) -> Iterable[BackendSession]: yield from self._sessions + def session_count(self) -> int: + return len(self._sessions) + def set_nc_by_token(self, sess: BackendSession, token: str) -> None: self._sess_by_token[token] = sess self._tokens_by_sess[sess].add(token) @@ -1464,13 +1789,6 @@ class Chat: last_pop = False - if len(self._users_by_sess) == 1 and self.circle is None: - _, last_user = next(iter(self._users_by_sess.values())) - if last_user == su[0]: - for scope_id in self.ids: - del self.backend._chats_by_id[scope_id] - last_pop = True - sess_others = [sess_other for sess_other in self._users_by_sess.keys() if sess_other.user is su[0]] if sess_others: @@ -1481,7 +1799,9 @@ class Chat: break if no_primary_pop: sess_others[-1].primary_pop = True - elif last_pop: + else: + # `sess` was the user's last place in the chat: they've left it (every frontend tells its clients then; with MPoP, + # the places before it leaving are only for the clients that show places) last_pop = True # Notify others that `sess` has left @@ -1543,37 +1863,57 @@ class ChatSession(Session): if len(ctc_sessions) == len(disabled_sessions): raise error.ContactNotOnline() if len(ctc_sessions) == len(already_invited_sessions): raise error.ContactAlreadyOnContactList() - def send_message_to_everyone(self, data: MessageData) -> None: + def send_message_to_everyone(self, data: MessageData) -> bool: stats = self.chat._stats client = self.bs.client - - if stats and data.type == MessageType.Chat or MessageType.Nudge or MessageType.Emoticon or MessageType.Ink: + backend = self.bs.backend + + if client.program not in _UNRATED_PROGRAMS and not backend.util_message_allowed(self.user, data): return False + + if stats and data.type in _STATS_MESSAGE_TYPES: stats.on_message_sent(self.user, client) stats.on_user_active(self.user, client) - - for cs_other in self.chat._users_by_sess.keys(): + + tracked: Set[str] = set() + for cs_other in list(self.chat._users_by_sess.keys()): if cs_other is self: continue if self.chat.circle is not None and self.chat.circle.memberships[cs_other.user.uuid].blocking: continue cs_other.evt.on_message(data) print(f"[Chat] {self.user.username} ({self.user.email}) has sent a messasge to {cs_other.user.username} ({cs_other.user.email}) of type {data.type}") if stats: stats.on_message_received(cs_other.user, client) - - def send_message_to_user(self, user_uuid: str, data: MessageData) -> None: + if data.type in RATED_MESSAGE_TYPES and cs_other.user.uuid not in tracked and 'abuse_tracked' not in data.front_cache: + tracked.add(cs_other.user.uuid) + backend.abuse.track_message(self.user, cs_other.user) + if tracked: + data.front_cache['abuse_tracked'] = True + return True + + def send_message_to_user(self, user_uuid: str, data: MessageData) -> bool: stats = self.chat._stats client = self.bs.client - - if stats and data.type == MessageType.Chat or MessageType.Nudge or MessageType.Emoticon or MessageType.Ink: + backend = self.bs.backend + + if client.program not in _UNRATED_PROGRAMS and not backend.util_message_allowed(self.user, data): return False + + if stats and data.type in _STATS_MESSAGE_TYPES: stats.on_message_sent(self.user, client) stats.on_user_active(self.user, client) - - for cs_other in self.chat._users_by_sess.keys(): + + tracked = False + for cs_other in list(self.chat._users_by_sess.keys()): if cs_other is self: continue if cs_other.user.uuid != user_uuid: continue print(f"[Chat] {self.user.username} ({self.user.email}) has sent a messasge to {cs_other.user.username} ({cs_other.user.email}) of type {data.type}") cs_other.evt.on_message(data) - if stats and data.type == MessageType.Chat or MessageType.Nudge or MessageType.Emoticon or MessageType.Ink: + if stats and data.type in _STATS_MESSAGE_TYPES: stats.on_message_received(cs_other.user, client) + if data.type in RATED_MESSAGE_TYPES and not tracked and 'abuse_tracked' not in data.front_cache: + tracked = True + backend.abuse.track_message(self.user, cs_other.user) + if tracked: + data.front_cache['abuse_tracked'] = True + return True def _gen_group_id(detail: UserDetail) -> str: id = 1 @@ -1595,10 +1935,62 @@ def _gen_contact_id(detail: UserDetail) -> str: MAX_GROUP_NAME_LENGTH = 61 +_STATS_MESSAGE_TYPES = (MessageType.Chat, MessageType.Nudge, MessageType.Emoticon, MessageType.Ink) + + # TODO: PL LST_LIMITS = { ContactList.FL: 1000, ContactList.AL: 1500, ContactList.BL: 1200, ContactList.RL: 1500, -} \ No newline at end of file +} +_UIN_RE = re.compile(r'^[0-9]{1,10}$') + +class _WatchRegistry: + __slots__ = ('_watchers_by_uuid', '_watched_by_sess') + + _watchers_by_uuid: Dict[str, Set['BackendSession']] + _watched_by_sess: Dict['BackendSession', Set[str]] + + def __init__(self) -> None: + self._watchers_by_uuid = {} + self._watched_by_sess = {} + + def add(self, bs: 'BackendSession', uuid: str) -> None: + self._watchers_by_uuid.setdefault(uuid, set()).add(bs) + self._watched_by_sess.setdefault(bs, set()).add(uuid) + + def remove(self, bs: 'BackendSession', uuid: str) -> None: + watchers = self._watchers_by_uuid.get(uuid) + if watchers is not None: + watchers.discard(bs) + if not watchers: + del self._watchers_by_uuid[uuid] + watched = self._watched_by_sess.get(bs) + if watched is not None: + watched.discard(uuid) + if not watched: + del self._watched_by_sess[bs] + + def remove_session(self, bs: 'BackendSession') -> None: + for uuid in list(self._watched_by_sess.get(bs, ())): + self.remove(bs, uuid) + + def watched_by(self, bs: 'BackendSession') -> Set[str]: + return set(self._watched_by_sess.get(bs, ())) + + def watchers_of(self, uuid: str) -> List['BackendSession']: + return [bs for bs in self._watchers_by_uuid.get(uuid, ()) if not bs.closed] + +def _sees_through_list(user: User, detail: UserDetail, other: User) -> bool: + if other.uuid not in detail.contacts: return False + detail_other = other.detail + if detail_other is None: return False + ctc_me = detail_other.contacts.get(user.uuid) + return ctc_me is not None and bool(ctc_me.lists & ContactList.FL) + +def _watch_contact(user: User, viewer: User) -> Contact: + ctc = Contact(user, set(), ContactList.Empty, UserStatus(user.status.name), ContactDetail('0')) + ctc.compute_visible_status(viewer) + return ctc diff --git a/core/db.py b/core/db.py index 37432b0..0afa5dc 100644 --- a/core/db.py +++ b/core/db.py @@ -48,9 +48,9 @@ class User(WithFrontData): uuid = Col(sa.String(50), unique = True) email = Col(sa.String(80, collation='utf8mb4_unicode_ci'), nullable=False, unique=True) username = Col(sa.String(40, collation='utf8mb4_unicode_ci'), nullable=False, unique=True) - first_name = Col(sa.String(50), default = 'John') + first_name = Col(sa.String(50), nullable = True) middle_name = Col(sa.String(50), nullable = True) - last_name = Col(sa.String(50), default = 'Doe') + last_name = Col(sa.String(50), nullable = True) # specifically used for social features/member directory nickname = Col(sa.String(60), nullable = True) uin = Col(sa.BigInteger, nullable = True) @@ -68,6 +68,7 @@ class User(WithFrontData): groups = Col(JSONType) settings = Col(JSONType) suspended = Col(sa.Boolean) + suspended_at = Col(sa.DateTime, nullable = True) is_tester = Col(sa.Boolean) is_mvp = Col(sa.Boolean) show_in_dir = Col(sa.Boolean) @@ -76,6 +77,7 @@ class User(WithFrontData): alias_active = Col(sa.Boolean, default=False) did_firsttime_email_change = Col(sa.Boolean, default=False) account_verified = Col(sa.Boolean, default=False) # for e-mail address verification + is_admin = Col(sa.Boolean, default = False, server_default = sa.false()) lang = Col(sa.String(10), nullable = True) avatar = Col(sa.String(16), nullable = True) profile = relationship("UserProfile", backref="user", uselist=False, cascade="all, delete-orphan") @@ -131,7 +133,7 @@ class UserProfile(WithFrontData): state = Col(sa.String(80), nullable = True) zip = Col(sa.Integer, nullable = True) country = Col(sa.String(60), nullable = True) - language = Col(sa.String(50), nullable = True) + language = Col(JSONType, nullable = True) interests = Col(JSONType, nullable = True, default = {}) visibility = Col(sa.String(25), default='public') @@ -172,6 +174,68 @@ class Sound(Base): is_public = Col(sa.Boolean) hits = Col(sa.Integer, default = 0) +class Activity(Base): + __tablename__ = 'user_activity' + + id = Col(sa.Integer, primary_key = True) + # `None` for service announcements + user_uuid = Col(sa.String(50), sa.ForeignKey('user.uuid'), nullable = True, index = True) + type = Col(sa.Integer) + title = Col(sa.String(100), nullable = True) + text = Col(sa.String(255), nullable = True) + url = Col(sa.String(255), nullable = True) + date_created = Col(sa.DateTime, default = datetime.utcnow, index = True) + +class ActivityReaction(Base): + __tablename__ = 'user_activity_reaction' + __table_args__ = (sa.UniqueConstraint('activity_id', 'user_uuid', 'reaction'),) + + id = Col(sa.Integer, primary_key = True) + activity_id = Col(sa.Integer, index = True) + user_uuid = Col(sa.String(50), index = True) + reaction = Col(sa.String(64)) + date_created = Col(sa.DateTime, default = datetime.utcnow) + +class ActivityComment(Base): + __tablename__ = 'user_activity_comment' + + id = Col(sa.Integer, primary_key = True) + activity_id = Col(sa.Integer, index = True) + user_uuid = Col(sa.String(50), index = True) + text = Col(sa.String(255, collation='utf8mb4_unicode_ci')) + date_created = Col(sa.DateTime, default = datetime.utcnow) + +class InsClient(Base): + __tablename__ = 'ins_client' + + id = Col(sa.Integer, primary_key = True) + identifier = Col(sa.String(64)) + label = Col(sa.String(100), default = '') + transport_public = Col(sa.String(64), unique = True) + auth_public = Col(sa.String(64)) + machine = Col(sa.String(64)) + addresses = Col(JSONType) + date_created = Col(sa.DateTime, default = datetime.utcnow) + date_last_seen = Col(sa.DateTime, nullable = True) + last_address = Col(sa.String(64), nullable = True) + revoked = Col(sa.Boolean, default = False) + date_revoked = Col(sa.DateTime, nullable = True) + +class InsEnrollment(Base): + __tablename__ = 'ins_enrollment' + + id = Col(sa.Integer, primary_key = True) + code_id = Col(sa.String(32), unique = True) + secret_hash = Col(sa.String(64)) + identifier = Col(sa.String(64)) + label = Col(sa.String(100), default = '') + address = Col(sa.String(64), nullable = True) + created_by = Col(sa.String(50), nullable = True) + date_created = Col(sa.DateTime, default = datetime.utcnow) + date_expires = Col(sa.DateTime) + date_used = Col(sa.DateTime, nullable = True) + client_id = Col(sa.Integer, nullable = True) + class LoginToken(Base): __tablename__ = 'login_token' @@ -195,6 +259,29 @@ def _simplify_json_data(data: Any) -> Any: return [_simplify_json_data(x) for x in data] return data +def ensure_schema(engine: Any) -> list[str]: + changed: list[str] = [] + inspector = sa.inspect(engine) + tables = set(inspector.get_table_names()) + for table in (InsClient.__table__, InsEnrollment.__table__): + if table.name not in tables: + table.create(engine) + changed.append(table.name) + if 'user' in tables: + columns = { column['name'] for column in inspector.get_columns('user') } + quote = engine.dialect.identifier_preparer.quote + if 'is_admin' not in columns: + false = str(sa.false().compile(dialect = engine.dialect)) + with engine.begin() as conn: + conn.execute(sa.text('ALTER TABLE {} ADD COLUMN {} BOOLEAN NOT NULL DEFAULT {}'.format(quote('user'), quote('is_admin'), false))) + changed.append('user.is_admin') + if 'suspended_at' not in columns: + kind = sa.DateTime().compile(dialect = engine.dialect) + with engine.begin() as conn: + conn.execute(sa.text('ALTER TABLE {} ADD COLUMN {} {} NULL'.format(quote('user'), quote('suspended_at'), kind))) + changed.append('user.suspended_at') + return changed + engine = sa.create_engine(settings.DB, echo='debug' if settings.DEBUG and settings.DEBUG_FULL and settings.DEBUG_LOG_SQL_QUERIES else None) session_factory = sessionmaker(bind = engine) diff --git a/core/event.py b/core/event.py index 6f07874..3ec959f 100644 --- a/core/event.py +++ b/core/event.py @@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Optional, Dict, Any, List from abc import ABCMeta, abstractmethod from .models import User, Contact, OIM, Circle, CircleRole, MessageData, TextWithData, Substatus, LoginOption +from .alerts import Alert from util.misc import MultiDict if TYPE_CHECKING: @@ -26,12 +27,15 @@ class BackendEventHandler(metaclass = ABCMeta): def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None: pass - def on_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None: - pass + def on_client_alert(self, alert: Alert) -> bool: + return False def on_maintenance_boot(self) -> None: pass - + + def on_warning_level_changed(self, level: int, warner: Optional[User]) -> None: + pass + @abstractmethod def on_presence_notification( self, ctc: Contact, on_contact_add: bool, old_substatus: Substatus, *, @@ -92,17 +96,23 @@ class BackendEventHandler(metaclass = ABCMeta): pass def msn_on_uun_sent( - self, sender: User, type: int, data: Optional[bytes], *, - pop_id_sender: Optional[str] = None, pop_id: Optional[str] = None, + self, sender: User, type: Optional[int], data: Optional[bytes], *, + pop_id_sender: Optional[str] = None, pop_id: Optional[str] = None, sdg: Optional[bytes] = None, ) -> None: pass def msn_on_notify_ab(self) -> None: pass + def msn_on_whats_new(self, publisher: User) -> None: + pass + def msn_on_notify_circle_ab(self, chat_id: str) -> None: pass + def msn_on_page(self, sender: User, text: str) -> bool: + return False + def ymsg_on_p2p_msg_request(self, sess_id: int, yahoo_data: MultiDict[bytes, bytes]) -> None: pass @@ -115,7 +125,74 @@ class BackendEventHandler(metaclass = ABCMeta): def ymsg_on_upload_file_ft(self, recipient: str, message: str) -> None: pass + + def ymsg_on_friend_icon(self, yahoo_id_sender: str, yahoo_id_receiver: str, checksum: bytes) -> None: + pass + def ymsg_on_friend_icon_download(self, yahoo_id_sender: str, yahoo_id_receiver: str, url: str, checksum: bytes) -> None: + pass + + def ymsg_on_friend_icon_file_transfer(self, yahoo_id_sender: str, yahoo_id_receiver: str, url: str, filename: str, ts: str) -> None: + pass + + def ymsg_on_friend_icon_flag(self, yahoo_id_sender: str, yahoo_id_receiver: str, icon_flag: bytes) -> None: + pass + + def ymsg_on_audible(self, sender: str, receiver: str, audible_id: bytes, text: bytes, checksum: bytes) -> None: + pass + + def ymsg_on_im_panel_feature(self, sender: str, receiver: str, feature: bytes, state: bytes) -> None: + pass + + def ymsg_on_im_session(self, sender: str, receiver: str, flag: bytes) -> None: + pass + + def ymsg_on_message_ack(self, sender: str, receiver: str, msg_id: bytes) -> None: + pass + + def ymsg_on_imvironment(self, sender: str, receiver: str, imv: bytes, state: bytes) -> None: + pass + + def ymsg_on_buddy_response(self, buddy: User, accepted: bool, message: str = '') -> None: + pass + + def ymsg_on_photo_add( + self, sender: str, receiver: str, photo_id: bytes, + name: Optional[bytes], thumbnail: Optional[bytes], url: Optional[bytes], + ) -> None: + pass + + def ymsg_on_photo_ack(self, sender: str, receiver: str, photo_id: bytes) -> None: + pass + + def ymsg_on_photo_select(self, sender: str, receiver: str, photo_id: bytes, action: bytes) -> None: + pass + + def ymsg_on_photo_relay( + self, sender: str, receiver: str, photo_id: bytes, token: bytes, *, + relay_host: bytes, filesize: Optional[bytes], ack: bool, + ) -> None: + pass + + def ymsg_on_ft_invite(self, sender: str, receiver: str, cookie: bytes, yahoo_data: MultiDict[bytes, bytes]) -> None: + pass + + def ymsg_on_ft_setup( + self, sender: str, receiver: str, cookie: bytes, *, + filename: bytes, relay_host: bytes, peer_path: bytes, transfer_type: bytes, + ) -> None: + pass + + def ymsg_on_ft_init( + self, sender: str, receiver: str, cookie: bytes, yahoo_data: MultiDict[bytes, bytes], *, cancelled: bool = False, + ) -> None: + pass + + def ymsg_on_sip_invite(self, caller: str, callee: str, call_id: str, sdp: str, *, video: bool = False) -> None: + pass + + def ymsg_on_sip_bye(self, caller: str, callee: str, call_id: str) -> None: + pass class ChatEventHandler(metaclass = ABCMeta): __slots__ = ('cs',) diff --git a/core/http.py b/core/http.py index 19e8986..754a915 100644 --- a/core/http.py +++ b/core/http.py @@ -25,7 +25,9 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, *, devmode: bool backend.add_runner(AIOHTTPRunner(http_host, http_port, app, ssl_context=ssl_context, service='HTTP')) app.router.add_get('/', handle_misc_conns) app.router.add_post('/', handle_blankok) + # TODO: migrate to static.ugnet.xyz app.router.add_static('/static', 'core/static') + # TODO: move ads / avatars out of azul and into their own svcs app.router.add_get('/ads/txt', handle_textad) app.router.add_get('/ads/banner', handle_bannerad) app.router.add_get('/ads/banner-lg', lambda req: handle_bannerad(req, yuge=True)) @@ -34,8 +36,7 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, *, devmode: bool app.router.add_get('/svcs/mms/adxml_main.asp', lambda req: handle_bannerad(req, msnxml=True)) app.router.add_get('/avatar/{uuid}/static', handle_avatar) app.router.add_get('/avatar/{uuid}/small', lambda req: handle_avatar(req, small=True)) - app.router.add_get('/avatar/{uuid}/msn', lambda req: handle_avatar(req, msn=True)) - app.router.add_route('*', '/{path:.*}', handle_notfound) + app.router.add_get('/avatar/{uuid}/im', lambda req: handle_avatar(req, im=True)) return app @@ -48,11 +49,18 @@ def create_app(loop: asyncio.AbstractEventLoop, backend: Backend) -> Any: ) app.on_response_prepare.append(on_response_prepare) + app.middlewares.append(notfound_middleware) util.misc.add_to_jinja_env(app, 'misc', MISC_TMPL_DIR) return app +@web.middleware +async def notfound_middleware(req: web.Request, handler: Any) -> web.StreamResponse: + if isinstance(req.match_info.http_exception, web.HTTPNotFound): + return await handle_notfound(req) + return await handler(req) + async def on_response_prepare(req: web.Request, res: web.StreamResponse) -> None: res.headers['X-Azul-Version'] = settings.VERSION @@ -86,7 +94,7 @@ async def handle_notfound(req: web.Request) -> web.Response: return render(req, 'misc:miscconns.html', { 'settings': settings }, status=404) - + async def handle_bannerad(req: web.Request, yuge: bool = False, sq: bool = False, msnxml: bool = False) -> web.Response: with open('config/big-bannerimages.json' if yuge else 'config/sq-bannerimages.json' if sq else 'config/bannerimages.json', 'r') as json_file: data = json.load(json_file) @@ -154,14 +162,21 @@ async def handle_blankok(req: web.Request) -> web.Response: # MSN counts the login server as a "key port" by POSTing to the root of the server with no content. return web.Response(status = 200) -async def handle_avatar(req: web.Request, small: bool = False, msn: bool = False) -> web.Response: +async def handle_avatar(req: web.Request, small: bool = False, im: bool = False) -> web.Response: uuid = req.match_info['uuid'] backend: Backend = req.app['backend'] user = backend.user_service.get(uuid) avatar_md5 = user.avatar if user else None - result = get_avatar_data(uuid, avatar_md5, small=small, msn=msn) + md5_query = req.query.get('md5') or '' + if user is not None and 8 <= len(md5_query) <= 32 and all(c in '0123456789abcdef' for c in md5_query): + result = get_avatar_data(uuid, md5_query, small=small, im=im) + if result is not None: + data, content_type = result + return web.Response(status=200, body=data, content_type=content_type) + + result = get_avatar_data(uuid, avatar_md5, small=small, im=im) if result is not None: data, content_type = result return web.Response(status=200, body=data, content_type=content_type) diff --git a/core/interservice/crypto.py b/core/interservice/crypto.py new file mode 100644 index 0000000..696aede --- /dev/null +++ b/core/interservice/crypto.py @@ -0,0 +1,547 @@ +import base64, hashlib, hmac, os, secrets, struct +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable + +from cryptography.exceptions import InvalidSignature, InvalidTag +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes +from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305 +from cryptography.hazmat.primitives.kdf.hkdf import HKDF + +try: + from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey, MLKEM768PublicKey + HAS_MLKEM = True +except ImportError: + HAS_MLKEM = False + +MAGIC = b'KNIT' +TRANSPORT_VERSION = 2 +IV_SIZE = 16 +KEY_SIZE = 32 +HELLO_SIZE = len(MAGIC) + 2 + KEY_SIZE +WELCOME_SIZE = len(MAGIC) + 2 + KEY_SIZE + 16 +RECORD_HEADER = struct.Struct('>I') +TAG_SIZE = 16 +MAX_DATA = 32 * 1024 +MAX_PADDING = 64 +MAX_RECORD = 1 + MAX_DATA + 2 + MAX_PADDING + 2 * TAG_SIZE + 2048 +MLKEM_PUBLIC_SIZE = 1184 +MLKEM_CIPHERTEXT_SIZE = 1088 +CODE_ID_SIZE = 16 +CODE_SECRET_SIZE = 32 +MAX_LABEL = 100 + +FLAG_PQ = 0x01 +FLAG_ENROLL = 0x02 + +REC_CLIENT_KEX = 0x01 +REC_SERVER_KEX = 0x02 +REC_DATA = 0x03 +REC_REJECT = 0x04 + +CHALLENGE_IDN = b'INS2-IDN' +CHALLENGE_CHK = b'INS2-CHK' + +HOST_KEY_FILE = 'host.key' +HOST_PUB_FILE = 'host.pub' +ENROLLMENT_CODE_PREFIX = 'ins2-' + +class Reject: + UnknownKey = 1 + WrongAddress = 2 + WrongMachine = 3 + BadEnrollment = 4 + Revoked = 5 + WrongIdentifier = 6 + TooManyAttempts = 7 + + MESSAGES = { + UnknownKey: 'this client key is not enrolled on the server', + WrongAddress: 'this client key is not allowed from this address', + WrongMachine: 'this client key belongs to a different machine or OS install', + BadEnrollment: 'the enrollment code is not valid, was already used or has expired', + Revoked: 'this client key was revoked', + WrongIdentifier: 'this client key is not allowed to use that identifier', + TooManyAttempts: 'too many failed attempts from this address, try again later', + } + +class INSCryptoError(Exception): + pass + +class INSRejected(INSCryptoError): + reason: int + + def __init__(self, reason: int, detail: str | None = None) -> None: + super().__init__(detail or Reject.MESSAGES.get(reason, 'rejected by the server ({})'.format(reason))) + self.reason = reason + +@dataclass(frozen = True) +class EnrollmentRequest: + code_id: bytes + secret: bytes + auth_public: bytes + identifier: str + label: str + +@dataclass(frozen = True) +class ClientHello: + transport_public: bytes + machine: bytes + enrollment: EnrollmentRequest | None + +def _nonce(counter: int) -> bytes: + return struct.pack('>4xQ', counter) + +def raw_public(key: X25519PublicKey | Ed25519PublicKey) -> bytes: + return key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) + +def _hkdf(ikm: bytes, salt: bytes, info: bytes, length: int = 32) -> bytes: + return HKDF(algorithm = hashes.SHA256(), length = length, salt = salt, info = info).derive(ikm) + +def _exchange(private: X25519PrivateKey, public: X25519PublicKey) -> bytes: + try: + return private.exchange(public) + except ValueError as ex: + raise INSCryptoError('invalid key exchange') from ex + +def _x25519(raw: bytes) -> X25519PublicKey: + try: + return X25519PublicKey.from_public_bytes(raw) + except ValueError as ex: + raise INSCryptoError('invalid X25519 key') from ex + +def _short_string(data: bytes, offset: int, limit: int) -> tuple[str, int]: + if offset >= len(data): + raise INSCryptoError('truncated enrollment') + length = data[offset] + end = offset + 1 + length + if length > limit or end > len(data): + raise INSCryptoError('invalid enrollment') + try: + return data[offset + 1:end].decode('utf-8'), end + except UnicodeDecodeError as ex: + raise INSCryptoError('invalid enrollment') from ex + +def _pack_string(value: str, limit: int) -> bytes: + data = value.encode('utf-8')[:limit] + while data: + try: + data.decode('utf-8') + break + except UnicodeDecodeError: + data = data[:-1] + return bytes((len(data),)) + data + +class _Veil: + __slots__ = ('_ctx',) + + def __init__(self, server_public: bytes, iv: bytes, direction: bytes) -> None: + key = _hkdf(server_public, iv, b'INS2 veil ' + direction) + self._ctx = Cipher(algorithms.AES(key), modes.CTR(bytes(16))).encryptor() + + def apply(self, data: bytes) -> bytes: + return self._ctx.update(data) + +class SecureChannel: + __slots__ = ( + '_initiator', '_server_public', '_host_key', '_resolver', '_client_key', '_machine', '_enrollment', '_ephemeral', + '_peer_ephemeral', '_buffer', '_outbox', '_out_veil', '_in_veil', '_link_send', '_link_recv', '_link_send_ctr', + '_link_recv_ctr', '_link_binding', '_kex_x25519', '_kex_mlkem', '_kex_random', '_client_body', '_client_send', + '_client_recv', '_client_send_ctr', '_client_recv_ctr', 'binding', 'established', 'post_quantum', 'pq_offer', + 'identity', 'enrolled', 'rejected', + ) + + def __init__(self) -> None: + raise TypeError('use SecureChannel.client or SecureChannel.server') + + @classmethod + def _new(cls, initiator: bool, server_public: bytes, pq_offer: bool) -> 'SecureChannel': + self = object.__new__(cls) + self._initiator = initiator + self._server_public = server_public + self._host_key: X25519PrivateKey | None = None + self._resolver: Callable[[ClientHello], Any] | None = None + self._client_key: X25519PrivateKey | None = None + self._machine = b'' + self._enrollment: EnrollmentRequest | None = None + self._ephemeral = X25519PrivateKey.generate() + self._peer_ephemeral: X25519PublicKey | None = None + self._buffer = bytearray() + self._outbox = bytearray() + self._out_veil: _Veil | None = None + self._in_veil: _Veil | None = None + self._link_send: ChaCha20Poly1305 | None = None + self._link_recv: ChaCha20Poly1305 | None = None + self._link_send_ctr = 0 + self._link_recv_ctr = 0 + self._link_binding = b'' + self._kex_x25519 = X25519PrivateKey.generate() + self._kex_mlkem: MLKEM768PrivateKey | None = None + self._kex_random = secrets.token_bytes(32) + self._client_body = b'' + self._client_send: AESGCM | None = None + self._client_recv: AESGCM | None = None + self._client_send_ctr = 0 + self._client_recv_ctr = 0 + self.binding = b'' + self.established = False + self.post_quantum = False + self.pq_offer = pq_offer and HAS_MLKEM + self.identity = None # type: Any + self.enrolled = False + self.rejected: int | None = None + return self + + @classmethod + def client( + cls, server_public: X25519PublicKey | bytes, client_key: X25519PrivateKey, machine: bytes, *, + enrollment: EnrollmentRequest | None = None, pq_offer: bool = True, + ) -> 'SecureChannel': + server_raw = server_public if isinstance(server_public, bytes) else raw_public(server_public) + if len(server_raw) != KEY_SIZE or len(machine) != 32: + raise INSCryptoError('invalid server key or machine fingerprint') + self = cls._new(True, server_raw, pq_offer) + self._client_key = client_key + self._machine = machine + self._enrollment = enrollment + self._start_veil() + self._write_veiled(MAGIC + bytes((TRANSPORT_VERSION, FLAG_PQ if self.pq_offer else 0)) + raw_public(self._ephemeral.public_key())) + return self + + @classmethod + def server(cls, host_key: X25519PrivateKey, resolver: Callable[[ClientHello], Any], *, pq_offer: bool = True) -> 'SecureChannel': + self = cls._new(False, raw_public(host_key.public_key()), pq_offer) + self._host_key = host_key + self._resolver = resolver + return self + + def _start_veil(self) -> None: + iv = secrets.token_bytes(IV_SIZE) + self._out_veil = _Veil(self._server_public, iv, b'c2s' if self._initiator else b's2c') + self._outbox += iv + + def _write_veiled(self, data: bytes) -> None: + assert self._out_veil is not None + self._outbox += self._out_veil.apply(data) + + def receive(self, data: bytes) -> list[bytes]: + if self.rejected is not None: + raise INSRejected(self.rejected) + if self._in_veil is None: + self._buffer += data + if len(self._buffer) < IV_SIZE: + return [] + iv = bytes(self._buffer[:IV_SIZE]) + rest = bytes(self._buffer[IV_SIZE:]) + self._buffer.clear() + self._in_veil = _Veil(self._server_public, iv, b's2c' if self._initiator else b'c2s') + data = rest + self._buffer += self._in_veil.apply(data) + chunks: list[bytes] = [] + if self._link_recv is None and not self._link_handshake(): + return chunks + while len(self._buffer) >= RECORD_HEADER.size: + (size,) = RECORD_HEADER.unpack_from(self._buffer) + if size < TAG_SIZE + 1 or size > MAX_RECORD: + raise INSCryptoError('invalid record size {}'.format(size)) + if len(self._buffer) < RECORD_HEADER.size + size: + break + header = bytes(self._buffer[:RECORD_HEADER.size]) + body = bytes(self._buffer[RECORD_HEADER.size:RECORD_HEADER.size + size]) + del self._buffer[:RECORD_HEADER.size + size] + assert self._link_recv is not None + try: + record = self._link_recv.decrypt(_nonce(self._link_recv_ctr), body, header) + except InvalidTag as ex: + raise INSCryptoError('link record failed authentication') from ex + self._link_recv_ctr += 1 + chunk = self._on_record(record) + if chunk: + chunks.append(chunk) + return chunks + + def _link_handshake(self) -> bool: + expected = (WELCOME_SIZE if self._initiator else HELLO_SIZE) + if len(self._buffer) < len(MAGIC): + return False + if bytes(self._buffer[:len(MAGIC)]) != MAGIC: + raise INSCryptoError('unrecognised traffic') + if len(self._buffer) < expected: + return False + message = bytes(self._buffer[:expected]) + del self._buffer[:expected] + if message[4] != TRANSPORT_VERSION: + raise INSCryptoError('unsupported transport version {}'.format(message[4])) + peer_raw = message[6:38] + peer = _x25519(peer_raw) + self._peer_ephemeral = peer + own_raw = raw_public(self._ephemeral.public_key()) + client_raw, server_raw = ((own_raw, peer_raw) if self._initiator else (peer_raw, own_raw)) + self._link_binding = hashlib.sha256(b'INS2 link' + self._server_public + client_raw + server_raw).digest() + ee = _exchange(self._ephemeral, peer) + if self._initiator: + es = _exchange(self._ephemeral, _x25519(self._server_public)) + else: + assert self._host_key is not None + es = _exchange(self._host_key, peer) + okm = _hkdf(ee + es, self._link_binding, b'INS2 link keys', 64) + c2s, s2c = ChaCha20Poly1305(okm[:32]), ChaCha20Poly1305(okm[32:]) + if self._initiator: + self._link_send, self._link_recv = c2s, s2c + try: + s2c.decrypt(_nonce(0), message[38:], self._link_binding) + except InvalidTag as ex: + raise INSCryptoError('the server did not prove the host key this client trusts') from ex + self._link_recv_ctr = 1 + self.pq_offer = self.pq_offer and bool(message[5] & FLAG_PQ) + self._send_client_kex() + else: + self._link_send, self._link_recv = s2c, c2s + self.pq_offer = self.pq_offer and bool(message[5] & FLAG_PQ) + self._start_veil() + self._write_veiled(MAGIC + bytes((TRANSPORT_VERSION, FLAG_PQ if self.pq_offer else 0)) + own_raw + s2c.encrypt(_nonce(0), b'', self._link_binding)) + self._link_send_ctr = 1 + return True + + def _send_record(self, record: bytes) -> None: + assert self._link_send is not None + header = RECORD_HEADER.pack(len(record) + TAG_SIZE) + self._write_veiled(header + self._link_send.encrypt(_nonce(self._link_send_ctr), record, header)) + self._link_send_ctr += 1 + + def _send_client_kex(self) -> None: + assert self._client_key is not None + flags = 0 + body = raw_public(self._client_key.public_key()) + raw_public(self._kex_x25519.public_key()) + self._kex_random + self._machine + if self.pq_offer: + self._kex_mlkem = MLKEM768PrivateKey.generate() + body += self._kex_mlkem.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) + flags |= FLAG_PQ + enrollment = self._enrollment + if enrollment is not None: + flags |= FLAG_ENROLL + body += ( + enrollment.code_id + enrollment.secret + enrollment.auth_public + + _pack_string(enrollment.identifier, 64) + _pack_string(enrollment.label, MAX_LABEL) + ) + self._client_body = bytes((flags,)) + body + self._send_record(bytes((REC_CLIENT_KEX,)) + self._client_body) + + def _derive_client_key(self, client_body: bytes, server_body: bytes, shared: bytes) -> tuple[bytes, bytes]: + self.binding = hashlib.sha256(b'INS2 client' + self._link_binding + client_body + server_body).digest() + okm = _hkdf(shared, self.binding, b'INS2 client keys', 64) + return okm[:32], okm[32:] + + def _parse_client_kex(self, body: bytes) -> tuple[ClientHello, bytes, bytes, bytes | None]: + if len(body) < 1 + 4 * KEY_SIZE: + raise INSCryptoError('truncated client KEX') + flags = body[0] + static_raw = body[1:33] + kex_raw = body[33:65] + machine = body[97:129] + offset = 129 + mlkem_raw: bytes | None = None + if flags & FLAG_PQ: + mlkem_raw = body[offset:offset + MLKEM_PUBLIC_SIZE] + if len(mlkem_raw) != MLKEM_PUBLIC_SIZE: + raise INSCryptoError('truncated ML-KEM key') + offset += MLKEM_PUBLIC_SIZE + enrollment: EnrollmentRequest | None = None + if flags & FLAG_ENROLL: + end = offset + CODE_ID_SIZE + CODE_SECRET_SIZE + KEY_SIZE + if len(body) < end: + raise INSCryptoError('truncated enrollment') + code_id = body[offset:offset + CODE_ID_SIZE] + secret = body[offset + CODE_ID_SIZE:offset + CODE_ID_SIZE + CODE_SECRET_SIZE] + auth_raw = body[end - KEY_SIZE:end] + identifier, offset = _short_string(body, end, 64) + label, offset = _short_string(body, offset, MAX_LABEL) + enrollment = EnrollmentRequest(code_id, secret, auth_raw, identifier, label) + if offset != len(body): + raise INSCryptoError('unexpected bytes after client KEX') + return ClientHello(static_raw, machine, enrollment), static_raw, kex_raw, mlkem_raw + + def reject(self, reason: int) -> None: + if self.rejected is None and self._link_send is not None: + self._send_record(bytes((REC_REJECT, reason & 0xff))) + self.rejected = reason + + def _on_record(self, record: bytes) -> bytes | None: + kind = record[0] + if kind == REC_DATA and self.established: + assert self._client_recv is not None + try: + inner = self._client_recv.decrypt(_nonce(self._client_recv_ctr), record[1:], b'\x03') + except InvalidTag as ex: + raise INSCryptoError('client record failed authentication') from ex + self._client_recv_ctr += 1 + (length,) = struct.unpack_from('>H', inner) + if length > len(inner) - 2: + raise INSCryptoError('invalid data length') + return inner[2:2 + length] + if kind == REC_CLIENT_KEX and not self._initiator and self._client_send is None: + hello, static_raw, kex_raw, mlkem_raw = self._parse_client_kex(record[1:]) + assert self._resolver is not None + try: + self.identity = self._resolver(hello) + except INSRejected as ex: + self.reject(ex.reason) + raise + self.enrolled = hello.enrollment is not None + shared = _exchange(self._kex_x25519, _x25519(kex_raw)) + shared += _exchange(self._ephemeral, _x25519(static_raw)) + pq_part = b'' + used_pq = mlkem_raw is not None and self.pq_offer + if used_pq: + assert mlkem_raw is not None + try: + mlkem_pub = MLKEM768PublicKey.from_public_bytes(mlkem_raw) + except ValueError as ex: + raise INSCryptoError('invalid ML-KEM key') from ex + pq_shared, pq_part = mlkem_pub.encapsulate() + shared += pq_shared + flags = (FLAG_PQ if used_pq else 0) | (FLAG_ENROLL if self.enrolled else 0) + server_body = bytes((flags,)) + raw_public(self._kex_x25519.public_key()) + self._kex_random + pq_part + client_random = record[66:98] + c2s, s2c = self._derive_client_key(record[1:], server_body, shared + client_random + self._kex_random) + self._client_send, self._client_recv = AESGCM(s2c), AESGCM(c2s) + self._send_record(bytes((REC_SERVER_KEX,)) + server_body + self._client_send.encrypt(_nonce(0), b'', self.binding)) + self._client_send_ctr = 1 + self.post_quantum = used_pq + self.established = True + return None + if kind == REC_SERVER_KEX and self._initiator and self._client_recv is None: + assert self._client_key is not None and self._peer_ephemeral is not None + flags = record[1] + used_pq = bool(flags & FLAG_PQ) + end = 66 + (MLKEM_CIPHERTEXT_SIZE if used_pq else 0) + if len(record) != end + TAG_SIZE: + raise INSCryptoError('invalid server KEX') + server_body = record[1:end] + shared = _exchange(self._kex_x25519, _x25519(record[2:34])) + shared += _exchange(self._client_key, self._peer_ephemeral) + if used_pq: + if self._kex_mlkem is None: + raise INSCryptoError('server used ML-KEM that was not offered') + try: + shared += self._kex_mlkem.decapsulate(record[66:end]) + except ValueError as ex: + raise INSCryptoError('invalid ML-KEM ciphertext') from ex + c2s, s2c = self._derive_client_key(self._client_body, server_body, shared + self._kex_random + record[34:66]) + self._client_send, self._client_recv = AESGCM(c2s), AESGCM(s2c) + try: + self._client_recv.decrypt(_nonce(0), record[end:], self.binding) + except InvalidTag as ex: + raise INSCryptoError('server failed client key confirmation') from ex + self._client_recv_ctr = 1 + self.post_quantum = used_pq + self.enrolled = bool(flags & FLAG_ENROLL) + self.established = True + return None + if kind == REC_REJECT and self._initiator and len(record) == 2: + self.rejected = record[1] + raise INSRejected(record[1]) + raise INSCryptoError('unexpected record type {}'.format(kind)) + + def send(self, plaintext: bytes) -> None: + if not plaintext: + return + if not self.established or self._client_send is None: + raise INSCryptoError('channel not established') + for i in range(0, len(plaintext), MAX_DATA): + chunk = plaintext[i:i + MAX_DATA] + inner = struct.pack('>H', len(chunk)) + chunk + secrets.token_bytes(secrets.randbelow(MAX_PADDING + 1)) + self._send_record(bytes((REC_DATA,)) + self._client_send.encrypt(_nonce(self._client_send_ctr), inner, b'\x03')) + self._client_send_ctr += 1 + + def drain(self) -> bytes: + if not self._outbox: + return b'' + data = bytes(self._outbox) + self._outbox.clear() + return data + +def _challenge_message(purpose: bytes, nonce: bytes, binding: bytes, identifier: str) -> bytes: + return purpose + b'\x00' + identifier.encode('utf-8') + b'\x00' + nonce + binding + +def sign_challenge(key: Ed25519PrivateKey, purpose: bytes, nonce: bytes, binding: bytes, identifier: str = '') -> str: + return base64.b64encode(key.sign(_challenge_message(purpose, nonce, binding, identifier))).decode('ascii') + +def verify_challenge(key: Ed25519PublicKey, signature: str, purpose: bytes, nonce: bytes, binding: bytes, identifier: str = '') -> bool: + try: + key.verify(base64.b64decode(signature, validate = True), _challenge_message(purpose, nonce, binding, identifier)) + except (InvalidSignature, ValueError): + return False + return True + +def ed25519_public(raw: bytes) -> Ed25519PublicKey: + try: + return Ed25519PublicKey.from_public_bytes(raw) + except ValueError as ex: + raise INSCryptoError('invalid Ed25519 key') from ex + +def fingerprint(key: X25519PublicKey | Ed25519PublicKey | bytes) -> str: + digest = hashlib.sha256(key if isinstance(key, bytes) else raw_public(key)).hexdigest() + return ':'.join(digest[i:i + 4] for i in range(0, 32, 4)) + +def b64(data: bytes) -> str: + return base64.urlsafe_b64encode(data).decode('ascii').rstrip('=') + +def unb64(text: str) -> bytes: + try: + return base64.urlsafe_b64decode(text + '=' * (-len(text) % 4)) + except (ValueError, TypeError) as ex: + raise INSCryptoError('invalid base64') from ex + +def make_enrollment_code(server_public: bytes, code_id: bytes, secret: bytes) -> str: + body = bytes((1,)) + server_public + code_id + secret + return ENROLLMENT_CODE_PREFIX + b64(body + hashlib.sha256(body).digest()[:4]) + +def parse_enrollment_code(code: str) -> tuple[bytes, bytes, bytes]: + code = ''.join(code.split()) + if not code.lower().startswith(ENROLLMENT_CODE_PREFIX): + raise INSCryptoError('not an INS2 enrollment code') + data = unb64(code[len(ENROLLMENT_CODE_PREFIX):]) + body, check = data[:-4], data[-4:] + if len(body) != 1 + KEY_SIZE + CODE_ID_SIZE + CODE_SECRET_SIZE or body[0] != 1 or not hmac.compare_digest(hashlib.sha256(body).digest()[:4], check): + raise INSCryptoError('the enrollment code is damaged or incomplete') + return body[1:33], body[33:49], body[49:81] + +def _write_new(path: Path, data: bytes, mode: int) -> None: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode) + with os.fdopen(fd, 'wb') as f: + f.write(data) + +def _private_pem(key: X25519PrivateKey) -> bytes: + return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) + +def _public_pem(key: X25519PublicKey) -> bytes: + return key.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo) + +@dataclass(frozen = True) +class ServerKeys: + host: X25519PrivateKey + generated: bool + + @property + def public_raw(self) -> bytes: + return raw_public(self.host.public_key()) + +def load_or_generate_server_keys(directory: str | os.PathLike[str]) -> ServerKeys: + base = Path(directory) + base.mkdir(parents = True, exist_ok = True) + key_path = base / HOST_KEY_FILE + if key_path.exists(): + key = serialization.load_pem_private_key(key_path.read_bytes(), password = None) + if not isinstance(key, X25519PrivateKey): + raise INSCryptoError('{} must be an X25519 private key'.format(key_path)) + return ServerKeys(key, False) + if (base / HOST_PUB_FILE).exists(): + raise INSCryptoError('{} is missing but {} exists'.format(key_path, base / HOST_PUB_FILE)) + key = X25519PrivateKey.generate() + _write_new(key_path, _private_pem(key), 0o600) + _write_new(base / HOST_PUB_FILE, _public_pem(key.public_key()), 0o644) + return ServerKeys(key, True) diff --git a/core/interservice/ctrl.py b/core/interservice/ctrl.py index 698f023..86abf47 100644 --- a/core/interservice/ctrl.py +++ b/core/interservice/ctrl.py @@ -1,21 +1,85 @@ -from typing import Tuple, Optional, Iterable, List, Any, Callable, Dict +from typing import Tuple, Optional, Iterable, List, Any, Callable, Dict, Coroutine from disposable_email_domains import blocklist as disposable_emails -import asyncio, io, hashlib, base64, json, traceback +from datetime import datetime, timedelta +from enum import Enum +import asyncio, io, hashlib, base64, json, re, traceback, secrets, time +import emoji import sqlalchemy as sa from sqlalchemy.orm.attributes import flag_modified -from core.backend import Backend -from core.models import CircleRole +from core.backend import Backend, BackendSession +from core.alerts import Alert, AlertError +from core.models import CircleRole, CircleState, ActivityType, ContactList, User, Activity, Circle from core import error -from util import misc, hash +from core.user import beacon_enabled, directory_online_visible +from core.stats import collect_snapshot import core.db as db +from util import misc, hash +from util.avatar import get_img_type, store_avatar_file, store_photo_file + import settings +from .crypto import SecureChannel, ServerKeys, ClientHello, verify_challenge, ed25519_public, INSCryptoError, CHALLENGE_IDN, CHALLENGE_CHK +from .registry import ClientRegistry, ClientRecord + +PROTOCOL_VERSION = 'INS2' +LINE_COMMANDS = frozenset(('HLO', 'IDN', 'PRV', 'HBT', 'END')) +JSON_COMMANDS = frozenset(( + 'SGN', 'INF', 'WCH', 'ALR', 'MNT', 'ANC', 'MKU', 'EDU', 'RMU', 'GTU', 'LSU', 'LSS', 'GTS', 'KLS', 'CIR', 'CTA', 'CTQ', 'GRP', + 'PRF', 'BFD', 'BST', 'BPH', 'BDL', 'BRX', 'BCM', 'STA', +)) +PRE_AUTH_COMMANDS = LINE_COMMANDS +def twemoji_key(chars: str) -> str: + points = [ord(char) for char in chars] + if 0x200d not in points: + points = [point for point in points if point != 0xfe0f] + return '-'.join('{:x}'.format(point) for point in points) + +REACTIONS = frozenset(twemoji_key(chars) for chars, data in emoji.EMOJI_DATA.items() if data['status'] <= emoji.STATUS['fully_qualified']) +LANGUAGE_TAG = re.compile(r'[a-z]{2,3}(-[a-z0-9]{2,8})*', re.I) +MAX_PROFILE_LANGUAGES = 10 +PREFS = { 'beacon': 'beacon_off', 'dir_online': 'dir_hide_online' } +LEGACY_PREFS = { 'beacon': ('konekt_off',) } +NFY_EVENTS = frozenset(( + 'user.created', 'user.updated', 'user.deleted', 'session.killed', 'maintenance', 'alert', 'announcement', 'activity', 'link', + 'password.reset', 'circle.deleted', 'alert.email', +)) +ALERT_NETWORKS = ('msn', 'ymsg', 'aim', 'icq', 'irc') +MAX_LINE = 4096 +MAX_PAYLOAD_PRE_AUTH = 4096 +MAX_PAYLOAD = 16 * 1024 * 1024 +PHOTO_MAX_SIZE = 10 * 1024 * 1024 +AVATAR_MAX_SIZE = 2 * 1024 * 1024 +USER_TRAITS = ('show_in_dir', 'is_tester', 'is_mvp', 'account_verified', 'verified_to_login', 'alias_active', 'suspended') +PREF_TRAITS = ('beacon', 'dir_online') +CACHED_USER_FIELDS = ('email', 'username', 'uin', 'first_name', 'last_name') + USER_TRAITS +SOFT_USER_FIELDS = ('show_in_dir', 'is_tester', 'is_mvp', 'account_verified', 'is_admin') + +class INSFail(Exception): + code: int + detail: Dict[str, Any] + + def __init__(self, code: int, message: str | None = None, **detail: Any) -> None: + super().__init__(message or str(code)) + self.code = code + self.detail = detail + if message: + self.detail['error'] = message + +class INSProtocolError(Exception): + too_large: bool + + def __init__(self, message: str, *, too_large: bool = False) -> None: + super().__init__(message) + self.too_large = too_large + class INSCtrl: __slots__ = ( 'logger', 'reader', 'writer', 'peername', 'close_callback', 'closed', 'transport', 'authenticated', 'current_challenge', 'backend', #'alive', 'alive_task', + 'channel', 'raw_transport', 'link_id', 'identifier', 'client_info', 'version_ok', 'auth_nonce', 'pending_identifier', + 'connected_at', 'last_activity', 'challenge_sent_at', 'next_challenge_at', 'watchdog', 'subscriptions', 'tasks', 'client_record', ) logger: misc.Logger @@ -30,6 +94,26 @@ class INSCtrl: #alive: bool #alive_task: Optional[misc.VoidTaskType] backend: Backend + channel: SecureChannel + raw_transport: asyncio.WriteTransport | None + link_id: str + identifier: str | None + client_info: Dict[str, str] + version_ok: bool + auth_nonce: bytes | None + pending_identifier: str | None + connected_at: float + last_activity: float + challenge_sent_at: float + next_challenge_at: float + watchdog: 'asyncio.Task[None] | None' + subscriptions: set[str] + tasks: 'set[asyncio.Task[None]]' + client_record: ClientRecord | None + + _keys: ServerKeys | None = None + _registry: ClientRegistry | None = None + _links: Dict[str, 'INSCtrl'] = {} def __init__(self, logger: misc.Logger, via: str, backend: Backend) -> None: self.logger = logger @@ -45,32 +129,121 @@ class INSCtrl: #self.alive = True #self.alive_task = None self.backend = backend + + keys = INSCtrl._keys + assert keys is not None and INSCtrl._registry is not None, "InterService keys not loaded, call `INSCtrl.configure` first" + self.channel = SecureChannel.server(keys.host, self._resolve_client) + self.client_record = None + self.raw_transport = None + self.link_id = secrets.token_hex(8) + self.identifier = None + self.client_info = {} + self.version_ok = False + self.auth_nonce = None + self.pending_identifier = None + self.connected_at = time.monotonic() + self.last_activity = self.connected_at + self.challenge_sent_at = 0.0 + self.next_challenge_at = 0.0 + self.watchdog = None + self.subscriptions = set() + self.tasks = set() - def _m_linksrv(self, password: str, identifier: Optional[str]) -> None: - backend = self.backend - - bytes_enc = identifier.encode("ascii") - base64_dec = base64.b64decode(bytes_enc) - identifier_dec = base64_dec.decode("ascii") + @classmethod + def configure(cls, keys: ServerKeys, registry: ClientRegistry) -> None: + cls._keys = keys + cls._registry = registry + registry.on_revoke = cls._client_revoked - valid_identifiers = ['WEB', 'AzuL-SERV', 'WTV', 'uMaIL', 'sBOOK', 'NOTBAY', 'CrossBot', 'SEARCH', 'WebTalk'] + @classmethod + def attach(cls, backend: Backend) -> None: + backend.on_user_deleted = lambda uuid, reason: cls.broadcast('user.deleted', { 'uuid': uuid, 'reason': reason }) + + @classmethod + def _client_revoked(cls, record: ClientRecord) -> None: + for link in list(cls._links.values()): + if link.client_record is not None and link.client_record.id == record.id: + link.logger.info(f'InterService link {link.identifier} closed, its key was revoked') + link.close('REV') + + def _resolve_client(self, hello: ClientHello) -> ClientRecord: + registry = INSCtrl._registry + assert registry is not None + record = registry.resolve(hello, self.peername[0] if self.peername else '', self.logger) + self.client_record = record + return record + + def connection_made(self, transport: asyncio.WriteTransport) -> None: + self.raw_transport = transport + self.peername = transport.get_extra_info('peername') + self.watchdog = self.backend.loop.create_task(self._watchdog()) + + def _m_hlo(self, trid: str, *args: str) -> None: + if not args or args[0] != PROTOCOL_VERSION: + self.send_reply('HLO', trid, '-') + self.close() + return + self.version_ok = True + if len(args) >= 3: + self.client_info = { 'program': args[1][:32], 'version': args[2][:32] } + self.send_reply('HLO', trid, PROTOCOL_VERSION, 'azul', settings.VERSION) + + def _m_idn(self, trid: str, *args: str) -> None: + if self.authenticated: + raise INSFail(Err.AlreadyAuthenticated) + if not self.version_ok: + raise INSFail(Err.ProtocolVersionUnsupported, 'HLO must come first') + if len(args) < 1: + raise INSFail(Err.TooFewArguments) + identifier_dec = args[0] + valid_identifiers = settings.INS_IDENTIFIERS if identifier_dec not in valid_identifiers: self.logger.info(f'InterService identification failed, invalid identifier "{identifier_dec}".') - self.send_numeric(Err.AuthenticationFailed) + self.send_numeric(Err.AuthenticationFailed, trid) self.close() - else: - hashed_pw = hashlib.sha256(settings.INS_LINK_PASSWORD.encode()).hexdigest() - if password == hashed_pw: - self.authenticated = True - backend._linked = True - # TODO: Re-implement in V2 - #self.alive_task = backend.loop.create_task(self._ping_conn()) - self.logger.info(f'New InterService session established (identifier: {identifier_dec})') - self.send_reply('LINKSRV', 'OK') - else: - self.send_numeric(Err.AuthenticationFailed) - self.close() - + return + record = self.client_record + if record is None or record.revoked or record.identifier != identifier_dec: + self.logger.info(f'InterService identification failed, "{identifier_dec}" does not match the key\'s enrollment') + self.send_numeric(Err.AuthenticationFailed, trid) + self.close() + return + self.pending_identifier = identifier_dec + self.auth_nonce = secrets.token_bytes(32) + self.send_reply('IDN', trid, base64.b64encode(self.auth_nonce).decode('ascii')) + + def _m_prv(self, trid: str, *args: str) -> None: + if self.authenticated: + raise INSFail(Err.AlreadyAuthenticated) + nonce = self.auth_nonce + identifier_dec = self.pending_identifier + record = self.client_record + self.auth_nonce = None + if nonce is None or identifier_dec is None or record is None or record.revoked or not args or not verify_challenge( + ed25519_public(record.auth_public), args[0], CHALLENGE_IDN, nonce, self.channel.binding, identifier_dec, + ): + self.logger.info(f'InterService authentication failed for identifier "{identifier_dec}", bad challenge response') + self.send_numeric(Err.AuthenticationFailed, trid) + self.close() + return + + backend = self.backend + self.authenticated = True + self.identifier = identifier_dec + self.reader.max_payload = MAX_PAYLOAD + INSCtrl._links[self.link_id] = self + backend._linked = True + # TODO: Re-implement in V2 + #self.alive_task = backend.loop.create_task(self._ping_conn()) + if settings.INS_CHALLENGE_INTERVAL > 0: + self.next_challenge_at = time.monotonic() + settings.INS_CHALLENGE_INTERVAL + registry = INSCtrl._registry + if registry is not None: + registry.seen(record, self.peername[0] if self.peername else '') + self.logger.info(f'New InterService session established (identifier: {identifier_dec}, client: "{record.label}", key: {record.fingerprint}, enrolled now: {self.channel.enrolled}, post-quantum: {self.channel.post_quantum})') + self.send_reply('PRV', trid, identifier_dec, self.link_id) + INSCtrl.broadcast('link', { 'state': 'up', 'identifier': identifier_dec, 'link': self.link_id }, exclude = self) + #def _m_pong(self, challenge: str) -> None: # if self.alive: return # if not self.current_challenge or challenge != self.current_challenge: @@ -79,658 +252,1114 @@ class INSCtrl: # self.alive = True # self.current_challenge = None - def _m_circle(self, ts: str, chat_id: str, action: str, *args: str) -> None: + def _m_hbt(self) -> None: + self.send_reply('HBT', str(settings.INS_PING_INTERVAL)) + + def _m_end(self) -> None: + self.send_reply('END') + self.close() + + def _m_sgn(self, trid: str, data: Dict[str, Any]) -> None: + record = self.client_record + challenge = self.current_challenge + if challenge is None: + raise INSFail(Err.InvalidArgument, 'no challenge pending') + self.current_challenge = None + if record is None or record.revoked or not verify_challenge( + ed25519_public(record.auth_public), str(data.get('signature') or ''), CHALLENGE_CHK, base64.b64decode(challenge), self.channel.binding, self.identifier or '', + ): + self.logger.info(f'InterService link {self.identifier} failed its challenge') + self.send_numeric(Err.ChallengeFailed, trid) + self.close('CHL') + return + self.next_challenge_at = time.monotonic() + settings.INS_CHALLENGE_INTERVAL + self.send_payload('SGN', trid, None) + + def _m_inf(self, trid: str, data: Dict[str, Any]) -> None: backend = self.backend + sessions = list(backend._sc.iter_sessions()) + self.send_payload('INF', trid, { + 'server': 'azul', 'version': settings.VERSION, 'protocol': PROTOCOL_VERSION, + 'link': self.link_id, 'identifier': self.identifier, + 'maintenance': { + 'active': backend.maintenance_mode, 'pending': backend.notify_maintenance, 'minutes': backend.maintenance_mins, + }, + 'sessions': len(sessions), + 'users_online': len({ bs.user.uuid for bs in sessions }), + 'links': [ + { + 'link': link.link_id, 'identifier': link.identifier, 'client': link.client_info, 'peer': link.peername[0] if link.peername else None, + 'label': link.client_record.label if link.client_record else None, + 'key': link.client_record.fingerprint if link.client_record else None, + } + for link in INSCtrl._links.values() + ], + 'commands': sorted(JSON_COMMANDS | LINE_COMMANDS), + 'post_quantum': self.channel.post_quantum, + 'events': sorted(NFY_EVENTS), + 'ping_interval': settings.INS_PING_INTERVAL, + 'challenge_interval': settings.INS_CHALLENGE_INTERVAL, + 'started': backend._stats.snapshot_started(), + 'uptime': backend._stats.uptime(), + 'services': _services(backend), + }) + + def _m_sta(self, trid: str, data: Dict[str, Any]) -> None: + self.send_payload('STA', trid, collect_snapshot(self.backend)) + + def _m_wch(self, trid: str, data: Dict[str, Any]) -> None: + events = data.get('events') + if not isinstance(events, list): + raise INSFail(Err.InvalidArgument, 'events must be a list') + wanted = { str(e) for e in events } + unknown = wanted - NFY_EVENTS - { '*' } + if unknown: + raise INSFail(Err.InvalidArgument, 'unknown events', events = sorted(unknown)) + self.subscriptions = wanted + self.send_payload('WCH', trid, { 'events': sorted(wanted) }) + + def _m_cir(self, trid: str, data: Dict[str, Any]) -> None: + backend = self.backend + action = _req_str(data, 'action').upper() - if not self.authenticated: - self.send_numeric(Err.NotAuthenticated) - self.close() + if action == 'LIST': + self.send_payload('CIR', trid, { 'circles': [_circle_info(circle, members = False) for circle in backend.user_service.get_all_circles()] }) return + chat_id = _req_str(data, 'chat_id') circle = backend.user_service.get_circle(chat_id) if circle is None: - self.send_numeric(Err.CircleDoesNotExist, ':CIRCLE {}'.format(ts)) + raise INSFail(Err.CircleDoesNotExist) + + if action == 'INFO': + self.send_payload('CIR', trid, _circle_info(circle, members = True, backend = backend)) return + if action == 'DELETE': + if data.get('uuid') or data.get('email'): + owner = self._user_from(data) + membership = circle.memberships.get(owner.uuid) + if membership is None or membership.role is not CircleRole.Admin or membership.state is not CircleState.Accepted: + raise INSFail(Err.DoesntHaveSufficientPermissions) + members = backend.util_delete_circle(circle) + self.logger.info(f'Circle {circle.name} ({chat_id}) deleted, {len(members)} members dropped') + self.send_payload('CIR', trid, { 'chat_id': chat_id, 'action': action, 'members': len(members), 'status': StatusCode.CircleActionSuccessful }) + INSCtrl.broadcast('circle.deleted', { 'chat_id': chat_id }, exclude = self) + return + + user = self._user_from(data) + if action == 'INCHAT': - if len(args) < 1: - self.send_numeric(Err.TooFewArguments, ':CIRCLE {}'.format(ts)) - return - - uuid = args[0] - - user = backend._load_user_record(uuid) - if user is None: - self.send_numeric(Err.UserNotInDB, ':CIRCLE {}'.format(ts)) - return - try: in_chat = backend.util_user_online_in_circle(circle, user) - self.send_reply('CIRCLE', ts, 'INCHAT', uuid, str(in_chat)) except error.MemberNotInCircle: - self.send_numeric(Err.CircleMemberInvalid, ':CIRCLE {}'.format(ts)) + raise INSFail(Err.CircleMemberInvalid) + self.send_payload('CIR', trid, { 'chat_id': chat_id, 'uuid': user.uuid, 'in_chat': in_chat }) return elif action == 'ACCEPT': - if len(args) < 1: - self.send_numeric(Err.TooFewArguments, ':CIRCLE {}'.format(ts)) - return - - uuid = args[0] - - user = backend._load_user_record(uuid) - if user is None: - self.send_numeric(Err.UserNotInDB, ':CIRCLE {}'.format(ts)) - return - try: backend.util_accept_circle_invite(circle, user) except error.MemberNotInCircle: - self.send_numeric(Err.CircleMemberInvalid, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.CircleMemberInvalid) except error.MemberAlreadyInCircle: - self.send_numeric(Err.MemberAlreadyInCircle, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.MemberAlreadyInCircle) elif action == 'DECLINE': - if len(args) < 1: - self.send_numeric(Err.TooFewArguments, ':CIRCLE {}'.format(ts)) - return - - uuid = args[0] - - user = backend._load_user_record(uuid) - if user is None: - self.send_numeric(Err.UserNotInDB, ':CIRCLE {}'.format(ts)) - return - try: backend.util_decline_circle_invite(circle, user) except error.MemberNotInCircle: - self.send_numeric(Err.CircleMemberInvalid, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.CircleMemberInvalid) except error.MemberAlreadyInCircle: - self.send_numeric(Err.MemberAlreadyInCircle, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.MemberAlreadyInCircle) elif action == 'REVOKE': - if len(args) < 1: - self.send_numeric(Err.TooFewArguments, ':CIRCLE {}'.format(ts)) - return - - uuid = args[0] - - user = backend._load_user_record(uuid) - if user is None: - self.send_numeric(Err.UserNotInDB, ':CIRCLE {}'.format(ts)) - return - try: backend.util_revoke_circle_invite(circle, user) except error.MemberNotInCircle: - self.send_numeric(Err.CircleMemberInvalid, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.CircleMemberInvalid) except error.MemberAlreadyInCircle: - self.send_numeric(Err.MemberAlreadyInCircle, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.MemberAlreadyInCircle) elif action == 'ROLE': - if len(args) < 2: - self.send_numeric(Err.TooFewArguments, ':CIRCLE {}'.format(ts)) - return - user_self = None - uuid = args[0] - role_num = args[1] - - user = backend._load_user_record(uuid) - if user is None: - self.send_numeric(Err.UserNotInDB, ':CIRCLE {}'.format(ts)) - return - - if len(args) >= 3: - uuid_self = args[2] - user_self = backend._load_user_record(uuid_self) - if user_self is None: - self.send_numeric(Err.UserNotInDB, ':{}'.format(ts)) - return + if data.get('uuid_self') or data.get('email_self'): + user_self = self._user_from({ 'uuid': data.get('uuid_self'), 'email': data.get('email_self') }) try: - role = CircleRole(int(role_num)) + role = CircleRole(int(data.get('role'))) if user_self is not None and role is not CircleRole.Admin: raise ValueError() backend.util_change_circle_membership_role(circle, user, role, user_self) - except ValueError: - self.send_numeric(Err.CircleRoleInvalid, ':CIRCLE {}'.format(ts)) - return + except (ValueError, TypeError): + raise INSFail(Err.CircleRoleInvalid) except error.MemberNotInCircle: - self.send_numeric(Err.CircleMemberInvalid, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.CircleMemberInvalid) except error.CircleMemberIsPending: - self.send_numeric(Err.CircleMemberIsPending, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.CircleMemberIsPending) except error.MemberDoesntHaveSufficientCircleRole: - self.send_numeric(Err.DoesntHaveSufficientPermissions, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.DoesntHaveSufficientPermissions) elif action == 'REMOVE': - if len(args) < 1: - self.send_numeric(Err.TooFewArguments, ':CIRCLE {}'.format(ts)) - return - - uuid = args[0] - - user = backend._load_user_record(uuid) - if user is None: - self.send_numeric(Err.UserNotInDB, ':CIRCLE {}'.format(ts)) - return - try: backend.util_remove_user_from_circle(circle, user) except error.MemberNotInCircle: - self.send_numeric(Err.CircleMemberInvalid, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.CircleMemberInvalid) except error.CantLeaveCircle: - self.send_numeric(Err.CantLeaveCircle, ':CIRCLE {}'.format(ts)) - return + raise INSFail(Err.CantLeaveCircle) else: - self.send_numeric(Err.InvalidArgument, ':CIRCLE {}'.format(ts)) + raise INSFail(Err.InvalidArgument, 'unknown circle action') + + self.send_payload('CIR', trid, { 'chat_id': chat_id, 'uuid': user.uuid, 'action': action, 'status': StatusCode.CircleActionSuccessful }) + + def _m_alr(self, trid: str, data: Dict[str, Any]) -> None: + backend = self.backend + if str(data.get('action') or '').upper() == 'LIST': + self.send_payload('ALR', trid, { 'alerts': list(reversed(backend.recent_alerts)) }) return - self.send_numeric(StatusCode.CircleActionSuccessful, ':CIRCLE {}'.format(ts)) - - def _m_alert(self, ts: str, type: str, content: str = '', url: str = '', targets: str = 'all', icon: str = '') -> None: - if not self.authenticated: - self.send_numeric(Err.NotAuthenticated) - self.close() - return - - def _quote_circumcision(s: str) -> str: - if not s or len(s) < 2: - return s - if (s[0] == s[-1]) and s[0] in ('"', "'"): - quote = s[0] - inner = s[1:-1] - inner = inner.replace('\\\\', '\\').replace('\\' + quote, quote) - return inner - return s - - if not content: - return self.send_numeric(Err.InvalidArgument, ts) - - if type == 'MAINTENANCE': + def number(key: str, default: int) -> int: + value = data.get(key) + if value in (None, ''): + return default try: - mt_mins = int(content) - except ValueError: - return self.send_numeric(Err.TooFewArguments, ts) - if self.backend.maintenance_mode or self.backend.notify_maintenance: - return self.send_numeric(Err.ServerInModeAlready, ts) - self.backend.push_maintenance_message(1, mt_mins) - return self.send_reply('ALERT', ts, 'OK') - + return int(value) + except (TypeError, ValueError): + raise INSFail(Err.InvalidArgument, '{} must be a number'.format(key), field = key) + + targets = data.get('targets', 'all') + if isinstance(targets, str): + targets = [t.strip() for t in targets.split(',') if t.strip()] + if not isinstance(targets, list): + raise INSFail(Err.InvalidArgument, 'targets must be "all" or a list', field = 'targets') + targets = [str(t).strip() for t in targets if str(t).strip()] + everyone = not targets or targets == ['all'] + networks = data.get('networks') or list(ALERT_NETWORKS) + if not isinstance(networks, list) or not networks or any(n not in ALERT_NETWORKS for n in networks): + raise INSFail(Err.InvalidArgument, 'networks is a list of {}'.format(', '.join(ALERT_NETWORKS)), field = 'networks') + email = bool(data.get('email')) + if email and everyone: + raise INSFail(Err.InvalidArgument, 'alerts are only e-mailed to the people named in targets', field = 'email') + kind = str(data.get('kind') or 'bell') + + try: + alert = Alert( + str(data.get('text') or data.get('message') or ''), rich = str(data.get('rich') or '') or None, + align = str(data.get('align') or 'left'), url = str(data.get('url') or ''), subscr_url = str(data.get('subscr_url') or ''), + icon = str(data.get('icon') or ''), kind = kind, lang = number('lang', 1033), priority = number('priority', 1), + message_id = number('message_id', 0), via = str(data.get('via') or '') or None, + email_text = (str(data.get('email_text') or '').strip() or None) if email else None, + ) + if email and not alert.email_text: + alert.email_text = alert.plain_with_link() + alert.check(emailed = email) + except AlertError as ex: + raise INSFail(Err.InvalidArgument, str(ex), field = ex.field) + + sessions = set() + recipients: dict[str, User] = {} + if everyone: + sessions = set(backend._sc.iter_sessions()) else: - content = content.strip() - content_circumcised = _quote_circumcision(content) - - if not content_circumcised: - return self.send_numeric(Err.InvalidArgument, ts) - - sessions = set() - if targets.strip() == 'all': - sessions = set(self.backend._sc.iter_sessions()) + for t in targets: + uuid = (backend.util_get_uuid_from_email(t) if '@' in t else None) or backend.util_get_uuid_from_username(t) or t + user = backend._load_user_record(uuid) + if user: + recipients[user.uuid] = user + for s in backend.util_get_sessions_by_user(user): + sessions.add(s) + continue + for bs in backend._sc.iter_sessions(): + if str(id(bs)) == t: + sessions.add(bs) + + counts: dict[str, int] = { network: 0 for network in networks } + skipped = 0 + for bs in sessions: + program = bs.client.program + if program not in networks: + continue + if bs.evt.on_client_alert(alert): + counts[program] += 1 else: - for t in [t.strip() for t in targets.split(',') if t.strip()]: - uuid = self.backend.util_get_uuid_from_email(t) - if uuid: - user = self.backend._load_user_record(uuid) - if user: - for s in self.backend.util_get_sessions_by_user(user): - sessions.add(s) - continue - for bs in self.backend._sc.iter_sessions(): - if str(id(bs)) == t: - sessions.add(bs) - - for bs in sessions: - bs.evt.on_client_alert(icon, url, content_circumcised) - - self.send_reply('ALERT', ts, 'OK') - - - def _m_user(self, ts: str, action: str, uuid: str, field: str = '', *args: str) -> None: - if not self.authenticated: - self.send_numeric(Err.NotAuthenticated) - self.close() - return - - def _parse_value_for_column(col, value_str): - py_type = getattr(col.type, 'python_type', None) - if py_type is not None: + skipped += 1 + delivered = sum(counts.values()) + + emailed = 0 + if email and recipients: + emailed = len(recipients) + INSCtrl.broadcast('alert.email', { + 'id': alert.id, 'subject': (alert.plain().split('\n', 1)[0])[:100], 'text': alert.email_text, 'url': alert.url, + 'recipients': [{ 'uuid': user.uuid, 'email': user.email, 'username': user.username } for user in recipients.values()], + }) + + summary = { 'id': alert.id, 'delivered': delivered, 'networks': counts, 'skipped': skipped, 'emailed': emailed } + backend.recent_alerts.append({ + **alert.summary(), 'date': datetime.utcnow().isoformat() + 'Z', 'by': getattr(self, 'actor', None) or self.identifier, + 'targets': 'all' if everyone else targets, **summary, + }) + self.send_payload('ALR', trid, summary) + INSCtrl.broadcast('alert', summary, exclude = self) + + def _m_mnt(self, trid: str, data: Dict[str, Any]) -> None: + try: + mt_mins = int(data.get('minutes')) + except (ValueError, TypeError): + raise INSFail(Err.TooFewArguments, 'minutes is required') + if mt_mins < 0: + raise INSFail(Err.InvalidArgument, 'minutes must not be negative') + if self.backend.maintenance_mode or self.backend.notify_maintenance: + raise INSFail(Err.ServerInModeAlready) + self.backend.push_maintenance_message(1, mt_mins) + self.send_payload('MNT', trid, None) + INSCtrl.broadcast('maintenance', { 'minutes': mt_mins }, exclude = self) + + def _m_anc(self, trid: str, data: Dict[str, Any]) -> None: + title = str(data.get('title') or '').strip() + content = str(data.get('text') or '').strip() + url = str(data.get('url') or '').strip() + + if not title or not content: + raise INSFail(Err.InvalidArgument, 'title and text are required') + + self.backend.user_service.add_activity(None, ActivityType.Announcement, title = title, text = content, url = url or None) + self.send_payload('ANC', trid, None) + INSCtrl.broadcast('announcement', { 'title': title }, exclude = self) + + def _m_mku(self, trid: str, data: Dict[str, Any]) -> None: + email = _req_str(data, 'email') + username = _req_str(data, 'username') + first_name = str(data.get('first_name') or '') + last_name = str(data.get('last_name') or '') + try: + uin = int(data.get('uin') or 0) + except (ValueError, TypeError): + raise INSFail(Err.InvalidArgument, 'uin must be a number') + password = _req_str(data, 'password') + flags = _client_flags(data) + if len(username) > 32: + raise INSFail(Err.TooManyCharactersUsername) + if len(email) > 254: + raise INSFail(Err.TooManyCharactersEmail) + if username and not username.isalnum(): + raise INSFail(Err.InvalidArgument, 'username must be alphanumeric') + try: + with db.Session() as sess: + user_row = sess.query(db.User).filter_by(email=email).one_or_none() + if user_row is not None: + raise INSFail(Err.EmailTaken) + with open('config/restricted-usernames.json', 'r') as file: + restricted_usernames = json.load(file) + if username.lower() in restricted_usernames: + raise INSFail(Err.RestrictedUseranme) + with open('config/restricted-emails.json', 'r') as file: + restricted_emails = json.load(file) + email_domain = email.lower().split('@')[-1] if '@' in email else '' + if email_domain in restricted_emails: + raise INSFail(Err.RestrictedEmail) + if email_domain in disposable_emails: + raise INSFail(Err.RestrictedEmail) + username_conflict = sess.query(db.User).filter_by(username=username).one_or_none() + email_conflict = sess.query(db.User).filter_by(email=email).one_or_none() + if username_conflict: + raise INSFail(Err.UsernameTaken) + elif email_conflict: + raise INSFail(Err.EmailTaken) + if uin and sess.query(db.User).filter_by(uin=uin).first() is not None: + raise INSFail(Err.UinTaken) + new_user = db.User( + uuid=misc.gen_uuid(), + email=email, + first_name=first_name, + last_name=last_name, + username=username, + uin=uin, + verified_to_login=False, + account_verified=False, + alias_active=False, + friendly_name=email, + groups={}, + settings={}, + suspended=False, + is_tester=False, + is_mvp=False, + show_in_dir=False + ) + _set_passwords_and_prune(new_user, password, flags) + sess.add(new_user) + self.logger.info(f"New user created") + self.logger.info(f"UUID: {new_user.uuid}") + self.logger.info(f"Username: {new_user.username}") + self.logger.info(f"E-mail: {new_user.email}") + self.logger.info(f"UIN: {new_user.uin}") + self.logger.info(f"Flags: {flags}") + sess.commit() + created_uuid = new_user.uuid + except INSFail: + raise + except Exception as e: + self.logger.error(e) + raise INSFail(Err.UserCreationFailed) + try: + domain_user = self.backend._load_user_record(created_uuid) + if domain_user is not None: try: - if py_type is bool: - v = value_str.strip().lower() - return v in ('1', 'true', 'yes', 'on') - if py_type is int: - return int(value_str) - if py_type is float: - return float(value_str) - return py_type(value_str) + detail = self.backend._load_detail(domain_user) except Exception: - return value_str - tname = col.type.__class__.__name__.lower() - if 'json' in tname or 'json' in str(col.type).lower(): - try: - return json.loads(value_str) - except Exception: - return value_str - if 'boolean' in tname: - v = value_str.strip().lower() - return v in ('1', 'true', 'yes', 'on') - if 'integer' in tname or 'int' in tname: - try: - return int(value_str) - except Exception: - return value_str - return value_str - - def set_passwords_and_prune(user_obj, pw: str, flags_list: List[str]): - if 'oldmsn' in flags_list: - user_obj.set_front_data('msn', 'pw_md5', hash.hasher_md5.encode(pw)) - else: - if user_obj._front_data and 'msn' in user_obj._front_data: - user_obj._front_data.pop('msn', None) - flag_modified(user_obj, '_front_data') - - if 'yahoo' in flags_list: - user_obj.set_front_data('ymsg', 'pw_md5_unsalted', hash.hasher_md5.encode(pw, salt='')) - user_obj.set_front_data('ymsg', 'pw_md5crypt', hash.hasher_md5crypt.encode(pw, salt='$1$_2S43d5f')) - else: - if user_obj._front_data and 'ymsg' in user_obj._front_data: - user_obj._front_data.pop('ymsg', None) - flag_modified(user_obj, '_front_data') - - if 'oldaim' in flags_list: - pw_md5_encoded = hash.hasher_md5.encode(pw, identifier='AOL Instant Messenger (SM)') - pw_md5_salt = hash.hasher_md5.extract_salt(pw_md5_encoded) - user_obj.set_front_data('aim', 'pw_md5', pw_md5_encoded) - user_obj.set_front_data('aim', 'pw_md5_v5', hash.hasher_md5.encode_aim5(pw, salt=pw_md5_salt)) - else: - if user_obj._front_data and 'aim' in user_obj._front_data: - user_obj._front_data.pop('aim', None) - flag_modified(user_obj, '_front_data') - - if 'msim' in flags_list: - user_obj.set_front_data('msim', 'pw_sha1', hash.hasher_sha1.encode(pw)) - else: - if user_obj._front_data and 'msim' in user_obj._front_data: - user_obj._front_data.pop('msim', None) - flag_modified(user_obj, '_front_data') - - user_obj.password = hash.hasher.encode(pw) - - if action == 'CREATE': - if len(args) < 4: - return self.send_numeric(Err.TooFewArguments, ts) - email = uuid - username = field - first_name = args[0] - last_name = args[1] + detail = None + self.backend._mark_modified(domain_user, detail=detail) + except Exception as e: + self.logger.error(e) + self.logger.info("post-create backend processing failed") + + self.send_payload('MKU', trid, { 'uuid': created_uuid }) + INSCtrl.broadcast('user.created', { 'uuid': created_uuid }, exclude = self) + + def _m_edu(self, trid: str, data: Dict[str, Any]) -> None: + uuid = _req_str(data, 'uuid') + fields = data.get('fields') + if not isinstance(fields, dict) or not fields: + raise INSFail(Err.TooFewArguments, 'fields must be a non-empty object') + updated = self._user_update(uuid, { str(k): v for k, v in fields.items() }, _client_flags(data)) + self.send_payload('EDU', trid, { 'uuid': uuid, 'updated': updated }) + INSCtrl.broadcast('user.updated', { 'uuid': uuid, 'fields': updated }, exclude = self) + + def _user_update(self, uuid: str, fields: Dict[str, Any], flags: List[str]) -> List[str]: + values = { field: _value_to_str(value) for field, value in fields.items() } + if 'alias_active' in values: try: - uin = int(args[2]) - except Exception: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - password_b64 = args[3] - flags = [f.lower() for f in args[4:]] - try: - pw_bytes = base64.b64decode(password_b64, validate=True) - password = pw_bytes.decode('utf-8') - except Exception: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - if len(username) > 32: - return self.send_numeric(Err.TooManyCharactersUsername, f':USER {ts}') - if len(email) > 254: - return self.send_numeric(Err.TooManyCharactersEmail, f':USER {ts}') - if username and not username.isalnum(): - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - try: - with db.Session() as sess: - user_row = sess.query(db.User).filter_by(email=email).one_or_none() - if user_row is not None: - set_passwords_and_prune(user_row, password, flags) - sess.add(user_row) - created_uuid = user_row.uuid - else: - with open('config/restricted-usernames.json', 'r') as file: - restricted_usernames = json.load(file) - if username.lower() in restricted_usernames: - return self.send_numeric(Err.RestrictedUseranme, f':USER {ts}') - with open('config/restricted-emails.json', 'r') as file: - restricted_emails = json.load(file) - email_domain = email.lower().split('@')[-1] if '@' in email else '' - if email_domain in restricted_emails: - return self.send_numeric(Err.RestrictedEmail, f':USER {ts}') - if email_domain in disposable_emails: - return self.send_numeric(Err.RestrictedEmail, f':USER {ts}') - username_conflict = sess.query(db.User).filter_by(username=username).one_or_none() - email_conflict = sess.query(db.User).filter_by(email=email).one_or_none() - if username_conflict: - return self.send_numeric(Err.UsernameTaken, f':USER {ts}') - elif email_conflict: - return self.send_numeric(Err.EmailTaken, f':USER {ts}') - new_user = db.User( - uuid=misc.gen_uuid(), - email=email, - first_name=first_name, - last_name=last_name, - username=username, - uin=uin, - verified_to_login=False, - account_verified=False, - alias_active=False, - friendly_name=email, - groups={}, - settings={}, - suspended=False, - is_tester=False, - is_mvp=False, - show_in_dir=False - ) - set_passwords_and_prune(new_user, password, flags) - sess.add(new_user) - self.logger.info(f"New user created") - self.logger.info(f"UUID: {new_user.uuid}") - self.logger.info(f"Username: {new_user.username}") - self.logger.info(f"E-mail: {new_user.email}") - self.logger.info(f"UIN: {new_user.uin}") - self.logger.info(f"Flags: {flags}") - sess.commit() - created_uuid = new_user.uuid - except Exception as e: - self.logger.error(e) - return self.send_numeric(Err.UserCreationFailed, f':USER {ts}') - try: - domain_user = self.backend._load_user_record(created_uuid) - if domain_user is not None: - try: - detail = self.backend._load_detail(domain_user) - except Exception: - detail = None - self.backend._mark_modified(domain_user, detail=detail) - except Exception as e: - self.logger.error(e) - self.logger.info("post-create backend processing failed") - - self.send_reply('USER', 'CREATE', ts, created_uuid, 'OK') - return - - elif action == 'UPDATE': - new_raw_value = ' '.join(args) - try: - domain_user = self.backend._load_user_record(uuid) - if domain_user: - for bs in self.backend.util_get_sessions_by_user(domain_user): - try: - bs.close() - except Exception: - pass + self.backend._handle_worklist_notify() + self.backend._worklist_notify.clear() except Exception: traceback.print_exc() - if field == 'alias_active': + _avatar_md5 = None + avatar_old = None + try: + with db.Session() as sess: + user_row = sess.query(db.User).filter_by(uuid=uuid).one_or_none() + if user_row is None: + raise INSFail(Err.UserNotInDB) + avatar_old = user_row.avatar + for field, new_raw_value in values.items(): + md5 = self._user_update_field(sess, user_row, uuid, field, new_raw_value, flags) + if md5 is not None: + _avatar_md5 = md5 + except INSFail: + raise + except Exception: + traceback.print_exc() + raise INSFail(Err.ServerUnknownError) + + try: + domain_user = self.backend._load_user_record(uuid) + except Exception: + domain_user = None + if domain_user is not None: + for field, new_raw_value in values.items(): + if field not in CACHED_USER_FIELDS or not hasattr(domain_user, field): + continue try: - self.backend._handle_worklist_notify() - self.backend._worklist_notify.clear() - except Exception: - traceback.print_exc() - try: - with db.Session() as sess: - user_row = sess.query(db.User).filter_by(uuid=uuid).one_or_none() - if user_row is None: - return self.send_numeric(Err.UserNotInDB, ts) - if field == 'password': - if len(args) < 1: - return self.send_numeric(Err.TooFewArguments, ts) - password_b64 = args[0] - flags = [f.lower() for f in args[1:]] - try: - pw_bytes = base64.b64decode(password_b64, validate=True) - password = pw_bytes.decode('utf-8') - except Exception: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - set_passwords_and_prune(user_row, password, flags) - sess.add(user_row) - try: - self.backend._user_by_uuid.pop(uuid, None) - except Exception as e: - self.logger.error(e) - self.logger.info("Failed to nuke stale user cache") - #elif field not in ('account_verified', 'verified_to_login') and not user_row.verified_to_login: - # return self.send_numeric(Err.EmailNotVerified, ts) - elif field in ('alias_active') and not user_row.account_verified: - return self.send_numeric(Err.EmailNotVerified, ts) - elif field in ('show_in_dir', 'alias_active', 'account_verified' 'verified_to_login', 'suspended', 'is_tester', 'is_mvp'): - col = user_row.__table__.columns[field] - parsed_val = _parse_value_for_column(col, new_raw_value) - setattr(user_row, field, parsed_val) - sess.add(user_row) - elif field.startswith('profile.'): - prof_field = field.split('.', 1)[1] - profile = sess.query(db.UserProfile).filter_by(user_id=user_row.id).one_or_none() - if not profile: - profile = db.UserProfile(user_id=user_row.id) - sess.add(profile) - sess.flush() - if prof_field == 'interests': - try: - interests_json = json.loads(new_raw_value) - if not isinstance(interests_json, list): - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - total_len = 0 - for item in interests_json: - if not isinstance(item, str): - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - if len(item) > 50: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - total_len += len(item) - if total_len > 200: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - profile.interests = interests_json - except json.JSONDecodeError: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - elif prof_field == 'pronouns': - if len(new_raw_value) > 16: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - col = profile.__table__.columns[prof_field] - val = _parse_value_for_column(col, new_raw_value) - setattr(profile, prof_field, val) - elif prof_field == 'website': - if len(new_raw_value) > 75: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - col = profile.__table__.columns[prof_field] - val = _parse_value_for_column(col, new_raw_value) - setattr(profile, prof_field, val) - elif prof_field == 'bio': - if len(new_raw_value) > 200: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - col = profile.__table__.columns[prof_field] - val = _parse_value_for_column(col, new_raw_value) - setattr(profile, prof_field, val) - elif prof_field not in profile.__table__.columns: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - else: - col = profile.__table__.columns[prof_field] - val = _parse_value_for_column(col, new_raw_value) - setattr(profile, prof_field, val) - sess.add(profile) - else: - if field.endswith('_uuid'): - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - if '.' in field: - top, sub = field.split('.', 1) - if top not in user_row.__table__.columns: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - col = user_row.__table__.columns[top] - tname = col.type.__class__.__name__.lower() - if 'json' in tname or 'json' in str(col.type).lower(): - orig = getattr(user_row, top) or {} - try: - subval = json.loads(new_raw_value) - except Exception: - subval = new_raw_value - orig[sub] = subval - setattr(user_row, top, orig) - sess.add(user_row) - else: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - else: - username_conflict = sess.query(db.User).filter_by(username=new_raw_value).one_or_none() - email_conflict = sess.query(db.User).filter_by(email=new_raw_value).one_or_none() - if field not in user_row.__table__.columns: - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - if field == 'username' and len(new_raw_value) > 32: - return self.send_numeric(Err.TooManyCharactersUsername, f':USER {ts}') - if field == 'email' and len(new_raw_value) > 254: - return self.send_numeric(Err.TooManyCharactersEmail, f':USER {ts}') - if field == 'username' and new_raw_value and not new_raw_value.isalnum(): - return self.send_numeric(Err.InvalidArgument, f':USER {ts}') - if field == 'username' and username_conflict: - return self.send_numeric(Err.UsernameTaken, f':USER {ts}') - if field == 'email' and email_conflict: - return self.send_numeric(Err.EmailTaken, f':USER {ts}') - with open('config/restricted-usernames.json', 'r') as file: - restricted_usernames = json.load(file) - if field == 'username' and new_raw_value.lower() in restricted_usernames: - return self.send_numeric(Err.RestrictedUseranme, f':USER {ts}') - if field == 'email': - with open('config/restricted-emails.json', 'r') as file: - restricted_emails = json.load(file) - email_domain = new_raw_value.lower().split('@')[-1] if '@' in new_raw_value else '' - if email_domain in restricted_emails: - return self.send_numeric(Err.RestrictedEmail, f':USER {ts}') - if email_domain in disposable_emails: - return self.send_numeric(Err.RestrictedEmail, f':USER {ts}') - col = user_row.__table__.columns[field] - val = _parse_value_for_column(col, new_raw_value) - setattr(user_row, field, val) - sess.add(user_row) - except Exception: - traceback.print_exc() - return self.send_numeric(Err.ServerUnknownError, ts) - try: - domain_user = self.backend._load_user_record(uuid) - except Exception: - domain_user = None - if field == 'email': - try: - if domain_user: - domain_user.email = new_raw_value + setattr(domain_user, field, _parse_value_for_column(db.User.__table__.columns[field], new_raw_value)) except Exception as e: self.logger.error(e) - self.logger.info("Failed to update cached email") - if field == 'alias_active': + self.logger.info(f"Failed to update cached {field}") + if _avatar_md5: try: - if domain_user: - v = new_raw_value.strip().lower() - domain_user.alias_active = v in ('1', 'true', 'yes', 'on') + domain_user.avatar = _avatar_md5 except Exception as e: self.logger.error(e) - self.logger.info("Failed to update cached alias status") - try: - if domain_user: + self.logger.info("Failed to update cached avatar") + if any(not (field in SOFT_USER_FIELDS or field.startswith('profile.')) for field in values): + for bs in self.backend.util_get_sessions_by_user(domain_user): try: - detail = self.backend._load_detail(domain_user) + bs.close() except Exception: - detail = None - self.backend._mark_modified(domain_user, detail=detail) + pass + try: + try: + detail = self.backend._load_detail(domain_user) + except Exception: + detail = None + self.backend._mark_modified(domain_user, detail=detail) except Exception as e: self.logger.error(e) self.logger.info("Failed while post-processing USER UPDATE") + if _avatar_md5 and _avatar_md5 != avatar_old: + if self.backend.user_service.add_activity(domain_user, ActivityType.DisplayPicture, text = _avatar_md5): + self.backend.notify_whats_new(domain_user) + + for field, new_raw_value in values.items(): + output_value = "[REDACTED]" if field == "password" else ("[IMAGE]" if field == 'avatar_b64' else new_raw_value) if domain_user is not None: - output_value = "[REDACTED]" if field == "password" else new_raw_value self.logger.info(f"{domain_user.username} ({domain_user.email}) has changed user attribute {field} to {output_value}") else: - output_value = "[REDACTED]" if field == "password" else new_raw_value self.logger.info(f"User with UUID {uuid} (unresolved) has changed user attribute {field} to {output_value}") - self.send_reply('USER', 'UPDATE', ts, uuid, 'OK') - return - - elif action == 'DELETE': + return list(values) + + def _user_update_field(self, sess: Any, user_row: Any, uuid: str, field: str, new_raw_value: str, flags: List[str]) -> str | None: + try: + return self._user_update_field_impl(sess, user_row, uuid, field, new_raw_value, flags) + except INSFail as ex: + ex.detail.setdefault('field', field) + raise + + def _user_update_field_impl(self, sess: Any, user_row: Any, uuid: str, field: str, new_raw_value: str, flags: List[str]) -> str | None: + if field == 'is_admin': + if not getattr(self, 'privileged', False): + raise INSFail(Err.InvalidArgument, 'is_admin can only be changed from the admin panel') + user_row.is_admin = _parse_value_for_column(user_row.__table__.columns['is_admin'], new_raw_value) + sess.add(user_row) + return None + if field == 'password': + if not new_raw_value: + raise INSFail(Err.TooFewArguments) + _set_passwords_and_prune(user_row, new_raw_value, flags) + sess.add(user_row) try: - with db.Session() as sess: - user_row = sess.query(db.User).filter_by(uuid=uuid).one_or_none() - if user_row is None: - return self.send_numeric(Err.UserNotInDB, ts) - sess.delete(user_row) - sess.flush() - try: - domain_user = self.backend._load_user_record(uuid) - if domain_user: - for bs in self.backend.util_get_sessions_by_user(domain_user): - try: - bs.close() - except Exception: - pass - self.backend._mark_modified(domain_user, deleted=True) - except Exception as e: - self.logger.error(e) - self.logger.info("Failed while post-processing USER DELETE") - if domain_user is not None: - self.logger.info(f"{domain_user.username} ({domain_user.email}) has deleted their account") - else: - self.logger.info(f"User with UUID {uuid} (unresolved) has deleted their account") - self.send_reply('USER', 'DELETE', ts, uuid, 'OK') - return + self.backend._user_by_uuid.pop(uuid, None) except Exception as e: self.logger.error(e) - self.logger.info("USER DELETE failed") - return self.send_numeric(Err.ServerUnknownError, ts) - + self.logger.info("Failed to nuke stale user cache") + #elif field not in ('account_verified', 'verified_to_login') and not user_row.verified_to_login: + # return self.send_numeric(Err.EmailNotVerified, ts) + elif field == 'alias_active' and not user_row.account_verified: + raise INSFail(Err.EmailNotVerified) + elif field in ('show_in_dir', 'alias_active', 'account_verified', 'verified_to_login', 'suspended', 'is_tester', 'is_mvp'): + col = user_row.__table__.columns[field] + parsed_val = _parse_value_for_column(col, new_raw_value) + if field == 'suspended': + if parsed_val and not user_row.suspended: + user_row.suspended_at = datetime.utcnow() + elif not parsed_val: + user_row.suspended_at = None + setattr(user_row, field, parsed_val) + sess.add(user_row) + elif field == 'avatar_b64': + try: + img_data = base64.b64decode(new_raw_value) + except Exception: + raise INSFail(Err.InvalidArgument) + ext = get_img_type(img_data) + if ext is None: + raise INSFail(Err.ImageInvalid) + if len(img_data) > AVATAR_MAX_SIZE: + raise INSFail(Err.PayloadTooLarge) + try: + _avatar_md5 = store_avatar_file(uuid, img_data, ext) + except Exception: + traceback.print_exc() + raise INSFail(Err.ServerUnknownError) + user_row.avatar = _avatar_md5 + sess.add(user_row) + return _avatar_md5 + elif field.startswith('profile.'): + prof_field = field.split('.', 1)[1] + profile = sess.query(db.UserProfile).filter_by(user_id=user_row.id).one_or_none() + if not profile: + profile = db.UserProfile(user_id=user_row.id) + sess.add(profile) + sess.flush() + if prof_field == 'interests': + try: + interests_json = json.loads(new_raw_value) + if not isinstance(interests_json, list): + raise INSFail(Err.InvalidArgument) + total_len = 0 + for item in interests_json: + if not isinstance(item, str): + raise INSFail(Err.InvalidArgument) + if len(item) > 50: + raise INSFail(Err.InvalidArgument) + total_len += len(item) + if total_len > 200: + raise INSFail(Err.InvalidArgument) + profile.interests = interests_json + except json.JSONDecodeError: + raise INSFail(Err.InvalidArgument) + elif prof_field == 'pronouns': + if len(new_raw_value) > 16: + raise INSFail(Err.InvalidArgument) + col = profile.__table__.columns[prof_field] + val = _parse_value_for_column(col, new_raw_value) + setattr(profile, prof_field, val) + elif prof_field == 'website': + if len(new_raw_value) > 75: + raise INSFail(Err.InvalidArgument) + col = profile.__table__.columns[prof_field] + val = _parse_value_for_column(col, new_raw_value) + setattr(profile, prof_field, val) + elif prof_field == 'bio': + new_raw_value = new_raw_value.replace('\\n', '\n') + if len(new_raw_value) > 200: + raise INSFail(Err.InvalidArgument) + col = profile.__table__.columns[prof_field] + val = _parse_value_for_column(col, new_raw_value) + setattr(profile, prof_field, val) + elif prof_field == 'visibility': + if new_raw_value not in ('public', 'members_only'): + raise INSFail(Err.InvalidArgument) + profile.visibility = new_raw_value + elif prof_field == 'language': + try: + languages = json.loads(new_raw_value) + except json.JSONDecodeError: + raise INSFail(Err.InvalidArgument) + if not isinstance(languages, list) or len(languages) > MAX_PROFILE_LANGUAGES: + raise INSFail(Err.InvalidArgument) + for item in languages: + if not isinstance(item, str) or not LANGUAGE_TAG.fullmatch(item): + raise INSFail(Err.InvalidArgument) + profile.language = list(dict.fromkeys(item.lower() for item in languages)) + elif prof_field not in profile.__table__.columns or prof_field == 'user_id': + raise INSFail(Err.InvalidArgument) + else: + col = profile.__table__.columns[prof_field] + val = _parse_value_for_column(col, new_raw_value) + setattr(profile, prof_field, val) + sess.add(profile) else: - return self.send_numeric(Err.InvalidArgument, ts) - - def _m_allthesessions(self, ts: str, email_filter: str = '') -> None: + if field.endswith('_uuid') or field in ('id', 'uuid', 'password', 'avatar', 'date_created', 'suspended_at'): + raise INSFail(Err.InvalidArgument) + if '.' in field: + top, sub = field.split('.', 1) + if top not in user_row.__table__.columns: + raise INSFail(Err.InvalidArgument) + col = user_row.__table__.columns[top] + tname = col.type.__class__.__name__.lower() + if 'json' in tname or 'json' in str(col.type).lower(): + orig = dict(getattr(user_row, top) or {}) + try: + subval = json.loads(new_raw_value) + except Exception: + subval = new_raw_value + orig[sub] = subval + setattr(user_row, top, orig) + flag_modified(user_row, top) + sess.add(user_row) + else: + raise INSFail(Err.InvalidArgument) + else: + if field not in user_row.__table__.columns: + raise INSFail(Err.InvalidArgument) + if field == 'username' and len(new_raw_value) > 32: + raise INSFail(Err.TooManyCharactersUsername) + if field == 'email' and len(new_raw_value) > 254: + raise INSFail(Err.TooManyCharactersEmail) + if field == 'username' and new_raw_value and not new_raw_value.isalnum(): + raise INSFail(Err.InvalidArgument) + if field == 'username' and sess.query(db.User).filter(db.User.username == new_raw_value, db.User.uuid != uuid).first() is not None: + raise INSFail(Err.UsernameTaken) + if field == 'email' and sess.query(db.User).filter(db.User.email == new_raw_value, db.User.uuid != uuid).first() is not None: + raise INSFail(Err.EmailTaken) + if field == 'uin' and new_raw_value and sess.query(db.User).filter(db.User.uin == new_raw_value, db.User.uuid != uuid).first() is not None: + raise INSFail(Err.UinTaken) + if field == 'username': + with open('config/restricted-usernames.json', 'r') as file: + restricted_usernames = json.load(file) + if new_raw_value.lower() in restricted_usernames: + raise INSFail(Err.RestrictedUseranme) + if field == 'email': + with open('config/restricted-emails.json', 'r') as file: + restricted_emails = json.load(file) + email_domain = new_raw_value.lower().split('@')[-1] if '@' in new_raw_value else '' + if email_domain in restricted_emails: + raise INSFail(Err.RestrictedEmail) + if email_domain in disposable_emails: + raise INSFail(Err.RestrictedEmail) + col = user_row.__table__.columns[field] + val = _parse_value_for_column(col, new_raw_value) + setattr(user_row, field, val) + sess.add(user_row) + return None + + def _m_rmu(self, trid: str, data: Dict[str, Any]) -> None: + uuid = _req_str(data, 'uuid') + backend = self.backend + try: + domain_user = backend.util_delete_user(uuid) + except Exception as e: + self.logger.error(e) + self.logger.info("USER DELETE failed") + raise INSFail(Err.ServerUnknownError) + if domain_user is None: + raise INSFail(Err.UserNotInDB) + self.logger.info(f"{domain_user.username} ({domain_user.email}) has deleted their account") + self.send_payload('RMU', trid, None) + INSCtrl.broadcast('user.deleted', { 'uuid': uuid, 'reason': 'removed' }, exclude = self) + + def _m_gtu(self, trid: str, data: Dict[str, Any]) -> None: + user = self._user_from(data) + info = self._user_info(user, full = True) + with db.Session() as sess: + row = sess.query(db.User).filter_by(uuid = user.uuid).one_or_none() + if row is not None: + front = row._front_data or {} + info['clients'] = [flag for flag, key in (('oldmsn', 'msn'), ('yahoo', 'ymsg'), ('oldaim', 'aim'), ('msim', 'msim')) if key in front] + if getattr(self, 'privileged', False): + info['is_admin'] = bool(row.is_admin) + if row.suspended: + info.update(_suspension(row)) + self.send_payload('GTU', trid, info) + + def _m_lsu(self, trid: str, data: Dict[str, Any]) -> None: + try: + since = int(data.get('since') or 60) + except (ValueError, TypeError): + raise INSFail(Err.InvalidArgument, 'since must be a number of minutes') + online_since = datetime.utcnow() - timedelta(minutes = since) + try: + limit = max(0, min(200, int(data.get('limit') or 0))) + offset = max(0, int(data.get('offset') or 0)) + except (ValueError, TypeError): + raise INSFail(Err.InvalidArgument, 'limit and offset must be numbers') + query = str(data.get('query') or '').strip() + trait = str(data.get('trait') or '').strip() + negate = trait.startswith('!') + trait = trait.lstrip('!') + traits = USER_TRAITS + ('online',) + (('is_admin',) if getattr(self, 'privileged', False) else ()) + if trait and trait not in traits: + raise INSFail(Err.InvalidArgument, 'trait must be one of {}'.format(', '.join(traits)), field = 'trait') + online_uuids = { bs.user.uuid for bs in self.backend._sc.iter_sessions() } + with db.Session() as sess: + total = sess.query(sa.func.count(db.User.id)).scalar() or 0 + recent = sess.query(sa.func.count(db.User.id)).filter(db.User.date_login >= online_since).scalar() or 0 + emails = ([email for (email,) in sess.query(db.User.email).order_by(db.User.email)] if data.get('verbose') else None) + users: list[dict[str, Any]] | None = None + matched = None # type: Optional[int] + if limit: + rows = sess.query(db.User) + if query: + like = '%{}%'.format(query.replace('%', '').replace('_', '')) + rows = rows.filter(sa.or_(db.User.username.ilike(like), db.User.email.ilike(like), db.User.uuid == query)) + if trait == 'online': + signed_in = db.User.uuid.in_(online_uuids) if online_uuids else sa.false() + rows = rows.filter(sa.not_(signed_in) if negate else signed_in) + elif trait: + column = getattr(db.User, trait) + rows = rows.filter(sa.or_(column.is_(None), column == sa.false()) if negate else column == sa.true()) + matched = rows.with_entities(sa.func.count(db.User.id)).scalar() or 0 + users = [ + { + 'uuid': row.uuid, 'username': row.username, 'email': row.email, 'uin': row.uin, + 'date_created': _iso(row.date_created), 'date_login': _iso(row.date_login), 'online': row.uuid in online_uuids, + **{ trait: bool(getattr(row, trait, False)) for trait in USER_TRAITS }, + **({ 'is_admin': bool(row.is_admin) } if getattr(self, 'privileged', False) else {}), + **(_suspension(row) if row.suspended else {}), + } + for row in rows.order_by(db.User.id.desc()).offset(offset).limit(limit) + ] + result = { + 'total': total, 'since': since, 'logged_in_since': recent, + 'online': len(online_uuids), + } # type: Dict[str, Any] + if emails is not None: + result['emails'] = emails + if users is not None: + result['users'] = users + result['matched'] = matched + self.send_payload('LSU', trid, result) + + def _m_lss(self, trid: str, data: Dict[str, Any]) -> None: # TODO: make this a payload command - if not self.authenticated: - self.send_numeric(Err.NotAuthenticated) - self.close() + flt = data.get('filter') or {} + if not isinstance(flt, dict): + raise INSFail(Err.InvalidArgument, 'filter must be an object') + group = str(data.get('group') or 'session').lower() + if group not in ('session', 'user'): + raise INSFail(Err.InvalidArgument, 'group must be session or user') + try: + limit = max(0, int(data.get('limit') or 0)) + offset = max(0, int(data.get('offset') or 0)) + except (ValueError, TypeError): + raise INSFail(Err.InvalidArgument, 'limit and offset must be numbers') + + matched = [bs for bs in self.backend._sc.iter_sessions() if _session_matches(bs, flt)] + + if group == 'user': + users: dict[str, dict[str, Any]] = {} + for bs in matched: + entry = users.get(bs.user.uuid) + if entry is None: + entry = self._user_info(bs.user) + entry['clients'] = [] + users[bs.user.uuid] = entry + entry['clients'].append(bs.client.ToJSON(bs.client)) + items = list(users.values()) + key = 'users' + else: + items = [_session_info(bs) for bs in matched] + key = 'sessions' + total = len(items) + items = items[offset:offset + limit] if limit else items[offset:] + self.send_payload('LSS', trid, { 'count': total, key: items }) + + def _m_gts(self, trid: str, data: Dict[str, Any]) -> None: + target = self._find_session(_req_str(data, 'id')) + info = _session_info(target) + info.update(self._user_info(target.user)) + self.send_payload('GTS', trid, info) + + def _m_kls(self, trid: str, data: Dict[str, Any]) -> None: + if data.get('id'): + sess_id = str(data['id']) + targets = [self._find_session(sess_id)] + for target in targets: + target.close(sess_id=sess_id) + elif data.get('uuid') or data.get('email') or data.get('username'): + targets = list(self.backend.util_get_sessions_by_user(self._user_from(data))) + for target in targets: + target.close() + else: + raise INSFail(Err.TooFewArguments, 'id or uuid is required') + self.send_payload('KLS', trid, { 'killed': len(targets) }) + INSCtrl.broadcast('session.killed', { 'count': len(targets) }, exclude = self) + + def _m_bfd(self, trid: str, data: Dict[str, Any]) -> None: + backend = self.backend + action = str(data.get('action') or 'FEED').upper() + try: + count = min(100, max(1, int(data.get('count') or 20))) + before_id = (int(data['before']) if data.get('before') is not None else None) + after_id = (int(data['after']) if data.get('after') is not None else None) + types = [_activity_type(t) for t in (data.get('types') or [])] + except (ValueError, TypeError, KeyError): + raise INSFail(Err.InvalidArgument, 'invalid count, cursor or type') + + if action == 'FEED': + user = self._user_from(data) + if not beacon_enabled(user): + raise INSFail(Err.BeaconDisabled) + viewer = user + detail = backend._load_detail(user) + publishers = [user] + [ + ctc.head for ctc in detail.contacts.values() if ctc.lists & ContactList.FL and not ctc.lists & ContactList.BL + ] + activities = backend.user_service.get_activities( + [head.uuid for head in publishers], count, announcements = bool(data.get('announcements', True)), + before_id = before_id, after_id = after_id, types = types or None, + ) + elif action == 'USER': + target = self._user_from(data) + viewer = (self._user_from({ 'uuid': data['viewer'] }) if data.get('viewer') else None) + if viewer is not None and not beacon_enabled(viewer): + raise INSFail(Err.BeaconDisabled) + if not self._can_view_activity(viewer, target): + raise INSFail(Err.ActivityNotPermitted) + activities = backend.user_service.get_activities( + [target.uuid], count, before_id = before_id, after_id = after_id, types = types or None, + ) + elif action == 'ANNOUNCEMENTS': + viewer = (self._user_from({ 'uuid': data['viewer'] }) if data.get('viewer') else None) + activities = backend.user_service.get_activities([], count, announcements = True, before_id = before_id, after_id = after_id) + elif action == 'GET': + try: + activity = backend.user_service.get_activity(int(data.get('id'))) + except (ValueError, TypeError): + raise INSFail(Err.InvalidArgument, 'id must be a number') + if activity is None: + raise INSFail(Err.ActivityDoesNotExist) + if activity.user is not None: + viewer = (self._user_from({ 'uuid': data['viewer'] }) if data.get('viewer') else None) + if not self._can_view_activity(viewer, activity.user): + raise INSFail(Err.ActivityNotPermitted) + self.send_payload('BFD', trid, self._social([activity], viewer)[0]) return - sessions_info = [] - for bs in self.backend._sc.iter_sessions(): - if email_filter and bs.user.email != email_filter: - continue - info = f"{id(bs)}|{bs.user.uuid}|{bs.user.email}|{bs.client.ToJSON(bs.client)}" - sessions_info.append(info) - self.send_reply('ALLTHESESSIONS', ts, *sessions_info) + else: + raise INSFail(Err.InvalidArgument, 'unknown activity action') + + self.send_payload('BFD', trid, { + 'activities': self._social(activities, viewer), + 'more': len(activities) >= count, + }) + + def _social(self, activities: List[Activity], viewer: User | None) -> List[Dict[str, Any]]: + service = self.backend.user_service + ids = [activity.id for activity in activities] + reactions = service.get_reactions(ids) + comments = service.get_comments(ids) + result = [] + for activity in activities: + info = _activity_info(activity) + info['reactions'] = [] + for name, uuids in reactions.get(activity.id, {}).items(): + people = [u for u in (self._beacon_user(uuid) for uuid in uuids) if u is not None] + if people: + info['reactions'].append({ + 'name': name, 'count': len(people), 'mine': viewer is not None and any(u.uuid == viewer.uuid for u in people), + 'users': [u.username for u in people[:8]], + }) + shown = [] + for comment_id, uuid, text, date in comments.get(activity.id, []): + author = self._beacon_user(uuid) + if author is None: + continue + shown.append({ + 'id': comment_id, 'text': text, 'date': _iso(date), 'user': _user_brief(author), + 'can_delete': viewer is not None and (author.uuid == viewer.uuid or (activity.user is not None and activity.user.uuid == viewer.uuid)), + }) + info['comment_count'] = len(shown) + info['comments'] = shown[-50:] + info['can_comment'] = activity.user is not None + result.append(info) + return result + + def _beacon_user(self, uuid: str) -> User | None: + user = self.backend._load_user_record(uuid) + return (user if user is not None and beacon_enabled(user) else None) + + def _visible_activity(self, data: Dict[str, Any], viewer: User) -> Activity: + try: + activity = self.backend.user_service.get_activity(int(data.get('id'))) + except (ValueError, TypeError): + raise INSFail(Err.InvalidArgument, 'id must be a number') + if activity is None or (activity.user is not None and not beacon_enabled(activity.user)): + raise INSFail(Err.ActivityDoesNotExist) + if activity.user is not None and not self._can_view_activity(viewer, activity.user): + raise INSFail(Err.ActivityNotPermitted) + return activity + + def _m_bdl(self, trid: str, data: Dict[str, Any]) -> None: + try: + activity_id = int(data.get('id')) + except (ValueError, TypeError): + raise INSFail(Err.InvalidArgument, 'id must be a number') + user = (self._user_from(data) if data.get('uuid') or data.get('email') or data.get('username') else None) + if not self.backend.user_service.delete_activity(activity_id, user.uuid if user is not None else None): + raise INSFail(Err.ActivityDoesNotExist) + if user is not None: + self.backend.notify_whats_new(user) + self.send_payload('BDL', trid, { 'deleted': activity_id }) + INSCtrl.broadcast('activity', { 'deleted': activity_id, 'uuid': user.uuid if user is not None else None }, exclude = self) + + def _m_brx(self, trid: str, data: Dict[str, Any]) -> None: + user = self._user_from(data) + if not beacon_enabled(user): + raise INSFail(Err.BeaconDisabled) + name = str(data.get('reaction') or '').strip().lower() + if name not in REACTIONS: + raise INSFail(Err.ReactionInvalid, 'reaction must be a Twemoji code point sequence, like 1f44d') + activity = self._visible_activity(data, user) + now_set = self.backend.user_service.toggle_reaction(activity.id, user.uuid, name) + info = self._social([activity], user)[0] + self.send_payload('BRX', trid, { 'id': activity.id, 'reaction': name, 'set': now_set, 'reactions': info['reactions'] }) + INSCtrl.broadcast('activity', { 'id': activity.id, 'reaction': name }, exclude = self) + + def _m_bcm(self, trid: str, data: Dict[str, Any]) -> None: + user = self._user_from(data) + if not beacon_enabled(user): + raise INSFail(Err.BeaconDisabled) + action = str(data.get('action') or 'ADD').upper() + service = self.backend.user_service + if action == 'DEL': + try: + comment_id = int(data.get('comment')) + except (ValueError, TypeError): + raise INSFail(Err.InvalidArgument, 'comment must be a number') + if not service.delete_comment(comment_id, user.uuid): + raise INSFail(Err.CommentDoesNotExist) + self.send_payload('BCM', trid, { 'deleted': comment_id }) + return + if action != 'ADD': + raise INSFail(Err.InvalidArgument, 'action must be ADD or DEL') + activity = self._visible_activity(data, user) + if activity.user is None: + raise INSFail(Err.ActivityNotPermitted, 'announcements only take reactions') + text = ' '.join(str(data.get('text') or '').split()) + if not text or len(text) > 255: + raise INSFail(Err.InvalidArgument, 'comments are 1 to 255 characters') + comment_id = service.add_comment(activity.id, user.uuid, text) + info = self._social([activity], user)[0] + self.send_payload('BCM', trid, { 'id': comment_id, 'activity': activity.id, 'comments': info['comments'], 'comment_count': info['comment_count'] }) + INSCtrl.broadcast('activity', { 'id': activity.id, 'comment': comment_id }, exclude = self) + + def _contact_pair(self, data: Dict[str, Any]) -> Tuple[User, User]: + user = self._user_from(data) + if not data.get('target'): + raise INSFail(Err.TooFewArguments, 'target is required') + return user, self._user_from({ 'uuid': data['target'] }) + + def _m_cta(self, trid: str, data: Dict[str, Any]) -> None: + user, target = self._contact_pair(data) + if user.uuid == target.uuid: + raise INSFail(Err.ContactInvalid, 'you cannot add yourself') + group_id = data.get('group') + if group_id is not None and (not isinstance(group_id, str) or not group_id or len(group_id) > 64): + raise INSFail(Err.InvalidArgument, 'group must be a group ID') + new_group = data.get('new_group') + if new_group is not None: + if group_id is not None: + raise INSFail(Err.InvalidArgument, 'group and new_group cannot both be given') + new_group = _group_name(new_group) + try: + added, group = self.backend.util_add_contact(user, target.uuid, group_id = group_id, new_group = new_group) + except error.ContactListIsFull: + raise INSFail(Err.ContactInvalid, 'contact list is full') + except error.GroupDoesNotExist: + raise INSFail(Err.GroupDoesNotExist, 'no such contact group') + except error.GroupAlreadyExists: + raise INSFail(Err.GroupNameInvalid, 'you already have a group with that name') + except error.GroupNameTooLong: + raise INSFail(Err.GroupNameInvalid, 'that group name is too long') + self.send_payload('CTA', trid, { + 'added': added, 'grouped': group is not None, 'group': ({ 'id': group.id, 'name': group.name } if group else None), + 'state': self.backend.util_contact_state(user, target), + }) - def _m_session(self, ts: str, sess_id: str, method: str) -> None: - if not self.authenticated: - self.send_numeric(Err.NotAuthenticated) - self.close() + def _m_ctq(self, trid: str, data: Dict[str, Any]) -> None: + if data.get('targets') is not None: + user = self._user_from(data) + targets = data['targets'] + if not isinstance(targets, list) or len(targets) > 500 or not all(isinstance(t, str) for t in targets): + raise INSFail(Err.InvalidArgument, 'targets must be a list of at most 500 UUIDs') + self.send_payload('CTQ', trid, { 'states': self.backend.util_contact_states(user, targets) }) return - target = None + user, target = self._contact_pair(data) + self.send_payload('CTQ', trid, { 'state': self.backend.util_contact_state(user, target) }) + + def _m_grp(self, trid: str, data: Dict[str, Any]) -> None: + user = self._user_from(data) + action = str(data.get('action') or 'LIST').upper() + created = None + if action == 'ADD': + try: + created = self.backend.util_add_group(user, _group_name(data.get('name'))) + except error.GroupAlreadyExists: + raise INSFail(Err.GroupNameInvalid, 'you already have a group with that name') + except error.GroupNameTooLong: + raise INSFail(Err.GroupNameInvalid, 'that group name is too long') + elif action != 'LIST': + raise INSFail(Err.InvalidArgument, 'action must be LIST or ADD') + reply = { 'groups': [ + { 'id': group.id, 'uuid': group.uuid, 'name': group.name, 'favorite': group.is_favorite } + for group in self.backend.util_contact_groups(user) + ] } # type: Dict[str, Any] + if created is not None: + reply['created'] = { 'id': created.id, 'uuid': created.uuid, 'name': created.name, 'favorite': created.is_favorite } + self.send_payload('GRP', trid, reply) + + def _m_prf(self, trid: str, data: Dict[str, Any]) -> None: + user = self._user_from(data) + changes = data.get('set') or {} + if not isinstance(changes, dict) or any(key not in PREFS or not isinstance(value, bool) for key, value in changes.items()): + raise INSFail(Err.InvalidArgument, 'set takes ' + ', '.join(PREFS) + ' as booleans') + if changes.get('beacon') and not user.account_verified: + raise INSFail(Err.EmailNotVerified, 'verify your e-mail address to use CrossTalk Beacon', field = 'beacon') + if changes: + with db.Session() as sess: + row = sess.query(db.User).filter_by(uuid=user.uuid).one_or_none() + if row is None: + raise INSFail(Err.UserNotInDB) + stored = dict(row.settings or {}) + for key, value in changes.items(): + for legacy in LEGACY_PREFS.get(key, ()): + stored.pop(legacy, None) + if value: + stored.pop(PREFS[key], None) + else: + stored[PREFS[key]] = True + row.settings = stored + flag_modified(row, 'settings') + if user.settings is None: + user.settings = {} + for key, value in changes.items(): + for legacy in LEGACY_PREFS.get(key, ()): + user.settings.pop(legacy, None) + if value: + user.settings.pop(PREFS[key], None) + else: + user.settings[PREFS[key]] = True + INSCtrl.broadcast('user.updated', { 'uuid': user.uuid, 'fields': ['prefs.' + key for key in changes] }, exclude = self) + self.send_payload('PRF', trid, _prefs(user)) + + def _can_view_activity(self, viewer: User | None, target: User) -> bool: + if viewer is None: + return False + if viewer.uuid == target.uuid: + return True + ctc = self.backend._load_detail(viewer).contacts.get(target.uuid) + if ctc is None or not ctc.lists & ContactList.FL or ctc.lists & ContactList.BL: + return False + ctc_rev = self.backend._load_detail(target).contacts.get(viewer.uuid) + if ctc_rev is not None and ctc_rev.lists & ContactList.BL: + return False + return True + + def _m_bst(self, trid: str, data: Dict[str, Any]) -> None: + backend = self.backend + user = self._user_from(data) + message = ' '.join(str(data.get('message') or '').split()) + if len(message) > 255: + raise INSFail(Err.InvalidArgument, 'message is longer than 255 characters') + activity_added = backend.user_service.save_single_roaming(user, { 'message': message }) + sessions = backend.util_get_sessions_by_user(user) + if sessions and message != user.status.message: + sessions[0].me_update({ 'message': message, 'notify_self': True }) + if activity_added: + backend.notify_whats_new(user) + self.send_payload('BST', trid, { 'uuid': user.uuid, 'activity': activity_added }) + if activity_added: + INSCtrl.broadcast('activity', { 'uuid': user.uuid, 'type': ActivityType.StatusMessage.name }, exclude = self) + + async def _m_bph(self, trid: str, data: Dict[str, Any]) -> None: + backend = self.backend + user = self._user_from(data) + if not beacon_enabled(user): + raise INSFail(Err.BeaconDisabled) + title = str(data.get('title') or '').strip() + summary = str(data.get('summary') or '').strip() + if len(title) > 100 or len(summary) > 255: + raise INSFail(Err.InvalidArgument, 'title or summary too long') + try: + img_data = base64.b64decode(str(data.get('data') or ''), validate = True) + except ValueError: + raise INSFail(Err.ImageInvalid) + if not img_data: + raise INSFail(Err.TooFewArguments, 'data is required') + if len(img_data) > PHOTO_MAX_SIZE: + raise INSFail(Err.PayloadTooLarge) + ext = get_img_type(img_data) + if ext is None: + raise INSFail(Err.ImageInvalid) + name = await backend.loop.run_in_executor(None, store_photo_file, user.uuid, img_data, ext) + media_url = 'https://{}/photos/{}/{}'.format(settings.USERSTORAGE_HOST, user.uuid, name) + activity_added = backend.user_service.add_activity(user, ActivityType.Photo, title = title, text = summary, url = media_url) + if activity_added: + backend.notify_whats_new(user) + INSCtrl.broadcast('activity', { 'uuid': user.uuid, 'type': ActivityType.Photo.name }, exclude = self) + self.send_payload('BPH', trid, { 'url': media_url, 'activity': activity_added }) + + def _user_from(self, data: Dict[str, Any]) -> User: + backend = self.backend + uuid = data.get('uuid') + if not uuid and data.get('email'): + uuid = backend.util_get_uuid_from_email(str(data['email'])) + elif not uuid and data.get('username'): + uuid = backend.util_get_uuid_from_username(str(data['username'])) + elif not uuid: + raise INSFail(Err.TooFewArguments, 'uuid is required') + user = (backend._load_user_record(str(uuid)) if uuid else None) + if user is None: + raise INSFail(Err.UserNotInDB) + return user + + def _user_info(self, user: User, *, full: bool = False) -> Dict[str, Any]: + sessions = self.backend.util_get_sessions_by_user(user) + substatus = user.status.substatus + info = { + 'uuid': user.uuid, 'username': user.username, 'email': user.email, 'uin': user.uin, + 'status': substatus.name, 'online': bool(sessions) and not substatus.is_offlineish(), 'sessions': len(sessions), + } # type: Dict[str, Any] + for trait in USER_TRAITS: + info[trait] = getattr(user, trait, None) + info.update(_prefs(user)) + if full: + info.update({ + 'name': user.status.name, 'message': user.status.message, 'avatar': getattr(user, 'avatar', None), + 'date_created': _iso(user.date_created), 'date_login': _iso(user.date_login), + }) + return info + + def _find_session(self, sess_id: str) -> BackendSession: for bs in self.backend._sc.iter_sessions(): if str(id(bs)) == sess_id: - target = bs - break - if not target: - return self.send_numeric(e, ts) - if not method: - return self.send_numeric(105, ts) - if method.upper() == 'GET': - data = ( - sess_id, - target.user.username, - target.user.uuid, - target.user.email, - str(target.user.uin), - target.client.ToJSON(target.client), - str(target.chat_enabled), - ) - self.send_reply('SESSION', ts, *data) - elif method.upper() == 'KILL': - target.close(sess_id=sess_id) - self.send_reply('SESSION', ts, 'KILLED') - else: - self.send_numeric(104, ts) - - def _m_quit(self) -> None: - self.send_reply('QUIT') - self.close() + return bs + raise INSFail(Err.SessionDoesNotExist) #async def _ping_conn(self) -> None: # while True: @@ -743,17 +1372,115 @@ class INSCtrl: # self.current_challenge = hash.gen_salt() # self.send_reply('PING', ':{}'.format(self.current_challenge)) + async def _watchdog(self) -> None: + while not self.closed: + await asyncio.sleep(1) + now = time.monotonic() + if not self.authenticated: + if now - self.connected_at > settings.INS_AUTH_TIMEOUT: + self.logger.info('InterService link did not authenticate in time') + self.close('TMO') + return + continue + if now - self.last_activity > settings.INS_IDLE_TIMEOUT: + self.logger.info(f'InterService link {self.identifier} idle for too long') + self.close('TMO') + return + if self.current_challenge is not None: + if now - self.challenge_sent_at > settings.INS_CHALLENGE_TIMEOUT: + self.logger.info(f'InterService link {self.identifier} did not answer its challenge') + self.send_numeric(Err.ChallengeFailed) + self.close('CHL') + return + elif settings.INS_CHALLENGE_INTERVAL > 0 and now >= self.next_challenge_at: + self.current_challenge = base64.b64encode(secrets.token_bytes(32)).decode('ascii') + self.challenge_sent_at = now + self.send_reply('CHK', '0', self.current_challenge) + def data_received(self, transport: asyncio.BaseTransport, data: bytes) -> None: self.peername = transport.get_extra_info('peername') - for m in self.reader.data_received(data): + if self.closed: return + self.last_activity = time.monotonic() + try: + chunks = self.channel.receive(data) + except INSCryptoError as ex: + self.logger.info(f'Dropping InterService link from {self.peername}: {ex}') + self.close() + return + for chunk in chunks: try: - f = getattr(self, '_m_{}'.format(m[0].lower())) - f(*m[1:]) - except Exception as ex: - self.logger.error(ex) + for m, payload in self.reader.data_received(chunk): + self._dispatch(m, payload) + if self.closed: return + except INSProtocolError as ex: + self.logger.info(f'InterService protocol error from {self.identifier or self.peername}: {ex}') + self.send_numeric(Err.PayloadTooLarge if ex.too_large else Err.InvalidArgument) + self.close() + return - def send_numeric(self, n: int, *m: str) -> None: - self.send_reply('{:03}'.format(n), *m) + def _dispatch(self, m: List[str], payload: Optional[bytes]) -> None: + cmd = m[0].upper() + if cmd == 'HBT': + self._m_hbt() + return + if cmd == 'END': + self._m_end() + return + trid = (m[1] if len(m) > 1 else '0') + if not trid.isdigit(): + self.send_numeric(Err.InvalidArgument) + return + if not self.authenticated and cmd not in PRE_AUTH_COMMANDS: + self.send_numeric(Err.NotAuthenticated, trid) + self.close() + return + if cmd not in JSON_COMMANDS and cmd not in LINE_COMMANDS: + self.send_numeric(Err.UnknownCommand, trid) + return + f = getattr(self, '_m_{}'.format(cmd.lower())) + try: + if cmd in JSON_COMMANDS: + result = f(trid, _decode_payload(payload)) + else: + result = f(trid, *m[2:]) + if asyncio.iscoroutine(result): + task = self.backend.loop.create_task(self._run_async(trid, result)) + self.tasks.add(task) + task.add_done_callback(self.tasks.discard) + except INSFail as ex: + self.send_numeric(ex.code, trid, ex.detail or None) + except Exception as ex: + traceback.print_exc() + self.logger.error(ex) + self.send_numeric(Err.ServerUnknownError, trid) + + async def _run_async(self, trid: str, coro: Coroutine[Any, Any, None]) -> None: + try: + await coro + except INSFail as ex: + self.send_numeric(ex.code, trid, ex.detail or None) + except asyncio.CancelledError: + raise + except Exception as ex: + traceback.print_exc() + self.logger.error(ex) + self.send_numeric(Err.ServerUnknownError, trid) + + @classmethod + def listeners(cls, event: str) -> List['INSCtrl']: + return [link for link in cls._links.values() if not link.closed and (event in link.subscriptions or '*' in link.subscriptions)] + + @classmethod + def broadcast(cls, event: str, data: Dict[str, Any], *, exclude: Optional['INSCtrl'] = None) -> None: + for link in list(cls._links.values()): + if link is exclude or link.closed: + continue + if event not in link.subscriptions and '*' not in link.subscriptions: + continue + link.send_payload('EVT', '0', { 'event': event, **data }) + + def send_numeric(self, n: int, trid: str = '0', detail: Optional[Dict[str, Any]] = None) -> None: + self.send_payload('{:03}'.format(n), trid, detail) def send_reply(self, *m: str) -> None: self.writer.write(m) @@ -761,30 +1488,279 @@ class INSCtrl: if transport is not None: transport.write(self.flush()) - def flush(self) -> bytes: - return self.writer.flush() + def send_payload(self, cmd: str, trid: str, obj: Any) -> None: + payload = (b'' if obj is None else json.dumps(obj, separators = (',', ':'), default = str).encode('utf-8')) + self.writer.write_payload((cmd, trid), payload) + if settings.DEBUG_FULL: + print(payload) + transport = self.transport + if transport is not None: + transport.write(self.flush()) - def close(self) -> None: + def flush(self) -> bytes: + data = self.writer.flush() + if data: + try: + self.channel.send(data) + except INSCryptoError: + pass + return self.channel.drain() + + def close(self, reason: Optional[str] = None) -> None: if self.closed: return + if reason is not None: + self.send_reply('END', reason) self.closed = True #if self.alive_task is not None and not self.alive_task.cancelled: # self.alive_task.cancel() + if self.watchdog is not None: + self.watchdog.cancel() + for task in list(self.tasks): + task.cancel() + if INSCtrl._links.pop(self.link_id, None) is not None: + INSCtrl.broadcast('link', { 'state': 'down', 'identifier': self.identifier, 'link': self.link_id }) if self.authenticated: - self.backend._linked = False + self.backend._linked = bool(INSCtrl._links) + raw_transport = self.raw_transport + if raw_transport is not None: + try: + raw_transport.write(self.flush()) + except Exception: + pass if self.close_callback: self.close_callback() +def _req_str(data: Dict[str, Any], key: str) -> str: + value = data.get(key) + if value is None or value == '': + raise INSFail(Err.TooFewArguments, f'{key} is required') + if not isinstance(value, (str, int)): + raise INSFail(Err.InvalidArgument, f'{key} must be a string') + return str(value) + +def _client_flags(data: Dict[str, Any]) -> List[str]: + clients = data.get('clients') or [] + if not isinstance(clients, list): + raise INSFail(Err.InvalidArgument, 'clients must be a list') + return [str(c).lower() for c in clients] + +def _value_to_str(value: Any) -> str: + if isinstance(value, bool): + return 'true' if value else 'false' + if value is None: + return '' + if isinstance(value, (list, dict)): + return json.dumps(value, separators = (',', ':')) + return str(value) + +def _decode_payload(payload: Optional[bytes]) -> Dict[str, Any]: + if not payload: + return {} + try: + data = json.loads(payload.decode('utf-8')) + except (UnicodeDecodeError, json.JSONDecodeError): + raise INSFail(Err.InvalidArgument, 'payload is not JSON') + if not isinstance(data, dict): + raise INSFail(Err.InvalidArgument, 'payload must be a JSON object') + return data + +def _iso(dt: Optional[datetime]) -> Optional[str]: + if dt is None: + return None + return dt.replace(microsecond = 0).isoformat() + ('Z' if dt.tzinfo is None else '') + +def _suspension(row: db.User) -> Dict[str, Optional[str]]: + days = getattr(settings, 'SUSPENDED_ACCOUNT_DAYS', None) + deleted_at: datetime | None = None + if days is not None: + deleted_at = row.suspended_at + timedelta(days = int(days)) if row.suspended_at else datetime.utcnow() + return { 'suspended_at': _iso(row.suspended_at), 'deleted_at': _iso(deleted_at) } + +def _enum_int(value: Any) -> Any: + if isinstance(value, Enum): + return value.value if isinstance(value.value, int) else value.name + return value + +def _activity_type(value: Any) -> ActivityType: + if isinstance(value, int) or (isinstance(value, str) and value.isdigit()): + return ActivityType(int(value)) + return ActivityType[str(value)] + +def _activity_info(activity: Activity) -> Dict[str, Any]: + user = activity.user + return { + 'id': activity.id, 'type': activity.type.name, 'title': activity.title, 'text': activity.text, 'url': activity.url, + 'date': _iso(activity.date_created), + 'user': None if user is None else _user_brief(user), + } + +def _services(backend: Backend) -> List[Dict[str, Any]]: + services: dict[str, list[int]] = {} + for runner in backend._runners: + ports = services.setdefault(runner.service, []) + if runner.port not in ports: + ports.append(runner.port) + return [{ 'name': name, 'ports': sorted(ports) } for name, ports in services.items()] + +def _user_brief(user: User) -> Dict[str, Any]: + return { + 'uuid': user.uuid, 'username': user.username, 'name': user.status.name, 'avatar': getattr(user, 'avatar', None), + 'show_in_dir': bool(getattr(user, 'show_in_dir', False)), + } + +def _prefs(user: User) -> Dict[str, bool]: + return { 'beacon': beacon_enabled(user), 'dir_online': directory_online_visible(user) } + +def _circle_info(circle: Circle, *, members: bool, backend: Optional[Backend] = None) -> Dict[str, Any]: + info = { + 'chat_id': circle.chat_id, 'name': circle.name, 'owner_uuid': circle.owner_uuid, 'owner_friendly': circle.owner_friendly, + 'membership_access': circle.membership_access, 'members_count': len(circle.memberships), + } # type: Dict[str, Any] + if members: + in_chat: set[str] = set() + chat = backend.chat_get('persistent', circle.chat_id) if backend is not None else None + if chat is not None: + in_chat = { cs.user.uuid for cs in chat.get_roster() } + info['members'] = [ + { + 'uuid': uuid, 'role': _enum_int(getattr(m, 'role', None)), 'state': _enum_int(getattr(m, 'state', None)), + 'username': m.head.username, 'email': m.head.email, 'name': m.head.status.name, + 'in_chat': uuid in in_chat, + 'online': backend is not None and bool(backend.util_get_sessions_by_user(m.head)) and not m.head.status.substatus.is_offlineish(), + 'inviter_email': m.inviter_email, 'invite_message': m.invite_message, + } + for uuid, m in circle.memberships.items() + ] + return info + +def _group_name(value: Any) -> str: + name = ' '.join(str(value or '').split()) + if not name: + raise INSFail(Err.TooFewArguments, 'a group name is required') + if name.lower() in ('(no group)', 'no group'): + raise INSFail(Err.GroupNameInvalid, 'that group name is reserved') + return name + +def _session_info(bs: BackendSession) -> Dict[str, Any]: + user = bs.user + return { + 'id': str(id(bs)), 'uuid': user.uuid, 'username': user.username, 'email': user.email, 'uin': user.uin, + 'client': bs.client.ToJSON(bs.client), 'status': user.status.substatus.name, + 'visible': not user.status.substatus.is_offlineish(), 'chat_enabled': bs.chat_enabled, + } + +def _match(actual: Any, expected: Any) -> bool: + if isinstance(expected, list): + return any(_match(actual, e) for e in expected) + if isinstance(actual, bool) or isinstance(expected, bool): + return bool(actual) == (expected if isinstance(expected, bool) else str(expected).lower() in ('1', 'true', 'yes', 'on')) + if isinstance(actual, str) or isinstance(expected, str): + return str(actual).lower() == str(expected).lower() + return actual == expected + +def _session_matches(bs: BackendSession, flt: Dict[str, Any]) -> bool: + user = bs.user + for key, expected in flt.items(): + if key in USER_TRAITS or key in ('uuid', 'email', 'username', 'uin'): + actual = getattr(user, key, None) + elif key in ('program', 'version', 'via'): + actual = getattr(bs.client, key) + elif key == 'status': + actual = user.status.substatus.name + elif key == 'visible': + actual = not user.status.substatus.is_offlineish() + elif key == 'beacon': + actual = beacon_enabled(user) + elif key == 'dir_online': + actual = directory_online_visible(user) + elif key == 'chat_enabled': + actual = bs.chat_enabled + elif key == 'id': + actual = str(id(bs)) + else: + raise INSFail(Err.InvalidArgument, f'unknown filter {key}') + if not _match(actual, expected): + return False + return True + +def _parse_value_for_column(col, value_str): + py_type = getattr(col.type, 'python_type', None) + if py_type is not None: + try: + if py_type is bool: + v = value_str.strip().lower() + return v in ('1', 'true', 'yes', 'on') + if py_type is int: + return int(value_str) + if py_type is float: + return float(value_str) + return py_type(value_str) + except Exception: + return value_str + tname = col.type.__class__.__name__.lower() + if 'json' in tname or 'json' in str(col.type).lower(): + try: + return json.loads(value_str) + except Exception: + return value_str + if 'boolean' in tname: + v = value_str.strip().lower() + return v in ('1', 'true', 'yes', 'on') + if 'integer' in tname or 'int' in tname: + try: + return int(value_str) + except Exception: + return value_str + return value_str + +def _set_passwords_and_prune(user_obj, pw: str, flags_list: List[str]): + if 'oldmsn' in flags_list: + user_obj.set_front_data('msn', 'pw_md5', hash.hasher_md5.encode(pw)) + else: + if user_obj._front_data and 'msn' in user_obj._front_data: + user_obj._front_data.pop('msn', None) + flag_modified(user_obj, '_front_data') + + if 'yahoo' in flags_list: + user_obj.set_front_data('ymsg', 'pw_md5_unsalted', hash.hasher_md5.encode(pw, salt='')) + user_obj.set_front_data('ymsg', 'pw_md5crypt', hash.hasher_md5crypt.encode(pw, salt='$1$_2S43d5f')) + else: + if user_obj._front_data and 'ymsg' in user_obj._front_data: + user_obj._front_data.pop('ymsg', None) + flag_modified(user_obj, '_front_data') + + if 'oldaim' in flags_list: + pw_md5_encoded = hash.hasher_md5.encode(pw, identifier='AOL Instant Messenger (SM)') + pw_md5_salt = hash.hasher_md5.extract_salt(pw_md5_encoded) + user_obj.set_front_data('aim', 'pw_md5', pw_md5_encoded) + user_obj.set_front_data('aim', 'pw_md5_v5', hash.hasher_md5.encode_aim5(pw, salt=pw_md5_salt)) + else: + if user_obj._front_data and 'aim' in user_obj._front_data: + user_obj._front_data.pop('aim', None) + flag_modified(user_obj, '_front_data') + + if 'msim' in flags_list: + user_obj.set_front_data('msim', 'pw_sha1', hash.hasher_sha1.encode(pw)) + else: + if user_obj._front_data and 'msim' in user_obj._front_data: + user_obj._front_data.pop('msim', None) + flag_modified(user_obj, '_front_data') + + user_obj.password = hash.hasher.encode(pw) + class INSReader: - __slots__ = ('_logger', '_data') + __slots__ = ('_logger', '_data', 'max_payload') _logger: misc.Logger _data: bytes + max_payload: int def __init__(self, logger: misc.Logger) -> None: self._logger = logger self._data = b'' + self.max_payload = MAX_PAYLOAD_PRE_AUTH - def data_received(self, data: bytes) -> Iterable[List[str]]: + def data_received(self, data: bytes) -> Iterable[Tuple[List[str], Optional[bytes]]]: if self._data: self._data += data else: @@ -793,32 +1769,41 @@ class INSReader: m = self._read() if m is None: break - self._logger.debug('[Client]', *m) + if not m[0]: + continue + if settings.DEBUG_FULL: + self._logger.debug('[Client]', *m) + else: + self._logger.debug('[Client]', *m[0], *(('<{} bytes>'.format(len(m[1])),) if m[1] is not None else ())) yield m - def _read(self) -> Optional[List[str]]: + def _read(self) -> Optional[Tuple[List[str], Optional[bytes]]]: try: i = self._data.index(b'\r\n') except ValueError: + if len(self._data) > MAX_LINE: + raise INSProtocolError('command line too long') return None - + if i > MAX_LINE: + raise INSProtocolError('command line too long') + chunk = self._data[:i].decode('utf-8', errors='replace') - self._data = self._data[i+2:] - + end = i + 2 + if '\r' in chunk or '\n' in chunk: self._logger.info('Embedded CR/LF in incoming line; whack his peepee') chunk = chunk.replace('\r', ' ').replace('\n', ' ') - + toks = [] while True: chunk = chunk.lstrip(' ') if not chunk: break - + if chunk[:1] == ':': toks.append(chunk[1:]) break - + if chunk[0] in ('"', "'"): quote_char = chunk[0] j = 1 @@ -852,7 +1837,7 @@ class INSReader: toks.append(inner) break continue - + k = chunk.find(' ') if k < 0: tok = chunk @@ -867,7 +1852,26 @@ class INSReader: toks.append(tok) if not chunk: break - return toks + + if not toks: + self._data = self._data[end:] + return toks, None + + payload = None + if toks[-1].startswith('#'): + try: + length = int(toks[-1][1:]) + except ValueError: + raise INSProtocolError(f'{toks[0]} with a bad payload length') + if length < 0 or length > self.max_payload: + raise INSProtocolError(f'{toks[0]} payload of {length} bytes', too_large = True) + if len(self._data) < end + length: + return None + payload = self._data[end:end + length] + toks = toks[:-1] + end += length + self._data = self._data[end:] + return toks, payload class INSWriter: __slots__ = ('_logger', '_buf') @@ -890,10 +1894,14 @@ class INSWriter: escaped = s.replace('\\', '\\\\').replace('"', '\\"') s = f'"{escaped}"' safe_parts.append(s) - self._logger.debug('[Server]', *safe_parts) + self._logger.debug('[Server]', *m) self._buf.write(' '.join(safe_parts).encode('utf-8')) self._buf.write(b'\r\n') - + + def write_payload(self, m: Iterable[Any], payload: bytes) -> None: + self.write((*m, '#{}'.format(len(payload)))) + self._buf.write(payload) + def flush(self) -> bytes: data = self._buf.getvalue() if data: @@ -905,8 +1913,13 @@ class INSWriter: class Err: AuthenticationFailed = 101 NotAuthenticated = 102 + UnknownCommand = 103 InvalidArgument = 104 TooFewArguments = 105 + PayloadTooLarge = 106 + ProtocolVersionUnsupported = 107 + ChallengeFailed = 108 + AlreadyAuthenticated = 109 CircleDoesNotExist = 200 CircleRoleInvalid = 202 CircleMemberInvalid = 203 @@ -915,9 +1928,11 @@ class Err: DoesntHaveSufficientPermissions = 206 CantLeaveCircle = 207 ServerUnknownError = 300 + SessionDoesNotExist = 301 ServerInModeAlready = 310 UsernameTaken = 410 EmailTaken = 411 + UinTaken = 412 RestrictedUseranme = 415 RestrictedEmail = 416 EmailNotVerified = 419 @@ -925,7 +1940,16 @@ class Err: TooManyCharactersEmail = 426 UserCreationFailed = 427 UserNotInDB = 428 + ActivityDoesNotExist = 501 + ActivityNotPermitted = 502 + ImageInvalid = 503 + BeaconDisabled = 504 + CommentDoesNotExist = 505 + ReactionInvalid = 506 + ContactInvalid = 430 + GroupDoesNotExist = 431 + GroupNameInvalid = 432 class StatusCode: - CircleActionSuccessful = 201 \ No newline at end of file + CircleActionSuccessful = 201 diff --git a/core/interservice/entry.py b/core/interservice/entry.py index de38bd3..c092252 100644 --- a/core/interservice/entry.py +++ b/core/interservice/entry.py @@ -1,44 +1,90 @@ from typing import Optional, Callable -import asyncio +import asyncio, ipaddress from core.backend import Backend from util.misc import Logger import settings +from .crypto import load_or_generate_server_keys, fingerprint from .ctrl import INSCtrl +from .registry import ClientRegistry -def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None: +IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network + +def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> ClientRegistry: from util.misc import ProtocolRunner - backend.add_runner(ProtocolRunner('0.0.0.0', 4309, ListenerINS, args = ['InterService', backend, INSCtrl], service = 'InterService')) + keys = load_or_generate_server_keys(settings.INS_KEY_DIR) + if keys.generated: + print(f'[InterService] Generated the InterService host key in {settings.INS_KEY_DIR}') + print(f'[InterService] Host key {fingerprint(keys.host.public_key())}') + registry = ClientRegistry(keys.public_raw) + active = [record for record in registry.clients() if not record.revoked] + if not active: + print('[InterService] No clients are enrolled yet. Make an enrollment code for each one in the admin panel (InterService)') + else: + print(f'[InterService] {len(active)} enrolled client(s)') + INSCtrl.configure(keys, registry) + INSCtrl.attach(backend) + allowed = parse_networks(settings.INS_ALLOWED_IPS) + backend.add_runner(ProtocolRunner(settings.INS_HOST, settings.INS_PORT, ListenerINS, args = ['InterService', backend, INSCtrl, allowed], service = 'InterService')) + return registry + +def parse_networks(entries: list[str]) -> list[IPNetwork]: + return [ipaddress.ip_network(str(entry).strip(), strict = False) for entry in entries] + +def is_allowed(host: str, allowed: list[IPNetwork]) -> bool: + try: + addr = ipaddress.ip_address(host.split('%', 1)[0]) + except ValueError: + return False + candidates: list[ipaddress.IPv4Address | ipaddress.IPv6Address] = [addr] + if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None: + candidates.append(addr.ipv4_mapped) + return any(candidate in network for candidate in candidates for network in allowed if candidate.version == network.version) class ListenerINS(asyncio.Protocol): logger: Logger backend: Backend controller: INSCtrl transport: Optional[asyncio.WriteTransport] + allowed: list[IPNetwork] - def __init__(self, logger_prefix: str, backend: Backend, controller_factory: Callable[[Logger, str, Backend], INSCtrl]) -> None: + def __init__( + self, logger_prefix: str, backend: Backend, controller_factory: Callable[[Logger, str, Backend], INSCtrl], allowed: list[IPNetwork], + ) -> None: super().__init__() self.logger = Logger(logger_prefix, self) self.backend = backend self.controller = controller_factory(self.logger, 'direct', backend) self.controller.close_callback = self._on_close self.transport = None + self.allowed = allowed def connection_made(self, transport: asyncio.BaseTransport) -> None: assert isinstance(transport, asyncio.WriteTransport) + peername = transport.get_extra_info('peername') + host = (peername[0] if peername else '') + if not is_allowed(host, self.allowed): + self.logger.info(f'Refused InterService connection from unauthorized address {host}') + self.controller.closed = True + transport.abort() + return self.transport = transport self.logger.log_connect() + self.controller.connection_made(transport) def connection_lost(self, exc: Optional[Exception]) -> None: + if self.transport is None: + return self.controller.close() self.logger.log_disconnect() self.transport = None def data_received(self, data: bytes) -> None: transport = self.transport - assert transport is not None + if transport is None: + return if self.backend.maintenance_mode: transport.close() return diff --git a/core/interservice/local.py b/core/interservice/local.py new file mode 100644 index 0000000..31a5d6b --- /dev/null +++ b/core/interservice/local.py @@ -0,0 +1,72 @@ +from types import SimpleNamespace +from typing import Any, Dict, Optional +import asyncio + +from core.backend import Backend +from util.misc import Logger +import settings + +from .ctrl import INSCtrl, INSFail, JSON_COMMANDS + +class LocalINSError(Exception): + code: int + detail: Dict[str, Any] + + def __init__(self, code: int, detail: Optional[Dict[str, Any]] = None) -> None: + self.code = code + self.detail = detail or {} + super().__init__('InterService error {:03}{}'.format(code, ': ' + self.message if self.message else '')) + + @property + def message(self) -> str: + return str(self.detail.get('error') or '') + +class LocalLink(INSCtrl): + def __init__(self, backend: Backend, actor: str) -> None: + self.logger = Logger('Admin', self) + self.backend = backend + self.identifier = 'admin' + self.authenticated = True + self.closed = False + self.link_id = 'local' + self.client_record = None + self.client_info = { 'program': 'admin panel', 'version': settings.VERSION } + self.subscriptions = set() + self.tasks = set() + self.peername = ('127.0.0.1', 0) + self.transport = None + self.raw_transport = None + self.channel = SimpleNamespace(post_quantum = False, binding = b'', enrolled = False) + self.privileged = True + self.actor = actor + self._reply: tuple[str, Any] | None = None + + def send_payload(self, cmd: str, trid: str, obj: Any) -> None: + self._reply = (cmd, obj) + + def send_reply(self, *m: str) -> None: + self._reply = (m[0] if m else '', list(m[1:])) + + def close(self, reason: Optional[str] = None) -> None: + pass + + async def call(self, cmd: str, data: Optional[Dict[str, Any]] = None) -> Any: + cmd = cmd.upper() + if cmd not in JSON_COMMANDS: + raise ValueError('{} is not a JSON command'.format(cmd)) + handler = getattr(self, '_m_{}'.format(cmd.lower())) + self._reply = None + self.logger.info(f'{self.actor} ran {cmd}') + try: + result = handler('1', dict(data or {})) + if asyncio.iscoroutine(result): + await result + except INSFail as ex: + raise LocalINSError(ex.code, ex.detail) + reply = self._reply + if reply is None: + return None + name, payload = reply + if name.isdigit(): + raise LocalINSError(int(name), payload if isinstance(payload, dict) else None) + return payload diff --git a/core/interservice/registry.py b/core/interservice/registry.py new file mode 100644 index 0000000..e9ed137 --- /dev/null +++ b/core/interservice/registry.py @@ -0,0 +1,313 @@ +from collections import deque +from dataclasses import dataclass +from datetime import datetime, timedelta +from typing import Any, Callable, Deque, Dict, List, Optional, Tuple +import hashlib, hmac, ipaddress, secrets, time + +import core.db as db +import settings + +from .crypto import ( + ClientHello, INSRejected, Reject, b64, unb64, ed25519_public, make_enrollment_code, fingerprint, CODE_ID_SIZE, CODE_SECRET_SIZE, +) + +MAX_FAILURES = 10 +FAIL_WINDOW = 600 +DEFAULT_CODE_HOURS = 24 + +IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network + +def normalize_address(host: str) -> str: + try: + addr = ipaddress.ip_address(host.split('%', 1)[0]) + except ValueError: + return host + if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None: + addr = addr.ipv4_mapped + return str(addr) + +def parse_address_list(entries: List[str]) -> List[str]: + result = [] # type: List[str] + for entry in entries: + entry = entry.strip() + if not entry: + continue + if '/' in entry: + value = str(ipaddress.ip_network(entry, strict = False)) + else: + value = normalize_address(str(ipaddress.ip_address(entry))) + if value not in result: + result.append(value) + return result + +def address_allowed(host: str, allowed: List[str]) -> bool: + try: + addr = ipaddress.ip_address(normalize_address(host)) + except ValueError: + return False + for entry in allowed: + try: + if '/' in entry: + if addr in ipaddress.ip_network(entry, strict = False): + return True + elif addr == ipaddress.ip_address(entry): + return True + except ValueError: + continue + return False + +@dataclass +class ClientRecord: + id: int + identifier: str + label: str + transport_public: bytes + auth_public: bytes + machine: bytes + addresses: List[str] + created: datetime + last_seen: Optional[datetime] + last_address: Optional[str] + revoked: bool + revoked_at: Optional[datetime] + + @property + def fingerprint(self) -> str: + return fingerprint(self.transport_public) + +@dataclass +class EnrollmentRecord: + id: int + code_id: str + identifier: str + label: str + address: Optional[str] + created_by: Optional[str] + created: datetime + expires: datetime + used: Optional[datetime] + client_id: Optional[int] + + @property + def state(self) -> str: + if self.used is not None: + return 'used' + if self.expires <= datetime.utcnow(): + return 'expired' + return 'waiting' + +def _client_from_row(row: Any) -> ClientRecord: + return ClientRecord( + row.id, row.identifier, row.label or '', unb64(row.transport_public), unb64(row.auth_public), bytes.fromhex(row.machine), + list(row.addresses or []), row.date_created, row.date_last_seen, row.last_address, bool(row.revoked), row.date_revoked, + ) + +def _enrollment_from_row(row: Any) -> EnrollmentRecord: + return EnrollmentRecord( + row.id, row.code_id, row.identifier, row.label or '', row.address, row.created_by, row.date_created, row.date_expires, + row.date_used, row.client_id, + ) + +class ClientRegistry: + __slots__ = ('host_public', '_by_key', '_failures', 'on_revoke') + + host_public: bytes + _by_key: Dict[bytes, ClientRecord] + _failures: Dict[str, Deque[float]] + on_revoke: Optional[Callable[[ClientRecord], None]] + + def __init__(self, host_public: bytes) -> None: + self.host_public = host_public + self._by_key = {} + self._failures = {} + self.on_revoke = None + self.reload() + + def reload(self) -> None: + with db.Session() as sess: + self._by_key = { record.transport_public: record for record in (_client_from_row(row) for row in sess.query(db.InsClient)) } + + def clients(self) -> List[ClientRecord]: + return sorted(self._by_key.values(), key = lambda record: (record.revoked, record.identifier.lower(), record.label.lower(), record.id)) + + def get(self, client_id: int) -> Optional[ClientRecord]: + for record in self._by_key.values(): + if record.id == client_id: + return record + return None + + def _fail(self, address: str, reason: int, logger: Any, detail: str) -> INSRejected: + now = time.monotonic() + failures = self._failures.setdefault(address, deque()) + failures.append(now) + while failures and now - failures[0] > FAIL_WINDOW: + failures.popleft() + if logger is not None: + logger.info(f'InterService client from {address} turned away: {detail}') + return INSRejected(reason) + + def _throttled(self, address: str) -> bool: + failures = self._failures.get(address) + if not failures: + return False + now = time.monotonic() + while failures and now - failures[0] > FAIL_WINDOW: + failures.popleft() + return len(failures) >= MAX_FAILURES + + def resolve(self, hello: ClientHello, peer: str, logger: Any = None) -> ClientRecord: + address = normalize_address(peer) + if self._throttled(address): + raise INSRejected(Reject.TooManyAttempts) + if hello.enrollment is not None: + return self._enroll(hello, address, logger) + record = self._by_key.get(hello.transport_public) + if record is None: + raise self._fail(address, Reject.UnknownKey, logger, 'unknown client key') + if record.revoked: + raise self._fail(address, Reject.Revoked, logger, f'revoked key of {record.identifier} "{record.label}"') + if not address_allowed(address, record.addresses): + raise self._fail(address, Reject.WrongAddress, logger, f'key of {record.identifier} "{record.label}" used from an address it is not bound to') + if not hmac.compare_digest(record.machine, hello.machine): + raise self._fail(address, Reject.WrongMachine, logger, f'key of {record.identifier} "{record.label}" used from a different machine or OS install') + return record + + def _enroll(self, hello: ClientHello, address: str, logger: Any) -> ClientRecord: + enrollment = hello.enrollment + assert enrollment is not None + now = datetime.utcnow() + if enrollment.identifier not in settings.INS_IDENTIFIERS: + raise self._fail(address, Reject.WrongIdentifier, logger, f'enrollment for unknown identifier "{enrollment.identifier}"') + if hello.transport_public in self._by_key: + raise self._fail(address, Reject.BadEnrollment, logger, 'enrollment with a key that is already enrolled') + try: + ed25519_public(enrollment.auth_public) + except Exception: + raise self._fail(address, Reject.BadEnrollment, logger, 'enrollment with an invalid auth key') + with db.Session() as sess: + row = sess.query(db.InsEnrollment).filter(db.InsEnrollment.code_id == enrollment.code_id.hex()).one_or_none() + secret_hash = hashlib.sha256(enrollment.secret).hexdigest() + if row is None or not hmac.compare_digest(row.secret_hash, secret_hash): + raise self._fail(address, Reject.BadEnrollment, logger, 'unknown enrollment code') + if row.date_used is not None: + raise self._fail(address, Reject.BadEnrollment, logger, f'enrollment code for {row.identifier} used again') + if row.date_expires <= now: + raise self._fail(address, Reject.BadEnrollment, logger, f'expired enrollment code for {row.identifier}') + if row.identifier != enrollment.identifier: + raise self._fail(address, Reject.WrongIdentifier, logger, f'enrollment code for {row.identifier} used for {enrollment.identifier}') + if row.address and not address_allowed(address, [row.address]): + raise self._fail(address, Reject.WrongAddress, logger, f'enrollment code for {row.identifier} used from an address it was not made for') + label = (enrollment.label or row.label or enrollment.identifier)[:100] + client_row = db.InsClient( + identifier = enrollment.identifier, label = label, transport_public = b64(hello.transport_public), + auth_public = b64(enrollment.auth_public), machine = hello.machine.hex(), addresses = [address], + date_created = now, revoked = False, + ) + sess.add(client_row) + sess.flush() + row.date_used = now + row.client_id = client_row.id + record = _client_from_row(client_row) + replaced = [ + other for other in self._by_key.values() + if not other.revoked and other.identifier == record.identifier and hmac.compare_digest(other.machine, record.machine) + ] + for other in replaced: + other_row = sess.query(db.InsClient).filter(db.InsClient.id == other.id).one_or_none() + if other_row is not None: + other_row.revoked = True + other_row.date_revoked = now + self._by_key[record.transport_public] = record + for other in replaced: + other.revoked = True + other.revoked_at = now + if self.on_revoke is not None: + self.on_revoke(other) + if logger is not None: + logger.info(f'InterService client {record.identifier} "{record.label}" enrolled from {address} (key {record.fingerprint})') + return record + + def seen(self, record: ClientRecord, peer: str) -> None: + now = datetime.utcnow() + address = normalize_address(peer) + record.last_seen = now + record.last_address = address + with db.Session() as sess: + row = sess.query(db.InsClient).filter(db.InsClient.id == record.id).one_or_none() + if row is not None: + row.date_last_seen = now + row.last_address = address + + def create_code( + self, identifier: str, *, label: str = '', address: Optional[str] = None, hours: int = DEFAULT_CODE_HOURS, + created_by: Optional[str] = None, + ) -> Tuple[str, EnrollmentRecord]: + if identifier not in settings.INS_IDENTIFIERS: + raise ValueError('unknown identifier') + if address: + address = parse_address_list([address])[0] + code_id = secrets.token_bytes(CODE_ID_SIZE) + secret = secrets.token_bytes(CODE_SECRET_SIZE) + now = datetime.utcnow() + with db.Session() as sess: + row = db.InsEnrollment( + code_id = code_id.hex(), secret_hash = hashlib.sha256(secret).hexdigest(), identifier = identifier, label = label[:100], + address = address or None, created_by = created_by, date_created = now, + date_expires = now + timedelta(hours = max(1, min(hours, 24 * 30))), + ) + sess.add(row) + sess.flush() + record = _enrollment_from_row(row) + return make_enrollment_code(self.host_public, code_id, secret), record + + def codes(self) -> List[EnrollmentRecord]: + with db.Session() as sess: + rows = sess.query(db.InsEnrollment).order_by(db.InsEnrollment.date_created.desc()).limit(200).all() + return [_enrollment_from_row(row) for row in rows] + + def cancel_code(self, enrollment_id: int) -> bool: + with db.Session() as sess: + row = sess.query(db.InsEnrollment).filter(db.InsEnrollment.id == enrollment_id).one_or_none() + if row is None or row.date_used is not None: + return False + sess.delete(row) + return True + + def revoke(self, client_id: int) -> Optional[ClientRecord]: + record = self.get(client_id) + if record is None or record.revoked: + return record + now = datetime.utcnow() + with db.Session() as sess: + row = sess.query(db.InsClient).filter(db.InsClient.id == client_id).one_or_none() + if row is not None: + row.revoked = True + row.date_revoked = now + record.revoked = True + record.revoked_at = now + if self.on_revoke is not None: + self.on_revoke(record) + return record + + def delete(self, client_id: int) -> bool: + record = self.get(client_id) + if record is None or not record.revoked: + return False + with db.Session() as sess: + sess.query(db.InsClient).filter(db.InsClient.id == client_id).delete(synchronize_session = False) + self._by_key.pop(record.transport_public, None) + return True + + def set_addresses(self, client_id: int, addresses: List[str]) -> ClientRecord: + record = self.get(client_id) + if record is None: + raise KeyError(client_id) + parsed = parse_address_list(addresses) + if not parsed: + raise ValueError('at least one address is needed') + with db.Session() as sess: + row = sess.query(db.InsClient).filter(db.InsClient.id == client_id).one_or_none() + if row is not None: + row.addresses = parsed + record.addresses = parsed + return record diff --git a/core/models.py b/core/models.py index 9abd6a5..60534a8 100644 --- a/core/models.py +++ b/core/models.py @@ -144,11 +144,36 @@ class Contact: if found_group is not None: self._groups.discard(group) +AIM_PD_KEY = 'AIM_PD' +AIM_SSI_KEY = 'AIM_SSI' +AIM_CLASS_FREE = 0x0010 + +def _aim_pd_mode(user: User) -> Optional[Dict[str, Any]]: + pd = user.settings.get(AIM_PD_KEY) + if not isinstance(pd, dict) or pd.get('mode') not in (1, 2, 3, 4, 5): + return None + if user.settings.get('BLP', 'AL') != pd.get('blp'): + return None + return pd + def _is_blocking(blocker: User, blockee: User) -> bool: detail = blocker.detail assert detail is not None contact = detail.contacts.get(blockee.uuid) lists = (contact and contact.lists or 0) + pd = _aim_pd_mode(blocker) + if pd is not None: + mask = pd.get('mask') + if mask is not None and not (int(mask) & AIM_CLASS_FREE): return True + mode = pd['mode'] + if mode == 1: return False + if mode == 2: return True + if mode == 4: return bool(lists & ContactList.BL) + if mode == 5: return not (lists & ContactList.FL) + # mode 3: only explicit permits (AL without FL, or AL entries the client listed itself) get through + name = blockee.username.lower() + permits = (blocker.settings.get(AIM_SSI_KEY) or {}).get('permits', []) + return not (lists & ContactList.AL and (not lists & ContactList.FL or name in permits)) if lists & ContactList.BL: return True if lists & ContactList.AL: return False return (blocker.settings.get('BLP', 'AL') == 'BL') @@ -399,6 +424,35 @@ class TextWithData: self.text = text self.yahoo_utf8 = yahoo_utf8 +class ActivityType(IntEnum): + StatusMessage = 1 + Photo = 2 + DisplayPicture = 3 + Announcement = 20 + +class Activity: + __slots__ = ('id', 'user', 'type', 'title', 'text', 'url', 'date_created') + + id: int + user: Optional[User] + type: ActivityType + title: Optional[str] + text: Optional[str] + url: Optional[str] + date_created: datetime + + def __init__( + self, id: int, user: Optional[User], type: ActivityType, title: Optional[str], text: Optional[str], url: Optional[str], date_created: datetime, + ) -> None: + self.id = id + # `None` for service announcements + self.user = user + self.type = type + self.title = title + self.text = text + self.url = url + self.date_created = date_created + class RoamingInfo: __slots__ = ('name', 'name_last_modified', 'message', 'message_last_modified') diff --git a/core/stats.py b/core/stats.py index 954d153..fc96b7e 100644 --- a/core/stats.py +++ b/core/stats.py @@ -1,5 +1,6 @@ -from typing import Dict, Any, Optional -from datetime import datetime +from typing import Dict, Any, Optional, List, Iterable, Tuple +from datetime import datetime, timedelta +import base64, time import sqlalchemy as sa from sqlalchemy.orm import declarative_base from HLL import HyperLogLog @@ -9,19 +10,43 @@ from core.client import Client from core.models import User from util.json_type import JSONType +HOURS_KEPT = 48 +DAYS_KEPT = 35 + class Stats: - __slots__ = ('logged_in', 'by_client', '_conn', '_client_id_cache') + __slots__ = ( + 'logged_in', 'by_client', '_conn', '_client_id_cache', 'started', '_day', '_day_stats', '_pending_days', '_past_days', + '_hours', '_peak_record', '_collect_hour', + ) logged_in: int by_client: Dict[int, Dict[str, Any]] _conn: Conn _client_id_cache: Optional[Dict[Client, int]] + started: datetime + _day: int + _day_stats: Dict[str, Any] + _pending_days: Dict[int, Dict[str, Any]] + _past_days: Dict[int, bytes] + _hours: Dict[int, Dict[str, Any]] + _peak_record: Dict[str, Any] + _collect_hour: int def __init__(self, conn: Conn) -> None: self.logged_in = 0 self.by_client = {} self._conn = conn self._client_id_cache = None + self.started = datetime.utcnow() + self._day = _current_day() + self._day_stats = _new_day_stats() + self._pending_days = {} + self._past_days = {} + self._hours = {} + self._peak_record = { 'value': 0, 'at': None } + self._collect_hour = _current_hour() + + self._load_rollups() hour = _current_hour() with self._conn.session() as sess: @@ -35,12 +60,44 @@ class Stats: for client_id, stats in current.value['by_client'].items() } + def _load_rollups(self) -> None: + with self._conn.session() as sess: + for row in sess.query(CurrentStats).filter(CurrentStats.key.in_(['hours', 'peak_record'])): + if row.key == 'hours' and isinstance(row.value, dict): + self._hours = { int(hour): dict(entry) for hour, entry in row.value.items() } + elif row.key == 'peak_record' and isinstance(row.value, dict): + self._peak_record = { 'value': int(row.value.get('value') or 0), 'at': row.value.get('at') } + oldest = _day_key(self._day - DAYS_KEPT) + for row in sess.query(CurrentStats).filter(CurrentStats.key.like('day:%'), CurrentStats.key >= oldest): + try: + day = int(row.key[4:]) + except ValueError: + continue + if day == self._day: + self._day_stats = _day_from_json(row.value) + elif row.value.get('users_active'): + self._past_days[day] = base64.b64decode(row.value['users_active']) + def on_login(self) -> None: + self._roll_day() self.logged_in += 1 + self._day_stats['logins'] += 1 def on_logout(self) -> None: self.logged_in -= 1 + def on_online(self, online: int) -> None: + self._roll_day() + now = _iso(datetime.utcnow()) + if online > self._day_stats['peak']: + self._day_stats['peak'] = online + self._day_stats['peak_at'] = now + hour_entry = self._hour_entry(_current_hour()) + if online > hour_entry['peak']: + hour_entry['peak'] = online + if online > self._peak_record['value']: + self._peak_record = { 'value': online, 'at': now } + def on_user_active(self, user: User, client: Client) -> None: self._collect('users_active', user, client) @@ -68,17 +125,42 @@ class Stats: if stat not in bhc: bhc[stat] = 0 bhc[stat] += 1 + + self._roll_day() + if stat == 'users_active': + self._day_stats['users_active'].add(user.email) + else: + self._day_stats[stat] += 1 - def flush(self) -> None: + def _roll_day(self) -> None: + day = _current_day() + if day == self._day: + return + self._pending_days[self._day] = self._day_stats + self._past_days[self._day] = bytes(self._day_stats['users_active'].registers()) + for old in [d for d in self._past_days if d < day - DAYS_KEPT]: + del self._past_days[old] + self._day = day + self._day_stats = _new_day_stats() + + def _hour_entry(self, hour: int) -> Dict[str, Any]: + if hour not in self._hours: + self._hours[hour] = { 'users_active': 0, 'messages_sent': 0, 'messages_received': 0, 'peak': 0 } + return self._hours[hour] + + def flush(self, online: Optional[int] = None) -> None: hour = _current_hour() now = datetime.utcnow() + if online is not None: + self.on_online(online) + self._roll_day() with self._conn.session() as sess: current = sess.query(CurrentStats).filter(CurrentStats.key == 'logged_in').one_or_none() if not current: current = CurrentStats(key = 'logged_in') current.date_updated = now - current.value = self.logged_in + current.value = (online if online is not None else self.logged_in) sess.add(current) sess.flush() @@ -88,11 +170,37 @@ class Stats: cs_hour = current.value['hour'] current.date_updated = now - current.value = self._flush_to_hourly(sess, hour) - sess.add(current) + current.value = self._flush_to_hourly(sess, cs_hour) + self._update_hour_totals(cs_hour) if cs_hour != hour: self.by_client = {} + current.value = { 'hour': hour, 'by_client': {} } + self._collect_hour = hour + sess.add(current) + + self._flush_rollups(sess, now) + + def _update_hour_totals(self, hour: int) -> None: + entry = self._hour_entry(hour) + entry['users_active'] = _hll_union( + bytes(stats['users_active'].registers()) for stats in self.by_client.values() if 'users_active' in stats + ) + entry['messages_sent'] = sum(int(stats.get('messages_sent') or 0) for stats in self.by_client.values()) + entry['messages_received'] = sum(int(stats.get('messages_received') or 0) for stats in self.by_client.values()) + + def _flush_rollups(self, sess: Any, now: datetime) -> None: + hour = _current_hour() + for old in [h for h in self._hours if h <= hour - HOURS_KEPT]: + del self._hours[old] + _put(sess, 'hours', { str(h): entry for h, entry in self._hours.items() }, now) + _put(sess, 'peak_record', self._peak_record, now) + for day, stats in list(self._pending_days.items()) + [(self._day, self._day_stats)]: + _put(sess, _day_key(day), _day_to_json(stats), now) + self._pending_days.clear() + sess.query(CurrentStats).filter( + CurrentStats.key.like('day:%'), CurrentStats.key < _day_key(self._day - DAYS_KEPT), + ).delete(synchronize_session = False) def _flush_to_hourly(self, sess: Any, hour: int) -> Dict[str, Any]: for client_id, stats in self.by_client.items(): @@ -116,6 +224,76 @@ class Stats: } } + def snapshot(self) -> Dict[str, Any]: + self._roll_day() + hour = _current_hour() + self._update_hour_totals(self._collect_hour) + today_registers = bytes(self._day_stats['users_active'].registers()) + + def active_since(days: int) -> int: + return _hll_union([today_registers] + [regs for day, regs in self._past_days.items() if day > self._day - days]) + + current = self._hour_entry(hour) + hourly = [] + for h in range(hour - 23, hour + 1): + entry = self._hours.get(h) or {} + hourly.append({ + 'hour': _iso(datetime.utcfromtimestamp(h * 3600)), + 'users_active': int(entry.get('users_active') or 0), 'messages_sent': int(entry.get('messages_sent') or 0), + 'messages_received': int(entry.get('messages_received') or 0), 'peak': int(entry.get('peak') or 0), + }) + return { + 'active': { + 'hour': int(current['users_active']), + 'today': _hll_union([today_registers]), + 'week': active_since(7), + 'month': active_since(30), + }, + 'messages': { + 'hour': { 'sent': int(current['messages_sent']), 'received': int(current['messages_received']) }, + 'today': { 'sent': int(self._day_stats['messages_sent']), 'received': int(self._day_stats['messages_received']) }, + }, + 'logins_today': int(self._day_stats['logins']), + 'peak_today': { 'value': int(self._day_stats['peak']), 'at': self._day_stats['peak_at'] }, + 'peak_record': dict(self._peak_record), + 'hourly': hourly, + 'by_client_hourly': self._by_client_hourly(hour - 23), + 'started': _iso(self.started), + 'uptime': int((datetime.utcnow() - self.started).total_seconds()), + } + + def _by_client_hourly(self, since_hour: int) -> List[Dict[str, Any]]: + clients = { client_id: Client.ToJSON(client) for client, client_id in (self._client_id_cache or {}).items() } + by_hour: dict[int, dict[int, dict[str, int]]] = {} + with self._conn.session() as sess: + if len(clients) < sess.query(sa.func.count(DBClient.id)).scalar(): + clients = { row.id: row.data for row in sess.query(DBClient).all() } + for hcs in sess.query(HourlyClientStats).filter(HourlyClientStats.hour >= since_hour): + by_hour.setdefault(int(hcs.hour), {})[int(hcs.client_id)] = { + 'users_active': int(hcs.users_active), 'messages_sent': int(hcs.messages_sent), 'messages_received': int(hcs.messages_received), + } + for client_id, stats in self.by_client.items(): + by_hour.setdefault(self._collect_hour, {})[client_id] = { + 'users_active': int(stats['users_active'].cardinality()) if 'users_active' in stats else 0, + 'messages_sent': int(stats.get('messages_sent') or 0), 'messages_received': int(stats.get('messages_received') or 0), + } + return [ + { + 'hour': _iso(datetime.utcfromtimestamp(h * 3600)), + 'clients': sorted( + ({ 'client': clients.get(client_id), **values } for client_id, values in by_hour[h].items()), + key = lambda entry: -entry['users_active'], + ), + } + for h in sorted(by_hour, reverse = True) + ] + + def snapshot_started(self) -> str: + return _iso(self.started) + + def uptime(self) -> int: + return int((datetime.utcnow() - self.started).total_seconds()) + def _get_client_id(self, client: Client) -> int: if self._client_id_cache is None: with self._conn.session() as sess: @@ -131,6 +309,110 @@ class Stats: self._client_id_cache[client] = dbobj.id return self._client_id_cache[client] +def collect_snapshot(backend: Any) -> Dict[str, Any]: + sessions = list(backend._sc.iter_sessions()) + users: set[str] = set() + visible: set[str] = set() + by_program: dict[str, int] = {} + by_client: dict[Client, int] = {} + for bs in sessions: + users.add(bs.user.uuid) + if not bs.user.status.substatus.is_offlineish(): + visible.add(bs.user.uuid) + by_program[bs.client.program] = by_program.get(bs.client.program, 0) + 1 + by_client[bs.client] = by_client.get(bs.client, 0) + 1 + snapshot = backend._stats.snapshot() + snapshot['online'] = { + 'sessions': len(sessions), + 'users': len(users), + 'visible_users': len(visible), + 'by_program': [{ 'program': program, 'sessions': count } for program, count in sorted(by_program.items(), key = lambda item: -item[1])], + 'by_client': [ + { **Client.ToJSON(client), 'sessions': count } + for client, count in sorted(by_client.items(), key = lambda item: -item[1])[:20] + ], + } + snapshot.update(_db_counts()) + snapshot['generated'] = _iso(datetime.utcnow()) + return snapshot + +_counts_cache: tuple[float, dict[str, Any]] = (0.0, {}) + +def _db_counts() -> Dict[str, Any]: + global _counts_cache + if time.monotonic() - _counts_cache[0] < 60: + return _counts_cache[1] + import core.db as db + now = datetime.utcnow() + day_ago = now - timedelta(days = 1) + week_ago = now - timedelta(days = 7) + count = sa.func.count + with db.Session() as sess: + counts = { + 'accounts': { + 'total': sess.query(count(db.User.id)).scalar() or 0, + 'new_today': sess.query(count(db.User.id)).filter(db.User.date_created >= day_ago).scalar() or 0, + 'new_week': sess.query(count(db.User.id)).filter(db.User.date_created >= week_ago).scalar() or 0, + 'verified': sess.query(count(db.User.id)).filter(db.User.account_verified == True).scalar() or 0, + 'in_directory': sess.query(count(db.User.id)).filter(db.User.show_in_dir == True).scalar() or 0, + }, + 'circles': sess.query(count(db.Circle.id)).scalar() or 0, + 'beacon': { + 'posts_today': sess.query(count(db.Activity.id)).filter(db.Activity.user_uuid.isnot(None), db.Activity.date_created >= day_ago).scalar() or 0, + 'reactions_today': sess.query(count(db.ActivityReaction.id)).filter(db.ActivityReaction.date_created >= day_ago).scalar() or 0, + 'comments_today': sess.query(count(db.ActivityComment.id)).filter(db.ActivityComment.date_created >= day_ago).scalar() or 0, + }, + } # type: Dict[str, Any] + _counts_cache = (time.monotonic(), counts) + return counts + +def _hll_union(register_sets: Iterable[bytes]) -> int: + merged: bytearray | None = None + for registers in register_sets: + if merged is None: + merged = bytearray(registers) + else: + merged = bytearray(map(max, merged, registers)) + if merged is None: + return 0 + hll = HyperLogLog(12) + hll.set_registers(merged) + return int(round(hll.cardinality())) + +def _new_day_stats() -> Dict[str, Any]: + return { 'users_active': HyperLogLog(12), 'messages_sent': 0, 'messages_received': 0, 'logins': 0, 'peak': 0, 'peak_at': None } + +def _day_to_json(stats: Dict[str, Any]) -> Dict[str, Any]: + return { + 'users_active': base64.b64encode(bytes(stats['users_active'].registers())).decode('ascii'), + 'users_active_count': int(round(stats['users_active'].cardinality())), + 'messages_sent': stats['messages_sent'], 'messages_received': stats['messages_received'], 'logins': stats['logins'], + 'peak': stats['peak'], 'peak_at': stats['peak_at'], + } + +def _day_from_json(json: Dict[str, Any]) -> Dict[str, Any]: + stats = _new_day_stats() + if json.get('users_active'): + stats['users_active'].set_registers(bytearray(base64.b64decode(json['users_active']))) + for key in ('messages_sent', 'messages_received', 'logins', 'peak'): + stats[key] = int(json.get(key) or 0) + stats['peak_at'] = json.get('peak_at') + return stats + +def _put(sess: Any, key: str, value: Any, now: datetime) -> None: + row = sess.query(CurrentStats).filter(CurrentStats.key == key).one_or_none() + if row is None: + row = CurrentStats(key = key) + row.value = value + row.date_updated = now + sess.add(row) + +def _day_key(day: int) -> str: + return 'day:{:06d}'.format(day) + +def _iso(dt: datetime) -> str: + return dt.replace(microsecond = 0).isoformat() + 'Z' + def _stats_to_json(stats: Dict[str, Any]) -> Dict[str, Any]: json = {} if 'messages_sent' in stats: @@ -158,6 +440,9 @@ def _current_hour() -> int: ts = now.timestamp() return int(ts // 3600) +def _current_day() -> int: + return _current_hour() // 24 + class Base(declarative_base()): # type: ignore __abstract__ = True @@ -185,4 +470,4 @@ class CurrentStats(Base): key = sa.Column(sa.String(255), nullable = False, primary_key = True) date_updated = sa.Column(sa.DateTime, nullable = False, server_default = sa.text('CURRENT_TIMESTAMP')) - value = sa.Column(JSONType, nullable = False, default = {}) \ No newline at end of file + value = sa.Column(JSONType, nullable = False, default = {}) diff --git a/core/tls.py b/core/tls.py index 0a53300..06abe62 100644 --- a/core/tls.py +++ b/core/tls.py @@ -1,7 +1,7 @@ from typing import Dict, Tuple, Any, Optional from datetime import datetime, timedelta, timezone from pathlib import Path -import ssl +import ssl, settings from cryptography import x509 from cryptography.hazmat.backends import default_backend @@ -48,7 +48,7 @@ class TLSContext: p_key = self.cert_dir / '{}'.format(self.cert_root) if not exists_and_valid(p_crt, p_key): - raise ssl.CertificateError() + if not settings.DEBUG: raise ssl.CertificateError() return p_crt, p_key diff --git a/core/user.py b/core/user.py index 3dc2903..113b493 100644 --- a/core/user.py +++ b/core/user.py @@ -1,8 +1,8 @@ from typing import Dict, Optional, List, Tuple, Any, TYPE_CHECKING -from datetime import datetime +from datetime import datetime, timedelta from dateutil import parser as iso_parser from pathlib import Path -from sqlalchemy import func +from sqlalchemy import func, or_ from sqlalchemy.orm import joinedload import json, traceback @@ -13,11 +13,12 @@ from util.avatar import store_avatar_file, get_img_type from .conn import Conn from .db import ( User as DBUser, UserContact as DBUserContact, Circle as DBCircle, - CircleMembership as DBCircleMembership, UserProfile as DBUserProfile + CircleMembership as DBCircleMembership, UserProfile as DBUserProfile, Activity as DBActivity, + ActivityReaction as DBActivityReaction, ActivityComment as DBActivityComment ) from .models import ( User, Contact, ContactDetail, ContactLocation, ContactGroupEntry, UserStatus, UserDetail, Circle, - CircleMembership, CircleRole, CircleState, Group, RoamingInfo, OIM, UserProfile + CircleMembership, CircleRole, CircleState, Group, RoamingInfo, OIM, UserProfile, Activity, ActivityType ) if TYPE_CHECKING: @@ -43,11 +44,6 @@ class UserService: status = hasher.verify(pwd, dbuser.password) if status is True: return dbuser.uuid - elif status == 'MIGRATEMEPLSTHX': - new_hash = hasher.encode(pwd, salt=gen_salt()) - dbuser.password = new_hash - sess.add(dbuser) - return dbuser.uuid return None def login_with_username(self, username: str, pwd: str) -> Optional[str]: @@ -58,13 +54,25 @@ class UserService: status = hasher.verify(pwd, dbuser.password) if status is True: return dbuser.uuid - elif status == 'MIGRATEMEPLSTHX': - new_hash = hasher.encode(pwd, salt=gen_salt()) - dbuser.password = new_hash - sess.add(dbuser) + return None + + def login_with_uin(self, uin: int, pwd: str) -> Optional[str]: + uuid = self.get_uuid_uin(uin) + if uuid is None: + return None + return self.login_with_uuid(uuid, pwd) + + def login_with_uuid(self, uuid: str, pwd: str) -> Optional[str]: + # for frontends that already worked out which account a login name points at (screen name or UIN) + with self._conn.session() as sess: + dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none() + if dbuser is None: + return None + status = hasher.verify(pwd, dbuser.password) + if status is True: return dbuser.uuid return None - + def msn_login_md5(self, email: str, md5_hash: str) -> Optional[str]: with self._conn.session() as sess: dbuser = sess.query(DBUser).filter(func.lower(DBUser.email) == email.lower()).one_or_none() @@ -118,6 +126,31 @@ class UserService: return hasher.extract_salt(pw_md5) if pw_md5 else None + def aim_get_md5_password_by_uuid(self, uuid: str) -> Optional[bytes]: + with self._conn.session() as sess: + dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none() + if dbuser is None: + return None + + return hasher_md5.extract_hash(dbuser.get_front_data('aim', 'pw_md5') or '') + + def aim_get_md5_password_bucp2_by_uuid(self, uuid: str) -> Optional[bytes]: + with self._conn.session() as sess: + dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none() + if dbuser is None: + return None + + return hasher_md5.extract_hash(dbuser.get_front_data('aim', 'pw_md5_v5') or '') + + def aim_get_md5_salt_by_uuid(self, uuid: str) -> Optional[str]: + with self._conn.session() as sess: + dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none() + if dbuser is None: + return None + + pw_md5 = dbuser.get_front_data('aim', 'pw_md5') + + return hasher.extract_salt(pw_md5) if pw_md5 else None def msim_get_sha1_password(self, email: str) -> Optional[bytes]: with self._conn.session() as sess: @@ -152,6 +185,39 @@ class UserService: return None return dbuser.uuid + def get_uuid_uin(self, uin: int) -> Optional[str]: + # a UIN of 0 is what accounts without an ICQ number carry, so it never names anyone + if uin <= 0: + return None + with self._conn.session() as sess: + dbuser = sess.query(DBUser).filter(DBUser.uin == uin).first() + if dbuser is None: + return None + return dbuser.uuid + + def search_uuids( + self, *, email: Optional[str] = None, first_name: Optional[str] = None, last_name: Optional[str] = None, + nickname: Optional[str] = None, limit: int = 20, + ) -> List[str]: + # directory searches (ICQ white pages, AIM ODIR, find-by-email) only ever see people who listed themselves + criteria = [] + if email: + criteria.append(func.lower(DBUser.email) == email.lower()) + if first_name: + criteria.append(func.lower(DBUser.first_name) == first_name.lower()) + if last_name: + criteria.append(func.lower(DBUser.last_name) == last_name.lower()) + if nickname: + criteria.append(or_( + func.lower(DBUser.nickname) == nickname.lower(), func.lower(DBUser.friendly_name) == nickname.lower(), + func.lower(DBUser.username) == nickname.lower(), + )) + if not criteria: + return [] + with self._conn.session() as sess: + query = sess.query(DBUser.uuid).filter(DBUser.show_in_dir == True, DBUser.suspended == False, *criteria) + return [row.uuid for row in query.limit(limit)] + def get(self, uuid: str) -> Optional[User]: if uuid not in self._cache_by_uuid: self._cache_by_uuid[uuid] = self._get_uncached(uuid) @@ -218,10 +284,12 @@ class UserService: self._cache_by_uuid.pop(user.uuid, None) + if md5 != user.avatar: + self.add_activity(user, ActivityType.DisplayPicture, text = md5) + user.avatar = md5 return md5 - def get_detail(self, uuid: str) -> Optional[UserDetail]: with self._conn.session() as sess: dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none() @@ -408,6 +476,49 @@ class UserService: return circle + def delete_user(self, uuid: str, new_owners: Dict[str, Circle]) -> bool: + with self._conn.session() as sess: + dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none() + if dbuser is None: + return False + for chat_id, circle in new_owners.items(): + sess.query(DBCircle).filter(DBCircle.chat_id == chat_id).update({ + DBCircle.owner_id: circle.owner_id, DBCircle.owner_uuid: circle.owner_uuid, DBCircle.owner_friendly: circle.owner_friendly, + }, synchronize_session = False) + sess.query(DBCircleMembership).filter(or_( + DBCircleMembership.member_id == dbuser.id, DBCircleMembership.member_uuid == uuid, + )).delete(synchronize_session = False) + sess.query(DBUserContact).filter(or_( + DBUserContact.user_id == dbuser.id, DBUserContact.contact_id == dbuser.id, + DBUserContact.user_uuid == uuid, DBUserContact.uuid == uuid, + )).delete(synchronize_session = False) + for model in (DBActivityReaction, DBActivityComment): + sess.query(model).filter(model.user_uuid == uuid).delete(synchronize_session = False) + activity_ids = [activity_id for (activity_id,) in sess.query(DBActivity.id).filter(DBActivity.user_uuid == uuid)] + if activity_ids: + for model in (DBActivityReaction, DBActivityComment): + sess.query(model).filter(model.activity_id.in_(activity_ids)).delete(synchronize_session = False) + sess.query(DBActivity).filter(DBActivity.id.in_(activity_ids)).delete(synchronize_session = False) + sess.query(DBUserProfile).filter(DBUserProfile.user_id == dbuser.id).delete(synchronize_session = False) + sess.expire(dbuser) + sess.delete(dbuser) + self._cache_by_uuid.pop(uuid, None) + return True + + def expired_suspensions(self, days: int, now: Optional[datetime] = None) -> List[str]: + cutoff = (now or datetime.utcnow()) - timedelta(days = days) + with self._conn.session() as sess: + rows = sess.query(DBUser.uuid).filter( + DBUser.suspended == True, or_(DBUser.suspended_at == None, DBUser.suspended_at <= cutoff), + ).all() + return [uuid for (uuid,) in rows] + + def delete_circle(self, chat_id: str) -> None: + with self._conn.session() as sess: + sess.query(DBCircleMembership).filter(DBCircleMembership.chat_id == chat_id).delete(synchronize_session = False) + sess.query(DBCircle).filter(DBCircle.chat_id == chat_id).delete(synchronize_session = False) + self._circle_cache_by_chat_id.pop(chat_id, None) + def get_all_circles(self) -> List[Circle]: circles = [] @@ -548,8 +659,10 @@ class UserService: if dbusercontacts_to_add: sess.add_all(dbusercontacts_to_add) - def save_single_roaming(self, user: User, to_save: Dict[str, Any]) -> None: + def save_single_roaming(self, user: User, to_save: Dict[str, Any]) -> bool: + # Returns whether a "What's New" activity was added updated = False + activity_added = False with self._conn.session() as sess: dbuser = sess.query(DBUser).filter(DBUser.uuid == user.uuid).one() @@ -558,13 +671,149 @@ class UserService: dbuser.name_last_modified = datetime.utcnow() updated = True if 'message' in to_save: + # A new status message shows up in contacts' "What's New" + if to_save['message'] and to_save['message'] != dbuser.message: + activity_added = self.add_activity(user, ActivityType.StatusMessage, text = to_save['message']) dbuser.message = to_save['message'] dbuser.message_last_modified = datetime.utcnow() updated = True if updated: sess.add(dbuser) + + return activity_added + def add_activity( + self, user: Optional[User], type: ActivityType, *, title: Optional[str] = None, text: Optional[str] = None, url: Optional[str] = None, + ) -> bool: + # Returns whether the activity was added + if user is not None and not beacon_enabled(user): + return False + text = (text[:255] if text else text) + title = (title[:100] if title else title) + with self._conn.session() as sess: + if user is not None: + types = ((int(type), int(ActivityType.Photo)) if type is ActivityType.StatusMessage else (int(type),)) + dbactivity_last = sess.query(DBActivity).filter( + DBActivity.user_uuid == user.uuid, DBActivity.type.in_(types), + ).order_by(DBActivity.date_created.desc()).first() + if dbactivity_last is not None and dbactivity_last.text == text and ( + int(dbactivity_last.type) == int(type) or datetime.utcnow() - dbactivity_last.date_created < PHOTO_STATUS_WINDOW + ) and (type is not ActivityType.Photo or dbactivity_last.url == url): + return False + sess.add(DBActivity( + user_uuid = (user.uuid if user is not None else None), type = int(type), title = title, text = text, url = url, + )) + return True + + def get_activities( + self, uuids: List[str], count: int, *, announcements: bool = False, before_id: int | None = None, after_id: int | None = None, + types: list[ActivityType] | None = None, + ) -> List[Activity]: + activities = [] # type: List[Activity] + + with self._conn.session() as sess: + condition = DBActivity.user_uuid.in_(uuids) + if announcements: + condition = condition | DBActivity.user_uuid.is_(None) + if before_id is not None: + condition = condition & (DBActivity.id < before_id) + if after_id is not None: + condition = condition & (DBActivity.id > after_id) + if types: + condition = condition & DBActivity.type.in_([int(t) for t in types]) + for dbactivity in sess.query(DBActivity).filter(condition).order_by(DBActivity.date_created.desc(), DBActivity.id.desc()).limit(count): + user = (self.get(dbactivity.user_uuid) if dbactivity.user_uuid is not None else None) + if dbactivity.user_uuid is not None and user is None: continue + if user is not None and not beacon_enabled(user): continue + activities.append(Activity( + dbactivity.id, user, ActivityType(int(dbactivity.type)), dbactivity.title, dbactivity.text, dbactivity.url, dbactivity.date_created, + )) + + return activities + + def get_activity(self, activity_id: int) -> Activity | None: + with self._conn.session() as sess: + dbactivity = sess.query(DBActivity).filter(DBActivity.id == activity_id).one_or_none() + if dbactivity is None: + return None + user = (self.get(dbactivity.user_uuid) if dbactivity.user_uuid is not None else None) + return Activity( + dbactivity.id, user, ActivityType(int(dbactivity.type)), dbactivity.title, dbactivity.text, dbactivity.url, dbactivity.date_created, + ) + + def delete_activity(self, activity_id: int, user_uuid: str | None) -> bool: + with self._conn.session() as sess: + if sess.query(DBActivity).filter(DBActivity.id == activity_id).filter( + DBActivity.user_uuid.is_(None) if user_uuid is None else DBActivity.user_uuid == user_uuid + ).count(): + sess.query(DBActivityReaction).filter(DBActivityReaction.activity_id == activity_id).delete(synchronize_session = False) + sess.query(DBActivityComment).filter(DBActivityComment.activity_id == activity_id).delete(synchronize_session = False) + query = sess.query(DBActivity).filter(DBActivity.id == activity_id) + if user_uuid is None: + query = query.filter(DBActivity.user_uuid.is_(None)) + else: + query = query.filter(DBActivity.user_uuid == user_uuid) + return query.delete(synchronize_session = False) > 0 + + def toggle_reaction(self, activity_id: int, user_uuid: str, reaction: str) -> bool: + with self._conn.session() as sess: + existing = sess.query(DBActivityReaction).filter( + DBActivityReaction.activity_id == activity_id, DBActivityReaction.user_uuid == user_uuid, DBActivityReaction.reaction == reaction, + ).one_or_none() + if existing is not None: + sess.delete(existing) + return False + sess.add(DBActivityReaction(activity_id = activity_id, user_uuid = user_uuid, reaction = reaction)) + return True + + def get_reactions(self, activity_ids: List[int]) -> Dict[int, Dict[str, List[str]]]: + result: dict[int, dict[str, list[str]]] = {} + if not activity_ids: + return result + with self._conn.session() as sess: + for row in sess.query(DBActivityReaction).filter(DBActivityReaction.activity_id.in_(activity_ids)).order_by(DBActivityReaction.id): + result.setdefault(row.activity_id, {}).setdefault(row.reaction, []).append(row.user_uuid) + return result + + def add_comment(self, activity_id: int, user_uuid: str, text: str) -> int: + with self._conn.session() as sess: + dbcomment = DBActivityComment(activity_id = activity_id, user_uuid = user_uuid, text = text[:255]) + sess.add(dbcomment) + sess.flush() + return int(dbcomment.id) + + def delete_comment(self, comment_id: int, user_uuid: str) -> bool: + with self._conn.session() as sess: + dbcomment = sess.query(DBActivityComment).filter(DBActivityComment.id == comment_id).one_or_none() + if dbcomment is None: + return False + dbactivity = sess.query(DBActivity).filter(DBActivity.id == dbcomment.activity_id).one_or_none() + if dbcomment.user_uuid != user_uuid and (dbactivity is None or dbactivity.user_uuid != user_uuid): + return False + sess.delete(dbcomment) + return True + + def get_comments(self, activity_ids: List[int]) -> Dict[int, List[Tuple[int, str, str, datetime]]]: + result: dict[int, list[tuple[int, str, str, datetime]]] = {} + if not activity_ids: + return result + with self._conn.session() as sess: + for row in sess.query(DBActivityComment).filter(DBActivityComment.activity_id.in_(activity_ids)).order_by(DBActivityComment.id): + result.setdefault(row.activity_id, []).append((int(row.id), row.user_uuid, row.text, row.date_created)) + return result + +def beacon_enabled(user: User) -> bool: + if not getattr(user, 'account_verified', False): + return False + settings_json = user.settings or {} + return not (settings_json.get('beacon_off') or settings_json.get('konekt_off')) + +def directory_online_visible(user: User) -> bool: + return not (user.settings or {}).get('dir_hide_online') + +# How long after sharing a photo a status message with the same caption still belongs to it +PHOTO_STATUS_WINDOW = timedelta(minutes = 10) def _get_oim_path(recipient_uuid: str) -> Path: return Path('storage/oim') / recipient_uuid \ No newline at end of file diff --git a/deps.txt b/deps.txt index cd495ad..14dcfbc 100644 --- a/deps.txt +++ b/deps.txt @@ -19,4 +19,5 @@ argon2 argon2-cffi PyRSS2Gen pymysql -disposable-email-domains \ No newline at end of file +disposable-email-domains +emoji \ No newline at end of file diff --git a/front/api/__init__.py b/front/admin/__init__.py similarity index 100% rename from front/api/__init__.py rename to front/admin/__init__.py diff --git a/front/admin/auth.py b/front/admin/auth.py new file mode 100644 index 0000000..850cf94 --- /dev/null +++ b/front/admin/auth.py @@ -0,0 +1,127 @@ +from collections import deque +from dataclasses import dataclass, field +from typing import Any, Deque, Dict, List, Optional, Tuple +import asyncio, hashlib, hmac, secrets, time + +import sqlalchemy as sa + +import core.db as db +from util import hash +import settings + +COOKIE_NAME = 'azul_admin' +_DUMMY_HASH: Optional[str] = None +MAX_FAILURES = 5 +FAIL_WINDOW = 900 + +@dataclass +class AdminSession: + token: str + uuid: str + username: str + csrf: str + expires: float + address: str + flashes: List[Tuple[str, str]] = field(default_factory = list) + reveal: Optional[Dict[str, str]] = None + + def flash(self, text: str, kind: str = 'success') -> None: + self.flashes.append((kind, text)) + + def take_flashes(self) -> List[Tuple[str, str]]: + flashes, self.flashes = self.flashes, [] + return flashes + + def take_reveal(self) -> Optional[Dict[str, str]]: + reveal, self.reveal = self.reveal, None + return reveal + +class AdminAuth: + __slots__ = ('_sessions', '_failures') + + _sessions: Dict[str, AdminSession] + _failures: Dict[str, Deque[float]] + + def __init__(self) -> None: + self._sessions = {} + self._failures = {} + + @staticmethod + def configured() -> bool: + return len(str(getattr(settings, 'ADMIN_KEY', '') or '')) == 64 + + @staticmethod + def key_matches(key: str) -> bool: + expected = str(getattr(settings, 'ADMIN_KEY', '') or '').lower() + if len(expected) != 64: + return False + return hmac.compare_digest(hashlib.sha256(key.encode('utf-8')).hexdigest(), expected) + + def throttled(self, address: str) -> bool: + failures = self._failures.get(address) + if not failures: + return False + now = time.monotonic() + while failures and now - failures[0] > FAIL_WINDOW: + failures.popleft() + return len(failures) >= MAX_FAILURES + + def _fail(self, address: str) -> None: + self._failures.setdefault(address, deque()).append(time.monotonic()) + + async def sign_in(self, address: str, login: str, password: str, key: str) -> Optional[AdminSession]: + login = login.strip() + with db.Session() as sess: + row = sess.query(db.User).filter(sa.or_(sa.func.lower(db.User.email) == login.lower(), sa.func.lower(db.User.username) == login.lower())).first() + stored = row.password if row is not None else None + found = (row.uuid, row.username, bool(row.is_admin), bool(row.suspended)) if row is not None else None + loop = asyncio.get_running_loop() + global _DUMMY_HASH + if stored is None and _DUMMY_HASH is None: + _DUMMY_HASH = await loop.run_in_executor(None, hash.hasher.encode, secrets.token_hex(8)) + password_ok = bool(await loop.run_in_executor(None, hash.hasher.verify, password, stored or _DUMMY_HASH)) + key_ok = self.key_matches(key) + if found is None or not password_ok or not key_ok or not found[2] or found[3]: + self._fail(address) + return None + self._failures.pop(address, None) + session = AdminSession( + secrets.token_urlsafe(32), found[0], found[1], secrets.token_urlsafe(24), + time.time() + int(getattr(settings, 'ADMIN_SESSION_LIFETIME', 8 * 3600)), address, + ) + self._prune() + self._sessions[session.token] = session + return session + + def get(self, token: Optional[str]) -> Optional[AdminSession]: + if not token: + return None + session = self._sessions.get(token) + if session is None: + return None + if session.expires <= time.time(): + self._sessions.pop(token, None) + return None + return session + + def still_admin(self, session: AdminSession) -> bool: + with db.Session() as sess: + row = sess.query(db.User.is_admin, db.User.suspended).filter(db.User.uuid == session.uuid).one_or_none() + return row is not None and bool(row[0]) and not bool(row[1]) + + def sign_out(self, token: Optional[str]) -> None: + if token: + self._sessions.pop(token, None) + + def sign_out_user(self, uuid: str) -> None: + for token in [token for token, session in self._sessions.items() if session.uuid == uuid]: + self._sessions.pop(token, None) + + def _prune(self) -> None: + now = time.time() + for token in [token for token, session in self._sessions.items() if session.expires <= now]: + self._sessions.pop(token, None) + + @staticmethod + def csrf_ok(session: AdminSession, value: Any) -> bool: + return isinstance(value, str) and hmac.compare_digest(session.csrf, value) diff --git a/front/admin/entry.py b/front/admin/entry.py new file mode 100644 index 0000000..bf1acc8 --- /dev/null +++ b/front/admin/entry.py @@ -0,0 +1,625 @@ +from datetime import datetime +from math import ceil +from typing import Any, Awaitable, Callable, Dict, List, Optional +import asyncio, os, secrets + +import jinja2 +from aiohttp import web + +from core.alerts import AGENTS, MAX_BODY +from core.backend import Backend +from core.interservice.ctrl import ALERT_NETWORKS, INSCtrl +from core.interservice.local import LocalLink, LocalINSError +from core.interservice.registry import ClientRegistry +from util.misc import AIOHTTPRunner +import settings + +from .auth import AdminAuth, COOKIE_NAME + +TMPL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tmpl') +PAGE_SIZE = 50 +SECTIONS = [ + ('/', 'overview', 'bi-grid-1x2-fill'), + ('/users', 'users', 'bi-people-fill'), + ('/sessions', 'sessions', 'bi-plug-fill'), + ('/circles', 'circles', 'bi-chat-square-dots-fill'), + ('/broadcast', 'broadcast', 'bi-megaphone-fill'), + ('/interservice', 'interservice', 'bi-diagram-3-fill'), +] +USER_FILTERS = [ + ('online', 'signed in', 'online'), + ('suspended', 'suspended', 'suspended'), + ('unverified', 'unverified e-mail', '!account_verified'), + ('blocked', 'can\'t sign in', '!verified_to_login'), + ('admins', 'administrators', 'is_admin'), + ('testers', 'testers', 'is_tester'), +] +NETWORK_NAMES = { 'msn': 'MSN Messenger', 'ymsg': 'Yahoo! Messenger', 'aim': 'AIM', 'icq': 'ICQ', 'irc': 'IRC' } +PROGRAM_NAMES = { **NETWORK_NAMES, 'toc': 'AIM (TOC)', 'msim': 'MySpaceIM' } +ALERT_LANGUAGES = [ + (1033, 'English (United States)'), (2057, 'English (United Kingdom)'), (1031, 'German'), (1036, 'French (France)'), + (3082, 'Spanish (Spain)'), (2058, 'Spanish (Mexico)'), (1040, 'Italian'), (1043, 'Dutch'), (1046, 'Portuguese (Brazil)'), + (2070, 'Portuguese (Portugal)'), (1053, 'Swedish'), (1030, 'Danish'), (1044, 'Norwegian (Bokmål)'), (1035, 'Finnish'), + (1045, 'Polish'), (1049, 'Russian'), (1055, 'Turkish'), (1032, 'Greek'), (1041, 'Japanese'), (1042, 'Korean'), + (2052, 'Chinese (Simplified)'), (1028, 'Chinese (Traditional)'), +] +USER_FLAGS = [ + #('verified_to_login', 'Can sign in', 'Off blocks every client and the website until it\'s turned back on.'), + ('suspended', 'Suspended', 'Signs them out everywhere and keeps them out.'), + ('account_verified', 'E-mail verified', 'Their e-mail address is confirmed as theirs.'), + ('show_in_dir', 'Listed in the member directory', 'Other members can find them and see their profile.'), + ('alias_active', 'Username alias active', 'They sign in with username@crosstalk.im instead of their e-mail address.'), + ('is_tester', 'Tester', 'Sees experimental and unfinished features.'), + ('is_mvp', 'MVP', 'Shows the MVP badge where clients support it.'), + ('is_admin', 'Administrator', 'Can sign into this panel (with the admin key).'), +] +LEGACY_CLIENTS = [('oldmsn', 'MSN Messenger 1.0 - 4.7'), ('yahoo', 'Yahoo! Messenger'), ('oldaim', 'AOL Instant Messenger'), ('msim', 'MySpaceIM')] +ROLE_NAMES = { 1: 'owner', 2: 'administrator', 3: 'member', 4: 'invited' } + +Handler = Callable[[web.Request], Awaitable[web.StreamResponse]] + +def register(loop: asyncio.AbstractEventLoop, backend: Backend, registry: Optional[ClientRegistry]) -> web.Application: + app = create_app(backend, registry) + backend.add_runner(AIOHTTPRunner(settings.ADMIN_HOST, settings.ADMIN_PORT, app, service = 'Admin')) + if not AdminAuth.configured(): + print('[Admin] ADMIN_KEY is not set, so nobody can sign into the admin panel yet (see settings.py)') + print(f'[Admin] Admin panel on http://{settings.ADMIN_HOST}:{settings.ADMIN_PORT}/') + return app + +def create_app(backend: Backend, registry: Optional[ClientRegistry]) -> web.Application: + app = web.Application(middlewares = [_security_headers, _require_admin]) + app['backend'] = backend + app['registry'] = registry + app['auth'] = AdminAuth() + env = jinja2.Environment(loader = jinja2.FileSystemLoader(TMPL_DIR), autoescape = jinja2.select_autoescape(default = True)) + env.globals.update( + settings = settings, role_names = ROLE_NAMES, sections = SECTIONS, network_names = NETWORK_NAMES, program_names = PROGRAM_NAMES, + ) + env.filters['when'] = _when + env.filters['ago'] = _ago + env.filters['until'] = _until + app['jinja'] = env + r = app.router + r.add_get('/login', page_login) + r.add_post('/login', page_login) + r.add_post('/logout', action_logout) + r.add_get('/', page_overview) + r.add_get('/users', page_users) + r.add_get('/users/{uuid}', page_user) + r.add_post('/users/{uuid}', action_user) + r.add_get('/sessions', page_sessions) + r.add_post('/sessions', action_sessions) + r.add_get('/circles', page_circles) + r.add_get('/circles/{chat_id}', page_circle) + r.add_post('/circles/{chat_id}', action_circle) + r.add_get('/broadcast', page_broadcast) + r.add_post('/broadcast', action_broadcast) + r.add_get('/interservice', page_interservice) + r.add_post('/interservice', action_interservice) + return app + +def _when(value: Any) -> str: + if not value: + return 'never' + if isinstance(value, str): + try: + value = datetime.fromisoformat(value.rstrip('Z')) + except ValueError: + return value + return '{} {}, {} {}'.format(value.strftime('%B'), value.day, value.year, value.strftime('%H:%M UTC')) + +def _ago(value: Any) -> str: + if not value: + return 'never' + if isinstance(value, str): + try: + value = datetime.fromisoformat(value.rstrip('Z')) + except ValueError: + return value + seconds = int((datetime.utcnow() - value).total_seconds()) + if seconds < 60: + return 'just now' + for size, name in ((86400 * 365, 'year'), (86400 * 30, 'month'), (86400, 'day'), (3600, 'hour'), (60, 'minute')): + if seconds >= size: + n = seconds // size + return '{} {}{} ago'.format(n, name, '' if n == 1 else 's') + return 'just now' + +def _until(value: Any) -> str: + if not value: + return 'never' + if isinstance(value, str): + try: + value = datetime.fromisoformat(value.rstrip('Z')) + except ValueError: + return value + seconds = int((value - datetime.utcnow()).total_seconds()) + if seconds <= 0: + return 'at the next check' + for size, name in ((86400, 'day'), (3600, 'hour'), (60, 'minute')): + if seconds >= size: + n = seconds // size + return 'in {} {}{}'.format(n, name, '' if n == 1 else 's') + return 'in under a minute' + +def _peer(req: web.Request) -> str: + return req.remote or '' + +def _harden(headers: Any) -> None: + headers['X-Frame-Options'] = 'DENY' + headers['X-Content-Type-Options'] = 'nosniff' + headers['Referrer-Policy'] = 'no-referrer' + headers['Cache-Control'] = 'no-store' + headers['Content-Security-Policy'] = ( + "default-src 'none'; img-src 'self' data: http: https:; style-src 'unsafe-inline' https://{0} https://cdn.jsdelivr.net https://fonts.googleapis.com; " + "font-src https://{0} https://cdn.jsdelivr.net https://fonts.gstatic.com; script-src https://{0} https://code.jquery.com; " + "connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'" + ).format(settings.STATIC_HOST) + +@web.middleware +async def _security_headers(req: web.Request, handler: Handler) -> web.StreamResponse: + try: + resp = await handler(req) + except web.HTTPException as ex: + _harden(ex.headers) + raise + _harden(resp.headers) + return resp + +@web.middleware +async def _require_admin(req: web.Request, handler: Handler) -> web.StreamResponse: + if req.path == '/login': + return await handler(req) + auth: AdminAuth = req.app['auth'] + session = auth.get(req.cookies.get(COOKIE_NAME)) + if session is None or not auth.still_admin(session): + if session is not None: + auth.sign_out(session.token) + if req.method != 'GET': + raise web.HTTPForbidden(text = 'Sign in again.') + raise web.HTTPFound('/login?next={}'.format(req.path_qs if req.path != '/' else '/')) + if req.method == 'POST': + data = await req.post() + if not AdminAuth.csrf_ok(session, data.get('csrf')): + raise web.HTTPForbidden(text = 'That form expired. Go back, reload the page and try again.') + req['form'] = data + req['admin'] = session + req['ins'] = LocalLink(req.app['backend'], session.username) + return await handler(req) + +def render(req: web.Request, tmpl: str, ctxt: Optional[Dict[str, Any]] = None, *, status: int = 200) -> web.Response: + session: AdminSession | None = req.get('admin') + backend = req.app['backend'] # type: Backend + context = dict(ctxt or {}) + context.update( + admin = session, csrf = session.csrf if session else '', flashes = session.take_flashes() if session else [], + reveal = session.take_reveal() if session else None, path = req.path, + nav = { + 'sessions': sum(1 for _ in backend._sc.iter_sessions()), + 'maintenance': bool(backend.maintenance_mode or backend.notify_maintenance), + }, + ) + html = req.app['jinja'].get_template(tmpl).render(**context) + return web.Response(text = html, content_type = 'text/html', status = status) + +def back(req: web.Request, location: str, text: Optional[str] = None, kind: str = 'success') -> web.Response: + if text: + req['admin'].flash(text, kind) + raise web.HTTPSeeOther(location) + +async def ins(req: web.Request, cmd: str, data: Optional[Dict[str, Any]] = None) -> Any: + link: LocalLink = req['ins'] + return await link.call(cmd, data) + +def _error_text(ex: LocalINSError) -> str: + return ex.message or 'InterService error {:03}'.format(ex.code) + +async def page_login(req: web.Request) -> web.Response: + auth: AdminAuth = req.app['auth'] + next_page = req.query.get('next', '/') + if not next_page.startswith('/') or next_page.startswith('//'): + next_page = '/' + error = None + login = '' + if req.method == 'POST': + data = await req.post() + login = str(data.get('login', ''))[:254] + if not auth.configured(): + error = 'The admin key isn\'t set up on this server yet. Put its SHA-256 hash in ADMIN_KEY and restart azul.' + elif auth.throttled(_peer(req)): + error = 'Too many attempts. Wait a few minutes and try again.' + else: + session = await auth.sign_in(_peer(req), login, str(data.get('password', '')), str(data.get('key', ''))) + if session is None: + error = 'Those details aren\'t right, or that account can\'t use the admin panel.' + else: + resp = web.HTTPSeeOther(next_page) + resp.set_cookie( + COOKIE_NAME, session.token, httponly = True, samesite = 'Strict', path = '/', + secure = bool(getattr(settings, 'ADMIN_COOKIE_SECURE', False)), + ) + raise resp + env = req.app['jinja'] + html = env.get_template('login.html').render(settings = settings, error = error, login = login, next = next_page, configured = auth.configured()) + return web.Response(text = html, content_type = 'text/html', status = 401 if error else 200) + +async def action_logout(req: web.Request) -> web.Response: + req.app['auth'].sign_out(req['admin'].token) + resp = web.HTTPSeeOther('/login') + resp.del_cookie(COOKIE_NAME, path = '/') + raise resp + +async def page_overview(req: web.Request) -> web.Response: + info = await ins(req, 'INF') + stats = await ins(req, 'STA') + alerts = (await ins(req, 'ALR', { 'action': 'LIST' })).get('alerts') or [] + suspended = await ins(req, 'LSU', { 'trait': 'suspended', 'limit': 1 }) + registry: ClientRegistry | None = req.app['registry'] + clients = registry.clients() if registry is not None else [] + online = stats.get('online') or {} + sessions = int(online.get('sessions') or 0) + return render(req, 'overview.html', { + 'title': 'Overview', 'info': info, 'stats': stats, + 'clients_active': len([c for c in clients if not c.revoked]), + 'links': [link for link in info.get('links') or [] if link.get('link') != 'local'], + 'uptime': _duration(info.get('uptime')), + 'hourly': _hourly(stats.get('hourly') or []), + 'programs': [ + { 'name': PROGRAM_NAMES.get(p.get('program'), p.get('program')), 'sessions': p.get('sessions', 0), 'pct': round(100 * p.get('sessions', 0) / sessions, 1) if sessions else 0 } + for p in online.get('by_program') or [] + ], + 'alerts': _alert_rows(alerts[:4]), 'alerts_count': len(alerts), + 'suspended': int(suspended.get('matched') or 0), 'suspended_days': getattr(settings, 'SUSPENDED_ACCOUNT_DAYS', None), + }) + +def _hourly(hours: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + top = max([int(h.get('users_active') or 0) for h in hours] + [1]) + out = [] # type: List[Dict[str, Any]] + for i, h in enumerate(hours): + value = int(h.get('users_active') or 0) + try: + label = datetime.fromisoformat(str(h.get('hour') or '').rstrip('Z')).strftime('%H:00') + except ValueError: + label = '' + out.append({ 'label': label, 'value': value, 'peak': int(h.get('peak') or 0), 'messages': int(h.get('messages_sent') or 0), 'pct': round(100 * value / top, 1), 'is_now': i == len(hours) - 1 }) + return out + +def _duration(seconds: Any) -> str: + try: + seconds = int(seconds or 0) + except (TypeError, ValueError): + return '-' + days, rest = divmod(seconds, 86400) + hours, rest = divmod(rest, 3600) + minutes = rest // 60 + parts = [] # type: List[str] + if days: + parts.append('{} day{}'.format(days, '' if days == 1 else 's')) + if hours: + parts.append('{} hour{}'.format(hours, '' if hours == 1 else 's')) + if not days and minutes: + parts.append('{} minute{}'.format(minutes, '' if minutes == 1 else 's')) + return ', '.join(parts) or 'less than a minute' + +async def page_users(req: web.Request) -> web.Response: + query = req.query.get('q', '').strip()[:100] + shown = req.query.get('show', '') + trait = next((t for name, _, t in USER_FILTERS if name == shown), None) + if trait is None: + shown = '' + try: + page = max(1, int(req.query.get('page', 1))) + except ValueError: + page = 1 + result = await ins(req, 'LSU', { 'query': query, 'trait': trait, 'limit': PAGE_SIZE, 'offset': (page - 1) * PAGE_SIZE }) + matched = int(result.get('matched') or 0) + return render(req, 'users.html', { + 'title': 'Users', 'q': query, 'show': shown, 'filters': USER_FILTERS, 'page': page, 'pages': max(1, ceil(matched / PAGE_SIZE)), + 'matched': matched, 'users': result.get('users') or [], 'total': result.get('total'), 'online': result.get('online'), + }) + +async def _user_or_404(req: web.Request, uuid: str) -> Dict[str, Any]: + try: + return await ins(req, 'GTU', { 'uuid': uuid }) + except LocalINSError as ex: + if ex.code == 428: + raise web.HTTPNotFound(text = 'No such user.') + raise + +async def page_user(req: web.Request) -> web.Response: + uuid = req.match_info['uuid'] + user = await _user_or_404(req, uuid) + sessions = (await ins(req, 'LSS', { 'filter': { 'uuid': uuid } })).get('sessions') or [] + return render(req, 'user.html', { + 'title': user['username'], 'user': user, 'sessions': sessions, 'flags': USER_FLAGS, 'legacy_clients': LEGACY_CLIENTS, + 'reset_available': bool(INSCtrl.listeners('password.reset')), + 'email_available': bool(INSCtrl.listeners('alert.email')), + 'is_self': user['uuid'] == req['admin'].uuid, + 'suspended_days': getattr(settings, 'SUSPENDED_ACCOUNT_DAYS', None), + 'programs': sorted({ PROGRAM_NAMES.get((s.get('client') or {}).get('program'), '?') for s in sessions }), + }) + +async def action_user(req: web.Request) -> web.Response: + uuid = req.match_info['uuid'] + form = req['form'] + action = form.get('action') + here = '/users/{}'.format(uuid) + user = await _user_or_404(req, uuid) + try: + if action == 'flags': + changes = {} # type: Dict[str, bool] + for key, _, _ in USER_FLAGS: + value = form.get(key) == 'on' + if key == 'is_admin' and user['uuid'] == req['admin'].uuid and not value: + return back(req, here, 'You can\'t take away your own admin rights. Ask another administrator.', 'danger') + if bool(user.get(key)) != value: + changes[key] = value + if not changes: + return back(req, here, 'Nothing changed.', 'info') + await ins(req, 'EDU', { 'uuid': uuid, 'fields': changes }) + if changes.get('is_admin') is False or changes.get('suspended'): + req.app['auth'].sign_out_user(uuid) + return back(req, here, 'Saved {}.'.format(', '.join(label.lower() for key, label, _ in USER_FLAGS if key in changes))) + if action == 'password': + password = str(form.get('password', '')) + if len(password) < 6: + return back(req, here, 'Passwords need at least 6 characters.', 'danger') + clients = [flag for flag, _ in LEGACY_CLIENTS if form.get('client_' + flag) == 'on'] + await ins(req, 'EDU', { 'uuid': uuid, 'fields': { 'password': password }, 'clients': clients }) + return back(req, here, 'Password changed. Their open sessions were signed out.') + if action == 'temp-password': + password = '-'.join(secrets.token_hex(3) for _ in range(3)) + await ins(req, 'EDU', { 'uuid': uuid, 'fields': { 'password': password }, 'clients': user.get('clients') or [] }) + req['admin'].reveal = { 'kind': 'password', 'value': password, 'for': user['username'] } + return back(req, here) + if action == 'reset-email': + listeners = INSCtrl.listeners('password.reset') + if not listeners: + return back(req, here, 'No website is linked to send the e-mail right now.', 'danger') + INSCtrl.broadcast('password.reset', { 'uuid': uuid, 'email': user['email'] }) + return back(req, here, 'Asked the website to e-mail a reset link to {}.'.format(user['email'])) + if action == 'kill': + killed = (await ins(req, 'KLS', { 'id': str(form.get('session', '')) }))['killed'] + return back(req, here, 'Signed out {} session{}.'.format(killed, '' if killed == 1 else 's')) + if action == 'kill-all': + killed = (await ins(req, 'KLS', { 'uuid': uuid }))['killed'] + return back(req, here, 'Signed out {} session{}.'.format(killed, '' if killed == 1 else 's')) + if action == 'alert': + fields = _alert_fields(form) + if not fields['rich'] and not fields['text']: + return back(req, here, 'Write the alert first.', 'danger') + result = await ins(req, 'ALR', { **fields, 'targets': [uuid] }) + return back(req, here, _alert_report(result)) + if action == 'delete': + if str(form.get('confirm', '')).strip() != user['username']: + return back(req, here, 'Type their username exactly to delete the account.', 'danger') + if user['uuid'] == req['admin'].uuid: + return back(req, here, 'You can\'t delete your own account from here.', 'danger') + await ins(req, 'RMU', { 'uuid': uuid }) + req.app['auth'].sign_out_user(uuid) + return back(req, '/users', 'Deleted {}.'.format(user['username'])) + except LocalINSError as ex: + return back(req, here, _error_text(ex), 'danger') + raise web.HTTPBadRequest(text = 'Unknown action.') + +async def page_sessions(req: web.Request) -> web.Response: + program = req.query.get('program', '') + flt = { 'program': program } if program else {} + result = await ins(req, 'LSS', { 'filter': flt }) + sessions = result.get('sessions') or [] + everything = (await ins(req, 'LSS', {})).get('sessions') or [] if program else sessions + programs = sorted({ (s.get('client') or {}).get('program') or '?' for s in everything }) + return render(req, 'sessions.html', { + 'title': 'Sessions', 'sessions': sessions, 'program': program, 'programs': [(p, PROGRAM_NAMES.get(p, p)) for p in programs], + 'count': result.get('count', 0), 'total': len(everything), + }) + +async def action_sessions(req: web.Request) -> web.Response: + form = req['form'] + try: + killed = (await ins(req, 'KLS', { 'id': str(form.get('session', '')) }))['killed'] + except LocalINSError as ex: + return back(req, '/sessions', _error_text(ex), 'danger') + return back(req, '/sessions' + ('?program=' + str(form.get('program')) if form.get('program') else ''), 'Signed out {} session{}.'.format(killed, '' if killed == 1 else 's')) + +async def page_circles(req: web.Request) -> web.Response: + circles = (await ins(req, 'CIR', { 'action': 'LIST' })).get('circles') or [] + circles.sort(key = lambda c: str(c.get('name') or '').lower()) + return render(req, 'circles.html', { 'title': 'Circles', 'circles': circles }) + +async def _circle_or_404(req: web.Request, chat_id: str) -> Dict[str, Any]: + try: + return await ins(req, 'CIR', { 'action': 'INFO', 'chat_id': chat_id }) + except LocalINSError as ex: + if ex.code == 200: + raise web.HTTPNotFound(text = 'No such circle.') + raise + +async def page_circle(req: web.Request) -> web.Response: + circle = await _circle_or_404(req, req.match_info['chat_id']) + members = [m for m in circle.get('members') or [] if m.get('state') not in (0, 4)] + members.sort(key = lambda m: (m.get('role') or 9, str(m.get('username') or '').lower())) + return render(req, 'circle.html', { 'title': circle['name'], 'circle': circle, 'members': members }) + +async def action_circle(req: web.Request) -> web.Response: + chat_id = req.match_info['chat_id'] + circle = await _circle_or_404(req, chat_id) + form = req['form'] + action = form.get('action') + here = '/circles/{}'.format(chat_id) + member = str(form.get('uuid', '')) + try: + if action == 'role': + role = int(str(form.get('role', '0'))) + if role == 1: + owner = next((m for m in circle.get('members') or [] if m.get('role') == 1 and m.get('state') == 3), None) + await ins(req, 'CIR', { 'action': 'ROLE', 'chat_id': chat_id, 'uuid': member, 'role': 1, 'uuid_self': owner['uuid'] if owner else None }) + return back(req, here, 'Ownership moved.') + await ins(req, 'CIR', { 'action': 'ROLE', 'chat_id': chat_id, 'uuid': member, 'role': role }) + return back(req, here, 'Role changed.') + if action == 'remove': + await ins(req, 'CIR', { 'action': 'REMOVE', 'chat_id': chat_id, 'uuid': member }) + return back(req, here, 'Removed from the circle.') + if action == 'revoke': + await ins(req, 'CIR', { 'action': 'REVOKE', 'chat_id': chat_id, 'uuid': member }) + return back(req, here, 'Invite withdrawn.') + if action == 'delete': + if str(form.get('confirm', '')).strip() != circle['name']: + return back(req, here, 'Type the circle\'s name exactly to delete it.', 'danger') + await ins(req, 'CIR', { 'action': 'DELETE', 'chat_id': chat_id }) + return back(req, '/circles', 'Deleted {}.'.format(circle['name'])) + except (ValueError, TypeError): + return back(req, here, 'That isn\'t a role.', 'danger') + except LocalINSError as ex: + return back(req, here, _error_text(ex), 'danger') + raise web.HTTPBadRequest(text = 'Unknown action.') + +async def page_broadcast(req: web.Request) -> web.Response: + info = await ins(req, 'INF') + alerts = (await ins(req, 'ALR', { 'action': 'LIST' })).get('alerts') or [] + return render(req, 'broadcast.html', { + 'title': 'Broadcast', 'info': info, 'alerts': _alert_rows(alerts), 'languages': ALERT_LANGUAGES, 'agents': AGENTS, + 'networks': ALERT_NETWORKS, 'max_body': MAX_BODY, 'site_url': settings.ALERT_SITE_URL, + 'email_available': bool(INSCtrl.listeners('alert.email')), + }) + +def _alert_fields(form: Any) -> Dict[str, Any]: + message = str(form.get('message', '')).replace('\r\n', '\n').strip() + align = str(form.get('align', 'left') or 'left') + rich = message if message and (align != 'left' or '*' in message or '\\' in message) else '' + plain = str(form.get('plain', '')).strip() + kind = str(form.get('kind', 'bell') or 'bell') + icon = str(form.get('icon', '')).strip() if kind == 'custom' else '' + fields = { + 'text': plain if rich else message, 'rich': rich, 'align': align, + 'url': str(form.get('url', '')).strip(), 'subscr_url': str(form.get('subscr_url', '')).strip(), + 'kind': 'bell' if kind == 'custom' else kind, 'icon': icon, + 'lang': str(form.get('lang', '') or '1033'), 'priority': str(form.get('priority', '') or '1'), + 'message_id': str(form.get('message_id', '') or '0'), 'via': str(form.get('via', '')).strip() or None, + } # type: Dict[str, Any] + if form.get('networks_shown'): + fields['networks'] = [n for n in ALERT_NETWORKS if form.get('network_' + n) == 'on'] + if form.get('email') == 'on': + fields['email'] = True + fields['email_text'] = str(form.get('email_text', '')).strip() + return fields + +def _alert_report(result: Dict[str, Any]) -> str: + delivered = int(result.get('delivered') or 0) + per_network = [(NETWORK_NAMES.get(n, n), c) for n, c in (result.get('networks') or {}).items() if c] + text = 'Alert shown in {}'.format(_count(delivered, 'session')) + if len(per_network) > 1: + text += ' ({})'.format(', '.join('{} {}'.format(c, name) for name, c in per_network)) + elif per_network: + text += ' of {}'.format(per_network[0][0]) + text += '.' + skipped = int(result.get('skipped') or 0) + if skipped: + text += ' {} couldn\'t show it.'.format(_count(skipped, 'session').capitalize()) + emailed = int(result.get('emailed') or 0) + if emailed: + text += ' A copy was e-mailed to {}.'.format(_count(emailed, 'person', 'people')) + return text + +def _count(n: int, noun: str, plural: Optional[str] = None) -> str: + return '{} {}'.format(n, noun if n == 1 else (plural or noun + 's')) + +def _alert_rows(alerts: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + rows = [] + for alert in alerts: + targets = alert.get('targets') + shown = ['{} {}'.format(c, NETWORK_NAMES.get(n, n)) for n, c in (alert.get('networks') or {}).items() if c] + reach = '{} · shown in {}{}'.format( + 'everyone' if targets == 'all' else ', '.join(str(t) for t in targets or []), _count(int(alert.get('delivered') or 0), 'session'), + ' ({})'.format(', '.join(shown)) if len(shown) > 1 else (' of ' + shown[0].split(' ', 1)[1] if shown else ''), + ) + if alert.get('emailed'): + reach += ' · e-mailed to {}'.format(_count(int(alert['emailed']), 'person', 'people')) + rows.append({ **alert, 'reach': reach }) + return rows + +async def action_broadcast(req: web.Request) -> web.Response: + form = req['form'] + action = form.get('action') + try: + if action == 'alert': + fields = _alert_fields(form) + if not fields['rich'] and not fields['text']: + return back(req, '/broadcast#alert', 'Write the alert first.', 'danger') + everyone = form.get('who', 'everyone') != 'people' + targets = ['all'] if everyone else [t.strip() for t in str(form.get('targets', '')).replace('\n', ',').split(',') if t.strip()] + if not targets: + return back(req, '/broadcast#alert', 'Name who the alert is for, or send it to everyone.', 'danger') + if fields.get('email') and everyone: + return back(req, '/broadcast#alert', 'Alerts are only e-mailed to the people you name.', 'danger') + if 'networks' in fields and not fields['networks']: + return back(req, '/broadcast#alert', 'Pick at least one network.', 'danger') + result = await ins(req, 'ALR', { **fields, 'targets': targets }) + return back(req, '/broadcast#history', _alert_report(result)) + if action == 'announce': + await ins(req, 'ANC', { 'title': str(form.get('title', '')).strip(), 'text': str(form.get('text', '')).strip(), 'url': str(form.get('url', '')).strip() }) + return back(req, '/broadcast#announcement', 'Posted to CrossTalk Beacon and What\'s New.') + if action == 'maintenance': + await ins(req, 'MNT', { 'minutes': int(str(form.get('minutes', '')) or '-1') }) + return back(req, '/broadcast#maintenance', 'Maintenance announced to everyone signed in.') + except (ValueError, TypeError): + return back(req, '/broadcast#maintenance', 'Give the minutes as a number.', 'danger') + except LocalINSError as ex: + return back(req, '/broadcast#{}'.format('alert' if action == 'alert' else action), _error_text(ex), 'danger') + raise web.HTTPBadRequest(text = 'Unknown action.') + +async def page_interservice(req: web.Request) -> web.Response: + registry: ClientRegistry | None = req.app['registry'] + linked = { link.client_record.id: link for link in INSCtrl._links.values() if link.client_record is not None } + return render(req, 'interservice.html', { + 'title': 'InterService', 'enabled': registry is not None, + 'clients': registry.clients() if registry is not None else [], 'codes': registry.codes() if registry is not None else [], + 'linked': linked, 'identifiers': settings.INS_IDENTIFIERS, 'host_key': registry.host_public if registry is not None else b'', + 'fingerprint': _fingerprint(registry.host_public) if registry is not None else '', + }) + +def _fingerprint(raw: bytes) -> str: + from core.interservice.crypto import fingerprint + return fingerprint(raw) + +async def action_interservice(req: web.Request) -> web.Response: + registry: ClientRegistry | None = req.app['registry'] + if registry is None: + raise web.HTTPNotFound(text = 'InterService is turned off.') + form = req['form'] + action = form.get('action') + here = '/interservice' + try: + client_id = int(str(form.get('client', '0') or '0')) + except ValueError: + client_id = 0 + if action == 'code': + identifier = str(form.get('identifier', '')) + try: + hours = int(str(form.get('hours', '24') or '24')) + code, record = registry.create_code( + identifier, label = str(form.get('label', '')).strip(), address = str(form.get('address', '')).strip() or None, + hours = hours, created_by = req['admin'].username, + ) + except ValueError as ex: + return back(req, here, 'Couldn\'t make the code: {}.'.format(ex), 'danger') + req['admin'].reveal = { 'kind': 'code', 'value': code, 'for': identifier, 'expires': _when(record.expires) } + return back(req, here) + if action == 'cancel-code': + try: + ok = registry.cancel_code(int(str(form.get('code', '0')))) + except ValueError: + ok = False + return back(req, here, 'Code cancelled.' if ok else 'That code was already used.', 'success' if ok else 'danger') + if action == 'revoke': + record = registry.revoke(client_id) + return back(req, here, 'Revoked {} "{}". Its links were closed.'.format(record.identifier, record.label) if record else 'No such client.') + if action == 'delete': + return back(req, here, 'Deleted.' if registry.delete(client_id) else 'Only revoked keys can be deleted.') + if action == 'addresses': + try: + record = registry.set_addresses(client_id, str(form.get('addresses', '')).replace(',', '\n').splitlines()) + except (KeyError, ValueError) as ex: + return back(req, here, 'Couldn\'t save the addresses ({}).'.format(ex), 'danger') + return back(req, here, 'Addresses for {} "{}" saved.'.format(record.identifier, record.label)) + raise web.HTTPBadRequest(text = 'Unknown action.') diff --git a/front/admin/tmpl/_ui.html b/front/admin/tmpl/_ui.html new file mode 100644 index 0000000..49bd206 --- /dev/null +++ b/front/admin/tmpl/_ui.html @@ -0,0 +1,71 @@ +{% macro hub(title, sub=None) -%} +
+

{{ title }}

+ {% if sub %}

{{ sub }}

{% endif %} + {% if caller %}{{ caller() }}{% endif %} +
+{%- endmacro %} + +{% macro flash_list(flashes) -%} +{% for kind, text in flashes %} +
+ +
{{ text }}
+
+{% endfor %} +{%- endmacro %} + +{% macro csrf_field(csrf) -%} + +{%- endmacro %} + +{% macro copy_field(id, value, label) -%} +
+ + + +
+{%- endmacro %} + +{% macro flags(user) -%} +{%- if user.is_admin %}admin{% endif -%} +{%- if user.suspended %}suspended{% endif -%} +{#{%- if not user.verified_to_login %}can't sign in{% endif -%}#} +{%- if not user.account_verified %}unverified e-mail{% endif -%} +{%- if user.show_in_dir %}listed in directory{% endif -%} +{%- if user.is_tester %}tester{% endif -%} +{%- if user.is_mvp %}MVP{% endif -%} +{%- endmacro %} + +{% macro pager(page, pages, base) -%} +{% if pages > 1 %} + +{% endif %} +{%- endmacro %} + +{% macro tile(href, icon, big, name, note=None, tone=1, wide=False) -%} + + + {{ big }} + {{ name }} + {% if note %}{{ note }}{% endif %} + +{%- endmacro %} + +{% macro alert_row(alert) -%} +
  • + +
    +

    {{ alert.text }}

    +

    {{ alert.date | ago }} by {{ alert.by }} · {{ alert.reach }}{% if alert.url %} · link (opens in a new tab){% endif %}

    +
    +
  • +{%- endmacro %} diff --git a/front/admin/tmpl/base.html b/front/admin/tmpl/base.html new file mode 100644 index 0000000..fac8ab0 --- /dev/null +++ b/front/admin/tmpl/base.html @@ -0,0 +1,81 @@ +{% from '_ui.html' import flash_list -%} + + + + + + + + + + + + + + {% if title %}{{ title }} | {% endif %}azul admin + + +Skip to main content +
    + +
    + +
    + + +
    + {{ flash_list(flashes) }} + {% block content %}{% endblock %} +
    +
    + + diff --git a/front/admin/tmpl/broadcast.html b/front/admin/tmpl/broadcast.html new file mode 100644 index 0000000..f1521df --- /dev/null +++ b/front/admin/tmpl/broadcast.html @@ -0,0 +1,190 @@ +{% extends 'base.html' %} +{% from '_ui.html' import hub, csrf_field, alert_row %} +{% block content %} +{% set maintenance = info.maintenance or {} %} +{{ hub('broadcast', 'Alerts in people\'s clients, news on CrossTalk Beacon, and warnings before maintenance.') }} + +
    + + + + +
    + +
    +
    + {{ csrf_field(csrf) }} + + +
    +
    +
    + + +
    + + **bold**, *italic*, a backslash before a * to keep it, and a blank line for a new paragraph. Messenger 6 and later show the formatting; everything else gets the words. +
    + +
    +
    + + + Where clicking the alert goes. Empty goes to {{ site_url }}. +
    +
    + Icon +
    + {% for kind, label, icon in [('bell', 'bell', 'bi-bell-fill'), ('stocks', 'stocks', 'bi-graph-up-arrow'), ('calendar', 'calendar', 'bi-calendar-event-fill'), ('custom', 'your own', 'bi-image-fill')] %} + + + {% endfor %} +
    +
    +
    +
    + + + A 32×32 PNG. Messenger 6 and later swap _32x32 in its name for _48x32 and use that one if it's there. +
    + +
    + Who +
    + + + + +
    +
    +
    +
    + + + Separated with commas or on lines of their own. +
    +
    + + +
    + {% if not email_available %}

    The website isn't linked right now, so it can't send e-mail.

    {% endif %} +
    + + + Empty sends the alert's words and its link. Messenger also gets it as the alert's EMAILTEXT. +
    +
    + +
    + Clients +
    + {% for network in networks %} + + + {% endfor %} +
    +
    + +
    + more .NET Alerts options +
    +
    +
    + + + Messenger's option to change the alert (SUBSCR). Empty uses the link. +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    + + + What Messenger 5 and older, Yahoo!, AIM and IRC show when the message has formatting. Empty takes the message's words. +
    +
    +
    + +
    +
    +
    +
    + +
    +

    A news item on CrossTalk Beacon and in Windows Live Messenger's What's New.

    +
    + {{ csrf_field(csrf) }} + +
    + + +
    +
    + + +
    +
    + + +
    + +
    +
    + +
    + {% if maintenance.active %} +

    The server is in maintenance mode right now.

    + {% elif maintenance.pending %} +

    Maintenance is already announced, in about {{ maintenance.minutes }} minute{{ 's' if maintenance.minutes != 1 else '' }}.

    + {% else %} +

    Tells everyone signed in that the server is going down, with a countdown. The website's status page shows it too.

    +
    + {{ csrf_field(csrf) }} + +
    + + +
    + +
    + {% endif %} +
    + +
    + {% if alerts %} +

    The last {{ alerts | length }} alert{{ 's' if alerts | length != 1 else '' }} since azul started, newest first.

    +
      + {% for alert in alerts %}{{ alert_row(alert) }}{% endfor %} +
    + {% else %} +

    No alerts since azul started.

    + {% endif %} +
    +{% endblock %} diff --git a/front/admin/tmpl/circle.html b/front/admin/tmpl/circle.html new file mode 100644 index 0000000..fe18dbe --- /dev/null +++ b/front/admin/tmpl/circle.html @@ -0,0 +1,77 @@ +{% extends 'base.html' %} +{% from '_ui.html' import csrf_field %} +{% block content %} +

    Circles

    + +
    + +
    +

    {{ circle.name }}

    +

    {{ members | length }} member{{ 's' if members | length != 1 else '' }} · {{ members | selectattr('in_chat') | list | length }} in the conversation now · {{ circle.chat_id }}

    +
    +
    + +
    +

    members

    + +
    + +
    +

    delete this circle

    +

    Ends the conversation for everyone and takes the circle off every member's contact list. It can't be undone.

    +
    + {{ csrf_field(csrf) }} + + +
    + + +
    +
    +
    +{% endblock %} diff --git a/front/admin/tmpl/circles.html b/front/admin/tmpl/circles.html new file mode 100644 index 0000000..9031393 --- /dev/null +++ b/front/admin/tmpl/circles.html @@ -0,0 +1,24 @@ +{% extends 'base.html' %} +{% from '_ui.html' import hub %} +{% block content %} +{{ hub('circles', '{:,}'.format(circles | length) ~ ' group chats on the server.') }} + +{% if circles %} + +{% else %} +

    No circles yet.

    +{% endif %} +{% endblock %} diff --git a/front/admin/tmpl/interservice.html b/front/admin/tmpl/interservice.html new file mode 100644 index 0000000..6e70c33 --- /dev/null +++ b/front/admin/tmpl/interservice.html @@ -0,0 +1,133 @@ +{% extends 'base.html' %} +{% from '_ui.html' import hub, csrf_field, copy_field %} +{% block content %} +{{ hub('interservice', 'The services linked to azul (the website, bots, tools). Each one has keys of its own that only work from the machine and address it enrolled from.') }} + +{% if not enabled %} +

    InterService is turned off on this server (ENABLE_INS).

    +{% else %} + +{% if reveal and reveal.kind == 'code' %} +
    +

    enrollment code for {{ reveal['for'] }}

    +

    Put it in the service's settings (the website's is INS_ENROLLMENT_CODE) before {{ reveal.expires }}. It works once, and this is the only time it's shown.

    + {{ copy_field('enrollCodeValue', reveal.value, 'Enrollment code') }} +
    +{% endif %} + +
    +

    enrolled services

    + {% if clients %} +
      + {% for c in clients %} + {% set link = linked.get(c.id) %} +
    • +
      + +
      +

      {{ c.label or c.identifier }}

      +

      {{ c.identifier }} · {% if c.revoked %}revoked {{ c.revoked_at | ago }}{% elif link %}linked now{% else %}last seen {{ c.last_seen | ago }}{% endif %}

      +
      + {% if not c.revoked %} +
      + {{ csrf_field(csrf) }} + + + +
      + {% else %} +
      + {{ csrf_field(csrf) }} + + + +
      + {% endif %} +
      +
      +
      key
      {{ c.fingerprint }}
      +
      enrolled
      {{ c.created | when }}
      +
      last address
      {{ c.last_address or '-' }}
      +
      + {% if not c.revoked %} +
      + {{ csrf_field(csrf) }} + + + +
      + + +
      + Addresses or networks (CIDR), separated with commas. Anything else is turned away, even with the right keys. +
      + {% endif %} +
    • + {% endfor %} +
    + {% else %} +

    Nothing has enrolled yet. Make a code below for the website first.

    + {% endif %} +
    + +
    +
    +

    enroll a service

    +

    A one-time code. The service makes its own keys the first time it connects with it, and they never leave that machine.

    +
    + {{ csrf_field(csrf) }} + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    + +
    +

    codes

    + {% set shown = codes[:12] %} + {% if shown %} +
      + {% for code in shown %} +
    • + + {{ code.label or code.identifier }} + {{ code.identifier }}{% if code.address %} from {{ code.address }}{% endif %} · {% if code.state == 'used' %}used {{ code.used | ago }}{% elif code.state == 'expired' %}expired{% else %}waiting until {{ code.expires | when }}{% endif %} + + {% if code.state == 'waiting' %} +
      + {{ csrf_field(csrf) }} + + + +
      + {% endif %} +
    • + {% endfor %} +
    + {% else %} +

    None made yet.

    + {% endif %} +

    Server host key {{ fingerprint }}

    +
    +
    +{% endif %} +{% endblock %} diff --git a/front/admin/tmpl/login.html b/front/admin/tmpl/login.html new file mode 100644 index 0000000..c6326d2 --- /dev/null +++ b/front/admin/tmpl/login.html @@ -0,0 +1,68 @@ + + + + + + + + + + + + + Sign in | azul admin + + +
    + +
    +
    +
    +
    +

    sign in

    +

    sign in to manage azul {{ settings.VERSION }}

    +
    + {% if not configured %} +
    No admin key is set up yet. Put the SHA-256 hash of one in ADMIN_KEY and restart azul.
    + {% endif %} + {% if error %} + + {% elif next and next != '/' %} +
    Sign in to carry on where you were.
    + {% endif %} +
    +
    + + +
    +
    + +
    + + +
    +
    +
    + +
    + + +
    +
    + +
    +

    not an administrator? this panel is only for the people who run this server, so shoo, go away.

    +
    +
    + + diff --git a/front/admin/tmpl/overview.html b/front/admin/tmpl/overview.html new file mode 100644 index 0000000..a1ce504 --- /dev/null +++ b/front/admin/tmpl/overview.html @@ -0,0 +1,139 @@ +{% extends 'base.html' %} +{% from '_ui.html' import hub, tile, alert_row %} +{% block content %} +{% set online = stats.online or {} %} +{% set accounts = stats.accounts or {} %} +{% set maintenance = info.maintenance or {} %} +{{ hub('overview', 'azul ' ~ info.version ~ ', up for ' ~ uptime ~ '.') }} + +{% if maintenance.active or maintenance.pending %} +
    {% if maintenance.active %}The server is in maintenance mode.{% else %}Maintenance is coming up in about {{ maintenance.minutes }} minute{{ 's' if maintenance.minutes != 1 else '' }}.{% endif %}
    +{% endif %} + +
    +

    Right now

    +
    + {{ tile('/sessions', 'bi-plug-fill', '{:,}'.format(info.sessions or 0), 'sessions open', '{:,}'.format(info.users_online or 0) ~ (' person' if info.users_online == 1 else ' people') ~ ' signed in', tone='hero', wide=True) }} + {{ tile('/users', 'bi-people-fill', '{:,}'.format(accounts.total or 0), 'accounts', '{:,}'.format(accounts.new_week or 0) ~ ' new this week', tone=2) }} + {{ tile('/users?show=suspended', 'bi-person-fill-x', '{:,}'.format(suspended), 'suspended', ('deleted after ' ~ suspended_days ~ ' days') if suspended_days is not none else 'kept for good', tone=3) }} + {{ tile('/circles', 'bi-chat-square-dots-fill', '{:,}'.format(stats.circles or 0), 'circles', 'group chats', tone=4) }} + {{ tile('/broadcast#history', 'bi-bell-fill', '{:,}'.format(alerts_count), 'alerts', 'sent since azul started', tone=5) }} + {{ tile('/interservice', 'bi-diagram-3-fill', links | length, 'services linked', clients_active ~ ' enrolled', tone=6) }} + {% if maintenance.active %} + {{ tile('/broadcast#maintenance', 'bi-cone-striped', 'on', 'maintenance', 'the server is down for it', tone=3) }} + {% elif maintenance.pending %} + {{ tile('/broadcast#maintenance', 'bi-cone-striped', maintenance.minutes ~ ' min', 'maintenance', 'announced to everyone', tone=3) }} + {% else %} + {{ tile('/broadcast#maintenance', 'bi-cone-striped', 'none', 'maintenance', 'nothing planned', tone=1) }} + {% endif %} +
    +
    + +
    +
    +

    the last 24 hours

    + {% if hourly %} + {% set busiest = hourly | map(attribute='value') | max %} +
    + + +
    +
    + show as a table +
    +
    + + + + + {% for h in hourly | reverse %} + + {% endfor %} + +
    Every hour of the last 24, times in UTC
    houractivemost onlinemessages sent
    {{ h.label }}{% if h.is_now %} now{% endif %}{{ h.value }}{{ h.peak }}{{ h.messages }}
    +
    +
    +
    + {% else %} +

    Nothing counted yet.

    + {% endif %} +
    + +
    +

    clients

    + {% if programs %} +
      + {% for p in programs %} +
    • +
      {{ p.name }}{{ '{:,}'.format(p.sessions) }} session{{ 's' if p.sessions != 1 else '' }} · {{ p.pct }}%
      + +
    • + {% endfor %} +
    + {% else %} +

    Nobody is signed in right now.

    + {% endif %} +
    +
    active today
    {{ '{:,}'.format((stats.active or {}).today or 0) }}
    +
    sign-ins today
    {{ '{:,}'.format(stats.logins_today or 0) }}
    +
    messages today
    {{ '{:,}'.format(((stats.messages or {}).today or {}).sent or 0) }}
    +
    most online today
    {{ '{:,}'.format((stats.peak_today or {}).value or 0) }}
    +
    +
    + +
    +

    latest alerts

    + {% if alerts %} +
      + {% for alert in alerts %}{{ alert_row(alert) }}{% endfor %} +
    +

    Every alert since azul started

    + {% else %} +

    None sent since azul started.

    + {% endif %} +
    + +
    + + {% if links %} +
      + {% for link in links %} +
    • + + + {{ link.label or link.identifier }} + {{ link.identifier }} from {{ link.peer }}{% if link.client and link.client.program %} · {{ link.client.program }} {{ link.client.version }}{% endif %} + +
    • + {% endfor %} +
    + {% else %} +

    Nothing is linked over InterService right now. The website needs its own link for accounts, the directory and CrossTalk Beacon.

    + {% endif %} +

    listening

    + {% if info.services %} +
    + {% for service in info.services %} +
    {{ service.name }}
    {{ service.ports | join(', ') }}
    + {% endfor %} +
    + {% else %} +

    No IM services are listening (none are turned on in the settings).

    + {% endif %} +
    +
    + +
    +

    quick jobs

    + +
    +{% endblock %} diff --git a/front/admin/tmpl/sessions.html b/front/admin/tmpl/sessions.html new file mode 100644 index 0000000..94ae098 --- /dev/null +++ b/front/admin/tmpl/sessions.html @@ -0,0 +1,41 @@ +{% extends 'base.html' %} +{% from '_ui.html' import hub, csrf_field %} +{% block content %} +{{ hub('sessions', '{:,}'.format(count) ~ ' open' ~ (' in ' ~ program_names.get(program, program) if program else '') ~ '.') }} + +{% if programs %} + +{% endif %} + +{% if sessions %} +
    +
    + + + + {% for s in sessions %} + + + + + + + {% endfor %} + +
    whoclientstatusactions
    {{ s.username }}
    {{ s.email }}
    {{ program_names.get(s.client.program, s.client.program) }} {{ s.client.version }}
    {{ s.client.via }}
    {% if s.visible %}{% endif %}{{ s.status | lower }} +
    + {{ csrf_field(csrf) }} + + + +
    +
    +
    +
    +{% else %} +

    Nobody is signed in{% if program %} with {{ program_names.get(program, program) }}{% endif %}.

    +{% endif %} +{% endblock %} diff --git a/front/admin/tmpl/user.html b/front/admin/tmpl/user.html new file mode 100644 index 0000000..e65c290 --- /dev/null +++ b/front/admin/tmpl/user.html @@ -0,0 +1,181 @@ +{% extends 'base.html' %} +{% from '_ui.html' import flags as flag_chips, csrf_field, copy_field %} +{% block content %} +

    Users

    + +
    + + + {% if user.online %}{% endif %} + +
    +

    {{ user.username }}

    +

    {{ user.email }}{% if user.uin %} · UIN {{ user.uin }}{% endif %}

    +

    {{ flag_chips(user) }}

    +
    +
    +
    status
    {% if user.online %}{{ user.status | lower }}, {{ user.sessions }} session{{ 's' if user.sessions != 1 else '' }}{% if programs %} ({{ programs | join(', ') }}){% endif %}{% else %}signed out{% endif %}
    +
    joined
    {{ user.date_created | when }}
    +
    last signed in
    {{ user.date_login | when }}
    +
    UUID
    {{ user.uuid }}
    +
    +
    + +{% if user.suspended %} +
    +
    +

    suspended{% if user.suspended_at %} {{ user.suspended_at | ago }}{% endif %}

    + {% if user.deleted_at is none or suspended_days is none %} +

    {% if user.suspended_at %}Since {{ user.suspended_at | when }}. {% endif %}Suspended accounts are kept on this server.

    + {% elif user.suspended_at %} +

    Since {{ user.suspended_at | when }}. The account is deleted {{ user.deleted_at | until }} ({{ user.deleted_at | when }}), {{ suspended_days }} days after it was suspended, unless it's unsuspended before then.

    + {% else %} +

    It was suspended before azul kept the date, so it's deleted at the next hourly check, unless it's unsuspended first.

    + {% endif %} +
    +
    +{% endif %} + +{% if reveal and reveal.kind == 'password' %} +
    +

    temporary password for {{ reveal['for'] }}

    +

    Give it to them however you can reach them. It won't be shown again, and they should change it once they're in.

    + {{ copy_field('tempPasswordValue', reveal.value, 'Temporary password') }} +
    +{% endif %} + +
    +
    +

    account

    +
    + {{ csrf_field(csrf) }} + +
    + {% for key, label, desc in flags %} + + {% if key == 'is_admin' and is_self and user[key] %}{% endif %} + {% endfor %} +
    +
    +
    +
    + +
    +
    +

    alert

    +
    + {{ csrf_field(csrf) }} + +
    + + + **bold**, *italic*, and a blank line for a new paragraph: Messenger 6 and later show them, the rest get the words. +
    +
    + + +
    + {% if email_available %} +
    + + +
    + {% endif %} + + {% if not user.online %}

    {{ user.username }} isn't signed in{% if email_available %}, so only an e-mail copy would reach them{% else %}, and the website isn't linked to e-mail it{% endif %}.

    {% endif %} +
    +
    + +
    +

    sessions

    + {% if sessions %} +
      + {% for s in sessions %} +
    • + + {{ program_names.get(s.client.program, s.client.program) }} {{ s.client.version }} + {{ s.status | lower }} via {{ s.client.via }} + +
      + {{ csrf_field(csrf) }} + + + +
      +
    • + {% endfor %} +
    +
    + {{ csrf_field(csrf) }} + + +
    + {% else %} +

    Not signed in anywhere.

    + {% endif %} +
    + +
    +

    password

    +
    + {{ csrf_field(csrf) }} + +
    + +
    + + +
    +
    +
    + Keep working in + {% for flag, name in legacy_clients %} +
    + + +
    + {% endfor %} +
    + +
    +
    +
    + {{ csrf_field(csrf) }} + + +
    +
    + {{ csrf_field(csrf) }} + + +
    +
    + {% if not reset_available %}

    The website isn't linked right now, so it can't send the e-mail.

    {% endif %} +
    +
    +
    + +
    +

    delete this account

    + {% if is_self %} +

    You can't delete your own account from the admin panel.

    + {% else %} +

    Removes {{ user.username }} for good: their contacts, CrossTalk Beacon posts, reactions and comments go too, and circles they ran pass to the next administrator or member. It can't be undone.

    +
    + {{ csrf_field(csrf) }} + + +
    + + +
    +
    + {% endif %} +
    +{% endblock %} diff --git a/front/admin/tmpl/users.html b/front/admin/tmpl/users.html new file mode 100644 index 0000000..6f70b49 --- /dev/null +++ b/front/admin/tmpl/users.html @@ -0,0 +1,50 @@ +{% extends 'base.html' %} +{% from '_ui.html' import hub, flags, pager %} +{% block content %} +{{ hub('users', '{:,}'.format(total or 0) ~ ' accounts, ' ~ '{:,}'.format(online or 0) ~ ' signed in right now.') }} + + + +{% set query = ('&q=' ~ (q | urlencode)) if q else '' %} + + +{% if q or show %}

    {{ '{:,}'.format(matched) }} {{ 'account' if matched == 1 else 'accounts' }}{% if q %} matching "{{ q }}"{% endif %}

    {% endif %} + +{% if users %} + +{{ pager(page, pages, '/users?' ~ ('show=' ~ show ~ '&' if show else '') ~ ('q=' ~ (q | urlencode) ~ '&' if q else '')) }} +{% else %} +

    {% if q or show %}Nobody matches that.{% else %}There are no accounts yet.{% endif %}

    +{% endif %} +{% endblock %} diff --git a/front/api/entry.py b/front/api/entry.py deleted file mode 100644 index f185dc5..0000000 --- a/front/api/entry.py +++ /dev/null @@ -1,67 +0,0 @@ -from typing import Any, Dict, List -from aiohttp import web -import json, util.misc - -from core.backend import Backend -from core.http import render - -TMPL_DIR = 'front/api/tmpl' - -def register(app: web.Application) -> None: - util.misc.add_to_jinja_env(app, 'api', TMPL_DIR) - - # Actual APIs - app.router.add_get('/api/ircChats', handle_ircchats) - app.router.add_get('/api/stats/{service}', handle_stats_api) - - # API tests - app.router.add_route('*', '/api/chats-test', handle_chat_list) - -async def handle_ircchats(req: web.Request) -> web.Response: - backend = req.app['backend'] # type: Backend - - result = [] # type: List[Dict[str, Any]] - - for chat in backend.get_chats_by_scope('irc'): - nicks = [cs.user.email for cs in chat.get_roster_single()] - - result.append({ - 'channel': chat.ids['irc'], - 'users': nicks, - }) - - return web.Response(status = 200, body = json.dumps(result)) - -async def handle_stats_api(req: web.Request) -> web.Response: - backend = req.app['backend'] # type: Backend - - service = req.match_info['service'] - result = {} # type: Dict[str, Any] - - if service == 'usersActive': - result['users_active'] = str(backend._stats.logged_in) - return web.Response(status = 200, body = json.dumps(result)) - if service == 'messages': - # TODO: Support message count by client ID - - messages_received = 0 - messages_sent = 0 - - for stats_raw in backend._stats.by_client.values(): - from core.stats import _stats_to_json as stats_json - stats = stats_json(stats_raw) # type: Dict[str, Any] - - if 'messages_received' in stats: - messages_received += int(stats['messages_received']) - if 'messages_sent' in stats: - messages_sent += int(stats['messages_sent']) - - result['messages_received'] = str(messages_received) - result['messages_sent'] = str(messages_sent) - - return web.Response(status = 200, body = json.dumps(result)) - - return web.Response(status = 400) - -async def handle_chat_list(req: web.Request) -> web.Response: - return render(req, 'api:chats-test.html') \ No newline at end of file diff --git a/front/api/tmpl/chats-test.html b/front/api/tmpl/chats-test.html deleted file mode 100644 index 5fa048e..0000000 --- a/front/api/tmpl/chats-test.html +++ /dev/null @@ -1,36 +0,0 @@ - - -

    IRC Chats

    -
    -
    - - - \ No newline at end of file diff --git a/front/bot/entry.py b/front/bot/entry.py deleted file mode 100644 index d23e10d..0000000 --- a/front/bot/entry.py +++ /dev/null @@ -1,177 +0,0 @@ -from typing import Optional, Dict, Any -import asyncio, random - -from core.client import Client -from core.models import ( - Substatus, ContactList, Contact, User, Circle, CircleRole, TextWithData, - MessageData, MessageType, LoginOption, OIM, -) -from core.backend import Backend, BackendSession, Chat, ChatSession -from core import event -from util.misc import MultiDict - -CLIENT = Client('ct-bot', 'testing', 'direct') -BOT_EMAIL = 'bot1@crosstalk.im' - -def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None: - uuid = backend.util_get_uuid_from_email(BOT_EMAIL) - assert uuid is not None - bs = backend.login(uuid, CLIENT, BackendEventHandler(loop), option = LoginOption.BootOthers) - assert bs is not None - -class BackendEventHandler(event.BackendEventHandler): - __slots__ = ('loop', 'bs') - - loop: asyncio.AbstractEventLoop - bs: BackendSession - - def __init__(self, loop: asyncio.AbstractEventLoop) -> None: - self.loop = loop - - def on_open(self) -> None: - bs = self.bs - - bs.me_update({ 'substatus': Substatus.Online }) - print(f"[Bot] {bs.user.status.name} is now online!") - - detail = bs.user.detail - assert detail is not None - - def on_maintenance_boot(self) -> None: - pass - - 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, - send_status_on_bl: bool = False, sess_id: Optional[int] = None, updated_phone_info: Optional[Dict[str, Any]] = None, - ) -> None: - pass - - def on_presence_self_notification( - self, old_substatus: Substatus, *, update_status: bool = True, update_info: bool = True, - ) -> None: - pass - - def on_circle_created(self, circle: Circle) -> None: - pass - - def on_circle_updated(self, circle: Circle) -> None: - pass - - def on_left_circle(self, circle: Circle) -> None: - pass - - def on_accepted_circle_invite(self, circle: Circle) -> None: - pass - - def on_circle_invite_revoked(self, chat_id: str) -> None: - pass - - def on_circle_role_updated(self, chat_id: str, role: CircleRole) -> None: - pass - - def on_chat_invite( - self, chat: Chat, inviter: User, *, circle: bool = False, inviter_id: Optional[str] = None, invite_msg: str = '', - ) -> None: - cs = chat.join('ct-bot', self.bs, ChatEventHandler(self.loop, self.bs)) - chat.send_participant_joined(cs) - - def on_declined_chat_invite(self, chat: Chat, circle: bool = False) -> None: - pass - - def on_added_me(self, user: User, *, adder_id: Optional[str] = None, message: Optional[TextWithData] = None) -> None: - # Auto-remove people from pending list - bs = self.bs - detail = bs.user.detail - assert detail is not None - - ctc = detail.contacts.get(user.uuid) - if ctc is not None: - bs.me_contact_remove(ctc.head.uuid, ContactList.PL) - - def on_removed_me(self, user: User) -> None: - pass - - def on_contact_request_denied(self, user_added: User, message: Optional[str], *, contact_id: Optional[str] = None) -> None: - pass - - def on_oim_sent(self, oim: 'OIM') -> None: - pass - - def ymsg_on_p2p_msg_request(self, sess_id: int, yahoo_data: MultiDict[bytes, bytes]) -> None: - pass - - def ymsg_on_xfer_init(self, sess_id: int, yahoo_data: MultiDict[bytes, bytes]) -> None: - pass - - def ymsg_on_sent_ft_http(self, yahoo_id_sender: str, url_path: str, upload_time: float, message: str) -> None: - pass - - def on_login_elsewhere(self, option: LoginOption) -> None: - pass - -class ChatEventHandler(event.ChatEventHandler): - __slots__ = ('loop', 'bs', 'cs', '_sending') - - loop: asyncio.AbstractEventLoop - bs: BackendSession - cs: ChatSession - _sending: bool - - def __init__(self, loop: asyncio.AbstractEventLoop, bs: BackendSession) -> None: - self.loop = loop - self.bs = bs - self._sending = False - - def on_open(self) -> None: - self.cs.send_message_to_everyone(MessageData( - sender = self.cs.user, - type = MessageType.Chat, - text = "Hello, world!", - )) - - def on_participant_joined(self, cs_other: ChatSession, first_pop: bool, initial_join: bool) -> None: - pass - - def on_participant_left(self, cs_other: ChatSession, last_pop: bool) -> None: - pass - - def on_chat_invite_declined( - self, chat: Chat, invitee: User, *, invitee_id: Optional[str] = None, message: Optional[str] = None, circle: bool = False, - ) -> None: - pass - - def on_chat_updated(self) -> None: - pass - - def on_chat_roster_updated(self) -> None: - pass - - def on_participant_status_updated(self, cs_other: ChatSession, first_pop: bool, initial: bool, old_substatus: Substatus) -> None: - pass - - def on_invite_declined(self, invited_user: User, *, invited_id: Optional[str] = None, message: str = '') -> None: - pass - - def on_message(self, message: MessageData) -> None: - if self._sending: - return - - if message.sender.email.endswith('@crosstalk.im'): - return - - me = self.cs.user - self._sending = True - - typing_message = MessageData(sender = me, type = MessageType.Typing) - self.cs.send_message_to_everyone(typing_message) - - self.loop.create_task(self._send_delayed(random.uniform(0.5, 1), MessageData( - sender = me, type = MessageType.Chat, - text = "You, {}, insist that \"{}\".".format(message.sender.status.name, message.text), - ))) - - async def _send_delayed(self, delay: float, message: MessageData) -> None: - await asyncio.sleep(delay, loop = self.loop) - self.cs.send_message_to_everyone(message) - self._sending = False diff --git a/front/devbots/__init__.py b/front/devbots/__init__.py deleted file mode 100644 index d5b9166..0000000 --- a/front/devbots/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .entry import register diff --git a/front/devbots/entry.py b/front/devbots/entry.py deleted file mode 100644 index ad05718..0000000 --- a/front/devbots/entry.py +++ /dev/null @@ -1,170 +0,0 @@ -from typing import Optional, Dict, Any -import asyncio, random - -from core.client import Client -from core.models import ( - Substatus, ContactList, Contact, Circle, CircleRole, User, - TextWithData, MessageData, MessageType, LoginOption, OIM, -) -from core.backend import Backend, BackendSession, Chat, ChatSession -from core import event -from util.misc import MultiDict - -CLIENT = Client('ct-bot', '0.1', 'direct') - -def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None: - for i in range(5): - uuid = backend.util_get_uuid_from_email('bot{}@crosstalk.im'.format(i)) - assert uuid is not None - bs = backend.login(uuid, CLIENT, BackendEventHandler(loop), option = LoginOption.BootOthers) - assert bs is not None - -class BackendEventHandler(event.BackendEventHandler): - __slots__ = ('loop', 'bs') - - loop: asyncio.AbstractEventLoop - bs: BackendSession - - def __init__(self, loop: asyncio.AbstractEventLoop) -> None: - self.loop = loop - - def on_open(self) -> None: - self.bs.me_update({ 'substatus': Substatus.Online }) - print("Bot active:", self.bs.user.status.name) - - 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, - send_status_on_bl: bool = False, sess_id: Optional[int] = None, updated_phone_info: Optional[Dict[str, Any]] = None, - ) -> None: - pass - - def on_presence_self_notification( - self, old_substatus: Substatus, *, update_status: bool = True, update_info: bool = True, - ) -> None: - pass - - def on_circle_created(self, circle: Circle) -> None: - pass - - def on_circle_updated(self, circle: Circle) -> None: - pass - - def on_left_circle(self, circle: Circle) -> None: - pass - - def on_accepted_circle_invite(self, circle: Circle) -> None: - pass - - def on_circle_invite_revoked(self, chat_id: str) -> None: - pass - - def on_circle_role_updated(self, chat_id: str, role: CircleRole) -> None: - pass - - def on_chat_invite( - self, chat: Chat, inviter: User, *, circle: bool = False, inviter_id: Optional[str] = None, invite_msg: Optional[str] = None, - ) -> None: - cs = chat.join('ct-bot', self.bs, ChatEventHandler(self.loop, self.bs)) - chat.send_participant_joined(cs) - - def on_declined_chat_invite(self, chat: Chat, circle: bool = False) -> None: - pass - - def on_added_me(self, user: User, *, adder_id: Optional[str] = None, message: Optional[TextWithData] = None) -> None: - # Auto-remove people from pending list - bs = self.bs - detail = bs.user.detail - assert detail is not None - - ctc = detail.contacts.get(user.uuid) - if ctc is not None: - bs.me_contact_remove(ctc.head.uuid, ContactList.PL) - - def on_removed_me(self, user: User) -> None: - pass - - def on_contact_request_denied(self, user_added: User, message: Optional[str], *, contact_id: Optional[str] = None) -> None: - pass - - def on_oim_sent(self, oim: 'OIM') -> None: - pass - - def on_login_elsewhere(self, option: LoginOption) -> None: - pass - - def ymsg_on_p2p_msg_request(self, sess_id: int, yahoo_data: MultiDict[bytes, bytes]) -> None: - pass - - def ymsg_on_xfer_init(self, sess_id: int, yahoo_data: MultiDict[bytes, bytes]) -> None: - pass - - def ymsg_on_sent_ft_http(self, yahoo_id_sender: str, url_path: str, upload_time: float, message: str) -> None: - pass - -class ChatEventHandler(event.ChatEventHandler): - __slots__ = ('loop', 'bs', 'cs', '_sending') - - loop: asyncio.AbstractEventLoop - bs: BackendSession - cs: ChatSession - _sending: bool - - def __init__(self, loop: asyncio.AbstractEventLoop, bs: BackendSession) -> None: - self.loop = loop - self.bs = bs - self._sending = False - - def on_open(self) -> None: - pass - - def on_participant_joined(self, cs_other: ChatSession, first_pop: bool, initial_join: bool) -> None: - pass - - def on_participant_left(self, cs_other: ChatSession, last_pop: bool) -> None: - pass - - def on_chat_invite_declined( - self, chat: Chat, invitee: User, *, invitee_id: Optional[str] = None, message: Optional[str] = None, circle: bool = False, - ) -> None: - pass - - def on_chat_updated(self) -> None: - pass - - def on_chat_roster_updated(self) -> None: - pass - - def on_participant_status_updated(self, cs_other: ChatSession, first_pop: bool, initial: bool, old_substatus: Substatus) -> None: - pass - - def on_message(self, message: MessageData) -> None: - if message.type not in (MessageType.Chat,MessageType.Nudge): - return - - if self._sending: - return - - if message.sender.email.endswith('@bot.log1p.gay'): - return - - me = self.cs.user - self._sending = True - - typing_message = MessageData(sender = me, type = MessageType.Typing) - self.cs.send_message_to_everyone(typing_message) - - if message.type is MessageType.Chat: - self.loop.create_task(self._send_delayed(random.uniform(0.5, 1), MessageData( - sender = me, type = MessageType.Chat, - text = "lol :p", - ))) - elif message.type is MessageType.Nudge: - self.loop.create_task(self._send_delayed(random.uniform(0.5, 1), MessageData( - sender = me, type = MessageType.Nudge, - ))) - - async def _send_delayed(self, delay: float, message: MessageData) -> None: - await asyncio.sleep(delay, loop = self.loop) - self.cs.send_message_to_everyone(message) - self._sending = False diff --git a/front/bot/__init__.py b/front/icq/__init__.py similarity index 100% rename from front/bot/__init__.py rename to front/icq/__init__.py diff --git a/front/icq/crypt.py b/front/icq/crypt.py new file mode 100644 index 0000000..e5fd172 --- /dev/null +++ b/front/icq/crypt.py @@ -0,0 +1,122 @@ +import random +import struct + +# the V5 scrambling table: V5 packets are encrypted with it, and V3/V4/V5 +# checkcodes point into it +V5_TABLE = bytes(( + 0x59, 0x60, 0x37, 0x6B, 0x65, 0x62, 0x46, 0x48, 0x53, 0x61, 0x4C, 0x59, 0x60, 0x57, 0x5B, 0x3D, + 0x5E, 0x34, 0x6D, 0x36, 0x50, 0x3F, 0x6F, 0x67, 0x53, 0x61, 0x4C, 0x59, 0x40, 0x47, 0x63, 0x39, + 0x50, 0x5F, 0x5F, 0x3F, 0x6F, 0x47, 0x43, 0x69, 0x48, 0x33, 0x31, 0x64, 0x35, 0x5A, 0x4A, 0x42, + 0x56, 0x40, 0x67, 0x53, 0x41, 0x07, 0x6C, 0x49, 0x58, 0x3B, 0x4D, 0x46, 0x68, 0x43, 0x69, 0x48, + 0x33, 0x31, 0x44, 0x65, 0x62, 0x46, 0x48, 0x53, 0x41, 0x07, 0x6C, 0x69, 0x48, 0x33, 0x51, 0x54, + 0x5D, 0x4E, 0x6C, 0x49, 0x38, 0x4B, 0x55, 0x4A, 0x62, 0x46, 0x48, 0x33, 0x51, 0x34, 0x6D, 0x36, + 0x50, 0x5F, 0x5F, 0x5F, 0x3F, 0x6F, 0x47, 0x63, 0x59, 0x40, 0x67, 0x33, 0x31, 0x64, 0x35, 0x5A, + 0x6A, 0x52, 0x6E, 0x3C, 0x51, 0x34, 0x6D, 0x36, 0x50, 0x5F, 0x5F, 0x3F, 0x4F, 0x37, 0x4B, 0x35, + 0x5A, 0x4A, 0x62, 0x66, 0x58, 0x3B, 0x4D, 0x66, 0x58, 0x5B, 0x5D, 0x4E, 0x6C, 0x49, 0x58, 0x3B, + 0x4D, 0x66, 0x58, 0x3B, 0x4D, 0x46, 0x48, 0x53, 0x61, 0x4C, 0x59, 0x40, 0x67, 0x33, 0x31, 0x64, + 0x55, 0x6A, 0x32, 0x3E, 0x44, 0x45, 0x52, 0x6E, 0x3C, 0x31, 0x64, 0x55, 0x6A, 0x52, 0x4E, 0x6C, + 0x69, 0x48, 0x53, 0x61, 0x4C, 0x39, 0x30, 0x6F, 0x47, 0x63, 0x59, 0x60, 0x57, 0x5B, 0x3D, 0x3E, + 0x64, 0x35, 0x3A, 0x3A, 0x5A, 0x6A, 0x52, 0x4E, 0x6C, 0x69, 0x48, 0x53, 0x61, 0x6C, 0x49, 0x58, + 0x3B, 0x4D, 0x46, 0x68, 0x63, 0x39, 0x50, 0x5F, 0x5F, 0x3F, 0x6F, 0x67, 0x53, 0x41, 0x25, 0x41, + 0x3C, 0x51, 0x54, 0x3D, 0x5E, 0x54, 0x5D, 0x4E, 0x4C, 0x39, 0x50, 0x5F, 0x5F, 0x5F, 0x3F, 0x6F, + 0x47, 0x43, 0x69, 0x48, 0x33, 0x51, 0x54, 0x5D, 0x6E, 0x3C, 0x31, 0x64, 0x35, 0x5A, 0x00, 0x00, +)) + +# the V4 table is the first 256 bytes of the tips text ICQ 98a ships with +V4_TABLE = ( + b'\n[1] You can modify the sounds ICQ makes. Just select "Sounds" from the "preferences/misc" in ICQ or from the ' + b'"Sounds" in the control panel. Credit: Eran\n[2] Can\'t remember what was said? Double-click on a user to get a ' + b'dialog of all messages sent incomin' +) + +assert len(V5_TABLE) == 256 and len(V4_TABLE) == 256 + +# a V5 client packet's checkcode sits at 0x14, a server packet's at 0x11 +V5_CLIENT_CHECKCODE_OFFSET = 0x14 +V5_SERVER_CHECKCODE_OFFSET = 0x11 +# a V4 client packet's checkcode sits at 0x10, after the header it stands in for +V4_CLIENT_CHECKCODE_OFFSET = 0x10 + + +def _u32(value: int) -> int: + return value & 0xFFFFFFFF + +def _descramble_v5_checkcode(check: int) -> int: + # the checkcode's bits are shuffled before it goes into the key + a1 = (check & 0x0001F000) >> 0x0C + a2 = (check & 0x07C007C0) >> 0x01 + a3 = _u32((check & 0x003E0001) << 0x0A) + a4 = (check & 0xF8000000) >> 0x10 + a5 = _u32((check & 0x0000083E) << 0x0F) + return _u32(a5 + a1 + a2 + a3 + a4) + +def decrypt_v5(packet: bytes) -> bytes: + # a V5 client packet is encrypted from 0x0A on with a key made from its length and checkcode; the checkcode itself + # (0x14..0x17) is left as it is + if len(packet) < 0x18: + return packet + data = bytearray(packet) + length = len(data) + check = struct.unpack_from('> 8) & 0xFF + if i != 0x12: + if i + 2 < length: + data[i + 2] ^= (k >> 16) & 0xFF + if i + 3 < length: + data[i + 3] ^= (k >> 24) & 0xFF + return bytes(data) + +def v5_checkcode(packet: bytes) -> int: + # bytes 8, 4, 2 and 6 of the packet, against a random byte of the packet's first 16 and a random table entry + b2, b4, b6, b8 = packet[2], packet[4], packet[6], packet[8] + number1 = (b8 << 24) | (b4 << 16) | (b2 << 8) | b6 + x4 = random.randrange(0x10) + x3 = packet[x4] + x2 = random.randrange(0xFF) + x1 = V5_TABLE[x2] + number2 = ((x4 << 24) | (x3 << 16) | (x2 << 8) | x1) ^ 0x00FF00FF + return _u32(number1 ^ number2) + +def add_v5_server_checkcode(packet: bytearray) -> None: + # server packets aren't encrypted, only stamped with a checkcode at 0x11 the client verifies + struct.pack_into(' bytes: + # V4 only encrypts the first quarter of a packet, a dword at a time with a key made from its length and checkcode; the + # checkcode dword (the fifth) is skipped, and the version (never really encrypted) is put back + if len(packet) < 0x14: + return packet + data = bytearray(packet) + length = len(data) + check = struct.unpack_from('= length: + break + k = _u32(key + V4_TABLE[pos & 0xFF]) + for j in range(4): + if pos + j < length: + data[pos + j] ^= (k >> (j * 8)) & 0xFF + data[0:2] = b'\x04\x00' + return bytes(data) + +def v3_header_checkcode(header: bytes) -> int: + # what a V4 client checks a server packet's V3 header against: bytes 8, 4, 2 and 6 of it, xored with an offset into the + # header and the inverse of the byte there, and an offset into the V4 table and the inverse of that entry (the offsets + # are the server's to pick; the first byte of seq1 and the first entry) + check_a = (header[8] << 24) | (header[4] << 16) | (header[2] << 8) | header[6] + packet_offset = 4 + table_offset = 0 + check_b = (packet_offset << 24) | ((~header[packet_offset] & 0xFF) << 16) | (table_offset << 8) | (~V4_TABLE[table_offset] & 0xFF) + return _u32(check_a ^ check_b) diff --git a/front/icq/ctrl.py b/front/icq/ctrl.py new file mode 100644 index 0000000..249e03b --- /dev/null +++ b/front/icq/ctrl.py @@ -0,0 +1,1075 @@ +import asyncio +import socket +import struct +import time + +from datetime import datetime +from typing import Any, TYPE_CHECKING + +import settings + +from core import error +from core.backend import BackendSession, ChatSession +from core.client import Client +from core.models import Contact, ContactList, LoginOption, MessageData, MessageType as ChatMessageType, OIM, Substatus, User +from util import icq +from util.misc import Logger, gen_uuid + +from front.oscar.proto.names import uin_of +from front.oscar.proto.userinfo import icq_status_for, pick_session, substatus_from_icq_status + +from . import directory, meta, wire +from .packets import ( + Command, LE, MAX_ABOUT, MAX_HOMEPAGE, MAX_NAME, MAX_NICK, MAX_PHONE, MessageType, Reader, Server, Version, uin_list, +) + +if TYPE_CHECKING: + from .entry import ListenerICQ + from .events import ChatEventHandler + from .wire import Header + +Address = tuple[str, int] + +# what the old (pre-META) packets say about authorization: 1 means it's required +OLD_AUTH_REQUIRED = 1 + +# the trailing words a V4 login reply carries (the third is the keep-alive interval) +V4_HELLO_WORDS = (0x0000, 0x0000, 0x0019, 0x0002, 0x0001, 0x00FA, 0x002D, 0x0005, 0x000A, 0x0005) + +# the V5 deps list reply is a bare V3 header with this in its checkcode field +V5_DEPS_LIST_CHECK = 0x8FFCACBF + +REGISTRATION_NOTES = 'New accounts are made on the website. Choose "existing user" to sign on with your UIN.' + + +def _ip_bytes(addr: Address) -> bytes: + try: + return socket.inet_aton(addr[0]) + except OSError: + return bytes(4) + +def downgrade_v2(status: int) -> int: + # V1/V2 clients only show online, away and the combined DND/occupied (0x11); the rest map to the nearest of those + base = status & 0xFF + flags = status & 0xFFFFFF00 + base = { 0x02: 0x11, 0x04: 0x01, 0x05: 0x01, 0x10: 0x11, 0x13: 0x11, 0x20: 0x00 }.get(base, base) + return flags | base + +def status_word(backend: Any, user: User, substatus: Substatus) -> int: + # the status dword ICQ shows for `user`: the one their ICQ client set while it still holds, else worked out + return icq_status_for(user, pick_session(backend, user), substatus) + + +class LoginRequest: + __slots__ = ('password', 'status', 'port', 'internal_ip', 'dc_type', 'dc_version', 'login_seq') + + password: str + status: int + port: int + internal_ip: int + dc_type: int + dc_version: int + login_seq: int + + def __init__(self) -> None: + self.password = '' + self.status = 0 + self.port = 0 + self.internal_ip = 0 + self.dc_type = 0 + self.dc_version = 0 + self.login_seq = 0 + +def parse_login(version: int, data: bytes) -> LoginRequest | None: + request = LoginRequest() + reader = Reader(data) + try: + if version == Version.V1: + # CMD_GET_DEPS doubles as V1's login: password, u32 status + request.password = icq.from_latin1(reader.raw_string()) + request.status = reader.u32() if reader.remaining() >= 4 else 0 + elif version == Version.V2: + # u32 TCP port, password, u32, u32 IP, u8, u16 status, u16 DC version, 12 bytes; the login's own sequence + # number (which the reply echoes) sits 17 bytes past the password + request.port = reader.u32() + request.password = icq.from_latin1(reader.raw_string()) + rest = reader.rest() + if len(rest) >= 11: + request.status = struct.unpack_from('= 19: + request.login_seq = struct.unpack_from('= 13: + reader.u32() + request.internal_ip = reader.u32() + request.dc_type = reader.u8() + request.status = reader.u32() + if version == Version.V5 and reader.remaining() >= 4: + request.dc_version = reader.u32() + except ValueError: + return None + return request + + +class LegacyCtrl: + # one signed on pre-OSCAR client, found again by the address its datagrams come from + __slots__ = ( + 'server', 'backend', 'logger', 'addr', 'version', 'uin', 'session_id', 'seq', 'bs', 'last_activity', 'closed', + 'contacts', 'visible', 'invisible', 'shown', 'offline_pending', 'chats', 'dc_info', + ) + + server: 'ListenerICQ' + backend: Any + logger: Logger + addr: Address + version: int + uin: int + session_id: int + seq: int + bs: BackendSession | None + last_activity: float + closed: bool + # the client's own contact list (sent at every sign-on), by UIN, with the account each one is + contacts: dict[int, str] + visible: set[int] + invisible: set[int] + # who the client was last told is online, and with what status dword + shown: dict[int, int] + # offline messages handed over, deleted once the client says it has them + offline_pending: list[str] + chats: dict[str, tuple[ChatSession, 'ChatEventHandler']] + # u32 TCP port, u32 LAN IP, u8 DC type, u16 DC version, from the login + dc_info: tuple[int, int, int, int] + + def __init__(self, server: 'ListenerICQ', addr: Address, version: int, uin: int, session_id: int) -> None: + self.server = server + self.backend = server.backend + self.logger = Logger('ICQ', self) + self.addr = addr + self.version = version + self.uin = uin + self.session_id = session_id + # server sequence numbers start from 0 + self.seq = 0 + self.bs = None + self.last_activity = time.monotonic() + self.closed = False + self.contacts = {} + self.visible = set() + self.invisible = set() + self.shown = {} + self.offline_pending = [] + self.chats = {} + self.dc_info = (0, 0, 0, 0) + + @property + def user(self) -> User: + assert self.bs is not None + return self.bs.user + + def next_seq(self) -> int: + seq = self.seq + self.seq = (self.seq + 1) & 0xFFFF + return seq + + def send(self, command: int, data: bytes = b'', *, seq1: int | None = None, seq2: int = 0) -> None: + # what the server sends unprompted takes the next server sequence number + if self.closed: + return + if seq1 is None: + seq1 = self.next_seq() + packet = wire.build(self.version, command, data, seq1 = seq1, seq2 = seq2, uin = self.uin, session_id = self.session_id) + self.server.send(packet, self.addr) + + def ack(self, header: 'Header', *, with_seq2: bool = False) -> None: + if self.version == Version.V5: + seq2 = header.seq2 if with_seq2 else 0 + elif self.version in (Version.V3, Version.V4): + seq2 = header.seq2 + else: + seq2 = 0 + self.send(Server.Ack, seq1 = header.seq1, seq2 = seq2) + + def is_old(self) -> bool: + return self.version in (Version.V1, Version.V2) + + # sign on + + def send_login_reply(self, header: 'Header', login: LoginRequest) -> None: + ip = _ip_bytes(self.addr) + if self.version == Version.V5: + # u16 keep-alive interval (low, high), u16 ping time, u16 timeout, u16 0x0A, u16 retries, the client's IP, u32 + # server ID; seq1 0, the login's seq2 + data = LE().u16(0x008C).u16(0x0000).u16(50).u16(60).u16(0x000A).u16(5).raw(ip).u32(0x80CDC19B).bytes() + self.send(Server.Hello, data, seq1 = 0, seq2 = header.seq2) + elif self.version == Version.V4: + # the client's IP, then ten words + body = LE().raw(ip) + for word in V4_HELLO_WORDS: + body.u16(word) + self.send(Server.Hello, body.bytes(), seq2 = header.seq2) + elif self.version == Version.V3: + # the client's IP, u32 0, u32 externals, u32 deps list version, u8 must change password, u8 can broadcast, + # u32 0xFA, u16 ping frequency, u16 packet timeout, u16 retry timeout, u16 retries + data = LE().raw(ip).u32(0).u32(0).u32(1).u8(0).u8(0).u32(0x000000FA).u16(50).u16(60).u16(10).u16(3).bytes() + self.send(Server.Hello, data, seq1 = 0, seq2 = header.seq2) + else: + # u32 UIN, the client's IP, the login's own sequence number, then the 23 bytes a Mirabilis server sent + body = LE().u32(self.uin).raw(ip).u16(login.login_seq) + body.raw(bytes.fromhex('01000500' '00000000' '8c000000' 'f0000a00' '0a0005000a0001')) + self.send(Server.Hello, body.bytes()) + + def signed_on(self, login: LoginRequest) -> None: + bs = self.bs + assert bs is not None + bs.front_data['icq0'] = True + bs.front_data['icq0_status'] = login.status + self.dc_info = (login.port, login.internal_ip, login.dc_type, login.dc_version) + bs.me_update({ 'substatus': substatus_from_icq_status(login.status) }) + # authorization requests and answers held while this account wasn't on ICQ + from front.oscar.foodgroups.feedbag import deliver_queued_auth_events + deliver_queued_auth_events(self) + + # packets from a signed on client + + def on_packet(self, header: 'Header', data: bytes) -> None: + self.last_activity = time.monotonic() + command = header.command + if command == Command.Ack: + return + handler = self._handler(command) + if handler is None: + # anything else is acknowledged and dropped, so the client stops resending it + self.logger.info('[Client] Unhandled command', hex(command), 'from V{}'.format(self.version)) + self.ack(header) + return + handler(header, data) + + def _handler(self, command: int) -> Any: + version = self.version + common = { + Command.KeepAlive: self._keepalive, + Command.KeepAlive2: self._keepalive, + Command.Logoff: self._logoff, + Command.ContactList: self._contact_list, + Command.UserAdd: self._user_add, + Command.SetStatus: self._set_status, + Command.ThruServer: self._message, + Command.Authorize: self._message, + Command.SysMsgReq: self._offline_request, + Command.SysMsgDoneAck: self._offline_done, + Command.VisibleList: self._visible_list, + Command.InvisibleList: self._invisible_list, + Command.SearchUin: self._search_uin, + Command.SearchUser: self._search_user, + Command.InfoReq: self._info, + Command.ExtInfoReq: self._ext_info, + } + if version == Version.V5: + common.update({ + Command.MetaUser: lambda header, data: meta.handle(self, header, data), + Command.ChangeVILists: self._change_vi_lists, + # searches a V5 client sends outside META_USER, with the old answers + 0x0514: self._direct_search_name, 0x0515: self._direct_search_name, + 0x051F: self._direct_search_uin, + 0x0528: self._direct_search_email, 0x0529: self._direct_search_email, + 0x0532: self._direct_search_white, 0x0533: self._direct_search_white, + }) + elif version in (Version.V3, Version.V4): + common.update({ + Command.UserGetInfo: self._info, + Command.SetBasicInfo: self._update_basic, + }) + if version == Version.V4: + common[Command.UpdateDetail] = self._update_detail + else: + common[Command.SetAuth] = self._set_auth_v3 + # V3 has no extended info request of its own + del common[Command.ExtInfoReq] + else: + common.update({ + Command.UpdateBasic: self._update_basic, + Command.SetBasicInfo: self._update_basic, + Command.UpdateDetail: self._update_detail, + }) + return common.get(command) + + def _keepalive(self, header: 'Header', data: bytes) -> None: + self.ack(header) + + def _logoff(self, header: 'Header', data: bytes) -> None: + # CMD_LOGOFF ends the session; nothing goes back + self.close() + + # presence + + def _contact_list(self, header: 'Header', data: bytes) -> None: + # u8 count and that many UINs; a long list comes in several, each adding to what's there + self.ack(header) + for uin in uin_list(data): + self._watch(uin) + if self.is_old(): + self.send(Server.UserListDone, LE().u32(self.uin).bytes()) + else: + self.send(Server.UserListDone, seq2 = header.seq2) + + def _watch(self, uin: int) -> User | None: + if uin == self.uin or self.bs is None: + return None + uuid = self.contacts.get(uin) or self.backend.util_get_uuid_from_uin(uin) + if uuid is None: + return None + user = self.backend._load_user_record(uuid) + if user is None: + return None + self.contacts[uin] = uuid + self.backend.util_watch(self.bs, uuid) + self.push_presence(user) + return user + + def push_presence(self, user: User) -> None: + # where `user` stands right now, as this account sees them + from core.backend import _watch_contact + detail = self.user.detail + ctc = detail.contacts.get(user.uuid) if detail is not None else None + if ctc is None or not ctc.lists & ContactList.FL: + ctc = _watch_contact(user, self.user) + else: + ctc.compute_visible_status(self.user) + self.show(user, ctc.status.substatus) + + def on_presence(self, ctc: Contact) -> None: + uin = uin_of(ctc.head) + if uin is None or uin not in self.contacts: + return + ctc.compute_visible_status(self.user) + self.show(ctc.head, ctc.status.substatus) + + def show(self, user: User, substatus: Substatus) -> None: + # a contact's arrival (SRV_USER_ONLINE), a change while on (SRV_USER_STATUS) or departure (SRV_USER_OFFLINE) + uin = uin_of(user) + if uin is None or self.closed: + return + online = not substatus.is_offlineish() and bool(self.backend.util_get_sessions_by_user(user)) + if not online: + if self.shown.pop(uin, None) is not None: + self.send(Server.UserOffline, LE().u32(uin).bytes()) + return + status = status_word(self.backend, user, substatus) + if self.is_old(): + status = downgrade_v2(status) + previous = self.shown.get(uin) + self.shown[uin] = status + if previous is None: + self.send(Server.UserOnline, self._user_online(user, uin, status)) + elif previous != status: + # u32 UIN, u32 status (u16 status and u16 extended status) + self.send(Server.UserStatus, LE().u32(uin).u32(status).bytes()) + + def _user_online(self, user: User, uin: int, status: int) -> bytes: + if self.version == Version.V5: + # u32 UIN, u32 IP, u32 TCP port, u32 LAN IP, u8 DC type, u16 status, u16 extended status, u32 DC version, u32 DC + # cookie, u32 web port, u32 client features, three u32 update times + ip, port, lan_ip, dc_type, dc_version = self._peer_dc(user) + body = LE().u32(uin).raw(ip).u32(port).u32(lan_ip).u8(dc_type).u16(status & 0xFFFF).u16(status >> 16) + return body.u32(dc_version).raw(bytes(24)).bytes() + if self.version in (Version.V3, Version.V4): + # u32 UIN, u32 IP, u32 TCP port, u32 LAN IP, u8 DC type, u16 status, u16 extended status, u16 DC version, u16 + return LE().u32(uin).u32(0).u32(0).u32(0).u8(0).u16(status & 0xFFFF).u16(status >> 16).u16(0).u16(0).bytes() + # u32 UIN, u32 IP, u16 TCP port, u32 LAN IP, u16 DC version (3), u8 (4), u16 status, then six bytes + return LE().u32(uin).u32(0).u16(0).u32(0).u16(0x0003).u8(0x04).u16(status).raw(bytes.fromhex('020000000000')).bytes() + + def _peer_dc(self, user: User) -> tuple[bytes, int, int, int, int]: + # a V5 peer's direct connection details go out only when the operator allows it (they give its IP address away) + if not getattr(settings, 'ICQ_DIRECT_CONNECTIONS', False): + return bytes(4), 0, 0, 0, 0 + for bs_other in self.backend.util_get_sessions_by_user(user): + other = getattr(bs_other.evt, 'ctrl', None) + if isinstance(other, LegacyCtrl) and other.version == Version.V5 and not other.closed: + port, lan_ip, dc_type, dc_version = other.dc_info + return _ip_bytes(other.addr), port, lan_ip, dc_type, dc_version + return bytes(4), 0, 0, 0, 0 + + def _set_status(self, header: 'Header', data: bytes) -> None: + # u32 status + self.ack(header) + if len(data) < 4 or self.bs is None: + return + status = struct.unpack_from(' None: + # who may see this account while it's invisible; kept for the session (the other frontends have no such list) + self.ack(header) + self.visible = set(uin_list(data)) + + def _invisible_list(self, header: 'Header', data: bytes) -> None: + self.ack(header) + self.invisible = set(uin_list(data)) + + def _change_vi_lists(self, header: 'Header', data: bytes) -> None: + # u8 action (1: add to visible, 2: remove from visible, 3: add to invisible, 4: remove from invisible), u32 UIN + self.ack(header) + if len(data) < 5: + return + action, uin = struct.unpack_from(' None: + # u32 UIN: one more contact, who hears they were added + self.ack(header) + if len(data) < 4: + return + user = self._watch(struct.unpack_from(' None: + # u32 UIN, u16 type, the text (fields of the structured types split by 0xFE) + self.ack(header) + reader = Reader(data) + try: + to = reader.u32() + msg_type = reader.u16() + text = icq.from_latin1(reader.raw_string()) + except ValueError: + return + target = directory.find(self.backend, to) + if target is None or self.bs is None or target is self.user: + return + kind = msg_type & 0xFF + from front.oscar.foodgroups.icbm import icq_message_text + if kind in (MessageType.AuthRequest, MessageType.AuthDeny, MessageType.AuthGrant, MessageType.Added): + from front.oscar.foodgroups.feedbag import auth_event_from_icq_message + auth_event_from_icq_message(self.backend, self.user, target, kind, text) + return + plain = icq_message_text(kind, text) + if plain is not None: + self._send_text(target, plain, msg_type, text) + return + # anything else (chat and file requests, plugins, auto-away requests) only another ICQ client can make sense of + relay_icq_message(self.backend, self.user, target, msg_type, text) + + def _send_text(self, target: User, plain: str, msg_type: int, text: str) -> None: + # a message anyone can read goes through the chat machinery like every frontend's, carrying its ICQ form along for + # ICQ clients on the other end + md = MessageData(sender = self.user, type = ChatMessageType.Chat, text = plain) + md.front_cache['icbm_icq'] = (msg_type, 0x00, text) + md.front_cache['icq0_message'] = (msg_type, text) + try: + cs, evt = self._get_private_chat_with(target) + except (error.ContactNotOnline, error.ContactNotOnContactList): + # the server keeps messages for whoever isn't on, which is what the client counts on + self._store_offline(target, plain) + return + except Exception as ex: + self.logger.info('[Client] Could not open a chat:', str(ex)) + return + evt.send_when_joined(target.uuid, md) + + def _store_offline(self, target: User, plain: str) -> None: + bs = self.bs + if bs is None: + return + detail = self.backend._load_detail(target) + ctc_self = detail.contacts.get(self.user.uuid) if detail is not None else None + if ctc_self is not None and ctc_self.lists & ContactList.BL: + return + self.backend.user_service.save_oim(bs, target.uuid, gen_uuid(), self.addr[0], plain, True, from_friendly = self.user.status.name) + + def _get_private_chat_with(self, other: User) -> tuple[ChatSession, 'ChatEventHandler']: + from .events import ChatEventHandler + bs = self.bs + assert bs is not None + user = bs.user + detail = user.detail + ctc = detail.contacts.get(other.uuid) if detail is not None else None + if ctc is not None and ctc.lists & ContactList.BL: + raise error.ContactNotOnContactList() + # a chat whose other side has gone can't carry anything any more + existing = self.chats.get(other.uuid) + if existing is not None and existing[0].closed: + del self.chats[other.uuid] + existing = None + if existing is not None: + if other.status.is_offlineish(): + raise error.ContactNotOnline() + return existing + other_detail = self.backend._load_detail(other) + if other_detail is None: + raise error.ContactNotOnline() + ctc_self = other_detail.contacts.get(user.uuid) + if ctc_self is not None and ctc_self.lists & ContactList.BL: + raise error.ContactNotOnline() + chat = self.backend.chat_create() + chat.front_data['icq0'] = True + evt = ChatEventHandler(self) + cs = chat.join('icq0', bs, evt) + try: + cs.invite(other) + except error.ClientError: + cs.close() + raise + self.chats[other.uuid] = (cs, evt) + return cs, evt + + def join_chat(self, chat: Any, inviter: User) -> None: + # someone started a conversation; it replaces whatever older one there was with them + from .events import ChatEventHandler + if self.bs is None: + return + previous = self.chats.pop(inviter.uuid, None) + if previous is not None and previous[0].chat is not chat: + previous[0].close() + evt = ChatEventHandler(self) + cs = chat.join('icq0', self.bs, evt) + chat.send_participant_joined(cs) + self.chats[inviter.uuid] = (cs, evt) + + def deliver_chat_message(self, data: MessageData) -> None: + # a message reaches an ICQ client from a UIN, as the type it was sent as when that's known + sender = data.sender + uin = uin_of(sender) + if uin is None: + return + sent = data.front_cache.get('icq0_message') + if sent is None and data.front_cache.get('icbm_icq') is not None: + msg_type, _, text = data.front_cache['icbm_icq'] + sent = (msg_type, text) + if sent is None: + sent = (MessageType.Text, data.text or '') + msg_type, text = sent + if msg_type & 0xFF == MessageType.Text: + text = text.replace('\r\n', '\n').replace('\n', '\r\n') + self.deliver_message(uin, msg_type, text) + + def deliver_message(self, from_uin: int, msg_type: int, text: str) -> None: + # SRV_SYS_MSG_ONLINE: u32 UIN, u16 type (just the low byte for V3/V4), the text + if self.version in (Version.V3, Version.V4): + msg_type &= 0x00FF + self.send(Server.SysMsgOnline, LE().u32(from_uin).u16(msg_type).string(text).bytes()) + + def on_auth_event(self, event: str, sender: User, text: str) -> None: + # an authorization request or answer, or "you were added", as the message types ICQ has always had for them + uin = uin_of(sender) + if uin is None: + return + info = directory.profile(sender, self.user) + fields = [info['nick'], info['first'], info['last'], info['email']] + if event == 'request': + from front.oscar.foodgroups.feedbag import _legacy_auth_request_text + self.deliver_message(uin, MessageType.AuthRequest, _legacy_auth_request_text(sender, self.user, text)) + elif event in ('granted', 'preauth'): + self.deliver_message(uin, MessageType.AuthGrant, '\xfe'.join(fields + [''])) + if uin in self.contacts: + self.push_presence(sender) + elif event == 'denied': + self.deliver_message(uin, MessageType.AuthDeny, '\xfe'.join(fields + [text])) + elif event == 'added': + self.deliver_message(uin, MessageType.Added, '\xfe'.join(fields + ['0'])) + + # offline messages + + def _offline_request(self, header: 'Header', data: bytes) -> None: + self.ack(header) + self.backend.loop.create_task(self._send_offline_messages(header.seq2)) + + async def _send_offline_messages(self, seq2: int) -> None: + bs = self.bs + if bs is None: + return + loop = self.backend.loop + user_service = self.backend.user_service + oims = await loop.run_in_executor(None, user_service.get_oim_batch, bs.user) + if self.closed: + return + for oim in oims: + sender = _oim_sender(self.backend, oim) + uin = uin_of(sender) if sender is not None else None + if uin is None: + # an ICQ client can only show a message from a UIN; the rest wait for another client + continue + self._send_offline_message(uin, oim) + self.offline_pending.append(oim.uuid) + # SRV_SYS_MSG_DONE: V1/V2 carry the UIN, the rest answer the request's seq2 + if self.is_old(): + self.send(Server.SysMsgDone, LE().u32(self.uin).bytes()) + else: + self.send(Server.SysMsgDone, seq2 = seq2) + + def _send_offline_message(self, uin: int, oim: OIM) -> None: + # SRV_SYS_MSG_OFFLINE: u32 UIN, u16 year, u8 month, u8 day, u8 hour, u8 minute, u16 type, the text + sent = oim.sent if isinstance(oim.sent, datetime) else datetime.utcnow() + text = (oim.message or '').replace('\r\n', '\n').replace('\n', '\r\n') + body = LE().u32(uin).u16(sent.year).u8(sent.month).u8(sent.day).u8(sent.hour).u8(sent.minute) + self.send(Server.SysMsgOffline, body.u16(MessageType.Text).string(text).bytes()) + + def _offline_done(self, header: 'Header', data: bytes) -> None: + # CMD_SYS_MSG_DONE_ACK: the client has them, so they go + self.ack(header) + delivered, self.offline_pending = self.offline_pending, [] + if delivered and self.bs is not None: + self.backend.loop.create_task(_delete_oims(self.backend, self.bs.user.uuid, delivered)) + + def deliver_oim_now(self, oim: OIM) -> None: + # an offline message stored while this client was on (it signed on invisible, say) goes straight to it + sender = _oim_sender(self.backend, oim) + uin = uin_of(sender) if sender is not None else None + if uin is None or self.bs is None: + return + self.deliver_message(uin, MessageType.Text, (oim.message or '').replace('\r\n', '\n').replace('\n', '\r\n')) + self.backend.loop.create_task(_delete_oims(self.backend, self.bs.user.uuid, [oim.uuid])) + + # white pages, the old way + + def _search_uin(self, header: 'Header', data: bytes) -> None: + # V1/V2: u16 search id, u32 UIN; later versions just the UIN + self.ack(header) + reader = Reader(data) + try: + search_id = reader.u16() if self.is_old() else 0 + uin = reader.u32() + except ValueError: + self._search_done(header, 0) + return + user = directory.find(self.backend, uin) + if user is not None: + self._search_found(header, search_id, user) + self._search_done(header, search_id) + + def _search_user(self, header: 'Header', data: bytes) -> None: + # V1/V2: u16 search id, nick, first, last, e-mail; the later versions' layout of it isn't known, so they're told + # nothing was found + self.ack(header) + if not self.is_old(): + self._search_done(header, 0) + return + reader = Reader(data) + try: + search_id = reader.u16() + nick, first, last, email = reader.string(), reader.string(), reader.string(), reader.string() + except ValueError: + self._search_done(header, 0) + return + for user in directory.search(self.backend, email = email, first = first, last = last, nick = nick): + self._search_found(header, search_id, user) + self._search_done(header, search_id) + + def _direct_search_name(self, header: 'Header', data: bytes) -> None: + self.ack(header) + reader = Reader(data) + try: + nick, first, last = reader.string(), reader.string(), reader.string() + except ValueError: + self._search_done(header, 0) + return + for user in directory.search(self.backend, nick = nick, first = first, last = last): + self._search_found(header, 0, user) + self._search_done(header, 0) + + def _direct_search_uin(self, header: 'Header', data: bytes) -> None: + self.ack(header) + user = directory.find(self.backend, struct.unpack_from('= 4 else None + if user is not None: + self._search_found(header, 0, user) + self._search_done(header, 0) + + def _direct_search_email(self, header: 'Header', data: bytes) -> None: + self.ack(header) + try: + email = Reader(data).string() + except ValueError: + email = '' + for user in directory.search(self.backend, email = email): + self._search_found(header, 0, user) + self._search_done(header, 0) + + def _direct_search_white(self, header: 'Header', data: bytes) -> None: + self.ack(header) + reader = Reader(data) + try: + first, last, nick, email = reader.string(), reader.string(), reader.string(), reader.string() + except ValueError: + self._search_done(header, 0) + return + for user in directory.search(self.backend, email = email, first = first, last = last, nick = nick): + self._search_found(header, 0, user) + self._search_done(header, 0) + + def _old_record(self, info: dict[str, Any]) -> LE: + # u32 UIN, nick, first, last, e-mail, u8 auth (1: required), trimmed to what the old clients' buffers take + record = LE().u32(info['uin']).string(info['nick'], MAX_NICK).string(info['first'], MAX_NAME).string(info['last'], MAX_NAME) + return record.string(info['email'], MAX_NAME).u8(OLD_AUTH_REQUIRED if info['auth_required'] else 0) + + def _search_found(self, header: 'Header', search_id: int, user: User) -> None: + # SRV_SEARCH_FOUND: (V1/V2) u16 search id, the record, (V5) a trailing zero byte + record = self._old_record(directory.profile(user, self.user)) + if self.is_old(): + self.send(Server.SearchFound, LE().u16(search_id).raw(record.bytes()).bytes()) + elif self.version == Version.V5: + self.send(Server.SearchFound, record.u8(0).bytes(), seq2 = header.seq2) + else: + self.send(Server.SearchFound, record.bytes(), seq2 = header.seq2) + + def _search_done(self, header: 'Header', search_id: int) -> None: + # SRV_SEARCH_DONE: (V1/V2) u16 search id, u8 more (never: all hits went out) + if self.is_old(): + self.send(Server.SearchDone, LE().u16(search_id).u8(0).bytes()) + else: + self.send(Server.SearchDone, LE().u8(0).bytes(), seq2 = header.seq2) + + def _info(self, header: 'Header', data: bytes) -> None: + # CMD_INFO_REQ (and V3/V4's CMD_USER_GET_INFO): V1/V2 send u16 request id, u32 UIN; the rest just the UIN + self.ack(header) + reader = Reader(data) + try: + request_id = reader.u16() if self.is_old() else 0 + uin = reader.u32() + except ValueError: + return + user = directory.find(self.backend, uin) + if user is None and self.version == Version.V5: + self.send(Server.InvalidUin, LE().u32(uin).bytes()) + return + # the older clients get a bare entry for a UIN nobody has + info = directory.profile(user, self.user) if user is not None else directory.unknown_profile(uin) + names = LE().string(info['nick'], MAX_NICK).string(info['first'], MAX_NAME).string(info['last'], MAX_NAME).string(info['email'], MAX_NAME) + auth = OLD_AUTH_REQUIRED if info['auth_required'] else 0 + if self.is_old(): + # SRV_INFO_REPLY: u16 request id, u32 UIN, nick, first, last, e-mail, u8 auth, two zero words + body = LE().u16(request_id).u32(uin).raw(names.bytes()).u8(auth).u16(0).u16(0) + self.send(Server.InfoReply, body.bytes()) + elif self.version == Version.V5: + # u32 UIN, nick, first, last, e-mail, u8 auth + self.send(Server.InfoReply, LE().u32(uin).raw(names.bytes()).u8(auth).bytes()) + else: + # V3/V4: u32 UIN, nick, first, last, e-mail, u8 status, u8 auth + self.send(Server.InfoReply, LE().u32(uin).raw(names.bytes()).u8(0).u8(auth).bytes(), seq2 = header.seq2) + + def _ext_info(self, header: 'Header', data: bytes) -> None: + # CMD_EXT_INFO_REQ: the same request as CMD_INFO_REQ + self.ack(header) + reader = Reader(data) + try: + request_id = reader.u16() if self.is_old() else 0 + uin = reader.u32() + except ValueError: + return + user = directory.find(self.backend, uin) + if user is None and self.version == Version.V5: + self.send(Server.InvalidUin, LE().u32(uin).bytes()) + return + info = directory.profile(user, self.user) if user is not None else directory.unknown_profile(uin) + body = LE() + if self.is_old(): + # u16 request id, u32 UIN, city, u16 country, u8 country status, state, u16 age, u8 gender, phone, homepage, about + body.u16(request_id).u32(uin).string(info['city'], MAX_NAME).u16(info['country']).u8(0) + else: + # u32 UIN, city, u16 country, u8 time zone, state, u16 age, u8 gender, phone, homepage, about, u32 ZIP + body.u32(uin).string(info['city'], MAX_NAME).u16(info['country']).u8(info['gmt']) + body.string(info['state'], MAX_NAME).u16(info['age']).u8(info['gender']).string(info['phone'], MAX_PHONE) + body.string(info['homepage'], MAX_HOMEPAGE).string(info['notes'], MAX_ABOUT) + if self.is_old(): + self.send(Server.ExtInfoReply, body.bytes()) + elif self.version == Version.V5: + self.send(Server.ExtInfoReply, body.u32(info['zip_number']).bytes()) + else: + self.send(Server.ExtInfoReply, body.u32(info['zip_number']).bytes(), seq2 = header.seq2) + + # profile changes, the old way + + def set_nickname(self, nick: str) -> None: + # the ICQ nickname is what other people see this account as, which elsewhere is its friendly name + if nick and self.bs is not None and nick != self.user.status.name: + self.bs.me_update({ 'name': nick }) + + def _update_basic(self, header: 'Header', data: bytes) -> None: + # V1/V2: u16 update id, nick, first, last, e-mail, u8 auth (1: required); V4 the same without the id; V3 without + # the auth byte either + self.ack(header) + reader = Reader(data) + try: + update_id = reader.u16() if self.is_old() else 0 + nick, first, last, email = reader.string(), reader.string(), reader.string(), reader.string() + # (V1/V2 only take the auth byte from CMD_UPDATE_BASIC) + takes_auth = self.version == Version.V4 or (self.is_old() and header.command == Command.UpdateBasic) + auth = reader.u8() if reader.remaining() and takes_auth else None + except ValueError: + if self.is_old(): + self.send(Server.UpdateBasicFail, LE().u16(0).bytes()) + return + if self.bs is None: + return + self.set_nickname(nick) + icq.set_basic(self.user, { 'nick': nick, 'first': first, 'last': last, 'email': email }) + if auth is not None: + icq.set_permissions(self.user, auth_required = auth == OLD_AUTH_REQUIRED) + icq.save(self.backend, self.user) + if self.is_old(): + reply = Server.UpdatedBasic if header.command == Command.UpdateBasic else Server.UpdatedBasicV4 + self.send(reply, LE().u16(update_id).bytes()) + else: + self.send(Server.UpdatedBasicV4, seq2 = header.seq2) + + def _update_detail(self, header: 'Header', data: bytes) -> None: + # (V1/V2: u16 update id), city, u16 country, u8 country status or time zone, state, u16 age (worked out from the + # birth date instead), u8 gender, phone, homepage, about + self.ack(header) + reader = Reader(data) + try: + update_id = reader.u16() if self.is_old() else 0 + city = reader.string() + country = reader.u16() + zone = reader.u8() + state = reader.string() + reader.u16() + gender = reader.u8() + phone, homepage, about = reader.string(), reader.string(), reader.string() + except ValueError: + if self.is_old(): + self.send(Server.UpdateDetailFail, LE().u16(0).bytes()) + return + if self.bs is None: + return + basic: dict[str, Any] = { 'city': city, 'country': country, 'state': state, 'phone': phone } + if not self.is_old(): + basic['gmt'] = zone + icq.set_basic(self.user, basic) + icq.set_more(self.user, { 'gender': gender, 'homepage': homepage }) + if about: + icq.set_notes(self.user, about) + icq.save(self.backend, self.user) + if self.is_old(): + self.send(Server.UpdatedDetail, LE().u16(update_id).bytes()) + else: + self.send(Server.UpdatedDetail, seq2 = header.seq2) + + def _set_auth_v3(self, header: 'Header', data: bytes) -> None: + # u8 authorization mode (anything but 0: required), answered with 0x01F4 + self.ack(header) + if not data or self.bs is None: + return + icq.set_permissions(self.user, auth_required = data[0] != 0) + icq.save(self.backend, self.user) + self.send(0x01F4, seq2 = header.seq2) + + # the end + + def force_offline(self) -> None: + # signed on somewhere else: SRV_SET_OFFLINE tells the client it's off, without the reconnect SRV_NOT_CONNECTED makes + self.send(Server.SetOffline) + self.close() + + def close(self) -> None: + if self.closed: + return + self.closed = True + self.server.remove(self) + for cs, _ in list(self.chats.values()): + cs.close() + self.chats.clear() + bs = self.bs + if bs is not None and not bs.closed: + bs.close() + + +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 + +async def _delete_oims(backend: Any, recipient_uuid: str, uuids: list[str]) -> None: + # deleting is plain file work, done off the event loop + loop = backend.loop + for uuid in uuids: + await loop.run_in_executor(None, backend.user_service.delete_oim, recipient_uuid, uuid) + +def legacy_sessions(backend: Any, user: User) -> list[LegacyCtrl]: + # the pre-OSCAR clients `user` is signed on with + ctrls = [] + for bs in backend.util_get_sessions_by_user(user): + ctrl = getattr(bs.evt, 'ctrl', None) + if isinstance(ctrl, LegacyCtrl) and not ctrl.closed: + ctrls.append(ctrl) + return ctrls + +def relay_icq_message(backend: Any, sender: User, target: User, msg_type: int, text: str) -> None: + # a message only ICQ clients understand (chat/file requests, plugins...) goes to `target`'s ICQ clients as it is: a + # pre-OSCAR client gets SRV_SYS_MSG_ONLINE, an OSCAR one a channel 4 ICBM + uin = uin_of(sender) + if uin is None: + return + for ctrl in legacy_sessions(backend, target): + ctrl.deliver_message(uin, msg_type, text) + from front.oscar.foodgroups.icbm import ICBMChannel, ICBMTag, build_icq_message, gen_cookie, relay_icbm + from front.oscar.proto import names + from front.oscar.proto.delivery import oscar_sessions + from front.oscar.proto.tlv import TLV, marshal_tlvs + sessions = [bs for bs in oscar_sessions(backend, target) if names.is_icq_session(bs)] + if sessions: + tlvs = marshal_tlvs([TLV(ICBMTag.Data, build_icq_message(uin, msg_type, 0x00, text))]) + relay_icbm(backend, sender, target, gen_cookie(), ICBMChannel.ICQ, tlvs, sessions = sessions) + + +# before there's a session: the registration wizard's questions, the pre-login password check, the login itself + +def prelogin(server: 'ListenerICQ', header: 'Header', data: bytes, addr: Address) -> None: + version = header.version + command = header.command + if command == Command.Ack: + return + if command == Command.Login or (version == Version.V1 and command == Command.GetDeps): + login(server, header, data, addr) + return + if command == Command.GetDeps: + _check_password(server, header, data, addr) + return + if command == Command.FirstLogin: + if version == Version.V5: + # the reply is an ACK carrying u8 0x0A, the u32 the client sent, u16 1 + session_id2 = struct.unpack_from('= 4 else 0 + _send_to(server, addr, header, Server.Ack, LE().u8(0x0A).u32(session_id2).u16(0x0001).bytes(), seq1 = header.seq1, seq2 = header.seq2) + else: + _prelogin_ack(server, header, addr) + if version == Version.V4: + _send_register_info(server, header, addr) + return + if command == Command.RegRequestInfo and version == Version.V4: + _prelogin_ack(server, header, addr) + _send_register_info(server, header, addr) + return + if command in (Command.RegNewUser, Command.RegNewUserInfo): + # accounts are only made on the website + _prelogin_ack(server, header, addr) + return + # anything else from someone who isn't signed on: SRV_NOT_CONNECTED, so the client signs on again + if version == Version.V5: + _send_to(server, addr, header, Server.NotConnected, seq1 = header.seq1, seq2 = header.seq2) + elif version in (Version.V3, Version.V4): + _send_to(server, addr, header, Server.NotConnected, seq1 = 0, seq2 = header.seq2) + else: + _send_to(server, addr, header, Server.NotConnected, seq1 = header.seq1) + +def _send_to( + server: 'ListenerICQ', addr: Address, header: 'Header', command: int, data: bytes = b'', *, + seq1: int = 0, seq2: int = 0, version: int | None = None, +) -> None: + packet = wire.build( + version if version is not None else header.version, command, data, seq1 = seq1, seq2 = seq2, uin = header.uin, + session_id = header.session_id, + ) + server.send(packet, addr) + +def _prelogin_ack(server: 'ListenerICQ', header: 'Header', addr: Address) -> None: + if header.version in (Version.V1, Version.V2): + _send_to(server, addr, header, Server.Ack, seq1 = header.seq1) + else: + _send_to(server, addr, header, Server.Ack, seq1 = header.seq1, seq2 = header.seq2) + +def _send_wrong_password(server: 'ListenerICQ', header: 'Header', addr: Address) -> None: + if header.version == Version.V5 or header.version == Version.V3: + _send_to(server, addr, header, Server.WrongPassword, seq1 = 0, seq2 = header.seq2) + elif header.version == Version.V4: + _send_to(server, addr, header, Server.WrongPassword, seq1 = header.seq1, seq2 = header.seq2) + else: + _send_to(server, addr, header, Server.WrongPassword, seq1 = header.seq1) + +def _send_register_info(server: 'ListenerICQ', header: 'Header', addr: Address) -> None: + # SRV_REGISTER_INFO (the registration wizard's admin notes): u16 length and the notes with their NUL, u8 registration + # enabled (not here), u16 2, u16 0x2A + notes = icq.latin1(REGISTRATION_NOTES) + b'\x00' + data = LE().u16(len(notes)).raw(notes).u8(0x00).u16(0x0002).u16(0x002A).bytes() + _send_to(server, addr, header, 0x037A, data, seq1 = 0, seq2 = header.seq2) + +def _check_password(server: 'ListenerICQ', header: 'Header', data: bytes, addr: Address) -> None: + # CMD_GET_DEPS: the password check the registration wizard (and older clients) make before signing on, answered with + # the (empty) departments list + version = header.version + reader = Reader(data) + try: + if version == Version.V2: + uin = header.uin + else: + uin = reader.u32() + password = icq.from_latin1(reader.raw_string()) + except ValueError: + _send_wrong_password(server, header, addr) + return + if uin <= 0 or server.backend.user_service.login_with_uin(uin, password) is None: + _send_wrong_password(server, header, addr) + return + if version == Version.V5: + _prelogin_ack(server, header, addr) + server.send(struct.pack(' None: + # CMD_LOGIN: acknowledged straight away (V3-V5), then answered with SRV_HELLO or SRV_WRONG_PASSWORD + from .events import BackendEventHandler + version = header.version + if version not in (Version.V1, Version.V2): + _prelogin_ack(server, header, addr) + request = parse_login(version, data) + if request is not None and version == Version.V1: + # V1's reply echoes the login packet's own sequence number + request.login_seq = header.seq1 + uuid = None + if request is not None and header.uin > 0: + uuid = server.backend.user_service.login_with_uin(header.uin, request.password) + if request is None or uuid is None: + _send_wrong_password(server, header, addr) + return + # a client signing on again from where it was (after a crash, say) replaces its own earlier session quietly; one + # somewhere else is told it's off, like sessions on the other frontends are booted + existing = server.by_uin.get(header.uin) + if existing is not None: + if existing.addr == addr: + existing.close() + else: + existing.force_offline() + ctrl = LegacyCtrl(server, addr, version, header.uin, header.session_id) + if server.take_preauth(addr) and version == Version.V4: + ctrl.seq = 1 + evt = BackendEventHandler(ctrl) + bs = server.backend.login(uuid, Client('icq', 'V{}'.format(version), 'direct'), evt, option = LoginOption.BootOthers) + if bs is None: + _send_wrong_password(server, header, addr) + return + ctrl.bs = bs + server.add(ctrl) + if version in (Version.V1, Version.V2): + ctrl.send(Server.Ack, seq1 = header.seq1) + ctrl.send_login_reply(header, request) + ctrl.signed_on(request) diff --git a/front/icq/directory.py b/front/icq/directory.py new file mode 100644 index 0000000..f9996bc --- /dev/null +++ b/front/icq/directory.py @@ -0,0 +1,98 @@ +from typing import Any, TYPE_CHECKING + +from core.models import User +from util import icq + +from front.oscar.proto.names import uin_of + +if TYPE_CHECKING: + from core.backend import Backend + +# a search hands back at most this many people +MAX_RESULTS = 20 + + +def find(backend: 'Backend', uin: int) -> User | None: + uuid = backend.util_get_uuid_from_uin(uin) + return backend._load_user_record(uuid) if uuid is not None else None + +def listed(user: User, viewer: User | None) -> bool: + # the white pages only show someone who listed themselves in the member directory (or themselves, to themselves); the + # same rule the OSCAR ICQ frontend goes by + return user is viewer or bool(getattr(user, 'show_in_dir', False)) + +def _zip_number(text: str) -> int: + # the old info packets carry the ZIP code as a number + digits = ''.join(ch for ch in text if ch.isdigit())[:9] + return int(digits) if digits else 0 + +def profile(user: User, viewer: User | None) -> dict[str, Any]: + # everything the pre-OSCAR packets can show about `user`, as `viewer` may see it + info = icq.basic_info(user) + more = icq.more_info(user) + work = icq.work_info(user) + perms = icq.permissions(user) + show = listed(user, viewer) + uin = uin_of(user) or 0 + + def shown(value: Any, blank: Any = '') -> Any: + return value if show else blank + + affiliations = icq.affiliations(user) + return { + 'uin': uin, + 'nick': info['nick'] or str(uin), + 'first': shown(info['first']), + 'last': shown(info['last']), + # an e-mail address only ever goes out when its owner published it + 'email': info['email'] if info['publish_email'] or user is viewer else '', + 'publish_email': info['publish_email'], + 'city': shown(info['city']), + 'state': shown(info['state']), + 'phone': shown(info['phone']), + 'fax': shown(info['fax']), + 'address': shown(info['address']), + 'cell': shown(info['cell']), + 'zip': shown(info['zip']), + 'zip_number': shown(_zip_number(info['zip']), 0), + 'country': shown(info['country'], 0), + 'gmt': info['gmt'], + 'age': shown(icq.age(user), 0), + 'gender': shown(more['gender'], 0), + 'homepage': shown(more['homepage']), + 'birth_year': shown(more['birth_year'], 0), + 'birth_month': shown(more['birth_month'], 0), + 'birth_day': shown(more['birth_day'], 0), + 'lang1': more['lang1'], + 'lang2': more['lang2'], + 'lang3': more['lang3'], + 'notes': shown(icq.notes(user)), + 'work': { key: (value if show else (0 if isinstance(value, int) else '')) for key, value in work.items() }, + 'work_zip_number': shown(_zip_number(work['zip']), 0), + 'interests': icq.interests(user) if show else [], + 'past_affiliations': affiliations['past'] if show else [], + 'affiliations': affiliations['current'] if show else [], + 'auth_required': perms['auth_required'], + 'web_aware': perms['web_aware'], + } + +def unknown_profile(uin: int) -> dict[str, Any]: + # what the old info replies say about a UIN nobody has: its number for a nick, and nothing else + return { + 'uin': uin, 'nick': str(uin), 'first': '', 'last': '', 'email': '', 'city': '', 'state': '', 'phone': '', + 'homepage': '', 'notes': '', 'country': 0, 'gmt': 0, 'age': 0, 'gender': 0, 'zip_number': 0, 'auth_required': False, + } + +def search( + backend: 'Backend', *, email: str = '', first: str = '', last: str = '', nick: str = '', +) -> list[User]: + # a directory search: only people who listed themselves, and only those an ICQ client can name (by UIN) + criteria = { key: value for key, value in (('email', email), ('first_name', first), ('last_name', last), ('nickname', nick)) if value } + if not criteria: + return [] + users = [] + for uuid in backend.user_service.search_uuids(**criteria): + user = backend._load_user_record(uuid) + if user is not None and uin_of(user) is not None: + users.append(user) + return users[:MAX_RESULTS] diff --git a/front/icq/entry.py b/front/icq/entry.py new file mode 100644 index 0000000..a67e5f1 --- /dev/null +++ b/front/icq/entry.py @@ -0,0 +1,139 @@ +import asyncio +import time + +import settings + +from core.backend import Backend +from util.misc import DatagramRunner, Logger + +from . import wire +from .ctrl import LegacyCtrl, prelogin +from .packets import Command, Version + +Address = tuple[str, int] + +# a client that hasn't been heard from in this long is gone (it pings every minute or so) +SESSION_TIMEOUT = 120 +REAP_INTERVAL = 30 +# how long a passed password check (CMD_GET_DEPS) waits for the login that follows it +PREAUTH_LIFETIME = 60 + +# what a client sends before it has a session, answered the same whether or not it had one +PRELOGIN_COMMANDS = frozenset({ + Command.Login, Command.GetDeps, Command.FirstLogin, Command.RegRequestInfo, Command.RegNewUser, Command.RegNewUserInfo, +}) + + +def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None: + # the pre-OSCAR ICQ protocols (V1-V5, ICQ 1.x to ICQ 2000a) are all UDP, on Mirabilis' port 4000 + port = getattr(settings, 'ICQ_LEGACY_PORT', 4000) + backend.add_runner(DatagramRunner('0.0.0.0', port, ListenerICQ, args = ['ICQ', backend], service = 'ICQ')) + + +class ListenerICQ(asyncio.DatagramProtocol): + # one endpoint for every client: each datagram finds its session by the address it came from + logger: Logger + backend: Backend + transport: asyncio.DatagramTransport | None + by_addr: dict[Address, LegacyCtrl] + by_uin: dict[int, LegacyCtrl] + preauth: dict[Address, float] + _reaper: asyncio.Task | None + + def __init__(self, logger_prefix: str, backend: Backend) -> None: + super().__init__() + self.logger = Logger(logger_prefix, self) + self.backend = backend + self.transport = None + self.by_addr = {} + self.by_uin = {} + self.preauth = {} + self._reaper = None + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + assert isinstance(transport, asyncio.DatagramTransport) + self.transport = transport + self._reaper = self.backend.loop.create_task(self._reap()) + + def connection_lost(self, exc: Exception | None) -> None: + if self._reaper is not None: + self._reaper.cancel() + self._reaper = None + for ctrl in list(self.by_uin.values()): + ctrl.close() + self.transport = None + + def error_received(self, exc: Exception) -> None: + # an ICMP port unreachable from a client that went away; its session times out by itself + self.logger.info('UDP error:', str(exc)) + + def send(self, packet: bytes, addr: Address) -> None: + if self.transport is not None: + self.transport.sendto(packet, addr) + + def datagram_received(self, packet: bytes, addr: Address) -> None: + if self.backend.maintenance_mode: + return + try: + parsed = wire.parse(packet) + if parsed is None: + self.logger.info('Dropped a datagram that is no ICQ packet from', addr[0]) + return + header, data = parsed + self.logger.debug('[Client]', header, 'from', addr) + ctrl = self._find(header, addr) + if ctrl is None or header.command in PRELOGIN_COMMANDS: + # (a login or the steps before it from an address that already has a session: the client started over) + prelogin(self, header, data, addr) + else: + ctrl.on_packet(header, data) + except Exception as ex: + self.logger.error(ex) + + def _find(self, header: wire.Header, addr: Address) -> LegacyCtrl | None: + ctrl = self.by_addr.get(addr) + if ctrl is not None: + if ctrl.uin != header.uin and header.uin: + return None + return ctrl + # a client behind NAT can turn up from a new port: the same UIN from the same host (and for V5 the same session) + # is the same session + ctrl = self.by_uin.get(header.uin) if header.uin else None + if ctrl is None or ctrl.addr[0] != addr[0] or ctrl.version != header.version: + return None + if header.version == Version.V5 and ctrl.session_id != header.session_id: + return None + self.by_addr.pop(ctrl.addr, None) + ctrl.addr = addr + self.by_addr[addr] = ctrl + return ctrl + + def add(self, ctrl: LegacyCtrl) -> None: + self.by_addr[ctrl.addr] = ctrl + self.by_uin[ctrl.uin] = ctrl + + def remove(self, ctrl: LegacyCtrl) -> None: + if self.by_addr.get(ctrl.addr) is ctrl: + del self.by_addr[ctrl.addr] + if self.by_uin.get(ctrl.uin) is ctrl: + del self.by_uin[ctrl.uin] + + def note_preauth(self, addr: Address) -> None: + self.preauth[addr] = time.monotonic() + + def take_preauth(self, addr: Address) -> bool: + noted = self.preauth.pop(addr, None) + return noted is not None and time.monotonic() - noted < PREAUTH_LIFETIME + + async def _reap(self) -> None: + # UDP has no hang-up: a session that stops pinging is signed off + while True: + await asyncio.sleep(REAP_INTERVAL) + now = time.monotonic() + for ctrl in list(self.by_uin.values()): + if now - ctrl.last_activity > SESSION_TIMEOUT: + ctrl.logger.info('Timed out') + ctrl.close() + for addr, noted in list(self.preauth.items()): + if now - noted > PREAUTH_LIFETIME: + del self.preauth[addr] diff --git a/front/icq/events.py b/front/icq/events.py new file mode 100644 index 0000000..44a48f0 --- /dev/null +++ b/front/icq/events.py @@ -0,0 +1,160 @@ +from typing import Any, TYPE_CHECKING + +from core import event +from core.models import Circle, CircleRole, Contact, LoginOption, MessageData, MessageType, OIM, Substatus, TextWithData, User + +from front.oscar.proto.names import uin_of + +if TYPE_CHECKING: + from core.backend import Chat, ChatSession + from .ctrl import LegacyCtrl + + +class BackendEventHandler(event.BackendEventHandler): + __slots__ = ('ctrl',) + + ctrl: 'LegacyCtrl' + + def __init__(self, ctrl: 'LegacyCtrl') -> None: + self.ctrl = ctrl + + def on_close(self) -> None: + self.ctrl.close() + + def on_maintenance_boot(self) -> None: + self.ctrl.close() + + def on_presence_notification( + self, ctc: Contact, on_contact_add: bool, old_substatus: Substatus, *, + trid: str | None = None, update_status: bool = True, update_info_other: bool = True, + send_status_on_bl: bool = False, sess_id: int | None = None, updated_phone_info: dict[str, Any] | None = None, + ) -> None: + # only the people on the client's own contact list, and only when their status is what changed + if not update_status: + return + try: + self.ctrl.on_presence(ctc) + except Exception as ex: + self.ctrl.logger.error(ex) + + def on_presence_self_notification(self, old_substatus: Substatus, *, update_status: bool = True, update_info: bool = True) -> None: + pass + + def on_chat_invite( + self, chat: 'Chat', inviter: User, *, circle: bool = False, inviter_id: str | None = None, invite_msg: str = '', + ) -> None: + if chat is None: + chat = self.ctrl.backend.chat_create() + chat.add_id('icq0', chat.ids['main']) + self.ctrl.join_chat(chat, inviter) + + def on_declined_chat_invite(self, chat: 'Chat', circle: bool = False) -> None: + pass + + def on_added_me(self, user: User, *, adder_id: str | None = None, message: TextWithData | None = None) -> None: + # someone put this account on their (stored) contact list: ICQ's "you were added", unless they're still waiting on + # this account's authorization + if uin_of(user) is None: + return + from front.oscar.foodgroups.buddy import buddy_pending + if buddy_pending(user, self.ctrl.user): + return + self.ctrl.on_auth_event('added', user, '') + + def on_removed_me(self, user: User) -> None: + pass + + def on_contact_request_denied(self, user_added: User, message: str | None, *, contact_id: str | None = None) -> None: + pass + + def on_login_elsewhere(self, option: LoginOption) -> None: + self.ctrl.force_offline() + + def on_oim_sent(self, oim: OIM) -> None: + self.ctrl.deliver_oim_now(oim) + + def icq_on_auth_event(self, event: str, sender: User, text: str) -> None: + # authorization traffic from the OSCAR ICQ frontend's machinery (see `front.oscar.foodgroups.feedbag`) + self.ctrl.on_auth_event(event, sender, text) + + def icq_on_message(self, sender: User, msg_type: int, text: str) -> None: + # an ICQ-only message (chat/file request, plugin...) relayed from an OSCAR ICQ client + uin = uin_of(sender) + if uin is not None: + self.ctrl.deliver_message(uin, msg_type, text) + + # circles are not a thing in ICQ + def on_circle_invite_revoked(self, chat_id: str) -> None: + pass + + def on_accepted_circle_invite(self, circle: Circle) -> None: + pass + + def on_circle_updated(self, circle: Circle) -> None: + pass + + def on_left_circle(self, circle: Circle) -> None: + pass + + def on_circle_role_updated(self, chat_id: str, role: CircleRole) -> None: + pass + + def on_circle_created(self, circle: Circle) -> None: + pass + + +class ChatEventHandler(event.ChatEventHandler): + __slots__ = ('ctrl', 'cs', '_pending') + + ctrl: 'LegacyCtrl' + cs: 'ChatSession' + _pending: list[tuple[str, MessageData]] + + def __init__(self, ctrl: 'LegacyCtrl') -> None: + self.ctrl = ctrl + self._pending = [] + + def on_participant_joined(self, cs_other: 'ChatSession', first_pop: bool, initial_join: bool) -> None: + still_pending = [] + for target_uuid, data in self._pending: + if cs_other.user.uuid == target_uuid: + self.cs.send_message_to_user(target_uuid, data) + else: + still_pending.append((target_uuid, data)) + self._pending = still_pending + + def on_participant_left(self, cs_other: 'ChatSession', last_pop: bool) -> None: + # once the other side is gone this chat can't reach them again (they'd be invited to a new one), so it's let go + if any(cs is not self.cs for cs in self.cs.chat.get_roster()): + return + for uuid, (cs, _) in list(self.ctrl.chats.items()): + if cs is self.cs: + del self.ctrl.chats[uuid] + # (closed once the chat is done telling everyone, since it's still walking its roster) + self.ctrl.backend.loop.call_soon(self.cs.close) + + def on_chat_invite_declined( + self, chat: 'Chat', invitee: User, *, invitee_id: str | None = None, message: str | None = None, circle: bool = False, + ) -> None: + pass + + def on_chat_updated(self) -> None: + pass + + def on_chat_roster_updated(self) -> None: + pass + + def on_participant_status_updated(self, cs_other: 'ChatSession', first_pop: bool, initial: bool, old_substatus: Substatus) -> None: + pass + + def on_message(self, data: MessageData) -> None: + # typing notifications and the like have no ICQ form before OSCAR; only messages go through + if self.ctrl.bs is None or data.sender is self.ctrl.bs.user or data.type is not MessageType.Chat: + return + self.ctrl.deliver_chat_message(data) + + def send_when_joined(self, user_uuid: str, data: MessageData) -> None: + if any(cs_other.user.uuid == user_uuid for cs_other in self.cs.chat.get_roster()): + self.cs.send_message_to_user(user_uuid, data) + else: + self._pending.append((user_uuid, data)) diff --git a/front/icq/icq.py b/front/icq/icq.py new file mode 100644 index 0000000..c67d41f --- /dev/null +++ b/front/icq/icq.py @@ -0,0 +1,709 @@ +import struct + +from datetime import datetime +from enum import IntEnum +from typing import Any + +from core.models import OIM, User +from util import icq +from util.misc import Logger + +from ..proto import names +from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup +from ..proto.tlv import TLV, unmarshal_tlvs, find_tlv + + +class ICQRequest(IntEnum): + # ICQ__DB_QUERY request types (the u16 after the UIN in the little-endian envelope) + OfflineMessages = 0x003C + DeleteOfflineMessages = 0x003E + Meta = 0x07D0 + +class ICQReply(IntEnum): + OfflineMessage = 0x0041 + OfflineMessagesDone = 0x0042 + Meta = 0x07DA + +class ICQResult(IntEnum): + Ok = 0x0A + Fail = 0x32 + Error = 0x14 + +class ICQMeta(IntEnum): + # requests + SetBasicInfo = 0x03EA + SetWorkInfo = 0x03F3 + SetMoreInfo = 0x03FD + SetNotes = 0x0406 + SetEmails = 0x040B + SetInterests = 0x0410 + SetAffiliations = 0x041A + SetPermissions = 0x0424 + FullInfo = 0x04B2 + ShortInfo = 0x04BA + FullInfo2 = 0x04D0 + SearchByDetails = 0x0515 + SearchByUin = 0x051F + SearchByEmail = 0x0529 + SearchWhitePages = 0x0533 + SearchWhitePages2 = 0x055F + SearchByUin2 = 0x0569 + SearchByEmail3 = 0x0573 + SetIcqPhone = 0x0654 + XmlRequest = 0x0898 + SetFullInfo = 0x0C3A + DirectoryQuery = 0x0FA0 + # replies + SetBasicInfoAck = 0x0064 + SetWorkInfoAck = 0x006E + SetMoreInfoAck = 0x0078 + SetNotesAck = 0x0082 + SetEmailsAck = 0x0087 + SetInterestsAck = 0x008C + SetAffiliationsAck = 0x0096 + SetPermissionsAck = 0x00A0 + BasicInfo = 0x00C8 + WorkInfo = 0x00D2 + MoreInfo = 0x00DC + Notes = 0x00E6 + ExtEmails = 0x00EB + Interests = 0x00F0 + Affiliations = 0x00FA + ShortInfoReply = 0x0104 + HomepageCategory = 0x010E + UserFound = 0x01A4 + LastUserFound = 0x01AE + SetIcqPhoneAck = 0x031E + SetFullInfoAck = 0x0C3F + XmlReply = 0x08A2 + DirectoryResponse = 0x0FB4 + +# ICQ__TLV tags for the TLV-based requests (white pages 2, search by UIN 2/e-mail 3, set full info); values little endian +class ICQTag(IntEnum): + Uin = 0x0136 + FirstName = 0x0140 + LastName = 0x014A + Nickname = 0x0154 + Email = 0x015E + Gender = 0x017C + HomeCity = 0x0190 + HomeState = 0x019A + HomeCountry = 0x01A4 + WorkCompany = 0x01AE + WorkDepartment = 0x01B8 + WorkPosition = 0x01C2 + WorkOccupation = 0x01CC + HomepageUrl = 0x0213 + OnlineOnly = 0x0230 + Birthday = 0x023A + Notes = 0x0258 + HomeAddress = 0x0262 + HomeZip = 0x026C + HomePhone = 0x0276 + HomeFax = 0x0280 + HomeCell = 0x028A + WorkAddress = 0x0294 + WorkCity = 0x029E + WorkState = 0x02A8 + WorkCountry = 0x02B2 + WorkZip = 0x02BC + WorkPhone = 0x02C6 + WorkFax = 0x02D0 + WorkWebpage = 0x02DA + Authorization = 0x02F8 + WebAware = 0x030C + GmtOffset = 0x0316 + +# search hits' online status +DIR_STATUS_OFFLINE = 0 +DIR_STATUS_ONLINE = 1 +DIR_STATUS_HIDDEN = 2 + +MAX_SEARCH_RESULTS = 20 + + +class LE: + # a little-endian writer, the byte order the ICQ envelope inside foodgroup 0x15 uses + __slots__ = ('data',) + + def __init__(self) -> None: + self.data = b'' + + def u8(self, value: int) -> 'LE': + self.data += struct.pack(' 'LE': + self.data += struct.pack(' 'LE': + self.data += struct.pack(' '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(' int: + return struct.unpack(' 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('= 2: + return struct.unpack(' 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(' None: + # server-side XML data (Beacon"what's new" and such) isn't something there is any of + query.meta(ICQMeta.XmlReply, ICQResult.Error) + +def meta_directory_query(query: ICQContext, reader: LEReader) -> None: + # ICQ 6's directory protocol, a SNAC of its own (family 0x05B9) inside the request; it gets the empty answer Open + # OSCAR Server sends for what it doesn't handle: the request's subtype, result 0, nothing found + payload = reader.rest() + if len(payload) < 2 + 10: + return + body = payload[2:] + subtype, flags = struct.unpack('>HH', body[2:6]) + versioned = bool(flags & 0x8000) + nested = struct.pack('>HHHHH', 0x05B9, subtype, 0x8000 if versioned else 0x0000, 0, 0) + if versioned: + # the version block the request came with, mirrored: TLV 0x01 = 2 + version = TLV(0x0001, struct.pack('>H', 0x0002)).marshal() + nested += struct.pack('>H', len(version)) + version + # u8 result, string16 error message, 10 bytes nothing, [6 more], u32 total, [u16 pages], u16 block count + nested += struct.pack('>BH', 0, 0) + bytes(10) + if versioned: + nested += bytes(6) + nested += struct.pack('>L', 0) + if versioned: + nested += struct.pack('>H', 0) + nested += struct.pack('>H', 0) + query.reply(ICQReply.Meta, LE().u16(ICQMeta.DirectoryResponse).u8(ICQResult.Ok).u16(len(nested)).raw(nested).data) + + +META_HANDLERS = { + ICQMeta.ShortInfo: meta_short_info, + ICQMeta.FullInfo: meta_full_info, + ICQMeta.FullInfo2: meta_full_info, + ICQMeta.SearchByUin: meta_search_by_uin, + ICQMeta.SearchByUin2: meta_search_by_uin2, + ICQMeta.SearchByEmail: meta_search_by_email, + ICQMeta.SearchByEmail3: meta_search_by_email3, + ICQMeta.SearchByDetails: meta_search_by_details, + ICQMeta.SearchWhitePages: meta_search_white_pages, + ICQMeta.SearchWhitePages2: meta_search_white_pages2, + ICQMeta.SetBasicInfo: meta_set_basic_info, + ICQMeta.SetWorkInfo: meta_set_work_info, + ICQMeta.SetMoreInfo: meta_set_more_info, + ICQMeta.SetNotes: meta_set_notes, + ICQMeta.SetEmails: meta_set_emails, + ICQMeta.SetInterests: meta_set_interests, + ICQMeta.SetAffiliations: meta_set_affiliations, + ICQMeta.SetPermissions: meta_set_permissions, + ICQMeta.SetIcqPhone: meta_set_icq_phone, + ICQMeta.SetFullInfo: meta_set_full_info, + ICQMeta.XmlRequest: meta_xml_request, + ICQMeta.DirectoryQuery: meta_directory_query, +} diff --git a/front/icq/meta.py b/front/icq/meta.py new file mode 100644 index 0000000..61756ae --- /dev/null +++ b/front/icq/meta.py @@ -0,0 +1,335 @@ +from typing import Any, Callable, TYPE_CHECKING + +from core.models import User +from util import icq + +from . import directory +from .packets import LE, Meta, MetaReply, MetaResult, Reader, Server + +if TYPE_CHECKING: + from .ctrl import LegacyCtrl + from .wire import Header + + +# META_USER (0x064A), the V5 directory and profile requests: u16 subtype, then its data; every answer is a SRV_META_USER +# (0x03DE) of u16 reply subtype, u8 result and the reply's data, under the request's seq2 + +def handle(ctrl: 'LegacyCtrl', header: 'Header', data: bytes) -> None: + # the ACK echoes both sequence numbers + ctrl.ack(header, with_seq2 = True) + if len(data) < 2: + return + reader = Reader(data) + subtype = reader.u16() + handler = HANDLERS.get(subtype) + if handler is None: + ctrl.logger.info('[Client] Unhandled META_USER request', hex(subtype)) + reply(ctrl, header, subtype, MetaResult.Ok) + return + ctrl.logger.info('[Client] META_USER', hex(subtype)) + try: + handler(ctrl, header, reader) + except ValueError: + ctrl.logger.info('[Client] Malformed META_USER request', hex(subtype)) + +def reply(ctrl: 'LegacyCtrl', header: 'Header', subtype: int, result: int, body: bytes = b'') -> None: + ctrl.send(Server.MetaUser, LE().u16(subtype).u8(result).raw(body if result == MetaResult.Ok else b'').bytes(), seq2 = header.seq2) + +def _target(ctrl: 'LegacyCtrl', reader: Reader) -> User | None: + return directory.find(ctrl.backend, reader.u32()) + +def _meta_auth(info: dict[str, Any]) -> int: + # the META replies (like their OSCAR descendants): 0 means authorization required, 1 that anyone may add + return 0 if info['auth_required'] else 1 + + +# the info replies + +def _basic_info3(info: dict[str, Any]) -> bytes: + # nick, first, last, three e-mail addresses (primary, secondary, old), city, state, phone, fax, street, cell, ZIP, + # u16 country, u16 GMT offset, u8 auth, u8 hide e-mail (1: hidden), three zero bytes + body = LE().string(info['nick']).string(info['first']).string(info['last']).string(info['email']).string('').string('') + for field in ('city', 'state', 'phone', 'fax', 'address', 'cell', 'zip'): + body.string(info[field]) + body.u16(info['country']).u16(info['gmt']).u8(_meta_auth(info)).u8(0 if info['publish_email'] else 1).u8(0).u8(0).u8(0) + return body.bytes() + +def _basic_info_old(info: dict[str, Any]) -> bytes: + # the older basic info (META_USER_FULLINFO's): u32 UIN, nick, first, last, e-mail, u8 auth + return LE().u32(info['uin']).string(info['nick']).string(info['first']).string(info['last']).string(info['email']).u8(_meta_auth(info)).bytes() + +def _more_info(info: dict[str, Any], *, full_year: bool) -> bytes: + # u16 age, u8 gender, homepage, birth year (u16, or before ICQ 99b a u8 of the year less 1900), u8 month, u8 day, three + # u8 languages + body = LE().u16(info['age']).u8(info['gender']).string(info['homepage']) + year = info['birth_year'] + if full_year: + body.u16(year) + else: + body.u8(year - 1900 if year >= 1900 else year) + body.u8(info['birth_month']).u8(info['birth_day']).u8(info['lang1']).u8(info['lang2']).u8(info['lang3']) + return body.bytes() + +def _homepage_category() -> bytes: + # u8 enabled, u16 category, description, u8: nobody has one here + return LE().u8(0).u16(0).string('').u8(0).bytes() + +def _work_info(info: dict[str, Any], *, zip_string: bool) -> bytes: + # city, state, phone, fax, street, ZIP (a string from ICQ 99b, before that a u32), u16 country, company, department, + # position, u16 occupation, webpage + work = info['work'] + body = LE() + for field in ('city', 'state', 'phone', 'fax', 'address'): + body.string(work[field]) + if zip_string: + body.string(work['zip']) + else: + body.u32(info['work_zip_number']) + body.u16(work['country']).string(work['company']).string(work['department']).string(work['position']) + body.u16(work['occupation']).string(work['webpage']) + return body.bytes() + +def _pairs(pairs: list[list[Any]]) -> LE: + body = LE().u8(len(pairs)) + for code, keyword in pairs: + body.u16(int(code)).string(keyword) + return body + +def _padded(pairs: list[list[Any]], slots: int) -> list[list[Any]]: + return (list(pairs) + [[0, '']] * slots)[:slots] + +def _affiliations(info: dict[str, Any]) -> bytes: + body = _pairs(_padded(info['past_affiliations'], icq.AFFILIATION_SLOTS)).raw(_pairs(_padded(info['affiliations'], icq.AFFILIATION_SLOTS)).bytes()) + return body.u16(0x0000).u16(0x0001).u8(0).bytes() + +def _full_info(ctrl: 'LegacyCtrl', header: 'Header', user: User, *, newer: bool) -> None: + # seven replies: basic, more, homepage category, work, about, interests, affiliations; ICQ 99b's requests (and the + # login info) get the newer layouts + info = directory.profile(user, ctrl.user) + reply(ctrl, header, MetaReply.BasicInfo, MetaResult.Ok, _basic_info3(info) if newer else _basic_info_old(info)) + reply(ctrl, header, MetaReply.MoreInfo, MetaResult.Ok, _more_info(info, full_year = newer)) + reply(ctrl, header, MetaReply.HomepageCategory, MetaResult.Ok, _homepage_category()) + reply(ctrl, header, MetaReply.WorkInfo, MetaResult.Ok, _work_info(info, zip_string = newer)) + reply(ctrl, header, MetaReply.About, MetaResult.Ok, LE().string(info['notes']).bytes()) + reply(ctrl, header, MetaReply.Interests, MetaResult.Ok, _pairs(info['interests']).bytes()) + reply(ctrl, header, MetaReply.Affiliations, MetaResult.Ok, _affiliations(info)) + +def meta_login(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # answered with the subtype echoed, then u16 0 and u16 0x46 (no result byte) + ctrl.send(Server.MetaUser, LE().u16(Meta.Login).u16(0x0000).u16(0x0046).bytes(), seq2 = header.seq2) + +def meta_login_info(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # the client's own details after signing on (a UIN when it says whose) + user = _target(ctrl, reader) if reader.remaining() >= 4 else ctrl.user + if user is None: + reply(ctrl, header, MetaReply.BasicInfo, MetaResult.Fail) + return + _full_info(ctrl, header, user, newer = True) + +def meta_full_info(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + user = _target(ctrl, reader) + if user is None: + reply(ctrl, header, MetaReply.BasicInfo, MetaResult.Fail) + return + _full_info(ctrl, header, user, newer = False) + +def meta_full_info2(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + user = _target(ctrl, reader) + if user is None: + reply(ctrl, header, MetaReply.BasicInfo, MetaResult.Fail) + return + _full_info(ctrl, header, user, newer = True) + +def meta_short_info(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # nick, first, last, e-mail, u8 auth, u8 gender, u8 0 + user = _target(ctrl, reader) + if user is None: + reply(ctrl, header, MetaReply.ShortInfo, MetaResult.Fail) + return + info = directory.profile(user, ctrl.user) + body = LE().string(info['nick']).string(info['first']).string(info['last']).string(info['email']) + reply(ctrl, header, MetaReply.ShortInfo, MetaResult.Ok, body.u8(_meta_auth(info)).u8(info['gender']).u8(0).bytes()) + + +# searches + +def _record(info: dict[str, Any]) -> LE: + # a hit: u32 UIN, nick, first, last, e-mail, u8 auth, u8 web aware + record = LE().u32(info['uin']).string(info['nick']).string(info['first']).string(info['last']).string(info['email']) + return record.u8(_meta_auth(info)).u8(1 if info['web_aware'] else 0) + +def _search_results(ctrl: 'LegacyCtrl', header: 'Header', users: list[User]) -> None: + # every hit but the last is USER_FOUND, the last LAST_USER_FOUND with u32 users left after it (outside its u16 length); + # no hits at all is a failed LAST_USER_FOUND + if not users: + reply(ctrl, header, MetaReply.LastUserFound, MetaResult.Fail) + return + for index, user in enumerate(users): + last = index == len(users) - 1 + record = _record(directory.profile(user, ctrl.user)).u8(0).bytes() + body = LE().u16(len(record)).raw(record) + if last: + body.u32(0) + reply(ctrl, header, MetaReply.LastUserFound if last else MetaReply.UserFound, MetaResult.Ok, body.bytes()) + +def _white_results(ctrl: 'LegacyCtrl', header: 'Header', users: list[User], *, length_prefixed: bool) -> None: + # white pages hits are WHITE_FOUND/WHITE_LAST_FOUND: the first search's records have no length and only the last has + # users left; the second's (0x0533) carry a u16 length and users left on every record + if not users: + reply_body = LE().u16(MetaReply.WhiteLastFound).u8(MetaResult.Fail).u32(0).bytes() + ctrl.send(Server.MetaUser, reply_body, seq2 = header.seq2) + return + for index, user in enumerate(users): + last = index == len(users) - 1 + record = _record(directory.profile(user, ctrl.user)) + if length_prefixed: + payload = record.u8(0).bytes() + body = LE().u16(len(payload)).raw(payload).u32(0) + else: + body = record + if last: + body.u32(0) + reply(ctrl, header, MetaReply.WhiteLastFound if last else MetaReply.WhiteFound, MetaResult.Ok, body.bytes()) + +def meta_search_name(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # nick, first, last + nick, first, last = reader.string(), reader.string(), reader.string() + _search_results(ctrl, header, directory.search(ctrl.backend, nick = nick, first = first, last = last)) + +def meta_search_uin(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # finding someone by their exact number is how ICQ adds a contact, so it doesn't need a directory listing + user = _target(ctrl, reader) + _search_results(ctrl, header, [user] if user is not None else []) + +def meta_search_email(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + email = reader.string() + _search_results(ctrl, header, directory.search(ctrl.backend, email = email)) + +def meta_search_white(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # first, last, nick and e-mail lead it; the rest (ages, location, work, interests) narrows and isn't kept here + first, last, nick, email = reader.string(), reader.string(), reader.string(), reader.string() + users = directory.search(ctrl.backend, email = email, first = first, last = last, nick = nick) + _white_results(ctrl, header, users, length_prefixed = False) + +def meta_search_white2(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + first, last, nick, email = reader.string(), reader.string(), reader.string(), reader.string() + users = directory.search(ctrl.backend, email = email, first = first, last = last, nick = nick) + _white_results(ctrl, header, users, length_prefixed = True) + + +# profile changes + +def _save(ctrl: 'LegacyCtrl') -> None: + icq.save(ctrl.backend, ctrl.user) + +def meta_set_basic(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # nick, first, last, three e-mail addresses (only the primary is kept), city, state, phone, fax, street, cell, ZIP, + # u16 country, u8 GMT offset, u8 publish e-mail (0: yes) + fields: dict[str, Any] = { field: reader.string() for field in ('nick', 'first', 'last', 'email') } + reader.string() + reader.string() + for field in ('city', 'state', 'phone', 'fax', 'address', 'cell', 'zip'): + fields[field] = reader.string() + fields['country'] = reader.u16() if reader.remaining() >= 2 else 0 + fields['gmt'] = reader.u8() if reader.remaining() else 0 + fields['publish_email'] = (reader.u8() == 0) if reader.remaining() else False + ctrl.set_nickname(fields['nick']) + icq.set_basic(ctrl.user, fields) + _save(ctrl) + reply(ctrl, header, MetaReply.SetBasicAck, MetaResult.Ok) + +def meta_set_work(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # city, state, phone, fax, street, ZIP, u16 country, company, department, position, u16 occupation, webpage + fields: dict[str, Any] = { field: reader.string() for field in ('city', 'state', 'phone', 'fax', 'address', 'zip') } + fields['country'] = reader.u16() + for field in ('company', 'department', 'position'): + fields[field] = reader.string() + fields['occupation'] = reader.u16() + fields['webpage'] = reader.string() + icq.set_work(ctrl.user, fields) + _save(ctrl) + reply(ctrl, header, MetaReply.SetWorkAck, MetaResult.Ok) + +def meta_set_more(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # u8 age (worked out from the birth date instead), u16 gender, homepage, u16 year, u8 month, u8 day, three languages + reader.u8() + fields: dict[str, Any] = { 'gender': reader.u16() & 0xFF, 'homepage': reader.string(), 'birth_year': reader.u16() } + fields['birth_month'] = reader.u8() + fields['birth_day'] = reader.u8() + for lang in ('lang1', 'lang2', 'lang3'): + fields[lang] = reader.u8() if reader.remaining() else 0 + icq.set_more(ctrl.user, fields) + _save(ctrl) + reply(ctrl, header, MetaReply.SetMoreAck, MetaResult.Ok) + +def meta_set_about(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + icq.set_notes(ctrl.user, reader.string()) + _save(ctrl) + reply(ctrl, header, MetaReply.SetAboutAck, MetaResult.Ok) + +def _read_pairs(reader: Reader) -> list[list[Any]]: + count = reader.u8() + return [[reader.u16(), reader.string()] for _ in range(count)] + +def meta_set_interests(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + icq.set_interests(ctrl.user, _read_pairs(reader)) + _save(ctrl) + reply(ctrl, header, MetaReply.SetInterestsAck, MetaResult.Ok) + +def meta_set_affiliations(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + past = _read_pairs(reader) + current = _read_pairs(reader) + icq.set_affiliations(ctrl.user, past, current) + _save(ctrl) + reply(ctrl, header, MetaReply.SetAffiliationsAck, MetaResult.Ok) + +def meta_set_security(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # u8 authorization (0: required, 1: anyone may add), u8 web aware, u8 direct connection permissions, u8 + authorization = reader.u8() + web_aware = reader.u8() if reader.remaining() else 0 + icq.set_permissions(ctrl.user, auth_required = authorization == 0, web_aware = web_aware == 1) + _save(ctrl) + reply(ctrl, header, MetaReply.SetSecurityAck, MetaResult.Ok) + +def meta_set_password(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # every protocol's copy of the password comes from the one set on the website, so it isn't changed from here + reply(ctrl, header, MetaReply.SetPasswordAck, MetaResult.Fail) + +def meta_set_homepage_category(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # homepage categories aren't kept (nothing shows them but this client), but the client needs its answer + reply(ctrl, header, MetaReply.SetHomepageCategoryAck, MetaResult.Ok) + +def meta_unregister(ctrl: 'LegacyCtrl', header: 'Header', reader: Reader) -> None: + # the account belongs to the website, which is where it can be closed + reply(ctrl, header, MetaReply.UnregisterAck, MetaResult.Fail) + + +HANDLERS: dict[int, Callable[['LegacyCtrl', 'Header', Reader], None]] = { + Meta.Login: meta_login, + Meta.LoginInfo: meta_login_info, + Meta.LoginInfo2: meta_login_info, + Meta.FullInfo: meta_full_info, + Meta.FullInfo2: meta_full_info2, + Meta.ShortInfo: meta_short_info, + Meta.SearchName: meta_search_name, + Meta.SearchName2: meta_search_name, + Meta.SearchUin: meta_search_uin, + Meta.SearchUin2: meta_search_uin, + Meta.SearchEmail: meta_search_email, + Meta.SearchEmail2: meta_search_email, + Meta.SearchWhite: meta_search_white, + Meta.SearchWhite2: meta_search_white2, + Meta.SetBasic: meta_set_basic, + Meta.SetBasic2: meta_set_basic, + Meta.SetWork: meta_set_work, + Meta.SetWork2: meta_set_work, + Meta.SetMore: meta_set_more, + Meta.SetMore2: meta_set_more, + Meta.SetAbout: meta_set_about, + Meta.SetInterests: meta_set_interests, + Meta.SetAffiliations: meta_set_affiliations, + Meta.SetSecurity: meta_set_security, + Meta.SetPassword: meta_set_password, + Meta.SetHomepageCategory: meta_set_homepage_category, + Meta.Unregister: meta_unregister, +} diff --git a/front/icq/packets.py b/front/icq/packets.py new file mode 100644 index 0000000..03914d7 --- /dev/null +++ b/front/icq/packets.py @@ -0,0 +1,275 @@ +import struct + +from enum import IntEnum + +from util import icq + + +class Version(IntEnum): + V1 = 0x0001 + V2 = 0x0002 + V3 = 0x0003 + V4 = 0x0004 + V5 = 0x0005 + +class Command(IntEnum): + # what clients send (CMD_*) + Ack = 0x000A + ThruServer = 0x010E + Reconnect = 0x015E + Login = 0x03E8 + GetDeps = 0x03F2 + RegNewUser = 0x03FC + ContactList = 0x0406 + SearchUin = 0x041A + SearchUser = 0x0424 + KeepAlive = 0x042E + Logoff = 0x0438 + SysMsgDoneAck = 0x0442 + SysMsgReq = 0x044C + Authorize = 0x0456 + InfoReq = 0x0460 + ExtInfoReq = 0x046A + SetPassword = 0x049C + UpdateBasic = 0x04A6 + UpdateDetail = 0x04B0 + GetExternals = 0x04C4 + SetStatus = 0x04D8 + FirstLogin = 0x04EC + SetBasicInfo = 0x050A + SetAuth = 0x0514 + KeepAlive2 = 0x051E + UserAdd = 0x053C + SetWorkInfo = 0x0578 + SetHomeInfo = 0x0582 + SetHomeWeb = 0x058C + SetNotes = 0x0596 + GetNotes = 0x05AA + SetWorkWeb = 0x05BE + SearchStart = 0x05C8 + RegRequestInfo = 0x05DC + RegNewUserInfo = 0x05E6 + GetDeps1 = 0x05F0 + UserGetInfo = 0x05FA + MetaUser = 0x064A + InvisibleList = 0x06A4 + VisibleList = 0x06AE + ChangeVILists = 0x06B8 + +class Server(IntEnum): + # what the server sends (SRV_*) + Ack = 0x000A + SetOffline = 0x0028 + DepsList = 0x0032 + Hello = 0x005A + WrongPassword = 0x0064 + UserOnline = 0x006E + UserOffline = 0x0078 + SearchFound = 0x008C + SearchDone = 0x00A0 + UpdatedBasic = 0x00B4 + UpdateBasicFail = 0x00BE + UpdatedDetail = 0x00C8 + UpdateDetailFail = 0x00D2 + SysMsgOffline = 0x00DC + SysMsgDone = 0x00E6 + NotConnected = 0x00F0 + Busy = 0x00FA + SysMsgOnline = 0x0104 + InfoReply = 0x0118 + ExtInfoReply = 0x0122 + InvalidUin = 0x012C + UserStatus = 0x01A4 + UpdatedBasicV4 = 0x01E0 + UpdateBasicFailV4 = 0x01EA + UserListDone = 0x021C + MetaUser = 0x03DE + +class Meta(IntEnum): + # META_USER (0x064A) requests: the u16 that leads the data + SetBasic = 0x03E8 + SetBasic2 = 0x03E9 + SetWork = 0x03F2 + SetWork2 = 0x03F3 + SetMore = 0x03FC + SetMore2 = 0x03FD + SetAbout = 0x0406 + SetInterests = 0x0410 + SetAffiliations = 0x041A + SetSecurity = 0x0424 + SetPassword = 0x042E + SetHomepageCategory = 0x0442 + FullInfo = 0x04B0 + FullInfo2 = 0x04B1 + ShortInfo = 0x04BA + Unregister = 0x04C4 + LoginInfo = 0x04CE + LoginInfo2 = 0x04CF + SearchName = 0x0514 + SearchName2 = 0x0515 + SearchUin = 0x051E + SearchUin2 = 0x051F + SearchEmail = 0x0528 + SearchEmail2 = 0x0529 + SearchWhite = 0x0532 + SearchWhite2 = 0x0533 + UsageStats = 0x06B8 + Login = 0x07D0 + +class MetaReply(IntEnum): + # SRV_META_USER (0x03DE) replies: the u16 that leads the data, then a u8 result + SetBasicAck = 0x0064 + SetWorkAck = 0x006E + SetMoreAck = 0x0078 + SetAboutAck = 0x0082 + SetInterestsAck = 0x008C + SetAffiliationsAck = 0x0096 + SetSecurityAck = 0x00A0 + SetPasswordAck = 0x00AA + UnregisterAck = 0x00B4 + SetHomepageCategoryAck = 0x00BE + BasicInfo = 0x00C8 + WorkInfo = 0x00D2 + MoreInfo = 0x00DC + About = 0x00E6 + Interests = 0x00F0 + Affiliations = 0x00FA + ShortInfo = 0x0104 + HomepageCategory = 0x010E + UserFound = 0x0190 + LastUserFound = 0x019A + WhiteFound = 0x01A4 + WhiteLastFound = 0x01AE + +class MetaResult(IntEnum): + Ok = 0x0A + Fail = 0x32 + +class MessageType(IntEnum): + # the low byte of a message's type + Text = 0x01 + Chat = 0x02 + File = 0x03 + Url = 0x04 + AuthRequest = 0x06 + AuthDeny = 0x07 + AuthGrant = 0x08 + Server = 0x09 + Added = 0x0C + WebPager = 0x0D + EmailPager = 0x0E + Contacts = 0x13 + Plugin = 0x1A + AutoAway = 0xE8 + AutoOccupied = 0xE9 + AutoNotAvailable = 0xEA + AutoDnd = 0xEB + AutoFreeForChat = 0xEC + +# what the client's fixed-size buffers take +MAX_NICK = 20 +MAX_NAME = 64 +MAX_PHONE = 30 +MAX_HOMEPAGE = 127 +MAX_ABOUT = 450 +# the longest password a client sends; the rest of the packet isn't trusted past it +MAX_PASSWORD = 20 + + +class LE: + # a little-endian writer, the only byte order the pre-OSCAR protocol has + __slots__ = ('data',) + + data: bytearray + + def __init__(self) -> None: + self.data = bytearray() + + def u8(self, value: int) -> 'LE': + self.data += struct.pack(' 'LE': + self.data += struct.pack(' 'LE': + self.data += struct.pack(' 'LE': + self.data += value + return self + + def string(self, value: str, limit: int = 0) -> 'LE': + # u16 length counting the NUL, the text, the NUL; an empty string is still a length of 1 and its NUL + encoded = icq.latin1(value) + if limit: + encoded = encoded[:limit] + return self.u16(len(encoded) + 1).raw(encoded).u8(0) + + def bytes(self) -> bytes: + return bytes(self.data) + +class Reader: + __slots__ = ('data', 'pos') + + data: bytes + pos: int + + def __init__(self, data: bytes) -> None: + self.data = data + self.pos = 0 + + def remaining(self) -> int: + return len(self.data) - self.pos + + def take(self, length: int) -> bytes: + if length < 0 or self.pos + length > len(self.data): + raise ValueError('truncated ICQ packet') + chunk = self.data[self.pos:self.pos + length] + self.pos += length + return chunk + + def skip(self, length: int) -> None: + self.take(length) + + def u8(self) -> int: + return self.take(1)[0] + + def u16(self) -> int: + return struct.unpack(' int: + return struct.unpack(' bytes: + # u16 length, then that many bytes ending in a NUL; a client's own length is trusted only up to `limit` + length = self.u16() + if limit and length > limit + 1: + raw = self.take(length)[:limit] + else: + raw = self.take(length) + if b'\x00' in raw: + raw = raw[:raw.index(b'\x00')] + return raw + + def string(self) -> str: + return icq.from_latin1(self.raw_string()) + + def rest(self) -> bytes: + chunk = self.data[self.pos:] + self.pos = len(self.data) + return chunk + +def uin_list(data: bytes) -> list[int]: + # u8 count, then that many u32 UINs (contact, visible and invisible lists); a short packet ends the list early + reader = Reader(data) + uins = [] + try: + count = reader.u8() + for _ in range(count): + uins.append(reader.u32()) + except ValueError: + pass + return uins diff --git a/front/icq/wire.py b/front/icq/wire.py new file mode 100644 index 0000000..ea20ab7 --- /dev/null +++ b/front/icq/wire.py @@ -0,0 +1,91 @@ +import struct + +from .crypt import add_v5_server_checkcode, decrypt_v4, decrypt_v5, v3_header_checkcode +from .packets import Command, Version + + +class Header: + # what every version's client packet header comes down to (the fields a version doesn't have stay 0) + __slots__ = ('version', 'command', 'seq1', 'seq2', 'uin', 'session_id') + + version: int + command: int + seq1: int + seq2: int + uin: int + session_id: int + + def __init__(self, version: int, command: int, seq1: int, seq2: int, uin: int, session_id: int = 0) -> None: + self.version = version + self.command = command + self.seq1 = seq1 + self.seq2 = seq2 + self.uin = uin + self.session_id = session_id + + def __repr__(self) -> str: + return ''.format(self.version, self.command, self.seq1, self.seq2, self.uin) + +def version_of(packet: bytes) -> int | None: + if len(packet) < 2: + return None + return struct.unpack_from(' tuple[Header, bytes] | None: + # client packet -> (header, data); None for anything too short to be one + version = version_of(packet) + if version == Version.V5: + # u16 version, u32 zero, u32 UIN, then (encrypted) u32 session ID, u16 command, u16 seq1, u16 seq2, u32 checkcode + if len(packet) < 24: + return None + plain = decrypt_v5(packet) + uin, session_id, command, seq1, seq2 = struct.unpack_from(' bytes: + # server packet for a client of `version` + if version == Version.V5: + # u16 version, u8 zero, u32 session ID, u16 command, u16 seq1, u16 seq2, u32 UIN, u32 checkcode; not encrypted + packet = bytearray(struct.pack(' None: self.ctrl = ctrl - def on_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None: - self.ctrl.send_reply('PRIVMSG', '$*', ':' + message, source = "System") + def on_client_alert(self, alert: Alert) -> bool: + for line in irc_lines(alert.paragraphs) + ([alert.url] if alert.url else []): + self.ctrl.send_reply('PRIVMSG', '$*', ':' + line, source = "System") + return True def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None: if args[1] is not None: diff --git a/front/msim/ctrl.py b/front/msim/ctrl.py index 9d1154f..ef866b8 100644 --- a/front/msim/ctrl.py +++ b/front/msim/ctrl.py @@ -226,7 +226,7 @@ class MSIMCtrl: 'GroupID': id, 'GroupName': group, 'Position': id, - 'GroupFlag': 131073 # unclear what GroupFlag does, TODO(subpurple): figure it out + 'GroupFlag': 131073 # unclear what GroupFlag does, TODO: figure it out }) # self.send_persist_reply(cmd, dsn, lid, rid, msim_groups) diff --git a/front/msn/entry.py b/front/msn/entry.py index f17bbbf..e565b7a 100644 --- a/front/msn/entry.py +++ b/front/msn/entry.py @@ -10,8 +10,8 @@ from .msnp import MSNPCtrl def register(loop: asyncio.AbstractEventLoop, backend: Backend, http_app: web.Application) -> None: from util.misc import ProtocolRunner - from . import msnp_dp, msnp_ns, msnp_sb - from .http import appdirectory, abservice, gateway, other + from . import msnp_dp, msnp_ns, msnp_sb#, spotlife, turn + from .http import appdirectory, abservice, gateway, other, schematizedstore, sharingservice backend.add_runner(ProtocolRunner('0.0.0.0', 1863, ListenerMSNP, args = ['MSNP Dispatch', backend, msnp_dp.MSNPCtrlDP], service = 'MSNP Dispatch')) backend.add_runner(ProtocolRunner('0.0.0.0', 1864, ListenerMSNP, args = ['MSNP Notification', backend, msnp_ns.MSNPCtrlNS], service = 'MSNP Notification')) @@ -19,7 +19,11 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, http_app: web.Ap appdirectory.register(http_app) other.register(http_app) abservice.register(http_app) + sharingservice.register(http_app) + schematizedstore.register(http_app) gateway.register(loop, http_app) + #spotlife.register(loop, backend, http_app) + #turn.register(loop, backend) class ListenerMSNP(asyncio.Protocol): logger: Logger diff --git a/front/msn/http/abservice.py b/front/msn/http/abservice.py index 3227ea0..7ec70dd 100644 --- a/front/msn/http/abservice.py +++ b/front/msn/http/abservice.py @@ -1,4 +1,4 @@ -from typing import Any, Optional +from typing import Any from enum import IntEnum from datetime import datetime import asyncio, secrets, sys, util.misc, settings @@ -10,168 +10,15 @@ from markupsafe import Markup from core import models, error from core.backend import Backend, BackendSession, MAX_GROUP_NAME_LENGTH -from .util import preprocess_soap, get_tag_localname, unknown_soap, find_element, render, bool_to_str, xml_to_string +from .util import find_element, render, bool_to_str, dispatch_abch, abch_fault, schema_fault, server_fault from ..misc import gen_signedticket_xml def register(app: web.Application) -> None: - app.router.add_post('/abservice/SharingService.asmx', lambda req: handle_abservice(req, sharing = True)) app.router.add_post('/abservice/abservice.asmx', handle_abservice) -async def handle_abservice(req: web.Request, *, sharing: bool = False) -> web.Response: - header, action, bs, _ = await preprocess_soap(req) - if bs is None: - raise web.HTTPForbidden() - action_str = get_tag_localname(action) - if find_element(action, 'deltasOnly') or find_element(action, 'DeltasOnly'): - return render(req, 'msn:abservice/Fault.fullsync.xml', { 'faultactor': action_str }) - - if settings.DEBUG_FULL: - print(xml_to_string(action)) - - method = getattr(sys.modules[__name__], ('sharing' if sharing else 'ab') + '_' + action_str, None) - if not method: - return unknown_soap(req, header, action) - - try: - return method(req, header, action, bs) - except: - import traceback - return render(req, 'msn:Fault.generic.xml', { - 'exception': traceback.format_exc(), - }, status = 500) +async def handle_abservice(req: web.Request) -> web.Response: + return await dispatch_abch(req, sys.modules[__name__], 'ab') -def sharing_FindMembership(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: - backend: Backend = req.app['backend'] - now_str = util.misc.date_format(datetime.utcnow()) - user = bs.user - detail = user.detail - cachekey = secrets.token_urlsafe(172) - return render(req, 'msn:sharing/FindMembershipResponse.xml', { - 'cachekey': cachekey, - 'host': settings.ADDRESSBOOK_HOST, - 'session_id': util.misc.gen_uuid(), - 'user': user, - 'detail': detail, - 'ContactList': models.ContactList, - 'lists': [models.ContactList.AL, models.ContactList.BL, models.ContactList.RL], - 'circles': backend.user_service.get_circle_batch(user), - 'now': now_str, - }) - -def sharing_AddMember(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: - backend: Backend = req.app['backend'] - cachekey = secrets.token_urlsafe(172) - - user = bs.user - detail = user.detail - assert detail is not None - - memberships = action.findall('.//{*}memberships/{*}Membership') - for membership in memberships: - email = None # type: Optional[str] - circle_id = None - - lst = models.ContactList.Parse(str(find_element(membership, 'MemberRole'))) - assert lst is not None - members = membership.findall('.//{*}Members/{*}Member') - for member in members: - member_type = member.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if member_type == 'PassportMember': - if find_element(member, 'Type') == 'Passport' and find_element(member, 'State') == 'Accepted': - email = find_element(member, 'PassportName') - elif member_type == 'EmailMember': - if find_element(member, 'Type') == 'Email' and find_element(member, 'State') == 'Accepted': - email = find_element(member, 'Email') - elif member_type == 'CircleMember': - if find_element(member, 'Type') == 'Circle' and find_element(member, 'State') == 'Accepted': - circle_id = find_element(member, 'CircleId') - if email is None and circle_id is None: - return render(req, 'msn:sharing/Fault.userdoesnotexist.xml', status = 500) - if email is not None: - name = None - contact_uuid = backend.util_get_uuid_from_email(email) - if contact_uuid is None: - return render(req, 'msn:sharing/Fault.userdoesnotexist.xml', status = 500) - ctc = detail.contacts.get(contact_uuid) - if ctc is None: - name = email - - try: - bs.me_contact_add(contact_uuid, lst, name = name) - except error.ContactListIsFull: - return web.HTTPInternalServerError() - except: - pass - elif circle_id is not None: - if not (circle_id.startswith('00000000-0000-0000-0009-') and len(circle_id[24:]) == 12): - return render(req, 'msn:sharing/Fault.userdoesnotexist.xml', status = 500) - chat_id = circle_id[-12:] - circle = backend.user_service.get_circle(chat_id) - if circle is None: return web.HTTPInternalServerError() - - if lst in (models.ContactList.RL,models.ContactList.PL): - return web.HTTPInternalServerError() - if lst == models.ContactList.BL: - bs.me_block_circle(circle) - return render(req, 'msn:sharing/AddMemberResponse.xml', { - 'cachekey': cachekey, - 'host': settings.ADDRESSBOOK_HOST, - 'session_id': util.misc.gen_uuid(), - }) - -def sharing_DeleteMember(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: - backend: Backend = req.app['backend'] - cachekey = secrets.token_urlsafe(172) - - user = bs.user - detail = user.detail - assert detail is not None - - contact_uuid = None - circle_id = None - - memberships = action.findall('.//{*}memberships/{*}Membership') - for membership in memberships: - lst = models.ContactList.Parse(str(find_element(membership, 'MemberRole'))) - assert lst is not None - members = membership.findall('.//{*}Members/{*}Member') - for member in members: - member_type = member.get('{http://www.w3.org/2001/XMLSchema-instance}type') - if member_type == 'PassportMember': - if find_element(member, 'Type') == 'Passport' and find_element(member, 'State') == 'Accepted': - try: - contact_uuid = find_element(member, 'MembershipId').split('/', 1)[1] - except: - email = find_element(member, 'PassportName') - contact_uuid = backend.util_get_uuid_from_email(email or '') - assert contact_uuid is not None - elif member_type == 'CircleMember': - if find_element(member, 'Type') == 'Circle' and find_element(member, 'State') == 'Accepted': - circle_id = find_element(member, 'CircleId') - assert circle_id is not None - if contact_uuid is not None: - if contact_uuid not in detail.contacts: - return render(req, 'msn:sharing/Fault.memberdoesnotexist.xml', status = 500) - try: - bs.me_contact_remove(contact_uuid, lst) - except: - pass - elif circle_id is not None: - if not (circle_id.startswith('00000000-0000-0000-0009-') and len(circle_id[24:]) == 12): - return web.HTTPInternalServerError() - chat_id = circle_id[-12:] - circle = backend.user_service.get_circle(chat_id) - if circle is None: return web.HTTPInternalServerError() - - if lst in (models.ContactList.RL,models.ContactList.PL): - return web.HTTPInternalServerError() - if lst == models.ContactList.BL: - bs.me_unblock_circle(circle) - return render(req, 'msn:sharing/DeleteMemberResponse.xml', { - 'cachekey': cachekey, - 'host': settings.ADDRESSBOOK_HOST, - 'session_id': util.misc.gen_uuid(), - }) def ab_ABFindAll(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: now_str = util.misc.date_format(datetime.utcnow()) @@ -188,7 +35,7 @@ def ab_ABFindAll(req: web.Request, header: Any, action: Any, bs: BackendSession) ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABFindAll', 'ABDoesNotExist') return render(req, 'msn:abservice/ABFindAllResponse.xml', { 'cachekey': cachekey, @@ -220,9 +67,9 @@ def ab_ABFindContactsPaged(req: web.Request, header: Any, action: Any, bs: Backe try: if not (ab_id == '00000000-0000-0000-0000-000000000000' or (ab_id.startswith('00000000-0000-0000-0009-') and len(ab_id[24:]) == 12)): - return web.HTTPInternalServerError() + return abch_fault(req, 'ABFindContactsPaged', 'ABDoesNotExist') except: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABFindContactsPaged', 'ABDoesNotExist') if ab_id == '00000000-0000-0000-0000-000000000000': ab_type = 'Individual' @@ -230,6 +77,9 @@ def ab_ABFindContactsPaged(req: web.Request, header: Any, action: Any, bs: Backe ab_type = 'Group' chat_id = ab_id[-12:] circle = backend.user_service.get_circle(chat_id) + # A circle's address book is only there for its members + if circle is None or user.uuid not in circle.memberships: + return abch_fault(req, 'ABFindContactsPaged', 'ABDoesNotExist') circles = [ circle @@ -274,12 +124,12 @@ def ab_ABContactAdd(req: web.Request, header: Any, action: Any, bs: BackendSessi ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABContactAdd', 'ABDoesNotExist') contact = find_element(action, 'contacts/Contact') if contact is None: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactAdd') type = find_element(contact, 'contactType') or 'LivePending' email = find_element(contact, 'passportName') or '' @@ -300,7 +150,7 @@ def ab_ABContactAdd(req: web.Request, header: Any, action: Any, bs: BackendSessi for annotation in annotations: name = find_element(annotation, 'Name') if name not in _ANNOTATION_NAMES: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactAdd') value = find_element(annotation, 'Value') if name == 'AB.NickName': nickname = value @@ -319,7 +169,7 @@ def ab_ABContactAdd(req: web.Request, header: Any, action: Any, bs: BackendSessi bs.me_contact_add(contact_uuid, models.ContactList.FL, name = email, nickname = nickname) except error.ContactListIsFull: # TODO - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactAdd', 'Contact list is full') except: pass @@ -330,6 +180,82 @@ def ab_ABContactAdd(req: web.Request, header: Any, action: Any, bs: BackendSessi 'contact_uuid': contact_uuid, }) +def ab_CreateContact(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: + backend: Backend = req.app['backend'] + cachekey = secrets.token_urlsafe(172) + + user = bs.user + detail = user.detail + assert detail is not None + + email = str(find_element(action, 'contactHandle/Email') or '') + if '@' not in email: + return render(req, 'msn:abservice/Fault.emailmissingatsign.xml', status = 500) + elif '.' not in email: + return render(req, 'msn:abservice/Fault.emailmissingdot.xml', status = 500) + + contact_uuid = backend.util_get_uuid_from_email(email) + if contact_uuid is None: + return render(req, 'msn:abservice/Fault.invaliduser.xml', { + 'action_str': 'CreateContact', + 'email': email, + }, status = 500) + head = backend._load_user_record(contact_uuid) + if head is None: + return abch_fault(req, 'CreateContact', 'InvalidPassportUser') + + ab_id = str(find_element(action, 'abHandle/ABId') or '00000000-0000-0000-0000-000000000000').lower() + if ab_id != '00000000-0000-0000-0000-000000000000': + if not (ab_id.startswith('00000000-0000-0000-0009-') and len(ab_id[24:]) == 12): + return abch_fault(req, 'CreateContact', 'ABDoesNotExist') + circle = backend.user_service.get_circle(ab_id[-12:]) + if circle is None or user.uuid not in circle.memberships: + return abch_fault(req, 'CreateContact', 'ABDoesNotExist') + caller_membership = circle.memberships[user.uuid] + if contact_uuid not in circle.memberships and caller_membership.role in (models.CircleRole.Admin, models.CircleRole.AssistantAdmin): + bs.me_add_user_to_circle(circle, head) + return render(req, 'msn:abservice/CreateContactResponse.xml', { + 'cachekey': cachekey, + 'host': settings.ADDRESSBOOK_HOST, + 'session_id': util.misc.gen_uuid(), + 'head': head, + 'user': user, + 'now': util.misc.date_format(datetime.utcnow()), + 'trust_level': 0, + }) + + nickname = None + for annotation in action.findall('.//{*}contactInfo/{*}annotations/{*}Annotation'): + if find_element(annotation, 'Name') == 'AB.NickName': + nickname = find_element(annotation, 'Value') + + ctc = detail.contacts.get(contact_uuid) + if ctc is None or not ctc.lists & models.ContactList.FL: + try: + bs.me_contact_add(contact_uuid, models.ContactList.FL, name = email, nickname = nickname) + except error.ContactListIsFull: + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/CreateContact', 'Contact list is full') + except: + pass + + trust_level = find_element(action, 'contactInfo/TrustLevel') + if trust_level is not None: + try: + user.settings['TrustLevels'] = { **(user.settings.get('TrustLevels') or {}), contact_uuid: int(trust_level) } + except (TypeError, ValueError): + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/CreateContact') + backend._mark_modified(user) + + return render(req, 'msn:abservice/CreateContactResponse.xml', { + 'cachekey': cachekey, + 'host': settings.ADDRESSBOOK_HOST, + 'session_id': util.misc.gen_uuid(), + 'head': head, + 'user': user, + 'now': util.misc.date_format(datetime.utcnow()), + 'trust_level': (user.settings.get('TrustLevels') or {}).get(contact_uuid, 0), + }) + def ab_ABContactDelete(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: cachekey = secrets.token_urlsafe(172) @@ -344,7 +270,7 @@ def ab_ABContactDelete(req: web.Request, header: Any, action: Any, bs: BackendSe ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABContactDelete', 'ABDoesNotExist') contacts = action.findall('.//{*}contacts/{*}Contact') for contact in contacts: @@ -375,7 +301,7 @@ def ab_ABContactUpdate(req: web.Request, header: Any, action: Any, bs: BackendSe ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABContactUpdate', 'ABDoesNotExist') contacts = action.findall('.//{*}contacts/{*}Contact') for contact in contacts: @@ -386,7 +312,7 @@ def ab_ABContactUpdate(req: web.Request, header: Any, action: Any, bs: BackendSe else: contact_uuid = find_element(contact, 'contactId') if not contact_uuid: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_uuid is not user.uuid: ctc = detail.contacts.get(contact_uuid) if not ctc: @@ -395,11 +321,11 @@ def ab_ABContactUpdate(req: web.Request, header: Any, action: Any, bs: BackendSe }, status = 500) properties_changed = contact.find('./{*}propertiesChanged') if not properties_changed: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') properties_changed = str(properties_changed).strip().split(' ') for contact_property in properties_changed: if contact_property not in _CONTACT_PROPERTIES: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') for contact_property in properties_changed: if contact_property == 'Anniversary': @@ -411,7 +337,7 @@ def ab_ABContactUpdate(req: web.Request, header: Any, action: Any, bs: BackendSe property = str(property) property = datetime.strptime(property, '%Y/%m/%d') except: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_property == 'ContactBirthDate': assert ctc is not None property = find_element(contact_info, 'birthdate') @@ -420,80 +346,80 @@ def ab_ABContactUpdate(req: web.Request, header: Any, action: Any, bs: BackendSe property = str(property) if property != '0001-01-01T00:00:00': if not property.endswith('Z'): - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') property = iso_parser.parse(property) except: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_property == 'ContactLocation': assert ctc is not None contact_locations = contact_info.findall('.//{*}locations/{*}ContactLocation') for contact_location in contact_locations: if str(find_element(contact_location, 'contactLocationType')) not in ('ContactLocationPersonal','ContactLocationBusiness'): - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') location_properties_changed = find_element(contact_location, 'Changes') if location_properties_changed is None: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') location_properties_changed = str(location_properties_changed).strip().split(' ') for location_property in location_properties_changed: if location_property not in _CONTACT_LOCATION_PROPERTIES: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') for location_property in location_properties_changed: if location_property == 'Name' and str(find_element(contact_location, 'contactLocationType')) != 'ContactLocationBusiness': - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_property == 'IsMessengerUser': assert ctc is not None property = find_element(contact_info, 'isMessengerUser') if property is None: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_property == 'ContactEmail': assert ctc is not None contact_emails = contact_info.findall('.//{*}emails/{*}ContactEmail') for contact_email in contact_emails: email_properties_changed = find_element(contact_email, 'propertiesChanged') if email_properties_changed is None: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') email_properties_changed = str(email_properties_changed).strip().split(' ') for email_property in email_properties_changed: if email_property not in _CONTACT_EMAIL_PROPERTIES: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if ( str(find_element(contact_email, 'contactEmailType')) not in ( 'ContactEmailPersonal', 'ContactEmailBusiness', 'ContactEmailMessenger', 'ContactEmailOther', ) ): - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_property == 'ContactPrimaryEmailType': assert ctc is not None email_primary_type = str(find_element(contact_info, 'primaryEmailType')) if email_primary_type not in ('Passport','ContactEmailPersonal','ContactEmailBusiness','ContactEmailOther'): - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_property == 'ContactPhone': assert ctc is not None contact_phones = contact_info.findall('.//{*}phones/{*}ContactPhone') for contact_phone in contact_phones: phone_properties_changed = find_element(contact_phone, 'propertiesChanged') if phone_properties_changed is None: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') phone_properties_changed = str(phone_properties_changed).strip().split(' ') for phone_property in phone_properties_changed: if phone_property not in _CONTACT_PHONE_PROPERTIES: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if ( str(find_element(contact_phone, 'contactPhoneType')) not in ( 'ContactPhonePersonal', 'ContactPhoneBusiness', 'ContactPhoneMobile', 'ContactPhoneFax', 'ContactPhonePager', 'ContactPhoneOther', - ), + ) ): - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_property == 'ContactWebSite': assert ctc is not None contact_websites = contact_info.findall('.//{*}webSites/{*}ContactWebSite') for contact_website in contact_websites: if str(find_element(contact_website, 'contactWebSiteType')) not in ('ContactWebSitePersonal','ContactWebSiteBusiness'): - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if contact_property == 'Annotation': if find_element(contact_info, 'contactType') != 'Me': if ctc is None: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABContactUpdate', 'ContactDoesNotExist') annotations = contact_info.findall('.//{*}annotations/{*}Annotation') for annotation in annotations: name = find_element(annotation, 'Name') @@ -509,7 +435,7 @@ def ab_ABContactUpdate(req: web.Request, header: Any, action: Any, bs: BackendSe else: gtc = GTCAnnotation(int(value)) except ValueError: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if name == 'MSN.IM.BLP': try: if value == '': @@ -517,10 +443,10 @@ def ab_ABContactUpdate(req: web.Request, header: Any, action: Any, bs: BackendSe else: blp = BLPAnnotation(int(value)) except ValueError: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABContactUpdate') if find_element(contact_info, 'contactType') != 'Me': if ctc is None: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABContactUpdate', 'ContactDoesNotExist') for contact in contacts: updated = False ctc = None @@ -766,6 +692,60 @@ def ab_ABContactUpdate(req: web.Request, header: Any, action: Any, bs: BackendSe 'session_id': util.misc.gen_uuid(), }) + +def ab_UpdateContact(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: + from lxml import etree + from lxml.objectify import fromstring as parse_xml + + backend: Backend = req.app['backend'] + cachekey = secrets.token_urlsafe(172) + + user = bs.user + detail = user.detail + assert detail is not None + + contact_uuid = str(find_element(action, 'contactId') or '') + contact_info = action.find('./{*}contactInfo') + if contact_info is None: + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/UpdateContact') + if contact_uuid != user.uuid and contact_uuid not in detail.contacts: + return render(req, 'msn:abservice/Fault.contactdoesnotexist.xml', { + 'action_str': 'UpdateContact', + }, status = 500) + + properties_changed = str(find_element(contact_info, 'PropertiesChanged') or '').strip().split() + + if 'TrustLevel' in properties_changed: + try: + trust_level = int(find_element(contact_info, 'TrustLevel')) + except (TypeError, ValueError): + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/UpdateContact') + user.settings['TrustLevels'] = { **(user.settings.get('TrustLevels') or {}), contact_uuid: trust_level } + backend._mark_modified(user) + + properties_changed = [contact_property for contact_property in properties_changed if contact_property != 'TrustLevel'] + if properties_changed: + contact_info_elm = etree.fromstring(etree.tostring(contact_info)) + for elm in contact_info_elm.findall('{*}PropertiesChanged') + contact_info_elm.findall('{*}TrustLevel'): + contact_info_elm.remove(elm) + if contact_uuid == user.uuid and contact_info_elm.find('{*}contactType') is None: + # `ABContactUpdate` addresses the user's own contact by its type + etree.SubElement(contact_info_elm, '{http://www.msn.com/webservices/AddressBook}contactType').text = 'Me' + response = ab_ABContactUpdate(req, header, parse_xml( + b'00000000-0000-0000-0000-000000000000' + + '{}'.format(contact_uuid).encode('utf-8') + etree.tostring(contact_info_elm) + + '{}'.format(' '.join(properties_changed)).encode('utf-8') + + b'' + ), bs) + if response.status != 200: + return response + + return render(req, 'msn:abservice/UpdateContactResponse.xml', { + 'cachekey': cachekey, + 'host': settings.ADDRESSBOOK_HOST, + 'session_id': util.misc.gen_uuid(), + }) + def ab_ABGroupAdd(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: cachekey = secrets.token_urlsafe(172) @@ -780,7 +760,7 @@ def ab_ABGroupAdd(req: web.Request, header: Any, action: Any, bs: BackendSession ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupAdd', 'ABDoesNotExist') name = find_element(action, 'name') is_favorite = find_element(action, 'IsFavorite') @@ -823,17 +803,17 @@ def ab_ABGroupUpdate(req: web.Request, header: Any, action: Any, bs: BackendSess ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupUpdate', 'ABDoesNotExist') groups = action.findall('.//{*}groups/{*}Group') for group_elm in groups: group_id = str(find_element(group_elm, 'groupId')) if group_id not in detail._groups_by_uuid: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupUpdate', 'GroupDoesNotExist') group_info = group_elm.find('.//{*}groupInfo') properties_changed = find_element(group_elm, 'propertiesChanged') if not properties_changed: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABGroupUpdate') properties_changed = str(properties_changed).strip().split(' ') #for contact_property in properties_changed: # if contact_property not in _CONTACT_PROPERTIES: @@ -842,7 +822,7 @@ def ab_ABGroupUpdate(req: web.Request, header: Any, action: Any, bs: BackendSess if contact_property == 'GroupName': name = str(find_element(group_info, 'name')) if name is None: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABGroupUpdate') elif name == '(No Group)': return render(req, 'msn:abservice/Fault.groupalreadyexists.xml', { 'action_str': 'ABGroupUpdate', @@ -859,7 +839,7 @@ def ab_ABGroupUpdate(req: web.Request, header: Any, action: Any, bs: BackendSess is_favorite = find_element(group_info, 'IsFavorite') if is_favorite is not None: if not isinstance(is_favorite, bool): - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABGroupUpdate') for group_elm in groups: group_id = str(find_element(group_elm, 'groupId')) group_info = group_elm.find('.//{*}groupInfo') @@ -893,12 +873,12 @@ def ab_ABGroupDelete(req: web.Request, header: Any, action: Any, bs: BackendSess ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupDelete', 'ABDoesNotExist') group_ids = [str(group_id) for group_id in action.findall('.//{*}groupFilter/{*}groupIds/{*}guid')] for group_id in group_ids: if group_id not in detail._groups_by_uuid: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupDelete', 'GroupDoesNotExist') for group_id in group_ids: bs.me_group_remove(group_id) return render(req, 'msn:abservice/ABGroupDeleteResponse.xml', { @@ -922,35 +902,39 @@ def ab_ABGroupContactAdd(req: web.Request, header: Any, action: Any, bs: Backend ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupContactAdd', 'ABDoesNotExist') group_ids = [str(group_id) for group_id in action.findall('.//{*}groupFilter/{*}groupIds/{*}guid')] for group_id in group_ids: if group_id not in detail._groups_by_uuid: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupContactAdd', 'GroupDoesNotExist') if find_element(action, 'contactInfo') is not None: email = find_element(action, 'passportName') if email is None: email = find_element(action, 'email') if email is None: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ABGroupContactAdd') contact_uuid = backend.util_get_uuid_from_email(email) - assert contact_uuid is not None + if contact_uuid is None: + return render(req, 'msn:abservice/Fault.invaliduser.xml', { + 'action_str': 'ABGroupContactAdd', + 'email': email, + }, status = 500) ctc = detail.contacts.get(contact_uuid) if ctc is not None and ctc.lists & models.ContactList.FL: for group_id in group_ids: for group_contact_entry in ctc._groups: if group_contact_entry.uuid == group_id: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupContactAdd', 'ContactAlreadyExists') for group_id in group_ids: try: ctc, _ = bs.me_contact_add(contact_uuid, models.ContactList.FL, group_id = group_id, name = email) except: - return web.HTTPInternalServerError() + return server_fault(req, 'http://www.msn.com/webservices/AddressBook/ABGroupContactAdd') else: contact_uuid = find_element(action, 'contactId') assert contact_uuid is not None @@ -964,7 +948,7 @@ def ab_ABGroupContactAdd(req: web.Request, header: Any, action: Any, bs: Backend for group_id in group_ids: for group_contact_entry in ctc._groups: if group_contact_entry.uuid == group_id: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupContactAdd', 'ContactAlreadyExists') for group_id in group_ids: bs.me_group_contact_add(group_id, ctc.head.uuid) @@ -989,13 +973,13 @@ def ab_ABGroupContactDelete(req: web.Request, header: Any, action: Any, bs: Back ab_id = '00000000-0000-0000-0000-000000000000' if ab_id != '00000000-0000-0000-0000-000000000000': - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupContactDelete', 'ABDoesNotExist') group_ids = [str(group_id) for group_id in action.findall('.//{*}groupFilter/{*}groupIds/{*}guid')] for group_id in group_ids: if group_id not in detail._groups_by_uuid: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupContactDelete', 'GroupDoesNotExist') contact_uuid = find_element(action, 'contactId') ctc = detail.contacts.get(contact_uuid or '') @@ -1008,7 +992,7 @@ def ab_ABGroupContactDelete(req: web.Request, header: Any, action: Any, bs: Back ctc_in_group = True break if not ctc_in_group: - return web.HTTPInternalServerError() + return abch_fault(req, 'ABGroupContactDelete', 'ContactDoesNotExist') for group_id in group_ids: bs.me_group_contact_remove(group_id, ctc.head.uuid) else: @@ -1021,121 +1005,6 @@ def ab_ABGroupContactDelete(req: web.Request, header: Any, action: Any, bs: Back 'session_id': util.misc.gen_uuid(), }) -def sharing_CreateCircle(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: - backend: Backend = req.app['backend'] - cachekey = secrets.token_urlsafe(172) - - user = bs.user - - if ( - find_element(action, 'Domain') == 1 - and find_element(action, 'HostedDomain') == 'live.com' - and find_element(action, 'Type') == 2 - and isinstance(find_element(action, 'IsPresenceEnabled'), bool) - ): - membership_access = int(find_element(action, 'MembershipAccess')) - name = str(find_element(action, 'DisplayName')) - owner_friendly = str(find_element(action, 'PublicDisplayName')) - - circle = bs.me_create_circle(name, owner_friendly, membership_access) - - backend.loop.create_task(_dispatch_circle_created(backend, user, circle)) - - return render(req, 'msn:sharing/CreateCircleResponse.xml', { - 'cachekey': cachekey, - 'host': settings.ADDRESSBOOK_HOST, - 'session_id': util.misc.gen_uuid(), - 'chat_id': circle.chat_id, - }) - - return web.HTTPInternalServerError() - -def ab_CreateContact(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: - backend: Backend = req.app['backend'] - now_str = util.misc.date_format(datetime.utcnow()) - cachekey = secrets.token_urlsafe(172) - - # Used as a step in Circle invites, but also used for regular contact adds in WLM 2011/2012 - user = bs.user - detail = user.detail - assert detail is not None - - ab_id = find_element(action, 'ABId') - if ab_id is not None: - ab_id = str(ab_id) - else: - ab_id = '00000000-0000-0000-0000-000000000000' - - chat_id = ab_id[-12:] - circle = backend.user_service.get_circle(chat_id) - - caller_membership = circle.memberships.get(user.uuid) - if caller_membership is None or caller_membership.role not in (models.CircleRole.Admin,models.CircleRole.AssistantAdmin): - return web.HTTPInternalServerError() - - contact_email = find_element(action, 'Email') - contact_uuid = backend.util_get_uuid_from_email(contact_email) - - if contact_uuid is None: - return render(req, 'msn:abservice/Fault.invaliduser.xml', { - 'action_str': 'CreateContact', - 'email': contact_email, - }, status = 500) - head = backend._load_user_record(contact_uuid) - if head is None: - return render(req, 'msn:abservice/Fault.invaliduser.xml', { - 'action_str': 'CreateContact', - 'email': contact_email, - }, status = 500) - - membership = circle.memberships.get(head.uuid) - - if ( - membership is not None and ( - membership.state == models.CircleState.Rejected - or (membership.role == models.CircleRole.Member and membership.state == models.CircleState.Empty) - ) - ): - bs.me_change_circle_membership(circle, head, role = models.CircleRole.Empty, state = models.CircleState.Empty) - else: - if circle: - try: - bs.me_add_user_to_circle(circle, head) - except error.MemberAlreadyInCircle: - return render(req, 'msn:abservice/Fault.contactalreadyexists.xml', { - 'action_str': 'CreateContact', - }, status = 500) - except: - return web.HTTPInternalServerError() - else: - add_ctc = False - - ctc = detail.contacts.get(contact_uuid) - if ctc is not None: - if not ctc.lists & models.ContactList.FL: - add_ctc = True - else: - add_ctc = True - - if add_ctc: - try: - bs.me_contact_add(contact_uuid, models.ContactList.FL, name = email, nickname = nickname) - except error.ContactListIsFull: - # TODO - return web.HTTPInternalServerError() - except: - pass - - return render(req, 'msn:abservice/CreateContactResponse.xml', { - 'cachekey': cachekey, - 'host': settings.ADDRESSBOOK_HOST, - 'session_id': util.misc.gen_uuid(), - 'ab_id': ab_id, - 'head': head, - 'now': now_str, - 'user': user - }) - def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: backend: Backend = req.app['backend'] now_str = util.misc.date_format(datetime.utcnow()) @@ -1149,7 +1018,7 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen ab_id = str(ab_id) if ab_id is not None else '00000000-0000-0000-0000-000000000000' if not (ab_id == '00000000-0000-0000-0000-000000000000' or (ab_id.startswith('00000000-0000-0000-0009-') and len(ab_id[24:]) == 12)): - return web.HTTPInternalServerError() + return abch_fault(req, 'ManageWLConnection', 'ABDoesNotExist') circle = None invite_message = None @@ -1157,7 +1026,14 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen contact_uuid = find_element(action, 'contactId') assert contact_uuid is not None - head = backend._load_user_record(contact_uuid) if ab_id != '00000000-0000-0000-0000-000000000000' else user + contact_uuid = str(contact_uuid) + + if ab_id != '00000000-0000-0000-0000-000000000000': + head = backend._load_user_record(contact_uuid) + elif contact_uuid.startswith('00000000-0000-0000-0009-'): + head = user + else: + head = backend._load_user_record(contact_uuid) if head is None: return render(req, 'msn:abservice/Fault.contactdoesnotexist.xml', { @@ -1166,7 +1042,7 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen if ab_id == '00000000-0000-0000-0000-000000000000' and contact_uuid.startswith('00000000-0000-0000-0009-'): chat_id = contact_uuid[-12:] - uuid = head.uuid + uuid = user.uuid circle_mode = True elif ab_id.startswith('00000000-0000-0000-0009-'): chat_id = ab_id[-12:] @@ -1175,15 +1051,18 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen if circle_mode: circle = backend.user_service.get_circle(chat_id) - if circle is None or uuid not in circle.memberships: - return web.HTTPInternalServerError() + if circle is None: + return abch_fault(req, 'ManageWLConnection', 'ABDoesNotExist') + if uuid not in circle.memberships: + return abch_fault(req, 'ManageWLConnection', 'MemberDoesNotExist') if find_element(action, 'connection') == True: + # Parse relationship variables; relationshipRole is optional (absent in older clients) try: - relationship_type = models.RelationshipType(find_element(action, 'relationshipType')) - relationship_role = int(find_element(action, 'relationshipRole')) + relationship_type_raw = find_element(action, 'relationshipType') + relationship_role_raw = find_element(action, 'relationshipRole') wl_action = int(find_element(action, 'action')) - except ValueError: + except (ValueError, TypeError): return render(req, 'msn:abservice/ManageWLConnectionResponse.xml', { 'cachekey': cachekey, 'host': settings.ADDRESSBOOK_HOST, @@ -1191,13 +1070,20 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen 'error': 'Relationship variables invalid', }, status=500) - if relationship_type == models.RelationshipType.Circle: - if circle is None: + try: + relationship_type = models.RelationshipType(relationship_type_raw) + except (ValueError, TypeError): + relationship_type = None + relationship_role = int(relationship_role_raw) if relationship_role_raw is not None else None + + if circle_mode: + # All circle operations require a valid Circle relationship type + if relationship_type != models.RelationshipType.Circle: return render(req, 'msn:abservice/ManageWLConnectionResponse.xml', { 'cachekey': cachekey, 'host': settings.ADDRESSBOOK_HOST, 'session_id': util.misc.gen_uuid(), - 'error': 'Relationship type not suitable for non-specialized contacts', + 'error': 'Expected Circle relationship type for circle operation', }, status=500) if wl_action == 1: @@ -1244,7 +1130,6 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen for annotation in annotations: name = find_element(annotation, 'Name') value = find_element(annotation, 'Value') - if name == 'MSN.IM.InviteMessage': invite_message = value break @@ -1275,7 +1160,7 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen }, status=500) else: error_msg = 'RelationshipRole `{role}` not currently supported for relationship type `{type}`'.format( - role=relationship_role, type=relationship_type.name + role=relationship_role, type=relationship_type.name, ) return render(req, 'msn:abservice/ManageWLConnectionResponse.xml', { 'cachekey': cachekey, @@ -1312,11 +1197,33 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen 'error': '`Circle` does not currently exist', }, status=500) else: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ManageWLConnection') else: - return web.HTTPInternalServerError() + # regular contact add/remove + if wl_action == 1: + add_ctc = False + ctc = detail.contacts.get(contact_uuid) + if ctc is not None: + if not ctc.lists & models.ContactList.FL: + add_ctc = True + else: + add_ctc = True + if add_ctc: + try: + bs.me_contact_add(contact_uuid, models.ContactList.FL, name=head.email) + except error.ContactListIsFull: + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ManageWLConnection', 'Contact list is full') + except: + pass + elif wl_action == 2: + try: + bs.me_contact_remove(contact_uuid, models.ContactList.FL) + except: + pass + else: + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ManageWLConnection') else: - return web.HTTPInternalServerError() + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/ManageWLConnection') return render(req, 'msn:abservice/ManageWLConnectionResponse.xml', { 'cachekey': cachekey, @@ -1328,7 +1235,7 @@ def ab_ManageWLConnection(req: web.Request, header: Any, action: Any, bs: Backen 'CircleRole': models.CircleRole, 'CircleState': models.CircleState, 'now': now_str, - 'user': user + 'user': user, }) def ab_BreakConnection(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: @@ -1343,44 +1250,42 @@ def ab_BreakConnection(req: web.Request, header: Any, action: Any, bs: BackendSe ab_id = str(ab_id) if ab_id is not None else '00000000-0000-0000-0000-000000000000' if not (ab_id == '00000000-0000-0000-0000-000000000000' or (ab_id.startswith('00000000-0000-0000-0009-') and len(ab_id[24:]) == 12)): - return web.HTTPInternalServerError() - - circle = None - chat_id = None - circle_mode = False + return abch_fault(req, 'BreakConnection', 'ABDoesNotExist') contact_uuid = find_element(action, 'contactId') assert contact_uuid is not None + contact_uuid = str(contact_uuid) - if ab_id != '00000000-0000-0000-0000-000000000000': - # Right now, this only supports requests from the calling user - if contact_uuid != user.uuid: - return web.HTTPInternalServerError() - head = user - else: - head = None - - if head is None: - return render(req, 'msn:abservice/Fault.contactdoesnotexist.xml', { - 'action_str': 'BreakConnection', - }, status=500) + circle_mode = False + chat_id = None if ab_id.startswith('00000000-0000-0000-0009-'): + # Circle-AB leave: the caller must be the contact being removed + if contact_uuid != user.uuid: + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/BreakConnection', 'Access Denied') chat_id = ab_id[-12:] - uuid = contact_uuid + circle_mode = True + elif contact_uuid.startswith('00000000-0000-0000-0009-'): + # Default-AB with circle contactId: alternate leave form + chat_id = contact_uuid[-12:] circle_mode = True if circle_mode: circle = backend.user_service.get_circle(chat_id) - if circle is None or uuid not in circle.memberships: - return web.HTTPInternalServerError() - + if circle is None: + return abch_fault(req, 'BreakConnection', 'ABDoesNotExist') + if user.uuid not in circle.memberships: + return abch_fault(req, 'BreakConnection', 'MemberDoesNotExist') try: bs.me_leave_circle(circle) except Exception: - return web.HTTPInternalServerError() - + return server_fault(req, 'http://www.msn.com/webservices/AddressBook/BreakConnection') backend.loop.create_task(_dispatch_circle_left(backend, user, circle)) + else: + try: + bs.me_contact_remove(contact_uuid, models.ContactList.FL) + except: + pass return render(req, 'msn:abservice/BreakConnectionResponse.xml', { 'cachekey': cachekey, @@ -1388,11 +1293,6 @@ def ab_BreakConnection(req: web.Request, header: Any, action: Any, bs: BackendSe 'session_id': util.misc.gen_uuid(), }) -async def _dispatch_circle_created(backend: Backend, user: models.User, circle: models.Circle) -> None: - await asyncio.sleep(0.04) - for sess in backend.util_get_sessions_by_user(user): - sess.evt.on_circle_created(circle) - async def _dispatch_circle_invite_status(backend: Backend, user: models.User, circle: models.Circle, accepted: bool) -> None: await asyncio.sleep(0.04) if accepted: diff --git a/front/msn/http/appdirdb/app/en-US/games.mess.be-morris.json b/front/msn/http/appdirdb/app/en-US/games.mess.be-morris.json index 4fd6ef1..21e90cc 100644 --- a/front/msn/http/appdirdb/app/en-US/games.mess.be-morris.json +++ b/front/msn/http/appdirdb/app/en-US/games.mess.be-morris.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Nine Men's Morris", "description": "A 9 pieces Tic-Tac-Toe spin-off. Originally developed by Doron for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/morris/index.en-us.html", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/morris/imgs/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/morris/index.en-us.html", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/morris/imgs/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/he-IL/games.mess.be-morris.json b/front/msn/http/appdirdb/app/he-IL/games.mess.be-morris.json index 91ea8e4..f7ef182 100644 --- a/front/msn/http/appdirdb/app/he-IL/games.mess.be-morris.json +++ b/front/msn/http/appdirdb/app/he-IL/games.mess.be-morris.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Nine Men's Morris", "description": "A 9 pieces Tic-Tac-Toe spin-off (Hebrew). Originally developed by Doron for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/morris/index.he-il.html", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/morris/imgs/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/morris/index.he-il.html", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/morris/imgs/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/games.mess.be-backgammon.json b/front/msn/http/appdirdb/app/none/games.mess.be-backgammon.json index de351f3..0d7d760 100644 --- a/front/msn/http/appdirdb/app/none/games.mess.be-backgammon.json +++ b/front/msn/http/appdirdb/app/none/games.mess.be-backgammon.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Backgammon", "description": "The game of luck and skill. Originally developed by Koen for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/backgammon/backgammon.htm", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/backgammon/images/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/backgammon/backgammon.htm", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/backgammon/images/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/games.mess.be-battleships.json b/front/msn/http/appdirdb/app/none/games.mess.be-battleships.json index 357a8a8..91af0fe 100644 --- a/front/msn/http/appdirdb/app/none/games.mess.be-battleships.json +++ b/front/msn/http/appdirdb/app/none/games.mess.be-battleships.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Battleships", "description": "Sink your opponent's fleet. Originally developed by Koen for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/battleships/battleships.htm", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/battleships/images/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/battleships/battleships.htm", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/battleships/images/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/games.mess.be-chess.json b/front/msn/http/appdirdb/app/none/games.mess.be-chess.json index d2f19b3..eb40476 100644 --- a/front/msn/http/appdirdb/app/none/games.mess.be-chess.json +++ b/front/msn/http/appdirdb/app/none/games.mess.be-chess.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Chess", "description": "The king's game. Originally developed by Koen for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/chess/chess.htm", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/chess/images/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/chess/chess.htm", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/chess/images/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/games.mess.be-connect4.json b/front/msn/http/appdirdb/app/none/games.mess.be-connect4.json index 0cf8675..863ad2a 100644 --- a/front/msn/http/appdirdb/app/none/games.mess.be-connect4.json +++ b/front/msn/http/appdirdb/app/none/games.mess.be-connect4.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Connect 4", "description": "Four in a row. Originally developed by Koen for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/connect4/connect4.htm", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/connect4/images/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/connect4/connect4.htm", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/connect4/images/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/games.mess.be-memory.json b/front/msn/http/appdirdb/app/none/games.mess.be-memory.json index 8da3766..ec5f8c8 100644 --- a/front/msn/http/appdirdb/app/none/games.mess.be-memory.json +++ b/front/msn/http/appdirdb/app/none/games.mess.be-memory.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Memory", "description": "Find the matching pairs. Originally developed by Koen for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/memory/memory.htm", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/memory/images/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/memory/memory.htm", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/memory/images/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/games.mess.be-reversi.json b/front/msn/http/appdirdb/app/none/games.mess.be-reversi.json index 0573622..c7fab3b 100644 --- a/front/msn/http/appdirdb/app/none/games.mess.be-reversi.json +++ b/front/msn/http/appdirdb/app/none/games.mess.be-reversi.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Reversi", "description": "Also known as Othello. Originally developed by Koen for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/reversi/reversi.htm", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/reversi/images/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/reversi/reversi.htm", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/reversi/images/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/games.mess.be-tetris.json b/front/msn/http/appdirdb/app/none/games.mess.be-tetris.json index b979ea5..96898c3 100644 --- a/front/msn/http/appdirdb/app/none/games.mess.be-tetris.json +++ b/front/msn/http/appdirdb/app/none/games.mess.be-tetris.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Tetris", "description": "The simple, highly addictive, real-time puzzle game. Originally developed by Koen for games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/tetris/tetris.htm", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/tetris/images/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/tetris/tetris.htm", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/tetris/images/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/games.mess.be-yahtzee.json b/front/msn/http/appdirdb/app/none/games.mess.be-yahtzee.json index 19f0ece..97fb09a 100644 --- a/front/msn/http/appdirdb/app/none/games.mess.be-yahtzee.json +++ b/front/msn/http/appdirdb/app/none/games.mess.be-yahtzee.json @@ -5,8 +5,8 @@ "category_id": 102, "name": "Yahtzee", "description": "The famous dice game. Originally developed by Koen of games.mess.be", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/yahtzee/yahtzee.htm", - "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/yahtzee/images/icon.png", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/yahtzee/yahtzee.htm", + "icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/yahtzee/images/icon.png", "type": "dir", "height": 500, "width": 500, diff --git a/front/msn/http/appdirdb/app/none/tic-tac-toe.json b/front/msn/http/appdirdb/app/none/tic-tac-toe.json index fbc39f1..f563ece 100644 --- a/front/msn/http/appdirdb/app/none/tic-tac-toe.json +++ b/front/msn/http/appdirdb/app/none/tic-tac-toe.json @@ -5,7 +5,7 @@ "category_id": 101, "name": "Tic Tac Toe", "description": "Play against your friends in a game of Tic Tac Toe. Originally developed by Microsoft.", - "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/tic-tac-toe/tictactoe.htm", + "url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/tic-tac-toe/tictactoe.htm", "icon_url": null, "type": "dir", "height": 500, diff --git a/front/msn/http/other.py b/front/msn/http/other.py index 1430cb9..f00f388 100644 --- a/front/msn/http/other.py +++ b/front/msn/http/other.py @@ -1,4 +1,4 @@ -from typing import Optional, Any, Tuple +from typing import Optional, Any, Tuple, Literal, List, Dict from datetime import datetime, timedelta from io import BytesIO from email.parser import Parser @@ -6,21 +6,23 @@ from email.header import decode_header from email.utils import parsedate_to_datetime from urllib.parse import unquote, parse_qsl from pathlib import Path -import re, secrets, base64, random, json, mimetypes, uuid, PyRSS2Gen, settings, util.misc +import asyncio, re, secrets, base64, random, json, mimetypes, uuid, PyRSS2Gen, settings, util.misc from markupsafe import Markup from aiohttp import web - + from core import models +from core.user import beacon_enabled from core.backend import Backend, BackendSession -from util.avatar import get_img_type, find_avatar_file -from ..misc import gen_mail_data, format_oim, cid_format, puid_format +from util.avatar import get_img_type, store_photo_file, get_photo_data +from ..misc import gen_mail_data, format_oim, cid_format, puid_format, encode_xml_ne from .util import find_element, get_tag_localname, render, preprocess_soap, unknown_soap, bool_to_str - -LOGIN_PATH = '/login.srf' + +LOGIN_PATH = '/login2.srf' TMPL_DIR = 'front/msn/http/tmpl' ETC_DIR = 'front/msn/etc' PP = 'Passport1.4' - +PHOTO_MAX_SIZE = 10 * 1024 * 1024 + def register(app: web.Application) -> None: util.misc.add_to_jinja_env(app, 'msn', TMPL_DIR, globals = { 'date_format': util.misc.date_format, @@ -29,6 +31,7 @@ def register(app: web.Application) -> None: 'bool_to_str': bool_to_str, 'contact_is_favorite': _contact_is_favorite, 'datetime': datetime, + 'settings': settings }) # MSN >= 5 @@ -57,242 +60,73 @@ def register(app: web.Application) -> None: app.router.add_post('/RST2.srf', lambda req: handle_rst(req, rst2 = True)) # MSN >= 8 - app.router.add_post('/storageservice/SchematizedStore.asmx', handle_storageservice) app.router.add_post('/ppsecure/sha1auth.srf', handle_sha1auth) app.router.add_post('/rsi/rsi.asmx', handle_rsi) app.router.add_post('/OimWS/oim.asmx', handle_oim) app.router.add_get('/svcs/msn-video-feeds/', handle_videofeed) app.router.add_get('/svcs/feed', lambda req: handle_videofeed(req, get_videos = True)) - + # MSN >= 14 app.router.add_post('/whatsnew/whatsnewservice.asmx', handle_whatsnew) app.router.add_get('/svcs/tab={id}', handle_tabs_newer) - + # MSN >= 15 app.router.add_post('/sqm/messenger/sqmserver.dll', handle_blankok) app.router.add_post('/sqm/WindowsLive/sqmserver.dll', handle_blankok) app.router.add_post('/uploaddata.aspx', handle_blankok) app.router.add_get('/ppcrlcheck.srf', handle_ppcrlcheck) - app.router.add_post('/profile/profile.asmx', handle_blankok) # TODO: do the thing + app.router.add_post('/profile/profile.asmx', handle_profile) app.router.add_get(r'/~Live.ConfigServer/{junk:.*}/~op-GetClientConfig/{tail:.*}', handle_msgrconfig16) app.router.add_get(r'/~Live.ConfigServer.SuiteUpdate/{tail:.*}', handle_suiteupdate) app.router.add_get(r'/~Live.ConfigServer.PSA/{tail:.*}', handle_socialint) app.router.add_get('/svcs/GameBrowser', handle_gamebrowser) - + app.router.add_post('/Users({cid})/Status', handle_user_status) + app.router.add_post('/Users({cid})/files/{folder}', handle_user_files) + app.router.add_get('/photos/{uuid}/{name}', handle_photo) + # Misc app.router.add_get('/{i}meen_{locale}/{id}', handle_msn_redirect) - + async def handle_blankok(req: web.Request) -> web.Response: return web.Response(status = 200) - -async def handle_storageservice(req: web.Request) -> web.Response: + +async def handle_profile(req: web.Request) -> web.Response: backend = req.app['backend'] - header, action, bs, token = await preprocess_soap(req) - assert bs is not None - soapaction = (req.headers.get('SOAPAction') or '') - if soapaction.startswith('"') and soapaction.endswith('"'): - soapaction = soapaction[1:-1] - storage_ns = ('w10' if soapaction.startswith('http://www.msn.com/webservices/storage/w10/') else '2008') + header, action, bs, token = await preprocess_soap(req) # was missing entirely + user = _get_user_from_token(backend, bs, token) + if user is None: + raise web.HTTPInternalServerError() + action_str = get_tag_localname(action) now_str = util.misc.date_format(datetime.utcnow()) - user = bs.user cachekey = secrets.token_urlsafe(172) - - cid = cid_format(user.uuid) - - if action_str == 'GetProfile': - roaming_info = backend.user_service.get_roaming_info(user) - assert roaming_info is not None - # Resolve the active avatar using the md5 stored in users.avatar. - # find_avatar_file returns None if no avatar has been uploaded yet. - avatar_md5 = user.avatar - mime = None - image_size = 0 - image_thumb_size = 0 + if action_str in ('Get', 'GetMany'): + heads = { cid_format(head.uuid, decimal = True): head for head in [user] + [ctc.head for ctc in backend._load_detail(user).contacts.values()] } + if action_str == 'Get': + requested = [(heads.get(str(find_element(action, 'V1'))) or user, str(find_element(action, 'V2')))] + else: + requested = [(heads[str(v1)], None) for v1 in action.findall('.//{*}ProfileId/{*}V1') if str(v1) in heads] - if avatar_md5: - full_file = find_avatar_file(user.uuid, avatar_md5, small=False) - thumb_file = find_avatar_file(user.uuid, avatar_md5, small=True) + profiles = [] # type: List[Dict[str, Any]] + for head, puid in requested: + roaming_info = backend.user_service.get_roaming_info(head) + if roaming_info is None: continue + profiles.append({ 'user': head, 'cid': cid_format(head.uuid), 'puid': puid, 'roaming_info': roaming_info }) + if not profiles and action_str == 'Get': + raise web.HTTPInternalServerError() - if full_file and full_file.is_file(): - ext = full_file.suffix.lstrip('.').lower() - mime = ext - image_size = full_file.stat().st_size - - if thumb_file and thumb_file.is_file(): - image_thumb_size = thumb_file.stat().st_size - - return render(req, 'msn:storageservice/GetProfileResponse.xml', { - 'storage_ns': storage_ns, + return render(req, 'msn:profile/ProfileResponse.xml', { + 'action': action_str, + 'profiles': profiles, 'cachekey': cachekey, - 'cid': cid, 'pptoken1': token, - 'user': user, 'now': now_str, - 'mime': mime, - 'size_static': image_size, - 'size_small': image_thumb_size, - 'roaming_info': roaming_info, 'host': settings.USERSTORAGE_HOST, }) - if action_str == 'FindDocuments': - # TODO: FindDocuments - return render(req, 'msn:storageservice/FindDocumentsResponse.xml', { - 'storage_ns': storage_ns, - 'cachekey': cachekey, - 'cid': cid, - 'pptoken1': token, - 'user': user, - }) - if action_str == 'UpdateProfile': - delete_psm = False - delete_name = False - delete_avatar = False - - # TODO: More properties? - - # Update to roaming name/message - # ``` - # - # - # 862d987eb60b7a63!106 - # - # Update - # Society is betrayal - # Prosperity is the best medicine. :) - # - # - # - # ``` - - # Remove roaming message - # ``` - # - # - # bb4542ce2eacdbde!106 - # - # Update - # %walkingphas3r% - # 0 - # - # - # - # - # true - # - # - # - # ``` - - expression_profile = find_element(action, 'ExpressionProfile') - name = find_element(expression_profile, 'DisplayName') - message = find_element(expression_profile, 'PersonalStatus') - - attributes_to_delete = find_element(action, 'profileAttributesToDelete/ExpressionProfileAttributes') - if attributes_to_delete is not None: - # `PersonalStatus` and `DisplayName` is the only known attribute that has the ability to be deleted - delete_psm = find_element(attributes_to_delete, 'PersonalStatus') or False - assert isinstance(delete_psm, bool) - delete_name = find_element(attributes_to_delete, 'DisplayName') or False - assert isinstance(delete_name, bool) - - name = find_element(action, 'DisplayName') - message = find_element(action, 'PersonalStatus') - - if name: - backend.user_service.save_single_roaming(user, { 'name': name }) - if message and not delete_psm: - backend.user_service.save_single_roaming(user, { 'message': message }) - - if delete_psm: - backend.user_service.save_single_roaming(user, { 'message': '' }) - if delete_name: - backend.user_service.save_single_roaming(user, { 'name': '' }) - - return render(req, 'msn:storageservice/UpdateProfileResponse.xml', { - 'storage_ns': storage_ns, - 'cachekey': cachekey, - 'cid': cid, - 'pptoken1': token, - 'user': user - }) - if action_str == 'DeleteRelationships': - # TODO: DeleteRelationships - return render(req, 'msn:storageservice/DeleteRelationshipsResponse.xml', { - 'storage_ns': storage_ns, - 'cachekey': cachekey, - 'cid': cid, - 'pptoken1': token, - 'user': user, - }) - if action_str in ('CreateDocument', 'UpdateDocument'): - op = 'Update' if action_str == 'UpdateDocument' else 'Create' - return handle_document(req, action, op, storage_ns, user, cid, token, backend) - if action_str == 'CreateRelationships': - # TODO: CreateRelationships - return render(req, 'msn:storageservice/CreateRelationshipsResponse.xml', { - 'storage_ns': storage_ns, - 'cachekey': cachekey, - 'cid': cid, - 'pptoken1': token, - 'user': user, - }) - if action_str in { 'ShareItem' }: - # TODO: ShareItem - return unknown_soap(req, header, action, expected = True) + return unknown_soap(req, header, action) - - -def handle_document( - req: web.Request, - action: Any, - op_type: str, # 'Create' or 'Update' - storage_ns: str, - user: models.User, - cid: str, - token: str, - backend: Backend, -) -> web.Response: - streamtype = find_element(action, 'DocumentStreamType') - - if streamtype == 'UserTileStatic': - raw_b64 = find_element(action, 'Data') - if raw_b64: - try: - data = base64.b64decode(raw_b64) - except Exception: - return web.HTTPInternalServerError(text='') - - err = _store_avatar_from_bytes(backend, user, data) - if err is not None: - return err - - return render(req, 'msn:storageservice/{}DocumentResponse.xml'.format(op_type), { - 'storage_ns': storage_ns, - 'cid': cid, - 'pptoken1': token, - 'user': user, - }) - - -def _store_avatar_from_bytes( - backend: Backend, - user: models.User, - data: bytes, -) -> Optional[web.Response]: - ext = get_img_type(data) - if ext is None: - return web.HTTPInternalServerError(text='AZUL: Unsupported image format') - - try: - backend.user_service.save_avatar(user, data, ext) - except Exception: - return web.HTTPInternalServerError(text='') - - return None - - + async def handle_sha1auth(req: web.Request) -> web.Response: post = await req.post() @@ -305,11 +139,11 @@ async def handle_sha1auth(req: web.Request) -> web.Response: return web.HTTPInternalServerError() return web.HTTPFound(token_fields['ru']) - + async def handle_ppcrlcheck(req: web.Request) -> web.Response: response = '\r\n\t\r\n\t\r\n' return web.HTTPOk(body=response) - + async def handle_rsi(req: web.Request) -> web.Response: _, action, bs, token = await preprocess_soap_rsi(req) @@ -345,7 +179,7 @@ async def handle_rsi(req: web.Request) -> web.Response: return render(req, 'msn:oim/DeleteMessagesResponse.xml') return render(req, 'msn:Fault.doesnotexist.xml', { 'action': action_str }) - + async def handle_oim(req: web.Request) -> web.Response: header, _, body_content, bs, _ = await preprocess_soap_oimws(req) soapaction = (req.headers.get('SOAPAction') or '') @@ -472,6 +306,20 @@ async def handle_oim(req: web.Request) -> web.Response: }, status = 500) oim_body_normal = oim_body.strip() oim_body_normal = base64.b64decode(oim_body_normal).decode('utf-8') + if len(oim_body_normal.encode('utf-8')) > OIM_MAX_SIZE: + return render(req, 'msn:oim/Fault.messagetoolarge.xml', { + 'owsns': owsns, + }, status = 500) + + # An offline message is a message like any other: over the sender's rate (or at the maximum warning level) it's + # refused, and its recipient may warn (vote) its sender for it + if not backend.util_message_allowed(user, models.MessageData(sender = user, type = models.MessageType.Chat, text = oim_body_normal)): + return render(req, 'msn:oim/Fault.throttle.xml', { + 'owsns': owsns, + }, status = 500) + recipient_user = backend._load_user_record(recipient_uuid) + if recipient_user is not None: + backend.abuse.track_message(user, recipient_user) backend.user_service.save_oim( bs, recipient_uuid, oim_run_id, host, oim_body_normal, True, from_friendly = friendlyname_str, @@ -486,6 +334,8 @@ async def handle_oim(req: web.Request) -> web.Response: 'seq': oim_msg_seq, 'owsns': owsns, }) + +OIM_MAX_SIZE = 64 * 1024 def _is_on_al(uuid: str, backend: Backend, user: models.User, detail: models.UserDetail) -> bool: contact = detail.contacts.get(uuid) @@ -504,7 +354,7 @@ def _is_on_al(uuid: str, backend: Backend, user: models.User, detail: models.Use if ctc_me is not None and not ctc_me.lists & models.ContactList.BL: return True return False - + async def preprocess_soap_rsi(req: web.Request) -> Tuple[Any, Any, Optional[BackendSession], str]: from lxml.objectify import fromstring as parse_xml @@ -526,7 +376,7 @@ async def preprocess_soap_rsi(req: web.Request) -> Tuple[Any, Any, Optional[Back #if settings.DEBUG: print('Action: {}'.format(get_tag_localname(action))) return header, action, bs, token - + async def preprocess_soap_oimws(req: web.Request) -> Tuple[Any, str, str, Optional[BackendSession], str]: from lxml.objectify import fromstring as parse_xml @@ -545,28 +395,175 @@ async def preprocess_soap_oimws(req: web.Request) -> Tuple[Any, str, str, Option body_content = str(find_element(root, 'Body/Content')).replace('\r\n', '\n') return header, body_msgtype, body_content, bs, token - -# TODO: Make this actually accurate + async def handle_whatsnew(req: web.Request) -> web.Response: - whatsnew = '' - with open('config/whatsnew.json', 'rb') as f: - whatsnew_list = json.loads(f.read()) - f.close() - - if len(whatsnew_list) > 0: - whatsnew_dict = whatsnew_list[0] - with open(TMPL_DIR + '/whatsnew/WhatsNewResponse.xml') as fh: - whatsnew = fh.read() - whatsnew = whatsnew.format( - date=whatsnew_dict['date'], - url=whatsnew_dict['url'], - title=whatsnew_dict['title'], - appName=whatsnew_dict['appName'], - content=whatsnew_dict['content'] - ) - - return web.HTTPOk(content_type = 'text/xml', text = whatsnew) + backend: Backend = req.app['backend'] + header, action, bs, token = await preprocess_soap(req) + user = _get_user_from_token(backend, bs, token) + if user is None: + raise web.HTTPInternalServerError() + action_str = get_tag_localname(action) + if action_str not in ('GetContactsRecentActivity', 'GetBatchRecentActivity'): + return unknown_soap(req, header, action) + + detail = backend._load_detail(user) + if action_str == 'GetContactsRecentActivity': + # The user's own activities, their contacts' and service announcements + publishers = [user] + [ + ctc.head for ctc in detail.contacts.values() if ctc.lists & models.ContactList.FL and not ctc.lists & models.ContactList.BL + ] + if not beacon_enabled(user): + publishers = [] + else: + # Activities of specific people (contact card, own profile) + cids = { cid.text for cid in action.findall('.//{*}Cid') } + publishers = [head for head in [user] + [ctc.head for ctc in detail.contacts.values()] if cid_format(head.uuid, decimal = True) in cids] + + activities = backend.user_service.get_activities( + [head.uuid for head in publishers], int(str(find_element(action, 'count') or 10)), + announcements = (action_str == 'GetContactsRecentActivity'), + ) + + return render(req, 'msn:whatsnew/WhatsNewResponse.xml', { + 'action': action_str, + 'owner_cid': cid_format(user.uuid, decimal = True), + 'locale': str(find_element(action, 'locales/string') or 'en-us'), + 'activities': activities, + 'types': { int(activity.type) for activity in activities }, + 'detail': detail, + 'now': datetime.utcnow(), + }) + +async def handle_user_status(req: web.Request) -> web.Response: + # WLM 2011 shares status messages to "What's New" through the Live Atom API + from lxml.etree import fromstring as parse_xml + + backend: Backend = req.app['backend'] + user, bs = _get_live_api_user(req) + cid = req.match_info['cid'] + + try: + message = parse_xml(await req.read()).findtext('{http://www.w3.org/2005/Atom}title') or '' + except Exception: + raise web.HTTPBadRequest() + + _set_status_message(backend, user, bs, message) + + message_xml = encode_xml_ne(message) + return web.HTTPOk(content_type = 'application/atom+xml', text = ( + '' + f'{req.url}{util.misc.date_format(datetime.utcnow())}' + f'{message_xml}{message_xml}' + f'{encode_xml_ne(user.status.name)}{cid}' + )) + +def _get_live_api_user(req: web.Request) -> Tuple[models.User, Optional[BackendSession]]: + backend: Backend = req.app['backend'] + auth = req.headers.get('Authorization') or '' + token = (auth.split('t=', 1)[1][:20] if 't=' in auth else '') + bs = backend.util_get_sess_by_token(token) + user = _get_user_from_token(backend, bs, token) + if user is None or cid_format(user.uuid, decimal = True) != req.match_info['cid']: + raise web.HTTPUnauthorized() + return user, bs + +def _set_status_message(backend: Backend, user: models.User, bs: Optional[BackendSession], message: str) -> None: + activity_added = backend.user_service.save_single_roaming(user, { 'message': message }) + sessions = backend.util_get_sessions_by_user(user) + if bs is None or bs not in sessions: + bs = (sessions[0] if sessions else None) + if bs is not None and message != bs.user.status.message: + bs.me_update({ 'message': message, 'notify_self': True }) + if activity_added: + backend.notify_whats_new(user) + +async def handle_user_files(req: web.Request) -> web.Response: + from lxml.etree import fromstring as parse_xml, XMLSyntaxError + + backend: Backend = req.app['backend'] + user, _ = _get_live_api_user(req) + cid = req.match_info['cid'] + + if not req.content_type.startswith('multipart/'): + raise web.HTTPUnsupportedMediaType() + entry = None # type: Optional[Any] + data = None # type: Optional[bytes] + try: + reader = await req.multipart() + while True: + part = await reader.next() + if part is None: break + body = await _read_part(part, PHOTO_MAX_SIZE) + if entry is None and 'atom+xml' in (part.headers.get('Content-Type') or ''): + entry = parse_xml(body) + elif data is None: + data = body + except (ValueError, XMLSyntaxError): + raise web.HTTPBadRequest() + if entry is None or not data: + raise web.HTTPBadRequest() + ext = get_img_type(data) + if ext is None: + raise web.HTTPUnsupportedMediaType() + + title = entry.findtext('{http://www.w3.org/2005/Atom}title') or '' + summary = entry.findtext('{http://www.w3.org/2005/Atom}summary') or '' + name = await asyncio.get_running_loop().run_in_executor(None, store_photo_file, user.uuid, data, ext) + media_url = 'https://{}/photos/{}/{}'.format(settings.USERSTORAGE_HOST, user.uuid, name) + if backend.user_service.add_activity(user, models.ActivityType.Photo, title = title, text = summary, url = media_url): + backend.notify_whats_new(user) + + location = '{}/{}'.format(str(req.url).rstrip('/'), name) + entry_url = encode_xml_ne(location) + media_url_xml = encode_xml_ne(media_url) + mime = 'image/' + ext + now_str = util.misc.date_format(datetime.utcnow()) + return web.Response(status = 201, content_type = 'application/atom+xml', headers = { 'Location': location }, text = ( + '' + f'{entry_url}{encode_xml_ne(title)}{encode_xml_ne(summary)}' + f'{now_str}{now_str}' + f'{encode_xml_ne(user.status.name or "")}{cid}' + f'' + f'' + f'photo' + )) + +async def _read_part(part: Any, limit: int) -> bytes: + chunks = [] # type: List[bytes] + size = 0 + while True: + chunk = await part.read_chunk() + if not chunk: break + size += len(chunk) + if size > limit: + raise web.HTTPRequestEntityTooLarge(max_size = limit, actual_size = size) + chunks.append(chunk) + return b''.join(chunks) + +async def handle_photo(req: web.Request) -> web.Response: + # Photos shared as a status, shown in "What's New" + user_uuid = req.match_info['uuid'] + name = req.match_info['name'] + if not (re.fullmatch(r'[0-9a-f-]{36}', user_uuid) and re.fullmatch(r'[0-9a-f]{16}\.(?:jpeg|png|gif)', name)): + raise web.HTTPNotFound() + result = await asyncio.get_running_loop().run_in_executor(None, get_photo_data, user_uuid, name) + if result is None: + raise web.HTTPNotFound() + photo, content_type = result + return web.Response(body = photo, content_type = content_type) + +def _get_user_from_token(backend: Backend, bs: Optional[BackendSession], token: Optional[str]) -> Optional[models.User]: + # Social services are also used before (or without) a notification server session + if bs is not None: + return bs.user + if not token: + return None + tpl = backend.login_auth_service.get_token('ns/login', token) + if tpl is None: + return None + return backend._load_user_record(tpl[0]) + async def handle_today(req: web.Request) -> web.Response: return render(req, 'msn:svcs/MSNToday.html', { 'title': "CrossTalk Today", @@ -574,21 +571,21 @@ async def handle_today(req: web.Request) -> web.Response: 'wlm': req.query.get('wlm') or False, 'windowslive': req.query.get('windowslive') or False }) - + async def handle_gamebrowser(req: web.Request) -> web.Response: return render(req, 'msn:svcs/GameBrowser.html', { 'title': "Game Browser | CrossTalk", }) - + async def handle_portal(req: web.Request) -> web.Response: - return web.HTTPFound(f'http://{settings.TODAY_HOSTs}/start/msn') - + return web.HTTPFound(f'http://{settings.TODAY_HOST}/start/msn') + async def handle_textadredir(req: web.Request) -> web.Response: return web.HTTPFound(f'http://{settings.AD_HOST}/ads/txt') - + async def handle_banneradredir(req: web.Request) -> web.Response: return web.HTTPFound(f'http://{settings.AD_HOST}/ads/banner') - + async def handle_msn_redirect(req: web.Request) -> web.Response: i = req.match_info['i'] id = req.match_info['id'] @@ -600,42 +597,42 @@ async def handle_msn_redirect(req: web.Request) -> web.Response: return web.HTTPFound('/start') return web.HTTPFound('http://g.msn.com{}'.format(req.path_qs)) - + async def handle_msn5ads(req: web.Request) -> web.Response: response = 'False10080' return web.HTTPOk(body=response) - + async def handle_suiteupdate(req: web.Request) -> web.Response: return render(req, 'msn:config/SuiteUpdate.xml') - + async def handle_socialint(req: web.Request) -> web.Response: return render(req, 'msn:config/Config.PSA.xml') - + async def handle_tabs(req: web.Request) -> web.Response: with open('config/tabs.json') as fh: tabs_data = json.load(fh) - + tmpl = req.app['jinja_env'].get_template('msn:svcs/svcs_tabs.xml') tab_tmpl = tmpl.render(tabs=tabs_data) - + return web.HTTPOk(content_type='text/xml', text='\n' + tab_tmpl) - + # TODO: Unify the tabs handlers so spaghetti code isn't a problem async def handle_tabs_newer(req: web.Request) -> web.Response: id = int(req.match_info['id']) - + with open('config/tabs.json') as fh: tabs_data = json.load(fh) - + tab_data = next((tab for tab in tabs_data if tab["id"] == id), None) if not tab_data: return web.HTTPNotFound(text="Tab not found") - + tmpl = req.app['jinja_env'].get_template('msn:svcs/svcs_tabs_newer.xml') tab_tmpl = tmpl.render(tab=tab_data) - + return web.HTTPOk(content_type='text/xml', text=tab_tmpl) - + async def handle_msgrconfig(req: web.Request) -> web.Response: if req.method == 'POST': body = await req.read() # type: Optional[bytes] @@ -645,15 +642,14 @@ async def handle_msgrconfig(req: web.Request) -> web.Response: if msgr_config == 'INVALID_VER': return web.Response(status = 500) return web.HTTPOk(content_type = 'text/xml', text = msgr_config) + +MsgrConfigVariant = Literal['msn', 'wlm8', 'wlm14', 'wlm16'] async def handle_msgrconfig16(req: web.Request) -> web.Response: - body = await req.read() - msgr_config = _get_msgr_config_16(req, body) - return web.HTTPOk(content_type = 'text/xml', text = msgr_config) + return web.HTTPOk(content_type = 'text/xml', text = _render_msgr_config(req, 'wlm16')) def _get_msgr_config(req: web.Request, body: Optional[bytes]) -> str: query = req.query - result = None # type: Optional[str] ver = query.get('ver') or '' if ver: @@ -662,56 +658,28 @@ def _get_msgr_config(req: web.Request, body: Optional[bytes]) -> str: config_ver = ver.split('.', 4) if 8 <= int(config_ver[0]) <= 9: - with open(TMPL_DIR + '/config/MsgrConfig.wlm.8.xml') as fh: - config = fh.read() - with open('config/tabs.json') as fh: - with open(TMPL_DIR + '/svcs/svcs_tabs.xml') as th: - template = th.read() - tabs_data = json.load(fh) - tmpl_before = req.app['jinja_env'].from_string(template) - tab_tmpl = tmpl_before.render(tabs=tabs_data, settings=settings) - result = config.format(tabs = tab_tmpl) + return _render_msgr_config(req, 'wlm8') elif int(config_ver[0]) >= 14: - with open(TMPL_DIR + '/config/MsgrConfig.wlm.14.xml') as fh: - template = fh.read() - with open('config/tabs.json') as fh: - tabs_data = json.load(fh) - tmpl_before = req.app['jinja_env'].from_string(template) - tmpl = tmpl_before.render(tabs=tabs_data, settings=settings) - result = tmpl + return _render_msgr_config(req, 'wlm14') elif body is not None: - with open(TMPL_DIR + '/config/MsgrConfig.msn.envelope.xml') as fh: - envelope = fh.read() - with open(TMPL_DIR + '/config/MsgrConfig.msn.xml') as fh: - config = fh.read() - with open('config/tabs.json') as fh: - with open(TMPL_DIR + '/svcs/svcs_tabs.xml') as th: - template = th.read() - tabs_data = json.load(fh) - tmpl_before = req.app['jinja_env'].from_string(template) - tab_tmpl = tmpl_before.render(tabs=tabs_data) - result = envelope.format(MsgrConfig = config.format(tabs = tab_tmpl, settings = settings)) + # MSN Messenger 6.0 - 7.5 only use the SOAP `GetClientConfig` action + return _render_msgr_config(req, 'msn', soap = True) - return result or '' + return '' -def _get_msgr_config_16(req: web.Request, body: Optional[bytes]) -> str: - with open(TMPL_DIR + '/config/MsgrConfig.wlm.16.xml') as fh: - template = fh.read() +def _render_msgr_config(req: web.Request, variant: MsgrConfigVariant, *, soap: bool = False) -> str: with open('config/tabs.json') as fh: tabs_data = json.load(fh) - tmpl_before = req.app['jinja_env'].from_string(template) - tmpl = tmpl_before.render(tabs=tabs_data, settings=settings) - result = tmpl - - return result or '' - + tmpl = req.app['jinja_env'].get_template('msn:config/MsgrConfig.xml') + return tmpl.render(variant = variant, soap = soap, tabs = tabs_data, settings = settings) + PassportURLs = 'PassportURLs' - + async def handle_nexus(req: web.Request) -> web.Response: return web.HTTPOk(headers = { PassportURLs: 'DALogin=https://{}{}'.format(settings.LOGIN_HOST, LOGIN_PATH), }) - + async def handle_login(req: web.Request) -> web.Response: tmp = _extract_pp_credentials(req.headers.get('Authorization') or '') if tmp is None: @@ -727,7 +695,7 @@ async def handle_login(req: web.Request) -> web.Response: return web.HTTPOk(headers={ 'Authentication-Info': '{}da-status=success,from-PP=\'{}\''.format(PP, token), }) - + async def handle_not_rst(req: web.Request) -> web.Response: if req.method == 'OPTIONS': return web.HTTPOk(headers = { @@ -750,6 +718,8 @@ async def handle_not_rst(req: web.Request) -> web.Response: token, _, _ = token_tpl headers['X-Token'] = token return web.HTTPOk(headers = headers) + +DA_TOKEN_LIFETIME = 86400 * 30 async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response: from lxml.objectify import fromstring as parse_xml @@ -760,17 +730,27 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response: except: return render(req, 'msn:RST/{}.error.xml'.format('RST2' if rst2 else 'RST')) - email = find_element(root, 'Username') - pwd = str(find_element(root, 'Password')) - - if email is None or pwd is None: - return render(req, 'msn:RST/{}.error.xml'.format('RST2' if rst2 else 'RST')) - backend: Backend = req.app['backend'] - token_tpl = _login(req, email, pwd, binary_secret = True, lifetime = 86400) + email = find_element(root, 'Username') + pwd = str(find_element(root, 'Password')) + # Saved passwords: IDCRL signs in with the `http://Passport.NET/tb` token (`BinaryDAToken0`) from its last sign-in + # instead of a username and password + da_token = find_element(root, 'Security/EncryptedData/CipherData/CipherValue') - uuid = backend.util_get_uuid_from_email(email) + if email is not None: + token_tpl = _login(req, email, pwd, binary_secret = True, lifetime = 86400) + uuid = backend.util_get_uuid_from_email(email) + elif da_token is not None: + uuid = _get_uuid_from_da_token(backend, str(da_token)) + token_tpl = None + if uuid is not None: + user = backend._load_user_record(uuid) + if user is not None: + email = user.email + token_tpl = _create_login_token(backend, uuid, binary_secret = True, lifetime = 86400) + else: + return render(req, 'msn:RST/{}.error.xml'.format('RST2' if rst2 else 'RST')) if token_tpl is not None and uuid is not None: token, expiry, bsecret = token_tpl @@ -783,6 +763,11 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response: cid = cid_format(uuid) puid = puid_format(uuid) + # The client stores this and sends it back to sign in again without the password + da_token_new, _ = backend.login_auth_service.create_token('rst/da', [uuid], lifetime = DA_TOKEN_LIFETIME) + datoken = base64.b64encode(da_token_new.encode('ascii')).decode('ascii') + dabinarysecret = base64.b64encode(secrets.token_bytes(24)).decode('ascii') + assert req.transport is not None peername = req.transport.get_extra_info('peername') if peername: @@ -818,6 +803,8 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response: lastname = "Doe", ip = req.headers.get('X-Forwarded-For', req.remote), pptoken1 = token, + datoken = datoken, + dabinarysecret = dabinarysecret, tokenxml = Markup(''.join(tokenxmls)), ) if rst2 else tmpl.render( puidhex = puid, @@ -829,6 +816,8 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response: lastname = "Doe", ip = req.headers.get('X-Forwarded-For', req.remote), pptoken1 = token, + datoken = datoken, + dabinarysecret = dabinarysecret, tokenxml = Markup(''.join(tokenxmls)), )), ) @@ -836,7 +825,7 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response: return render(req, 'msn:RST/{}.authfailed.xml'.format('RST2' if rst2 else 'RST'), { 'timez': util.misc.date_format(datetime.utcnow()), }) - + async def handle_videofeed(req: web.Request, get_videos: bool = False) -> web.Response: if not get_videos: return render(req, 'msn:svcs/videofeedroot.xml') @@ -869,18 +858,18 @@ async def handle_videofeed(req: web.Request, get_videos: bool = False) -> web.Re language="en-us", lastBuildDate=datetime.now(), ttl=10, - copyright="© 2023 - 2025 the undergr0und", + copyright="© 2023 - 2026 hiden", image=PyRSS2Gen.Image( - url="http://hiden.cc/static/icon/misc/hidnet.png", - title="CrossTalk Video - InDev", - link="http://crosstalk.im" + url="https://static.ugnet.xyz/svc/ct/logo/shadow.svg", + title="CrossTalk Videos", + link="https://crosstalk.im" ), items=rss_items ) - + rss_xml = rss_feed.to_xml(encoding="utf-8") return web.HTTPOk(content_type="text/xml", text=rss_xml) - + def _extract_pp_credentials(auth_str: str) -> Optional[Tuple[str, str]]: if not auth_str: return None @@ -893,7 +882,7 @@ def _extract_pp_credentials(auth_str: str) -> Optional[Tuple[str, str]]: email = auth['sign-in'] pwd = auth['pwd'] return email, pwd - + def _login(req: web.Request, email: str, pwd: str, binary_secret: bool = False, lifetime: int = 30) -> Optional[Tuple[str, datetime, Optional[str]]]: backend: Backend = req.app['backend'] uuid = backend.user_service.login(email, pwd) @@ -901,11 +890,23 @@ def _login(req: web.Request, email: str, pwd: str, binary_secret: bool = False, username = email.lower()[:-len('@crosstalk.im')] uuid = backend.user_service.login_with_username(username, pwd) if uuid is None: return None + return _create_login_token(backend, uuid, binary_secret = binary_secret, lifetime = lifetime) + +def _create_login_token(backend: Backend, uuid: str, *, binary_secret: bool = False, lifetime: int = 30) -> Tuple[str, datetime, Optional[str]]: bsecret = None if binary_secret: bsecret = base64.b64encode(secrets.token_bytes(24)).decode('ascii') return (*backend.login_auth_service.create_token('ns/login', [uuid, bsecret], lifetime = lifetime), bsecret) +def _get_uuid_from_da_token(backend: Backend, cipher_value: str) -> Optional[str]: + try: + token = base64.b64decode(cipher_value).decode('ascii') + except (ValueError, UnicodeDecodeError): + return None + tpl = backend.login_auth_service.get_token('rst/da', token) + if tpl is None: return None + return tpl[0] + def _contact_is_favorite(user_detail: models.UserDetail, ctc: models.Contact) -> bool: groups = user_detail._groups_by_uuid for group in ctc._groups.copy(): diff --git a/front/msn/http/schematizedstore.py b/front/msn/http/schematizedstore.py new file mode 100644 index 0000000..bcedf04 --- /dev/null +++ b/front/msn/http/schematizedstore.py @@ -0,0 +1,253 @@ +from typing import Optional, Any +from datetime import datetime +import secrets, base64, settings, util.misc +from aiohttp import web + +from core import models +from core.backend import Backend +from util.avatar import get_img_type, find_avatar_file +from ..misc import cid_format +from .util import find_element, get_tag_localname, render, preprocess_soap, unknown_soap, storage_fault + +def register(app: web.Application) -> None: + # MSN >= 8 + app.router.add_post('/storageservice/SchematizedStore.asmx', handle_storageservice) + +async def handle_storageservice(req: web.Request) -> web.Response: + backend = req.app['backend'] + header, action, bs, token = await preprocess_soap(req) + assert bs is not None + soapaction = (req.headers.get('SOAPAction') or '') + if soapaction.startswith('"') and soapaction.endswith('"'): + soapaction = soapaction[1:-1] + storage_ns = ('w10' if soapaction.startswith('http://www.msn.com/webservices/storage/w10/') else '2008') + action_str = get_tag_localname(action) + now_str = util.misc.date_format(datetime.utcnow()) + user = bs.user + cachekey = secrets.token_urlsafe(172) + + cid = cid_format(user.uuid) + + if action_str == 'GetProfile': + roaming_info = backend.user_service.get_roaming_info(user) + assert roaming_info is not None + + # Resolve the active avatar using the md5 stored in users.avatar. + # find_avatar_file returns None if no avatar has been uploaded yet. + avatar_md5 = user.avatar + mime = None + image_size = 0 + image_thumb_size = 0 + + if avatar_md5: + full_file = find_avatar_file(user.uuid, avatar_md5, small=False) + thumb_file = find_avatar_file(user.uuid, avatar_md5, small=True) + + if full_file and full_file.is_file(): + ext = full_file.suffix.lstrip('.').lower() + mime = ext + image_size = full_file.stat().st_size + + if thumb_file and thumb_file.is_file(): + image_thumb_size = thumb_file.stat().st_size + + return render(req, 'msn:storageservice/GetProfileResponse.xml', { + 'storage_ns': storage_ns, + 'cachekey': cachekey, + 'cid': cid, + 'pptoken1': token, + 'user': user, + 'now': now_str, + 'mime': mime, + 'size_static': image_size, + 'size_small': image_thumb_size, + 'roaming_info': roaming_info, + 'host': settings.USERSTORAGE_HOST, + }) + if action_str == 'FindDocuments': + # TODO: FindDocuments + return render(req, 'msn:storageservice/FindDocumentsResponse.xml', { + 'storage_ns': storage_ns, + 'cachekey': cachekey, + 'cid': cid, + 'pptoken1': token, + 'user': user, + }) + if action_str == 'UpdateProfile': + delete_psm = False + delete_name = False + delete_avatar = False + + # TODO: More properties? + + # Update to roaming name/message + # ``` + # + # + # 862d987eb60b7a63!106 + # + # Update + # Society is betrayal + # Prosperity is the best medicine. :) + # + # + # + # ``` + + # Remove roaming message + # ``` + # + # + # bb4542ce2eacdbde!106 + # + # Update + # %walkingphas3r% + # 0 + # + # + # + # + # true + # + # + # + # ``` + + expression_profile = find_element(action, 'ExpressionProfile') + name = find_element(expression_profile, 'DisplayName') + message = find_element(expression_profile, 'PersonalStatus') + + attributes_to_delete = find_element(action, 'profileAttributesToDelete/ExpressionProfileAttributes') + if attributes_to_delete is not None: + # `PersonalStatus` and `DisplayName` is the only known attribute that has the ability to be deleted + delete_psm = find_element(attributes_to_delete, 'PersonalStatus') or False + delete_name = find_element(attributes_to_delete, 'DisplayName') or False + if not (isinstance(delete_psm, bool) and isinstance(delete_name, bool)): + return storage_fault(req, storage_ns, action_str, 'GeneralException') + + name = find_element(action, 'DisplayName') + message = find_element(action, 'PersonalStatus') + + if name: + backend.user_service.save_single_roaming(user, { 'name': name }) + if message and not delete_psm: + if backend.user_service.save_single_roaming(user, { 'message': message }): + backend.notify_whats_new(user) + + if delete_psm: + backend.user_service.save_single_roaming(user, { 'message': '' }) + if delete_name: + backend.user_service.save_single_roaming(user, { 'name': '' }) + + return render(req, 'msn:storageservice/UpdateProfileResponse.xml', { + 'storage_ns': storage_ns, + 'cachekey': cachekey, + 'cid': cid, + 'pptoken1': token, + 'user': user + }) + if action_str == 'DeleteRelationships': + # TODO: DeleteRelationships + return render(req, 'msn:storageservice/DeleteRelationshipsResponse.xml', { + 'storage_ns': storage_ns, + 'cachekey': cachekey, + 'cid': cid, + 'pptoken1': token, + 'user': user, + }) + if action_str in ('CreateDocument', 'UpdateDocument'): + op = 'Update' if action_str == 'UpdateDocument' else 'Create' + return handle_document(req, action, op, storage_ns, user, cid, token, backend) + if action_str == 'CreateRelationships': + # TODO: CreateRelationships + return render(req, 'msn:storageservice/CreateRelationshipsResponse.xml', { + 'storage_ns': storage_ns, + 'cachekey': cachekey, + 'cid': cid, + 'pptoken1': token, + 'user': user, + }) + if action_str in { 'ShareItem' }: + # TODO: ShareItem + return unknown_soap(req, header, action, expected = True) + return unknown_soap(req, header, action) + + +def handle_document( + req: web.Request, + action: Any, + op_type: str, # 'Create' or 'Update' + storage_ns: str, + user: models.User, + cid: str, + token: str, + backend: Backend, +) -> web.Response: + streamtype = find_element(action, 'DocumentStreamType') + + if streamtype == 'UserTileStatic': + raw_b64 = find_element(action, 'Data') + if raw_b64: + try: + data = base64.b64decode(raw_b64) + except Exception: + return storage_fault(req, storage_ns, '{}Document'.format(op_type), 'InvalidDocumentStream') + + err = _store_avatar_from_bytes(backend, user, data) + # stupid dumb doodoo hack to make avatar interop work + # we compute a yahoo avatar hash so it can be displayed in yahoo as well + # i'm sure there's a better approach but overengineering is funnier + _yahoo_avatar_gaming(backend, user) + if err is not None: + return storage_fault(req, storage_ns, '{}Document'.format(op_type), err) + + return render(req, 'msn:storageservice/{}DocumentResponse.xml'.format(op_type), { + 'storage_ns': storage_ns, + 'cid': cid, + 'pptoken1': token, + 'user': user, + }) + + +def _store_avatar_from_bytes( + backend: Backend, + user: models.User, + data: bytes, +) -> Optional[str]: + # The storage fault (error code) if the picture can't be kept + ext = get_img_type(data) + if ext is None: + # Not a picture (in a format that can be shown) + return 'InvalidDocumentStream' + + avatar_old = user.avatar + try: + backend.user_service.save_avatar(user, data, ext) + except Exception: + import traceback + traceback.print_exc() + return 'GeneralException' + if user.avatar != avatar_old: + # A different picture is a new activity + backend.notify_whats_new(user) + + return None + +def _yahoo_avatar_gaming(backend: Backend, user: models.User) -> None: + avatar_md5 = getattr(user, 'avatar', None) + if not avatar_md5: + return + import struct, binascii + raw = bytes.fromhex(avatar_md5) + crc = binascii.crc32(raw) & 0xFFFFFFFF + checksum_bytes = str(struct.unpack('i', struct.pack('I', crc))[0]).encode('utf-8') + + detail = user.detail + if detail is None: + return + for ctc in detail.contacts.values(): + if not (ctc.lists & models.ContactList.FL) or ctc.status.is_offlineish(): + continue + for bs_other in backend.util_get_sessions_by_user(ctc.head): + if bs_other.front_data.get('ymsg'): + bs_other.evt.ymsg_on_friend_icon(user.username, bs_other.user.username, checksum_bytes) diff --git a/front/msn/http/sharingservice.py b/front/msn/http/sharingservice.py new file mode 100644 index 0000000..a3e7212 --- /dev/null +++ b/front/msn/http/sharingservice.py @@ -0,0 +1,188 @@ +from typing import Any, Optional +from datetime import datetime +import asyncio, secrets, sys, util.misc, settings + +from aiohttp import web + +from core import models, error +from core.backend import Backend, BackendSession + +from .util import find_element, render, dispatch_abch, abch_fault, schema_fault + +def register(app: web.Application) -> None: + app.router.add_post('/abservice/SharingService.asmx', handle_sharingservice) + +async def handle_sharingservice(req: web.Request) -> web.Response: + return await dispatch_abch(req, sys.modules[__name__], 'sharing') + +def sharing_FindMembership(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: + backend: Backend = req.app['backend'] + now_str = util.misc.date_format(datetime.utcnow()) + user = bs.user + detail = user.detail + cachekey = secrets.token_urlsafe(172) + return render(req, 'msn:sharing/FindMembershipResponse.xml', { + 'cachekey': cachekey, + 'host': settings.ADDRESSBOOK_HOST, + 'session_id': util.misc.gen_uuid(), + 'user': user, + 'detail': detail, + 'ContactList': models.ContactList, + 'lists': [models.ContactList.AL, models.ContactList.BL, models.ContactList.RL], + 'circles': backend.user_service.get_circle_batch(user), + 'now': now_str, + }) + +def sharing_AddMember(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: + backend: Backend = req.app['backend'] + cachekey = secrets.token_urlsafe(172) + + user = bs.user + detail = user.detail + assert detail is not None + + memberships = action.findall('.//{*}memberships/{*}Membership') + for membership in memberships: + email = None # type: Optional[str] + circle_id = None + + lst = models.ContactList.Parse(str(find_element(membership, 'MemberRole'))) + if lst is None: + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/AddMember') + members = membership.findall('.//{*}Members/{*}Member') + for member in members: + member_type = member.get('{http://www.w3.org/2001/XMLSchema-instance}type') + if member_type == 'PassportMember': + if find_element(member, 'Type') == 'Passport' and find_element(member, 'State') == 'Accepted': + email = find_element(member, 'PassportName') + elif member_type == 'EmailMember': + if find_element(member, 'Type') == 'Email' and find_element(member, 'State') == 'Accepted': + email = find_element(member, 'Email') + elif member_type == 'CircleMember': + if find_element(member, 'Type') == 'Circle' and find_element(member, 'State') == 'Accepted': + circle_id = find_element(member, 'CircleId') + if email is None and circle_id is None: + return render(req, 'msn:sharing/Fault.userdoesnotexist.xml', status = 500) + if email is not None: + name = None + contact_uuid = backend.util_get_uuid_from_email(email) + if contact_uuid is None: + return render(req, 'msn:sharing/Fault.userdoesnotexist.xml', status = 500) + ctc = detail.contacts.get(contact_uuid) + if ctc is None: + name = email + + try: + bs.me_contact_add(contact_uuid, lst, name = name) + except error.ContactListIsFull: + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/AddMember', 'Contact list is full') + except: + pass + elif circle_id is not None: + if not (circle_id.startswith('00000000-0000-0000-0009-') and len(circle_id[24:]) == 12): + return render(req, 'msn:sharing/Fault.userdoesnotexist.xml', status = 500) + chat_id = circle_id[-12:] + circle = backend.user_service.get_circle(chat_id) + if circle is None: return abch_fault(req, 'AddMember', 'UserDoesNotExist') + + if lst in (models.ContactList.RL,models.ContactList.PL): + # Only the service puts anyone on those + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/AddMember') + if lst == models.ContactList.BL: + bs.me_block_circle(circle) + return render(req, 'msn:sharing/AddMemberResponse.xml', { + 'cachekey': cachekey, + 'host': settings.ADDRESSBOOK_HOST, + 'session_id': util.misc.gen_uuid(), + }) + +def sharing_DeleteMember(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: + backend: Backend = req.app['backend'] + cachekey = secrets.token_urlsafe(172) + + user = bs.user + detail = user.detail + assert detail is not None + + contact_uuid = None + circle_id = None + + memberships = action.findall('.//{*}memberships/{*}Membership') + for membership in memberships: + lst = models.ContactList.Parse(str(find_element(membership, 'MemberRole'))) + if lst is None: + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/DeleteMember') + members = membership.findall('.//{*}Members/{*}Member') + for member in members: + member_type = member.get('{http://www.w3.org/2001/XMLSchema-instance}type') + if member_type == 'PassportMember': + if find_element(member, 'Type') == 'Passport' and find_element(member, 'State') == 'Accepted': + try: + contact_uuid = find_element(member, 'MembershipId').split('/', 1)[1] + except: + email = find_element(member, 'PassportName') + contact_uuid = backend.util_get_uuid_from_email(email or '') + if contact_uuid is None: + return abch_fault(req, 'DeleteMember', 'MemberDoesNotExist') + # (A circle member is one too, not a kind of Passport member) + elif member_type == 'CircleMember': + if find_element(member, 'Type') == 'Circle' and find_element(member, 'State') == 'Accepted': + circle_id = find_element(member, 'CircleId') + if contact_uuid is not None: + if contact_uuid not in detail.contacts: + return render(req, 'msn:sharing/Fault.memberdoesnotexist.xml', status = 500) + try: + bs.me_contact_remove(contact_uuid, lst) + except: + pass + elif circle_id is not None: + if not (circle_id.startswith('00000000-0000-0000-0009-') and len(circle_id[24:]) == 12): + return abch_fault(req, 'DeleteMember', 'MemberDoesNotExist') + chat_id = circle_id[-12:] + circle = backend.user_service.get_circle(chat_id) + if circle is None: return abch_fault(req, 'DeleteMember', 'MemberDoesNotExist') + + if lst in (models.ContactList.RL,models.ContactList.PL): + # Only the service takes anyone off those; there's nothing to do + continue + if lst == models.ContactList.BL: + bs.me_unblock_circle(circle) + return render(req, 'msn:sharing/DeleteMemberResponse.xml', { + 'cachekey': cachekey, + 'host': settings.ADDRESSBOOK_HOST, + 'session_id': util.misc.gen_uuid(), + }) + +def sharing_CreateCircle(req: web.Request, header: Any, action: Any, bs: BackendSession) -> web.Response: + backend: Backend = req.app['backend'] + cachekey = secrets.token_urlsafe(172) + + user = bs.user + + if ( + find_element(action, 'Domain') == 1 + and find_element(action, 'HostedDomain') == 'live.com' + and find_element(action, 'Type') == 2 + and isinstance(find_element(action, 'IsPresenceEnabled'), bool) + ): + membership_access = int(find_element(action, 'MembershipAccess')) + name = str(find_element(action, 'DisplayName')) + owner_friendly = str(find_element(action, 'PublicDisplayName')) + + circle = bs.me_create_circle(name, owner_friendly, membership_access) + + backend.loop.create_task(_dispatch_circle_created(backend, user, circle)) + + return render(req, 'msn:sharing/CreateCircleResponse.xml', { + 'cachekey': cachekey, + 'host': settings.ADDRESSBOOK_HOST, + 'session_id': util.misc.gen_uuid(), + 'chat_id': circle.chat_id, + }) + + return schema_fault(req, 'http://www.msn.com/webservices/AddressBook/CreateCircle') + +async def _dispatch_circle_created(backend: Backend, user: models.User, circle: models.Circle) -> None: + await asyncio.sleep(0.04) + for sess in backend.util_get_sessions_by_user(user): + sess.evt.on_circle_created(circle) diff --git a/front/msn/http/tmpl/Fault.schema.xml b/front/msn/http/tmpl/Fault.schema.xml new file mode 100644 index 0000000..c46758e --- /dev/null +++ b/front/msn/http/tmpl/Fault.schema.xml @@ -0,0 +1,11 @@ + + + + + soap:Client + {{ faultstring or 'Schema validation error' }} + {{ actor }} + + + + diff --git a/front/msn/http/tmpl/Fault.server.xml b/front/msn/http/tmpl/Fault.server.xml new file mode 100644 index 0000000..41e0d12 --- /dev/null +++ b/front/msn/http/tmpl/Fault.server.xml @@ -0,0 +1,11 @@ + + + + + soap:Server + Server was unable to process request. + {% if actor %}{{ actor }} + {% endif %} + + + diff --git a/front/msn/http/tmpl/RST/RST2.token.xml b/front/msn/http/tmpl/RST/RST2.token.xml index f6d7120..d963804 100644 --- a/front/msn/http/tmpl/RST/RST2.token.xml +++ b/front/msn/http/tmpl/RST/RST2.token.xml @@ -1,3 +1,4 @@ + urn:passport:compact @@ -28,3 +29,4 @@ {% endif %} + diff --git a/front/msn/http/tmpl/RST/RST2.xml b/front/msn/http/tmpl/RST/RST2.xml index 3a0fed6..37d00a5 100644 --- a/front/msn/http/tmpl/RST/RST2.xml +++ b/front/msn/http/tmpl/RST/RST2.xml @@ -72,7 +72,7 @@ http://Passport.NET/STS - Cap26AQZrSyMm2SwwTyJKyqLR9/S+vQWQsaBc5Mv7PwtQDMzup/udOOMMvSu99R284pmiD3IepBXrEMLK5rLrXAf2A6vrP6vYuGA45GCqQdoxusHZcjt9P2B8WyCTVT2cM8jtGqGIfRlU/4WzOLxNrDJwDfOsmilduGAGZfvRPW7/jyXXrnGK7/PWkymX4YDD+ygJfMrPAfvAprvw/HVE6tutKVc9cViTVYy8oHjosQlb8MKn3vKDW1O2ZWQUc47JPl7DkjQaanfNBGe6CL7K1nr6Z/jy7Ay7MjV+KQehmvphSEmCzLrpB4WWn2PdpdTrOcDj+aJfWHeGL4sIPwEKgrKnTQg9QD8CCsm5wew9P/br39OuIfsC6/PFBEHmVThqj0aMxYLRD4K2GoRay6Ab7NftoIP5dnFnclfRxETAoNpTPE2F5Q669QySrdXxBpBSk8GLmdCDMlhiyzSiByrhFQaZRcH8n9i+i289otYuJQ7xPyP19KwT4CRyOiIlh3DSdlBfurMwihQGxN2spU7P4MwckrDKeOyYQhvNm/XWId/oXBqpHbo2yRPiOwL9p1J4AxA4RaJuh77vyhn2lFQaxPDqZd5A8RJjpb2NE2N3UncKLW7GAangdoLbRDMqt51VMZ0la+b/moL61fKvFXinKRHc7PybrG3MWzgXxO/VMKAuXOsB9XnOgl2A524cgiwyg== + {{ datoken }} @@ -87,7 +87,7 @@ - tgoPVK67sU36fQKlGLMgWgTXp7oiaQgE + {{ dabinarysecret }} {{ tokenxml }} diff --git a/front/msn/http/tmpl/_funcs.xml b/front/msn/http/tmpl/_funcs.xml index 745e96f..9885d0b 100644 --- a/front/msn/http/tmpl/_funcs.xml +++ b/front/msn/http/tmpl/_funcs.xml @@ -1,7 +1,7 @@ -{% macro contact_entry(ab_id, ctc, detail, now) %} +{% macro contact_entry(ab_id, ctc, detail, now, trust_level = none) %} {{ ctc.head.uuid }} - {% if ctc.detail.personal_email or ctc.detail.work_phone or ctc.detail.im_email or ctc.detail.other_email %} + {% if ctc.detail.personal_email or ctc.detail.work_email or ctc.detail.im_email or ctc.detail.other_email %} {% if ctc.detail.work_email %} {{ email_entry('ContactEmailBusiness', ctc.detail.work_email) }} @@ -20,7 +20,7 @@ {% if ctc.detail.home_phone or ctc.detail.work_phone or ctc.detail.fax_phone or ctc.detail.pager_phone or ctc.detail.mobile_phone or ctc.detail.other_phone %} {% if ctc.detail.work_phone %} - {{ phone_entry('ContactPhoneBusiness', contact.work_phone) }} + {{ phone_entry('ContactPhoneBusiness', ctc.detail.work_phone) }} {% endif %} {% if ctc.detail.fax_phone %} {{ phone_entry('ContactPhoneFax', ctc.detail.fax_phone) }} @@ -123,6 +123,11 @@ false Unspecified None + {% if trust_level is not none %} + false + false + {{ trust_level }} + {% endif %} false @@ -212,6 +217,9 @@ false Unspecified None + false + false + {{ (user.settings.get('TrustLevels') or {}).get(user.uuid, 0) }} false diff --git a/front/msn/http/tmpl/abservice/ABFindContactsPagedResponse.xml b/front/msn/http/tmpl/abservice/ABFindContactsPagedResponse.xml index e5ccc3e..f0a5b30 100644 --- a/front/msn/http/tmpl/abservice/ABFindContactsPagedResponse.xml +++ b/front/msn/http/tmpl/abservice/ABFindContactsPagedResponse.xml @@ -1,4 +1,4 @@ -{% from 'msn:_funcs.xml' import contact_entry, group_entry, generate_me_entry, ab_properties -%} +{% from 'msn:_funcs.xml' import contact_entry, group_entry, generate_me_entry -%} @@ -13,88 +13,88 @@ - {% if ab_id == '00000000-0000-0000-0000-000000000000' %} - - {% for group in detail._groups_by_uuid.values() %} - {{ group_entry(group, now) }} - {% endfor %} - - {% endif %} + {%- if ab_id == '00000000-0000-0000-0000-000000000000' %} + + {%- for group in detail._groups_by_uuid.values() %} + {{ group_entry(group, now) }} + {%- endfor %} + + {%- endif %} - {% if ab_id == '00000000-0000-0000-0000-000000000000' %} - {% for ctc in detail.contacts.values() %} - {% if ctc.lists.__and__(ContactList.FL) %} - - {{ contact_entry(ab_id, ctc, detail, now) }} - - {% endif %} - {% endfor %} - {% for circle in circles %} - - 00000000-0000-0000-0009-{{ circle.chat_id }} - - Circle - circle - 00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com - false - {% if circle.memberships[user.uuid].role == CircleRole.Admin %}{{ circle.name }}{% else %}00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com{% endif %} - {{ puid_format(user.uuid) }} - {{ cid_format('00000000-0000-0000-0009-' + circle.chat_id, decimal = True) }} - false - false - false - false - false - false - NoDevice - 0001-01-01T00:00:00 - ContactEmailPersonal - ContactLocationPersonal - ContactPhonePersonal - false - true - Unspecified - None - - - 1 - WL - {% if circle.memberships[user.uuid].role != CircleRole.Admin %} - 00000000-0000-0000-0009-{{ circle.chat_id.upper() }} - 00000000-0000-0000-0009-{{ circle.chat_id.upper() }} - {% endif %} - 5 - {{ circle.memberships[user.uuid].state.value }} - {{ now }} - {% if circle.memberships[user.uuid].role == CircleRole.StatePendingOutbound %}4{% else %}0{% endif %} - 0 - {% if circle.memberships[user.uuid].invite_message %} - {{ circle.memberships[user.uuid].invite_message }} - {% endif %} - {% if user.uuid == circle.owner_uuid %}0{% else %}{{ cid_format(circle.memberships[user.uuid].inviter_uuid, decimal = True) }}{% endif %} - {% if circle.memberships[user.uuid].inviter_name %} - {{ circle.memberships[user.uuid].inviter_name }} - {% endif %} - {% if circle.memberships[user.uuid].inviter_email %} - {{ circle.memberships[user.uuid].inviter_email }} - {% endif %} - {{ now }} - {{ now }} - - - - false - false - 0 - - - - false + {%- if ab_id == '00000000-0000-0000-0000-000000000000' %} + {%- for ctc in detail.contacts.values() %} + {%- if ctc.lists.__and__(ContactList.FL) %} + + {{ contact_entry(ab_id, ctc, detail, now, trust_level = (user.settings.get('TrustLevels') or {}).get(ctc.head.uuid, 0)) }} + + {%- endif %} + {%- endfor %} + {%- for circle in circles %} + + 00000000-0000-0000-0009-{{ circle.chat_id }} + + Circle + circle + 00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com + false + {% if circle.memberships[user.uuid].role == CircleRole.Admin %}{{ circle.name }}{% else %}00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com{% endif %} + {{ puid_format(user.uuid) }} + {{ cid_format('00000000-0000-0000-0009-' + circle.chat_id, decimal = True) }} + false + false + false + false + false + false + NoDevice + 0001-01-01T00:00:00 + ContactEmailPersonal + ContactLocationPersonal + ContactPhonePersonal + false + true + Unspecified + None + + + 1 + WL + {%- if circle.memberships[user.uuid].role != CircleRole.Admin %} + 00000000-0000-0000-0009-{{ circle.chat_id.upper() }} + 00000000-0000-0000-0009-{{ circle.chat_id.upper() }} + {%- endif %} + 5 + {{ circle.memberships[user.uuid].state.value }} + {{ now }} + {% if circle.memberships[user.uuid].role == CircleRole.StatePendingOutbound %}4{% else %}0{% endif %} + 0 + {%- if circle.memberships[user.uuid].invite_message %} + {{ circle.memberships[user.uuid].invite_message }} + {%- endif %} + {% if user.uuid == circle.owner_uuid %}0{% else %}{{ cid_format(circle.memberships[user.uuid].inviter_uuid, decimal = True) }}{% endif %} + {%- if circle.memberships[user.uuid].inviter_name %} + {{ circle.memberships[user.uuid].inviter_name }} + {%- endif %} + {%- if circle.memberships[user.uuid].inviter_email %} + {{ circle.memberships[user.uuid].inviter_email }} + {%- endif %} {{ now }} - {{ now }} - 96 - - {% endfor %} + {{ now }} + + + + false + false + 0 + + + + false + {{ now }} + {{ now }} + 96 + + {%- endfor %} {% else %} {% for membership in circle.memberships.values() %} diff --git a/front/msn/http/tmpl/abservice/CreateContactResponse.xml b/front/msn/http/tmpl/abservice/CreateContactResponse.xml index 65c954e..01a708d 100644 --- a/front/msn/http/tmpl/abservice/CreateContactResponse.xml +++ b/front/msn/http/tmpl/abservice/CreateContactResponse.xml @@ -38,7 +38,7 @@ None false false - 0 + {{ trust_level }} diff --git a/front/msn/http/tmpl/abservice/Fault.abch.xml b/front/msn/http/tmpl/abservice/Fault.abch.xml new file mode 100644 index 0000000..7e86f4a --- /dev/null +++ b/front/msn/http/tmpl/abservice/Fault.abch.xml @@ -0,0 +1,20 @@ + + + + + {{ faultcode }} + {{ errorstring }} + http://www.msn.com/webservices/AddressBook/{{ action_str }} + + {{ errorcode }} + {{ errorstring }} + BAYABCHWBB133 + {% if parameter_fault %}{{ parameter_fault }} + {% endif %} + {% if conflict_object_id %}{{ conflict_object_id }} + {% endif %}{{ errorstring }} + + + + + diff --git a/front/msn/http/tmpl/abservice/ManageWLConnectionResponse.xml b/front/msn/http/tmpl/abservice/ManageWLConnectionResponse.xml index 54e2906..af87994 100644 --- a/front/msn/http/tmpl/abservice/ManageWLConnectionResponse.xml +++ b/front/msn/http/tmpl/abservice/ManageWLConnectionResponse.xml @@ -19,15 +19,15 @@ {% endif %} {% if not error %} - {% if ab_id == '00000000-0000-0000-0000-000000000000' %}00000000-0000-0000-0009-{{ circle.chat_id }}{% else %}{{ head.uuid }}{% endif %} + {% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}00000000-0000-0000-0009-{{ circle.chat_id }}{% else %}{{ head.uuid }}{% endif %} - {% if ab_id == '00000000-0000-0000-0000-000000000000' %}Circle{% else %}{% if circle.memberships[head.uuid].state == CircleState.WaitingResponse or circle.memberships[head.uuid].state == CircleState.Rejected or (circle.memberships[head.uuid].role == CircleRole.Empty or circle.memberships[head.uuid].state == CircleState.Empty) %}LivePending{% else %}Live{% endif %}{% endif %} - {% if ab_id == '00000000-0000-0000-0000-000000000000' %}circle{% else %}{{ head.email }}{% endif %} - {% if ab_id == '00000000-0000-0000-0000-000000000000' %}00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com{% else %}{{ head.email }}{% endif %} + {% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}Circle{% elif circle is not none %}{% if circle.memberships[head.uuid].state == CircleState.WaitingResponse or circle.memberships[head.uuid].state == CircleState.Rejected or (circle.memberships[head.uuid].role == CircleRole.Empty or circle.memberships[head.uuid].state == CircleState.Empty) %}LivePending{% else %}Live{% endif %}{% else %}Live{% endif %} + {% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}circle{% else %}{{ head.email }}{% endif %} + {% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com{% else %}{{ head.email }}{% endif %} false - {% if ab_id == '00000000-0000-0000-0000-000000000000' %}{{ circle.name }}{% else %}{{ head.email }}{% endif %} + {% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}{{ circle.name }}{% else %}{{ head.email }}{% endif %} {{ puid_format(user.uuid) }} - {{ cid_format('00000000-0000-0000-0009-' + circle.chat_id, decimal = True) }} + {% if circle is not none %}{{ cid_format('00000000-0000-0000-0009-' + circle.chat_id, decimal = True) }}{% else %}{{ cid_format(head.uuid, decimal = True) }}{% endif %} false false false @@ -40,10 +40,10 @@ ContactLocationPersonal ContactPhonePersonal false - {% if ab_id == '00000000-0000-0000-0000-000000000000' %}true{% else %}false{% endif %} + {% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}true{% else %}false{% endif %} Unspecified None - {% if (ab_id == '00000000-0000-0000-0000-000000000000' or ab_id.startswith('00000000-0000-0000-0009-')) and not (circle.memberships[head.uuid].role == CircleRole.Empty or circle.memberships[head.uuid].state == CircleState.Empty) %} + {% if circle is not none and (ab_id == '00000000-0000-0000-0000-000000000000' or ab_id.startswith('00000000-0000-0000-0009-')) and not (circle.memberships[head.uuid].role == CircleRole.Empty or circle.memberships[head.uuid].state == CircleState.Empty) %} 1 diff --git a/front/msn/http/tmpl/abservice/UpdateContactResponse.xml b/front/msn/http/tmpl/abservice/UpdateContactResponse.xml new file mode 100644 index 0000000..01ae39e --- /dev/null +++ b/front/msn/http/tmpl/abservice/UpdateContactResponse.xml @@ -0,0 +1,15 @@ + + + + + 15.01.1408.0000 + 12r1:{{ cachekey }} + true + {{ host }} + {{ session_id }} + + + + + + diff --git a/front/msn/http/tmpl/config/Config.PSA.xml b/front/msn/http/tmpl/config/Config.PSA.xml index d559eb9..e8ec7c3 100644 --- a/front/msn/http/tmpl/config/Config.PSA.xml +++ b/front/msn/http/tmpl/config/Config.PSA.xml @@ -1792,12 +1792,12 @@ 1140906031 https://{{ settings.USERSTORAGE_HOST }}/static/social/ugnetthumb.gif https://{{ settings.USERSTORAGE_HOST }}/static/social/mini.gif - ^https?://.*\.hiden\.cc/.*$ - mail.ugnet.gay - ugnet.gay - the undergr0und + ^https?://.*\.ugnet\.xyz/.*$ + mail.ugnet.xyz + ugnet.xyz + Testing... Making the internet fun again. - http://ugnet.gay/ + http://ugnet.xyz/ 1 true diff --git a/front/msn/http/tmpl/config/MsgrConfig.msn.envelope.xml b/front/msn/http/tmpl/config/MsgrConfig.msn.envelope.xml deleted file mode 100644 index 40730a8..0000000 --- a/front/msn/http/tmpl/config/MsgrConfig.msn.envelope.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/front/msn/http/tmpl/config/MsgrConfig.msn.xml b/front/msn/http/tmpl/config/MsgrConfig.msn.xml deleted file mode 100644 index 9bffba8..0000000 --- a/front/msn/http/tmpl/config/MsgrConfig.msn.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - - 0 - - 1 - - - 0 - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -{tabs} - - - - https://{{ settings.ADDRESSBOOK_HOST }}/abservice.asmx - - - - - 1 - http://{{ settings.AD_HOST }}/ads/txt - http://{{ settings.AD_HOST }}/ads/banner - - - http://{{ settings.APPDIR_HOST }}/AppDirectory/Directory.aspx?L=en-us - http://{{ settings.APPDIR_HOST }}/AppDirectory/AppDirectory.asmx - http://{{ settings.APPDIR_HOST }}/AppDirectory/GetAppdirVersion.aspx - - - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=images - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$+news&ia=news - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - - - http://{{ settings.TODAY_HOST }}/start?msn=1 - - - - https://{{ settings.WEBSITE_HOST }}/account/settings - - - 956 - https://{{ settings.WEBSITE_HOST }}/tos - - - diff --git a/front/msn/http/tmpl/config/MsgrConfig.wlm.14.xml b/front/msn/http/tmpl/config/MsgrConfig.wlm.14.xml deleted file mode 100644 index b9353f0..0000000 --- a/front/msn/http/tmpl/config/MsgrConfig.wlm.14.xml +++ /dev/null @@ -1,239 +0,0 @@ - - - - - 0 - - - - 1 - - - 1 - false - - - 0 - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - https://{{ settings.ADDRESSBOOK_HOST }}/abservice.asmx - - - - - 420 - 1 - http://{{ settings.AD_HOST }}/ads/txt - http://{{ settings.AD_HOST }}/ads/banner - - - - - - http://{{ settings.APPDIR_HOST }}/AppDirectory/Directory.aspx?L=en-us - http://{{ settings.APPDIR_HOST }}/AppDirectory/AppDirectory.asmx - http://{{ settings.APPDIR_HOST }}/AppDirectory/GetAppdirVersion.aspx - - - - 73625 - 672 - true - 808 - http://cid-%1!16.16I64X!.profile.live.com/invites?partner=Messenger - - - http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&mode=activecontacts&mkt=en-us&partner=Messenger - 73625 - - - http://profile.live.com/details - 73625 - - - http://cid-%1!16.16I64X!.profile.live.com/connect/?partner=Messenger - 73625 - - - http://cid-%1.profile.live.com/connect/send.aspx?email=%2 - http://cid-%1.profile.live.com/connect/send.aspx?cid=%2 - 73625 - - - http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&mkt=en-us&mem=%ls - http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&mkt=en-us&cid=%ls - http://cid-%1!16.16I64X!.profile.live.com - 73625 - - - http://cid-%1.profile.live.com/connect/Messenger.aspx?Email=%2 - http://cid-%1.profile.live.com/connect/Messenger.aspx?cid=0x%2 - 73625 - - true - - - 45930 - http://{{ settings.SOCIAL_HOST }}/?addblogentry=true&mkt=nl-nl - false - 45930 - http://{{ settings.SOCIAL_HOST }}/signup.aspx?mkt=nl-nl - http://ctas.storage.ugnet.gay/storageservice/schematizedstore.asmx - http://{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx - 45930 - http://{{ settings.SOCIAL_HOST }}/homepage.aspx - 45930 - http://{{ settings.SOCIAL_HOST }} - true - - http://{{ settings.STORAGE_HOST }}/crosstalk-dist/client/all/tools/flashplayer_10_3r183_48_winax.exe - - - https://{{ settings.WEBSITE_HOST }}/blog - - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=images - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$+news&ia=news - http://home.live.com/search?query=$QUERY$ - 73625 - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - - - 6528 - http://{{ settings.TODAY_HOST }}/start?wlm=1 - 2 - - - - - - - \ No newline at end of file diff --git a/front/msn/http/tmpl/config/MsgrConfig.wlm.8.xml b/front/msn/http/tmpl/config/MsgrConfig.wlm.8.xml deleted file mode 100644 index c95b2ce..0000000 --- a/front/msn/http/tmpl/config/MsgrConfig.wlm.8.xml +++ /dev/null @@ -1,180 +0,0 @@ - - - - - 0 - - 0 - false - - - 0 - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -{tabs} - - - - https://{{ settings.ADDRESSBOOK_HOST }}/abservice.asmx - - - - - 1 - http://{{ settings.AD_HOST }}/ads/txt - http://{{ settings.AD_HOST }}/ads/banner - - - - - - http://{{ settings.APPDIR_HOST }}/AppDirectory/Directory.aspx?L=en-us - http://{{ settings.APPDIR_HOST }}/AppDirectory/AppDirectory.asmx - http://{{ settings.APPDIR_HOST }}/AppDirectory/GetAppdirVersion.aspx - - - - http://{{ settings.SOCIAL_HOST }}/PendingRequests.aspx?mkt=en-us&partner=Messenger - 73625 - 672 - 808 - - - http://{{ settings.SOCIAL_HOST }}/NetworkExplorer.aspx?mkt=en-us&partner=Messenger&cid=%1 - 73625 - 674 - 808 - - - http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&mode=activecontacts&mkt=en-us&partner=Messenger - 73625 - - - http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&partner=Messenger&mkt=en-us - 73625 - - - http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&mkt=en-us&mem=%ls - http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&mkt=en-us&cid=%ls - 73625 - - - http://{{ settings.SOCIAL_HOST }}/NetworkSetup.aspx?mkt=en-us&partner=Messenger - 73625 - 674 - 808 - - false - - - 45930 - http://{{ settings.SOCIAL_HOST }}/?addblogentry=true&mkt=nl-nl - false - 45930 - http://{{ settings.SOCIAL_HOST }}/signup.aspx?mkt=nl-nl - http://storage.msn.com/storageservice/schematizedstore.asmx - http://services.{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx - 45930 - http://{{ settings.SOCIAL_HOST }}/homepage.aspx - 45930 - http://{{ settings.SOCIAL_HOST }} - true - - http://{{ settings.STORAGE_HOST }}/crosstalk-dist/client/all/tools/flashplayer_10_3r183_48_winax.exe - - https://{{ settings.WEBSITE_HOST }}/blog - - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=images - https://searx.ugnet.gay/searxng/search?q=$QUERY$+news&ia=news - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - - - 6528 - http://{{ settings.TODAY_HOST }}/start?wlm=1 - 2 - - - - - \ No newline at end of file diff --git a/front/msn/http/tmpl/config/MsgrConfig.wlm.16.xml b/front/msn/http/tmpl/config/MsgrConfig.xml similarity index 72% rename from front/msn/http/tmpl/config/MsgrConfig.wlm.16.xml rename to front/msn/http/tmpl/config/MsgrConfig.xml index 04d2297..048c029 100644 --- a/front/msn/http/tmpl/config/MsgrConfig.wlm.16.xml +++ b/front/msn/http/tmpl/config/MsgrConfig.xml @@ -1,5 +1,73 @@ - +{%- set is_wlm = variant in ('wlm8', 'wlm14', 'wlm16') -%} +{%- set is_wlm14_up = variant in ('wlm14', 'wlm16') -%} +{%- set search_url = 'https://searx.ugnet.xyz/searxng/search?q=$QUERY$' -%} +{%- set trusted_domains = ('hiden.cc', 'ugnet.xyz', 'crosstalk.im', 'ctsrv.xyz') -%} + +{%- set error_login_msn = [ + ('0x80072EE7', 3), ('0x81000306', 3), ('0x80072EFD', 3), ('0x81000362', 3), + ('0x8100030E', 3), ('0x80072745', 3), ('0x800701F7', 3), ('0x80072EFF', 3), + ('0x81000363', 3), ('0x81000395', 3), ('0x800B0001', 3), ('0x81000323', 3), + ('0x80072F19', 3), ('0x800701F8', 3), ('0x80072746', 3), ('0x800701F6', 3), + ('0x81000377', 3), ('0x81000314', 3), ('0x81000378', 3), ('0x80072EFF', 3), + ('0x80070190', 3), ('0x80070197', 3), ('0x80048820', 3), ('0x80048829', 3), + ('0x80048834', 3), ('0x80048852', 3), ('0x8004886a', 3), ('0x8004886b', 3), +] -%} +{%- set error_login_wlm14 = [ + ('0x80004002', 3), ('0x80004004', 3), ('0x80004005', 3), ('0x8000402A', 3), + ('0x8000FFFF', 3), ('0x8001012E', 3), ('0x80040200', 3), ('0x80048051', 3), + ('0x80048820', 3), ('0x80048823', 3), ('0x80070002', 3), ('0x80070005', 3), + ('0x8007000E', 3), ('0x80070057', 3), ('0x8007007E', 3), ('0x800702E4', 3), + ('0x800706BA', 3), ('0x800706BE', 3), ('0x80071392', 3), ('0x80072745', 3), + ('0x80072746', 3), ('0x80072EE2', 3), ('0x80072EF3', 3), ('0x80072EFD', 3), + ('0x80072EFF', 3), ('0x80072F06', 3), ('0x80072F7D', 3), ('0x800C013E', 3), + ('0x80191002', 3), ('0x81000306', 3), ('0x8100030D', 3), ('0x81000314', 3), + ('0x81000362', 3), ('0x81000378', 3), ('0x81000395', 3), ('0x85AE000B', 3), + ('0x85AE000F', 3), ('0x85AE001D', 3), ('0x85AE0022', 3), ('0x85AE0024', 3), + ('0x85AE0027', 3), ('0x85AE003C', 3), ('0x85AE0053', 3), ('0x8E5E0152', 3), + ('0x8E5E0158', 3), ('0x8E5E0211', 3), ('0x8E5E0220', 3), ('0x8E5E0226', 3), + ('0x8E5E03FE', 3), ('0x8E5E0408', 3), ('0x8E5E05F6', 3), ('0x8E5E0710', 3), + ('0x8E5E0713', 3), +] -%} +{%- set error_login_wlm16 = [ + ('*', 3), ('0x81000605', 3), ('0x80048849', 5), ('0x8004882A', 5), + ('0x80048800', 5), ('0x8004889C', 5), ('0x80048831', 5), ('0x81000306', 5), + ('0x80048862', 5), ('0x800488EB', 5), ('0x80048848', 5), ('0x80004002', 3), + ('0x80004004', 3), ('0x80004005', 3), ('0x8000402A', 3), ('0x8000FFFF', 3), + ('0x8001012E', 3), ('0x80040200', 3), ('0x80048051', 3), ('0x80048820', 5), + ('0x80048823', 3), ('0x80070002', 3), ('0x80070005', 3), ('0x8007000E', 3), + ('0x80070057', 3), ('0x8007007E', 3), ('0x800702E4', 3), ('0x800706BA', 3), + ('0x800706BE', 3), ('0x80071392', 3), ('0x80072745', 3), ('0x80072746', 3), + ('0x80072EE2', 3), ('0x80072EF3', 3), ('0x80072EFD', 3), ('0x80072EFF', 3), + ('0x80072F06', 3), ('0x80072F7D', 3), ('0x800C013E', 3), ('0x80191002', 3), + ('0x8100030D', 3), ('0x81000314', 3), ('0x81000362', 3), ('0x81000378', 3), + ('0x81000395', 3), ('0x85AE000B', 3), ('0x85AE000F', 3), ('0x85AE001D', 3), + ('0x85AE0022', 3), ('0x85AE0024', 3), ('0x85AE0027', 3), ('0x85AE003C', 3), + ('0x85AE0053', 3), ('0x8E5E0152', 3), ('0x8E5E0158', 3), ('0x8E5E0211', 3), + ('0x8E5E0220', 3), ('0x8E5E0226', 3), ('0x8E5E03FE', 3), ('0x8E5E0408', 3), + ('0x8E5E05F6', 3), ('0x8E5E0710', 3), ('0x8E5E0713', 3), +] -%} +{%- set error_login = {'msn': error_login_msn, 'wlm8': error_login_msn, 'wlm14': error_login_wlm14, 'wlm16': error_login_wlm16} -%} +{%- set error_mapfile_msn = [ + ('0x810003F0', 3), ('0x810003F1', 3), ('0x810003F2', 3), ('0x810003F3', 3), + ('0x810003F4', 3), ('0x810003F5', 3), ('0x810003F6', 3), ('0x810003F7', 3), +] -%} +{%- set error_mapfile_wlm14 = [ + ('0x810003F1', 3), ('0x810003F6', 3), +] -%} +{%- set error_mapfile = {'msn': error_mapfile_msn, 'wlm8': error_mapfile_msn, 'wlm14': error_mapfile_wlm14, 'wlm16': error_mapfile_wlm14} -%} +{%- set error_p2p_wlm8 = [ + ('0x82000012', 3), ('0x82000013', 3), ('0x82000016', 3), ('0x82000017', 3), + ('0x82000018', 3), ('0x82000019', 3), +] -%} +{%- set error_p2p_wlm14 = [ + ('0x82000016', 3), ('0x82000017', 3), ('0x82000019', 3), ('0x8200001b', 3), + ('0x8200001d', 3), ('0x8200001e', 3), ('0x82000024', 3), ('0x82000026', 3), +] -%} +{%- set error_p2p = {'wlm8': error_p2p_wlm8, 'wlm14': error_p2p_wlm14, 'wlm16': error_p2p_wlm14} -%} + +{%- macro msgr_config() -%} +{%- if variant == 'wlm16' %} @@ -9,23 +77,33 @@ +{%- endif %} - 2 + {{ 2 if variant == 'wlm16' else 0 }} +{%- if is_wlm14_up %} 1 - 1 +{%- endif %} + {{ 0 if variant == 'wlm8' else 1 }} +{%- if is_wlm %} false +{%- endif %} - http://mplocate.spotlife.net/locate.sxml + http://ms.msgrsvcs.ctsrv.xyz/locate.sxml 1 - http://mlocate.spotlife.net/locate.sxml + http://ms.msgrsvcs.ctsrv.xyz/locate.sxml +{%- if variant == 'msn' %} + +{%- else %} +{%- endif %} +{%- if variant == 'wlm16' %} http://rad.msn.com/ADSAdClient31.dll?GetAd?PG= http://b.scorecardresearch.com/p?c1=7&c2=3000001&c3=%1!d!&cj=1 @@ -35,11 +113,25 @@ avrelay.msn.com 7000 +{%- else %} + + 0 + 0 + +{%- endif %} +{%- if variant == 'wlm14' %} + + + + +{%- elif variant == 'wlm16' %} +{%- endif %} +{%- if variant == 'wlm16' %} @@ -136,95 +228,42 @@ - - - - +{%- endif %} +{%- for domain in trusted_domains %} + +{%- endfor %} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +{%- for hr, action in error_login[variant] %} + +{%- endfor %} - - +{%- for hr, action in error_mapfile[variant] %} + +{%- endfor %} +{%- if variant in error_p2p %} - - - - - - - - +{%- for hr, action in error_p2p[variant] %} + +{%- endfor %} +{%- endif %} +{%- if variant == 'wlm16' %} +{%- endif %} +{%- if variant == 'wlm14' %} + + + + + +{%- elif variant == 'wlm16' %} @@ -238,10 +277,14 @@ +{%- endif %} +{%- if is_wlm14_up %} +{%- endif %} +{%- if variant == 'wlm16' %} @@ -491,39 +534,135 @@ +{%- endif %} +{%- if variant in ('msn', 'wlm8') %} + +{% include 'msn:svcs/svcs_tabs.xml' %} + +{%- endif %} https://{{ settings.ADDRESSBOOK_HOST }}/abservice.asmx +{%- if variant == 'wlm16' %} 120 http://{{ settings.AD_HOST }}/ads/banner http://{{ settings.AD_HOST }}/ads/banner +{%- endif %} +{%- if variant == 'wlm16' %} http://{{ settings.AD_HOST }}/ads/banner http://{{ settings.AD_HOST }}/ads/banner-lg http://{{ settings.AD_HOST }}/ads/banner +{%- else %} + http://{{ settings.AD_HOST }}/ads/banner +{%- endif %} +{%- if is_wlm %} - + +{%- endif %} +{%- if is_wlm14_up %} 420 +{%- endif %} 1 - https://{{ settings.AD_HOST }}/ads/txt + {{ 'https' if variant == 'wlm16' else 'http' }}://{{ settings.AD_HOST }}/ads/txt +{%- if variant == 'wlm16' %} +{%- endif %} - https://{{ settings.APPDIR_HOST }}/AppDirectory/Directory.aspx?L=en-us - https://{{ settings.APPDIR_HOST }}/AppDirectory/AppDirectory.asmx - https://{{ settings.APPDIR_HOST }}/AppDirectory/GetAppdirVersion.aspx +{%- set appdir = ('https' if variant == 'wlm16' else 'http') ~ '://' ~ settings.APPDIR_HOST ~ '/AppDirectory' %} + {{ appdir }}/Directory.aspx?L=en-us + {{ appdir }}/AppDirectory.asmx + {{ appdir }}/GetAppdirVersion.aspx +{%- if variant == 'wlm16' %} +{%- endif %} +{%- if variant == 'wlm8' %} + + + http://{{ settings.SOCIAL_HOST }}/PendingRequests.aspx?mkt=en-us&partner=Messenger + 73625 + 672 + 808 + + + http://{{ settings.SOCIAL_HOST }}/NetworkExplorer.aspx?mkt=en-us&partner=Messenger&cid=%1 + 73625 + 674 + 808 + + + http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&mode=activecontacts&mkt=en-us&partner=Messenger + 73625 + + + http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&partner=Messenger&mkt=en-us + 73625 + + + http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&mkt=en-us&mem=%ls + http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&mkt=en-us&cid=%ls + 73625 + + + http://{{ settings.SOCIAL_HOST }}/NetworkSetup.aspx?mkt=en-us&partner=Messenger + 73625 + 674 + 808 + + false + +{%- elif variant == 'wlm14' %} + + + 73625 + 672 + true + 808 + http://cid-%1!16.16I64X!.profile.live.com/invites?partner=Messenger + + + http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&mode=activecontacts&mkt=en-us&partner=Messenger + 73625 + + + http://profile.live.com/details + 73625 + + + http://cid-%1!16.16I64X!.profile.live.com/connect/?partner=Messenger + 73625 + + + http://cid-%1.profile.live.com/connect/send.aspx?email=%2 + http://cid-%1.profile.live.com/connect/send.aspx?cid=%2 + 73625 + + + http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&mkt=en-us&mem=%ls + http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&mkt=en-us&cid=%ls + http://cid-%1!16.16I64X!.profile.live.com + 73625 + + + http://cid-%1.profile.live.com/connect/Messenger.aspx?Email=%2 + http://cid-%1.profile.live.com/connect/Messenger.aspx?cid=0x%2 + 73625 + + true + +{%- elif variant == 'wlm16' %} 73625 @@ -613,6 +752,28 @@ true +{%- endif %} +{%- if variant in ('wlm8', 'wlm14') %} + + 45930 + http://{{ settings.SOCIAL_HOST }}/?addblogentry=true&mkt=nl-nl + false + 45930 + http://{{ settings.SOCIAL_HOST }}/signup.aspx?mkt=nl-nl +{%- if variant == 'wlm8' %} + http://storage.msn.com/storageservice/schematizedstore.asmx + http://services.{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx +{%- else %} + http://ctas.storage.ugnet.xyz/storageservice/schematizedstore.asmx + http://{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx +{%- endif %} + 45930 + http://{{ settings.SOCIAL_HOST }}/homepage.aspx + 45930 + http://{{ settings.SOCIAL_HOST }} + true + +{%- elif variant == 'wlm16' %} 73625 http://{{ settings.SOCIAL_HOST }}/?addblogentry=true&mkt=en-us @@ -630,12 +791,20 @@ true http://www.msn.com/infopane/messenger.armx +{%- endif %} +{%- if is_wlm %} http://{{ settings.STORAGE_HOST }}/crosstalk-dist/client/all/tools/flashplayer_10_3r183_48_winax.exe +{%- endif %} +{%- if variant == 'wlm16' %} 71659 https://fss.live.com/krl/AddContact.aspx +{%- endif %} +{%- if is_wlm %} +{%- endif %} +{%- if variant == 'wlm16' %} @@ -659,31 +828,60 @@ +{%- endif %} +{%- if is_wlm14_up %} +{%- endif %} +{%- if variant == 'wlm16' %} +{%- endif %} +{%- if is_wlm %} https://{{ settings.WEBSITE_HOST }}/blog +{%- endif %} +{%- if variant == 'wlm16' %} +{%- endif %} - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=images - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$+news&ia=news +{%- if variant != 'wlm8' %} + {{ search_url }}&ia=web +{%- endif %} + {{ search_url }}&ia=images +{%- if variant != 'wlm8' %} + {{ search_url }}&ia=web +{%- endif %} + {{ search_url }}+news&ia=news +{%- if is_wlm14_up %} http://home.live.com/search?query=$QUERY$ 73625 - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web - https://searx.ugnet.gay/searxng/search?q=$QUERY$&ia=web +{%- endif %} +{%- if variant != 'wlm8' %} + {{ search_url }}&ia=web +{%- endif %} + {{ search_url }}&ia=web + {{ search_url }}&ia=web + {{ search_url }}&ia=web +{%- if variant == 'msn' %} + http://{{ settings.TODAY_HOST }}/start?msn=1 +{%- else %} 6528 +{%- if variant == 'wlm16' %} https://{{ settings.TODAY_HOST }}/start?windowslive=1 +{%- else %} + http://{{ settings.TODAY_HOST }}/start?wlm=1 +{%- endif %} 2 +{%- endif %} - + +{%- if variant in ('wlm8', 'wlm14') %} + +{%- endif %} +{%- if variant == 'wlm16' %} @@ -692,9 +890,19 @@ +{%- endif %} +{%- if variant == 'wlm14' %} + +{%- elif variant == 'wlm16' %} +{%- endif %} +{%- if is_wlm14_up %} - - \ No newline at end of file + +{%- endmacro -%} + +{%- if soap -%} + + + + + + + + +{%- else -%} + +{{ msgr_config() }} +{%- endif -%} \ No newline at end of file diff --git a/front/msn/http/tmpl/config/ppcrlconfig600.xml b/front/msn/http/tmpl/config/ppcrlconfig600.xml index c90738f..47697aa 100644 --- a/front/msn/http/tmpl/config/ppcrlconfig600.xml +++ b/front/msn/http/tmpl/config/ppcrlconfig600.xml @@ -3,10 +3,10 @@ When a certificate is rev'd, a line like the following should be added to the cfg:Settings section: SLCA_BACKUP.CER - -->.devicedns.ugnet.gayMicrosoft Base Smart Card Crypto Provider0tOOumDKocEgVaLhyDsVrUUBEMI=60480001000030000300001440sX6CAbEo4edMwCNRCrfqA6wn3eUNMtgQ6hV3dY8cwJg=,g2b69yfcSDF6LzoMN/oSfz81YZTPuy9LYo7H5qGnXA8=,uSUTbz6nwKGVFpChqzE5ENqB9AmUqFNC7GIoiPEocFE=,oHlCFSeKVn6IevbN4BWl6IQU72QPfas4VaPneWWL53g=,fVOTUco5wnynBkCeWptrBi25v43D2MqmE3Bnrn9otec=,KEg2GpweMt8dPi7Wp7nmelJc+KE7Fk+ABslHlXj3Rt4=,7r0PFuYpr4uDgb/t/dZJYF/pD3Y/XLe6Rz657vlNmvE=,Mb5ACW+THNfxHV4mLSssQ3xEOF+07LwQE9ladDWBb5w=,6EPuPaEZXWr7icqjznQnsI/AH9h4ok+lbpYsNccdXnA=,rQZmwqojBROk1Pc/okKkWGzY7WcmodDdVCUHcv2blgU=https://go.microsoft.com/fwlink/?LinkId=690512http://go.microsoft.com/fwlink/?LinkId=253579http://clientconfig.passport.net/ppcrlconfig.srf@hotmail.,@msn.,@live.,@yahoo.,@gmail.,@windowslive.,@sympatico.,@aol.,@163.,@freemail.,@gmx.,@comcast.,@web.,@libero.,@wanadoo.,@sbcglobal.,@example.,@tiscali.,@126.,@mail.,@q.,@xiaoi.,@hanmail.,@walla.,@free.,@ppauthz.com,@compaq.,@hotmail.co.,@messengeruser.,@passport.,@webtv.11{1C109E4C-2F30-4EA3-A57A-A290877A2303}Win32_USBControllerDeviceWin32_1394ControllerDeviceWin32_PCMCIAControllerDeviceWin32_ConnectionShareSerialNumberMACAddressManufacturerSerialNumber]]>01{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}0311{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}0211MIIDGjCCAtqgAwIBAgIJAL67zDTCqZpDMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTEzMDcwMjIxMTAzN1oXDTE4MDcwMTIxMTAzN1owIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtjCCASsGByqGSM44BAEwggEeAoGBAPPi828dNQiBJ1qnxffow1emUO8g3DK1PKd5hC3L/BUiKMHnZAGcVcp7+KARbMypNjbcaBFhyBiPefmFzOaxqKr0Tf/T6mwtYP2A7v0ITEoJxLl4TPPM9jjKjMqTf7rubUcsrU7i1d3aTmUxhOUS2YRsdwq9xeSUXOVobFE7848VAhUAn9eIFUVj31yox4o1Qnj8cDlON/sCgYA6dp0LN/eExvGvZo/6ey0LU96/rA5k24JE9MF5Pp40ysAgBH098FY93v0XGrL9avSffTYWwoXMQiWQw6bwyuDdOYfD8xCl7+DxJ/QGQW6YPsZJ6DXhAG4vzPSEdLkOgstny2JgjtQvLsRbcYA9Y9vWMQG4pJD9GrCRl270uxdqZQOBhAACgYBu0rix0SuIRsMiNoM3actVS804Cb/WhMi9rPtQDKUAMnGFVgzMg9muE1gPpyqp/Tbsyqn9eYYSRcxZG059zwR4R+gtWUaCljhHOScjYUL5ql2Z7DNxRndJLjl4QmT0hq2msCiDfbWZpY5RLjdsUkcLHLiZF5N4NJnnct5meNsr46OBmDCBlTAdBgNVHQ4EFgQURtLCWz4DNCN5LhccABkoTHEQK2QwUwYDVR0jBEwwSoAURtLCWz4DNCN5LhccABkoTHEQK2ShJ6QlMCMxITAfBgNVBAMTGFRva2VuIFNpZ25pbmcgUHVibGljIEtleYIJAL67zDTCqZpDMBIGA1UdEwEB/wQIMAYBAf8CAQAwCwYDVR0PBAQDAgHGMAkGByqGSM44BAMDLwAwLAIUC3k3NJt95Lh1CFXNQO9Luy0xRakCFBdAihMHEpTBGyyeUZXkEeuGpUhkMIIDGzCCAtugAwIBAgIJAL6pALeLZHDvMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTE2MDUwOTIwNDA1NVoXDTIxMDUwODIwNDA1NVowIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASwGByqGSM44BAEwggEfAoGBAKmnM6FKnJ1osHWBHd8jHFFMDNwygIcof9EfHW6xJbU2uIzVV5WRu251RbRbmOqozesK44vkeBx9Ntl7PSu0W5RJFCEw9o4RLG0J40MWDNDQ+7iqvIsM6lsgZrDjNoWJ2t/Yrnnp0r3F9YNtj7J4vgLCYNOlkr2kcfGiji+SXotXAhUAqGI2zlbARtjz+simu2PihUPkV1MCgYEAnrIIXPvjKvWiXd3uve7eDS8qRHW7yoAseVLgeEIbS4VSj/9iQqunx1weQGlds75CLZgpcrY4Z5wbkxSjnK1EV30qce4+VzgXYGLZIAvl78wbAMFrG0josXccAbmqVM4LX2Z5yu1TEpPZLvgiaV4gJk4jsYhInqPm3Bw2qQ+gZokDgYQAAoGAFozcPQdM9MmszvEWMXuFrfEA8kVMnKIyA60paSi7CIecSAlsRLyw3D9J9pRW6HHdRZgOrKvnNcY63gKB56SKyj6r3nGqtkwEpu9yw1K+k2aSyJcKPHYVNw1Um5McKJgQJ49ShJFPaWXfDZPOCpgMpdzibnWjMcTak5rz4FHSUtOjgZgwgZUwHQYDVR0OBBYEFKNT6lUDzQppxFhwtv/jkSCRx596MFMGA1UdIwRMMEqAFKNT6lUDzQppxFhwtv/jkSCRx596oSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQC+qQC3i2Rw7zASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAy8AMCwCFGjnp838qB/wTUdvoRt4G3aW0fv0AhRe8cZDdOveTDCbWane65nlVv0Udw==9001560231000015728640018031006000065536http://sqm.microsoft.com/sqm/WindowsLive/sqmserver.dll10account.ugnet.gayaccount.ugnet.gayaccount.ugnet.gay/password/resetsapimbi_sslmbi_ssl_sa821250720012360016.000.27832.00502231msn.comctas.login.ugnet.gayugnet.gayctas.login.ugnet.gay,signup.ugnet.gay,account.ugnet.gaylogin.srf;()]]>;'()]]>';()]]>post.srfManageEIDs.srfsecure.srflogout.srfugnet.gay,msn.com,zune.net,windowsmarketplace.com,workspace.office.ugnet.gay,atdmt.comhttps://ctas.login.ugnet.gay/RST.srf - https://ctas.login.ugnet.gay/RST.srfhttps://ctas.login.ugnet.gay/ppsecure/SHA1Auth.srf - https://ctas.login.ugnet.gay/resetpw.srf + -->.devicedns.ugnet.xyzMicrosoft Base Smart Card Crypto Provider0tOOumDKocEgVaLhyDsVrUUBEMI=60480001000030000300001440sX6CAbEo4edMwCNRCrfqA6wn3eUNMtgQ6hV3dY8cwJg=,g2b69yfcSDF6LzoMN/oSfz81YZTPuy9LYo7H5qGnXA8=,uSUTbz6nwKGVFpChqzE5ENqB9AmUqFNC7GIoiPEocFE=,oHlCFSeKVn6IevbN4BWl6IQU72QPfas4VaPneWWL53g=,fVOTUco5wnynBkCeWptrBi25v43D2MqmE3Bnrn9otec=,KEg2GpweMt8dPi7Wp7nmelJc+KE7Fk+ABslHlXj3Rt4=,7r0PFuYpr4uDgb/t/dZJYF/pD3Y/XLe6Rz657vlNmvE=,Mb5ACW+THNfxHV4mLSssQ3xEOF+07LwQE9ladDWBb5w=,6EPuPaEZXWr7icqjznQnsI/AH9h4ok+lbpYsNccdXnA=,rQZmwqojBROk1Pc/okKkWGzY7WcmodDdVCUHcv2blgU=https://go.microsoft.com/fwlink/?LinkId=690512http://go.microsoft.com/fwlink/?LinkId=253579http://clientconfig.passport.net/ppcrlconfig.srf@hotmail.,@msn.,@live.,@yahoo.,@gmail.,@windowslive.,@sympatico.,@aol.,@163.,@freemail.,@gmx.,@comcast.,@web.,@libero.,@wanadoo.,@sbcglobal.,@example.,@tiscali.,@126.,@mail.,@q.,@xiaoi.,@hanmail.,@walla.,@free.,@ppauthz.com,@compaq.,@hotmail.co.,@messengeruser.,@passport.,@webtv.11{1C109E4C-2F30-4EA3-A57A-A290877A2303}Win32_USBControllerDeviceWin32_1394ControllerDeviceWin32_PCMCIAControllerDeviceWin32_ConnectionShareSerialNumberMACAddressManufacturerSerialNumber]]>01{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}0311{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}0211MIIDGjCCAtqgAwIBAgIJAL67zDTCqZpDMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTEzMDcwMjIxMTAzN1oXDTE4MDcwMTIxMTAzN1owIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtjCCASsGByqGSM44BAEwggEeAoGBAPPi828dNQiBJ1qnxffow1emUO8g3DK1PKd5hC3L/BUiKMHnZAGcVcp7+KARbMypNjbcaBFhyBiPefmFzOaxqKr0Tf/T6mwtYP2A7v0ITEoJxLl4TPPM9jjKjMqTf7rubUcsrU7i1d3aTmUxhOUS2YRsdwq9xeSUXOVobFE7848VAhUAn9eIFUVj31yox4o1Qnj8cDlON/sCgYA6dp0LN/eExvGvZo/6ey0LU96/rA5k24JE9MF5Pp40ysAgBH098FY93v0XGrL9avSffTYWwoXMQiWQw6bwyuDdOYfD8xCl7+DxJ/QGQW6YPsZJ6DXhAG4vzPSEdLkOgstny2JgjtQvLsRbcYA9Y9vWMQG4pJD9GrCRl270uxdqZQOBhAACgYBu0rix0SuIRsMiNoM3actVS804Cb/WhMi9rPtQDKUAMnGFVgzMg9muE1gPpyqp/Tbsyqn9eYYSRcxZG059zwR4R+gtWUaCljhHOScjYUL5ql2Z7DNxRndJLjl4QmT0hq2msCiDfbWZpY5RLjdsUkcLHLiZF5N4NJnnct5meNsr46OBmDCBlTAdBgNVHQ4EFgQURtLCWz4DNCN5LhccABkoTHEQK2QwUwYDVR0jBEwwSoAURtLCWz4DNCN5LhccABkoTHEQK2ShJ6QlMCMxITAfBgNVBAMTGFRva2VuIFNpZ25pbmcgUHVibGljIEtleYIJAL67zDTCqZpDMBIGA1UdEwEB/wQIMAYBAf8CAQAwCwYDVR0PBAQDAgHGMAkGByqGSM44BAMDLwAwLAIUC3k3NJt95Lh1CFXNQO9Luy0xRakCFBdAihMHEpTBGyyeUZXkEeuGpUhkMIIDGzCCAtugAwIBAgIJAL6pALeLZHDvMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTE2MDUwOTIwNDA1NVoXDTIxMDUwODIwNDA1NVowIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASwGByqGSM44BAEwggEfAoGBAKmnM6FKnJ1osHWBHd8jHFFMDNwygIcof9EfHW6xJbU2uIzVV5WRu251RbRbmOqozesK44vkeBx9Ntl7PSu0W5RJFCEw9o4RLG0J40MWDNDQ+7iqvIsM6lsgZrDjNoWJ2t/Yrnnp0r3F9YNtj7J4vgLCYNOlkr2kcfGiji+SXotXAhUAqGI2zlbARtjz+simu2PihUPkV1MCgYEAnrIIXPvjKvWiXd3uve7eDS8qRHW7yoAseVLgeEIbS4VSj/9iQqunx1weQGlds75CLZgpcrY4Z5wbkxSjnK1EV30qce4+VzgXYGLZIAvl78wbAMFrG0josXccAbmqVM4LX2Z5yu1TEpPZLvgiaV4gJk4jsYhInqPm3Bw2qQ+gZokDgYQAAoGAFozcPQdM9MmszvEWMXuFrfEA8kVMnKIyA60paSi7CIecSAlsRLyw3D9J9pRW6HHdRZgOrKvnNcY63gKB56SKyj6r3nGqtkwEpu9yw1K+k2aSyJcKPHYVNw1Um5McKJgQJ49ShJFPaWXfDZPOCpgMpdzibnWjMcTak5rz4FHSUtOjgZgwgZUwHQYDVR0OBBYEFKNT6lUDzQppxFhwtv/jkSCRx596MFMGA1UdIwRMMEqAFKNT6lUDzQppxFhwtv/jkSCRx596oSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQC+qQC3i2Rw7zASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAy8AMCwCFGjnp838qB/wTUdvoRt4G3aW0fv0AhRe8cZDdOveTDCbWane65nlVv0Udw==9001560231000015728640018031006000065536http://sqm.microsoft.com/sqm/WindowsLive/sqmserver.dll10account.ugnet.xyzaccount.ugnet.xyzaccount.ugnet.xyz/password/resetsapimbi_sslmbi_ssl_sa821250720012360016.000.27832.00502231msn.comctas.login.ugnet.xyzugnet.xyzctas.login.ugnet.xyz,signup.ugnet.xyz,account.ugnet.xyzlogin.srf;()]]>;'()]]>';()]]>post.srfManageEIDs.srfsecure.srflogout.srfugnet.xyz,msn.com,zune.net,windowsmarketplace.com,workspace.office.ugnet.xyz,atdmt.comhttps://ctas.login.ugnet.xyz/RST.srf + https://ctas.login.ugnet.xyz/RST.srfhttps://ctas.login.ugnet.xyz/ppsecure/SHA1Auth.srf + https://ctas.login.ugnet.xyz/resetpw.srf http://www.microsoft.com/account/default.aspx - https://account.ugnet.gay - http://ctas.login.ugnet.gay/hp.srf?format=b1 - http://ctas.login.ugnet.gay/ppcrlcheck.srf*.ugnet.gayctas.login.ugnet.gay,account.ugnet.gayc.ugnet.gay,c.msn.comhttps://ctas.login.ugnet.gay/RST2.srfhttps://ctas.login.ugnet.gay/RST2.srfhttps://ctas.login.ugnet.gay/didtou.srfhttps://ctas.login.ugnet.gay/ppsecure/devicechangecredential.srfhttps://ctas.login.ugnet.gay/ppsecure/deviceaddcredential.srfhttps://ctas.login.ugnet.gay/ppsecure/deviceremovecredential.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceAssociate.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceDisassociate.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceQuery.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceUpdate.srfhttps://ctas.login.ugnet.gay/ppsecure/EnumerateDevices.srfhttps://ctas.login.ugnet.gay/ppsecure/ResolveUser.srfEIDhttps://ctas.login.ugnet.gay/getrealminfo.srfhttps://ctas.login.ugnet.gay/getuserrealm.srfhttps://ctas.login.ugnet.gay/retention.srfhttps://signup.ugnet.gay/signup.aspxhttp://go.microsoft.com/fwlink/p/?LinkId=253457https://ctas.login.ugnet.gay/ppsecure/GetUserKeyData.srfhttps://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80500https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80500https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&id=80500https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80501https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80501https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&id=80501https://account.ugnet.gay/Wizard/Password/Change?id=80501https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80502https://account.ugnet.gay/InlineSignup.aspx?iww=1&id=80502https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&id=80502https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80600https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80600https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&id=80600https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80600https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80601https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80601https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&id=80601https://account.ugnet.gay/Wizard/Password/Change?id=80601https://ctas.login.ugnet.gay/ppsecure/InlinePOPAuth.srf?id=80601&fid=cphttps://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80601https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80603https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80603https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80603https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80604https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80604https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80604https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80604https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80605https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80605https://ctas.login.ugnet.gay/ppsecure/InlinePOPAuth.srf?id=80605https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80606https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80607https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80608https://account.ugnet.gay/msangcwamhttps://account.microsoft.com/?ref=settingshttp://go.microsoft.com/fwlink/?LinkId=248215https://ctas.login.ugnet.gay/ppsecure/InlineClientAuth.srfhttps://ctas.login.ugnet.gay/ppsecure/InlineDesktop.srfhttps://ctas.login.ugnet.gay/ManageApprover.srfhttps://ctas.login.ugnet.gay/ListSessions.srfhttps://ctas.login.ugnet.gay/ApproveSession.srfhttps://ctas.login.ugnet.gay/ManageLoginKeys.srf \ No newline at end of file + https://account.ugnet.xyz + http://ctas.login.ugnet.xyz/hp.srf?format=b1 + http://ctas.login.ugnet.xyz/ppcrlcheck.srf*.ugnet.xyzctas.login.ugnet.xyz,account.ugnet.xyzc.ugnet.xyz,c.msn.comhttps://ctas.login.ugnet.xyz/RST2.srfhttps://ctas.login.ugnet.xyz/RST2.srfhttps://ctas.login.ugnet.xyz/didtou.srfhttps://ctas.login.ugnet.xyz/ppsecure/devicechangecredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/deviceaddcredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/deviceremovecredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceAssociate.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceDisassociate.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceQuery.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceUpdate.srfhttps://ctas.login.ugnet.xyz/ppsecure/EnumerateDevices.srfhttps://ctas.login.ugnet.xyz/ppsecure/ResolveUser.srfEIDhttps://ctas.login.ugnet.xyz/getrealminfo.srfhttps://ctas.login.ugnet.xyz/getuserrealm.srfhttps://ctas.login.ugnet.xyz/retention.srfhttps://signup.ugnet.xyz/signup.aspxhttp://go.microsoft.com/fwlink/p/?LinkId=253457https://ctas.login.ugnet.xyz/ppsecure/GetUserKeyData.srfhttps://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80500https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80500https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&id=80500https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80501https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80501https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&id=80501https://account.ugnet.xyz/Wizard/Password/Change?id=80501https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80502https://account.ugnet.xyz/InlineSignup.aspx?iww=1&id=80502https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&id=80502https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80600https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80600https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&id=80600https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80600https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80601https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80601https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&id=80601https://account.ugnet.xyz/Wizard/Password/Change?id=80601https://ctas.login.ugnet.xyz/ppsecure/InlinePOPAuth.srf?id=80601&fid=cphttps://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80601https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80603https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80603https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80603https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80604https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80604https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80604https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80604https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80605https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80605https://ctas.login.ugnet.xyz/ppsecure/InlinePOPAuth.srf?id=80605https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80606https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80607https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80608https://account.ugnet.xyz/msangcwamhttps://account.microsoft.com/?ref=settingshttp://go.microsoft.com/fwlink/?LinkId=248215https://ctas.login.ugnet.xyz/ppsecure/InlineClientAuth.srfhttps://ctas.login.ugnet.xyz/ppsecure/InlineDesktop.srfhttps://ctas.login.ugnet.xyz/ManageApprover.srfhttps://ctas.login.ugnet.xyz/ListSessions.srfhttps://ctas.login.ugnet.xyz/ApproveSession.srfhttps://ctas.login.ugnet.xyz/ManageLoginKeys.srf \ No newline at end of file diff --git a/front/msn/http/tmpl/config/wlidsvcconfig.xml b/front/msn/http/tmpl/config/wlidsvcconfig.xml index e7e086f..309d444 100644 --- a/front/msn/http/tmpl/config/wlidsvcconfig.xml +++ b/front/msn/http/tmpl/config/wlidsvcconfig.xml @@ -3,5 +3,5 @@ When a certificate is rev'd, a line like the following should be added to the cfg:Settings section: SLCA_BACKUP.CER - -->.devicedns.ugnet.gay1200006000030000300001440https://go.microsoft.com/fwlink/?LinkId=85952411{1C109E4C-2F30-4EA3-A57A-A290877A2303}Win32_USBControllerDeviceWin32_1394ControllerDeviceWin32_PCMCIAControllerDeviceWin32_ConnectionShareSerialNumberMACAddressManufacturerSerialNumber]]>01{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}0311{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}0211MIIDGzCCAtugAwIBAgIJAL6pALeLZHDvMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTE2MDUwOTIwNDA1NVoXDTIxMDUwODIwNDA1NVowIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASwGByqGSM44BAEwggEfAoGBAKmnM6FKnJ1osHWBHd8jHFFMDNwygIcof9EfHW6xJbU2uIzVV5WRu251RbRbmOqozesK44vkeBx9Ntl7PSu0W5RJFCEw9o4RLG0J40MWDNDQ+7iqvIsM6lsgZrDjNoWJ2t/Yrnnp0r3F9YNtj7J4vgLCYNOlkr2kcfGiji+SXotXAhUAqGI2zlbARtjz+simu2PihUPkV1MCgYEAnrIIXPvjKvWiXd3uve7eDS8qRHW7yoAseVLgeEIbS4VSj/9iQqunx1weQGlds75CLZgpcrY4Z5wbkxSjnK1EV30qce4+VzgXYGLZIAvl78wbAMFrG0josXccAbmqVM4LX2Z5yu1TEpPZLvgiaV4gJk4jsYhInqPm3Bw2qQ+gZokDgYQAAoGAFozcPQdM9MmszvEWMXuFrfEA8kVMnKIyA60paSi7CIecSAlsRLyw3D9J9pRW6HHdRZgOrKvnNcY63gKB56SKyj6r3nGqtkwEpu9yw1K+k2aSyJcKPHYVNw1Um5McKJgQJ49ShJFPaWXfDZPOCpgMpdzibnWjMcTak5rz4FHSUtOjgZgwgZUwHQYDVR0OBBYEFKNT6lUDzQppxFhwtv/jkSCRx596MFMGA1UdIwRMMEqAFKNT6lUDzQppxFhwtv/jkSCRx596oSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQC+qQC3i2Rw7zASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAy8AMCwCFGjnp838qB/wTUdvoRt4G3aW0fv0AhRe8cZDdOveTDCbWane65nlVv0Udw==MIIDHDCCAtugAwIBAgIJAPVhDwwaTUJrMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTIxMDMxODE4NDIzN1oXDTQxMDMxMzE4NDIzN1owIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASsGByqGSM44BAEwggEeAoGBANwZEes+CsJ6G4/Pe5XmGS9e5qki7KPMh9+IU5JE+z0H0Q4v51cKYCcm0OHtStB4oTF3RqTcYT6wYp/k6CcrGUVKo60tWY3C+ohOABpfoAnstLX/bZmWYQ87KzkRpB21WGCAJsoNQ5V0oQbwnEeeWO5sfZ6T3lfP7YgyeY4NatWhAhUAhFP2mQrVRzurTrsPRs5S1aNUWWUCgYBw3lXgm9xw1G9BSs8mP9sv8IefC87tBupniaUY/lz+AlN0qs6tXPHSesobCFxLDNT0Vhw4fSTJBPlq99tvV6ipEQkBtR3ColMVMq0G7ECW8ojnPWUcwdYUCyky7kyV7EuwnUYoAN4nZWBhN9BOj/nO0Ds5HInryR0RnTEvT0uojwOBhQACgYEA2SDhhPBDnKxvmH9RHvTUW0pvaTyAbFXxQ1WP+rcN608akqKmyMiskxCUySoBGAEbE/szcBqTu4VpvskyOBHY6Li6ewYP5cpVe7mARh27+cuGOzz3JZAVwi79D6u9/6OxnLyfbdRpYFq0qlmtUSbqtp895cs0cLn8TIppt+h6iDKjgZgwgZUwHQYDVR0OBBYEFNggH9qn8tEAK/Xtp75ejkmJcgjwMFMGA1UdIwRMMEqAFNggH9qn8tEAK/Xtp75ejkmJcgjwoSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQD1YQ8MGk1CazASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAzAAMC0CFHDGG3jer0Hzy/Qr08Dx/XpQGPG/AhUAg5mwhsY1EvBXNSor8eaySNirEH0=900560060000account.ugnet.gayaccount.ugnet.gayaccount.ugnet.gay/password/resetsapimbi_sslmbi_ssl_sa8212007200dc2191f2-1801-4fd8-84bd-e776344a34b04132880016.000.29743.005022331msn.comctas.login.ugnet.gayugnet.gayctas.login.ugnet.gay,signup.ugnet.gay,account.ugnet.gaylogin.srf;()]]>;'()]]>';()]]>post.srfManageEIDs.srfsecure.srflogout.srfhiden.cc,ugnet.gay,ctsrv.gay,crosstalk.im,ugnet.gay,ctsrv.gay,crosstalk.im,ugnet.gay,ctsrv.gay,crosstalk.im,live.com,msn.com,zune.net,windowsmarketplace.com,workspace.office.ugnet.gay,atdmt.comhttps://ctas.login.ugnet.gay/resetpw.srfhttps://ctas.login.ugnet.gay/ppsecure/SHA1Auth.srf*.ugnet.gayctas.login.ugnet.gay,account.ugnet.gayc.ugnet.gay,c.msn.comhttps://ctas.login.ugnet.gay/RST2.srfhttps://ctas.login.ugnet.gay/didtou.srfhttps://ctas.login.ugnet.gay/ppsecure/devicechangecredential.srfhttps://ctas.login.ugnet.gay/ppsecure/deviceaddcredential.srfhttps://ctas.login.ugnet.gay/ppsecure/deviceremovecredential.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceAssociate.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceDisassociate.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceQuery.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceUpdate.srfhttps://ctas.login.ugnet.gay/ppsecure/EnumerateDevices.srfhttps://ctas.login.ugnet.gay/ppsecure/ResolveUser.srfhttps://ctas.login.ugnet.gay/MSARST2.srfhttps://ctas.login.ugnet.gay/ppsecure/devicechangecredential.srfhttps://ctas.login.ugnet.gay/ppsecure/deviceaddmsacredential.srfhttps://ctas.login.ugnet.gay/ppsecure/deviceremovecredential.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceAssociate.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceDisassociate.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceQuery.srfhttps://ctas.login.ugnet.gay/ppsecure/DeviceUpdate.srfhttps://ctas.login.ugnet.gay/ppsecure/EnumerateDevices.srfhttps://ctas.login.ugnet.gay/ppsecure/ResolveUser.srfEIDhttps://ctas.login.ugnet.gay/getrealminfo.srfhttps://ctas.login.ugnet.gay/getuserrealm.srfhttps://ctas.login.ugnet.gay/retention.srfhttps://signup.ugnet.gay/signup.aspxhttp://go.microsoft.com/fwlink/p/?LinkId=253457https://ctas.login.ugnet.gay/ppsecure/GetUserKeyData.srfhttps://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80502https://account.ugnet.gay/InlineSignup.aspx?iww=1&id=80502https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&id=80502https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80600https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80600https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&id=80600https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80600https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80601https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80601https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&id=80601https://account.ugnet.gay/Wizard/Password/Change?id=80601https://ctas.login.ugnet.gay/ppsecure/InlinePOPAuth.srf?id=80601&fid=cphttps://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80601https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80603https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80603https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80603https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80604https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80604https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80604https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80604https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80605https://account.ugnet.gay/inlinesignup.aspx?iww=1&id=80605https://ctas.login.ugnet.gay/ppsecure/InlinePOPAuth.srf?id=80605https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80606https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80607https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80608https://account.ugnet.gay/msangcwamhttps://account.microsoft.com/?ref=settingshttp://go.microsoft.com/fwlink/?LinkId=248215https://ctas.login.ugnet.gay/ppsecure/InlineClientAuth.srfhttps://ctas.login.ugnet.gay/ppsecure/InlineDesktop.srfhttps://ctas.login.ugnet.gay/ManageApprover.srfhttps://ctas.login.ugnet.gay/ListSessions.srfhttps://ctas.login.ugnet.gay/ApproveSession.srfhttps://ctas.login.ugnet.gay/ManageLoginKeys.srfhttps://ctas.login.ugnet.gay/ppsecure/GetAppData.srf \ No newline at end of file + -->.devicedns.ugnet.xyz1200006000030000300001440https://go.microsoft.com/fwlink/?LinkId=85952411{1C109E4C-2F30-4EA3-A57A-A290877A2303}Win32_USBControllerDeviceWin32_1394ControllerDeviceWin32_PCMCIAControllerDeviceWin32_ConnectionShareSerialNumberMACAddressManufacturerSerialNumber]]>01{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}0311{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}0211MIIDGzCCAtugAwIBAgIJAL6pALeLZHDvMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTE2MDUwOTIwNDA1NVoXDTIxMDUwODIwNDA1NVowIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASwGByqGSM44BAEwggEfAoGBAKmnM6FKnJ1osHWBHd8jHFFMDNwygIcof9EfHW6xJbU2uIzVV5WRu251RbRbmOqozesK44vkeBx9Ntl7PSu0W5RJFCEw9o4RLG0J40MWDNDQ+7iqvIsM6lsgZrDjNoWJ2t/Yrnnp0r3F9YNtj7J4vgLCYNOlkr2kcfGiji+SXotXAhUAqGI2zlbARtjz+simu2PihUPkV1MCgYEAnrIIXPvjKvWiXd3uve7eDS8qRHW7yoAseVLgeEIbS4VSj/9iQqunx1weQGlds75CLZgpcrY4Z5wbkxSjnK1EV30qce4+VzgXYGLZIAvl78wbAMFrG0josXccAbmqVM4LX2Z5yu1TEpPZLvgiaV4gJk4jsYhInqPm3Bw2qQ+gZokDgYQAAoGAFozcPQdM9MmszvEWMXuFrfEA8kVMnKIyA60paSi7CIecSAlsRLyw3D9J9pRW6HHdRZgOrKvnNcY63gKB56SKyj6r3nGqtkwEpu9yw1K+k2aSyJcKPHYVNw1Um5McKJgQJ49ShJFPaWXfDZPOCpgMpdzibnWjMcTak5rz4FHSUtOjgZgwgZUwHQYDVR0OBBYEFKNT6lUDzQppxFhwtv/jkSCRx596MFMGA1UdIwRMMEqAFKNT6lUDzQppxFhwtv/jkSCRx596oSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQC+qQC3i2Rw7zASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAy8AMCwCFGjnp838qB/wTUdvoRt4G3aW0fv0AhRe8cZDdOveTDCbWane65nlVv0Udw==MIIDHDCCAtugAwIBAgIJAPVhDwwaTUJrMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTIxMDMxODE4NDIzN1oXDTQxMDMxMzE4NDIzN1owIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASsGByqGSM44BAEwggEeAoGBANwZEes+CsJ6G4/Pe5XmGS9e5qki7KPMh9+IU5JE+z0H0Q4v51cKYCcm0OHtStB4oTF3RqTcYT6wYp/k6CcrGUVKo60tWY3C+ohOABpfoAnstLX/bZmWYQ87KzkRpB21WGCAJsoNQ5V0oQbwnEeeWO5sfZ6T3lfP7YgyeY4NatWhAhUAhFP2mQrVRzurTrsPRs5S1aNUWWUCgYBw3lXgm9xw1G9BSs8mP9sv8IefC87tBupniaUY/lz+AlN0qs6tXPHSesobCFxLDNT0Vhw4fSTJBPlq99tvV6ipEQkBtR3ColMVMq0G7ECW8ojnPWUcwdYUCyky7kyV7EuwnUYoAN4nZWBhN9BOj/nO0Ds5HInryR0RnTEvT0uojwOBhQACgYEA2SDhhPBDnKxvmH9RHvTUW0pvaTyAbFXxQ1WP+rcN608akqKmyMiskxCUySoBGAEbE/szcBqTu4VpvskyOBHY6Li6ewYP5cpVe7mARh27+cuGOzz3JZAVwi79D6u9/6OxnLyfbdRpYFq0qlmtUSbqtp895cs0cLn8TIppt+h6iDKjgZgwgZUwHQYDVR0OBBYEFNggH9qn8tEAK/Xtp75ejkmJcgjwMFMGA1UdIwRMMEqAFNggH9qn8tEAK/Xtp75ejkmJcgjwoSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQD1YQ8MGk1CazASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAzAAMC0CFHDGG3jer0Hzy/Qr08Dx/XpQGPG/AhUAg5mwhsY1EvBXNSor8eaySNirEH0=900560060000account.ugnet.xyzaccount.ugnet.xyzaccount.ugnet.xyz/password/resetsapimbi_sslmbi_ssl_sa8212007200dc2191f2-1801-4fd8-84bd-e776344a34b04132880016.000.29743.005022331msn.comctas.login.ugnet.xyzugnet.xyzctas.login.ugnet.xyz,signup.ugnet.xyz,account.ugnet.xyzlogin.srf;()]]>;'()]]>';()]]>post.srfManageEIDs.srfsecure.srflogout.srfhiden.cc,ugnet.xyz,ctsrv.xyz,crosstalk.im,ugnet.xyz,ctsrv.xyz,crosstalk.im,ugnet.xyz,ctsrv.xyz,crosstalk.im,live.com,msn.com,zune.net,windowsmarketplace.com,workspace.office.ugnet.xyz,atdmt.comhttps://ctas.login.ugnet.xyz/resetpw.srfhttps://ctas.login.ugnet.xyz/ppsecure/SHA1Auth.srf*.ugnet.xyzctas.login.ugnet.xyz,account.ugnet.xyzc.ugnet.xyz,c.msn.comhttps://ctas.login.ugnet.xyz/RST2.srfhttps://ctas.login.ugnet.xyz/didtou.srfhttps://ctas.login.ugnet.xyz/ppsecure/devicechangecredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/deviceaddcredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/deviceremovecredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceAssociate.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceDisassociate.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceQuery.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceUpdate.srfhttps://ctas.login.ugnet.xyz/ppsecure/EnumerateDevices.srfhttps://ctas.login.ugnet.xyz/ppsecure/ResolveUser.srfhttps://ctas.login.ugnet.xyz/MSARST2.srfhttps://ctas.login.ugnet.xyz/ppsecure/devicechangecredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/deviceaddmsacredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/deviceremovecredential.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceAssociate.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceDisassociate.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceQuery.srfhttps://ctas.login.ugnet.xyz/ppsecure/DeviceUpdate.srfhttps://ctas.login.ugnet.xyz/ppsecure/EnumerateDevices.srfhttps://ctas.login.ugnet.xyz/ppsecure/ResolveUser.srfEIDhttps://ctas.login.ugnet.xyz/getrealminfo.srfhttps://ctas.login.ugnet.xyz/getuserrealm.srfhttps://ctas.login.ugnet.xyz/retention.srfhttps://signup.ugnet.xyz/signup.aspxhttp://go.microsoft.com/fwlink/p/?LinkId=253457https://ctas.login.ugnet.xyz/ppsecure/GetUserKeyData.srfhttps://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80502https://account.ugnet.xyz/InlineSignup.aspx?iww=1&id=80502https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&id=80502https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80600https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80600https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&id=80600https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80600https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80601https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80601https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&id=80601https://account.ugnet.xyz/Wizard/Password/Change?id=80601https://ctas.login.ugnet.xyz/ppsecure/InlinePOPAuth.srf?id=80601&fid=cphttps://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80601https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80603https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80603https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80603https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80604https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80604https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80604https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80604https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80605https://account.ugnet.xyz/inlinesignup.aspx?iww=1&id=80605https://ctas.login.ugnet.xyz/ppsecure/InlinePOPAuth.srf?id=80605https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80606https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80607https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80608https://account.ugnet.xyz/msangcwamhttps://account.microsoft.com/?ref=settingshttp://go.microsoft.com/fwlink/?LinkId=248215https://ctas.login.ugnet.xyz/ppsecure/InlineClientAuth.srfhttps://ctas.login.ugnet.xyz/ppsecure/InlineDesktop.srfhttps://ctas.login.ugnet.xyz/ManageApprover.srfhttps://ctas.login.ugnet.xyz/ListSessions.srfhttps://ctas.login.ugnet.xyz/ApproveSession.srfhttps://ctas.login.ugnet.xyz/ManageLoginKeys.srfhttps://ctas.login.ugnet.xyz/ppsecure/GetAppData.srf \ No newline at end of file diff --git a/front/msn/http/tmpl/oim/Fault.messagetoolarge.xml b/front/msn/http/tmpl/oim/Fault.messagetoolarge.xml new file mode 100644 index 0000000..dc2fab0 --- /dev/null +++ b/front/msn/http/tmpl/oim/Fault.messagetoolarge.xml @@ -0,0 +1,13 @@ + + + + + + + + q0:MessageTooLarge + Exception of type 'System.Web.Services.Protocols.SoapException' was thrown. + + + + diff --git a/front/msn/http/tmpl/profile/ProfileResponse.xml b/front/msn/http/tmpl/profile/ProfileResponse.xml new file mode 100644 index 0000000..461e465 --- /dev/null +++ b/front/msn/http/tmpl/profile/ProfileResponse.xml @@ -0,0 +1,64 @@ + +{%- macro profile_id(profile) %} + Cid + {{ cid_format(profile.user.uuid, decimal = True) }} + {%- if profile.puid is none %} + Unspecified + + {%- else %} + Puid + {{ profile.puid }} + {%- endif %} + Unspecified + +{%- endmacro %} +{%- macro profile_view(profile) %} + + WLX.DC.CoreProfile + 1 + + PublicProfile.ResourceId{{ profile.cid }}!106 + PublicProfile.DisplayName{{ (profile.user.first_name or '')|e }} + PublicProfile.DisplayName.LastModified{{ now }} + PublicProfile.DisplayLastName{{ (profile.user.last_name or '')|e }} + PublicProfile.DisplayLastName.LastModified{{ now }} + ExpressionProfile.ResourceId{{ profile.cid }}!118 + ExpressionProfile.DisplayName{{ (profile.roaming_info.name or profile.user.status.name or '')|e }} + ExpressionProfile.DisplayName.LastModified{{ date_format(profile.roaming_info.name_last_modified) }} + ExpressionProfile.PersonalStatus{{ (profile.roaming_info.message or '')|e }} + ExpressionProfile.PersonalStatus.LastModified{{ date_format(profile.roaming_info.message_last_modified) }} + ExpressionProfile.StaticUserTilePublicURLhttps://{{ host }}/avatar/{{ profile.user.uuid }}/im + UserTileStaticUrlhttps://{{ host }}/avatar/{{ profile.user.uuid }}/im + PictureProfile.UserTileStatic.ResourceId{{ profile.cid }}!205 + LastModified{{ now }} + + +{%- endmacro %} + + + <{{ action }}Response xmlns="http://profile.live.com/"> + <{{ action }}Result> + + {{ host }} + 0 + + {%- if action == 'GetMany' %} + + {%- for profile in profiles %} + {{ profile_id(profile) }} + + {%- endfor %} + + {%- else %} + {{ profile_id(profiles[0]) }} + + {%- endif %} + {%- if action == 'GetMany' %} + + {%- for profile in profiles %}{{ profile_view(profile) }}{%- endfor %} + + {%- else %}{{ profile_view(profiles[0]) }}{%- endif %} + + + + \ No newline at end of file diff --git a/front/msn/http/tmpl/sharing/FindMembershipResponse.xml b/front/msn/http/tmpl/sharing/FindMembershipResponse.xml index e0a4965..b830a0e 100644 --- a/front/msn/http/tmpl/sharing/FindMembershipResponse.xml +++ b/front/msn/http/tmpl/sharing/FindMembershipResponse.xml @@ -15,56 +15,56 @@ - {% for lst in lists %} + {%- for lst in lists %} - {{ lst.label }} - - {% for contact in detail.contacts.values() %} - {% if (contact.lists.__and__(lst) and lst not in (ContactList.AL,ContactList.BL,ContactList.RL)) or (lst in (ContactList.AL,ContactList.BL,ContactList.RL) and contact.lists.__and__(lst) and not contact.pending) %} - - {{ lst.label }}/{{ contact.head.uuid }} - Passport - Accepted - false - {{ now }} - {{ date_format(contact.head.date_created) }} - 0001-01-01T00:00:00 - - {{ contact.head.email }} - false - 0 - {{ cid_format(contact.head.uuid, decimal = True) }} - - false - - {% endif %} - {% endfor %} - {% if lst == ContactList.BL %} - {% for circle in circles %} - {% if circle.memberships[user.uuid].blocking %} - - Block/00000000-0000-0000-0009-{{ circle.chat_id }} - Circle - Accepted - false - {{ now }} - {{ now }} - 0001-01-01T00:00:00 - - 00000000-0000-0000-0009-{{ circle.chat_id }} - - {% endif %} - {% endfor %} - {% endif %} - - true - - {% endfor %} + {{ lst.label }} + + {%- for contact in detail.contacts.values() %} + {%- if (contact.lists.__and__(lst) and lst not in (ContactList.AL,ContactList.BL,ContactList.RL)) or (lst in (ContactList.AL,ContactList.BL,ContactList.RL) and contact.lists.__and__(lst) and not contact.pending) %} + + {{ lst.label }}/{{ contact.head.uuid }} + Passport + Accepted + false + {{ now }} + {{ date_format(contact.head.date_created) }} + 0001-01-01T00:00:00 + + {{ contact.head.email }} + false + 0 + {{ cid_format(contact.head.uuid, decimal = True) }} + + false + + {%- endif %} + {%- endfor %} + {%- if lst == ContactList.BL %} + {%- for circle in circles %} + {%- if circle.memberships[user.uuid].blocking %} + + Block/00000000-0000-0000-0009-{{ circle.chat_id }} + Circle + Accepted + false + {{ now }} + {{ now }} + 0001-01-01T00:00:00 + + 00000000-0000-0000-0009-{{ circle.chat_id }} + + {%- endif %} + {%- endfor %} + {%- endif %} + + true + + {%- endfor %} Pending - {% for contact in detail.contacts.values() %} - {% if contact.pending and not contact.lists.__and__(ContactList.FL) %} + {%- for contact in detail.contacts.values() %} + {%- if contact.pending and not contact.lists.__and__(ContactList.FL) %} Pending/{{ contact.head.uuid }} Passport @@ -81,8 +81,8 @@ false - {% endif %} - {% endfor %} + {%- endif %} + {%- endfor %} true diff --git a/front/msn/http/tmpl/storageservice/Fault.storage.xml b/front/msn/http/tmpl/storageservice/Fault.storage.xml new file mode 100644 index 0000000..0738506 --- /dev/null +++ b/front/msn/http/tmpl/storageservice/Fault.storage.xml @@ -0,0 +1,15 @@ + + + + + soap:Client + {{ errorstring }} + http://www.msn.com/webservices/storage/{{ storage_ns }}/{{ action_str }} + + {{ errorcode }} + {{ errorstring }} + BL2STRWBA103 + + + + diff --git a/front/msn/http/tmpl/storageservice/GetProfileResponse.xml b/front/msn/http/tmpl/storageservice/GetProfileResponse.xml index a3db2a3..9157821 100644 --- a/front/msn/http/tmpl/storageservice/GetProfileResponse.xml +++ b/front/msn/http/tmpl/storageservice/GetProfileResponse.xml @@ -34,7 +34,7 @@ UserTileStatic image/{{ mime }} {{ size_static }} - https://{{ host }}/avatar/{{ user.uuid }}/msn + https://{{ host }}/avatar/{{ user.uuid }}/im Overwrite None None @@ -68,7 +68,7 @@ {{ roaming_info.name }} {{ date_format(roaming_info.name_last_modified) }} {% endif %} - https://{{ host }}/avatar/{{ user.uuid }}/msn + https://{{ host }}/avatar/{{ user.uuid }}/im diff --git a/front/msn/http/tmpl/svcs/videofeedroot.xml b/front/msn/http/tmpl/svcs/videofeedroot.xml index 52ca989..caed5e7 100644 --- a/front/msn/http/tmpl/svcs/videofeedroot.xml +++ b/front/msn/http/tmpl/svcs/videofeedroot.xml @@ -5,7 +5,7 @@ https://{{ settings.WEBSITE_HOST }} CrossTalk Video en-us - 2023 - 2026 the undergr0und + 2023 - 2026 hiden Thu, 05 Sep 2024 5:48:54 GMT MSN_Microsoft 0 diff --git a/front/msn/http/tmpl/whatsnew/WhatsNewResponse.xml b/front/msn/http/tmpl/whatsnew/WhatsNewResponse.xml index b9b9432..52c8651 100644 --- a/front/msn/http/tmpl/whatsnew/WhatsNewResponse.xml +++ b/front/msn/http/tmpl/whatsnew/WhatsNewResponse.xml @@ -4,58 +4,231 @@ xmlns:xsd="http://www.w3.org/2001/XMLSchema"> - 15.1.1216.0 + 17.4.0.0 + false - - + <{{ action }}Response xmlns="http://www.msn.com/webservices/AddressBook"> + <{{ action }}Result> + {%- for activity in activities %} + {%- if activity.user %} + {%- set tile = 'https://' ~ settings.USERSTORAGE_HOST ~ '/avatar/' ~ activity.user.uuid ~ '/im' %} + {%- set profile = 'https://' ~ settings.WEBSITE_HOST ~ '/profile/+' ~ activity.user.username %} + {%- else %} + {%- set profile = activity.url or 'https://' ~ settings.WEBSITE_HOST %} + {%- endif %} - 0 - Fri, 08 Jan 2025 4:59:43 CDT - 420 - 20 - {date} + {{ owner_cid }} + {% if activity.type == 1 %}msgr_status_{{ activity.id }}{% elif activity.type == 3 %}msgr_dp_{{ activity.id }}{% elif activity.type == 2 %}msgr_photo_{{ activity.id }}{% else %}announcement_{{ activity.date_created.strftime('%Y%m%d%H%M%S') }}_{{ activity.id }}{% endif %} + {{ 1275182653 if activity.user else 420 }} + {{ activity.type|int }} + {{ date_format(activity.date_created) }} - - Name - {title} + {%- if activity.user %} + + + Live.RecentActivity.UserTileM{{ tile }} + Live.RecentActivity.UserTileL{{ tile }} + Live.RecentActivity.UserTileXL{{ tile }} + + publisher + {{ cid_format(activity.user.uuid, decimal = True) }} + {{ activity.user.status.name|e }} + {{ tile }} + {{ profile }} + {{ bool_to_str(activity.user.uuid in detail.contacts and contact_is_favorite(detail, detail.contacts[activity.user.uuid])) }} - - Url - {url} - + + + Live.RecentActivity.IsSelfPageUrltrue + + AppName + {{ profile }} + {{ profile }} + + {%- if activity.type == 3 %} + + StatusText + has a new display picture + + + DisplayPicture + {{ tile }} + {{ profile }} + {{ profile }} + + {%- elif activity.type == 2 %} + + CanonicalStatusText + {{ (activity.text or 'shared a photo')|e }} + + + Photo + {{ activity.url|e }} + {{ activity.url|e }} + {{ activity.url|e }} + + {%- else %} + + CanonicalStatusText + {{ activity.text|e }} + + {%- endif %} + {%- else %} + + publisher + 0 + {{ activity.title|e }} + + {{ profile|e }} + false + + + AppName + {{ profile|e }} + Announcements + {{ profile|e }} + + + CanonicalStatusText + {{ activity.text|e }} + + {%- endif %} + 1000000{{ activity.type|int if activity.user else 0 }}-0000-4000-8000-{{ '%012x'|format(activity.id) }} + + 0 + + + {{ '%.7f'|format(1 / (1 + (now - activity.date_created).total_seconds() / 86400)) }} + + false + 0 + false + {%- endfor %} + {%- if 3 in types %} - 420 - {appName} + 1275182653 + Messenger 0 0 - 20 - en-us + 3 + {{ locale|e }} - en-US + {{ locale|e }} - 1 + 2116 One - CrossTalk News - {content} + {image:DisplayPicture style="floatleft"} + {publisher-id:publisher} {text:StatusText="has a new display picture"} + + + MessengerGrid + + TypePhoto + PrimaryImage{image:DisplayPicture} + Publisher{publisher-id:publisher} + Action{text:StatusText="has a new display picture"} + + + - blog + status + photo false + false + {%- endif %} + {%- if 2 in types %} + + 1275182653 + Messenger + 0 + 0 + 2 + {{ locale|e }} + + {{ locale|e }} + + 2116 + + + One + {image:Photo style="floatleft"} + {publisher-id:publisher} {text:CanonicalStatusText} + + + MessengerGrid + + TypePhoto + PrimaryImage{image:Photo} + Publisher{publisher-id:publisher} + Action{text:CanonicalStatusText} + + + + + + + status + photo + + false + false + + {%- endif %} + {%- for change_type, application_id, application_name in ((1, 1275182653, 'Messenger'), (20, 420, 'Announcements')) if change_type in types %} + + {{ application_id }} + {{ application_name }} + 0 + 0 + {{ change_type }} + {{ locale|e }} + + {{ locale|e }} + + 2116 + + + One + + {publisher-id:publisher} {text:CanonicalStatusText} + + + MessengerGrid + + TypeStatus + Publisher{publisher-id:publisher} + Action{text:CanonicalStatusText} + {%- if change_type == 20 %} + Footervia {hlink:AppName} + {%- endif %} + + + + + + + status + + false + false + + {%- endfor %} - http://{{ settings.WEBSITE_HOST }} - - + https://{{ settings.SOCIAL_HOST }} + + diff --git a/front/msn/http/util.py b/front/msn/http/util.py index 4632bc1..5403305 100644 --- a/front/msn/http/util.py +++ b/front/msn/http/util.py @@ -20,7 +20,7 @@ async def preprocess_soap(req: web.Request) -> Tuple[Any, Any, Optional[BackendS mspauth = False body = await req.read() - root = parse_xml(body) + root = parse_xml(body[:body.rfind(b'>') + 1]) token = find_element(root, 'TicketToken') if token is None: @@ -48,6 +48,66 @@ async def preprocess_soap(req: web.Request) -> Tuple[Any, Any, Optional[BackendS return header, action, backend_sess, token +# What the Address Book and Contact Sharing services say for each of their error codes (`` in a fault's ``) +ABCH_FAULT_STRINGS = { + 'ABAlreadyExists': 'Address Book Already Exists ', + 'ABDoesNotExist': 'Address Book Does Not Exist ', + 'BadArgumentLength': 'Argument Exceeded Allowed Length', + 'BadEmailArgument': 'Malformed email Argument', + 'ContactAlreadyExists': 'Contact Already Exists ', + 'ContactDoesNotExist': 'Contact Does Not Exist ', + 'DynamicItemDoesNotExist': 'Dynamic Item Does Not Exist ', + 'EmailDomainIsFederated': 'Email Domain Is Federated ', + 'FullSyncRequired': 'Full sync required. Details: Delta syncs disabled.', + 'GroupAlreadyExists': 'Group Already Exists ', + 'GroupDoesNotExist': 'Group Does Not Exist ', + 'InvalidPassportUser': 'The Passport user specified is invalid', + 'InvalidSyncTimeStamp': 'Invalid Sync Time Stamp ', + 'MemberAlreadyExists': 'Member already exists ', + 'MemberDoesNotExist': 'Member does not exist ', + 'PassportAuthFail': 'Passport Authentication Failed ', + 'RequestLimitReached': 'Request Limit Reached ', + 'SecureConnectionRequired': 'Secure Connection Required ', + 'UserDoesNotExist': 'User does not exist ', +} + +# The same for the Schematized Storage service +STORAGE_FAULT_STRINGS = { + 'AccessDenied': 'Access Denied ', + 'GeneralException': 'General Exception ', + 'ItemAlreadyExists': 'Item Already Exists ', + 'ItemDoesNotExist': 'Item Does Not Exist ', + 'InvalidObjectHandle': 'Invalid Object Handle ', + 'InvalidDocumentStream': 'Invalid Document Stream ', +} + +def abch_fault( + req: web.Request, action_str: str, errorcode: str, *, errorstring: Optional[str] = None, faultcode: str = 'soap:Client', + parameter_fault: Optional[str] = None, conflict_object_id: Optional[str] = None, +) -> web.Response: + # An Address Book or Contact Sharing service fault (`errorcode` is one of `ABCH_FAULT_STRINGS`) + return render(req, 'msn:abservice/Fault.abch.xml', { + 'action_str': action_str, 'faultcode': faultcode, 'errorcode': errorcode, + 'errorstring': (errorstring or ABCH_FAULT_STRINGS.get(errorcode) or errorcode), 'parameter_fault': parameter_fault, + 'conflict_object_id': conflict_object_id, + }, status = 500) + +def storage_fault(req: web.Request, storage_ns: str, action_str: str, errorcode: str, *, errorstring: Optional[str] = None) -> web.Response: + # A Schematized Storage service fault (`errorcode` is one of `STORAGE_FAULT_STRINGS`) + return render(req, 'msn:storageservice/Fault.storage.xml', { + 'storage_ns': storage_ns, 'action_str': action_str, 'errorcode': errorcode, + 'errorstring': (errorstring or STORAGE_FAULT_STRINGS.get(errorcode) or errorcode), + }, status = 500) + +def schema_fault(req: web.Request, actor: str, faultstring: Optional[str] = None) -> web.Response: + # A request that's missing something, or has something that isn't allowed where it is (or `faultstring`, for a request + # that's fine but can't be done) + return render(req, 'msn:Fault.schema.xml', { 'actor': actor, 'faultstring': faultstring }, status = 500) + +def server_fault(req: web.Request, actor: Optional[str] = None) -> web.Response: + # Something went wrong handling the request; what it was stays in the server's log + return render(req, 'msn:Fault.server.xml', { 'actor': actor }, status = 500) + def get_tag_localname(elm: Any) -> str: return lxml.etree.QName(elm.tag).localname @@ -90,3 +150,26 @@ def parse_cookies(cookie_string: Optional[str]) -> Dict[str, Any]: cookie_dict[cookie_kv[0]] = cookie_data return cookie_dict + +async def dispatch_abch(req: web.Request, module: Any, prefix: str) -> web.Response: + header, action, bs, _ = await preprocess_soap(req) + if bs is None: + raise web.HTTPForbidden() + action_str = get_tag_localname(action) + if find_element(action, 'deltasOnly') or find_element(action, 'DeltasOnly'): + return render(req, 'msn:abservice/Fault.fullsync.xml', { 'faultactor': action_str }) + + if settings.DEBUG_FULL: + print(xml_to_string(action)) + + method = getattr(module, prefix + '_' + action_str, None) + if not method: + return unknown_soap(req, header, action) + + try: + return method(req, header, action, bs) + except: + import traceback + # The traceback goes to the log, not to the client + traceback.print_exc() + return server_fault(req, 'http://www.msn.com/webservices/AddressBook/{}'.format(action_str)) \ No newline at end of file diff --git a/front/msn/misc.py b/front/msn/misc.py index 7146e9d..410c540 100644 --- a/front/msn/misc.py +++ b/front/msn/misc.py @@ -13,10 +13,12 @@ from core import error from core.backend import Backend, BackendSession from core.models import User, OIM, Substatus, NetworkID, CircleState, Circle + def build_presence_notif( trid: Optional[str], old_substatus: Optional[Substatus], ctc_head: User, user_me: User, dialect: int, backend: Backend, iln_sent: bool, update_info: bool, *, self_presence: bool = False, update_status: bool = True, circle: Optional['Circle'] = None, circle_owner: bool = False, + announced_epids: dict[str, set[str]] | None = None, ) -> Iterable[Tuple[Any, ...]]: detail = user_me.detail assert detail is not None @@ -47,10 +49,9 @@ def build_presence_notif( head_display_email = backend.util_get_display_email(head) user_me_display_email = backend.util_get_display_email(user_me) - # TODO: This is insanely ugly. if dialect >= 19: + if circle is not None and circle_owner: return cm = None # type: Optional[str] - pop_id_ctc = None # type: Optional[str] substatus = status.substatus @@ -64,70 +65,20 @@ def build_presence_notif( cm = NFY_PUT_PRESENCE_USER_S_CM.format(cm = encode_xml_he(status.media or '', dialect)) nfy_rst += NFY_PUT_PRESENCE_USER_S_PE.format( msnobj = encode_xml_he(ctc_sess.front_data.get('msn_msnobj') or '', dialect), - name = status.name or head_display_email, message = status.message, + name = encode_xml_he(status.name or head_display_email, dialect), message = encode_xml_he(status.message or '', dialect), ddp = encode_xml_he(ctc_sess.front_data.get('msn_msnobj_ddp') or '', dialect), colorscheme = encode_xml_he(ctc_sess.front_data.get('msn_colorscheme') or '', dialect), scene = encode_xml_he(ctc_sess.front_data.get('msn_msnobj_scene') or '', dialect), sigsound = encode_xml_he(ctc_sess.front_data.get('msn_sigsound') or '', dialect), - ) - if ctc_sess.front_data.get('msn_pop_id') is not None: - pop_id_ctc = '{' + ctc_sess.front_data['msn_pop_id'] + '}' - nfy_rst += NFY_PUT_PRESENCE_USER_SEP_IM.format( - epid_attrib = (NFY_PUT_PRESENCE_USER_SEP_EPID.format(mguid = pop_id_ctc or '') if pop_id_ctc is not None else ''), - capabilities = encode_capabilities_capabilitiesex( - (ctc_sess.front_data.get('msn_capabilities') if ctc_sess.front_data.get('msn') is True else MAX_CAPABILITIES_BASIC), - ctc_sess.front_data.get('msn_capabilitiesex') or 0, + extra = ''.join( + '<{0}>{1}'.format(name, encode_xml_he(value or '', dialect)) + for name, value in (ctc_sess.front_data.get('msn_pe_extra') or {}).items() ), ) - if ctc_sess.front_data.get('msn_PE'): - pe_data = '' - pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_VER.format(ver = ctc_sess.front_data.get('msn_PE_VER') or '') - pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_TYP.format(typ = ctc_sess.front_data.get('msn_PE_TYP') or '') - pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_CAP.format( - pe_capabilities = encode_capabilities_capabilitiesex( - ctc_sess.front_data.get('msn_PE_capabilities') or 0, ctc_sess.front_data.get('msn_PE_capabilitiesex') or 0, - ) - ) - nfy_rst += NFY_PUT_PRESENCE_USER_SEP_PE.format( - epid_attrib = (NFY_PUT_PRESENCE_USER_SEP_EPID.format(mguid = pop_id_ctc or '') if pop_id_ctc is not None else ''), - pe_data = pe_data, - ) - if pop_id_ctc is not None: - nfy_rst += NFY_PUT_PRESENCE_USER_SEP_PD.format( - mguid = pop_id_ctc, ped_data = _list_private_endpoint_data(ctc_sess), - ) - + nfy_rst += _build_nfy_sep(ctc_sess, dialect) for ctc_sess_other in backend.util_get_sessions_by_user(ctc_sess.user): - if ctc_sess_other is ctc_sess: continue - if ctc_sess_other.front_data.get('msn_pop_id') is None: continue - - nfy_rst += NFY_PUT_PRESENCE_USER_SEP_IM.format( - epid_attrib = NFY_PUT_PRESENCE_USER_SEP_EPID.format(mguid = '{' + ctc_sess_other.front_data['msn_pop_id'] + '}'), - capabilities = encode_capabilities_capabilitiesex( - ( - (ctc_sess_other.front_data.get('msn_capabilities') or 0) - if ctc_sess_other.front_data.get('msn') is True else MAX_CAPABILITIES_BASIC - ), - ctc_sess_other.front_data.get('msn_capabilitiesex') or 0, - ), - ) - if ctc_sess_other.front_data.get('msn_PE'): - pe_data = '' - pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_VER.format(ver = ctc_sess_other.front_data.get('msn_PE_VER') or '') - pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_TYP.format(typ = ctc_sess_other.front_data.get('msn_PE_TYP') or '') - pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_CAP.format( - pe_capabilities = encode_capabilities_capabilitiesex( - ctc_sess_other.front_data.get('msn_PE_capabilities') or 0, - ctc_sess_other.front_data.get('msn_PE_capabilitiesex') or 0, - ), - ) - nfy_rst += NFY_PUT_PRESENCE_USER_SEP_PE.format( - epid_attrib = NFY_PUT_PRESENCE_USER_SEP_EPID.format(mguid = '{' + ctc_sess_other.front_data['msn_pop_id'] + '}'), - pe_data = pe_data, - ) - nfy_rst += NFY_PUT_PRESENCE_USER_SEP_PD.format( - mguid = '{' + ctc_sess_other.front_data['msn_pop_id'] + '}', ped_data = _list_private_endpoint_data(ctc_sess_other) - ) + if ctc_sess_other is ctc_sess or ctc_sess_other.front_data.get('msn_pop_id') is None: continue + nfy_rst += _build_nfy_sep(ctc_sess_other, dialect) msn_status = MSNStatus.FromSubstatus(substatus) @@ -136,7 +87,9 @@ def build_presence_notif( ) nfy_payload = encode_payload(NFY_PUT_PRESENCE, - to = user_me_display_email, from_email = head_display_email, cl = len(nfy_presence_body), payload = nfy_presence_body, + to = user_me_display_email, + from_email = (encode_email_networkid(head_display_email, None, circle = circle).split(':', 1)[1] if circle is not None else head_display_email), + cl = len(nfy_presence_body.encode('utf-8')), payload = nfy_presence_body, ) yield ('NFY', 'PUT', nfy_payload) @@ -159,28 +112,25 @@ def build_presence_notif( if ctc_sess is None: return if status.substatus is not old_substatus or update_status: - msn_status = MSNStatus.FromSubstatus(status.substatus) - + msn_status = MSNStatus.FromSubstatus(status.substatus if status.substatus is not None else Substatus.Offline) + if trid and dialect < 18: frst = ('ILN', trid) # type: Tuple[Any, ...] else: frst = ('NLN',) rst = [] if 8 <= dialect <= 15: - rst.append(((ctc_sess.front_data.get('msn_capabilities') or 0) if ctc_sess.front_data.get('msn') is True else MAX_CAPABILITIES_BASIC)) + rst.append(get_session_capabilities(ctc_sess, dialect)[0]) elif dialect >= 16: rst.append(( - '0:0' if circle is not None and circle_owner else encode_capabilities_capabilitiesex( - ((ctc_sess.front_data.get('msn_capabilities') or 0) if ctc_sess.front_data.get('msn') is True else MAX_CAPABILITIES_BASIC), - ctc_sess.front_data.get('msn_capabilitiesex') or 0, - ) + '0:0' if circle is not None and circle_owner else encode_capabilities_capabilitiesex(*get_session_capabilities(ctc_sess, dialect)) )) if dialect >= 9: rst.append(MSNObj(ctc_sess.front_data.get('msn_msnobj') or '')) if dialect >= 18: - yield (*frst, msn_status.name, encode_email_networkid(head_display_email, None, circle = circle), status.name, *rst) + yield (*frst, msn_status.name, encode_email_networkid(head_display_email, None, circle = circle), (status.name or head_display_email), *rst) else: - yield (*frst, msn_status.name, head_display_email, (int(NetworkID.WINDOWS_LIVE) if 14 <= dialect <= 17 else None), status.name, *rst) + yield (*frst, msn_status.name, head_display_email, (int(NetworkID.WINDOWS_LIVE) if 14 <= dialect <= 17 else None), (status.name or head_display_email), *rst) # MSNP16/18 requires `UBX`s when a user changes any sort of state (this makes MPoP and Circles work effectively) if dialect < 11 or (not update_info and dialect < 16): @@ -236,7 +186,7 @@ def cid_format(uuid: str, *, decimal: bool = False) -> str: return cid # convert to decimal string - return str(struct.unpack('q', binascii.unhexlify(cid))[0]) def uuid_to_high_low(uuid_str: str) -> Tuple[int, int]: import uuid @@ -288,20 +238,13 @@ def extend_ubx_payload(dialect: int, backend: Backend, user: User, ctc_sess: 'Ba ) if pop_id_ctc: response += EPDATA_PAYLOAD.format( - mguid = '{' + pop_id_ctc + '}', capabilities = encode_capabilities_capabilitiesex( - ((ctc_sess.front_data.get('msn_capabilities') or 0) if ctc_sess.front_data.get('msn') is True else MAX_CAPABILITIES_BASIC), - ctc_sess.front_data.get('msn_capabilitiesex') or 0, - ), + mguid = '{' + pop_id_ctc + '}', capabilities = encode_capabilities_capabilitiesex(*get_session_capabilities(ctc_sess, dialect)), ) for ctc_sess_other in backend.util_get_sessions_by_user(ctc_sess.user): pop_id = ctc_sess_other.front_data.get('msn_pop_id') or '' if pop_id.lower() == pop_id_ctc.lower(): continue response += EPDATA_PAYLOAD.format( - mguid = '{' + pop_id + '}', - capabilities = encode_capabilities_capabilitiesex( - ((ctc_sess.front_data.get('msn_capabilities') or 0) if ctc_sess.front_data.get('msn') is True else MAX_CAPABILITIES_BASIC), - ctc_sess_other.front_data.get('msn_capabilitiesex') or 0, - ) + mguid = '{' + pop_id + '}', capabilities = encode_capabilities_capabilitiesex(*get_session_capabilities(ctc_sess_other, dialect)), ) if ctc_sess.user is user: for ctc_sess_other in backend.util_get_sessions_by_user(ctc_sess.user): @@ -327,6 +270,35 @@ def _list_private_endpoint_data(ctc_sess: 'BackendSession') -> str: return ped_data +def _build_nfy_sep(sess: 'BackendSession', dialect: int) -> str: + pop_id = sess.front_data.get('msn_pop_id') + epid_attrib = NFY_PUT_PRESENCE_USER_SEP_EPID.format(mguid = '{' + (pop_id or '00000000-0000-0000-0000-000000000000') + '}') + front_data = sess.front_data + pe_epid_attrib = (epid_attrib if front_data.get('msn_PE') else NFY_PUT_PRESENCE_USER_SEP_EPID.format( + mguid = '{' + (session_p2p_epid(sess) or NULL_EPID) + '}', + )) + capabilities_known = (front_data.get('msn') is not True or 'msn_capabilities' in front_data) + + pe_data = '' + if front_data.get('msn_PE'): + pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_VER.format(ver = front_data.get('msn_PE_VER') or '') + pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_TYP.format(typ = front_data.get('msn_PE_TYP') or '') + if ('msn_PE_capabilities' in front_data if front_data.get('msn_PE') else capabilities_known): + pe_data += NFY_PUT_PRESENCE_USER_SEP_PE_CAP.format( + pe_capabilities = encode_capabilities_capabilitiesex(*get_session_capabilities(sess, dialect, pe = True)), + ) + + if capabilities_known: + result = NFY_PUT_PRESENCE_USER_SEP_IM.format( + epid_attrib = epid_attrib, capabilities = encode_capabilities_capabilitiesex(*get_session_capabilities(sess, dialect)), + ) + else: + result = NFY_PUT_PRESENCE_USER_SEP_IM_EMPTY.format(epid_attrib = epid_attrib) + result += NFY_PUT_PRESENCE_USER_SEP_PE.format(epid_attrib = pe_epid_attrib, pe_data = pe_data) + if pop_id is not None: + result += NFY_PUT_PRESENCE_USER_SEP_PD.format(mguid = '{' + pop_id + '}', ped_data = _list_private_endpoint_data(sess)) + return result + def gen_signedticket_xml(bs: BackendSession, backend: Backend) -> str: from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding @@ -364,7 +336,7 @@ def gen_chal_response(chal: str, id: str, id_key: str, *, msnp11: bool = False) ] pub_bytes = (chal + id).encode('ascii') - pub_bytes += b'0' * (8 - (len(pub_bytes) % 8)) + pub_bytes += b'0' * (-len(pub_bytes) % 8) public_seed = [ struct.unpack('{scene}{extra}{sigsound}' NFY_PUT_PRESENCE_USER_SEP_IM = '{capabilities}' +NFY_PUT_PRESENCE_USER_SEP_IM_EMPTY = '' + NFY_PUT_PRESENCE_USER_SEP_PE = '{pe_data}' NFY_PUT_PRESENCE_USER_SEP_PE_VER = '{ver}' @@ -613,8 +587,88 @@ NFY_PUT_PRESENCE_USER_SEP_PD = '{ped_data}' NFY_PUT_PRESENCE_USER_SEP_EPID = ' epid="{mguid}"' +NFY_DEL_PRESENCE_USER = '{rst}' + +NFY_DEL_PRESENCE_USER_SEP = '' + MAX_CAPABILITIES_BASIC = 1073741824 +CAPABILITIES_SIP_INVITE = 0x00100000 +CAPABILITIES_P2P_TURN = 0x02000000 +CAPABILITIES_P2P_BOOTSTRAP_VIA_UUN = 0x04000000 +CAPABILITIESEX_P2PV2 = 0x00000020 +CAPABILITIESEX_OFFLINE_IM = 0x00000100 +CAPABILITIESEX_NUDGES = 0x00000400 +CAPABILITIESEX_SIP_TUNNEL_V2 = 0x00800000 +CAPABILITIESEX_CUSTOM_EMOTICONS = 0x08000000 +CAPABILITIESEX_UTF8_PSM = 0x10000000 + +CAPABILITIES_DIRECT_IM = 0x00004000 +CAPABILITIES_DIRECT_MASK = CAPABILITIES_DIRECT_IM | CAPABILITIES_P2P_TURN | CAPABILITIES_P2P_BOOTSTRAP_VIA_UUN +CAPABILITIESEX_FTURN = 0x20000000 +CAPABILITIESEX_DIRECT_MASK = CAPABILITIESEX_FTURN + +CAPABILITIESEX_MULTIPARTY = 0x80000000 +CAPABILITIESEX_P2P_ENVELOPING = 0x00080000 + +CAPABILITIES_VERSION_SHIFT = 28 + +NULL_EPID = '00000000-0000-0000-0000-000000000000' + +DATACAST_MSNOBJ = { '2': 'Wink', '3': 'Voice' } + +DATACAST_ACTION = '4' + +PE_EXTRA_ELEMENTS = ('ASN', 'BDG', 'RUM', 'RUL', 'RLT', 'RID', 'SUL') + +UNSUPPORTED_MESSAGE_TEXT = "CrossTalk System Message: This message cannot be viewed on the client you're currently using." + +def get_session_capabilities(sess: 'BackendSession', dialect: int, *, pe: bool = False) -> Tuple[int, int]: + if sess.front_data.get('msn') is True: + capabilities = int(sess.front_data.get('msn_capabilities') or 0) + capabilitiesex = int(sess.front_data.get('msn_capabilitiesex') or 0) + else: + capabilities = MAX_CAPABILITIES_BASIC + capabilitiesex = 0 + + if sess.front_data.get('msn_PE'): + pe_capabilities = int(sess.front_data.get('msn_PE_capabilities') or 0) + if pe: + return _mask_direct(pe_capabilities, int(sess.front_data.get('msn_PE_capabilitiesex') or 0)) + if dialect < 19: + capabilities |= pe_capabilities + capabilitiesex |= CAPABILITIESEX_P2PV2 + if capabilitiesex & CAPABILITIESEX_SIP_TUNNEL_V2: + capabilities |= CAPABILITIES_SIP_INVITE + return _mask_direct(capabilities, capabilitiesex) + + version = capabilities >> CAPABILITIES_VERSION_SHIFT + if pe: + if version < 1 or sess.front_data.get('msn') is not True: + return 0, 0 + return 0, (capabilitiesex & CAPABILITIESEX_P2PV2) | CAPABILITIESEX_P2P_ENVELOPING + if dialect >= 19: + if version >= 1: capabilitiesex |= CAPABILITIESEX_CUSTOM_EMOTICONS + if version >= 4: capabilitiesex |= CAPABILITIESEX_NUDGES | CAPABILITIESEX_UTF8_PSM + if version >= 7: capabilitiesex |= CAPABILITIESEX_OFFLINE_IM + if sess.front_data.get('msn') is True: capabilitiesex |= CAPABILITIESEX_MULTIPARTY + return _mask_direct(capabilities, capabilitiesex) + +def _mask_direct(capabilities: int, capabilitiesex: int) -> Tuple[int, int]: + return capabilities & ~CAPABILITIES_DIRECT_MASK, capabilitiesex & ~CAPABILITIESEX_DIRECT_MASK + +def session_p2pv2(sess: 'BackendSession') -> bool: + front_data = sess.front_data + if front_data.get('msn_PE'): return True + if front_data.get('msn_pop_id') is None: return False + return bool(int(front_data.get('msn_capabilitiesex') or 0) & CAPABILITIESEX_P2PV2) + +def session_p2p_epid(sess: 'BackendSession') -> Optional[str]: + if not session_p2pv2(sess): return None + return sess.front_data.get('msn_pop_id') + +def is_null_epid(epid: Optional[str]) -> bool: + return epid is None or normalize_pop_id(epid).strip().lower() in ('', NULL_EPID) class MSNObj: __slots__ = ('data',) @@ -682,11 +736,13 @@ class Err: PrincipalNotOnline = 217 AlreadyInMode = 218 MutuallyExclusiveList = 219 + NotAcceptingPages = 220 GroupInvalid = 224 PrincipalNotInGroup = 225 GroupAlreadyExists = 228 GroupNameTooLong = 229 GroupZeroUnremovable = 230 + InvalidMSISDN = 232 XXLEmptyDomain = 240 XXLInvalidPayload = 241 ContactListUnavailable = 402 @@ -698,6 +754,8 @@ class Err: ChallengeResponseFailed = 540 Overload = 712 NotExpected = 715 + InvalidCVQ = 731 + RateLimitExceeded = 800 AuthFail = 911 NotAllowedWhileHDN = 913 InvalidDomain = 917 diff --git a/front/msn/msnp.py b/front/msn/msnp.py index 7a0857c..af2442d 100644 --- a/front/msn/msnp.py +++ b/front/msn/msnp.py @@ -137,7 +137,8 @@ class MSNPReader: self._data = self._data[e:] self._i = 0 _log(self.logger, '[Client]', m) - m = [unquote(x) for x in m] + if m[0] != 'QRY': + m = [unquote(x) for x in m] if body: m.append(body) if settings.DEBUG_FULL: @@ -173,7 +174,7 @@ def _encode_msnobj(msnobj: Optional[str]) -> Optional[str]: return quote(msnobj, safe = '') _PAYLOAD_COMMANDS = { - 'UUX', 'MSG', 'QRY', 'NOT', 'ADL', 'FQY', 'RML', 'UUN', 'UUM', 'PUT', 'DEL', 'SDG', 'VAS', 'SDC', + 'UUX', 'MSG', 'QRY', 'NOT', 'ADL', 'FQY', 'RML', 'UUN', 'UUM', 'PUT', 'DEL', 'SDG', 'VAS', 'SDC', 'PAG', 'PGD', } def _log(logger: Logger, pre: str, m: Sequence[Any]) -> None: diff --git a/front/msn/msnp_dp.py b/front/msn/msnp_dp.py index 5f60e12..d513d2a 100644 --- a/front/msn/msnp_dp.py +++ b/front/msn/msnp_dp.py @@ -64,6 +64,14 @@ class MSNPCtrlDP(MSNPCtrl): v = args[5] self.send_reply('CVR', trid, v, v, '1.0.0000', 'https://crosstalk.im/downloads', 'https://crosstalk.im/compat') + def _m_cvq(self, trid: str, *args: str) -> None: + if len(args) < 6: + self.send_reply(Err.InvalidCVQ, trid) + self.close() + return + v = args[5] + self.send_reply('CVQ', trid, v, v, '1.0.0000', 'https://crosstalk.im/downloads', 'https://crosstalk.im/compat') + def _m_inf(self, trid: str) -> None: if self.dialect < 9: self.send_reply('INF', trid, 'MD5') @@ -72,7 +80,7 @@ class MSNPCtrlDP(MSNPCtrl): return def __getattr__(self, name): - if name.startswith('_m_') and name not in ('_m_ver', '_m_cvr', '_m_inf'): + if name.startswith('_m_') and name not in ('_m_ver', '_m_cvr', '_m_cvq', '_m_inf'): def handler(trid: str, *args: str): if self.dialect == 2: self.send_reply('XFR', trid, 'NS', f'{settings.TARGET_IP}:1864') diff --git a/front/msn/msnp_ns.py b/front/msn/msnp_ns.py index ba13eec..85c7111 100644 --- a/front/msn/msnp_ns.py +++ b/front/msn/msnp_ns.py @@ -1,10 +1,11 @@ -from typing import Tuple, Dict, Any, Optional, List +from typing import Tuple, Dict, Any, Optional, List, Set, cast from datetime import datetime, timezone from lxml.etree import fromstring as parse_xml, XMLSyntaxError import base64, secrets, hmac, re, binascii, struct, time, asyncio, settings, random, json from email.parser import Parser -from hashlib import sha1 +from hashlib import sha1, md5 from urllib.parse import quote +from xml.sax.saxutils import escape as xml_escape, quoteattr from disposable_email_domains import blocklist as disposable_emails from util.misc import Logger, gen_uuid, date_format, MultiDict @@ -16,12 +17,19 @@ from core.models import ( Contact, TextWithData, MessageData, MessageType, LoginOption, OIM ) from core.client import Client +from core.alerts import Alert, MSNP_NOT, puid from .msnp import MSNPCtrl from .misc import ( build_presence_notif, cid_format, encode_payload, decode_capabilities_capabilitiesex, decode_email_networkid, - normalize_pop_id, decode_email_pop, gen_mail_data, gen_signedticket_xml, uuid_to_high_low, - generate_rps_key, encrypt_with_key_and_iv_tripledes_cbc, gen_chal_response, Err, MSNStatus, MSNObj, + normalize_pop_id, decode_email_pop, encode_email_pop, gen_mail_data, gen_signedticket_xml, uuid_to_high_low, + generate_rps_key, encrypt_with_key_and_iv_tripledes_cbc, gen_chal_response, Err, MSNStatus, MSNObj, DATACAST_MSNOBJ, + get_session_capabilities, CAPABILITIES_P2P_BOOTSTRAP_VIA_UUN, UNSUPPORTED_MESSAGE_TEXT, PE_EXTRA_ELEMENTS, + DATACAST_ACTION, NULL_EPID, is_null_epid, session_p2p_epid, +) +from .p2p_bridge import ( + split_sdg_p2p, get_p2p_state, build_sdg_data, neutralize_sdg_data, refuse_direct_invite, parse_slp, SLP_DIRECT_CONTENT_TYPES, + detect_p2p_version, ) MSNP_DIALECTS = ['MSNP{}'.format(d) for d in ( @@ -35,7 +43,8 @@ MSNP_DIALECTS = ['MSNP{}'.format(d) for d in ( class MSNPCtrlNS(MSNPCtrl): __slots__ = ( 'backend', 'dialect', 'usr_email', 'email_for_validation', 'bs', 'client', 'syn_ser', 'gcf_sent', 'syn_sent', 'iln_sent', 'is_third_party_client', - 'challenge', 'rps_challenge', 'circle_authenticated', 'new_circles', 'initial_adl_sent', 'circle_adl_sent', 'password', 'cs', 'email_conflict' + 'challenge', 'rps_challenge', 'circle_authenticated', 'new_circles', 'initial_adl_sent', 'circle_adl_sent', 'password', 'cs', 'email_conflict', + 'previous_challenge', 'challenge_answered', ) backend: Backend @@ -50,6 +59,8 @@ class MSNPCtrlNS(MSNPCtrl): gcf_sent: bool iln_sent: bool challenge: Optional[str] + previous_challenge: Optional[str] + challenge_answered: float rps_challenge: Optional[bytes] circle_authenticated: bool new_circles: List[Circle] @@ -74,6 +85,8 @@ class MSNPCtrlNS(MSNPCtrl): self.gcf_sent = False self.iln_sent = False self.challenge = None + self.previous_challenge = None + self.challenge_answered = 0.0 self.rps_challenge = None self.circle_authenticated = False self.new_circles = [] @@ -84,6 +97,10 @@ class MSNPCtrlNS(MSNPCtrl): def _on_close(self) -> None: if self.bs: + for cs, _ in list(self.bs.front_data.get('windowslive_chats', {}).values()): + cs.close() + for cs, _ in list(self.bs.front_data.get('windowslive_groups', {}).values()): + cs.close() self.bs.close() def on_connect(self) -> None: @@ -483,7 +500,7 @@ class MSNPCtrlNS(MSNPCtrl): now = datetime.now() if dialect < 10: - args = (user.status.name,) # type: Tuple[Any, ...] + args = ((user.status.name or email),) # type: Tuple[Any, ...] else: args = () if dialect >= 6: @@ -497,10 +514,10 @@ class MSNPCtrlNS(MSNPCtrl): email_domain = user.email.lower().split('@')[-1] if email_domain in restricted_emails or email_domain in disposable_emails: self.send_reply(Err.InvalidDomain, trid) - self.send_reply('NOT', encode_payload(PAYLOAD_MSG_10, - email = email, icon = '', url = 'https://crosstalk.im/alias-prep', - msg = "Your e-mail address contains a disallowed domain and needs to be changed before you can log in. Click this alert to learn more.", - )) + self._send_alert(Alert( + "Your e-mail address contains a disallowed domain and needs to be changed before you can log in. Click this alert to learn more.", + url = 'https://crosstalk.im/alias-prep', + ), user) self.close() return @@ -531,15 +548,15 @@ class MSNPCtrlNS(MSNPCtrl): msg1 = encode_payload(PAYLOAD_MSG_1, time = int(now.timestamp()), high = high, low = low, email = email, token = token, ip = ip, port = port, - mpop = (0 if not machineguid else 1), nickname = user.status.name, server_ip = settings.TARGET_IP, sess_id = str(id(bs)) + mpop = (0 if not machineguid else 1), nickname = (user.status.name or email), server_ip = settings.TARGET_IP, sess_id = str(id(bs)) ) real_email_domain = user.email.lower().split('@')[-1] if real_email_domain in restricted_emails or real_email_domain in disposable_emails: - self.send_reply('NOT', encode_payload(PAYLOAD_MSG_10, - email = email, icon = '', url = 'https://crosstalk.im/alias-prep', - msg = "Your e-mail address contains a blacklisted domain and needs to be changed before you can log in. Click this alert to learn more. Change your e-mail in your CrossTalk account settings.", - )) + self._send_alert(Alert( + "Your e-mail address contains a blacklisted domain and needs to be changed before you can log in. Click this alert to learn more. Change your e-mail in your CrossTalk account settings.", + url = 'https://crosstalk.im/alias-prep', + ), user) self.close() return @@ -548,14 +565,14 @@ class MSNPCtrlNS(MSNPCtrl): #if self.email_conflict: # self.send_reply('NOT', encode_payload(PAYLOAD_MSG_10, - # email = user.email, icon = 'http://static.ugnet.gay/', url = 'https://crosstalk.im/alias-prep', + # email = user.email, icon = 'http://static.ugnet.xyz/', url = 'https://crosstalk.im/alias-prep', # msg = "Your e-mail address contains the domain \"@crosstalk.im\" and needs to be changed to avoid conflicts and potential account deletion in the future. Click this alert to learn more.", # )) if settings.STRESS_TEST_ACTIVE: - self.send_reply('NOT', encode_payload(PAYLOAD_MSG_10, - email = email, icon = '', url = 'https://crosstalk.im', - msg = "We're currently doing a stress test of the CrossTalk service. Put load on the server, and tell your friends!", - )) + self._send_alert(Alert( + "We're currently doing a stress test of the CrossTalk service. Put load on the server, and tell your friends!", + url = 'https://crosstalk.im', + ), user) if 16 <= dialect < 19: # MSNP21 doesn't use this; I don't believe 19 & 20 do either @@ -603,7 +620,7 @@ class MSNPCtrlNS(MSNPCtrl): cs = [c for c in contacts.values() if c.lists & lst] if cs: for i, c in enumerate(cs): - self.send_reply('LST', trid, lst.name, ser, i + 1, len(cs), self.backend.util_get_display_email(c.head), c.status.name) + self.send_reply('LST', trid, lst.name, ser, i + 1, len(cs), self.backend.util_get_display_email(c.head), (c.status.name or self.backend.util_get_display_email(c.head))) if dialect >= 5: for bpr_setting in ('PHH','PHM','PHW','MOB'): bpr_value = c.head.settings.get(bpr_setting) @@ -660,7 +677,7 @@ class MSNPCtrlNS(MSNPCtrl): self.send_reply('SYN', trid, TIMESTAMP, TIMESTAMP, len(contacts), len(detail._groups_by_id.values())) self.send_reply('GTC', user_settings.get('GTC', 'A')) self.send_reply('BLP', user_settings.get('BLP', 'AL')) - self.send_reply('PRP', 'MFN', user.status.name) + self.send_reply('PRP', 'MFN', (user.status.name or self.backend.util_get_display_email(user))) for prp_setting in ('PHH','PHW','PHM','MOB','MBE'): prp_value = user_settings.get(prp_setting) if prp_value: @@ -740,17 +757,14 @@ class MSNPCtrlNS(MSNPCtrl): if mg is not None and mg.text is not None: bs.front_data['msn_machineguid'] = mg.text ddp = elm.find('DDP') - if ddp is not None: - bs.front_data['msn_msnobj_ddp'] = ddp.text sigsound = elm.find('SignatureSound') - if sigsound is not None: - bs.front_data['msn_sigsound'] = sigsound.text scene = elm.find('Scene') - if scene is not None: - bs.front_data['msn_msnobj_scene'] = scene.text colorscheme = elm.find('ColorScheme') - if colorscheme is not None: - bs.front_data['msn_colorscheme'] = colorscheme.text + self._update_presence_data({ + key: value_elm.text for key, value_elm in ( + ('msn_msnobj_ddp', ddp), ('msn_sigsound', sigsound), ('msn_msnobj_scene', scene), ('msn_colorscheme', colorscheme), + ) if value_elm is not None + }) bs.me_update({ 'message': ((psm.text or '') if psm is not None else None), @@ -764,15 +778,15 @@ class MSNPCtrlNS(MSNPCtrl): def _m_url(self, trid: str, site: str, ignored: Optional[str] = None) -> None: if site == 'CHAT': - self.send_reply('URL', trid, 'chatrooms.msgrsvcs.ctsrv.gay', 'chatrooms.msgrsvcs.ctsrv.gay', 1) + self.send_reply('URL', trid, 'chatrooms.msgrsvcs.ctsrv.xyz', 'chatrooms.msgrsvcs.ctsrv.xyz', 1) elif site == 'ADDRBOOK': - self.send_reply('URL', trid, '/', 'addressbook.ugnet.gay', 1) + self.send_reply('URL', trid, '/', 'addressbook.ugnet.xyz', 1) elif site == 'COMPOSE': - self.send_reply('URL', trid, '/', 'compose.mail.ugnet.gay', 1) + self.send_reply('URL', trid, '/', 'compose.mail.ugnet.xyz', 1) elif site == 'INBOX': - self.send_reply('URL', trid, '/', 'inbox.mail.ugnet.gay', 1) + self.send_reply('URL', trid, '/', 'inbox.mail.ugnet.xyz', 1) elif site == 'PROFILE': - self.send_reply('URL', trid, '/', 'members.ugnet.gay') + self.send_reply('URL', trid, '/', 'members.ugnet.xyz') else: self.send_reply('URL', trid, 'NOT_AVAILABLE', 'NOT_AVAILABLE', 1) @@ -967,6 +981,8 @@ class MSNPCtrlNS(MSNPCtrl): if circle is None and self.dialect < 20: # hack until i figure out how to make WLM 2011 not dc when you send it 933 self.send_reply(Err.InvalidCircleMembership, trid) return + # A circle WLM 2011 still lists but that's gone (or that it's no longer in) is skipped + if circle is None or (circle.memberships.get(user.uuid) is None and self.dialect >= 20): continue membership = circle.memberships.get(user.uuid) if membership is None or (membership is not None and membership.state != CircleState.Accepted) and self.dialect < 20: # hack until i figure out how to make WLM 2011 not dc when you send it 933 self.send_reply(Err.InvalidCircleMembership, trid) @@ -984,7 +1000,9 @@ class MSNPCtrlNS(MSNPCtrl): for d_el in d_els: domain = d_el.get('n') - + # Each domain's own contacts (not the last domain's, for every domain) + c_els = d_el.findall('c') + for c_el in c_els: ctc = None lsts = None @@ -1005,24 +1023,26 @@ class MSNPCtrlNS(MSNPCtrl): chat_id = username[-12:] circle = backend.user_service.get_circle(chat_id) if circle is None: continue - + if user.uuid not in circle.memberships: continue + if lsts & ContactList.FL or lsts & ContactList.AL: cs = None - + if circle.memberships[user.uuid].blocking and not lsts & ContactList.BL: on_unblock = True - + if on_unblock: try: bs.me_unblock_circle(circle) except: pass - + try: cs = backend.join_circle(chat_id, 'msn', bs, ChatEventHandler(self.backend.loop, self, bs), pop_id = bs.front_data.get('msn_pop_id')) except: if on_unblock: cs = backend.get_circle_cs(chat_id, bs) - raise Exception("Circle bad") + # Already in the circle's conversation from an earlier `ADL` (or not allowed in it): nothing to join + if cs is None or not on_unblock: continue if cs is None: continue chat = cs.chat @@ -1053,10 +1073,11 @@ class MSNPCtrlNS(MSNPCtrl): if isinstance(ex, XMLSyntaxError): self.send_reply(Err.XXLInvalidPayload, trid) self.close() - else: - self.send_reply(Err.GetCodeForException(ex, self.dialect), trid) return - + else: + self.send_reply(_err_code(ex, self.dialect), trid) + return + self.send_reply('ADL', trid, 'OK') def _m_rml(self, trid: str, data: bytes) -> None: @@ -1385,10 +1406,9 @@ class MSNPCtrlNS(MSNPCtrl): capabilities_msn_ex = None # type: Optional[str] if settings.FORCE_HOSTS_UPDATE: - self.send_reply('NOT', encode_payload(PAYLOAD_MSG_10, - email = self.backend.util_get_display_email(user), icon = '', url = 'http://diet.crosstalk.im/moving-hosts', - msg = "Your patches need to be updated before you can log in. Click this alert for more info." - )) + self._send_alert(Alert( + "Your patches need to be updated before you can log in. Click this alert for more info.", url = 'http://diet.crosstalk.im/moving-hosts', + ), user) self.backend.loop.call_later(5, self.close) return else: @@ -1416,10 +1436,9 @@ class MSNPCtrlNS(MSNPCtrl): bs.front_data['msn_capabilities'] = capabilities_msn or 0 bs.front_data['msn_capabilitiesex'] = capabilities_msn_ex or 0 if msnobj == capabilities: - bs.front_data['msn_msnobj'] = None - bs.front_data['msn_msnobj_ddp'] = None + self._update_presence_data({ 'msn_msnobj': None, 'msn_msnobj_ddp': None }) else: - bs.front_data['msn_msnobj'] = msnobj + self._update_presence_data({ 'msn_msnobj': msnobj }) bs.me_update({ 'substatus': msn_substatus, @@ -1440,7 +1459,10 @@ class MSNPCtrlNS(MSNPCtrl): dialect = self.dialect for ctc in detail.contacts.values(): if ctc.lists & ContactList.FL: - for m in build_presence_notif(trid, None, ctc.head, user, dialect, self.backend, self.iln_sent, True): + for m in build_presence_notif( + trid, None, ctc.head, user, dialect, self.backend, self.iln_sent, True, + announced_epids = bs.front_data.setdefault('msn_announced_epids', {}), + ): self.send_reply(*m) if dialect >= 6 and not self.is_third_party_client: self._send_chl(trid) @@ -1458,49 +1480,71 @@ class MSNPCtrlNS(MSNPCtrl): 'notify_status': True, }) + def _send_alert(self, alert: Alert, user: User) -> bool: + if self.dialect < MSNP_NOT: + return False + (high, low) = uuid_to_high_low(user.uuid) + self.send_reply('NOT', alert.notification( + pid = puid(high, low), name = self.backend.util_get_display_email(user), dialect = self.dialect, + email = user.email if alert.email_text else None, + )) + return True + + def _m_not(self, *args: Any) -> None: + self.close() + + def _m_chl(self, trid: str) -> None: + self.send_reply('CHL', trid, self._new_challenge()) + def _m_qry(self, trid: str, client_id: str, response: bytes) -> None: - challenge = self.challenge + id_key = _QRY_KEYPAIRS.get(client_id) + try: + answer = response.decode('ascii') + except UnicodeDecodeError: + answer = None - id_key, max_dialect = _QRY_KEYPAIRS[client_id] + ok = False + if id_key is not None and answer is not None and len(answer) == 32: + for challenge in (self.challenge, self.previous_challenge): + if challenge is None: continue + for msnp11 in (False, True): + server_response = gen_chal_response(challenge, client_id, id_key, msnp11 = msnp11) + if settings.DEBUG_FULL: + print(f"Server challenge response: {server_response}") + if hmac.compare_digest(answer, server_response): + ok = True + break + if ok: break - if self.dialect > max_dialect: + if not ok: self.send_reply(Err.ChallengeResponseFailed, trid) self.close() return - server_response = gen_chal_response(challenge, client_id, id_key, msnp11 = (self.dialect >= 11)) - if settings.DEBUG_FULL: - print(f"Server challenge response: {server_response}") - - if response.decode() != server_response: - self.send_reply(Err.ChallengeResponseFailed, trid) - self.close() - return - - self.challenge = None + self.challenge_answered = time.monotonic() self.send_reply('QRY', trid) - def _m_put(self, trid: str, data: bytes) -> None: + def _m_put(self, trid: str, data: bytes) -> None: if self.dialect < 18: self.close() return - + backend = self.backend bs = self.bs assert bs is not None user = bs.user detail = user.detail assert detail is not None - + chat_id = None presence = False - + i = data.index(b'\r\n\r\n') + 4 headers = Parser().parsestr(data[:i].decode('utf-8')) - + to = _split_email_epid(str(headers['To'])) from_email = _split_email_epid(str(headers['From'])) - + if to[1] is NetworkID.CIRCLE: if not to[0].endswith('@live.com'): self.send_reply(Err.InvalidParameter, trid) @@ -1511,31 +1555,42 @@ class MSNPCtrlNS(MSNPCtrl): self.send_reply(Err.InvalidParameter, trid) return chat_id = circle_id[-12:] - + nfy_1_index = data.index(b'\r\n\r\n', i) + 4 - + reliability = Parser().parsestr(data[i:nfy_1_index].decode('utf-8')) + # TODO: `PUT` ACK - + nfy_actual = data[nfy_1_index:] - + payload_index = nfy_actual.index(b'\r\n\r\n') + 4 nfy_headers = Parser().parsestr(nfy_actual[:payload_index].decode('utf-8')) payload = nfy_actual[payload_index:] - + + if to[1] is NetworkID.TEMPORARYGROUP: + if self.dialect < 19: + self.send_reply(Err.InvalidParameter, trid) + return + content_length = str(nfy_headers.get('Content-Length') or '').strip() + if content_length.isdigit(): + payload = payload[:int(content_length)] + self._put_group(trid, to[0], payload) + return + if nfy_headers.get('Content-Type') == 'application/circles+xml': if not self.circle_adl_sent: self.send_reply(Err.InvalidParameter, trid) return - + if chat_id is None: return - + circle = backend.user_service.get_circle(chat_id) if circle is None: self.send_reply(Err.InvalidParameter, trid) return chat = backend.chat_get('persistent', chat_id) if chat is None: return - + elm = parse_xml(payload) email_elm = elm.find('roster/user/id') if email_elm is not None: @@ -1554,42 +1609,44 @@ class MSNPCtrlNS(MSNPCtrl): else: self.send_reply(Err.InvalidParameter, trid) return - + presence_elm = elm.find('props/presence') if presence_elm is not None: cs = backend.get_circle_cs(chat_id, bs) if cs is None: self.send_reply(Err.InvalidParameter, trid) return - + psm_elm = presence_elm.find('Data/PSM') if psm_elm is not None: chat.front_data['msn_circle_psm'] = psm_elm.text cm_elm = presence_elm.find('Data/CurrentMedia') if cm_elm is not None: chat.front_data['msn_circle_cm'] = cm_elm.text - + chat.send_update() elif nfy_headers.get('Content-Type') == 'application/user+xml': presence = True try: payload_xml = parse_xml(payload) - + user_display_email = self.backend.util_get_display_email(user) if not (to[1] is NetworkID.WINDOWS_LIVE and to[0].lower() in (user.email.lower(), user_display_email.lower()) and to[2] is None): return - + name = None # type: Optional[str] psm = None # type: Optional[str] substatus = None # type: Optional[Substatus] currentmedia = None # type: Optional[str] capabilities = None # type: Optional[str] - capabilities_ex = None # type: Optional[str] + capabilitiesex = None # type: Optional[str] pe_capabilities = None # type: Optional[str] pe_capabilitiesex = None # type: Optional[str] - + pe_fields = {} # type: Dict[str, Any] + front_data_old = tuple(bs.front_data.get(key) for key in PUT_FRONT_DATA_KEYS) + #TODO: Better notification flag criteria - + s_els = payload_xml.findall('s') for s_el in s_els: if s_el.get('n') == 'IM': @@ -1597,31 +1654,41 @@ class MSNPCtrlNS(MSNPCtrl): if substatus_elm is not None: try: substatus = MSNStatus.ToSubstatus(getattr(MSNStatus, substatus_elm.text)) - except ValueError: + except (AttributeError, TypeError, ValueError): self.close() return currentmedia_elm = s_el.find('CurrentMedia') if currentmedia_elm is not None: - currentmedia = currentmedia_elm.text + currentmedia = currentmedia_elm.text or '' if s_el.get('n') == 'PE': name_elm = s_el.find('FriendlyName') if name_elm is not None: - name = name_elm.text + name = name_elm.text or user_display_email psm_elm = s_el.find('PSM') if psm_elm is not None: - psm = psm_elm.text + psm = psm_elm.text or '' utl_el = s_el.find('UserTileLocation') if utl_el is not None: - bs.front_data['msn_msnobj'] = utl_el.text + pe_fields['msn_msnobj'] = utl_el.text ddp = s_el.find('DDP') if ddp is not None: - bs.front_data['msn_msnobj_ddp'] = ddp.text + pe_fields['msn_msnobj_ddp'] = ddp.text scene = s_el.find('Scene') if scene is not None: - bs.front_data['msn_msnobj_scene'] = scene.text + pe_fields['msn_msnobj_scene'] = scene.text colorscheme = s_el.find('ColorScheme') if colorscheme is not None: - bs.front_data['msn_colorscheme'] = colorscheme.text + pe_fields['msn_colorscheme'] = colorscheme.text + sigsound = s_el.find('SignatureSound') + if sigsound is not None: + pe_fields['msn_sigsound'] = sigsound.text + pe_extra = { name: s_el.find(name) for name in PE_EXTRA_ELEMENTS } + if any(elm is not None for elm in pe_extra.values()): + pe_extra_old = bs.front_data.get('msn_pe_extra') or {} + pe_fields['msn_pe_extra'] = { + name: (elm.text if elm is not None else pe_extra_old.get(name)) for name, elm in pe_extra.items() + if elm is not None or name in pe_extra_old + } sep_elms = payload_xml.findall('sep') for sep_elm in sep_elms: if sep_elm.get('n') == 'IM': @@ -1682,30 +1749,55 @@ class MSNPCtrlNS(MSNPCtrl): bs.front_data['msn_PE_capabilities'] = pe_capabilities or 0 bs.front_data['msn_PE_capabilitiesex'] = pe_capabilitiesex or 0 + + self._update_presence_data(pe_fields) #TODO: Presence is a bit wonky - bs.me_update({ - 'name': name or user_display_email, + fields = { 'message': psm, - 'substatus': substatus, 'media': currentmedia, 'needs_notify': (False if user.status.substatus is Substatus.Offline and substatus is None else True), 'notify_self': True, - }) + } # type: Dict[str, Any] + if name is not None: + fields['name'] = name or user_display_email + if substatus is not None: + fields['substatus'] = substatus + front_data_changed = (tuple(bs.front_data.get(key) for key in PUT_FRONT_DATA_KEYS) != front_data_old) + changed = front_data_changed or ( + (psm is not None and psm != user.status.message) or (currentmedia is not None and currentmedia != user.status.media) + or ('name' in fields and fields['name'] != user.status.name) or (substatus is not None and substatus is not user.status.substatus) + ) - if not self.iln_sent: + if changed: + now = time.time() + put_times = [put_time for put_time in bs.front_data.get('msn_put_times', ()) if now - put_time < 10] + [now] + bs.front_data['msn_put_times'] = put_times + if len(put_times) > 30: + self.close() + return + if front_data_changed and not (substatus or user.status.substatus).is_offlineish(): + fields['notify_status'] = True + bs.me_update(fields) + + self.send_reply('PUT', trid, 'OK', b'') + if reliability.get('Flags') == 'ACK': + self.send_reply('NFY', 'PUT', encode_payload(PAYLOAD_MSG_14, + to_email = _encode_email_epid(user_display_email, bs.front_data.get('msn_pop_id')), from_email = user_display_email, + ) + nfy_actual) + + if not self.iln_sent and user.status.substatus is not Substatus.Offline: self.iln_sent = True for ctc in detail.contacts.values(): for m in build_presence_notif(None, None, ctc.head, user, self.dialect, self.backend, self.iln_sent, True): self.send_reply(*m) - self.send_reply('PUT', trid, 'OK', b'') return except XMLSyntaxError: self.close() return - + self.send_reply('PUT', trid, 'OK', b'') - + return def _m_sdg(self, trid: str, data: bytes) -> None: @@ -1729,9 +1821,18 @@ class MSNPCtrlNS(MSNPCtrl): headers = Parser().parsestr(data[:i].decode('utf-8')) to = _split_email_sdg(str(headers['To'])) from_email = _split_email_epid(str(headers['From'])) - except (KeyError, ValueError): + messaging_headers, body = _parse_sdg_messaging(data, i) + except (KeyError, ValueError, UnicodeDecodeError): self.send_reply(Err.InvalidParameter, trid) return + message_type = str(messaging_headers.get('Message-Type') or '') + pop_id = bs.front_data.get('msn_pop_id') + + user_display_email = self.backend.util_get_display_email(user) + if from_email[0].lower() not in (user.email.lower(), user_display_email.lower(), (self.usr_email or '').lower()): + if self.backend.util_get_uuid_from_email(from_email[0]) != user.uuid: + self.send_reply(Err.InvalidParameter, trid) + return if to[1] == NetworkID.CIRCLE and to[0].endswith('@live.com'): email_end = to[0].rfind('@live.com') @@ -1741,26 +1842,62 @@ class MSNPCtrlNS(MSNPCtrl): chat_id = circle_id[-12:] else: circle_mode = False + + if to[1] == NetworkID.TEMPORARYGROUP: + self._sdg_to_group(trid, to[0], data, i) + return if circle_mode: cs = self.backend.get_circle_cs(chat_id, bs) if cs is None: - self.send_reply(Err.InvalidParameter, trid) + self.send_reply(ERR_INVALID_CIRCLE if self.backend.user_service.get_circle(chat_id or '') is None else ERR_SENDER_NOT_MEMBER, trid) + return + message = messagedata_from_sdg(cs.user, pop_id, data, i) + if message.type is MessageType.Ignored: return + if not self.backend.util_message_allowed(user, message): + self.send_reply(ERR_SDG_THROTTLED, trid) return try: - cs.send_message_to_everyone(messagedata_from_sdg(cs.user, bs.front_data.get('msn_pop_id'), data, i)) + cs.send_message_to_everyone(message) except Exception as ex: - self.send_reply(Err.GetCodeForException(ex, self.dialect), trid) + self.send_reply(_err_code(ex, self.dialect), trid) else: if self.dialect > 18: to_str = str(to[0]).strip() contact_uuid = self.backend.util_get_uuid_from_email(to_str) if contact_uuid is None: + self.send_reply(Err.InvalidUser2, trid) return + + to_pop_id = _split_email_epid(str(headers['To']))[2] + if message_type.startswith('Signal/'): + if self._intercept_direct_signal(message_type, to_str, to_pop_id, body): return + self._send_uun(to_str, SDG_SIGNAL_UUN_TYPES.get(message_type), body, to_pop_id, sdg = data) + return + + p2pv2 = not is_null_epid(from_email[2]) + if message_type == 'Data': + packets = split_sdg_p2p(body, str(messaging_headers.get('Bridging-Offsets') or '0')) + version = (detect_p2p_version(packets[0]) if packets else None) + if version is not None: + p2pv2 = version + k = data.index(b'\r\n\r\n', data.index(b'\r\n\r\n', i) + 4) + 4 + body_new = neutralize_sdg_data(body, str(messaging_headers.get('Bridging-Offsets') or '0'), p2pv2) + if body_new != body: + data = data[:k] + body_new + data[k + len(body):] + try: cs, evt = self._get_private_chat_with(contact_uuid) if None not in (cs, evt): - evt._send_when_user_joins(contact_uuid, messagedata_from_sdg(cs.user, bs.front_data.get('msn_pop_id'), data, i)) + message = messagedata_from_sdg(cs.user, pop_id, data, i) + message.front_cache['msn_p2p_dest_pop_id'] = to_pop_id + message.front_cache['msn_p2p_dest_email'] = to_str + message.front_cache['msn_p2pv2'] = p2pv2 + if message.type is MessageType.Ignored: return + if not self.backend.util_message_allowed(user, message): + self.send_reply(ERR_SDG_THROTTLED, trid) + return + evt._send_when_user_joins(contact_uuid, message) except error.ContactNotOnline: contact_user = self.backend._load_user_record(contact_uuid) if contact_user is None: @@ -1775,7 +1912,11 @@ class MSNPCtrlNS(MSNPCtrl): elif ctc_self is None and contact_user.settings.get('BLP', 'AL') == 'BL': return md = messagedata_from_sdg(contact_user, bs.front_data.get('msn_pop_id'), data, i) - if md.type is MessageType.Chat: + if md is not None and md.type is MessageType.Chat and 'msn_datacast' not in md.front_cache: + # An offline message counts against the sender's rate like any other + if not self.backend.util_message_allowed(user, md): + self.send_reply(ERR_SDG_THROTTLED, trid) + return (ip, _) = self.peername from_user_id = to_str @@ -1784,10 +1925,161 @@ class MSNPCtrlNS(MSNPCtrl): from_user_id = from_user_id, ) except Exception as ex: - self.send_reply(Err.GetCodeForException(ex, self.dialect), trid) + self.send_reply(_err_code(ex, self.dialect), trid) return else: pass + + def _sdg_to_group(self, trid: str, group_address: str, data: bytes, i: int) -> None: + bs = self.bs + assert bs is not None + group_id = group_address.split('@', 1)[0].lower() + entry = (bs.front_data.get('windowslive_groups') or {}).get(group_id) + if entry is None or entry[0].closed: + self.send_reply(ERR_INVALID_TEMP_GROUP if self.backend.chat_get('tempgroup', group_id) is None else ERR_SENDER_NOT_MEMBER, trid) + return + cs, _ = entry + message = messagedata_from_sdg(bs.user, bs.front_data.get('msn_pop_id'), data, i) + if message.type in (MessageType.Ignored, MessageType.MSNP2P): return + if not self.backend.util_message_allowed(bs.user, message): + self.send_reply(ERR_SDG_THROTTLED, trid) + return + cs.send_message_to_everyone(message) + + def _put_group(self, trid: str, group_address: str, payload: bytes) -> None: + bs = self.bs + assert bs is not None + user = bs.user + backend = self.backend + + roster_ids = [] # type: List[str] + if payload.strip(): + try: + roster_ids = [str(elm.text or '').strip() for elm in parse_xml(payload).findall('roster/user/id')] + except XMLSyntaxError: + self.send_reply(Err.InvalidParameter, trid) + return + + user_display_email = backend.util_get_display_email(user) + if not roster_ids: + entry_existing = (bs.front_data.get('windowslive_groups') or {}).get(group_address.split('@', 1)[0].lower()) + if entry_existing is not None and not entry_existing[0].closed: + self.send_reply('PUT', trid, 'OK', b'') + return + chat = backend.chat_create() + chat.front_data['windowslive'] = True + group_id = _ensure_group_id(chat) + self._join_group(chat, group_id) + self.send_reply('PUT', trid, 'OK', encode_payload(PAYLOAD_MSG_16, + to_email = _encode_email_epid(user_display_email, bs.front_data.get('msn_pop_id')), group_id = group_id, + )) + return + + group_id = group_address.split('@', 1)[0].lower() + chat_group = backend.chat_get('tempgroup', group_id) + if chat_group is None: + self.send_reply(ERR_INVALID_TEMP_GROUP, trid) + return + chat = chat_group + entry = (bs.front_data.get('windowslive_groups') or {}).get(group_id) + if entry is not None and entry[0].closed: + entry = None + invited = chat.front_data.setdefault('msn_tempgroup_invited', set()) # type: Set[str] + joined_now = False + invitees = [] # type: List[User] + for roster_id in roster_ids: + (_, email, _) = _parse_address(roster_id) + if email.lower() in (user.email.lower(), user_display_email.lower()): + if entry is None: + if user.uuid not in invited and user not in _chat_users(chat): + self.send_reply(ERR_SENDER_NOT_MEMBER, trid) + return + try: + entry = self._join_group(chat, group_id) + except Exception as ex: + self.send_reply(_err_code(ex, self.dialect), trid) + return + joined_now = True + continue + invitee_uuid = (backend.util_get_uuid_from_email(email) if '@' in email else None) + invitee = (backend._load_user_record(invitee_uuid) if invitee_uuid is not None else None) + if invitee is None: + self.send_reply(Err.InvalidUser2, trid) + return + invitees.append(invitee) + + if invitees: + if entry is None: + self.send_reply(ERR_SENDER_NOT_MEMBER, trid) + return + cs = entry[0] + detail = user.detail + assert detail is not None + for invitee in invitees: + ctc = detail.contacts.get(invitee.uuid) + if (ctc.status if ctc is not None else invitee.status).is_offlineish(): + self.send_reply(Err.PrincipalNotOnline, trid) + return + invited.add(invitee.uuid) + try: + cs.invite(invitee) + except error.ContactAlreadyOnContactList: + # Already in the conversation + pass + except Exception as ex: + invited.discard(invitee.uuid) + self.send_reply(_err_code(ex, self.dialect), trid) + return + + self.send_reply('PUT', trid, 'OK', b'') + if joined_now and entry is not None: + entry[1].send_group_roster(entry[1].group_members(), full = True) + + def _join_group(self, chat: Chat, group_id: str) -> Tuple[ChatSession, 'ChatEventHandler']: + bs = self.bs + assert bs is not None + evt = ChatEventHandler(self.backend.loop, self, bs) + evt.group_id = group_id + cs = chat.join('msn', bs, evt, pop_id = _join_pop_id(chat, bs)) + bs.front_data.setdefault('windowslive_groups', {})[group_id] = (cs, evt) + cast(Set[str], chat.front_data.setdefault('msn_tempgroup_invited', set())).discard(bs.user.uuid) + chat.send_participant_joined(cs) + return cs, evt + + def _leave_group(self, trid: str, group_address: str, uri: str) -> None: + bs = self.bs + assert bs is not None + user = bs.user + group_id = group_address.split('@', 1)[0].lower() + entry = (bs.front_data.get('windowslive_groups') or {}).get(group_id) + if entry is None or entry[0].closed: + self.send_reply(ERR_INVALID_TEMP_GROUP if self.backend.chat_get('tempgroup', group_id) is None else ERR_SENDER_NOT_MEMBER, trid) + return + if '/user(' in uri: + (_, email, _) = _parse_address(uri[uri.index('/user(') + 6:].rstrip(')')) + if email.lower() not in (user.email.lower(), self.backend.util_get_display_email(user).lower()): + self.send_reply(ERR_SENDER_NOT_MEMBER, trid) + return + entry[0].close() + self.send_reply('DEL', trid, 'OK', b'') + + def _intercept_direct_signal(self, message_type: str, to_email: str, to_pop_id: Optional[str], body: bytes) -> bool: + bs = self.bs + assert bs is not None + if message_type == 'Signal/Turn': return True + if message_type != 'Signal/P2P': return False + slp = parse_slp(body) + if slp is None or slp.content_type not in SLP_DIRECT_CONTENT_TYPES: return False + reply = refuse_direct_invite(body) + if reply is not None: + (slp_to, _) = _slp_signal_parties(body) + (_, slp_to_pop_id) = decode_email_pop(slp_to or '') + from_pop_id = (to_pop_id or (normalize_pop_id(slp_to_pop_id) if slp_to_pop_id else None)) + self.send_reply('SDG', 0, encode_payload(PAYLOAD_MSG_12, + to_email = _encode_email_epid(self.backend.util_get_display_email(bs.user), bs.front_data.get('msn_pop_id')), + from_email = _encode_email_epid(to_email, from_pop_id), service_channel = 'PE', message_type = 'Signal/P2P', cl = len(reply), + ) + reply) + return True def _m_rea(self, trid: str, email: str, name: str) -> None: # Set a display name (MSNP10 and earlier) @@ -1830,17 +2122,149 @@ class MSNPCtrlNS(MSNPCtrl): bs.send_invitation_email(email, sender_email, name, message) self.send_reply('SDC', trid, 'OK') - def _m_vas(self, trid: str, email: str, arg3: str, arg4: str, data: bytes) -> None: - # "Vote as spam". Don't know how to respond. - if self.dialect < 18: + def _m_cvq(self, trid: str, *args: str) -> None: + # `CVR` as CVR0-only clients send it (to the dispatch server, but some send it here too) + if len(args) < 6: + self.send_reply(Err.InvalidCVQ, trid) self.close() return + v = args[5] + self.send_reply('CVQ', trid, v, v, '1.0.0000', 'https://crosstalk.im/downloads', 'https://crosstalk.im/compat') + + def _m_fnd(self, trid: str, *args: str) -> None: self.send_reply(Err.CommandDisabled, trid) - return + + def _m_gsb(self, trid: str) -> None: + if self.dialect < 11: + self.close() + return + self.send_reply('SBS', trid, 'null') + + def _m_lkp(self, trid: str, address: str) -> None: + if self.dialect < 12: + self.close() + return + number = (address[4:] if address.lower().startswith('tel:') else '') + if not (number.startswith('+') and number[1:].isdigit() and len(number) > 8): + self.send_reply(Err.InvalidMSISDN, trid) + return + self.send_reply('LKP', trid, address) + + def _m_pag(self, trid: str, email: str, data: bytes) -> None: + if self.dialect < 5: + self.close() + return + if self.dialect >= 9: + self.send_reply(Err.NotExpected, trid) + return + self._page(trid, email, data) + + def _m_pgd(self, trid: str, email: str, device_type: str, data: bytes) -> None: + if self.dialect < 9: + self.close() + return + if not device_type.isdigit(): + self.close() + return + if device_type not in ('1', '2'): + self.send_reply(Err.InvalidParameter, trid) + return + self._page(trid, email, data) + + def _page(self, trid: str, email: str, data: bytes) -> None: + # Nobody here has a phone to text, so a page goes to the paged user's messenger sessions as a mobile message from the + # sender (`IPG`), and is kept as an offline message if they have none that can show it. Only users who have paging on + # (`MOB`) can be paged. MSNP11 and later hear how it went in an `IPG` of their own; before that only a failure is answered + bs = self.bs + assert bs is not None + user = bs.user + backend = self.backend + + try: + text_elm = parse_xml(b'' + data + b'').find('TEXT') + except XMLSyntaxError: + self.send_reply(Err.InvalidParameter, trid) + return + text = ((text_elm.text or '') if text_elm is not None else '') + + uuid = (backend.util_get_uuid_from_email(email) if '@' in email else None) + target = (backend._load_user_record(uuid) if uuid is not None else None) + result = 1 + if target is None or target.settings.get('MOB') != 'Y' or not text: + # Not accepting pages + result = MOBILE_ERR_USER_DISABLED + else: + target_detail = backend._load_detail(target) + ctc_self = (target_detail.contacts.get(user.uuid) if target_detail is not None else None) + if ctc_self is not None and ctc_self.lists & ContactList.BL: + result = MOBILE_ERR_USER_DISABLED + elif not backend.util_message_allowed(user, MessageData(sender = user, type = MessageType.Chat, text = text)): + result = MOBILE_ERR_SMS_NOT_ALLOWED + if result == 1: + assert target is not None + delivered = False + for bs_other in backend.util_get_sessions_by_user(target): + if bs_other.evt.msn_on_page(user, text): + delivered = True + if not delivered: + (ip, _) = self.peername + backend.user_service.save_oim(bs, target.uuid, gen_uuid(), ip, text, True, from_user_id = backend.util_get_display_email(user)) + + if self.dialect >= 11: + self.send_reply('IPG', _ipg_payload( + backend, int(trid) if trid.isdigit() else 0, user, (target if target is not None else None), email, result, '', + )) + elif result != 1: + self.send_reply(Err.NotAcceptingPages if result == MOBILE_ERR_USER_DISABLED else Err.RateLimitExceeded, trid) + + def _m_vas(self, trid: str, email: str, arg3: str, arg4: str, data: bytes) -> None: + # "Vote as spam". + if self.dialect < 16: + self.close() + return + bs = self.bs + assert bs is not None + try: + networkid = NetworkID(int(arg3)) + except ValueError: + self.send_reply(Err.InvalidNetworkID, trid) + return + if networkid in (NetworkID.WINDOWS_LIVE, NetworkID.YAHOO) and '@' in email: + uuid = self.backend.util_get_uuid_from_email(email) + target = (self.backend._load_user_record(uuid) if uuid is not None else None) + if target is not None and target is not bs.user: + self.backend.abuse.warn(bs.user, target, anonymous = True) + self.send_reply('VAS', trid) def _m_del(self, trid: str, data: bytes) -> None: # OUT sends presence updates on logout, ignore for now until we have multiparties implemented - pass + bs = self.bs + assert bs is not None + user = bs.user + + pop_id_self = bs.front_data.get('msn_pop_id') + try: + i = data.index(b'\r\n\r\n') + 4 + to = _parse_address(str(Parser().parsestr(data[:i].decode('utf-8')).get('To') or '')) + i = data.index(b'\r\n\r\n', i) + 4 + content = Parser().parsestr(data[i:data.index(b'\r\n\r\n', i) + 4].decode('utf-8')) + i = data.index(b'\r\n\r\n', i) + 4 + sep_elms = (parse_xml(data[i:]).findall('sep') if data[i:].strip() and to[0] is not NetworkID.TEMPORARYGROUP else []) + except (ValueError, XMLSyntaxError): + self.send_reply(Err.InvalidParameter, trid) + return + + if to[0] is NetworkID.TEMPORARYGROUP: + self._leave_group(trid, to[1], str(content.get('Uri') or '')) + return + + for sep_elm in sep_elms: + epid = sep_elm.get('epid') + if sep_elm.get('n') != 'IM' or epid is None or normalize_pop_id(epid).lower() == (pop_id_self or '').lower(): continue + for bs_other in self.backend.util_get_sessions_by_user(user): + bs_other.evt.msn_on_uun_sent(user, 4, b'goawyplzthxbye', pop_id_sender = pop_id_self, pop_id = epid) + + self.send_reply('DEL', trid, 'OK', b'') def _m_prp(self, trid: str, key: str, value: Optional[str] = None, *rest: Optional[str]) -> None: # Set a display name @@ -1882,7 +2306,7 @@ class MSNPCtrlNS(MSNPCtrl): bs.me_update({ phone_type: value }) elif key == 'MOB': - if user.settings['MBE'] == 'N': + if user.settings.get('MBE') == 'N': value = 'N' else: if value not in ('Y','N'): @@ -1996,53 +2420,71 @@ class MSNPCtrlNS(MSNPCtrl): self.close() return - bs = self.bs - assert bs is not None - user = bs.user - - pop_id_self = None - (email, pop_id) = decode_email_pop(email) - uuid = self.backend.util_get_uuid_from_email(email) - if uuid is None: - return - - ctc_head = self.backend._load_user_record(uuid) - if ctc_head is None: - return - - if ctc_head.status.is_offlineish(): - self.send_reply(Err.PrincipalNotOnline, trid) - return - - ctc_detail = self.backend._load_detail(ctc_head) - assert ctc_detail is not None - - ctc_me = ctc_detail.contacts.get(user.uuid) - if ctc_me is not None: - if ctc_me.lists & ContactList.BL: - self.send_reply(Err.PrincipalNotOnline, trid) - return - else: - if ctc_head.settings.get('BLP', 'AL') == 'BL': - self.send_reply(Err.PrincipalNotOnline, trid) - return - try: uun_type = int(type) except ValueError: + self.send_reply(Err.InvalidParameter, trid) + return + if not 1 <= uun_type <= 12 or (4 <= uun_type <= 8 and self.dialect < 16): + self.send_reply(Err.InvalidParameter, trid) return - if uun_type is None: return + if uun_type == 10 or (uun_type == 3 and data is not None and self._intercept_direct_uun(email, pop_id, data)): + self.send_reply('UUN', trid, 'OK') + return - pop_id_self = bs.front_data.get('msn_pop_id') - - for sess_notify in self.backend.util_get_sessions_by_user(ctc_head): - sess_notify.evt.msn_on_uun_sent(bs.user, uun_type, data, pop_id_sender = pop_id_self, pop_id = pop_id) + if not self._send_uun(email, uun_type, data, pop_id): + self.send_reply(Err.PrincipalNotOnline, trid) + return self.send_reply('UUN', trid, 'OK') + def _intercept_direct_uun(self, email: str, pop_id: Optional[str], data: bytes) -> bool: + slp = parse_slp(data) + if slp is None or slp.content_type not in SLP_DIRECT_CONTENT_TYPES: return False + reply = refuse_direct_invite(data) + if reply is not None: + uuid = self.backend.util_get_uuid_from_email(email) + head = (self.backend._load_user_record(uuid) if uuid is not None else None) + sender = (self.backend.util_get_display_email(head) if head is not None else email) + (slp_to, _) = _slp_signal_parties(data) + (_, slp_to_pop_id) = decode_email_pop(slp_to or '') + to_pop_id = pop_id or slp_to_pop_id + self.send_reply('UBN', (encode_email_pop(sender, normalize_pop_id(to_pop_id)) if self.dialect >= 16 and to_pop_id else sender), 3, reply) + return True + + def _send_uun(self, email: str, uun_type: Optional[int], data: Optional[bytes], pop_id: Optional[str], *, sdg: Optional[bytes] = None) -> bool: + bs = self.bs + assert bs is not None + user = bs.user + + uuid = self.backend.util_get_uuid_from_email(email) + if uuid is None: + return False + + ctc_head = self.backend._load_user_record(uuid) + if ctc_head is None: + return False + + if ctc_head.uuid != user.uuid: + if uun_type in (4, 5, 6, 7, 8): + return False + if ctc_head.status.is_offlineish(): + return False + ctc_me = self.backend._load_detail(ctc_head).contacts.get(user.uuid) + if ctc_me is not None: + if ctc_me.lists & ContactList.BL: + return False + elif ctc_head.settings.get('BLP', 'AL') == 'BL': + return False + + for sess_notify in self.backend.util_get_sessions_by_user(ctc_head): + if sess_notify.front_data.get('msn') is not True: continue + sess_notify.evt.msn_on_uun_sent(user, uun_type, data, pop_id_sender = bs.front_data.get('msn_pop_id'), pop_id = pop_id, sdg = sdg) + return True + def _m_uum(self, trid: str, email: str, networkid: str, type: str, data: bytes) -> None: # For federated messaging (with Yahoo!); also used in MSNP18+ for OIMs @@ -2126,18 +2568,23 @@ class MSNPCtrlNS(MSNPCtrl): except: return + def _new_challenge(self) -> str: + self.previous_challenge = self.challenge + self.challenge = str(secrets.randbelow(89999999999999999999) + 10000000000000000000) + return self.challenge + def _send_chl(self, trid: str) -> None: backend = self.backend - self.challenge = str(secrets.randbelow(89999999999999999999) + 10000000000000000000) - backend.loop.create_task(self._check_qry_sent(trid)) - self.send_reply('CHL', 0, self.challenge) + challenge = self._new_challenge() + backend.loop.create_task(self._check_qry_sent(time.monotonic())) + self.send_reply('CHL', 0, challenge) - async def _check_qry_sent(self, trid: str) -> None: + async def _check_qry_sent(self, sent: float) -> None: await asyncio.sleep(50) if not self.is_third_party_client: - if self.challenge: - self.send_reply(Err.ChallengeResponseFailed, trid) + if self.challenge_answered < sent and not self.closed: + self.send_reply('OUT') self.close() return @@ -2160,12 +2607,17 @@ class MSNPCtrlNS(MSNPCtrl): 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['windowslive_chats']: + existing = bs.front_data['windowslive_chats'].get(other_user_uuid) + if existing is not None and (existing[0].closed or existing[1].group_id is not None): + del bs.front_data['windowslive_chats'][other_user_uuid] + existing = None + if existing is None: 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() + if other_user.status.is_offlineish(): raise error.ContactNotOnline() chat = self.backend.chat_create() chat.front_data['windowslive'] = True @@ -2173,10 +2625,17 @@ class MSNPCtrlNS(MSNPCtrl): evt = ChatEventHandler(self.backend.loop, self, bs) cs = chat.join('msn', bs, evt) bs.front_data['windowslive_chats'][other_user_uuid] = (cs, evt) - cs.invite(other_user) + # `other_user` is invited with the first message (`ChatEventHandler._send_when_user_joins`) elif other_user.status.is_offlineish(): raise error.ContactNotOnline() return bs.front_data['windowslive_chats'].get(other_user_uuid) + + def _update_presence_data(self, fields: Dict[str, Any]) -> None: + bs = self.bs + assert bs is not None + for bs_other in self.backend.util_get_sessions_by_user(bs.user): + if bs_other.front_data.get('msn') is not True: continue + bs_other.front_data.update(fields) class BackendEventHandler(event.BackendEventHandler): __slots__ = ('ctrl', 'loop') @@ -2188,15 +2647,31 @@ class BackendEventHandler(event.BackendEventHandler): self.ctrl = ctrl self.loop = loop - def on_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None: + def on_client_alert(self, alert: Alert) -> bool: bs = self.ctrl.bs assert bs is not None user = bs.user + + return self.ctrl._send_alert(alert, user) - self.ctrl.send_reply('NOT', encode_payload(PAYLOAD_MSG_10, - email = self.ctrl.backend.util_get_display_email(user), icon = icon_url, url = url, - msg = message, - )) + def on_warning_level_changed(self, level: int, warner: Optional[User]) -> None: + bs = self.ctrl.bs + if bs is None: return + level_old = bs.front_data.get('msn_warning_level', 0) + bs.front_data['msn_warning_level'] = level + if level <= level_old: return + who = ('Someone' if warner is None else (warner.status.name or self.ctrl.backend.util_get_display_email(warner))) + self.ctrl._send_alert(Alert( + text = '{} warned you. Your warning level is now {}%; the higher it is, the slower you can send messages.'.format(who, (level + 9) // 10), + ), bs.user) + + def msn_on_page(self, sender: User, text: str) -> bool: + # A page arrives as a message from the sender's mobile device (`IPG`, MSNP6 on) + ctrl = self.ctrl + bs = ctrl.bs + if bs is None or ctrl.closed or ctrl.dialect < 6: return False + ctrl.send_reply('IPG', _ipg_payload(ctrl.backend, 0, bs.user, sender, '', 0, text)) + return True def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None: if args[0] == 1 and args[1] < 0: return @@ -2233,7 +2708,7 @@ class BackendEventHandler(event.BackendEventHandler): if update_status or update_info_other: for m in build_presence_notif( trid, old_substatus, ctc.head, user, self.ctrl.dialect, self.ctrl.backend, self.ctrl.iln_sent, update_info_other, - update_status = update_status, + update_status = update_status, announced_epids = bs.front_data.setdefault('msn_announced_epids', {}), ): self.ctrl.send_reply(*m) return @@ -2246,6 +2721,7 @@ class BackendEventHandler(event.BackendEventHandler): if update_status or update_info: for m in build_presence_notif( None, old_substatus, user, user, self.ctrl.dialect, self.ctrl.backend, self.ctrl.iln_sent, update_info, self_presence = True, + announced_epids = bs.front_data.setdefault('msn_announced_epids', {}), ): self.ctrl.send_reply(*m) return @@ -2255,15 +2731,29 @@ class BackendEventHandler(event.BackendEventHandler): ) -> None: if circle and self.ctrl.circle_authenticated: self.msn_on_notify_ab() + elif circle: + return else: if self.ctrl.dialect >= 19: if chat is None: - chat = self.backend.chat_create() + chat = self.ctrl.backend.chat_create() chat.add_id('windowslive', chat.ids['main']) + others = [user_other for user_other in _chat_users(chat) if user_other is not self.bs.user] + if 'tempgroup' in chat.ids or len(others) >= 2: + group_id = _ensure_group_id(chat) + chat.front_data.setdefault('msn_tempgroup_invited', set()).add(self.bs.user.uuid) + send_group_roster(self.ctrl, self.bs, group_id, [ + (self.ctrl.backend.util_get_display_email(user_other), False) for user_other in others + ] + [(self.ctrl.backend.util_get_display_email(self.bs.user), True)], full = True) + return evt = ChatEventHandler(self.loop, self.ctrl, self.bs) - cs = chat.join('msn', self.bs, evt) + cs = chat.join('msn', self.bs, evt, pop_id = _join_pop_id(chat, self.bs)) chat.send_participant_joined(cs) - self.bs.front_data['windowslive_chats'][inviter.uuid] = (cs, evt) + peer = inviter + if inviter is self.bs.user: + peer = _private_chat_peer(cs, self.bs.user) + if peer is not None: + self.bs.front_data['windowslive_chats'][peer.uuid] = (cs, evt) return else: extra = () # type: Tuple[Any, ...] @@ -2348,10 +2838,26 @@ class BackendEventHandler(event.BackendEventHandler): def msn_on_oim_deletion(self, oims_deleted: int) -> None: if self.ctrl.iln_sent and self.ctrl.dialect >= 11: self.ctrl.send_reply('MSG', 'Hotmail', 'Hotmail', encode_payload(PAYLOAD_MSG_3, oims_deleted = str(oims_deleted))) - + + def msn_on_own_chat(self, chat: Chat, other_user_uuid: str) -> None: + ctrl = self.ctrl + bs = ctrl.bs + if bs is None or ctrl.closed or ctrl.dialect < 19: + return + windowslive_chats = bs.front_data.get('windowslive_chats') + if windowslive_chats is None: + return + existing = windowslive_chats.get(other_user_uuid) + if existing is not None and not existing[0].closed: + return + evt = ChatEventHandler(self.loop, ctrl, bs) + cs = chat.join('msn', bs, evt, pop_id = _join_pop_id(chat, bs)) + chat.send_participant_joined(cs) + windowslive_chats[other_user_uuid] = (cs, evt) + def msn_on_uun_sent( - self, sender: User, type: int, data: Optional[bytes], *, - pop_id_sender: Optional[str] = None, pop_id: Optional[str] = None, + self, sender: User, type: Optional[int], data: Optional[bytes], *, + pop_id_sender: Optional[str] = None, pop_id: Optional[str] = None, sdg: Optional[bytes] = None, ) -> None: ctrl = self.ctrl bs = ctrl.bs @@ -2360,16 +2866,60 @@ class BackendEventHandler(event.BackendEventHandler): if ctrl.dialect < 13: return - if pop_id is not None and 'msn_pop_id' in bs.front_data: - pop_id_self = bs.front_data.get('msn_pop_id') or '' + pop_id_self = bs.front_data.get('msn_pop_id') + if pop_id is not None and pop_id_self is not None: if normalize_pop_id(pop_id).lower() != pop_id_self.lower(): return + if sender.uuid == bs.user.uuid and pop_id_sender is not None and pop_id_sender == pop_id_self: return - if pop_id_sender is not None and pop_id is not None and ctrl.dialect >= 16: - email = '{};{}'.format(self.ctrl.backend.util_get_display_email(sender), '{' + pop_id_sender + '}') - else: - email = self.ctrl.backend.util_get_display_email(sender) + sender_email = ctrl.backend.util_get_display_email(sender) - self.ctrl.send_reply('UBN', email, type, data) + if ctrl.dialect >= 19: + if sdg is not None: + ctrl.send_reply('SDG', 0, sdg) + return + user_email = ctrl.backend.util_get_display_email(bs.user) + if type in (4, 8): + payload = ''.format(pop_id_self or '') + ctrl.send_reply('NFY', 'DEL', encode_payload(PAYLOAD_MSG_13, email = user_email, cl = len(payload), payload = payload)) + elif type == 6: + self.msn_on_notify_ab() + elif type in SDG_SIGNALS: + (message_type, service_channel) = SDG_SIGNALS[type] + body = data or b'' + if type == 5: + chat = ctrl.backend.chat_get('main', body.decode('utf-8', 'replace').split(';', 1)[0].strip()) + if chat is None: return + body = '/'.join( + '1:' + ctrl.backend.util_get_display_email(cs_other.user) + for cs_other in chat.get_roster_single() if cs_other.user.uuid != bs.user.uuid + ).encode('utf-8') + ctrl.send_reply('SDG', 0, encode_payload(PAYLOAD_MSG_12, + to_email = _encode_email_epid(user_email, pop_id_self), from_email = _encode_email_epid(sender_email, pop_id_sender), + service_channel = service_channel, message_type = message_type, cl = len(body), + ) + body) + return + + if type is None: + return + if sdg is not None: + if type == 3 and not get_session_capabilities(bs, ctrl.dialect)[0] & CAPABILITIES_P2P_BOOTSTRAP_VIA_UUN: + return + if type == 5: + parties = { party.split(':', 1)[-1].lower() for party in (data or b'').decode('utf-8', 'replace').split('/') if party } + for chat in ctrl.backend.get_chats_by_scope('main'): + roster = chat.get_roster() + if not any(cs_other.bs is bs for cs_other in roster): continue + if { ctrl.backend.util_get_display_email(cs_other.user).lower() for cs_other in roster if cs_other.user.uuid != bs.user.uuid } == parties: + data = '{};{}:1865'.format(chat.ids['main'], settings.TARGET_IP).encode('utf-8') + break + else: + return + + ctrl.send_reply('UBN', (encode_email_pop(sender_email, pop_id_sender) if ctrl.dialect >= 16 else sender_email), type, data) + + def msn_on_whats_new(self, publisher: User) -> None: + if self.ctrl.dialect < 13: return + self.msn_on_notify_ab() def msn_on_notify_ab(self) -> None: bs = self.ctrl.bs @@ -2468,17 +3018,21 @@ class BackendEventHandler(event.BackendEventHandler): self.ctrl.close() class ChatEventHandler(event.ChatEventHandler): - __slots__ = ('loop', 'ctrl', 'bs', 'cs') + __slots__ = ('loop', 'ctrl', 'bs', 'cs', 'pending', 'group_id') loop: asyncio.AbstractEventLoop ctrl: MSNPCtrlNS bs: Optional[BackendSession] cs: ChatSession + pending: Dict[str, List[MessageData]] + group_id: Optional[str] def __init__(self, loop: asyncio.AbstractEventLoop, ctrl: MSNPCtrlNS, bs: BackendSession) -> None: self.loop = loop self.ctrl = ctrl self.bs = bs + self.pending = {} + self.group_id = None def on_close(self) -> None: bs = self.ctrl.bs @@ -2487,9 +3041,14 @@ class ChatEventHandler(event.ChatEventHandler): chat = self.cs.chat circle = chat.circle + for key, front_key in ((self.group_id, 'windowslive_groups'), (_private_chat_peer_uuid(self.cs, user), 'windowslive_chats')): + conversations = bs.front_data.get(front_key) + if key is not None and conversations is not None and conversations.get(key, (None,))[0] is self.cs: + del conversations[key] + if circle is None: return - membership = circle.memberships[user.uuid] - if membership.state == CircleState.Empty: + membership = circle.memberships.get(user.uuid) + if membership is not None and membership.state == CircleState.Empty: for cs_other in chat.get_roster(): self.ctrl.send_reply('NFY', 'DEL', encode_payload(PAYLOAD_MSG_9, to_email = self.ctrl.backend.util_get_display_email(user), nid = str(int(NetworkID.CIRCLE)), uuid = '00000000-0000-0000-0009-{}'.format(circle.chat_id), @@ -2505,6 +3064,10 @@ class ChatEventHandler(event.ChatEventHandler): chat = cs.chat circle = chat.circle if circle: + if cs_other is cs and initial_join and self.ctrl.dialect >= 19: + self.ctrl.send_reply('NFY', 'PUT', encode_payload(PAYLOAD_MSG_7, + email = _encode_email_epid(self.ctrl.backend.util_get_display_email(user), bs.front_data.get('msn_pop_id')), chat_id = circle.chat_id, + )) if (cs_other.user.status.substatus is Substatus.Invisible and cs_other.user is user) or not cs_other.user.status.is_offlineish(): if cs_other.user.uuid == circle.owner_uuid: for m in build_presence_notif( @@ -2522,6 +3085,38 @@ class ChatEventHandler(event.ChatEventHandler): if not first_pop: return self.on_chat_roster_updated() + else: + if cs_other is not cs and cs_other.user is not user: + cast(Set[str], chat.front_data.get('msn_tempgroup_invited', set())).discard(cs_other.user.uuid) + if self.group_id is None and len(_chat_users(chat)) > 2: + self.become_group() + elif self.group_id is not None and first_pop: + self.send_group_roster([(self.ctrl.backend.util_get_display_email(cs_other.user), False)], full = False) + for data in self.pending.pop(cs_other.user.uuid, ()): + cs.send_message_to_user(cs_other.user.uuid, data) + + def become_group(self) -> None: + bs = self.ctrl.bs + assert bs is not None + self.group_id = _ensure_group_id(self.cs.chat) + chats = bs.front_data.get('windowslive_chats') or {} + for uuid, (cs_other, _) in list(chats.items()): + if cs_other is self.cs: + del chats[uuid] + bs.front_data.setdefault('windowslive_groups', {})[self.group_id] = (self.cs, self) + self.send_group_roster(self.group_members(pending_self = True), full = True) + + def group_members(self, *, pending_self: bool = False) -> List[Tuple[str, bool]]: + bs = self.ctrl.bs + assert bs is not None + return [ + (self.ctrl.backend.util_get_display_email(other), pending_self and other is bs.user) for other in _chat_users(self.cs.chat) + ] + + def send_group_roster(self, users: List[Tuple[str, bool]], *, full: bool) -> None: + bs = self.ctrl.bs + assert bs is not None and self.group_id is not None + send_group_roster(self.ctrl, bs, self.group_id, users, full = full) def on_participant_left(self, cs_other: ChatSession, last_pop: bool) -> None: bs = self.ctrl.bs @@ -2534,12 +3129,18 @@ class ChatEventHandler(event.ChatEventHandler): if last_pop: if circle: - membership = circle.memberships[cs_other.user.uuid] - if membership.state == CircleState.Empty: + membership = circle.memberships.get(cs_other.user.uuid) + if membership is None or membership.state == CircleState.Empty: self.ctrl.send_reply('NFY', 'DEL', encode_payload(PAYLOAD_MSG_9, to_email = self.ctrl.backend.util_get_display_email(user), nid = str(int(NetworkID.CIRCLE)), uuid = '00000000-0000-0000-0009-{}'.format(circle.chat_id), from_email = self.ctrl.backend.util_get_display_email(cs_other.user), )) + elif self.group_id is not None and cs_other.user is not user: + self.ctrl.send_reply('NFY', 'DEL', encode_payload(PAYLOAD_MSG_9, + to_email = _encode_email_epid(self.ctrl.backend.util_get_display_email(user), bs.front_data.get('msn_pop_id')), + nid = str(int(NetworkID.TEMPORARYGROUP)), uuid = self.group_id, + from_email = self.ctrl.backend.util_get_display_email(cs_other.user), + )) def on_chat_invite_declined( self, chat: Chat, invitee: User, *, invitee_id: Optional[str] = None, @@ -2602,8 +3203,8 @@ class ChatEventHandler(event.ChatEventHandler): chat = cs.chat circle = chat.circle - membership = circle.memberships[cs_other.user.uuid] - if membership.state == CircleState.Empty: return + membership = circle.memberships.get(cs_other.user.uuid) + if membership is None or membership.state == CircleState.Empty: return if not (initial and cs_other.user.status.is_offlineish()): for m in build_presence_notif( @@ -2627,29 +3228,43 @@ class ChatEventHandler(event.ChatEventHandler): chat = cs.chat circle = chat.circle if data.type is not MessageType.TypingDone: + dest_pop_id = data.front_cache.get('msn_p2p_dest_pop_id') + if dest_pop_id is not None and (bs.front_data.get('msn_pop_id') or '').lower() != dest_pop_id.lower(): return if data.sender is bs.user and data.sender_pop_id == bs.front_data.get('msn_pop_id'): - self.ctrl.send_reply('SDG', 0, messagedata_to_sdg(self, data, user)) + sdg = messagedata_to_sdg(self, data, user) else: - self.ctrl.send_reply('SDG', 0, messagedata_to_sdg(self, data, user, circle = circle)) - + sdg = messagedata_to_sdg(self, data, user, circle = circle, group_id = self.group_id) + if sdg is not None: + self.ctrl.send_reply('SDG', 0, sdg) + def _send_when_user_joins(self, user_uuid: str, data: MessageData) -> None: + if self._user_in_chat(user_uuid): + for data_pending in self.pending.pop(user_uuid, ()): + self.cs.send_message_to_user(user_uuid, data_pending) + self.cs.send_message_to_everyone(data) + return + # Send to everyone currently in chat self.cs.send_message_to_everyone(data) - if self._user_in_chat(user_uuid): + pending = self.pending.get(user_uuid) + if pending is None: + pending = self.pending[user_uuid] = [data] + user_other = self.ctrl.backend._load_user_record(user_uuid) + try: + if user_other is not None: + self.cs.invite(user_other) + except Exception: + if self.pending.get(user_uuid) is pending: + del self.pending[user_uuid] + raise + self.loop.call_later(PENDING_TIMEOUT, self._expire_pending, user_uuid, pending) return - - # If `user_uuid` hasn't joined yet, send it later - self.loop.create_task(self._send_delayed(user_uuid, data)) - - async def _send_delayed(self, user_uuid: str, data: MessageData) -> None: - delay = 0.1 - for _ in range(3): - await asyncio.sleep(delay) - delay *= 3 - if self._user_in_chat(user_uuid): - self.cs.send_message_to_user(user_uuid, data) - return + pending.append(data) + + def _expire_pending(self, user_uuid: str, pending: List[MessageData]) -> None: + if self.pending.get(user_uuid) is pending: + del self.pending[user_uuid] def _user_in_chat(self, user_uuid: str) -> bool: for cs_other in self.cs.chat.get_roster(): @@ -2667,6 +3282,20 @@ def _get_circle_roster(self, chat: Chat, cs: ChatSession) -> str: return users +def _ipg_payload( + backend: Backend, notification_id: int, to_user: User, from_user: Optional[User], from_email: str, msg_id: int, text: str, +) -> bytes: + (to_high, to_low) = uuid_to_high_low(to_user.uuid) + (from_high, from_low) = (uuid_to_high_low(from_user.uuid) if from_user is not None else (0, 0)) + to_email = backend.util_get_display_email(to_user) + if from_user is not None: + from_email = backend.util_get_display_email(from_user) + return IPG_PAYLOAD.format( + id = notification_id, siteurl = quoteattr(settings.ALERT_SITE_URL), to_pid = quoteattr(puid(to_high, to_low)), + to_email = quoteattr(to_email), from_pid = quoteattr(puid(from_high, from_low)), from_email = quoteattr(from_email), + msg_id = msg_id, text = xml_escape(text), + ).replace('\n', '\r\n').encode('utf-8') + def _split_email_epid(email: str) -> Tuple[str, NetworkID, Optional[str]]: email_epid = email.split(';', 1) networkid, email = decode_email_networkid(email_epid[0]) @@ -2686,113 +3315,232 @@ def _split_email_sdg(email: str) -> Tuple[str, NetworkID, Optional[str]]: def _encode_email_epid(email: str, pop_id: Optional[str]) -> str: return f'{email};epid={{{pop_id}}}' if pop_id else email -def messagedata_from_sdg(sender: User, sender_pop_id: Optional[str], data: bytes, i: int) -> Optional[MessageData]: +def _err_code(ex: Exception, dialect: int) -> int: try: - j = data.index(b'\r\n\r\n', i) + 4 - sdg_messaging = data[j:] - n = sdg_messaging.index(b'\r\n\r\n') + 4 - headers = Parser().parsestr(sdg_messaging[:n].decode('utf-8')) - body_raw = sdg_messaging[n:] + return Err.GetCodeForException(ex, dialect) + except ValueError: + return Err.InternalServerError - content_length = headers.get('Content-Length') - if content_length is None: - return None +def _join_pop_id(chat: Chat, bs: BackendSession) -> Optional[str]: + pop_id = bs.front_data.get('msn_pop_id') + if pop_id is None: return None + for user_other, pop_id_other in chat._users_by_sess.values(): + if user_other is bs.user and pop_id_other is None: return None + return pop_id - message_length = int(str(content_length)) - if len(body_raw) < message_length: - return None +def _private_chat_peer(cs: ChatSession, user: User) -> Optional[User]: + for cs_other in cs.chat.get_roster(): + if cs_other.user is not user: return cs_other.user + return None - body_raw = body_raw[:message_length] - message_type_str = str(headers.get('Message-Type')) - message_subtype = str(headers.get('Message-Subtype', '')) +def _private_chat_peer_uuid(cs: ChatSession, user: User) -> Optional[str]: + peer = _private_chat_peer(cs, user) + return (peer.uuid if peer is not None else None) - type_mapping = { - 'Text': MessageType.Chat, - 'Nudge': MessageType.Nudge, - 'Control': MessageType.Typing if message_subtype == 'Typing' else MessageType.Chat, - 'Control/Typing': MessageType.Typing, - 'Data': MessageType.MSNP2P, - 'Signal/P2P': MessageType.MSNP2PInvite - } +def send_group_roster(ctrl: 'MSNPCtrlNS', bs: BackendSession, group_id: str, users: List[Tuple[str, bool]], *, full: bool) -> None: + payload = _group_roster_payload(users) + ctrl.send_reply('NFY', 'PUT', encode_payload(PAYLOAD_MSG_15, + to_email = _encode_email_epid(ctrl.backend.util_get_display_email(bs.user), bs.front_data.get('msn_pop_id')), group_id = group_id, + notif_type = ('Full' if full else 'Partial'), cl = len(payload.encode('utf-8')), payload = payload, + )) - type = type_mapping.get(message_type_str, MessageType.Chat) - text = body_raw.decode('utf-8') if type == MessageType.Chat or MessageType.MSNP2P else '' +def _chat_users(chat: Chat) -> List[User]: + users = [] # type: List[User] + for cs_other in chat.get_roster(): + if cs_other.user not in users: users.append(cs_other.user) + return users + +def _ensure_group_id(chat: Chat) -> str: + group_id = chat.ids.get('tempgroup') + if group_id is None: + group_id = gen_uuid().lower() + chat.add_id('tempgroup', group_id) + return group_id + +def _parse_address(address: str) -> Tuple[Optional[NetworkID], str, Dict[str, str]]: + parts = address.strip().split(';') + params = {} # type: Dict[str, str] + for part in parts[1:]: + if '=' not in part: continue + name, value = part.split('=', 1) + params[name.strip().lower()] = value.strip() + try: + networkid, account = decode_email_networkid(parts[0]) + except (ValueError, IndexError): + return None, parts[0], params + return networkid, account, params + +def _parse_multimime(data: bytes) -> Tuple[Any, Any, Any, bytes]: + i = data.index(b'\r\n\r\n') + 4 + j = data.index(b'\r\n\r\n', i) + 4 + try: + k = data.index(b'\r\n\r\n', j) + 4 + except ValueError: + k = len(data) + routing = Parser().parsestr(data[:i].decode('utf-8')) + reliability = Parser().parsestr(data[i:j].decode('utf-8')) + content = Parser().parsestr(data[j:k].decode('utf-8')) + body = data[k:] + content_length = str(content.get('Content-Length') or '').strip() + if content_length.isdigit(): + body = body[:int(content_length)] + return routing, reliability, content, body + +def _group_roster_payload(users: List[Tuple[str, bool]]) -> str: + return CIRCLE.format(CIRCLE_ROSTER.format(users = ''.join( + TEMPGROUP_USER.format(email = email, state = (TEMPGROUP_USER_PENDING if pending else '')) for email, pending in users + ))) + +def _slp_signal_parties(slp_data: bytes) -> Tuple[Optional[str], Optional[str]]: + slp = parse_slp(slp_data) + if slp is None: return None, None + def strip(value: Optional[str]) -> Optional[str]: + if value is None: return None + value = value.strip().strip('<>') + return value.split(':', 1)[1] if value.lower().startswith('msnmsgr:') else value + return strip(slp.get('To')), strip(slp.get('From')) + +def _parse_sdg_messaging(data: bytes, i: int) -> Tuple[Any, bytes]: + j = data.index(b'\r\n\r\n', i) + 4 + k = data.index(b'\r\n\r\n', j) + 4 + headers = Parser().parsestr(data[j:k].decode('utf-8')) + body = data[k:] + content_length = headers.get('Content-Length') + if content_length is not None: + body = body[:int(str(content_length))] + return headers, body + +def messagedata_from_sdg(sender: User, sender_pop_id: Optional[str], data: bytes, i: int) -> MessageData: + front_cache = { 'msnp_sdg': data } # type: Dict[str, Any] + try: + headers, body_raw = _parse_sdg_messaging(data, i) + message_type = str(headers.get('Message-Type')) + + if message_type == 'Text': + type = MessageType.Chat + text = body_raw.decode('utf-8') # type: Any + if headers.get('X-MMS-IM-Format') is not None: + front_cache['msn_im_format'] = str(headers.get('X-MMS-IM-Format')) + elif message_type == 'Nudge': + type = MessageType.Nudge + text = '' + elif message_type == 'Control/Typing' or (message_type == 'Control' and headers.get('Message-Subtype') == 'Typing'): + type = MessageType.Typing + text = '' + elif message_type == 'Control/ClearTyping': + type = MessageType.TypingDone + text = '' + elif message_type == 'Data': + type = MessageType.MSNP2P + text = body_raw + front_cache['msn_p2p'] = split_sdg_p2p(body_raw, str(headers.get('Bridging-Offsets') or '0')) + if str(headers.get('Pipe') or '').isdigit(): + front_cache['msn_sdg_pipe'] = int(str(headers.get('Pipe'))) + elif message_type == 'CustomEmoticon': + type = MessageType.Emoticon + text = body_raw + front_cache['msn_emoticon'] = headers.get_content_type() + elif message_type in DATACAST_MSNOBJ.values(): + type = MessageType.Other + text = body_raw.decode('utf-8') + front_cache['msn_datacast'] = next(id for id, datacast_type in DATACAST_MSNOBJ.items() if datacast_type == message_type) + elif message_type.startswith('Signal/'): + type = MessageType.Ignored + text = '' + else: + raise ValueError(message_type) except Exception: type = MessageType.Chat - text = "CrossTalk System Message: This message cannot be viewed on the client you're currently using." - - message = MessageData(sender=sender, sender_pop_id=sender_pop_id, type=type, text=text) - message.front_cache['msnp_sdg'] = data + text = UNSUPPORTED_MESSAGE_TEXT + + message = MessageData(sender = sender, sender_pop_id = sender_pop_id, type = type, text = text) + message.front_cache.update(front_cache) return message -def messagedata_to_sdg(self, data: MessageData, user: User, *, circle: Optional[Circle] = None) -> bytes: - if 'msnp_sdg' not in data.front_cache: - text = data.text or (b'' if data.type == MessageType.MSNP2P else '') - if data.type == MessageType.Typing: - if circle: - s = ( - f'Content-Length: 2\r\nContent-Type: text/x-msmsgscontrol\r\n' - f'Content-Transfer-Encoding: 7bit\r\nMessage-Type: Control\r\n' - f'Message-Subtype: Typing\r\nMIME-Version: 1.0\r\nTypingUser: {self.ctrl.backend.util_get_display_email(data.sender)}\r\n\r\n\r\n' - ).encode('utf-8') - else: - s = 'Message-Type: Control/Typing\r\nContent-Length: 0\r\n\r\n'.encode('utf-8') - elif data.type == MessageType.Nudge: - s = ( - 'Content-Length: 9\r\nContent-Type: text/plain; charset=UTF-8\r\n' - 'Content-Transfer-Encoding: 7bit\r\nMessage-Type: Nudge\r\n' - 'MIME-Version: 1.0\r\n\r\nID: 1\r\n\r\n' - ).encode('utf-8') - elif data.type == MessageType.Chat: - s = ( - f'Content-Length: {len(text)}\r\nContent-Type: text/plain; charset=UTF-8\r\n' - f'Content-Transfer-Encoding: 7bit\r\nMessage-Type: Text\r\n' - f'MIME-Version: 1.0\r\n\r\n' - ).encode('utf-8') + text.encode('utf-8') - elif data.type == MessageType.MSNP2P: - s = ( - b'Bridging-Offsets: 0\r\n' - + f'Content-Length: {len(text)}\r\n'.encode() - + b'Content-Transfer-Encoding: binary\r\n' - + b'Content-Type: application/x-msnmsgrp2p\r\n' - + b'Message-Type: Data\r\n\r\n' - + text - ) - elif data.type == MessageType.MSNP2PInvite: - s = ( - f'Content-Length: {len(text)}\r\n'.encode() - + b'Content-Type: text/plain; charset=UTF-8\r\n' - + b'Message-Type: Signal/P2P\r\n\r\n' - ).encode('utf-8') + text.encode('utf-8') - else: - raise ValueError("Unknown message type", data.type) - - sender_display_email = self.ctrl.backend.util_get_display_email(data.sender) +def messagedata_to_sdg(self, data: MessageData, user: User, *, circle: Optional[Circle] = None, group_id: Optional[str] = None) -> Optional[bytes]: + if data.type == MessageType.MSNP2P and 'msnp_sdg' not in data.front_cache: + pop_id = self.bs.front_data.get('msn_pop_id') + state = get_p2p_state(self.cs.chat.front_data, user.uuid, data.sender.uuid) user_display_email = self.ctrl.backend.util_get_display_email(user) - - to = f'9:00000000-0000-0000-0009-{circle.chat_id}@live.com;path=IM' if circle else f'1:{_encode_email_epid(user_display_email, self.bs.front_data.get('msn_pop_id'))}' - pre = f'Routing: 1.0\r\nTo: {to}\r\n' - - if data.type == MessageType.MSNP2P: - pre += 'Options: 0\r\nService-Channel: PE\r\n' + (dest_email, dest_pop_id) = decode_email_pop(data.front_cache.get('msn_p2p_dest') or '') + if dest_email and dest_email.lower() not in (user.email.lower(), user_display_email.lower()): return None + p2pv2 = bool(data.front_cache.get('msn_p2pv2', dest_pop_id is not None)) + dest_pop_id = (normalize_pop_id(dest_pop_id) if dest_pop_id is not None else state.get('pop_id')) + if dest_pop_id is not None and pop_id is not None and dest_pop_id.lower() != pop_id.lower(): return None + return build_sdg_data( + _encode_email_epid(user_display_email, pop_id), + _encode_email_epid(self.ctrl.backend.util_get_display_email(data.sender), (data.sender_pop_id if p2pv2 else None)), [data.text], state['pipe'], + ) + if 'msnp_sdg' in data.front_cache: + return data.front_cache['msnp_sdg'] + + sender_display_email = self.ctrl.backend.util_get_display_email(data.sender) + user_display_email = self.ctrl.backend.util_get_display_email(user) + + if data.type == MessageType.Typing: + if circle or group_id: + s = ( + f'Content-Length: 2\r\nContent-Type: text/x-msmsgscontrol\r\n' + f'Content-Transfer-Encoding: 7bit\r\nMessage-Type: Control\r\n' + f'Message-Subtype: Typing\r\nMIME-Version: 1.0\r\nTypingUser: {sender_display_email}\r\n\r\n\r\n' + ).encode('utf-8') else: - pre += 'Service-Channel: IM/Online\r\n' + s = 'Message-Type: Control/Typing\r\nContent-Length: 0\r\n\r\n'.encode('utf-8') + elif data.type == MessageType.Nudge: + s = ( + 'Content-Length: 9\r\nContent-Type: text/plain; charset=UTF-8\r\n' + 'Content-Transfer-Encoding: 7bit\r\nMessage-Type: Nudge\r\n' + 'MIME-Version: 1.0\r\n\r\nID: 1\r\n\r\n' + ).encode('utf-8') + elif data.type == MessageType.Chat or data.type in (MessageType.Ink, MessageType.MSNP2PInvite): + if data.type is MessageType.Chat: + text = data.text or '' + elif data.type is MessageType.Ink or b'Invitation-Command: INVITE' in (data.front_cache.get('msnp') or b''): + text = UNSUPPORTED_MESSAGE_TEXT + else: + return None + body = text.encode('utf-8') + im_format = data.front_cache.get('msn_im_format') + s = ( + f'Content-Length: {len(body)}\r\nContent-Type: text/plain; charset=UTF-8\r\n' + f'Content-Transfer-Encoding: 7bit\r\nMessage-Type: Text\r\n' + + (f'X-MMS-IM-Format: {im_format}\r\n' if im_format else '') + + f'MIME-Version: 1.0\r\n\r\n' + ).encode('utf-8') + body + elif data.type == MessageType.Emoticon: + emoticons = (data.text if isinstance(data.text, bytes) else (data.text or '').encode('utf-8')) + s = ( + f'Content-Length: {len(emoticons)}\r\nContent-Type: {data.front_cache.get("msn_emoticon") or "text/x-mms-emoticon"}\r\n' + f'Message-Type: CustomEmoticon\r\n\r\n' + ).encode('utf-8') + emoticons + elif data.type == MessageType.Other and data.front_cache.get('msn_datacast') in DATACAST_MSNOBJ: + body = (data.text or '').encode('utf-8') + s = ( + f'Message-Type: {DATACAST_MSNOBJ[data.front_cache["msn_datacast"]]}\r\nContent-Length: {len(body)}\r\n' + f'Content-Type: text/plain; charset=UTF-8\r\n\r\n' + ).encode('utf-8') + body + else: + return None - timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z' - pre += f'Original-Arrival-Time: {timestamp}\r\n' - pre += f'From: 1:{_encode_email_epid(sender_display_email, data.sender_pop_id)}\r\n\r\n' - pre = pre.encode('utf-8') + if circle: + to = f'9:00000000-0000-0000-0009-{circle.chat_id}@live.com;path=IM' + elif group_id: + to = f'10:{group_id}@live.com;path=IM' + else: + to = f'1:{_encode_email_epid(user_display_email, self.bs.front_data.get("msn_pop_id"))}' + pre = f'Routing: 1.0\r\nTo: {to}\r\n' + pre += 'Service-Channel: IM/Online\r\n' + timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z' + pre += f'Original-Arrival-Time: {timestamp}\r\n' + pre += f'From: 1:{_encode_email_epid(sender_display_email, data.sender_pop_id)}\r\n\r\n' + pre_bytes = pre.encode('utf-8') - r = 'Reliability: 1.0' - if circle: - r += '\r\nStream: 0\r\nSegment: 0' - r += '\r\n\r\n' - r += 'Messaging: 2.0\r\n' - r = r.encode('utf-8') - - data.front_cache['msnp_sdg'] = pre + r + s - - return data.front_cache['msnp_sdg'] + r = 'Reliability: 1.0' + if circle or group_id: + r += '\r\nStream: 0\r\nSegment: 0' + r += '\r\n\r\n' + r += 'Messaging: 2.0\r\n' + return pre_bytes + r.encode('utf-8') + s PAYLOAD_MSG_0 = '''Routing: 1.0 To: 1:{email_address};epid={endpoint_ID} @@ -2966,27 +3714,139 @@ Inbox-Unread: {unread} Folders-Unread: 0 Inbox-URL: /cgi-bin/MaiL Folders-URL: /cgi-bin/Folders -Post-URL: http://mail.ugnet.gay +Post-URL: http://mail.ugnet.xyz ''' +PUT_FRONT_DATA_KEYS = ( + 'msn_msnobj', 'msn_msnobj_ddp', 'msn_msnobj_scene', 'msn_colorscheme', 'msn_sigsound', 'msn_capabilities', 'msn_capabilitiesex', + 'msn_PE', 'msn_PE_VER', 'msn_PE_TYP', 'msn_PE_capabilities', 'msn_PE_capabilitiesex', 'msn_client_type', 'msn_epname', + 'msn_endpoint_idle', 'msn_ep_state', 'msn_pe_extra', +) + +PENDING_TIMEOUT = 60 + +SDG_SIGNALS = { + 3: ('Signal/P2P', 'PE'), + 5: ('Signal/CloseIMWindow', 'IM/Online'), + 6: ('Signal/ForceAbchSync', 'PD'), + 10: ('Signal/Turn', 'PE'), + 12: ('Signal/AudioTunnel', 'IM/Online'), +} +SDG_SIGNAL_UUN_TYPES = { message_type: uun_type for uun_type, (message_type, _) in SDG_SIGNALS.items() } + +PAYLOAD_MSG_12 = '''Routing: 1.0 +To: 1:{to_email} +From: 1:{from_email} +Options: 0 +Service-Channel: {service_channel} + +Reliability: 1.0 + +Messaging: 2.0 +Message-Type: {message_type} +Content-Type: text/plain; charset=UTF-8 +Content-Length: {cl} + +''' + +PAYLOAD_MSG_13 = '''Routing: 1.0 +To: 1:{email} +From: 1:{email} + +Reliability: 1.0 + +Notification: 1.0 +NotifNum: 0 +Uri: /user +NotifType: Partial +Content-Type: application/user+xml +Content-Length: {cl} + +{payload}''' + +PAYLOAD_MSG_14 = '''Routing: 1.0 +To: 1:{to_email} +From: 1:{from_email} + +Reliability: 1.0 +Stream: 1 + +''' + +PAYLOAD_MSG_15 = '''Routing: 1.0 +To: 1:{to_email} +From: 10:{group_id}@live.com + +Reliability: 1.0 +Stream: 0 + +Notification: 1.0 +NotifNum: 0 +Uri: /circle +NotifType: {notif_type} +Content-Type: application/circles+xml +Content-Length: {cl} + +{payload}''' + +PAYLOAD_MSG_16 = '''Routing: 1.0 +To: 1:{to_email} +From: 10:{group_id}@live.com + +Reliability: 1.0 + +Publication: 1.0 +Uri: /circle +Content-Type: application/multiparty+xml +Content-Length: 0 + +''' + +TEMPGROUP_USER = '1:{email}{state}' +TEMPGROUP_USER_PENDING = 'Pending' + +IPG_PAYLOAD = ''' + + + + + + + + + + {text} + + +''' + +MOBILE_ERR_USER_DISABLED = 551 +MOBILE_ERR_SMS_NOT_ALLOWED = 595 + +ERR_SENDER_NOT_MEMBER = 250 +ERR_INVALID_CIRCLE = 252 +ERR_INVALID_TEMP_GROUP = 254 +ERR_SDG_THROTTLED = 801 + SHIELDS = ''' '''.encode('utf-8') -SHIELDS_MSNP13 = ''' +GCF_POLICY_ABCH = '\ + \ + \ + 100' +SHIELDS_MSNP13 = (''' \ - \ - \ - \ - 100 + ' + GCF_POLICY_ABCH + ''' \ \ \ -'''.encode('utf-8') +''').encode('utf-8') CIRCLE_ROSTER = 'IM{users}' CIRCLE_USER = '1:{email}' @@ -2997,44 +3857,53 @@ TIMESTAMP = '2000-01-01T00:00:00.0-00:00' _QRY_KEYPAIRS = { # MSNP6 - 9 - 'msmsgs@msnmsgr.com': ('Q1P7W2E4J9R8U3S5', 10), - 'msntv@msnmsgr.com': ('', 10), # found in MSN TV 2.7 build 16109 - 'macmsgr@msnmsgr.com': ('A8J3D5F7L3K2V6F4', 10), - 'assist@msnmsgr.com': ('L2P3B7C6V9J4T8D5', 10), - 'appshare@msnmsgr.com': ('W5N2C9D7A6P3K4J8', 10), - 'pocketpc@msnmsgr.com': ('', 10), - 'TEST00578M1WM}RR': ('', 10), - 'PROD0038W!61ZTF9': ('VT6PX?UQTM4WM%YR', 10), - 'PROD0058#7IL2{QD': ('QHDCY@7R1TB6W?5B', 10), - 'PROD0061VRRZH@4F': ('JXQ6J@TUOGYV@N0M', 10), - 'PROD0062I2RVG#RV': ('LPOFJ{8L6AM2N!G', 10), - 'PROD0066X_86JBY8': ('%_IP#M2WDG247}@I', 10), - 'PROD00678K?EPLA}': ('MP8JK{DUDLDMC{9L', 10), - 'PROD0074Z}QA4HPI': ('5JHDY@F5_KLEF?3O', 10), - 'PROD0075THRTM{7!': ('WLJIQ$8LDLNI_J4Q', 10), - 'PROD0076ENE8*@AW': ('CEQJ8}OE0!WTSWII', 10), - 'PROD0039E3VGM%GB': ('B7WRX$T9S3875{68', 10), # found in MSN Messenger 4.7.0106 - 'PROD00504RLUG%WL': ('I2EBK%PYNLZL5_J4', 10), - 'PROD00517IFH4@RV': ('MYRED!3QTCFWG@9G', 10), # found in Windows Messenger 5.1.0701 - 'PROD00444_M6XYJT': ('UMJBL@QN17VEI{5L', 10), # found in Messenger for Mac 3.0 - 'PROD0045YI56T?TX': ('FV!WOP5UKXO8$LV$', 10), - 'PROD0046K9O#QFXY': ('8{B7#LEX_V5HV@SQ', 10), + 'msmsgs@msnmsgr.com': 'Q1P7W2E4J9R8U3S5', + 'msntv@msnmsgr.com': 'P3U6T9R8B4N3C2F5', # found in MSN TV 2.7 build 16109 + 'macmsgr@msnmsgr.com': 'A8J3D5F7L3K2V6F4', + 'assist@msnmsgr.com': 'L2P3B7C6V9J4T8D5', + 'appshare@msnmsgr.com': 'W5N2C9D7A6P3K4J8', + 'pocketpc@msnmsgr.com': 'J2G1A7P4V9H3R6Q5', + 'PROD0038W!61ZTF9': 'VT6PX?UQTM4WM%YR', + 'PROD0058#7IL2{QD': 'QHDCY@7R1TB6W?5B', + 'PROD0061VRRZH@4F': 'JXQ6J@TUOGYV@N0M', + 'PROD0062I2RVG#RV': 'LPOFJ{8L6AM2N!G_', + 'PROD0066X_86JBY8': '%_IP#M2WDG247}@I', + 'PROD00678K?EPLA}': 'MP8JK{DUDLDMC{9L', + 'PROD0074Z}QA4HPI': '5JHDY@F5_KLEF?3O', + 'PROD0075THRTM{7!': 'WLJIQ$8LDLNI_J4Q', + 'PROD0076ENE8*@AW': 'CEQJ8}OE0!WTSWII', + 'PROD0039E3VGM%GB': 'B7WRX$T9S3875{68', # found in MSN Messenger 4.7.0106 + 'PROD00504RLUG%WL': 'I2EBK%PYNLZL5_J4', + 'PROD00517IFH4@RV': 'MYRED!3QTCFWG@9G', # found in Windows Messenger 5.1.0701 + 'PROD00444_M6XYJT': 'UMJBL@QN17VEI{5L', # found in Messenger for Mac 3.0 + 'PROD0045YI56T?TX': 'FV!WOP5UKXO8$LV$', + 'PROD0046K9O#QFXY': '8{B7#LEX_V5HV@SQ', # MSNP11 - 12 - 'PROD008955JTJ_S7': ('DHCPQ$8JI5HD3{4L', 12), - 'PROD0090YUAUV{2B': ('YMM8C_H7KCQ2S_KL', 12), - 'PROD00974#MT*RC2': ('LMCVO*18PQJ3H!K3', 12), - 'PROD0101{0RM?UBW': ('CFHUR$52U_{VIX5T', 12), - 'PROD0102LUNTP%M?': ('JD5QT%#ILEBP5?LI', 12), - "PROD0104U6VVM{UJ": ('VK67B}379XYM5}$T', 12), + 'PROD008955JTJ_S7': 'DHCPQ$8JI5HD3{4L', + 'PROD0090YUAUV{2B': 'YMM8C_H7KCQ2S_KL', + 'PROD00974#MT*RC2': 'LMCVO*18PQJ3H!K3', + 'PROD0101{0RM?UBW': 'CFHUR$52U_{VIX5T', + 'PROD0102LUNTP%M?': 'JD5QT%#ILEBP5?LI', + "PROD0104U6VVM{UJ": 'VK67B}379XYM5}$T', # MSNP13 - 14 - 'PROD01065C%ZFN6F': ('O4BG@C7BWLYQX?5G', 14), - 'PROD0112J1LW7%NB': ('RH96F{PHI8PPX_TJ', 14), + 'PROD01065C%ZFN6F': 'O4BG@C7BWLYQX?5G', + 'PROD0112J1LW7%NB': 'RH96F{PHI8PPX_TJ', # MSNP15+ - 'PROD0113H11T8$X_': ('RG@XY*28Q5QHS%Q5', 21), - 'PROD0114ES4Z%Q5W': ('PK}_A_0N_K%O?A9S', 21), - 'PROD0116PE?TSI1': ('EXFK#_48PJR82_3G', 21), - 'PROD0118R6%2WYOS': ('YIXPX@5I2P0UT*LK', 21), - 'PROD0119GSJUC$18': ('ILTXC!4IXB5FB*PX', 21), + 'PROD0113H11T8$X_': 'RG@XY*28Q5QHS%Q5', + 'PROD0114ES4Z%Q5W': 'PK}_A_0N_K%O?A9S', + 'PROD0116PE?TSI1_': 'EXFK#_48PJR82_3G', + 'PROD0118R6%2WYOS': 'YIXPX@5I2P0UT*LK', + 'PROD0119GSJUC$18': 'ILTXC!4IXB5FB*PX', # Thanks J.M. for making the tweet with this WLM 2009 ID-key combo. ^_^ - 'PROD0120PW!CCV9@': ('C1BX{V4W}Q3*10SM', 21), + 'PROD0120PW!CCV9@': 'C1BX{V4W}Q3*10SM', + 'smartphone@msnmsgr.com': 'L3S9P4D5V7N1C6Z8', + 'PROD0063ZIEAF}0V': 'WDHAC}O7WBHFV{3_', + 'PROD00651XKFM@S@': '9B4E7$JG88YHX@LE', + 'PROD00647HVX2{MN': 'DEVUD@2LO6HUE$EV', + 'PROD0122P%C9%RV1': 'BN3WI}H4LUFPJ{2S', + 'PROD0123E1_08UHK': 'PRXSC!2$!KJ7_MVW', + 'PROD0121MRI8R?C_': 'R48!JWGWT$G4J74_', + 'PROD0042@3Q14{82': 'LYIS1?Z4!WPG}L2R', + 'PROD00437_19OG@3': '8V1G#ROXF1MYJ#4V', + 'PROD0056U!SS0YG5': 'MOEXO_Y@G_94S$NF', } diff --git a/front/msn/msnp_sb.py b/front/msn/msnp_sb.py index e968f36..f750765 100644 --- a/front/msn/msnp_sb.py +++ b/front/msn/msnp_sb.py @@ -1,16 +1,21 @@ -from typing import Tuple, Any, Optional, List, Set +from typing import Tuple, Any, Optional, List, Set, Dict, cast import time, asyncio from email.parser import Parser -from util.misc import Logger, VoidTaskType +from util.misc import Logger, VoidTaskType, gen_uuid from core.models import User, MessageData, MessageType, Substatus from core.backend import Backend, BackendSession, ChatSession, Chat from core import event, error -from .misc import Err, encode_capabilities_capabilitiesex, decode_email_pop, encode_email_pop, normalize_pop_id, MAX_CAPABILITIES_BASIC from .msnp import MSNPCtrl - +from .misc import ( + Err, encode_capabilities_capabilitiesex, decode_email_pop, encode_email_pop, normalize_pop_id, get_session_capabilities, + CAPABILITIESEX_P2PV2, DATACAST_MSNOBJ, DATACAST_ACTION, UNSUPPORTED_MESSAGE_TEXT, is_null_epid, +) +from .p2p_bridge import ( + get_p2p_state, chunk_p2p, translate_p2pv2_ack, build_sb_p2p_headers, sb_p2p_is_v2, neutralize_direct_p2p, sb_p2p_messages, +) class MSNPCtrlSB(MSNPCtrl): - __slots__ = ('backend', 'dialect', 'loop', 'counter_task', 'auth_sent', 'bs', 'cs') + __slots__ = ('backend', 'dialect', 'loop', 'counter_task', 'auth_sent', 'bs', 'cs', 'chunks') backend: Backend dialect: int @@ -19,6 +24,7 @@ class MSNPCtrlSB(MSNPCtrl): auth_sent: bool bs: Optional[BackendSession] cs: Optional[ChatSession] + chunks: Dict[str, Dict[str, Any]] def __init__(self, logger: Logger, via: str, backend: Backend) -> None: super().__init__(logger) @@ -29,6 +35,7 @@ class MSNPCtrlSB(MSNPCtrl): self.auth_sent = False self.bs = None self.cs = None + self.chunks = {} def on_connect(self) -> None: self.counter_task = self.loop.create_task(self._conn_auth_limit_counter()) @@ -171,17 +178,14 @@ class MSNPCtrlSB(MSNPCtrl): for other_cs in tmp: other_user = other_cs.user other_user_display_email = self.backend.util_get_display_email(other_user) - capabilities = encode_capabilities_capabilitiesex( - ((other_cs.bs.front_data.get('msn_capabilities') or 0) if other_cs.bs.front_data.get('msn') is True else MAX_CAPABILITIES_BASIC), - other_cs.bs.front_data.get('msn_capabilitiesex') or 0, - ) + capabilities = encode_capabilities_capabilitiesex(*get_session_capabilities(other_cs.bs, dialect)) self.send_reply( 'IRO', trid, i, l, encode_email_pop(other_user_display_email, other_cs.bs.front_data.get('msn_pop_id')), - other_user.status.name, capabilities, + _friendly_name(self.backend, other_user), capabilities, ) if other_cs.primary_pop and other_cs.bs.front_data.get('msn_pop_id') is not None: i += 1 - self.send_reply('IRO', trid, i, l, other_user_display_email, other_user.status.name, capabilities) + self.send_reply('IRO', trid, i, l, other_user_display_email, _friendly_name(self.backend, other_user), capabilities) i += 1 else: roster_one_per_user = [] # type: List[ChatSession] @@ -197,15 +201,9 @@ class MSNPCtrlSB(MSNPCtrl): if dialect >= 12: # Capability flags in IRO were technically introduced by MSNP13, but there are MSNP12 logs that show that they # had been introduced in that protocol version by then - extra = ( - ( - (other_cs.bs.front_data.get('msn_capabilities') or 0) - if other_cs.bs.front_data.get('msn') is True - else MAX_CAPABILITIES_BASIC - ), - ) - self.send_reply('IRO', trid, i + 1, l, self.backend.util_get_display_email(other_user), other_user.status.name, *extra) - + extra = (get_session_capabilities(other_cs.bs, dialect)[0],) + self.send_reply('IRO', trid, i + 1, l, self.backend.util_get_display_email(other_user), _friendly_name(self.backend, other_user), *extra) + self.send_reply('ANS', trid, 'OK') chat.send_participant_joined(cs) @@ -276,21 +274,72 @@ class MSNPCtrlSB(MSNPCtrl): self.close() return + chunks = self._collect_chunk(data) + if chunks is None: + if ack in ('A', 'D'): + self.send_reply('ACK', trid) + return + try: - cs.send_message_to_everyone(messagedata_from_msnp(cs.user, bs.front_data.get('msn_pop_id'), ack, data)) + message = messagedata_from_msnp(cs.user, bs.front_data.get('msn_pop_id'), ack, b''.join(_chunk_body(chunk, i) for i, chunk in enumerate(chunks)) if len(chunks) > 1 else data) except error.SpecialMessageNotSentWithDType: self.close() return + if len(chunks) > 1: + message.front_cache['msnp_chunks'] = chunks + + if message.type is MessageType.MSNP2P: + p2pv2 = sb_p2p_is_v2(message.front_cache.get('msn_p2p_dest')) + message.front_cache['msn_p2pv2'] = p2pv2 + packet = neutralize_direct_p2p(cast(bytes, message.text), p2pv2) + if packet != message.text: + i = data.index(b'\r\n\r\n') + 4 + message.text = cast(Any, packet) + message.front_cache['msnp'] = data[:i] + packet + + (p2p_dest, p2p_dest_pop_id) = decode_email_pop(message.front_cache.get('msn_p2p_dest') or '') + if p2p_dest_pop_id is not None: + p2p_dest_uuid = self.backend.util_get_uuid_from_email(p2p_dest) + if p2p_dest_uuid is not None: + message.text = translate_p2pv2_ack(message.text, get_p2p_state(cs.chat.front_data, p2p_dest_uuid, bs.user.uuid)) + delivered = cs.send_message_to_everyone(message) # TODO: Implement ACK/NAK if ack == 'U': return - any_failed = False + any_failed = not delivered if any_failed: # ADN self.send_reply('NAK', trid) elif ack != 'N': # AD self.send_reply('ACK', trid) + def _collect_chunk(self, data: bytes) -> Optional[List[bytes]]: + try: + i = data.index(b'\r\n\r\n') + 4 + headers = Parser().parsestr(data[:i].decode('utf-8')) + except (ValueError, UnicodeDecodeError): + return [data] + message_id = headers.get('Message-ID') + if message_id is None or (headers.get('Chunks') is None and headers.get('Chunk') is None): + return [data] + pending = self.chunks.setdefault(str(message_id), { 'total': 0, 'parts': {} }) + try: + if headers.get('Chunks') is not None: + pending['total'] = int(str(headers.get('Chunks'))) + pending['parts'][0] = data + else: + pending['parts'][int(str(headers.get('Chunk')))] = data + except ValueError: + del self.chunks[str(message_id)] + return [data] + total = pending['total'] + if not total or len(pending['parts']) < total or total > MAX_CHUNKS: + if total > MAX_CHUNKS or len(self.chunks) > MAX_CHUNKED_MESSAGES: + del self.chunks[str(message_id)] + return None + del self.chunks[str(message_id)] + return [pending['parts'][n] for n in range(total) if n in pending['parts']] + async def _conn_auth_limit_counter(self) -> None: counter = 0 @@ -336,29 +385,14 @@ class ChatEventHandler(event.ChatEventHandler): # Capability flags in JOI were technically introduced by MSNP13, but there are MSNP12 logs that show that they # had been introduced in that protocol version by then if 12 <= ctrl.dialect <= 15: - extra = ( - ( - (cs_other.bs.front_data.get('msn_capabilities') or 0) - if cs_other.bs.front_data.get('msn') is True - else MAX_CAPABILITIES_BASIC - ), - ) # type: Tuple[Any, ...] + extra = (get_session_capabilities(cs_other.bs, ctrl.dialect)[0],) # type: Tuple[Any, ...] elif ctrl.dialect >= 16: - extra = ( - encode_capabilities_capabilitiesex( - ( - (cs_other.bs.front_data.get('msn_capabilities') or 0) - if cs_other.bs.front_data.get('msn') is True - else MAX_CAPABILITIES_BASIC - ), - cs_other.bs.front_data.get('msn_capabilitiesex') or 0, - ), - ) + extra = (encode_capabilities_capabilitiesex(*get_session_capabilities(cs_other.bs, ctrl.dialect)),) else: extra = () - ctrl.send_reply('JOI', email, user.status.name, *extra) + ctrl.send_reply('JOI', email, _friendly_name(ctrl.backend, user), *extra) if cs_other.user is not cs.user and pop_id_other is not None and first_pop and ctrl.dialect >= 16: - ctrl.send_reply('JOI', user_display_email, user.status.name, *extra) + ctrl.send_reply('JOI', user_display_email, _friendly_name(ctrl.backend, user), *extra) def on_participant_left(self, cs_other: ChatSession, last_pop: bool) -> None: ctrl = self.ctrl @@ -388,8 +422,53 @@ class ChatEventHandler(event.ChatEventHandler): pass def on_message(self, data: MessageData) -> None: - if data.type is not MessageType.TypingDone: - self.ctrl.send_reply('MSG', self.ctrl.backend.util_get_display_email(data.sender), data.sender.status.name, messagedata_to_msnp(data)) + if data.type in (MessageType.TypingDone, MessageType.Ignored): return + if data.type is MessageType.MSNP2P and 'msn_p2p' in data.front_cache: + self._send_p2p(data) + return + ctrl = self.ctrl + sender_email = ctrl.backend.util_get_display_email(data.sender) + if 'msnp_chunks' in data.front_cache: + for chunk in data.front_cache['msnp_chunks']: + ctrl.send_reply('MSG', sender_email, data.sender.status.name, chunk) + return + payload = messagedata_to_msnp(data, sender_email = sender_email) + if payload is None: return + for chunk in chunk_msnp(payload): + ctrl.send_reply('MSG', sender_email, data.sender.status.name, chunk) + + def _send_p2p(self, data: MessageData) -> None: + ctrl = self.ctrl + bs = ctrl.bs + assert bs is not None + + pop_id = bs.front_data.get('msn_pop_id') + dest_pop_id = data.front_cache.get('msn_p2p_dest_pop_id') + if is_null_epid(dest_pop_id): dest_pop_id = None + if dest_pop_id is not None and pop_id is not None and normalize_pop_id(dest_pop_id).lower() != pop_id.lower(): return + + sender_email = ctrl.backend.util_get_display_email(data.sender) + user_email = ctrl.backend.util_get_display_email(bs.user) + dest_email = data.front_cache.get('msn_p2p_dest_email') + if dest_email is not None and dest_email.lower() not in (user_email.lower(), bs.user.email.lower()): return + p2pv2 = data.front_cache.get('msn_p2pv2') + if p2pv2 is None: + p2pv2 = (ctrl.dialect >= 16 and bool(get_session_capabilities(bs, ctrl.dialect)[1] & CAPABILITIESEX_P2PV2)) + if p2pv2 and (ctrl.dialect < 16 or pop_id is None): return + if p2pv2: + dest = encode_email_pop(user_email, dest_pop_id or pop_id) + src = encode_email_pop(sender_email, data.sender_pop_id) # type: Optional[str] + else: + dest = user_email + src = None + + state = get_p2p_state(self.cs.chat.front_data, data.sender.uuid, bs.user.uuid) + if data.front_cache.get('msn_sdg_pipe'): + state['pipe'] = data.front_cache['msn_sdg_pipe'] + state['pop_id'] = data.sender_pop_id + for packet in data.front_cache['msn_p2p']: + for payload in sb_p2p_messages(packet, dest, src, p2pv2, state): + ctrl.send_reply('MSG', sender_email, data.sender.status.name, payload) def on_close(self) -> None: self.ctrl.close() @@ -433,73 +512,127 @@ def messagedata_from_msnp(sender: User, sender_pop_id: Optional[str], ack: str, i = data.index(b'\r\n\r\n') + 4 headers = Parser().parsestr(data[:i].decode('utf-8')) body_raw = data[i:] - except: - type = MessageType.Chat - text = "CrossTalk System Message: This message cannot be viewed on the client you're currently using." + except Exception: + message = MessageData(sender = sender, sender_pop_id = sender_pop_id, type = MessageType.Chat, text = UNSUPPORTED_MESSAGE_TEXT) + message.front_cache['msnp'] = data + return message + front_cache: dict[str, Any] = {} + text: Any = body_raw content_type = headers.get_content_type() - if content_type is not None: - if content_type == 'text/x-msmsgscontrol': - type = MessageType.Typing + if content_type == 'text/x-msmsgscontrol': + type = MessageType.Typing + text = '' + elif content_type == 'text/x-msnmsgr-datacast': + body = body_raw.decode('utf-8', 'replace') + fields = _parse_body_fields(body) + id = (fields.get('ID') or '').strip() + if id == '1': + type = MessageType.Nudge text = '' - elif content_type == 'text/x-msnmsgr-datacast': - body = body_raw.decode('utf-8') - id_start = body.index('ID:') + 3 - id_end = body.index('\r\n', id_start) - id = body[id_start:id_end].strip() - if id == '1': - type = MessageType.Nudge - text = '' - else: - type = MessageType.Chat - text = "CrossTalk System Message: This message cannot be viewed on the client you're currently using." - elif content_type == 'application/x-msnmsgrp2p': - if ack != 'D': - raise error.SpecialMessageNotSentWithDType() - type = MessageType.MSNP2P - text = body_raw - elif content_type == "text/x-mms-emoticon": - type = MessageType.Emoticon - text = body_raw - elif content_type == "text/x-mms-animemoticon": - type = MessageType.Emoticon - text = body_raw - elif content_type == 'text/x-msmsgsinvite': - type = MessageType.MSNP2PInvite - text = body_raw - elif content_type == 'text/x-clientcaps': + elif id in DATACAST_MSNOBJ: type = MessageType.Other - text = body_raw - elif content_type == 'text/x-msnmsgr-roster-change': - type = MessageType.Other - text = body_raw - elif content_type == 'application/x-ms-ink': - type = MessageType.Ink - text = body_raw - elif content_type == 'text/plain': + text = (fields.get('Data') or '').strip() + elif id == DATACAST_ACTION: type = MessageType.Chat - text = body_raw.decode('utf-8') + front_cache['msn_action'] = (fields.get('Data') or '').strip() + text = '* {} {}'.format(sender.status.name or sender.email, front_cache['msn_action']) else: - pass - else: + type = MessageType.Chat + text = UNSUPPORTED_MESSAGE_TEXT + elif content_type == 'application/x-msnmsgrp2p': + if ack != 'D': + raise error.SpecialMessageNotSentWithDType() + type = MessageType.MSNP2P + elif content_type == 'text/x-msmsgsinvite': + type = MessageType.MSNP2PInvite + elif content_type in ('application/x-ms-ink', 'image/gif'): + type = MessageType.Ink + elif content_type in ('text/x-mms-emoticon', 'text/x-mms-animemoticon'): + type = MessageType.Emoticon + elif content_type == 'text/plain': type = MessageType.Chat - text = "CrossTalk System Message: This message cannot be viewed on the client you're currently using." + text = body_raw.decode('utf-8', 'replace') + im_format = headers.get('X-MMS-IM-Format') + if im_format is not None: + front_cache['msn_im_format'] = str(im_format) + else: + type = MessageType.Other message = MessageData(sender = sender, sender_pop_id = sender_pop_id, type = type, text = text) message.front_cache['msnp'] = data + message.front_cache.update(front_cache) + if type is MessageType.MSNP2P: + message.front_cache['msn_p2p_dest'] = str(headers.get('P2P-Dest') or '') + elif type is MessageType.Emoticon: + message.front_cache['msn_emoticon'] = content_type + elif type is MessageType.Other and content_type == 'text/x-msnmsgr-datacast': + message.front_cache['msn_datacast'] = id + elif type is MessageType.Chat and 'msn_action' in front_cache: + message.front_cache['msn_datacast'] = DATACAST_ACTION return message -def messagedata_to_msnp(data: MessageData) -> bytes: +def messagedata_to_msnp(data: MessageData, *, sender_email: Optional[str] = None) -> Optional[bytes]: if 'msnp' not in data.front_cache: if data.type is MessageType.Typing: - s = F'MIME-Version: 1.0\r\nContent-Type: text/x-msmsgscontrol\r\nTypingUser: {data.sender.email}\r\n\r\n\r\n' + s = F'MIME-Version: 1.0\r\nContent-Type: text/x-msmsgscontrol\r\nTypingUser: {sender_email or data.sender.email}\r\n\r\n\r\n' elif data.type is MessageType.Nudge: s = 'MIME-Version: 1.0\r\nContent-Type: text/x-msnmsgr-datacast\r\n\r\nID: 1\r\n\r\n' - elif data.type is MessageType.MSNP2P: - s = F'MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: {other_user.email}\r\n\r\n{data.text}' + elif data.type is MessageType.Other and 'msn_datacast' in data.front_cache: + s = 'MIME-Version: 1.0\r\nContent-Type: text/x-msnmsgr-datacast\r\n\r\nID: {}\r\nData: {}\r\n\r\n'.format(data.front_cache['msn_datacast'], data.text) + elif data.type is MessageType.Emoticon: + emoticons = (data.text.decode('utf-8', 'replace') if isinstance(data.text, bytes) else (data.text or '')) + s = 'MIME-Version: 1.0\r\nContent-Type: {}\r\n\r\n'.format(data.front_cache.get('msn_emoticon') or 'text/x-mms-emoticon') + emoticons + elif data.type is MessageType.Chat and 'msn_action' in data.front_cache: + s = 'MIME-Version: 1.0\r\nContent-Type: text/x-msnmsgr-datacast\r\n\r\nID: {}\r\nData: {}\r\n\r\n'.format(DATACAST_ACTION, data.front_cache['msn_action']) elif data.type is MessageType.Chat: - s = 'MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n' + (data.text or '') + im_format = data.front_cache.get('msn_im_format') + s = 'MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n{}\r\n'.format( + 'X-MMS-IM-Format: {}\r\n'.format(im_format) if im_format else '', + ) + (data.text or '') else: - raise ValueError("unknown message type", data.type) + return None data.front_cache['msnp'] = s.encode('utf-8') return data.front_cache['msnp'] + +def chunk_msnp(payload: bytes) -> List[bytes]: + if len(payload) <= SB_MSG_LIMIT: + return [payload] + i = payload.index(b'\r\n\r\n') + 4 + headers = payload[:i - 2] + body = payload[i:] + message_id = '{' + gen_uuid().upper() + '}' + room = SB_MSG_LIMIT - len(headers) - 80 + parts = [body[n:n + room] for n in range(0, len(body), room)] + chunks = [headers + 'Message-ID: {}\r\nChunks: {}\r\n\r\n'.format(message_id, len(parts)).encode('ascii') + parts[0]] + content_type = (b'Content-Type: ' + headers.split(b'Content-Type: ', 1)[1].split(b'\r\n', 1)[0] + b'\r\n') if b'Content-Type: ' in headers else b'' + for n, part in enumerate(parts[1:], 1): + chunks.append(b'MIME-Version: 1.0\r\n' + content_type + 'Message-ID: {}\r\nChunk: {}\r\n\r\n'.format(message_id, n).encode('ascii') + part) + return chunks + +def _chunk_body(chunk: bytes, n: int) -> bytes: + if n == 0: return chunk + try: + return chunk[chunk.index(b'\r\n\r\n') + 4:] + except ValueError: + return b'' + +def _parse_body_fields(body: str) -> Dict[str, str]: + fields = {} # type: Dict[str, str] + for line in body.split('\r\n'): + if ':' not in line: continue + key, value = line.split(':', 1) + fields.setdefault(key.strip(), value.strip()) + return fields + +SB_MSG_LIMIT = 1664 +MAX_CHUNKS = 64 +MAX_CHUNKED_MESSAGES = 16 + +def _encode_participant_capabilities(cs_other: ChatSession, dialect: int) -> int | str: + if dialect < 16: + return get_session_capabilities(cs_other.bs, dialect)[0] + return encode_capabilities_capabilitiesex(*get_session_capabilities(cs_other.bs, dialect)) + +def _friendly_name(backend: Backend, user: User) -> str: + return user.status.name or backend.util_get_display_email(user) \ No newline at end of file diff --git a/front/msn/p2p_bridge.py b/front/msn/p2p_bridge.py new file mode 100644 index 0000000..163df13 --- /dev/null +++ b/front/msn/p2p_bridge.py @@ -0,0 +1,359 @@ +from typing import Any, Dict, List, Optional +import struct + +from .misc import encode_payload + +# Largest P2P payload official clients put in one switchboard `MSG` (which is capped at 1664 bytes) +SB_P2P_DATA_SIZE = 1202 + +# The most a switchboard `MSG` payload (MIME headers and P2P packet) may be; clients enforce it on what they send, so what +# the server sends them stays under it too +SB_MSG_MAX = 1664 + +SDG_DATA = '''Routing: 1.0 +To: 1:{to_email} +From: 1:{from_email} +Options: 0 +Service-Channel: PE + +Reliability: 1.0 + +Messaging: 2.0 +Message-Type: Data +Content-Type: application/x-msnmsgrp2p +Content-Transfer-Encoding: binary +Content-Length: {cl} +Pipe: {pipe} +Bridging-Offsets: {offsets} + +''' + + +SLP_DIRECT_CONTENT_TYPES = frozenset({ + 'application/x-msnmsgr-transreqbody', 'application/x-msnmsgr-transrespbody', + 'application/x-msnmsgr-transdestaddrupdate', 'application/x-msnmsgr-transudpswitch', +}) +SLP_TRANSREQ = 'application/x-msnmsgr-transreqbody' +SLP_TRANSRESP = 'application/x-msnmsgr-transrespbody' + + +SLP_BRIDGES = 'TCPv1 SBBridge' +SLP_NULL_NONCE = '{00000000-0000-0000-0000-000000000000}' + +_SLP_SESSION_HEADERS = ('SessionID', 'SChannelState', 'Capabilities-Flags') + +_SLP_PAD_HEADER = 'X-Padding' + +def split_sdg_p2p(body: bytes, offsets: str) -> List[bytes]: + starts = [int(offset) for offset in offsets.split(',') if offset.strip()] or [0] + ends = starts[1:] + [len(body)] + return [body[start:end] for start, end in zip(starts, ends) if end > start] + +def detect_p2p_version(packet: bytes) -> Optional[bool]: + v1 = len(packet) >= 52 and len(packet) == 48 + struct.unpack('= 8: + (hl, _, payload_size) = struct.unpack('>BBH', packet[:4]) + v2 = hl >= 8 and hl % 4 == 0 and len(packet) in (hl + payload_size + 4, hl + payload_size) + if v1 == v2: return None + return v2 + +def get_p2p_state(front_data: Dict[str, Any], sender_uuid: str, receiver_uuid: str) -> Dict[str, Any]: + return front_data.setdefault('msn_p2p', {}).setdefault((sender_uuid, receiver_uuid), { 'shift': 0, 'acks': {}, 'pipe': 1 }) + +def build_sdg_data(to_email: str, from_email: str, packets: List[bytes], pipe: int) -> bytes: + offsets = [] # type: List[str] + body = b'' + for packet in packets: + offsets.append(str(len(body))) + body += packet + return encode_payload(SDG_DATA, + to_email = to_email, from_email = from_email, cl = len(body), pipe = pipe, offsets = ','.join(offsets), + ) + body + +def build_sb_p2p_headers(dest: str, src: Optional[str]) -> bytes: + headers = 'MIME-Version: 1.0\r\nContent-Type: application/x-msnmsgrp2p\r\nP2P-Dest: {}\r\n'.format(dest) + if src is not None: + headers += 'P2P-Src: {}\r\n'.format(src) + return (headers + '\r\n').encode('utf-8') + +def sb_p2p_data_size(headers: bytes, p2pv2: bool) -> int: + if p2pv2: + overhead = 24 + 20 + 4 + else: + overhead = 48 + 4 + return max(256, SB_MSG_MAX - len(headers) - overhead) + +def chunk_p2p(packet: bytes, p2pv2: bool, state: Dict[str, Any], max_data: int = SB_P2P_DATA_SIZE) -> List[bytes]: + if p2pv2: + return _chunk_p2pv2(packet, state, max_data) + return _chunk_p2pv1(packet, min(max_data, SB_P2P_DATA_SIZE)) + +def translate_p2pv2_ack(packet: bytes, state: Dict[str, Any]) -> bytes: + if len(packet) < 8: return packet + hl = packet[0] + tlvs = bytearray(packet[8:hl]) + i = 0 + while i + 2 <= len(tlvs) and tlvs[i]: + t, l = tlvs[i], tlvs[i + 1] + if t in (0x02, 0x03) and l == 4: + value = struct.unpack('>I', tlvs[i + 2:i + 6])[0] + tlvs[i + 2:i + 6] = struct.pack('>I', state['acks'].get(value, value)) + i += 2 + l + return packet[:8] + bytes(tlvs) + packet[hl:] + +def _chunk_p2pv1(packet: bytes, max_data: int = SB_P2P_DATA_SIZE) -> List[bytes]: + data = packet[48:-4] + if len(data) <= max_data: + return [packet] + (session_id, identifier, offset, total_size, _, flags, ack_session_id, ack_unique_id, ack_data_size) = struct.unpack(' List[bytes]: + (hl, op, payload_size, identifier) = struct.unpack('>BBHI', packet[:8]) + payload = packet[hl:hl + payload_size] + footer = packet[hl + payload_size:] + next_identifier = (identifier + payload_size) & 0xFFFFFFFF + shift = state['shift'] + + if payload_size == 0 or payload_size - payload[0] <= max_data: + if shift: + state['acks'][(next_identifier + shift) & 0xFFFFFFFF] = next_identifier + packet = packet[:4] + struct.pack('>I', (identifier + shift) & 0xFFFFFFFF) + packet[8:] + return [packet] + + (dhl, tf, package_number, session_id) = struct.unpack('>BBHI', payload[:8]) + data = payload[dhl:] + data_remaining = _get_data_remaining(payload[8:dhl]) + chunks = [] + chunk_identifier = identifier + shift + for i in range(0, len(data), max_data): + chunk_data = data[i:i + max_data] + first = (i == 0) + last = (i + len(chunk_data) >= len(data)) + left = data_remaining + len(data) - i - len(chunk_data) + data_tlvs = (struct.pack('>BBQ', 0x01, 8, left) + b'\x00\x00' if left else b'') + chunk_payload = struct.pack('>BBHI', 8 + len(data_tlvs), (tf if first else tf & ~0x01), package_number, session_id) + data_tlvs + chunk_data + tlvs = (packet[8:hl] if first else b'') + chunk_op = (op & 0x01 if first else 0) | (op & 0x02 if last else 0) + chunks.append(struct.pack('>BBHI', 8 + len(tlvs), chunk_op, len(chunk_payload), chunk_identifier & 0xFFFFFFFF) + tlvs + chunk_payload + footer) + chunk_identifier += len(chunk_payload) + state['shift'] = chunk_identifier - (identifier + payload_size) + state['acks'][chunk_identifier & 0xFFFFFFFF] = next_identifier + return chunks + +def _get_data_remaining(tlvs: bytes) -> int: + i = 0 + while i + 2 <= len(tlvs) and tlvs[i]: + t, l = tlvs[i], tlvs[i + 1] + if t == 0x01 and l == 8: + return struct.unpack('>Q', tlvs[i + 2:i + 10])[0] + i += 2 + l + return 0 + +class SLPMessage: + __slots__ = ('start_line', 'headers', 'body') + + start_line: str + headers: list[tuple[str, str]] + body: bytes + + def __init__(self, start_line: str, headers: list[tuple[str, str]], body: bytes) -> None: + self.start_line = start_line + self.headers = headers + self.body = body + + def get(self, name: str) -> str | None: + for key, value in self.headers: + if key.lower() == name.lower(): return value + return None + + @property + def content_type(self) -> str: + return (self.get('Content-Type') or '').split(';', 1)[0].strip().lower() + + @property + def is_request(self) -> bool: + return not self.start_line.startswith('MSNSLP/') + + @property + def method(self) -> str: + return self.start_line.split(' ', 1)[0] + + def body_values(self) -> list[tuple[str, str]]: + return _parse_slp_lines(self.body.rstrip(b'\x00').decode('utf-8', 'replace')) + +def parse_slp(data: bytes) -> SLPMessage | None: + if not (data.startswith(b'MSNSLP/') or data[:12].split(b' ', 1)[0] in _SLP_METHODS): + return None + try: + end = data.index(b'\r\n\r\n') + head = data[:end].decode('utf-8') + except (ValueError, UnicodeDecodeError): + return None + lines = head.split('\r\n') + headers = [] + for line in lines[1:]: + if ':' not in line: continue + key, value = line.split(':', 1) + headers.append((key.strip(), value.strip())) + slp = SLPMessage(lines[0], headers, b'') + try: + length = int(slp.get('Content-Length') or '0') + except ValueError: + return None + slp.body = data[end + 4:end + 4 + length] + return slp + +def is_direct_connection_slp(data: bytes) -> bool: + slp = parse_slp(data) + return slp is not None and slp.content_type in SLP_DIRECT_CONTENT_TYPES + +def rewrite_direct_slp(data: bytes, *, preserve_length: bool) -> bytes | None: + slp = parse_slp(data) + if slp is None or slp.content_type not in SLP_DIRECT_CONTENT_TYPES: + return None + values = slp.body_values() + content_type = slp.content_type + if content_type == SLP_TRANSREQ: + nonce = _nonce_line(values, keep = True) + required = [('Bridges', SLP_BRIDGES), ('NetID', '0'), ('Conn-Type', 'Firewall'), ('TCP-Conn-Type', 'Firewall'), ('UPnPNat', 'false'), ('ICF', 'true')] + nonce + optional = [(key, value) for key, value in values if key in _SLP_SESSION_HEADERS or key == 'Nat-Trav-Msg-Type'] + elif content_type == SLP_TRANSRESP: + required = [('Bridge', 'SBBridge'), ('Listening', 'false')] + _nonce_line(values, keep = False) + optional = [(key, value) for key, value in values if key in _SLP_SESSION_HEADERS] + else: + required = [] + optional = [(key, value) for key, value in values if key == 'Nat-Trav-Msg-Type'] + + body_old = slp.body + terminator = (b'\x00' if body_old.endswith(b'\x00') else b'') + body = _build_slp_body(required, optional, (len(body_old) - len(terminator)) if preserve_length else None) + if body is None: + return None + body += terminator + + head_old = data[:data.index(b'\r\n\r\n') + 4] + if preserve_length: + head = head_old + else: + head = _replace_content_length(head_old, len(body) + (0 if terminator else 1)) + return head + body + data[len(head_old) + len(body_old):] + +def refuse_direct_invite(data: bytes) -> bytes | None: + slp = parse_slp(data) + if slp is None or not slp.is_request or slp.method != 'INVITE' or slp.content_type != SLP_TRANSREQ: + return None + values = slp.body_values() + body_values = [('Bridge', 'SBBridge'), ('Listening', 'false')] + _nonce_line(values, keep = False) + [ + (key, value) for key, value in values if key in _SLP_SESSION_HEADERS + ] + body = ''.join('{}: {}\r\n'.format(key, value) for key, value in body_values) + '\r\n' + headers = [ + ('To', slp.get('From') or ''), ('From', slp.get('To') or ''), ('Via', slp.get('Via') or ''), + ('CSeq', '{} '.format(_next_cseq(slp.get('CSeq')))), ('Call-ID', slp.get('Call-ID') or ''), ('Max-Forwards', '0'), + ('Content-Type', SLP_TRANSRESP), ('Content-Length', str(len(body.encode('utf-8')) + 1)), + ] + return ('MSNSLP/1.0 200 OK\r\n' + ''.join('{}: {}\r\n'.format(key, value) for key, value in headers) + '\r\n' + body).encode('utf-8') + +def slp_direct_negotiation_kind(data: bytes) -> str | None: + slp = parse_slp(data) + if slp is None or slp.content_type not in SLP_DIRECT_CONTENT_TYPES: return None + return slp.content_type + +def neutralize_direct_p2p(packet: bytes, p2pv2: bool) -> bytes: + try: + if p2pv2: + if len(packet) < 8: return packet + (hl, _, payload_size, _) = struct.unpack('>BBHI', packet[:8]) + if payload_size == 0 or len(packet) < hl + payload_size: return packet + payload = packet[hl:hl + payload_size] + (dhl, tf, _, session_id) = struct.unpack('>BBHI', payload[:8]) + if session_id != 0 or not tf & 0x01 or _get_data_remaining(payload[8:dhl]): return packet + start = hl + dhl + end = hl + payload_size + else: + if len(packet) < 52: return packet + (session_id, _, offset, total_size, size, flags) = struct.unpack(' len(packet) - 4: return packet + rewritten = rewrite_direct_slp(packet[start:end], preserve_length = True) + except (struct.error, IndexError): + return packet + if rewritten is None or len(rewritten) != end - start: + return packet + return packet[:start] + rewritten + packet[end:] + +def _nonce_line(values: list[tuple[str, str]], *, keep: bool) -> list[tuple[str, str]]: + for key, value in values: + if key in ('Hashed-Nonce', 'Nonce'): + return [(key, value if keep else SLP_NULL_NONCE)] + return ([] if keep else [('Nonce', SLP_NULL_NONCE)]) + +def _build_slp_body(required: list[tuple[str, str]], optional: list[tuple[str, str]], length: int | None) -> bytes | None: + def encode(lines: list[tuple[str, str]], pad: int = 0) -> bytes: + text = ''.join('{}: {}\r\n'.format(key, value) for key, value in lines) + if pad: + text += '{}: {}\r\n'.format(_SLP_PAD_HEADER, '0' * (pad - len(_SLP_PAD_HEADER) - 4)) + return (text + '\r\n').encode('utf-8') + + if length is None: + return encode(required + optional) + min_pad = len(_SLP_PAD_HEADER) + 4 + for count in range(len(optional), -1, -1): + body = encode(required + optional[:count]) + rest = length - len(body) + if rest == 0: + return body + if rest >= min_pad: + return encode(required + optional[:count], rest) + return None + +def _replace_content_length(head: bytes, length: int) -> bytes: + lines = head.split(b'\r\n') + for i, line in enumerate(lines): + if line.lower().startswith(b'content-length:'): + lines[i] = b'Content-Length: ' + str(length).encode('ascii') + return b'\r\n'.join(lines) + +def _next_cseq(cseq: str | None) -> int: + try: + return int((cseq or '0').strip()) + 1 + except ValueError: + return 1 + +def _parse_slp_lines(text: str) -> list[tuple[str, str]]: + values = [] + for line in text.split('\r\n'): + if ':' not in line: continue + key, value = line.split(':', 1) + values.append((key.strip(), value.strip())) + return values + +_SLP_METHODS = frozenset({ b'INVITE', b'ACK', b'BYE', b'CANCEL' }) + +def sb_p2p_is_v2(dest: Optional[str]) -> bool: + return dest is not None and ';' in dest + +def neutralize_sdg_data(body: bytes, offsets: str, p2pv2: bool) -> bytes: + starts = [int(offset) for offset in offsets.split(',') if offset.strip()] or [0] + ends = starts[1:] + [len(body)] + out = body[:starts[0]] + for start, end in zip(starts, ends): + out += neutralize_direct_p2p(body[start:end], p2pv2) + return out + +def slp_reply_signal(data: bytes) -> bytes | None: + return refuse_direct_invite(data) + +def sb_p2p_messages(packet: bytes, dest: str, src: Optional[str], p2pv2: bool, state: Dict[str, Any]) -> List[bytes]: + headers = build_sb_p2p_headers(dest, src) + return [headers + chunk for chunk in chunk_p2p(packet, p2pv2, state, sb_p2p_data_size(headers, p2pv2))] diff --git a/front/oscar/ctrl.py b/front/oscar/ctrl.py index 16ff217..e42dbb6 100644 --- a/front/oscar/ctrl.py +++ b/front/oscar/ctrl.py @@ -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) \ No newline at end of file + return chats.get(other_user_uuid) diff --git a/front/oscar/entry.py b/front/oscar/entry.py index 89afe05..62c90b4 100644 --- a/front/oscar/entry.py +++ b/front/oscar/entry.py @@ -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() \ No newline at end of file + self.transport.close() diff --git a/front/oscar/foodgroups/__init__.py b/front/oscar/foodgroups/__init__.py index 25238ff..6c1ec5e 100644 --- a/front/oscar/foodgroups/__init__.py +++ b/front/oscar/foodgroups/__init__.py @@ -7,5 +7,14 @@ __all__ = [ 'stats', 'feedbag', 'popup', - 'bucp' + 'bucp', + 'directory', + 'email', + 'icq', + 'admin', + 'bart', + 'chat', + 'chatnav', + 'user_lookup', + 'invite' ] \ No newline at end of file diff --git a/front/oscar/foodgroups/admin.py b/front/oscar/foodgroups/admin.py new file mode 100644 index 0000000..9d17e3a --- /dev/null +++ b/front/oscar/foodgroups/admin.py @@ -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) diff --git a/front/oscar/foodgroups/bart.py b/front/oscar/foodgroups/bart.py new file mode 100644 index 0000000..b3528c4 --- /dev/null +++ b/front/oscar/foodgroups/bart.py @@ -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) diff --git a/front/oscar/foodgroups/bos.py b/front/oscar/foodgroups/bos.py index 7a309d6..b98b941 100644 --- a/front/oscar/foodgroups/bos.py +++ b/front/oscar/foodgroups/bos.py @@ -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) \ No newline at end of file diff --git a/front/oscar/foodgroups/bucp.py b/front/oscar/foodgroups/bucp.py index 4013a0f..06aad38 100644 --- a/front/oscar/foodgroups/bucp.py +++ b/front/oscar/foodgroups/bucp.py @@ -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) \ No newline at end of file + client.send_snac(response_msg) diff --git a/front/oscar/foodgroups/buddy.py b/front/oscar/foodgroups/buddy.py index cfab386..040fc10 100644 --- a/front/oscar/foodgroups/buddy.py +++ b/front/oscar/foodgroups/buddy.py @@ -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) \ No newline at end of file diff --git a/front/oscar/foodgroups/chat.py b/front/oscar/foodgroups/chat.py new file mode 100644 index 0000000..4410095 --- /dev/null +++ b/front/oscar/foodgroups/chat.py @@ -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) diff --git a/front/oscar/foodgroups/chatnav.py b/front/oscar/foodgroups/chatnav.py new file mode 100644 index 0000000..6606690 --- /dev/null +++ b/front/oscar/foodgroups/chatnav.py @@ -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))])) diff --git a/front/oscar/foodgroups/directory.py b/front/oscar/foodgroups/directory.py new file mode 100644 index 0000000..6ddc0cc --- /dev/null +++ b/front/oscar/foodgroups/directory.py @@ -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) diff --git a/front/oscar/foodgroups/email.py b/front/oscar/foodgroups/email.py new file mode 100644 index 0000000..bffdf4a --- /dev/null +++ b/front/oscar/foodgroups/email.py @@ -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)') diff --git a/front/oscar/foodgroups/feedbag.py b/front/oscar/foodgroups/feedbag.py index fc12349..dd3e4b6 100644 --- a/front/oscar/foodgroups/feedbag.py +++ b/front/oscar/foodgroups/feedbag.py @@ -1,23 +1,27 @@ import time import struct +import base64 +import hashlib from array import array from core import error -from core.models import ContactList, Substatus +from core.models import ContactList, Substatus, Contact, Group, User, _aim_pd_mode from dataclasses import dataclass from enum import IntEnum -from typing import Optional -from util.misc import Logger +from typing import Optional, Any +from util.misc import Logger, is_valid_oscar_screenname from .buddy import build_presence_notif # TODO(subpurple): move build_presence_notif out of buddy? -from ..proto.tlv import TLV +from .buddy import push_presence, push_buddy_list +from .pd import PDMode, PDStatus, apply_pd_info, pd_add, pd_remove +from ..proto import names +from ..proto import bart +from ..proto.delivery import oscar_sessions, feedbag_sessions +from ..proto.tlv import TLV, find_tlv, marshal_tlvs from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup from ..proto.buffer import Buffer +from util import icq - -# I only put the classes I need in this IntEnum -# -# For a complete list of feedbag classes, see https://ninawiki.preloading.dev/wiki/Protocols/OSCAR/Foodgroups/FEEDBAG/Items#Class:_FEEDBAG_CLASS_IDS class FeedbagClass(IntEnum): Buddy = 0x0000, Group = 0x0001, @@ -25,6 +29,30 @@ class FeedbagClass(IntEnum): Deny = 0x0003, PdInfo = 0x0004, BuddyPrefs = 0x0005 + NonBuddy = 0x0006 + TpaProvider = 0x0007 + TpaSubscription = 0x0008 + ClientPrefs = 0x0009 + Stock = 0x000A + Weather = 0x000B + WatchList = 0x000D + IgnoreList = 0x000E + DateTime = 0x000F + ExternalUser = 0x0010 + RootCreator = 0x0011 + Fish = 0x0012 + ImportTimestamp = 0x0013 + Bart = 0x0014 + RbOrder = 0x0015 + Personality = 0x0016 + AlProf = 0x0017 + AlInfo = 0x0018 + Interaction = 0x0019 + VanityInfo = 0x001D + FavoriteLocation = 0x001E + BartPdInfo = 0x001F + CustomEmoticons = 0x0024 + IcqStatusNote = 0x015C class FeedbagAttributes(IntEnum): @@ -36,6 +64,10 @@ class FeedbagAttributes(IntEnum): FishIgnoreMode = 0x00D3, PdMask = 0x00CB, BuddyPrefs = 0x00C9 + Pending = 0x0066 + TimeT = 0x0067 + PdFlags = 0x00CC + BartInfo = 0x00D5 class FeedbagStatus(IntEnum): Success = 0x0000, @@ -44,6 +76,60 @@ class FeedbagStatus(IntEnum): BadRequest = 0x000A, OverLimit = 0x000C, BadLoginID = 0x0010, + DbError = 0x0001 + Unavailable = 0x0005 + DbTimeOut = 0x000B + NotExecuted = 0x000D + AuthRequired = 0x000E + AutoAuth = 0x000F + OverBuddyLimit = 0x0011 + InsertSmartGroup = 0x0014 + Timeout = 0x001A + +class FeedbagError(IntEnum): + # unconfirmed on the NINA wiki, but the only FEEDBAG__ERR code it records + BuddyListUnavailable = 0x0005 + +# limits mirror what FEEDBAG__RIGHTS_REPLY advertises +MAX_ID = 0x7FFF +MAX_ITEM_NAME_LEN = 97 +MAX_ITEM_ATTRS_SIZE = 1698 +MAX_BUDDIES = 1000 +MAX_GROUPS = 100 +MAX_BUDDIES_PER_GROUP = 600 +MAX_CLIENT_ITEMS = 100 +MIN_CLIENT_CLASS = 0x0400 +MAX_REPLY_ITEM_BYTES = 0xE000 + +# everything the backend model has no native home for lives in user.settings under this key +SSI_KEY = 'AIM_SSI' + +# the privacy mode/mask the permit/deny logic in core.models reads +PD_KEY = 'AIM_PD' + +KNOWN_CLASSES = frozenset(int(c) for c in FeedbagClass) + +# classes the wiki marks (R): only valid in the root group +ROOT_ONLY_CLASSES = frozenset({ + FeedbagClass.Permit, FeedbagClass.Deny, FeedbagClass.PdInfo, FeedbagClass.BuddyPrefs, FeedbagClass.NonBuddy, + FeedbagClass.ClientPrefs, FeedbagClass.DateTime, FeedbagClass.Bart, FeedbagClass.RbOrder, FeedbagClass.Personality, + FeedbagClass.AlProf, FeedbagClass.AlInfo, FeedbagClass.Interaction, FeedbagClass.VanityInfo, + FeedbagClass.FavoriteLocation, FeedbagClass.BartPdInfo, +}) + +# classes limited to one item, which must have "" for a name +SINGLE_ITEM_CLASSES = frozenset({FeedbagClass.PdInfo, FeedbagClass.BuddyPrefs}) + +# every attribute tag registered in the FEEDBAG__ATTRIBUTES table (the server rejects unregistered tags below 0x2710) +REGISTERED_ATTRIBUTES = frozenset({ + 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006A, 0x006B, 0x006D, 0x006F, + 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x00D0, 0x00D1, 0x00D2, 0x00D3, + 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, + 0x012C, 0x012D, 0x012E, 0x012F, 0x0130, 0x0131, 0x0132, 0x0133, 0x0134, 0x0135, 0x0136, 0x0137, + 0x0138, 0x0139, 0x013A, 0x013B, 0x013C, 0x013D, 0x013E, 0x013F, 0x0140, 0x0141, 0x0142, 0x0143, + 0x0145, 0x0150, 0x0151, 0x0152, 0x0153, 0x0154, 0x0158, 0x0159, 0x015F, 0x0167, 0x016E, +}) + @dataclass class FeedbagItem: @@ -52,13 +138,16 @@ class FeedbagItem: item_id: int class_id: int attributes: array[TLV] + # for buddies and permit/deny entries: the screen name (lowercased) the item stands for, whatever form `name` is in + key: Optional[str] - def __init__(self, name: str, group_id: int, item_id: int, class_id: int, attributes: Optional[array[TLV]] = None) -> None: + def __init__(self, name: str, group_id: int, item_id: int, class_id: int, attributes: Optional[array[TLV]] = None, key: Optional[str] = None) -> None: self.name = name self.group_id = group_id self.item_id = item_id self.class_id = class_id self.attributes = attributes or [] + self.key = key def marshal(self) -> bytes: buf = Buffer() @@ -71,81 +160,182 @@ class FeedbagItem: return buf.data -def get_items(context: OSCARContext) -> array[FeedbagItem]: +def _get_store(user: User) -> dict[str, Any]: + store = user.settings.get(SSI_KEY) + if not isinstance(store, dict): + store = {} + user.settings[SSI_KEY] = store + return store + +def _attrs_to_json(attrs: list[TLV]) -> list[list[Any]]: + return [[tlv.type, base64.b64encode(tlv.data).decode('ascii')] for tlv in attrs] + +def _attrs_from_json(attrs: list[list[Any]]) -> list[TLV]: + return [TLV(tag, base64.b64decode(data)) for tag, data in attrs] + +def _to_int(value: str, default: int = 1) -> int: + try: + return int(value) + except ValueError: + return default + +def _compress(name: str) -> str: + # "abc", "a b c" and "aBc" are the same name as far as the uniqueness rules go + return name.replace(' ', '').lower() + +def _alloc_id(preferred: int, used: set[int]) -> int: + # ids 0x8000 and above are reserved for the server + candidate = preferred if 0 < preferred <= MAX_ID else 1 + while candidate in used: + candidate = candidate + 1 if candidate < MAX_ID else 1 + used.add(candidate) + return candidate + +def _encode_order(ids: list[int]) -> bytes: + return b''.join(struct.pack('>H', ident) for ident in ids) + +def _decode_order(tlv: Optional[TLV]) -> list[int]: + if tlv is None: + return [] + return [struct.unpack('>H', tlv.data[i:i + 2])[0] for i in range(0, len(tlv.data) - 1, 2)] + +def _apply_order(stored: list[str], entries: list[tuple[str, int]]) -> list[int]: + # stored names first (in the client's order), then anything the client hasn't ordered yet + by_name = dict(entries) + ordered = [by_name[name] for name in dict.fromkeys(stored) if name in by_name] + return ordered + [ident for _, ident in entries if ident not in ordered] + +def _time_of(attrs: list[TLV]) -> int: + tlv = find_tlv(attrs, FeedbagAttributes.TimeT) + return struct.unpack('>L', tlv.data[:4])[0] if tlv is not None and len(tlv.data) >= 4 else 0 + +def _stamp_time(attrs: list[TLV], previous: int) -> list[TLV]: + # the server always overrides TIME_T, and keeps it strictly increasing + stamped = max(int(time.time()), previous + 1) + return [tlv for tlv in attrs if tlv.type != FeedbagAttributes.TimeT] + [TLV(FeedbagAttributes.TimeT, struct.pack('>L', stamped))] + + +def get_items(context: OSCARContext) -> list[FeedbagItem]: user = context.user detail = user.detail + store = _get_store(user) - contacts = list({ - *detail.get_contacts_by_list(ContactList.AL), - *detail.get_contacts_by_list(ContactList.FL) - }) + battrs: dict[str, list[list[Any]]] = store.get('battrs', {}) + gattrs: dict[str, list[list[Any]]] = store.get('gattrs', {}) + border: dict[str, list[str]] = store.get('border', {}) + misc: list[dict[str, Any]] = store.get('misc', []) + permits: set[str] = set(store.get('permits', [])) - group_feedbag = [] - group_order = b"" + # only contacts whose screen name is representable over OSCAR ever show up here + def valid(lst: ContactList) -> list[Contact]: + return sorted( + [ctc for ctc in detail.get_contacts_by_list(lst) if names.representable(ctc.head)], + key = lambda ctc: ctc.head.id, + ) - contact_feedbag = [] + fl = valid(ContactList.FL) + items: list[FeedbagItem] = [] + used_gids: set[int] = {0} + used_iids: set[int] = {int(entry['i']) for entry in misc} + group_entries: list[tuple[str, int]] = [] - for id, group in detail._groups_by_id.items(): - order = b"" - - for contact in contacts: - user = contact.head - - for grp in contact._groups.copy(): - if grp.id == id: - contact_feedbag.append(FeedbagItem(user.username, int(group.id), user.id, FeedbagClass.Buddy)) - order += struct.pack(">H", user.id) - - group_feedbag.append(FeedbagItem(group.name, int(group.id), 0x0000, FeedbagClass.Group, [ - TLV(FeedbagAttributes.Order, order) + def add_group(name: str, preferred: int, members: list[Contact]) -> None: + gkey = name.lower() + gid = _alloc_id(preferred, used_gids) + buddy_entries: list[tuple[str, int]] = [] + for ctc in members: + iid = _alloc_id(ctc.head.id, used_iids) + # each client gets its buddies by the name it knows them by (a UIN for ICQ, a screen name for AIM) + items.append(FeedbagItem( + names.name_for(context.bs, ctc.head), gid, iid, FeedbagClass.Buddy, + _attrs_from_json(battrs.get('{}:{}'.format(gkey, ctc.head.username.lower()), [])), + key = ctc.head.username.lower(), + )) + buddy_entries.append((ctc.head.username.lower(), iid)) + items.append(FeedbagItem(name, gid, 0, FeedbagClass.Group, [ + TLV(FeedbagAttributes.Order, _encode_order(_apply_order(border.get(gkey, []), buddy_entries))), + *_attrs_from_json(gattrs.get(gkey, [])), ])) + group_entries.append((gkey, gid)) - group_order += struct.pack(">H", int(group.id)) + for group in sorted(detail._groups_by_id.values(), key = lambda g: (len(g.id), g.id)): + add_group(group.name, _to_int(group.id), [ctc for ctc in fl if ctc.is_in_group_id(group.id)]) # deal with any ungrouped contacts left - if ungrouped_contacts := [contact for contact in contacts if not contact._groups]: - no_group_gid = len(group_feedbag) + 1 + if ungrouped := [ctc for ctc in fl if not ctc._groups]: + add_group("(No Group)", max(used_gids) + 1, ungrouped) - order = b"" + # AL-only contacts are explicit permits; buddies are implicitly allowed unless the client permitted them itself + for ctc in valid(ContactList.AL): + if ctc.lists & ContactList.FL and ctc.head.username.lower() not in permits: + continue + items.append(FeedbagItem(names.name_for(context.bs, ctc.head), 0, _alloc_id(ctc.head.id, used_iids), FeedbagClass.Permit, key = ctc.head.username.lower())) - for contact in ungrouped_contacts: - user = contact.head + for ctc in valid(ContactList.BL): + items.append(FeedbagItem(names.name_for(context.bs, ctc.head), 0, _alloc_id(ctc.head.id, used_iids), FeedbagClass.Deny, key = ctc.head.username.lower())) - contact_feedbag.append(FeedbagItem(user.username, no_group_gid, user.id, FeedbagClass.Buddy)) + # PD__SET_GROUP_PERMIT_MASK only touches the user's settings, so a stored PDINFO item picks the mask up here + stored_pd = user.settings.get(PD_KEY) + pd_mask_override = stored_pd.get('mask') if isinstance(stored_pd, dict) else None - order += struct.pack(">H", user.id) + for entry in misc: + attrs = _attrs_from_json(entry['a']) + if entry['c'] == FeedbagClass.PdInfo and pd_mask_override is not None: + attrs = [tlv for tlv in attrs if tlv.type != FeedbagAttributes.PdMask] + [ + TLV(FeedbagAttributes.PdMask, struct.pack('>L', int(pd_mask_override))) + ] + items.append(FeedbagItem(entry['n'], entry['g'], entry['i'], entry['c'], attrs)) - group_feedbag.append(FeedbagItem("(No Group)", no_group_gid, 0x0000, FeedbagClass.Group, [ - TLV(FeedbagAttributes.Order, order) - ])) + present = {entry['c'] for entry in misc} - return [ - FeedbagItem("", 0x0000, 0x0000, FeedbagClass.Group, [ - TLV(FeedbagAttributes.Order, group_order) - ]), - - FeedbagItem("", 0x0000, 0x0E63, FeedbagClass.PdInfo, [ - TLV(FeedbagAttributes.PdMode, struct.pack(">H", 0x0004)), + # defaults are synthesised until the client first stores its own copy + if FeedbagClass.PdInfo not in present: + pd = _aim_pd_mode(user) + if pd is not None: + pd_mode = pd['mode'] + pd_mask = int(pd.get('mask', 0xFFFFFFFF)) + else: + pd_mode = PDMode.DenySome if user.settings.get('BLP', 'AL') == 'AL' else PDMode.PermitOnList + pd_mask = 0xFFFFFFFF + items.append(FeedbagItem("", 0x0000, _alloc_id(0x0E63, used_iids), FeedbagClass.PdInfo, [ + TLV(FeedbagAttributes.PdMode, struct.pack(">B", pd_mode)), TLV(FeedbagAttributes.WirelessPdMode, struct.pack(">B", 0x0001)), TLV(FeedbagAttributes.WirelessIgnoreMode, struct.pack(">B", 0x0001)), TLV(FeedbagAttributes.FishPdMode, struct.pack(">B", 0x0001)), TLV(FeedbagAttributes.FishIgnoreMode, struct.pack(">B", 0x0001)), - TLV(FeedbagAttributes.PdMask, struct.pack(">H", 0xFFFF)) - ]), + TLV(FeedbagAttributes.PdMask, struct.pack(">L", pd_mask)), + TLV(FeedbagAttributes.PdFlags, struct.pack(">L", 0x00000001)), + ])) - FeedbagItem("", 0x0000, 0x4B1D, FeedbagClass.BuddyPrefs, [ + if FeedbagClass.BuddyPrefs not in present: + items.append(FeedbagItem("", 0x0000, _alloc_id(0x4B1D, used_iids), FeedbagClass.BuddyPrefs, [ TLV(FeedbagAttributes.BuddyPrefs, struct.pack(">L", 0x00000400)) - ]), + ])) - *group_feedbag, - *contact_feedbag - ] + items.append(FeedbagItem("", 0x0000, 0x0000, FeedbagClass.Group, [ + TLV(FeedbagAttributes.Order, _encode_order(_apply_order(store.get('gorder', []), group_entries))), + ])) + + # FEEDBAG__REPLY items are ordered by group id, then item id (root group first) + items.sort(key = lambda item: (item.group_id, item.item_id)) + return items def marshal_items(items: array[FeedbagItem]) -> bytes: return b"".join([item.marshal() for item in items]) +def _read_attributes(buf: Buffer) -> list[TLV]: + # tlvLBlock; read here so a trailing empty TLV (COLLAPSED, PENDING) isn't dropped + block = Buffer(buf.read_bytes(buf.read_u16())) + tlvs: list[TLV] = [] + while len(block) >= 4: + tag = block.read_u16() + length = block.read_u16() + tlvs.append(TLV(tag, block.read_bytes(length))) + return tlvs + + def unmarshal_items(item_bytes: bytes) -> array[FeedbagItem]: buf = Buffer(item_bytes) items = [] @@ -157,12 +347,16 @@ def unmarshal_items(item_bytes: bytes) -> array[FeedbagItem]: # Class ID = +2 = 8 # Attributes = +2 = 10 # - while len(buf) > 10: - name = buf.read_string_u16() - group_id = buf.read_u16() - item_id = buf.read_u16() - class_id = buf.read_u16() - attributes = buf.read_tlv_l_block() + while len(buf) >= 10: + try: + name = buf.read_string_u16() + group_id = buf.read_u16() + item_id = buf.read_u16() + class_id = buf.read_u16() + attributes = _read_attributes(buf) + except (struct.error, UnicodeDecodeError): + # a truncated or garbled item ends the list + break items.append(FeedbagItem(name, group_id, item_id, class_id, attributes)) @@ -185,13 +379,518 @@ def _resolve_group_backend_id(context: OSCARContext, client_group_id: int) -> Op mapping = context.bs.front_data.get("oscar0_group_id_map", {}) return mapping.get(client_group_id) +def _extended_info(version: int) -> bytes: + # what SNAC flag 0x8000 puts ahead of the body: a TLV block (u16 length) holding the feedbag version in TLV 0x01 + return struct.pack('>H', 6) + TLV(0x0001, struct.pack('>H', version)).marshal() + +def _string08(value: str) -> bytes: + encoded = value.encode('latin-1', errors = 'replace') + return struct.pack('>B', len(encoded)) + encoded + +def _string16(value: str) -> bytes: + encoded = value.encode('utf-8') + return struct.pack('>H', len(encoded)) + encoded + def build_buddy_added_notif(adder_username: str) -> SNACMessage: - msg = SNACMessage(0x0013, 0x001C) - username_bytes = adder_username.encode('ascii') - msg.write_u8(len(username_bytes)) - msg.write_bytes(username_bytes) + # FEEDBAG__BUDDY_ADDED: extended info (feedbag version 4), string08 who added you, u16 0 + msg = SNACMessage(0x0013, 0x001C, 0x8000) + msg.write_bytes(_extended_info(4)) + msg.write_bytes(_string08(adder_username)) + msg.write_u16(0) return msg + +def send_feedbag_error(client: OSCARClient, request_id: int, code: int, *, subcode: Optional[int] = None) -> None: + # SNAC(13,01): u16 error code, then an optional TLV(0x08) holding a u16 subcode + msg = SNACMessage(0x0013, 0x0001, 0x0000, request_id) + msg.write_u16(code) + if subcode is not None: + msg.write_tlv(TLV(0x0008, struct.pack('>H', subcode))) + client.send_snac(msg) + +def _send_feedbag_reply(client: OSCARClient, request_id: int, items: list[FeedbagItem], last_update: int) -> None: + # a feedbag too big for one SNAC is split with flag 0x0001 on every part but the last, which alone carries the timestamp + chunks: list[list[FeedbagItem]] = [[]] + size = 0 + for item in items: + item_len = len(item.marshal()) + if size + item_len > MAX_REPLY_ITEM_BYTES and chunks[-1]: + chunks.append([]) + size = 0 + chunks[-1].append(item) + size += item_len + for index, chunk in enumerate(chunks): + last = (index == len(chunks) - 1) + msg = SNACMessage(0x0013, 0x0006, 0x0000 if last else 0x0001, request_id) + msg.write_u8(0) # feedbag protocol version - always 0 + msg.write_u16(len(chunk)) # no. of feedbag items + msg.write_bytes(marshal_items(chunk)) # list of feedbag items + if last: + msg.write_u32(last_update) # feedbag last change time - TODO: should pull from db + client.send_snac(msg) + +def _sync_modified(context: OSCARContext, items: list[FeedbagItem]) -> int: + # the last-change time only moves when the marshalled feedbag actually changes (including changes made from other frontends) + user = context.user + store = _get_store(user) + digest = hashlib.md5(marshal_items(items)).hexdigest() + last_update = int(store.get('ts', 0)) + if store.get('digest') != digest or not last_update: + last_update = max(int(time.time()), last_update + 1) + store['ts'] = last_update + store['digest'] = digest + context.backend._mark_modified(user) + return last_update + +def _push_presence(client: OSCARClient, context: OSCARContext, name: str) -> None: + # the server never pushed a freshly added buddy's presence to whoever added them, so they stayed offline until a relog + contact_uuid = names.resolve(context.backend, name) + contact = context.user.detail.contacts.get(contact_uuid) if contact_uuid is not None else None + if contact is None or not context.bs.front_data.get('oscar0_ready'): + return + push_presence(context.bs, contact.head) + +def _key_name(context: OSCARContext, name: str) -> str: + # the screen name a client's name for someone stands for, which is what stored buddy attributes are filed under + user = names.resolve_user(context.backend, name) + return user.username.lower() if user is not None else names.normalize(name) + + +def _validate_item(item: FeedbagItem, *, check_attributes: bool, allow_pending: bool = False) -> Optional[FeedbagStatus]: + if item.group_id > MAX_ID or item.item_id > MAX_ID or len(item.name) > MAX_ITEM_NAME_LEN: + return FeedbagStatus.BadRequest + if item.class_id < MIN_CLIENT_CLASS and item.class_id not in KNOWN_CLASSES: + return FeedbagStatus.BadRequest + if item.class_id == FeedbagClass.Group: + if item.item_id != 0 or (item.group_id == 0 and item.name): + return FeedbagStatus.BadRequest + elif item.item_id == 0: + return FeedbagStatus.BadRequest + if item.class_id == FeedbagClass.Buddy and item.group_id == 0: + return FeedbagStatus.BadRequest + if item.class_id in ROOT_ONLY_CLASSES and item.group_id != 0: + return FeedbagStatus.BadRequest + if item.class_id in SINGLE_ITEM_CLASSES and item.name: + return FeedbagStatus.BadRequest + if check_attributes: + if len(marshal_tlvs(item.attributes)) > MAX_ITEM_ATTRS_SIZE: + return FeedbagStatus.BadRequest + for tlv in item.attributes: + if tlv.type < 0x0064: + return FeedbagStatus.BadRequest + if tlv.type <= 0x00C7: + # server-only range; clients may only insert PENDING (and send TIME_T on DATE_TIME, which gets overridden) + if tlv.type == FeedbagAttributes.Pending and allow_pending: + continue + if tlv.type == FeedbagAttributes.TimeT and item.class_id == FeedbagClass.DateTime: + continue + return FeedbagStatus.BadRequest + if tlv.type <= 0x270F and tlv.type not in REGISTERED_ATTRIBUTES: + return FeedbagStatus.BadRequest + return None + +def _resolve_group(context: OSCARContext, client_group_id: int) -> Optional[Group]: + detail = context.user.detail + backend_id = _resolve_group_backend_id(context, client_group_id) + return detail._groups_by_id.get(backend_id) if backend_id is not None else None + +def _generated_buddy_ids(context: OSCARContext, group_name: str) -> dict[int, str]: + items = get_items(context) + gid = next((i.group_id for i in items if i.class_id == FeedbagClass.Group and i.group_id != 0 and i.name == group_name), None) + return {i.item_id: (i.key or i.name.lower()) for i in items if i.class_id == FeedbagClass.Buddy and i.group_id == gid} + +def _store_order(context: OSCARContext, item: FeedbagItem) -> None: + # the client's ORDER holds its own ids; translate them to names so they survive id regeneration + order_tlv = find_tlv(item.attributes, FeedbagAttributes.Order) + if order_tlv is None: + return + detail = context.user.detail + store = _get_store(context.user) + ids = _decode_order(order_tlv) + if item.group_id == 0: + names = [] + for cid in ids: + backend_id = _resolve_group_backend_id(context, cid) + group = detail._groups_by_id.get(backend_id) if backend_id is not None else None + if group is not None: + names.append(group.name.lower()) + store['gorder'] = names + return + group = _resolve_group(context, item.group_id) + gname = group.name if group is not None else ("(No Group)" if item.name.lower() == '(no group)' else None) + if gname is None: + return + known = _generated_buddy_ids(context, gname) + iid_map = context.bs.front_data.get('oscar0_iid_map', {}) + names = [] + for iid in ids: + name = iid_map.get((item.group_id, iid)) or known.get(iid) + if name: + names.append(name) + store.setdefault('border', {})[gname.lower()] = names + +def _rename_group_keys(store: dict[str, Any], old: str, new: str) -> None: + for section in ('gattrs', 'border'): + entries = store.get(section, {}) + if old in entries: + entries[new] = entries.pop(old) + battrs = store.get('battrs', {}) + for key in [key for key in battrs if key.startswith(old + ':')]: + battrs[new + ':' + key[len(old) + 1:]] = battrs.pop(key) + store['gorder'] = [new if name == old else name for name in store.get('gorder', [])] + +def _drop_group_keys(store: dict[str, Any], key: str) -> None: + store.get('gattrs', {}).pop(key, None) + store.get('border', {}).pop(key, None) + battrs = store.get('battrs', {}) + for stale in [stale for stale in battrs if stale.startswith(key + ':')]: + battrs.pop(stale) + store['gorder'] = [name for name in store.get('gorder', []) if name != key] + +def _apply_pd_mode(context: OSCARContext, attrs: list[TLV]) -> None: + # PD_MODE is a single byte and PD_MASK a dword; what they mean for the permit/deny rules is the PD foodgroup's business + mode_tlv = find_tlv(attrs, FeedbagAttributes.PdMode) + mask_tlv = find_tlv(attrs, FeedbagAttributes.PdMask) + mode = mode_tlv.data[-1] if mode_tlv is not None and mode_tlv.data else None + mask = struct.unpack('>L', mask_tlv.data)[0] if mask_tlv is not None and len(mask_tlv.data) == 4 else None + apply_pd_info(context, mode, mask) + + +def _insert_group(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + bs = context.bs + detail = context.user.detail + store = _get_store(context.user) + + if item.group_id == 0 and item.item_id == 0: + _store_order(context, item) + return FeedbagStatus.Success + if not item.name: + return FeedbagStatus.BadRequest + if item.name.lower() == '(no group)' or item.name.lower() in {g.name.lower() for g in detail._groups_by_id.values()}: + return FeedbagStatus.AlreadyExists + if str(item.group_id) in detail._groups_by_id: + return FeedbagStatus.AlreadyExists + if len(detail._groups_by_id) >= MAX_GROUPS: + return FeedbagStatus.OverLimit + + try: + group = bs.me_group_add(item.name) + except error.GroupAlreadyExists: + return FeedbagStatus.AlreadyExists + except Exception: + return FeedbagStatus.BadRequest + + bs.front_data.setdefault("oscar0_group_id_map", {})[item.group_id] = group.id + logger.info("[Client] Added group:", item.name) + + attrs = [tlv for tlv in item.attributes if tlv.type != FeedbagAttributes.Order] + if attrs: + store.setdefault('gattrs', {})[group.name.lower()] = _attrs_to_json(attrs) + _store_order(context, item) + + # buddies the client inserted before this group existed (the wiki's recommended insert order) join it now + for contact_uuid, username, buddy_attrs in bs.front_data.get('oscar0_pending_buddies', {}).pop(item.group_id, []): + try: + bs.me_group_contact_add(group.id, contact_uuid) + except Exception: + continue + if buddy_attrs: + store.setdefault('battrs', {})['{}:{}'.format(group.name.lower(), username)] = buddy_attrs + return FeedbagStatus.Success + +def _insert_buddy(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + bs = context.bs + detail = context.user.detail + store = _get_store(context.user) + + if not item.name or not names.valid_name(item.name): + return FeedbagStatus.BadLoginID + contact_user = names.resolve_user(context.backend, item.name) + if contact_user is None or contact_user is context.user: + logger.info("[Client] Unknown buddy:", item.name) + return FeedbagStatus.BadLoginID + contact_uuid = contact_user.uuid + key = contact_user.username.lower() + + pending = find_tlv(item.attributes, FeedbagAttributes.Pending) is not None + if icq.requires_authorization(contact_user, context.user): + if not pending: + if names.is_icq_session(bs): + return FeedbagStatus.AuthRequired + item.attributes = list(item.attributes) + [TLV(FeedbagAttributes.Pending)] + request_authorization(context.backend, context.user, contact_user, '') + elif pending: + # authorization has been granted since: the buddy goes on as an ordinary one + item.attributes = [tlv for tlv in item.attributes if tlv.type != FeedbagAttributes.Pending] + if names.is_icq_session(bs) and names.uin_of(contact_user) is None: + # AIM can't take part in authorization, so an ICQ user adding an AIM user authorizes them back + icq.record_preauth(context.user, contact_uuid) + + contact = detail.contacts.get(contact_uuid) + is_buddy = contact is not None and bool(contact.lists & ContactList.FL) + group = _resolve_group(context, item.group_id) + + if not is_buddy and len(detail.get_contacts_by_list(ContactList.FL)) >= MAX_BUDDIES: + return FeedbagStatus.OverLimit + if group is not None: + if is_buddy and contact.is_in_group_id(group.id): + return FeedbagStatus.AlreadyExists + if len([c for c in detail.get_contacts_by_list(ContactList.FL) if c.is_in_group_id(group.id)]) >= MAX_BUDDIES_PER_GROUP: + return FeedbagStatus.OverLimit + + attrs = _attrs_to_json(list(item.attributes)) + battr_key = '{}:{}'.format(group.name.lower(), key) if group is not None else None + try: + # the attributes go in first, so a PENDING_AUTH buddy is already marked when the add tells the other side + if battr_key is not None and attrs: + store.setdefault('battrs', {})[battr_key] = attrs + if not is_buddy: + bs.me_contact_add(contact_uuid, ContactList.FL | ContactList.AL) + if group is not None: + bs.me_group_contact_add(group.id, contact_uuid) + else: + bs.front_data.setdefault('oscar0_pending_buddies', {}).setdefault(item.group_id, []).append((contact_uuid, key, attrs)) + except error.ContactListIsFull: + if battr_key is not None: + store.get('battrs', {}).pop(battr_key, None) + return FeedbagStatus.OverLimit + except Exception: + if battr_key is not None: + store.get('battrs', {}).pop(battr_key, None) + return FeedbagStatus.BadRequest + + bs.front_data.setdefault('oscar0_iid_map', {})[(item.group_id, item.item_id)] = key + # whatever this client called the buddy (a UIN, a differently spaced screen name) is what it'll hear about them as + names.remember(bs, contact_user, item.name) + names.store_alias(bs, contact_user, item.name) + logger.info("[Client] Added buddy:", item.name) + return FeedbagStatus.Success + +def _insert_list_entry(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + is_permit = (item.class_id == FeedbagClass.Permit) + status = FeedbagStatus(int(pd_add(context, item.name, permit = is_permit))) + if status == FeedbagStatus.Success: + logger.info("[Client] Added {} entry:".format('permit' if is_permit else 'deny'), item.name) + return status + +def _insert_generic(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + store = _get_store(context.user) + misc: list[dict[str, Any]] = store.setdefault('misc', []) + + # (groupId, itemId) is unique across everything in the feedbag + if any(i.group_id == item.group_id and i.item_id == item.item_id and i.class_id != item.class_id for i in get_items(context)): + return FeedbagStatus.AlreadyExists + same_class = [entry for entry in misc if entry['c'] == item.class_id] + if item.class_id in SINGLE_ITEM_CLASSES and same_class: + return FeedbagStatus.OverLimit + if item.group_id == 0 and any(_compress(entry['n']) == _compress(item.name) for entry in same_class): + return FeedbagStatus.AlreadyExists + if item.class_id >= MIN_CLIENT_CLASS and len([entry for entry in misc if entry['c'] >= MIN_CLIENT_CLASS]) >= MAX_CLIENT_ITEMS: + return FeedbagStatus.OverLimit + + attrs = list(item.attributes) + if item.class_id == FeedbagClass.DateTime: + attrs = _stamp_time(attrs, 0) + misc.append({ 'n': item.name, 'g': item.group_id, 'i': item.item_id, 'c': int(item.class_id), 'a': _attrs_to_json(attrs) }) + + if item.class_id == FeedbagClass.PdInfo: + _apply_pd_mode(context, attrs) + logger.info("[Client] Stored item of class", hex(item.class_id)) + return FeedbagStatus.Success + + +def _update_group(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + bs = context.bs + detail = context.user.detail + store = _get_store(context.user) + + if item.group_id == 0 and item.item_id == 0: + _store_order(context, item) + return FeedbagStatus.Success + + group = _resolve_group(context, item.group_id) + if group is None: + # the synthesised "(No Group)" group has no backend group, but clients still reorder it + if item.name.lower() == '(no group)': + _store_order(context, item) + return FeedbagStatus.Success + return FeedbagStatus.NotFound + + if item.name and item.name != group.name: + if item.name.lower() == '(no group)' or any(g.name.lower() == item.name.lower() and g.id != group.id for g in detail._groups_by_id.values()): + return FeedbagStatus.AlreadyExists + old_key = group.name.lower() + try: + bs.me_group_edit(group.id, new_name = item.name) + except Exception: + return FeedbagStatus.BadRequest + _rename_group_keys(store, old_key, item.name.lower()) + logger.info("[Client] Renamed group to:", item.name) + + attrs = [tlv for tlv in item.attributes if tlv.type != FeedbagAttributes.Order] + gattrs = store.setdefault('gattrs', {}) + if attrs: + gattrs[group.name.lower()] = _attrs_to_json(attrs) + else: + gattrs.pop(group.name.lower(), None) + _store_order(context, item) + return FeedbagStatus.Success + +def _update_buddy(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + detail = context.user.detail + store = _get_store(context.user) + + if not item.name or not names.valid_name(item.name): + return FeedbagStatus.BadLoginID + contact_uuid = names.resolve(context.backend, item.name) + if contact_uuid is None: + return FeedbagStatus.BadLoginID + + group = _resolve_group(context, item.group_id) + contact = detail.contacts.get(contact_uuid) + if contact is None or not contact.lists & ContactList.FL: + return FeedbagStatus.NotFound + if group is not None: + if not contact.is_in_group_id(group.id): + return FeedbagStatus.NotFound + gkey = group.name.lower() + elif contact._groups: + return FeedbagStatus.NotFound + else: + gkey = '(no group)' + + key = '{}:{}'.format(gkey, contact.head.username.lower()) + battrs = store.setdefault('battrs', {}) + had_pending = any(tag == FeedbagAttributes.Pending for tag, _ in battrs.get(key, [])) + invalid = _validate_item(item, check_attributes = True, allow_pending = had_pending) + if invalid is not None: + return invalid + + # the client sends every attribute it wants to keep, so this replaces the stored set + if item.attributes: + battrs[key] = _attrs_to_json(list(item.attributes)) + else: + battrs.pop(key, None) + logger.info("[Client] Updated buddy:", item.name) + return FeedbagStatus.Success + +def _update_list_entry(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + detail = context.user.detail + lst = ContactList.AL if item.class_id == FeedbagClass.Permit else ContactList.BL + + if not item.name or not names.valid_name(item.name): + return FeedbagStatus.BadLoginID + contact_uuid = names.resolve(context.backend, item.name) + if contact_uuid is None: + return FeedbagStatus.BadLoginID + + contact = detail.contacts.get(contact_uuid) + if contact is None or not contact.lists & lst: + return FeedbagStatus.NotFound + return FeedbagStatus.Success + +def _update_generic(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + store = _get_store(context.user) + misc: list[dict[str, Any]] = store.setdefault('misc', []) + attrs = list(item.attributes) + + for entry in misc: + if entry['g'] == item.group_id and entry['i'] == item.item_id and entry['c'] == item.class_id: + if item.class_id == FeedbagClass.DateTime: + attrs = _stamp_time(attrs, _time_of(_attrs_from_json(entry['a']))) + entry['n'] = item.name + entry['a'] = _attrs_to_json(attrs) + if item.class_id == FeedbagClass.PdInfo: + _apply_pd_mode(context, attrs) + return FeedbagStatus.Success + + # the synthesised PDINFO/BUDDY_PREFS defaults only become stored items once the client first updates them + if item.class_id in SINGLE_ITEM_CLASSES and not any(entry['c'] == item.class_id for entry in misc): + misc.append({ 'n': item.name, 'g': item.group_id, 'i': item.item_id, 'c': int(item.class_id), 'a': _attrs_to_json(attrs) }) + if item.class_id == FeedbagClass.PdInfo: + _apply_pd_mode(context, attrs) + return FeedbagStatus.Success + return FeedbagStatus.NotFound + + +def _delete_group(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + bs = context.bs + store = _get_store(context.user) + + # the root group is never deleted + if item.group_id == 0 and item.item_id == 0: + return FeedbagStatus.BadRequest + group = _resolve_group(context, item.group_id) + if group is None: + return FeedbagStatus.NotFound + + try: + bs.me_group_remove(group.id) + except Exception: + return FeedbagStatus.NotFound + + mapping = bs.front_data.get("oscar0_group_id_map", {}) + for k in [k for k, v in mapping.items() if v == group.id]: + del mapping[k] + _drop_group_keys(store, group.name.lower()) + logger.info("[Client] Removed group:", item.name) + return FeedbagStatus.Success + +def _delete_buddy(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + bs = context.bs + detail = context.user.detail + store = _get_store(context.user) + + if not item.name or not names.valid_name(item.name): + return FeedbagStatus.BadLoginID + contact_uuid = names.resolve(context.backend, item.name) + if contact_uuid is None: + return FeedbagStatus.BadLoginID + + contact = detail.contacts.get(contact_uuid) + if contact is None or not (contact.lists & ContactList.FL): + return FeedbagStatus.NotFound + group = _resolve_group(context, item.group_id) + if group is not None and not contact.is_in_group_id(group.id): + return FeedbagStatus.NotFound + if group is None and contact._groups: + return FeedbagStatus.NotFound + + try: + if group is not None: + bs.me_group_contact_remove(group.id, contact_uuid) + store.get('battrs', {}).pop('{}:{}'.format(group.name.lower() if group is not None else '(no group)', contact.head.username.lower()), None) + if not contact._groups: + bs.me_contact_remove(contact_uuid, ContactList.FL) + names.drop_alias(bs, contact_uuid) + # AL was added alongside FL on insert; drop it unless the client also permitted this name explicitly + if contact.head.username.lower() not in store.get('permits', []): + try: + bs.me_contact_remove(contact_uuid, ContactList.AL) + except Exception: + pass + except Exception: + return FeedbagStatus.BadRequest + + logger.info("[Client] Removed buddy:", item.name) + return FeedbagStatus.Success + +def _delete_list_entry(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + is_permit = (item.class_id == FeedbagClass.Permit) + status = FeedbagStatus(int(pd_remove(context, item.name, permit = is_permit))) + if status == FeedbagStatus.Success: + logger.info("[Client] Removed {} entry:".format('permit' if is_permit else 'deny'), item.name) + return status + +def _delete_generic(logger: Logger, context: OSCARContext, item: FeedbagItem) -> FeedbagStatus: + misc: list[dict[str, Any]] = _get_store(context.user).get('misc', []) + for entry in misc: + if entry['g'] == item.group_id and entry['i'] == item.item_id and entry['c'] == item.class_id: + misc.remove(entry) + return FeedbagStatus.Success + return FeedbagStatus.NotFound + + @Foodgroup(0x0013) class FeedbagFoodgroup: logger: Logger @@ -256,16 +955,17 @@ class FeedbagFoodgroup: def query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: self.logger.info("[Client] FEEDBAG__QUERY") - items = get_items(context) - - response_msg = SNACMessage(0x0013, 0x0006, 0x0000, message.request_id) - response_msg.write_u8(0) # feedbag protocol version - always 0 - response_msg.write_u16(len(items)) # no. of feedbag items - response_msg.write_bytes(marshal_items(items)) # list of feedbag items - response_msg.write_u32(int(time.time())) # feedbag last change time - TODO: should pull from db + try: + items = get_items(context) + last_update = _sync_modified(context, items) + except Exception as ex: + self.logger.error(ex) + self.logger.info("[Server] FEEDBAG__ERR") + send_feedbag_error(client, message.request_id, FeedbagError.BuddyListUnavailable) + return self.logger.info("[Server] FEEDBAG__REPLY") - client.send_snac(response_msg) + _send_feedbag_reply(client, message.request_id, items, last_update) @Subgroup(0x0005) def query_if_modified(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: @@ -281,38 +981,44 @@ class FeedbagFoodgroup: self.logger.info("[Client] Cached feedbag timestamp:", cached_feedbag_timestamp) self.logger.info("[Client] Cached feedbag items num:", cached_feedbag_num_items) - current_items = get_items(context) + try: + current_items = get_items(context) + last_update = _sync_modified(context, current_items) + except Exception as ex: + self.logger.error(ex) + self.logger.info("[Server] FEEDBAG__ERR") + send_feedbag_error(client, message.request_id, FeedbagError.BuddyListUnavailable) + return - if len(current_items) == cached_feedbag_num_items: + # both the modification time and the item count have to match for the client's copy to count as current + if cached_feedbag_timestamp == last_update and cached_feedbag_num_items == len(current_items): response_msg = SNACMessage(0x0013, 0x000F, 0x0000, message.request_id) - response_msg.write_u32(cached_feedbag_timestamp) - response_msg.write_u16(cached_feedbag_num_items) + response_msg.write_u32(last_update) + response_msg.write_u16(len(current_items)) self.logger.info("[Server] FEEDBAG__REPLY_NOT_MODIFIED") client.send_snac(response_msg) else: - self.query(client, context, message) + self.logger.info("[Server] FEEDBAG__REPLY") + _send_feedbag_reply(client, message.request_id, current_items, last_update) @Subgroup(0x0007) def use(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: self.logger.info("[Client] FEEDBAG__USE") + bs = context.bs + # from here on the stored buddy list is the one this client runs on + bs.front_data['oscar0_feedbag'] = True + _restore_bart_icon(context) + # set our status to Online - context.bs.me_update({ - "substatus": Substatus.Online - }) + # (that's done at OSERVICE__CLIENT_READY, which every client sends: AIM sends this before it, ICQ 5 after, so ICQ 5 + # would otherwise come online before its privacy settings were in use) # notify the client if any contacts are online - user = context.user - detail = user.detail - - contacts = list({ - *detail.get_contacts_by_list(ContactList.AL) - }) - - for contact in contacts: - if not contact.status.is_offlineish(): - client.send_snac(build_presence_notif(contact)) + # cached statuses can lag behind, so recompute before deciding who is online + if bs.front_data.get('oscar0_ready'): + push_buddy_list(bs) # stubs because I cba to implement more of feedbag rn @Subgroup(0x0011) @@ -328,260 +1034,390 @@ class FeedbagFoodgroup: self.logger.info("[Client] FEEDBAG__INSERT_ITEM") bs = context.bs - user = context.user - detail = user.detail - items = unmarshal_items(message.data) + before = bs.me_visibility_snapshot() statuses = [] + added = [] + bart_items = [] - for item in items: - if item.class_id == FeedbagClass.Group: - if item.group_id == 0 and item.item_id == 0: - statuses.append(FeedbagStatus.Success) - continue - - existing_names = {g.name.lower() for g in detail._groups_by_id.values()} - if item.name.lower() in existing_names: - statuses.append(FeedbagStatus.AlreadyExists) - continue - - try: - group = bs.me_group_add(item.name) - mapping = bs.front_data.setdefault("oscar0_group_id_map", {}) - mapping[item.group_id] = group.id - self.logger.info("[Client] Added group:", item.name) - statuses.append(FeedbagStatus.Success) - except Exception: - statuses.append(FeedbagStatus.BadRequest) - + for item in unmarshal_items(message.data): + invalid = _validate_item(item, check_attributes = True, allow_pending = True) + if invalid is not None: + statuses.append(invalid) + elif item.class_id == FeedbagClass.Group: + statuses.append(_insert_group(self.logger, context, item)) elif item.class_id == FeedbagClass.Buddy: - if not item.name: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact_uuid = context.backend.util_get_uuid_from_username(item.name) - if contact_uuid is None: - self.logger.info("[Client] Unknown buddy:", item.name) - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact = detail.contacts.get(contact_uuid) - if contact is not None and contact.lists & ContactList.FL: - statuses.append(FeedbagStatus.AlreadyExists) - continue - - try: - bs.me_contact_add(contact_uuid, ContactList.FL | ContactList.AL) - - if item.group_id != 0: - backend_group_id = _resolve_group_backend_id(context, item.group_id) - if backend_group_id is not None: - bs.me_group_contact_add(backend_group_id, contact_uuid) - - self.logger.info("[Client] Added buddy:", item.name) - statuses.append(FeedbagStatus.Success) - except error.ContactListIsFull: - statuses.append(FeedbagStatus.OverLimit) - except Exception: - statuses.append(FeedbagStatus.BadRequest) - - elif item.class_id == FeedbagClass.Deny: - if not item.name: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact_uuid = context.backend.util_get_uuid_from_username(item.name) - if contact_uuid is None: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact = detail.contacts.get(contact_uuid) - if contact is not None and contact.lists & ContactList.BL: - statuses.append(FeedbagStatus.AlreadyExists) - continue - - try: - bs.me_contact_add(contact_uuid, ContactList.BL) - self.logger.info("[Client] Added deny entry:", item.name) - statuses.append(FeedbagStatus.Success) - except Exception: - statuses.append(FeedbagStatus.BadRequest) - - elif item.class_id == FeedbagClass.Permit: - if not item.name: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact_uuid = context.backend.util_get_uuid_from_username(item.name) - if contact_uuid is None: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact = detail.contacts.get(contact_uuid) - if contact is not None and contact.lists & ContactList.AL: - statuses.append(FeedbagStatus.AlreadyExists) - continue - - try: - bs.me_contact_add(contact_uuid, ContactList.AL) - self.logger.info("[Client] Added permit entry:", item.name) - statuses.append(FeedbagStatus.Success) - except Exception: - statuses.append(FeedbagStatus.BadRequest) - + status = _insert_buddy(self.logger, context, item) + statuses.append(status) + if status == FeedbagStatus.Success: + added.append(item.name) + elif item.class_id in (FeedbagClass.Permit, FeedbagClass.Deny): + statuses.append(_insert_list_entry(self.logger, context, item)) else: - statuses.append(FeedbagStatus.Success) + status = _insert_generic(self.logger, context, item) + statuses.append(status) + if status == FeedbagStatus.Success and item.class_id == FeedbagClass.Bart: + bart_items.append(item) + + context.backend._mark_modified(context.user) + bs.me_visibility_changed(before) self.logger.info("[Server] FEEDBAG__STATUS") _send_feedbag_status(client, message.request_id, statuses) + # the buddy has to be in the client's list before its arrival means anything, so this goes after the STATUS + for name in added: + _push_presence(client, context, name) + for item in bart_items: + _set_bart_item(client, context, item) + @Subgroup(0x0009) def update_item(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: self.logger.info("[Client] FEEDBAG__UPDATE_ITEM") bs = context.bs - user = context.user - detail = user.detail - items = unmarshal_items(message.data) + before = bs.me_visibility_snapshot() statuses = [] + bart_items = [] - for item in items: - if item.class_id == FeedbagClass.Group: - if item.group_id == 0 and item.item_id == 0: - statuses.append(FeedbagStatus.Success) - continue - - backend_group_id = _resolve_group_backend_id(context, item.group_id) - if backend_group_id is None: - statuses.append(FeedbagStatus.NotFound) - continue - - group = detail._groups_by_id.get(backend_group_id) - if group is None: - statuses.append(FeedbagStatus.NotFound) - continue - - if item.name and item.name != group.name: - try: - bs.me_group_edit(backend_group_id, new_name=item.name) - self.logger.info("[Client] Renamed group to:", item.name) - statuses.append(FeedbagStatus.Success) - except Exception: - statuses.append(FeedbagStatus.BadRequest) - else: - statuses.append(FeedbagStatus.Success) - + for item in unmarshal_items(message.data): + # buddies validate their own attributes, since whether PENDING is allowed depends on what is already stored + invalid = _validate_item(item, check_attributes = item.class_id != FeedbagClass.Buddy) + if invalid is not None: + statuses.append(invalid) + elif item.class_id == FeedbagClass.Group: + statuses.append(_update_group(self.logger, context, item)) + elif item.class_id == FeedbagClass.Buddy: + statuses.append(_update_buddy(self.logger, context, item)) + elif item.class_id in (FeedbagClass.Permit, FeedbagClass.Deny): + statuses.append(_update_list_entry(self.logger, context, item)) else: - statuses.append(FeedbagStatus.Success) + status = _update_generic(self.logger, context, item) + statuses.append(status) + if status == FeedbagStatus.Success and item.class_id == FeedbagClass.Bart: + bart_items.append(item) + + context.backend._mark_modified(context.user) + bs.me_visibility_changed(before) self.logger.info("[Server] FEEDBAG__STATUS") _send_feedbag_status(client, message.request_id, statuses) + for item in bart_items: + _set_bart_item(client, context, item) + @Subgroup(0x000A) def delete_item(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: self.logger.info("[Client] FEEDBAG__DELETE_ITEM") bs = context.bs - user = context.user - detail = user.detail - items = unmarshal_items(message.data) + before = bs.me_visibility_snapshot() statuses = [] - for item in items: - if item.class_id == FeedbagClass.Group: - if item.group_id == 0 and item.item_id == 0: - statuses.append(FeedbagStatus.BadRequest) - continue - - backend_group_id = _resolve_group_backend_id(context, item.group_id) - if backend_group_id is None: - statuses.append(FeedbagStatus.NotFound) - continue - - try: - bs.me_group_remove(backend_group_id) - mapping = bs.front_data.get("oscar0_group_id_map", {}) - for k in [k for k, v in mapping.items() if v == backend_group_id]: - del mapping[k] - self.logger.info("[Client] Removed group:", item.name) - statuses.append(FeedbagStatus.Success) - except Exception: - statuses.append(FeedbagStatus.NotFound) - + for item in unmarshal_items(message.data): + invalid = _validate_item(item, check_attributes = False) + if invalid is not None: + statuses.append(invalid) + elif item.class_id == FeedbagClass.Group: + statuses.append(_delete_group(self.logger, context, item)) elif item.class_id == FeedbagClass.Buddy: - if not item.name: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact_uuid = context.backend.util_get_uuid_from_username(item.name) - if contact_uuid is None: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact = detail.contacts.get(contact_uuid) - if contact is None or not (contact.lists & ContactList.FL): - statuses.append(FeedbagStatus.NotFound) - continue - - try: - if item.group_id != 0: - backend_group_id = _resolve_group_backend_id(context, item.group_id) - if backend_group_id is not None: - bs.me_group_contact_remove(backend_group_id, contact_uuid) - - if not contact._groups: - bs.me_contact_remove(contact_uuid, ContactList.FL) - - self.logger.info("[Client] Removed buddy:", item.name) - statuses.append(FeedbagStatus.Success) - except Exception: - statuses.append(FeedbagStatus.BadRequest) - - elif item.class_id == FeedbagClass.Deny: - if not item.name: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact_uuid = context.backend.util_get_uuid_from_username(item.name) - if contact_uuid is None: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact = detail.contacts.get(contact_uuid) - if contact is None or not (contact.lists & ContactList.BL): - statuses.append(FeedbagStatus.NotFound) - continue - - try: - bs.me_contact_remove(contact_uuid, ContactList.BL) - self.logger.info("[Client] Removed deny entry:", item.name) - statuses.append(FeedbagStatus.Success) - except Exception: - statuses.append(FeedbagStatus.BadRequest) - - elif item.class_id == FeedbagClass.Permit: - if not item.name: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact_uuid = context.backend.util_get_uuid_from_username(item.name) - if contact_uuid is None: - statuses.append(FeedbagStatus.BadLoginID) - continue - - contact = detail.contacts.get(contact_uuid) - if contact is None or not (contact.lists & ContactList.AL): - statuses.append(FeedbagStatus.NotFound) - continue - - try: - bs.me_contact_remove(contact_uuid, ContactList.AL) - self.logger.info("[Client] Removed permit entry:", item.name) - statuses.append(FeedbagStatus.Success) - except Exception: - statuses.append(FeedbagStatus.BadRequest) - + statuses.append(_delete_buddy(self.logger, context, item)) + elif item.class_id in (FeedbagClass.Permit, FeedbagClass.Deny): + statuses.append(_delete_list_entry(self.logger, context, item)) else: - statuses.append(FeedbagStatus.Success) + status = _delete_generic(self.logger, context, item) + statuses.append(status) + # without its BART item the icon is gone + if status == FeedbagStatus.Success and item.class_id == FeedbagClass.Bart and item.name in ('0', '1'): + if bs.front_data.pop('oscar0_bart_icon', None) is not None: + _announce_icon(client, context) + + context.backend._mark_modified(context.user) + bs.me_visibility_changed(before) self.logger.info("[Server] FEEDBAG__STATUS") - _send_feedbag_status(client, message.request_id, statuses) \ No newline at end of file + _send_feedbag_status(client, message.request_id, statuses) + + @Subgroup(0x0014) + def pre_authorize_buddy(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: + # FEEDBAG__PRE_AUTHORIZE_BUDDY: string08 who, string16 message, u16 flags; they may add us without asking + self.logger.info("[Client] FEEDBAG__PRE_AUTHORIZE_BUDDY") + name = message.read_bytes(message.read_u8()).decode('latin-1') + text = _read_string16(message) + target = names.resolve_user(context.backend, name) + if target is None: + return + if target is context.user: + client.ctrl.send_snac_error(0x0013, message.request_id, 0x0008) + return + grant_authorization(context.backend, context.user, target, text, pre = True) + + @Subgroup(0x0018) + def request_authorize_to_host(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: + # FEEDBAG__REQUEST_AUTHORIZE_TO_HOST: string08 who, string16 reason, u16 unknown + self.logger.info("[Client] FEEDBAG__REQUEST_AUTHORIZE_TO_HOST") + name = message.read_bytes(message.read_u8()).decode('latin-1') + reason = _read_string16(message) + target = names.resolve_user(context.backend, name) + if target is None or target is context.user: + return + names.remember(context.bs, target, name) + request_authorization(context.backend, context.user, target, reason) + + @Subgroup(0x001A) + def respond_authorize_to_host(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: + # FEEDBAG__RESPOND_AUTHORIZE_TO_HOST: string08 who, u8 accepted, string16 reason + self.logger.info("[Client] FEEDBAG__RESPOND_AUTHORIZE_TO_HOST") + name = message.read_bytes(message.read_u8()).decode('latin-1') + accepted = message.read_u8() if len(message) > 0 else 0 + reason = _read_string16(message) + requester = names.resolve_user(context.backend, name) + if requester is None or requester is context.user: + return + if accepted: + grant_authorization(context.backend, context.user, requester, reason) + else: + deny_authorization(context.backend, context.user, requester, reason) + + @Subgroup(0x0016) + def remove_me(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None: + self.logger.info("[Client] FEEDBAG__REMOVE_ME") + + # xx byte length of the uin string + # xx .. string remote client uin string + target_name = message.read_string_u8() + + # there is no server reply to this SNAC, whether or not it did anything + if not names.valid_name(target_name): + return + + backend = context.backend + target_uuid = names.resolve(backend, target_name) + if target_uuid is None: + return + target_user = backend._load_user_record(target_uuid) + if target_user is None: + return + target_detail = backend._load_detail(target_user) + contact = target_detail.contacts.get(context.user.uuid) + if contact is None or not (contact.lists & ContactList.FL): + return + + # we are the contact being removed, so this is Backend.me_contact_remove seen from the list owner's side: + # drop us from their FL (and the AL their buddy add implied), then drop the matching RL we hold for them + permitted = context.user.username.lower() in (target_user.settings.get(SSI_KEY) or {}).get('permits', []) + unlink = [(target_user, context.user, ContactList.FL), (context.user, target_user, ContactList.RL)] + if not permitted: + unlink.insert(1, (target_user, context.user, ContactList.AL)) + + for owner, head, lst in unlink: + try: + context.bs._remove_from_list(owner, head, lst, None) + except Exception: + self.logger.info("[Server] FEEDBAG__REMOVE_ME could not clear", lst.name, "between", owner.username, "and", head.username) + + self.logger.info(context.user.username, "removed themselves from", target_user.username + "'s Buddy List") + +def _read_string16(message: SNACMessage) -> str: + if len(message) < 2: + return '' + return message.read_bytes(message.read_u16()).decode('utf-8', errors = 'replace') + +def _legacy_auth_request_text(requester: User, target: User, reason: str) -> str: + # MSG_TYPE_AUTH_REQ text: nick, first, last, e-mail, whether the requester already authorizes the target, reason + info = icq.basic_info(requester) + authorized = 0 if icq.requires_authorization(requester, target) else 1 + email = info['email'] if info['publish_email'] else '' + return '\xfe'.join([info['nick'], info['first'], info['last'], email, str(authorized), reason]) + +def _icq5_reason(reason: str) -> str: + # ICQ 5 drops an authorization request that has more than one period in it + first = reason.find('.') + if first < 0: + return reason + return reason[:first + 1] + reason[first + 1:].replace('.', '') + +def _deliver_auth_event(backend: Any, target: User, sender: User, event: str, text: str = '', *, sessions: Optional[list] = None) -> bool: + # returns whether any session took it + from .icbm import send_icq_system_message, ICQMessageType + delivered = False + for bs_t in (sessions if sessions is not None else backend.util_get_sessions_by_user(target)): + if bs_t.closed: + continue + if bs_t.front_data.get('oscar0') and hasattr(bs_t.evt, 'oscar_on_snac'): + ctrl = bs_t.evt.ctrl + sender_name = names.name_for(bs_t, sender) + if bs_t.front_data.get('oscar0_feedbag'): + if event == 'request': + msg = SNACMessage(0x0013, 0x0019, 0x8000) + msg.write_bytes(_extended_info(2)) + msg.write_bytes(_string08(sender_name)) + msg.write_bytes(_string16(_icq5_reason(text))) + msg.write_u16(0) + elif event in ('granted', 'denied'): + msg = SNACMessage(0x0013, 0x001B, 0x8000) + msg.write_bytes(_extended_info(2)) + msg.write_bytes(_string08(sender_name)) + msg.write_u8(1 if event == 'granted' else 0) + msg.write_bytes(_string16(text)) + msg.write_u16(0) + elif event == 'preauth': + msg = SNACMessage(0x0013, 0x0015) + msg.write_bytes(_string08(sender_name)) + msg.write_bytes(_string16(text)) + msg.write_u16(0) + elif event == 'added': + msg = build_buddy_added_notif(sender_name) + else: + continue + ctrl.send_snac(msg) + delivered = True + elif names.is_icq_session(bs_t) and names.uin_of(sender) is not None: + kind = { + 'request': ICQMessageType.AuthRequest, 'denied': ICQMessageType.AuthDeny, 'granted': ICQMessageType.AuthGrant, + 'preauth': ICQMessageType.AuthGrant, 'added': ICQMessageType.Added, + }.get(event) + if kind is None: + continue + if event == 'request': + body = _legacy_auth_request_text(sender, target, text) + elif event == 'denied': + body = text + else: + # grants and "you were added" carry no text over OSCAR + body = '' + send_icq_system_message(ctrl, sender, kind, body) + delivered = True + elif hasattr(bs_t.evt, 'icq_on_auth_event'): + bs_t.evt.icq_on_auth_event(event, sender, text) + delivered = True + return delivered + +def _queue_or_deliver(backend: Any, target: User, sender: User, event: str, text: str = '') -> None: + if _deliver_auth_event(backend, target, sender, event, text): + return + icq.queue_auth_event(target, { 'type': event, 'from': sender.uuid, 'text': text }) + icq.save(backend, target) + +def deliver_queued_auth_events(ctrl: Any) -> None: + # everything held for this account while it wasn't on ICQ, handed to the session that just signed on + bs = ctrl.bs + if bs is None: + return + events = icq.take_auth_events(bs.user) + if not events: + return + icq.save(ctrl.backend, bs.user) + for event in events: + sender = ctrl.backend._load_user_record(event.get('from') or '') + if sender is None: + continue + _deliver_auth_event(ctrl.backend, bs.user, sender, str(event.get('type')), str(event.get('text') or ''), sessions = [bs]) + +def request_authorization(backend: Any, requester: User, target: User, reason: str) -> None: + _queue_or_deliver(backend, target, requester, 'request', reason) + +def _clear_pending(backend: Any, owner: User, contact: User) -> bool: + # drop PENDING_AUTH from `owner`'s stored buddy entry for `contact`; returns whether there was one + store = owner.settings.get(SSI_KEY) + if not isinstance(store, dict): + return False + suffix = ':' + contact.username.lower() + cleared = False + for key, attrs in (store.get('battrs') or {}).items(): + if key.endswith(suffix) and any(tag == FeedbagAttributes.Pending for tag, _ in attrs): + store['battrs'][key] = [[tag, data] for tag, data in attrs if tag != FeedbagAttributes.Pending] + cleared = True + if cleared: + icq.save(backend, owner) + return cleared + +def _send_item_update(bs: Any, contact: User) -> None: + # FEEDBAG__UPDATE_ITEM from the server, so the client's copy of a buddy item matches what's stored again + from ..proto.snac import OSCARContext as _Context + context = _Context(bs.backend, bs.client) + context.bs = bs + context.user = bs.user + try: + items = [item for item in get_items(context) if item.class_id == FeedbagClass.Buddy and item.key == contact.username.lower()] + except Exception: + return + if not items: + return + msg = SNACMessage(0x0013, 0x0009) + msg.write_bytes(marshal_items(items)) + bs.evt.oscar_on_snac(msg) + +def grant_authorization(backend: Any, granter: User, requester: User, text: str = '', *, pre: bool = False) -> None: + # `granter` lets `requester` add them: recorded, the requester's pending buddy cleared, both sides told + icq.record_preauth(granter, requester.uuid) + icq.save(backend, granter) + if _clear_pending(backend, requester, granter): + for bs_r in feedbag_sessions(backend, requester): + _send_item_update(bs_r, granter) + _queue_or_deliver(backend, requester, granter, 'granted', text) + # now that it's settled, the granter hears they were added + _deliver_auth_event(backend, granter, requester, 'added') + for bs_r in oscar_sessions(backend, requester): + if bs_r.front_data.get('oscar0_ready'): + push_presence(bs_r, granter) + return + _queue_or_deliver(backend, requester, granter, 'preauth' if pre else 'granted', text) + +def deny_authorization(backend: Any, denier: User, requester: User, reason: str) -> None: + _queue_or_deliver(backend, requester, denier, 'denied', reason) + +def auth_event_from_icq_message(backend: Any, sender: User, target: User, kind: int, text: str) -> None: + # an ICQ client without a feedbag runs authorization through channel 4 messages; they become the same events + from .icbm import ICQMessageType + if kind == ICQMessageType.AuthRequest: + fields = text.split('\xfe') + request_authorization(backend, sender, target, fields[5] if len(fields) >= 6 else (fields[-1] if fields else '')) + elif kind == ICQMessageType.AuthGrant: + grant_authorization(backend, sender, target) + elif kind == ICQMessageType.AuthDeny: + deny_authorization(backend, sender, target, text) + elif kind == ICQMessageType.Added: + _deliver_auth_event(backend, target, sender, 'added') + +def _restore_bart_icon(context: OSCARContext) -> None: + # the buddy icon a feedbag client set last time is in its BART item; an icon the server has goes on show straight away + for entry in _get_store(context.user).get('misc', []): + if entry.get('c') != FeedbagClass.Bart or entry.get('n') not in ('0', '1'): + continue + attr = find_tlv(_attrs_from_json(entry['a']), FeedbagAttributes.BartInfo) + info = bart.parse_bart_info(attr.data) if attr is not None else None + if info is not None and bart.is_known(info[1]): + context.bs.front_data['oscar0_bart_icon'] = (info[0] & ~bart.BARTFlags.Unknown, info[1]) + return + +def _announce_icon(client: OSCARClient, context: OSCARContext) -> None: + from .buddy import refresh_contact + from .oservice import build_self_info + client.send_snac(build_self_info(context.bs)) + refresh_contact(context.backend, context.user) + +def _set_bart_item(client: OSCARClient, context: OSCARContext, item: FeedbagItem) -> None: + # a BART item (named after its BART type) holds a BART_INFO in attribute 0xD5; an icon the server already has goes on + # show, otherwise OSERVICE__BART_REPLY comes back flagged unknown (0x40) and the client uploads it over BART + try: + bart_type = int(item.name, 0) + except ValueError: + return + attr = find_tlv(item.attributes, FeedbagAttributes.BartInfo) + info = bart.parse_bart_info(attr.data) if attr is not None else None + if info is None: + return + flags, hash = info + known = bart.is_known(hash) + if not known: + flags |= bart.BARTFlags.Unknown + icon = bart_type in (bart.BARTType.BuddyIconSmall, bart.BARTType.BuddyIcon) + if icon: + context.bs.front_data['oscar0_bart_icon'] = (flags, hash) + + reply = SNACMessage(0x0001, 0x0021) + reply.write_bytes(bart.build_bart_id(bart_type, flags, hash)) + client.send_snac(reply) + + if icon and known: + _announce_icon(client, context) diff --git a/front/oscar/foodgroups/icbm.py b/front/oscar/foodgroups/icbm.py index 42502dc..9ba68ff 100644 --- a/front/oscar/foodgroups/icbm.py +++ b/front/oscar/foodgroups/icbm.py @@ -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'', 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', '
    ') + +def looks_like_html(text: str) -> bool: + return text[:6].lower() == '' or text[:5].lower() == ' 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(' bytes: + raw = latin1(text) + b'\x00' + return struct.pack(' 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 \ No newline at end of file + 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 diff --git a/front/oscar/foodgroups/icq.py b/front/oscar/foodgroups/icq.py new file mode 100644 index 0000000..ca3894d --- /dev/null +++ b/front/oscar/foodgroups/icq.py @@ -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(' 'LE': + self.data += struct.pack(' 'LE': + self.data += struct.pack(' '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(' int: + return struct.unpack(' 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('= 2: + return struct.unpack(' 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(' 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, +} diff --git a/front/oscar/foodgroups/invite.py b/front/oscar/foodgroups/invite.py new file mode 100644 index 0000000..4e1ef32 --- /dev/null +++ b/front/oscar/foodgroups/invite.py @@ -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)') diff --git a/front/oscar/foodgroups/locate.py b/front/oscar/foodgroups/locate.py index b63c3cd..ac18b4d 100644 --- a/front/oscar/foodgroups/locate.py +++ b/front/oscar/foodgroups/locate.py @@ -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', '
    ') + +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) diff --git a/front/oscar/foodgroups/oservice.py b/front/oscar/foodgroups/oservice.py index e779464..42a8e82 100644 --- a/front/oscar/foodgroups/oservice.py +++ b/front/oscar/foodgroups/oservice.py @@ -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)) ]) diff --git a/front/oscar/foodgroups/pd.py b/front/oscar/foodgroups/pd.py new file mode 100644 index 0000000..8e2ca51 --- /dev/null +++ b/front/oscar/foodgroups/pd.py @@ -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) \ No newline at end of file diff --git a/front/oscar/foodgroups/popup.py b/front/oscar/foodgroups/popup.py index acf099f..8a3b548 100644 --- a/front/oscar/foodgroups/popup.py +++ b/front/oscar/foodgroups/popup.py @@ -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 diff --git a/front/oscar/foodgroups/user_lookup.py b/front/oscar/foodgroups/user_lookup.py new file mode 100644 index 0000000..cbfedc8 --- /dev/null +++ b/front/oscar/foodgroups/user_lookup.py @@ -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) diff --git a/front/oscar/proto/backend.py b/front/oscar/proto/backend.py index f3cad3e..37d2977 100644 --- a/front/oscar/proto/backend.py +++ b/front/oscar/proto/backend.py @@ -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 - ]) \ No newline at end of file + TLV(0x0004, ERROR_URLS.get(int(error_code), '')), # Error URL + ]) diff --git a/front/oscar/proto/bart.py b/front/oscar/proto/bart.py new file mode 100644 index 0000000..241f3f0 --- /dev/null +++ b/front/oscar/proto/bart.py @@ -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) diff --git a/front/oscar/proto/chat.py b/front/oscar/proto/chat.py index 0944388..f6468df 100644 --- a/front/oscar/proto/chat.py +++ b/front/oscar/proto/chat.py @@ -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): diff --git a/front/oscar/proto/delivery.py b/front/oscar/proto/delivery.py new file mode 100644 index 0000000..a556822 --- /dev/null +++ b/front/oscar/proto/delivery.py @@ -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) diff --git a/front/oscar/proto/names.py b/front/oscar/proto/names.py new file mode 100644 index 0000000..7a87fb2 --- /dev/null +++ b/front/oscar/proto/names.py @@ -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) diff --git a/front/oscar/proto/snac.py b/front/oscar/proto/snac.py index 7ad88bb..30401c5 100644 --- a/front/oscar/proto/snac.py +++ b/front/oscar/proto/snac.py @@ -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 diff --git a/front/oscar/proto/tlv.py b/front/oscar/proto/tlv.py index bf02594..d788016 100644 --- a/front/oscar/proto/tlv.py +++ b/front/oscar/proto/tlv.py @@ -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 \ No newline at end of file diff --git a/front/oscar/proto/userinfo.py b/front/oscar/proto/userinfo.py new file mode 100644 index 0000000..2280eed --- /dev/null +++ b/front/oscar/proto/userinfo.py @@ -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 \ No newline at end of file diff --git a/front/toc/__init__.py b/front/toc/__init__.py new file mode 100644 index 0000000..fff762e --- /dev/null +++ b/front/toc/__init__.py @@ -0,0 +1,2 @@ +__all__ = ['entry', 'ctrl', 'commands', 'roast'] +from .entry import register \ No newline at end of file diff --git a/front/toc/commands.py b/front/toc/commands.py new file mode 100644 index 0000000..67bb5e4 --- /dev/null +++ b/front/toc/commands.py @@ -0,0 +1,393 @@ +from typing import Callable + +from core import error, event +from core.backend import Chat +from core.models import ContactList, MessageData, MessageType, Substatus, User + +from util.misc import is_valid_oscar_screenname + +COMMANDS: dict[str, Callable] = {} + +def command(name: str): + def deco(func): + COMMANDS[name] = func + return func + return deco + +@command('toc_signon') +def _toc_signon(ctrl, args: list[str]) -> None: + if len(args) < 4: + ctrl.send_line('ERROR:980') + return + ctrl.sign_on(args[2], args[3], dialect = 1) + +@command('toc2_signon') +def _toc2_signon(ctrl, args: list[str]) -> None: + if len(args) < 4: + ctrl.send_line('ERROR:980') + return + ctrl.sign_on(args[2], args[3], dialect = 2) + +@command('toc_init_done') +def _toc_init_done(ctrl, args: list[str]) -> None: + ctrl.init_done() + +@command('toc_quit') +def _toc_quit(ctrl, args: list[str]) -> None: + ctrl.close() + +@command('toc_ping') +def _toc_ping(ctrl, args: list[str]) -> None: + pass + +@command('toc_add_buddy') +def _toc_add_buddy(ctrl, args: list[str]) -> None: + if ctrl.bs is None: return + for name in args: + if not is_valid_oscar_screenname(name): continue + uuid = ctrl.backend.util_get_uuid_from_username(name) + if uuid is None: continue + try: + ctrl.bs.me_contact_add(uuid, ContactList.FL, name = name) + except error.ClientError: + pass + +@command('toc_remove_buddy') +def _toc_remove_buddy(ctrl, args: list[str]) -> None: + if ctrl.bs is None: return + for name in args: + if name == ':': continue + uuid = ctrl.backend.util_get_uuid_from_username(name) + if uuid is None: continue + try: + ctrl.bs.me_contact_remove(uuid, ContactList.FL) + except error.ClientError: + pass + +@command('toc_add_permit') +def _toc_add_permit(ctrl, args: list[str]) -> None: + _add_pd(ctrl, args, ContactList.AL) + +@command('toc_add_deny') +def _toc_add_deny(ctrl, args: list[str]) -> None: + _add_pd(ctrl, args, ContactList.BL) + +def _add_pd(ctrl, args: list[str], lst) -> None: + if ctrl.bs is None: return + for name in args: + if not is_valid_oscar_screenname(name): continue + uuid = ctrl.backend.util_get_uuid_from_username(name) + if uuid is None: continue + try: + ctrl.bs.me_contact_add(uuid, lst, name = name) + except error.ClientError: + pass + +@command('toc_set_config') +def _toc_set_config(ctrl, args: list[str]) -> None: + if ctrl.bs is None or not args: return + for line in args[0].split('\n'): + line = line.strip() + if line.startswith('m '): + try: + mode = int(line[2:].strip()) + except ValueError: + continue + blp = 'AL' if mode in (1, 3, 5) else 'BL' + ctrl.bs.me_update({'blp': blp}) + + +@command('toc_set_away') +def _toc_set_away(ctrl, args: list[str]) -> None: + if ctrl.bs is None: return + message = args[0] if args else '' + ctrl.bs.me_update({'message': message, 'substatus': Substatus.Away if message else Substatus.Online}) + +@command('toc_set_idle') +def _toc_set_idle(ctrl, args: list[str]) -> None: + pass + + +@command('toc_send_im') +def _toc_send_im(ctrl, args: list[str]) -> None: + if ctrl.bs is None or len(args) < 2: return + receiver_name, message = args[0], args[1] + + if not is_valid_oscar_screenname(receiver_name): + ctrl.send_line('ERROR:901:{}'.format(receiver_name)) # not available + return + receiver_uuid = ctrl.backend.util_get_uuid_from_username(receiver_name) + if receiver_uuid is None: + ctrl.send_line('ERROR:901:{}'.format(receiver_name)) + return + + try: + cs, evt = _get_private_chat_with(ctrl, receiver_uuid) + except error.ClientError: + ctrl.send_line('ERROR:901:{}'.format(receiver_name)) + return + + md = MessageData(sender = ctrl.bs.user, type = MessageType.Chat, text = message) + if not ctrl.backend.util_message_allowed(ctrl.bs.user, md): + ctrl.send_line('ERROR:903') + return + evt._send_when_user_joins(receiver_uuid, md) + +@command('toc_evil') +def _toc_evil(ctrl, args: list[str]) -> None: + pass + if ctrl.bs is None or not args: return + name = args[0] + target_uuid = ctrl.backend.util_get_uuid_from_username(name) if is_valid_oscar_screenname(name) else None + target = ctrl.backend._load_user_record(target_uuid) if target_uuid is not None else None + if ( + target is None or target is ctrl.bs.user or target.status.is_offlineish() + or not ctrl.backend.util_get_sessions_by_user(target) + ): + ctrl.send_line('ERROR:902:{}'.format(name)) # warning of not currently available + return + anonymous = (len(args) > 1 and args[1].lower() == 'anon') + if ctrl.backend.abuse.warn(ctrl.bs.user, target, anonymous = anonymous) is None: + ctrl.send_line('ERROR:902:{}'.format(name)) + +@command('toc_chat_join') +def _toc_chat_join(ctrl, args: list[str]) -> None: + if ctrl.bs is None or len(args) < 2: return + room_name = args[1] + chat = ctrl.backend.chat_create() + chat.add_id('toc', chat.ids['main']) + evt = TOCChatEventHandler(ctrl, ctrl.bs, room_name) + cs = chat.join('toc', ctrl.bs, evt) + chat_id = id(chat) & 0xFFFF + ctrl.chats[chat_id] = (cs, evt) + ctrl.send_line('CHAT_JOIN:{}:{}'.format(chat_id, room_name)) + +@command('toc_chat_send') +def _toc_chat_send(ctrl, args: list[str]) -> None: + if len(args) < 2: return + try: + chat_id = int(args[0]) + except ValueError: + return + entry = ctrl.chats.get(chat_id) + if entry is None: return + cs, evt = entry + md = MessageData(sender = ctrl.bs.user, type = MessageType.Chat, text = args[1]) + cs.send_message_to_everyone(md) + +@command('toc_chat_leave') +def _toc_chat_leave(ctrl, args: list[str]) -> None: + if not args: return + try: + chat_id = int(args[0]) + except ValueError: + return + entry = ctrl.chats.pop(chat_id, None) + if entry is not None: + entry[0].close() + +@command('toc_chat_invite') +def _toc_chat_invite(ctrl, args: list[str]) -> None: + if len(args) < 3: return + try: + chat_id = int(args[0]) + except ValueError: + return + entry = ctrl.chats.get(chat_id) + if entry is None: return + cs, evt = entry + invite_msg = args[1] + for name in args[2:]: + if not is_valid_oscar_screenname(name): continue + uuid = ctrl.backend.util_get_uuid_from_username(name) + if uuid is None: continue + invitee = ctrl.backend._load_user_record(uuid) + if invitee is not None: + try: + cs.invite(invitee, invite_msg = invite_msg) + except error.ClientError: + pass + +@command('toc_get_info') +def _toc_get_info(ctrl, args: list[str]) -> None: + if args: + ctrl.logger.info('[Client] toc_get_info for', args[0], '(no profile service configured)') + +@command('toc_set_info') +def _toc_set_info(ctrl, args: list[str]) -> None: + if ctrl.bs is None or not args: return + ctrl.bs.me_update({'message': args[0]}) + +@command('toc_format_nickname') +def _toc_format_nickname(ctrl, args: list[str]) -> None: + if ctrl.bs is None or not args: return + ctrl.bs.me_update({'name': args[0], 'needs_notify': True, 'notify_self': True}) + ctrl.send_line('ADMIN_NICK_STATUS:0') + +@command('toc_dir_search') +def _toc_dir_search(ctrl, args: list[str]) -> None: + ctrl.send_line('DIR_STATUS:0:No matches found.') + +@command('toc_set_caps') +def _toc_set_caps(ctrl, args: list[str]) -> None: + pass + +def build_config2(bs) -> str: + detail = bs.user.detail + assert detail is not None + lines = [] + for grp in detail._groups_by_id.values(): + lines.append('g {}'.format(grp.name)) + for ctc in detail.get_contacts_by_list(ContactList.FL): + if not is_valid_oscar_screenname(ctc.head.username): continue + if any(g.id == grp.id for g in ctc._groups): + lines.append('b {}'.format(ctc.head.username)) + for ctc in detail.get_contacts_by_list(ContactList.AL): + if is_valid_oscar_screenname(ctc.head.username): + lines.append('p {}'.format(ctc.head.username)) + for ctc in detail.get_contacts_by_list(ContactList.BL): + if is_valid_oscar_screenname(ctc.head.username): + lines.append('d {}'.format(ctc.head.username)) + mode = 3 if bs.user.settings.get('BLP', 'AL') == 'AL' else 4 + lines.append('m {}'.format(mode)) + return 'CONFIG2:{}'.format('\n'.join(lines)) + +def build_nick(user: User) -> str: + return 'NICK:{}'.format(user.status.name or user.username) + +def build_update_buddy(ctc, *, dialect: int) -> str: + online = 'T' if not ctc.status.is_offlineish() else 'F' + signon_time = int(ctc.head.date_login.timestamp()) if ctc.head.date_login else 0 + cmd = 'UPDATE_BUDDY2' if dialect == 2 else 'UPDATE_BUDDY' + evil = max(0, min(999, int(ctc.head.evil_permanent or 0) + int(ctc.head.evil_temporary or 0))) // 10 + return '{}:{}:{}:{}:{}:0:'.format(cmd, ctc.head.username, online, evil, signon_time) + + +def _get_private_chat_with(ctrl, other_user_uuid: str): + bs = ctrl.bs + other_user = ctrl.backend._load_user_record(other_user_uuid) + if other_user is None or not is_valid_oscar_screenname(other_user.username): + raise error.ContactNotOnContactList() + + toc_chats = ctrl.front_data.setdefault('toc_chats', {}) + if other_user_uuid not in toc_chats: + chat = ctrl.backend.chat_create() + chat.front_data['toc'] = True + evt = TOCChatEventHandler(ctrl, bs, other_user.username) + cs = chat.join('toc', bs, evt) + toc_chats[other_user_uuid] = (cs, evt) + cs.invite(other_user) + return toc_chats[other_user_uuid] + + +class TOCBackendEventHandler(event.BackendEventHandler): + __slots__ = ('ctrl', 'bs') + + def __init__(self, ctrl) -> None: + self.ctrl = ctrl + + def on_presence_notification(self, ctc, on_contact_add, old_substatus, **kwargs) -> None: + if not is_valid_oscar_screenname(ctc.head.username): + return + self.ctrl.send_line(build_update_buddy(ctc, dialect = self.ctrl.dialect)) + + def on_presence_self_notification(self, old_substatus, **kwargs) -> None: + pass + + def on_chat_invite(self, chat: Chat, inviter: User, *, circle: bool = False, inviter_id = None, invite_msg: str = '') -> None: + evt = TOCChatEventHandler(self.ctrl, self.bs, inviter.username) + cs = chat.join('toc', self.bs, evt) + chat_id = id(chat) & 0xFFFF + self.ctrl.chats[chat_id] = (cs, evt) + self.ctrl.front_data.setdefault('toc_chats', {})[inviter.uuid] = (cs, evt) + + def on_declined_chat_invite(self, chat: Chat, circle: bool = False) -> None: + pass + + def on_added_me(self, user: User, *, adder_id = None, message = None) -> None: + pass + + def on_removed_me(self, user: User) -> None: + pass + + def on_contact_request_denied(self, user_added: User, message, *, contact_id = None) -> None: + pass + + def on_oim_sent(self, oim) -> None: + pass + + def on_login_elsewhere(self, option) -> None: + self.ctrl.send_line('ERROR:982') # signed on elsewhere + self.ctrl.close() + + def on_circle_invite_revoked(self, chat_id: str) -> None: pass + def on_accepted_circle_invite(self, circle) -> None: pass + def on_circle_updated(self, circle) -> None: pass + def on_left_circle(self, circle) -> None: pass + def on_circle_role_updated(self, chat_id: str, role) -> None: pass + def on_circle_created(self, circle) -> None: pass + + def on_maintenance_message(self, *args, **kwargs) -> None: + pass + + def on_maintenance_boot(self) -> None: + self.ctrl.close() + + def on_warning_level_changed(self, level: int, warner) -> None: + previous = self.ctrl.front_data.get('toc_evil', 0) + self.ctrl.front_data['toc_evil'] = level + if level > previous: + self.ctrl.send_line('EVILED:{}:{}'.format(level // 10, warner.username if warner is not None else '')) + + def on_close(self) -> None: + self.ctrl.close() + + +class TOCChatEventHandler(event.ChatEventHandler): + __slots__ = ('ctrl', 'bs', 'cs', 'peer_name', '_pending') + + def __init__(self, ctrl, bs, peer_name: str) -> None: + self.ctrl = ctrl + self.bs = bs + self.peer_name = peer_name + self._pending = [] + + def on_participant_joined(self, cs_other, first_pop, initial_join) -> None: + still = [] + for uuid, data in self._pending: + if cs_other.user.uuid == uuid: + self.cs.send_message_to_user(uuid, data) + else: + still.append((uuid, data)) + self._pending = still + + def on_participant_left(self, cs_other, last_pop) -> None: + pass + + def on_chat_invite_declined(self, chat, invitee, *, invitee_id = None, message = None, circle = False) -> None: + pass + + def on_chat_updated(self) -> None: pass + def on_chat_roster_updated(self) -> None: pass + def on_participant_status_updated(self, cs_other, first_pop, initial, old_substatus) -> None: pass + + def on_message(self, data: MessageData) -> None: + if data.sender is self.bs.user: + return + auto_reply = 'T' if data.front_cache.get('away_response') else 'F' + if self.ctrl.dialect == 2: + self.ctrl.send_line('IM_IN2:{}:{}:0:0:{}'.format(data.sender.username, auto_reply, data.text or '')) + else: + self.ctrl.send_line('IM_IN:{}:{}:{}'.format(data.sender.username, auto_reply, data.text or '')) + + def _send_when_user_joins(self, user_uuid: str, data: MessageData) -> None: + if self._user_in_chat(user_uuid): + self.cs.send_message_to_user(user_uuid, data) + else: + self._pending.append((user_uuid, data)) + + def _user_in_chat(self, user_uuid: str) -> bool: + for cs_other in self.cs.chat.get_roster(): + if cs_other.user.uuid == user_uuid: + return True + return False \ No newline at end of file diff --git a/front/toc/ctrl.py b/front/toc/ctrl.py new file mode 100644 index 0000000..d6276c2 --- /dev/null +++ b/front/toc/ctrl.py @@ -0,0 +1,143 @@ +import random +import struct + +from core.backend import Backend, BackendSession +from core.client import Client +from typing import Optional, Callable +from util.misc import Logger, is_valid_oscar_screenname + +from .commands import COMMANDS, TOCBackendEventHandler, build_config2, build_nick, build_update_buddy +from core.models import ContactList + + +class TOCCtrl: + logger: Logger + transport: Optional[object] + + close_callback: Optional[Callable[[], None]] + closed: bool + + backend: Backend + bs: Optional[BackendSession] + client: Client + + dialect: int + sequence: int + + def __init__(self, logger: Logger, via: str, backend: Backend) -> None: + self.logger = logger + self.transport = None + self.close_callback = None + self.closed = False + self.backend = backend + self.bs = None + self.client = Client('toc', '1.0', via) + self.dialect = 1 + self.sequence = random.randint(0x0000, 0xFFFF) + self.evt = None # type: Optional[TOCBackendEventHandler] + self.front_data = {} + self.chats = {} # numeric chat id -> (ChatSession, TOCChatEventHandler) + + def on_connect(self) -> None: + self.transport.write(struct.pack('>BBHHL', 0x2A, 0x01, self._next_seq(), 4, 1)) + + def _next_seq(self) -> int: + self.sequence = 0 if self.sequence == 0xFFFF else self.sequence + 1 + return self.sequence + + def send_line(self, line: str) -> None: + payload = line.encode('utf-8', 'replace') + b'\x00' + packet = struct.pack('>BBHH', 0x2A, 0x02, self._next_seq(), len(payload)) + payload + if self.transport is not None: + self.transport.write(packet) + + def on_signon_frame(self, data: bytes) -> None: + pass + + def on_data_frame(self, data: bytes) -> None: + line = data.rstrip(b'\x00').decode('utf-8', 'replace') + if not line: + return + + parts = _tokenize(line) + if not parts: + return + + handler = COMMANDS.get(parts[0]) + if handler is None: + self.logger.info('[Client] Unknown TOC command:', parts[0]) + return + handler(self, parts[1:]) + + def sign_on(self, username_login: str, roasted_pw: str, *, dialect: int) -> None: + from .roast import unroast_hex + + self.dialect = dialect + self.client = Client('toc', 'TOC{}.0'.format(dialect), self.client.via) + + password = unroast_hex(roasted_pw.encode('utf-8')).decode('utf-8', 'replace') + uuid = self.backend.user_service.login_with_username(username_login, password) + if uuid is None: + self.send_line('ERROR:980') # incorrect nickname or password + self.close() + return + + self.evt = TOCBackendEventHandler(self) + self.bs = self.backend.login(uuid, self.client, self.evt, option = None) + if self.bs is None: + self.send_line('ERROR:981') # service temporarily unavailable + self.close() + return + self.bs.front_data['toc'] = True + + self.send_line('SIGN_ON:TOC{}.0'.format(dialect)) + + def init_done(self) -> None: + if self.bs is None: + return + self.send_line(build_config2(self.bs)) + self.send_line(build_nick(self.bs.user)) + + # push presence for everyone already online, otherwise nobody shows online + # until their status next changes + detail = self.bs.user.detail + if detail is not None: + for ctc in detail.get_contacts_by_list(ContactList.FL): + if is_valid_oscar_screenname(ctc.head.username) and not ctc.status.is_offlineish(): + self.send_line(build_update_buddy(ctc, dialect = self.dialect)) + + def close(self) -> None: + if self.closed: + return + self.closed = True + if self.close_callback: + self.close_callback() + if self.bs: + self.bs.close() + + +def _tokenize(line: str) -> list[str]: + tokens = [] + i = 0 + n = len(line) + while i < n: + while i < n and line[i] == ' ': + i += 1 + if i >= n: + break + if line[i] == '{': + depth = 1 + j = i + 1 + while j < n and depth > 0: + if line[j] == '{': depth += 1 + elif line[j] == '}': depth -= 1 + j += 1 + tokens.append(line[i + 1:j - 1]) + i = j + else: + j = i + while j < n and line[j] != ' ': + j += 1 + tokens.append(line[i:j]) + i = j + return tokens \ No newline at end of file diff --git a/front/toc/entry.py b/front/toc/entry.py new file mode 100644 index 0000000..ddfb309 --- /dev/null +++ b/front/toc/entry.py @@ -0,0 +1,78 @@ +import asyncio +import struct + +from core.backend import Backend +from typing import Optional, Callable +from util.misc import Logger, ProtocolRunner + +from .ctrl import TOCCtrl + + +def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None: + backend.add_runner(ProtocolRunner('0.0.0.0', 9898, ListenerTOC, args = ['TOC', backend, TOCCtrl], service = 'TOC')) + + +class ListenerTOC(asyncio.Protocol): + logger: Logger + backend: Backend + controller: TOCCtrl + transport: Optional[asyncio.WriteTransport] + + buffer: bytes = b'' + + def __init__(self, logger_prefix: str, backend: Backend, controller_factory: Callable[[Logger, str, Backend], TOCCtrl]) -> None: + super().__init__() + self.logger = Logger(logger_prefix, self) + self.backend = backend + self.controller = controller_factory(self.logger, 'direct', backend) + self.controller.close_callback = self._on_close + self.transport = None + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.controller.transport = transport + self.controller.on_connect() + self.logger.log_connect() + + def connection_lost(self, exc: Optional[Exception]) -> None: + self.controller.close() + self.logger.log_disconnect() + + def data_received(self, packet: bytes) -> None: + if self.backend.maintenance_mode: + self.transport.close() + return + self.buffer += packet + self.parse_buffer() + + def parse_buffer(self) -> None: + while True: + if self.controller.closed: + self.buffer = b'' + break + if not self.buffer or self.buffer[0] != 0x2A: + break + if len(self.buffer) < 6: + break + + channel, sequence, length = struct.unpack('>BHH', self.buffer[1:6]) + if len(self.buffer) < length + 6: + break + + data = self.buffer[6:length + 6] + match channel: + case 0x01: + self.controller.on_signon_frame(data) + case 0x02: + self.controller.on_data_frame(data) + case 0x04: + self.controller.close() + case 0x05: + pass + case _: + self.logger.info('Recieved unknown FLAP channel:', str(channel)) + + self.buffer = self.buffer[length + 6:] + + def _on_close(self) -> None: + if self.transport is not None: + self.transport.close() \ No newline at end of file diff --git a/front/toc/roast.py b/front/toc/roast.py new file mode 100644 index 0000000..a9b28c9 --- /dev/null +++ b/front/toc/roast.py @@ -0,0 +1,13 @@ +from itertools import cycle + +ROAST_STRING = b'Tic/Toc' + +def roast(password: bytes) -> bytes: + chars = cycle(ROAST_STRING) + return bytes(byte ^ next(chars) for byte in password) + +def unroast_hex(roasted: bytes) -> bytes: + text = roasted.decode('ascii', 'replace') + if text.startswith('0x'): + text = text[2:] + return roast(bytes.fromhex(text)) \ No newline at end of file diff --git a/front/ymsg/avatar_sync.py b/front/ymsg/avatar_sync.py new file mode 100644 index 0000000..7317b97 --- /dev/null +++ b/front/ymsg/avatar_sync.py @@ -0,0 +1,86 @@ +from typing import Dict, List, Optional +import asyncio, time, traceback + +from core.backend import Backend +from core.models import ContactList, User, _is_blocking + +from . import misc + +SYNC_INTERVAL = 15 +PUSH_DEDUPE_SECS = 5 + +_UNSET = object() +_last_checksum = {} # type: Dict[str, Optional[bytes]] +_last_push = {} # type: Dict[str, tuple] + + +def refresh_avatar(backend: Backend, user: User) -> bool: + try: + fresh = backend.user_service.get(user.uuid) + except Exception: + traceback.print_exc() + return False + if fresh is None or fresh.avatar == user.avatar: + return False + user.avatar = fresh.avatar + return True + +def note_login(backend: Backend, user: User) -> None: + refresh_avatar(backend, user) + _last_checksum[user.uuid] = misc.yahoo_avatar_checksum(user) + +def icon_recipients(user: User) -> List[User]: + detail = user.detail + if detail is None: + return [] + heads = [] # type: List[User] + for ctc in detail.contacts.values(): + if not ctc.lists & (ContactList.FL | ContactList.RL): + continue + if _is_blocking(user, ctc.head): + continue + heads.append(ctc.head) + return heads + +def push_avatar_change(backend: Backend, user: User) -> None: + checksum = misc.yahoo_avatar_checksum(user) + _last_checksum[user.uuid] = checksum + if checksum is None: + return + _last_push[user.uuid] = (checksum, time.monotonic()) + + for bs_self in backend.util_get_sessions_by_user(user): + bs_self.evt.ymsg_on_friend_icon(user.username, user.username, checksum) + + for head in icon_recipients(user): + for bs_other in backend.util_get_sessions_by_user(head): + bs_other.evt.ymsg_on_friend_icon(user.username, head.username, checksum) + +def recently_pushed(user: User, checksum: bytes) -> bool: + last = _last_push.get(user.uuid) + return last is not None and last[0] == checksum and (time.monotonic() - last[1]) < PUSH_DEDUPE_SECS + +def sync_once(backend: Backend) -> None: + seen = set() + for bs in list(backend._sc.iter_sessions()): + user = bs.user + if user.uuid in seen: + continue + seen.add(user.uuid) + + refresh_avatar(backend, user) + checksum = misc.yahoo_avatar_checksum(user) + previous = _last_checksum.get(user.uuid, _UNSET) + if previous is _UNSET: + _last_checksum[user.uuid] = checksum + continue + if checksum != previous: + push_avatar_change(backend, user) + +async def worker_sync_avatars(backend: Backend) -> None: + while True: + await asyncio.sleep(SYNC_INTERVAL) + try: + sync_once(backend) + except Exception: + traceback.print_exc() \ No newline at end of file diff --git a/front/ymsg/entry.py b/front/ymsg/entry.py index d149347..ac3cb50 100644 --- a/front/ymsg/entry.py +++ b/front/ymsg/entry.py @@ -9,8 +9,8 @@ from .ymsg_ctrl import YMSGCtrlBase def register(loop: asyncio.AbstractEventLoop, backend: Backend, http_app: web.Application, *, devmode: bool = False) -> None: from util.misc import ProtocolRunner - from . import pager, http, videochat, voicechat - + from . import pager, http, videochat, voicechat, avatar_sync#, sip + backend.add_runner(ProtocolRunner('0.0.0.0', 5050, ListenerYMSG, args = ['Yahoo', backend, pager.YMSGCtrlPager], service = "YMSG Pager")) # Funny that Yahoo! used the FTP transfer, Telnet, SMTP, and NNTP (Usenet) ports as the fallback ports. backend.add_runner(ProtocolRunner('0.0.0.0', 20, ListenerYMSG, args = ['Yahoo', backend, pager.YMSGCtrlPager], service = "YMSG Pager")) @@ -25,6 +25,8 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, http_app: web.Ap http.register(http_app, devmode = devmode) voicechat.register(backend) videochat.register(backend) + #sip.register(backend) + loop.create_task(avatar_sync.worker_sync_avatars(backend)) class ListenerYMSG(asyncio.Protocol): logger: Logger @@ -56,12 +58,9 @@ class ListenerYMSG(asyncio.Protocol): if self.backend.maintenance_mode: transport.close() return - self.controller.transport = None - if self.controller.transport is None: - self.controller.transport = self.transport + self.controller.transport = transport self.controller.data_received(data) transport.write(self.controller.flush()) - self.controller.transport = transport def _on_close(self) -> None: if self.transport is None: return diff --git a/front/ymsg/http.py b/front/ymsg/http.py index 8972cd3..88e7926 100644 --- a/front/ymsg/http.py +++ b/front/ymsg/http.py @@ -1,8 +1,8 @@ from typing import Any, Dict, Optional, Tuple from aiohttp import web -import asyncio, shutil, time, uuid, datetime, util.misc, settings +import asyncio, shutil, time, uuid, datetime, util.misc, html, settings from markupsafe import Markup -from urllib.parse import unquote, unquote_plus, quote +from urllib.parse import unquote, unquote_plus, quote, parse_qs from pathlib import Path from core.backend import Backend, BackendSession @@ -10,11 +10,12 @@ from core.models import Contact, Substatus, ContactList from util.hash import gen_salt from util.misc import Logger from .ymsg_ctrl import YMSGCtrlBase, _try_decode_ymsg -from .misc import YMSGService +from .misc import YMSGService, yahoo_avatar_url, yahoo_avatar_checksum, TOKEN_LIFETIME from .pager import _encode_yahoo_id, Y_COOKIE_TEMPLATE, T_COOKIE_TEMPLATE +from . import avatar_sync YAHOO_TMPL_DIR = 'front/ymsg/tmpl' -# https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/src/yahoo/yahooutil.py#L33 +# https://github.com/ifwe/digsby/blob/master/digsby/src/yahoo/yahooutil.py FILE_STORE_PATH = '/storage/file/{filename}' _tasks_by_token = {} # type: Dict[str, asyncio.Task[None]] @@ -53,6 +54,14 @@ def register(app: web.Application, *, devmode: bool = False) -> None: # Misc stuff app.router.add_get('/capacity', handle_capacity) app.router.add_get('/nofriends/', handle_nofriends) + + # Yahoo! Address Book (address.yahoo.com) + app.router.add_get('/yab/{intl}', handle_yab) + app.router.add_post('/yab/{intl}', handle_yab) + + # Photo sharing and P2P file transfer body + app.router.add_post('/relay', handle_relay_upload) + app.router.add_get('/relay', handle_relay_download) async def handle_insider_ycontent(req: web.Request) -> web.Response: backend = req.app['backend'] @@ -123,6 +132,20 @@ async def handle_insider_ycontent(req: web.Request) -> web.Response: config_xml.append(ab2_tmpl.render(epoch = round(time.time()), records = Markup(_gen_yab_record(target_ctc)))) continue + + if query_xml.startswith('getaudibles_'): + feed = _get_ycontent_feed('audibles', query_xml[len('getaudibles_'):]) + if feed is not None: + config_xml.append(feed) + continue + if query_xml == 'getimv': + feed = _get_ycontent_feed('imvs', req.query.get('getimv') or '') + if feed is not None: + config_xml.append(feed) + continue + if query_xml in ('getgp', 'getwc'): + continue + tmpl = req.app['jinja_env'].get_template('ymsg:Yinsider/Yinsider.' + query_xml + '.xml') config_xml.append(tmpl.render()) @@ -229,11 +252,14 @@ async def handle_ft_http(req: web.Request) -> web.Response: try: # check version and vendorId - if y_ft_pkt[1] > 16 or y_ft_pkt[2] not in (0, 100): + if y_ft_pkt[1] > 18 or y_ft_pkt[2] not in (0, 100): return web.HTTPInternalServerError(text = '') except Exception: return web.HTTPInternalServerError(text = '') + if y_ft_pkt[0] is YMSGService.FriendIconFileTransfer: + return await _handle_picture_upload(req, backend, y_ft_pkt[5], stream) + if y_ft_pkt[0] is not YMSGService.FileTransfer: return web.HTTPInternalServerError(text = '') @@ -268,7 +294,7 @@ async def handle_ft_http(req: web.Request) -> web.Response: try: filename = Path(file_path).name except: - return web.HTTPInternalServerError(text = '') + return web.HTTPInternalServerError(text = 'File not found') token = gen_salt(length = 30) path = _get_tmp_file_storage_path(token) @@ -294,6 +320,58 @@ async def handle_ft_http(req: web.Request) -> web.Response: return web.HTTPOk(text = '') +async def handle_relay_upload(req: web.Request) -> web.Response: + backend = req.app['backend'] + token = req.query.get('token') + if not token or not backend.auth_service.get_token('ymsg/relay', token): + return web.HTTPNotFound(text = 'Token invalid') + + body = await req.read() + if not body or len(body) > (2 ** 24): + return web.HTTPInternalServerError(text = 'No body') + + path = _get_tmp_file_storage_path(token) + path.mkdir(exist_ok = True, parents = True) + (path / 'blob').write_bytes(body) + + expiry_task = req.app.loop.create_task(_store_tmp_file_until_expiry(path)) + _tasks_by_token[token] = expiry_task + + return web.HTTPOk(text = '') + +async def handle_relay_download(req: web.Request) -> web.Response: + backend = req.app['backend'] + token = req.query.get('token') + if not token or not backend.auth_service.get_token('ymsg/relay', token): + return web.HTTPNotFound(text = 'Token invalid') + + blob = _get_tmp_file_storage_path(token) / 'blob' + if req.method == 'HEAD': + size = blob.stat().st_size if blob.is_file() else 0 + return web.Response(status = 200, headers = {'Content-Length': str(size)}) + + try: + data = blob.read_bytes() + except FileNotFoundError: + return web.HTTPNotFound(text = 'File not found') + + task = _tasks_by_token.pop(token, None) + if task is not None: + task.cancel() + shutil.rmtree(_get_tmp_file_storage_path(token), ignore_errors = True) + return web.Response(status = 200, body = data) + +IGNORED_QUERIES = { + 'intl', 'os', 'ver', 'fmt', 't', + 'imv', 'sms', 'system', + 'countries', 'defaultcountry', 'filter', 'url', 'searchbar', 'games', + 'fn', 'ln', 'yid', + 'nn', 'e', 'hp', + 'wp', 'mb', 'pp', + 'ee', 'ow', 'id', +} + + async def _store_tmp_file_until_expiry(path: Path) -> None: await asyncio.sleep(86400) # When a day passes, delete the file (unless it has already been deleted by @@ -326,7 +404,7 @@ async def handle_yahoo_filedl(req: web.Request) -> web.Response: }, body = file_stream) async def handle_capacity(req: web.Request) -> web.Response: - return web.Response(text="COLO_CAPACITY=1\nCS_IP_ADDRESS={}".format(settings.TARGET_IP)) + return web.Response(text = 'COLO_CAPACITY=1\r\nCS_IP_ADDRESS={}\r\n'.format(settings.TARGET_IP)) async def handle_nofriends(req: web.Request) -> web.Response: return render(req, 'ymsg:layout/nofriends.html') @@ -350,7 +428,7 @@ async def handle_gettoken(req: web.Request) -> web.Response: elif user.suspended: error_int = "1218" else: - token_tpl = _login(req, username, pwd, lifetime=86400) + token_tpl = _login(req, username, pwd, lifetime = TOKEN_LIFETIME) if token_tpl is None: error_int = "1212" else: @@ -394,6 +472,37 @@ async def handle_login(req: web.Request) -> web.Response: else: return web.Response(text="100") +async def handle_yab(req: web.Request) -> web.Response: + backend = req.app['backend'] + user = _resolve_user(req, backend) + if user is None: + return web.HTTPInternalServerError(text = '') + detail = user.detail + if detail is None: + return web.HTTPInternalServerError(text = '') + + esc = lambda s: html.escape(str(s), quote = True) + + wanted = None # type: Optional[set[str]] + if req.method == 'POST': + posted = (await req.read()).decode('utf-8', 'replace') + wanted = {yi.lower() for yi in re.findall(r'''\byi=["']([^"']+)["']''', posted)} + + records = ['\n'.format(esc(user.username))] + for ctc in detail.contacts.values(): + if not ctc.lists & ContactList.FL: + continue + if wanted is not None and ctc.head.username.lower() not in wanted: + continue + attrs = '' + if ctc.detail.first_name: attrs += ' fn="{}"'.format(esc(ctc.detail.first_name)) + if ctc.detail.last_name: attrs += ' ln="{}"'.format(esc(ctc.detail.last_name)) + if ctc.detail.nickname: attrs += ' nn="{}"'.format(esc(ctc.detail.nickname)) + records.append('\n'.format(esc(ctc.detail.index_id), esc(ctc.head.username), attrs)) + + body = '\n{}\r\n'.format(esc(user.username), len(records), ''.join(records)) + return web.Response(status = 200, body = body.encode('utf-8'), content_type = 'text/html', charset = 'utf-8') + async def handle_ncclogin(req: web.Request) -> web.Response: backend = req.app['backend'] params = req.rel_url.query @@ -405,13 +514,6 @@ async def handle_ncclogin(req: web.Request) -> web.Response: user = backend.user_service.get(uuid) if uuid else None detail = backend._load_detail(user) - if settings.DEBUG: - print(f"Username: {username}") - print(f"Encoded Password: {encoded_pwd}") - print(f"Decoded Password: {pwd}") - print(f"UUID: {uuid}") - print(f"User: {user}") - contacts = detail.contacts cs = list(contacts.values()) cs_fl = [c for c in cs if c.lists & ContactList.FL and not c.lists & ContactList.BL] @@ -449,9 +551,98 @@ async def handle_ncclogin(req: web.Request) -> web.Response: async def handle_banneradredir(req: web.Request) -> web.Response: return web.HTTPFound(f'http://{settings.TARGET_HOST}/ads/banner') +async def _handle_picture_upload( + req: web.Request, backend: Backend, ymsg_data: Any, stream: bytes, +) -> web.Response: + from util.avatar import get_img_type + import traceback + + user = _resolve_user(req, backend) + if user is None: + return web.HTTPInternalServerError(text = '') + + try: + declared_len = int(util.misc.arbitrary_decode(ymsg_data.get(b'28') or b'0')) + except ValueError: + declared_len = 0 + if declared_len <= 0 or len(stream) < declared_len or declared_len > (2 ** 22): + return web.HTTPInternalServerError(text = '') + stream = stream[:declared_len] + + ext = get_img_type(stream) + if ext is None: + return web.HTTPInternalServerError(text = '') + + try: + backend.user_service.save_avatar(user, stream, ext) + except Exception: + traceback.print_exc() + return web.HTTPInternalServerError(text = '') + avatar_sync.refresh_avatar(backend, user) + + filename_raw = ymsg_data.get(b'27') + filename = util.misc.arbitrary_decode(filename_raw) if filename_raw else 'im.{}'.format(ext) + try: + filename = Path(filename).name + except Exception: + filename = 'im.{}'.format(ext) + + try: + lifetime = int(util.misc.arbitrary_decode(ymsg_data.get(b'38') or b'604800')) + except ValueError: + lifetime = 604800 + expiry = str(int(time.time()) + lifetime) + + url = yahoo_avatar_url(user) + if url is None or yahoo_avatar_checksum(user) is None: + return web.HTTPInternalServerError(text = '') + + for bs_self in backend.util_get_sessions_by_user(user): + bs_self.evt.ymsg_on_friend_icon_file_transfer(user.username, user.username, url.decode('utf-8'), filename, expiry) + avatar_sync.push_avatar_change(backend, user) + + return web.Response(status = 200, body = b'\x00\x00\x00\x00', content_type = 'text/html', charset = 'UTF-8') + def _get_tmp_file_storage_path(token: str) -> Path: return Path('storage/file') / token +def _get_cookie(req: web.Request, name: str) -> Optional[str]: + value = req.cookies.get(name) + if value: + return value + for part in (req.headers.get('Cookie') or '').split(';'): + key, sep, val = part.strip().partition('=') + if sep and key == name: + return val + return None + +def _resolve_user(req: web.Request, backend: Backend) -> Optional[Any]: + y_cookie = _get_cookie(req, 'Y') + t_cookie = _get_cookie(req, 'T') + + (yahoo_id, bs) = _parse_cookies(req, backend, y = y_cookie or '', t = t_cookie or '') + if bs is not None and yahoo_id is not None: + return bs.user + + if not t_cookie: + return None + qs = parse_qs(t_cookie, keep_blank_values = True) + token = None + for key in ('z', 'sk', 'd'): + if qs.get(key) and qs[key][0]: + token = qs[key][0] + break + if not token: + return None + + tpl = backend.login_auth_service.get_token('ymsg/cookie', token) + if not tpl: + return None + user = backend._load_user_record(tpl[0]) + if user is None or not backend.util_get_sessions_by_user(user): + return None + return user + def _parse_cookies( req: web.Request, backend: Backend, y: Optional[str] = None, t: Optional[str] = None, ) -> Tuple[Optional[str], Optional[BackendSession]]: @@ -466,7 +657,7 @@ def _parse_cookies( return (backend.auth_service.get_token('ymsg/cookie', y_cookie or ''), backend.auth_service.get_token('ymsg/cookie', t_cookie or '')) -def _login(req: web.Request, username: str, pwd: str, lifetime: int = 86400) -> Optional[Tuple[str, datetime]]: +def _login(req: web.Request, username: str, pwd: str, lifetime: int = TOKEN_LIFETIME) -> Optional[Tuple[str, datetime]]: backend: Backend = req.app['backend'] uuid_val = backend.user_service.login_with_username(username, pwd) if uuid_val is None: diff --git a/front/ymsg/misc.py b/front/ymsg/misc.py index cc7ab7a..70037c5 100644 --- a/front/ymsg/misc.py +++ b/front/ymsg/misc.py @@ -4,10 +4,11 @@ from enum import IntEnum from util.misc import DefaultDict, MultiDict, arbitrary_encode from core.backend import BackendSession -from core.models import Substatus +from core.models import Contact, Substatus, User, UserStatus -import settings +import settings, binascii, struct, secrets +TOKEN_LIFETIME = int(getattr(settings, 'YMSG_TOKEN_LIFETIME', 60 * 60 * 24 * 30)) class YMSGService(IntEnum): LogOn = 0x01 LogOff = 0x02 @@ -21,7 +22,9 @@ class YMSGService(IntEnum): AddIgnore = 0x11 PingConfiguration = 0x12 SystemMessage = 0x14 + ClientStats = 0x15 SkinName = 0x15 + ClientAlertStats = 0x16 ClientHostStats = 0x16 MassMessage = 0x17 ConfInvite = 0x18 @@ -31,38 +34,59 @@ class YMSGService(IntEnum): ConfAddInvite = 0x1C ConfMsg = 0x1D MessageV2 = 0x27 - AvatarOld = 0xBD - Avatar6 = 0xC1 - Avatar = 0xC7 FileTransfer = 0x46 VoiceChat = 0x4A Notify = 0x4B Handshake = 0x4C P2PFileXfer = 0x4D - P2PFileXfer8 = 0xDC - P2PPhotoSharing = 0xD2 PeerToPeer = 0x4F VideoChat = 0x50 AuthResp = 0x54 List = 0x55 + PreLoginData = 0x55 Auth = 0x57 FriendAdd = 0x83 FriendRemove = 0x84 Ignore = 0x85 ContactDeny = 0x86 GroupRename = 0x89 + KeepAlive = 0x8A Ping = 0x8A ChatJoin = 0x96 + ChatPing = 0xA1 + FriendIcon = 0xBD + AvatarOld = 0xBD + FriendIconDownload = 0xBE + DisplayTypeChanged = 0xC1 + Avatar6 = 0xC1 + FriendIconFileTransfer = 0xC2 IsInvisible = 0xC5 StatusUpdate = 0xC6 - StatusUpdate2 = 0xF0 - # `static var YES_CHAT_PING = 161;` 161 = 0xA1 - # Yahoo! Messenger 9.0's `desktopHub` SWF seems to list a lot of YMSG service codes and field defs in its code. :p - ChatPing = 0xA1 + DisplayImagePrefs = 0xC7 + Avatar = 0xC7 + Audible = 0xD0 + IMPanelFeature = 0xD2 + P2PPhotoSharing = 0xD2 + IMSession = 0xD4 ChatSession = 0xD4 + BuddyAuthorize = 0xD6 + PhotoAdd = 0xD7 + PhotoSelect = 0xD8 + PhotoFileRequest = 0xDA + FileTransferInvite = 0xDC + P2PFileXfer8 = 0xDC + PeerSetup = 0xDD + PeerInit = 0xDE ContactRegroup = 0xE7 + Preference = 0xEF + BuddyInfo = 0xF0 + StatusUpdate2 = 0xF0 + BuddyList = 0xF1 NewBuddyList = 0xF1 - # Documented by the Yahsmosis project (https://www.autoitscript.com/forum/topic/142448-help-with-yahomosis/) - this appears to be used when a protocol-level error occurs (protocol version "cloaking", bad `Y`/`T` cookies, invalid Yahoo ID, invalid key/value pairs, etc.). Unsure what protocol version this was first placed into or how far back in the protocol version Yahoo's servers decided to send this on (A Wireshark capture indicates as far back as YMSG12) + MessageAck = 0xFB + SmsMessage = 0x2EA + MobileSetup = 0x2ED + # Documented by the Yahsmosis project (https://www.autoitscript.com/forum/topic/142448-help-with-yahomosis/) - this appears to be used when a protocol-level error occurs ProtocolError = 0x07D1 class YMSGStatus(IntEnum): @@ -85,9 +109,11 @@ class YMSGStatus(IntEnum): Invisible = 0x0000000C Bad = 0x0000000D Locked = 0x0000000E + Ack = 0x00000012 Typing = 0x00000016 Custom = 0x00000063 Idle = 0x000003E7 + CmdSentAck = 0x000003E8 WebLogin = 0x5A55AA55 Offline = 0x5A55AA56 LoginError = 0xFFFFFFFF @@ -223,3 +249,102 @@ def split_to_chunks(s: str, count: int) -> List[str]: i += count return final + +def build_photo_notify_packet( + sender: str, recipient: str, photo_id: bytes, *, + name: bytes | None = None, thumbnail: bytes | None = None, url: bytes | None = None, +) -> Iterable[EncodedYMSG]: + kvs = MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(recipient)), + (b'245', photo_id), + ]) # type: KVSType + if name is not None: kvs.add(b'246', name) + if url is not None: kvs.add(b'20', url) + if thumbnail is not None: kvs.add(b'267', thumbnail) + yield (YMSGService.PhotoAdd, YMSGStatus.BRB, kvs) + +def build_photo_relay_packet( + sender: str, recipient: str, photo_id: bytes, token: bytes, *, + relay_host: bytes, filesize: bytes | None = None, status: YMSGStatus = YMSGStatus.BRB, +) -> Iterable[EncodedYMSG]: + kvs = MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(recipient)), + (b'249', b'3'), + ]) # type: KVSType + if status is YMSGStatus.Ack: + kvs.add(b'250', relay_host) + kvs.add(b'251', token) + kvs.add(b'245', photo_id) + kvs.add(b'248', b'2') + if filesize is not None: kvs.add(b'28', filesize) + if status is YMSGStatus.Ack: kvs.add(b'253', photo_id) + kvs.add(b'276', token) + yield (YMSGService.PhotoFileRequest, status, kvs) + +AVATAR_URL_TEMPLATE = 'http://{host}/avatar/{uuid}/im' +BUDDY_INFO_BUILD = b'3017751' + +def _avatar_raw(avatar: str) -> bytes: + try: + return bytes.fromhex(avatar) + except ValueError: + return avatar.encode('utf-8') + +def yahoo_avatar_checksum(user: User) -> bytes | None: + avatar = getattr(user, 'avatar', None) + if not avatar: + return None + crc = binascii.crc32(_avatar_raw(avatar)) & 0xFFFFFFFF + return str(struct.unpack('i', struct.pack('I', crc))[0]).encode('utf-8') + +def yahoo_avatar_url(user: User) -> bytes | None: + if not getattr(user, 'avatar', None): + return None + return AVATAR_URL_TEMPLATE.format(host = settings.USERSTORAGE_HOST, uuid = user.uuid).encode('utf-8') + +def _buddy_info_entry(kvs: KVSType, status: UserStatus, head: User, *, wrapped: bool = True) -> None: + is_offlineish = status.is_offlineish() + if wrapped: + kvs.add(b'300', b'315') + kvs.add(b'7', arbitrary_encode(head.username)) + kvs.add(b'241', b'0') + if is_offlineish or not status.message: + kvs.add(b'10', str(int(YMSGStatus.Available if is_offlineish else YMSGStatus.FromSubstatus(status.substatus))).encode('utf-8')) + kvs.add(b'19', b'') + kvs.add(b'47', b'0') + else: + kvs.add(b'10', str(int(YMSGStatus.Custom)).encode('utf-8')) + kvs.add(b'19', arbitrary_encode(status.message)) + kvs.add(b'47', (b'1' if status.substatus is not Substatus.Online else b'0')) + kvs.add(b'187', b'0') + kvs.add(b'283', b'0') + kvs.add(b'60', b'0') + kvs.add(b'244', BUDDY_INFO_BUILD) + checksum = yahoo_avatar_checksum(head) + kvs.add(b'213', (b'2' if checksum is not None else b'0')) + kvs.add(b'198', b'0') + if checksum is not None: + kvs.add(b'192', checksum) + if wrapped: + kvs.add(b'301', b'315') + +def build_user_login_v16(contact: Contact) -> KVSType: + kvs = MultiDict() # type: KVSType + _buddy_info_entry(kvs, contact.status, contact.head, wrapped = False) + return kvs + +def build_buddy_info_v16(contacts: Iterable[Contact]) -> KVSType: + kvs = MultiDict([(b'241', b'0')]) # type: KVSType + contacts = list(contacts) + if not contacts: + return kvs + kvs.add(b'302', b'315') + for c in contacts: + _buddy_info_entry(kvs, c.status, c.head) + kvs.add(b'303', b'315') + return kvs + +def gen_relay_token() -> str: + return secrets.token_hex(20) \ No newline at end of file diff --git a/front/ymsg/pager.py b/front/ymsg/pager.py index f6faf26..dadecf5 100644 --- a/front/ymsg/pager.py +++ b/front/ymsg/pager.py @@ -1,5 +1,5 @@ from typing import Optional, Dict, Any, Tuple -import datetime, asyncio, time, settings, base64, util, secrets, json +import datetime, asyncio, time, settings, base64, util, secrets, json, traceback from urllib.parse import parse_qs from disposable_email_domains import blocklist as disposable_emails @@ -14,10 +14,11 @@ from core.models import ( ) from core.client import Client from core.auth import GenTokenStr +from core.alerts import Alert from .ymsg_ctrl import YMSGCtrlBase from .misc import YMSGService, YMSGStatus, split_to_chunks -from . import misc, Y64 +from . import misc, Y64, avatar_sync # "Pre" because it's needed before BackendSession is created. # Comment out session ID stuff as that'll have to be reworked with account usernames being a thing @@ -55,6 +56,7 @@ class YMSGCtrlPager(YMSGCtrlBase): self.client = Client('ymsg', 'YMSG{}'.format(str(args[0])), self.client.via) self.dialect = int(args[0]) + self.set_dialect(self.dialect) self.send_reply(YMSGService.Handshake, YMSGStatus.BRB, 0, None) def _y_0057(self, *args: Any) -> None: @@ -64,8 +66,8 @@ class YMSGCtrlPager(YMSGCtrlBase): # Yahoo for Vista & 9+ doesn't send SERVICE_HANDSHAKE apparently, so I'm adding this here as well self.client = Client('ymsg', 'YMSG{}'.format(str(args[0])), self.client.via) self.dialect = int(args[0]) + self.set_dialect(self.dialect) - print(f'Shit: {self.dialect}') yahoo_data = args[4] # type: MultiDict[bytes, bytes] yahoo_id = yahoo_data.get(b'1') @@ -305,19 +307,80 @@ class YMSGCtrlPager(YMSGCtrlBase): self.close() return + avatar_sync.note_login(self.backend, user) + self._update_buddy_list(cached_y = cached_y, cached_t = cached_t, on_login = True) - if self.dialect >= 10: + if self.dialect >= 16: + self.send_reply(YMSGService.PingConfiguration, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'143', b'60'), + (b'144', b'1'), + ])) + self.send_reply(YMSGService.BuddyInfo, YMSGStatus.Available, self.sess_id, misc.build_buddy_info_v16(self._online_contacts(user))) + self._announce_own_icon(user) + elif self.dialect >= 10: kvs = MultiDict([ (b'143', b'60'), (b'144', b'13') ]) # type: MultiDict[bytes, bytes] self.send_reply(YMSGService.PingConfiguration, YMSGStatus.Available, self.sess_id, kvs) + self._send_pending_requests(user) self._get_oims(user) if self.backend.notify_maintenance: bs.evt.on_maintenance_message(None, self.backend.maintenance_mins) + + def _announce_own_icon(self, user: User) -> None: + checksum = misc.yahoo_avatar_checksum(user) + if checksum is None: + return + self.send_reply(YMSGService.FriendIcon, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(user.username)), + (b'5', arbitrary_encode(user.username)), + (b'192', checksum), + ])) + + def _online_contacts(self, user: User) -> list[Contact]: + detail = user.detail + assert detail is not None + return [ + c for c in detail.contacts.values() + if c.lists & ContactList.FL and not c.lists & ContactList.BL and not c.status.is_offlineish() + ] + + def _send_prelogin_data(self, user: User, cached_y: Optional[str], cached_t: Optional[str]) -> None: + tpl = self._refresh_cookies() + if tpl is not None: + (y_cookie, t_cookie, _, _) = tpl + else: + y_cookie = cached_y or '' + t_cookie = cached_t or '' + + username = arbitrary_encode(user.username) + kvs = MultiDict([ + (b'2', username), + (b'3', username), + (b'89', username), + (b'216', b''), + (b'254', b''), + (b'213', (b'2' if misc.yahoo_avatar_checksum(user) is not None else b'0')), + (b'208', arbitrary_encode(t_cookie)), + (b'93', str(misc.TOKEN_LIFETIME - 1).encode('utf-8')), + (b'59', arbitrary_encode('Y\t{}; path=/;'.format(y_cookie))), + (b'219', b''), + (b'59', arbitrary_encode('T\t{}; path=/;'.format(t_cookie))), + (b'219', b''), + (b'300', b'444'), + (b'301', b'444'), + ]) # type: MultiDict[bytes, bytes] + self.send_reply(YMSGService.PreLoginData, YMSGStatus.Available, self.sess_id, kvs) + + def _send_preference(self) -> None: + self.send_reply(YMSGService.Preference, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'302', b'312'), + (b'303', b'312'), + ])) # State = Live @@ -364,10 +427,27 @@ class YMSGCtrlPager(YMSGCtrlBase): return + def _y_008a(self, *args: Any) -> None: + # SERVICE_PING (0x8a) + if self.dialect >= 16: + self.send_reply(YMSGService.KeepAlive, YMSGStatus.BRB, self.sess_id, None) + return + bs = self.bs + assert bs is not None + self.send_reply(YMSGService.Ping, YMSGStatus.Available, self.sess_id, MultiDict([ + (b'1', arbitrary_encode(bs.user.username)), + ])) + def _y_0015(self, *args: Any) -> None: - # SERVICE_SKINNAME (0x15); used for IMVironments - # Also happens when enabling/disabling Yahoo Helper. - return + # SERVICE_SKINNAME (0x15); used for IMVironments. On YMSG16 this is "Client Stats" + # (key 211 telemetry), acknowledged with an empty Ack. + if self.dialect >= 16: + self.send_reply(YMSGService.ClientStats, YMSGStatus.Ack, self.sess_id, None) + + def _y_0002(self, *args: Any) -> None: + # SERVICE_LOGOFF (0x02); empty request, empty Ack, then tear down. + self.send_reply(YMSGService.LogOff, YMSGStatus.Ack, self.sess_id, None) + self.close() def _y_0083(self, *args: Any) -> None: # SERVICE_FRIENDADD (0x83); add a friend to your contact list @@ -388,18 +468,35 @@ class YMSGCtrlPager(YMSGCtrlBase): old_lists = None action_group_refresh = False - add_request_response = MultiDict([ - (b'1', arbitrary_encode(yahoo_id)), - (b'7', arbitrary_encode(contact_yahoo_id)), - (b'65', arbitrary_encode(buddy_group)) - ]) # type: MultiDict[bytes, bytes] + def reply(err: bytes, *, pending: bool = False) -> None: + if self.dialect >= 16: + kvs = MultiDict([ + (b'1', arbitrary_encode(yahoo_id)), + (b'241', b'0'), + (b'65', arbitrary_encode(buddy_group)), + (b'7', arbitrary_encode(contact_yahoo_id)), + (b'216', b''), + (b'254', b''), + (b'14', arbitrary_encode(message)), + (b'97', b'1'), + (b'66', err), + ]) # type: MultiDict[bytes, bytes] + if pending: + kvs.add(b'223', b'1') + else: + kvs = MultiDict([ + (b'1', arbitrary_encode(yahoo_id)), + (b'7', arbitrary_encode(contact_yahoo_id)), + (b'65', arbitrary_encode(buddy_group)), + (b'66', err), + ]) + self.send_reply(YMSGService.FriendAdd, YMSGStatus.BRB, self.sess_id, kvs) # Yahoo! Messenger has a function that lets you add people by email address (a.k.a. stripping the "@domain.tld" part of the address and # filling that out in the "Yahoo! ID" section of the contact add dialog). Treat as is. contact_uuid = backend.util_get_uuid_from_username(contact_yahoo_id) if contact_uuid is None: - add_request_response.add(b'66', b'3') # User doesn't exist in database - self.send_reply(YMSGService.FriendAdd, YMSGStatus.BRB, self.sess_id, add_request_response) + reply(b'3') # User doesn't exist in database return bs = self.bs @@ -417,13 +514,11 @@ class YMSGCtrlPager(YMSGCtrlBase): if contact._groups: for group_other in contact._groups.copy(): if detail._groups_by_id[group_other.id].name == buddy_group: - add_request_response.add(b'66', b'2') # Contact already in group - self.send_reply(YMSGService.FriendAdd, YMSGStatus.BRB, self.sess_id, add_request_response) + reply(b'2') # Contact already in group return else: if buddy_group == '(No Group)': - add_request_response.add(b'66', b'2') - self.send_reply(YMSGService.FriendAdd, YMSGStatus.BRB, self.sess_id, add_request_response) + reply(b'2') return if buddy_group != '(No Group)': @@ -444,14 +539,14 @@ class YMSGCtrlPager(YMSGCtrlBase): adder_id = yahoo_id, needs_notify = True, )[0] except error.ContactListIsFull: - add_request_response.add(b'66', b'6') # Contact list full - self.send_reply(YMSGService.FriendAdd, YMSGStatus.BRB, self.sess_id, add_request_response) + reply(b'6') # Contact list full return except: - add_request_response.add(b'66', b'1') # General failure - self.send_reply(YMSGService.FriendAdd, YMSGStatus.BRB, self.sess_id, add_request_response) + reply(b'1') # General failure return + self._clear_pending(user, contact_new) + if (contact_new is not None and contact is None) or (old_lists is not None and (not old_lists & ContactList.FL and not old_lists & ContactList.BL)): contact_struct = MultiDict([ (b'8', (b'1' if not contact_new.status.is_offlineish() else b'0')), @@ -460,8 +555,7 @@ class YMSGCtrlPager(YMSGCtrlBase): self.send_reply(YMSGService.ContactNew, YMSGStatus.BRB, self.sess_id, contact_struct) - add_request_response.add(b'66', b'0') # Success - self.send_reply(YMSGService.FriendAdd, YMSGStatus.BRB, self.sess_id, add_request_response) + reply(b'0', pending = not (contact_new.lists & ContactList.RL)) try: # TODO: Moving/copying contacts to groups if len(contact_new._groups) >= 1 or (contact_new._groups and buddy_group == '(No Group)'): action_group_refresh = True @@ -480,13 +574,13 @@ class YMSGCtrlPager(YMSGCtrlBase): if group is not None: bs.me_group_contact_add(group.id, contact_new.head.uuid) - if action_group_refresh: self._update_buddy_list() + if action_group_refresh: self._update_buddy_list(after_login = True) except error.ContactAlreadyOnContactList: # Ignore, because this condition was checked earlier, so the only way this # can happen is if the the contact list gets in an inconsistent state. # (I.e. contact is not on FL, but still part of groups.) pass - + def _y_0086(self, *args: Any) -> None: # SERVICE_CONTACTDENY (0x86); deny a contact request backend = self.backend @@ -502,6 +596,9 @@ class YMSGCtrlPager(YMSGCtrlBase): bs = self.bs assert bs is not None bs.me_contact_deny(adder_uuid, deny_message, addee_id = yahoo_id) + ctc = bs.user.detail.contacts.get(adder_uuid) if bs.user.detail is not None else None + if ctc is not None: + self._clear_pending(bs.user, ctc) def _y_0089(self, *args: Any) -> None: # SERVICE_GROUPRENAME (0x89); rename a contact group @@ -655,25 +752,359 @@ class YMSGCtrlPager(YMSGCtrlBase): YMSGService.UserStat, bs.front_data.get('ymsg_status') or YMSGStatus.FromSubstatus(user.status.substatus), self.sess_id, self._gen_multi_user_status_dict(user), ) - + + def _y_00d7(self, *args: Any) -> None: + # SERVICE_PHOTOADD (0xd7); status Ack (18) is the receipt for an offer we relayed + bs = self.bs + assert bs is not None + user = bs.user + + status = args[2] + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + photo_id = yahoo_data.get(b'245') + if recipient is None or photo_id is None: + return + + if status == YMSGStatus.Ack: + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_photo_ack(user.username, recipient, photo_id) + return + + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_photo_add( + user.username, recipient, photo_id, + yahoo_data.get(b'246'), yahoo_data.get(b'267'), yahoo_data.get(b'20'), + ) + + def _y_00d8(self, *args: Any) -> None: + # SERVICE_PHOTOSELECT (0xd8); which photo in the tray is currently displayed. + # Key 194: 0 deselect, 1 select, 2 remove. + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + photo_id = yahoo_data.get(b'245') + if recipient is None or photo_id is None: + return + + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_photo_select( + user.username, recipient, photo_id, yahoo_data.get(b'194') or b'0', + ) + + def _y_00da(self, *args: Any) -> None: + # SERVICE_PHOTOFILEREQUEST (0xda); status Ack (18) is the owner answering with token + size + backend = self.backend + bs = self.bs + assert bs is not None + user = bs.user + + status = args[2] + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + photo_id = yahoo_data.get(b'245') + if recipient is None or photo_id is None: + return + + relay_host = settings.TARGET_IP.encode('utf-8') + + if status == YMSGStatus.Ack: + token = yahoo_data.get(b'251') or yahoo_data.get(b'276') + if token is None: + return + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_photo_relay( + user.username, recipient, photo_id, token, + relay_host = relay_host, filesize = yahoo_data.get(b'28'), ack = True, + ) + return + + token = misc.gen_relay_token().encode('utf-8') + backend.auth_service.create_token('ymsg/relay', [user.uuid, recipient], token = token.decode('utf-8'), lifetime = 3600) + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_photo_relay( + user.username, recipient, photo_id, token, + relay_host = relay_host, filesize = None, ack = False, + ) + def _y_00d2(self, *args: Any) -> None: # photo sharing invite, stub for now pass def _y_00dc(self, *args: Any) -> None: - # P2P file transfers on newer version, stub for now - pass + # SERVICE_FILETRANSFERINVITE (0xdc). Key 222 is the mode: + # 1 invite, 3 accept, 4 decline/cancel. + # 265 is the p2p cookie (always '$$'-suffixed), 266 the file count, and the + # filename/filesize pair is wrapped in a 302=268 … 303=268 list block. + # 267 carries a base64 thumbnail for image transfers. + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + cookie = yahoo_data.get(b'265') + if recipient is None or cookie is None: + return + + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_ft_invite(user.username, recipient, cookie, yahoo_data) + def _y_00dd(self, *args: Any) -> None: + # SERVICE_PEERSETUP (0xdd); sender publishes the relay endpoint (250) and path + # token (251) for an accepted transfer. + backend = self.backend + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + cookie = yahoo_data.get(b'265') + if recipient is None or cookie is None: + return + + token = yahoo_data.get(b'251') or misc.gen_relay_token().encode('utf-8') + backend.auth_service.create_token( + 'ymsg/relay', [user.uuid, recipient], token = token.decode('utf-8'), lifetime = 3600, + ) + + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_ft_setup( + user.username, recipient, cookie, + filename = yahoo_data.get(b'27') or b'', + relay_host = settings.TARGET_IP.encode('utf-8'), + peer_path = token, + transfer_type = yahoo_data.get(b'249') or b'3', + ) + + def _y_00de(self, *args: Any) -> None: + # SERVICE_PEERINIT (0xde); receiver started pulling from the relay, or cancelled (status -1 / key 66 == -1) + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + cookie = yahoo_data.get(b'265') + if recipient is None or cookie is None: + return + + cancelled = (args[2] == YMSGStatus.LoginError or yahoo_data.get(b'66') == b'-1') + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_ft_init(user.username, recipient, cookie, yahoo_data, cancelled = cancelled) + def _y_00bd(self, *args: Any) -> None: - pass - + # SERVICE_PICTURE_CHECKSUM / Friend Icon (0xbd); the client announces its icon after an upload, to + # everyone (`1, 212, 192`) or to one buddy (`1, 5, 212, 192`). The original answers each with a + # `4=me, 5=me` notify to the sender and relays to the buddies. + backend = self.backend + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + avatar_sync.refresh_avatar(backend, user) + + checksum = misc.yahoo_avatar_checksum(user) + if checksum is None: + return + + for bs_self in backend.util_get_sessions_by_user(user): + bs_self.evt.ymsg_on_friend_icon(user.username, user.username, checksum) + + recipient = self._peer_id(yahoo_data) + if recipient is not None: + targets = [recipient] + else: + if avatar_sync.recently_pushed(user, checksum): + return + targets = [head.username for head in avatar_sync.icon_recipients(user)] + + for target in targets: + if target.lower() == user.username.lower(): + continue + for bs_other in self._peer_sessions(target): + bs_other.evt.ymsg_on_friend_icon(user.username, target, checksum) + + def _y_00be(self, *args: Any) -> None: + # SERVICE_PICTURE / Friend Icon Download (0xbe); `1=me, 5=owner, 13=1` asks for an icon, and the + # reply is `4=owner, 5=me, 13=2, 20=url, 192=checksum`. Answered by the server out of the + # avatar store, so icons stay available while their owner is offline. + backend = self.backend + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + if arbitrary_decode(yahoo_data.get(b'13') or b'1') != '1': + return + + target = self._peer_id(yahoo_data) + if target is None: + return + target_uuid = backend.util_get_uuid_from_username(target) + if target_uuid is None: + return + target_head = backend._load_user_record(target_uuid) + if target_head is None: + return + + avatar_sync.refresh_avatar(backend, target_head) + + url = misc.yahoo_avatar_url(target_head) + checksum = misc.yahoo_avatar_checksum(target_head) + if url is None or checksum is None: + return + + self.send_reply(YMSGService.FriendIconDownload, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(target)), + (b'5', arbitrary_encode(user.username)), + (b'13', b'2'), + (b'20', url), + (b'192', checksum), + ])) + def _y_00c1(self, *args: Any) -> None: - pass + # SERVICE_PICTURE_UPDATE / Display Type Changed (0xc1); `1=me, 5=buddy, 206=flag` + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + icon_flag = yahoo_data.get(b'206') + recipient = self._peer_id(yahoo_data) + if icon_flag is None or recipient is None: + return + + for bs_other in self._peer_sessions(recipient): + relay = getattr(bs_other.evt, 'ymsg_on_friend_icon_flag', None) + if relay is not None: + relay(user.username, recipient, icon_flag) def _y_00c7(self, *args: Any) -> None: - # for changing avatars, ignore for now - pass - + # SERVICE_AVATAR_UPDATE / Display Image Prefs (0xc7); `3=me, 213=flag` is answered with + # `4=me, 213=flag` + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + avatar_flag = yahoo_data.get(b'213') or b'2' + bs.front_data['ymsg_avatar_flag'] = avatar_flag + + self.send_reply(YMSGService.DisplayImagePrefs, YMSGStatus.Available, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(user.username)), + (b'213', avatar_flag), + ])) + + def _y_00d0(self, *args: Any) -> None: + # SERVICE_AUDIBLE (0xd0). 230 is the audible ID, 231 the spoken text used as the + # fallback IM body, 232 the SHA-1 of the .swf the client fetches + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + audible_id = yahoo_data.get(b'230') + if recipient is None or audible_id is None: + return + + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_audible( + user.username, recipient, audible_id, + yahoo_data.get(b'231') or b'', yahoo_data.get(b'232') or b'', + ) + + def _y_00d2(self, *args: Any) -> None: + # SERVICE_IMPANELFEATURE (0xd2); IM-window feature panel state. + # 221 is the feature id, 222 the state (1 open, 2 peer-acknowledged, 5 closed). + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + feature = yahoo_data.get(b'221') + state = yahoo_data.get(b'222') + if None in (recipient, feature, state): + return + + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_im_panel_feature(user.username, recipient or '', feature or b'1', state or b'1') + + def _y_00d4(self, *args: Any) -> None: + # SERVICE_IMSESSION (0xd4); IM window opened/closed against a buddy (key 13). + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + if recipient is None: + return + + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_im_session(user.username, recipient, yahoo_data.get(b'13') or b'1') + + def _y_00d6(self, *args: Any) -> None: + # SERVICE_BUDDYAUTHORIZE (0xd6); our answer to a contact request: `1=me, 5=requester, 13=1 accept / 2 deny, 14=message` + backend = self.backend + bs = self.bs + assert bs is not None + user = bs.user + detail = user.detail + assert detail is not None + + yahoo_data = args[4] + buddy = self._peer_id(yahoo_data) or self._peer_id(yahoo_data, b'4') + if buddy is None: + return + buddy_uuid = backend.util_get_uuid_from_username(buddy) + if buddy_uuid is None: + return + buddy_head = backend._load_user_record(buddy_uuid) + if buddy_head is None: + return + + accepted = (yahoo_data.get(b'13') or b'1') == b'1' + message = arbitrary_decode(yahoo_data.get(b'14') or b'') + + try: + if accepted: + for bs_other in backend.util_get_sessions_by_user(buddy_head): + bs_other.evt.ymsg_on_buddy_response(user, True, '') + bs.me_contact_add(buddy_uuid, ContactList.AL, name = buddy) + else: + bs.me_contact_deny(buddy_uuid, message, addee_id = user.username) + except error.ClientError: + pass + + # Answered, so it no longer shows up at login + ctc = detail.contacts.get(buddy_uuid) + if ctc is not None: + self._clear_pending(user, ctc) + + def _y_00fb(self, *args: Any) -> None: + # SERVICE_MESSAGEACK (0xfb); a client acknowledging a message it received: + # `1=me, 5=original sender, 302=430, 430=id, 303=430` + bs = self.bs + assert bs is not None + user = bs.user + + yahoo_data = args[4] + sender = self._peer_id(yahoo_data) + msg_id = yahoo_data.get(b'430') + if sender is None or msg_id is None: + return + + for bs_other in self._peer_sessions(sender): + bs_other.evt.ymsg_on_message_ack(user.username, sender, msg_id) + def _y_0055(self, *args: Any) -> None: # SERVICE_LIST (0x55); send a user's buddy list @@ -893,23 +1324,27 @@ class YMSGCtrlPager(YMSGCtrlBase): return def _y_004d(self, *args: Any) -> None: - # SERVICE_P2PFILEXFER (0x4d); initiate P2P file transfer. Due to this service being present - # in 3rd-party libraries; we can implement it here - - yahoo_data = args[4] # type: MultiDict[bytes, bytes] - - backend = self.backend + # SERVICE_P2PFILEXFER / "Send Data Thru" (0x4d) bs = self.bs assert bs is not None + user = bs.user - contact_id = arbitrary_decode(yahoo_data.get(b'5') or b'') - contact_uuid = backend.util_get_uuid_from_username(contact_id) - if contact_uuid is None: + yahoo_data = args[4] + recipient = self._peer_id(yahoo_data) + if recipient is None: return - for bs_other in backend._sc.iter_sessions(): - if bs_other.user.uuid == contact_uuid: - bs_other.evt.ymsg_on_xfer_init(self.sess_id, yahoo_data) + notify_type = yahoo_data.get(b'49') + if notify_type == b'IMVIRONMENT': + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_imvironment( + user.username, recipient, + yahoo_data.get(b'63') or b';0', yahoo_data.get(b'64') or b'0', + ) + return + + for bs_other in self._peer_sessions(recipient): + bs_other.evt.ymsg_on_xfer_init(self.sess_id, yahoo_data) def _y_0018(self, *args: Any) -> None: # SERVICE_CONFINVITE (0x18); send a conference invite to one or more people @@ -1058,15 +1493,17 @@ class YMSGCtrlPager(YMSGCtrlBase): cs = self._get_chat_session(yahoo_id, chat) if cs is not None: cs.close() - - # Other functions - + def _message_common(self, yahoo_data: MultiDict[bytes, bytes], contact_yahoo_id: Optional[str]) -> None: backend = self.backend bs = self.bs assert bs is not None user = bs.user + # Key 429 is the client's id for this message, key 1 the id it is logged in as + msg_id = yahoo_data.get(b'429') + sender_id = arbitrary_decode(yahoo_data.get(b'1') or b'') or user.username + if contact_yahoo_id is not None and contact_yahoo_id.lower() == 'yahoohelper': yhlper_msg_dict = MultiDict([ (b'5', yahoo_data.get(b'1') or b''), @@ -1086,12 +1523,26 @@ class YMSGCtrlPager(YMSGCtrlBase): yhlper_msg_dict.add(b'206', yahoo_data.get(b'206') or b'') self.send_reply(YMSGService.Message, YMSGStatus.BRB, self.sess_id, yhlper_msg_dict) + self._begin_ack(contact_yahoo_id, sender_id, msg_id, wait_for_recipient = False) return contact_uuid = backend.util_get_uuid_from_username(contact_yahoo_id or '') if contact_uuid is None: return + if self._is_duplicate_message(contact_yahoo_id or '', msg_id): + if msg_id is not None and msg_id not in self._pending_acks(): + self._begin_ack(contact_yahoo_id or '', sender_id, msg_id, wait_for_recipient = False) + return + + self._deliver_message(yahoo_data, contact_uuid) + self._begin_ack(contact_yahoo_id or '', sender_id, msg_id, wait_for_recipient = True) + + def _deliver_message(self, yahoo_data: MultiDict[bytes, bytes], contact_uuid: str) -> None: + bs = self.bs + assert bs is not None + user = bs.user + try: cs, evt = self._get_private_chat_with(contact_uuid) if None not in (cs, evt): @@ -1125,6 +1576,153 @@ class YMSGCtrlPager(YMSGCtrlBase): except error.ContactNotOnContactList: pass + ACK_MIN_DELAY = 0.2 + ACK_FALLBACK_DELAY = 2.5 + + def _pending_acks(self) -> Dict[bytes, Dict[str, Any]]: + bs = self.bs + assert bs is not None + return bs.front_data.setdefault('ymsg_pending_acks', {}) + + def _recipient_acks(self, recipient: str) -> bool: + for bs_other in self._peer_sessions(recipient): + ctrl = getattr(bs_other.evt, 'ctrl', None) + if bs_other.front_data.get('ymsg') and getattr(ctrl, 'dialect', 0) >= 16: + return True + return False + + def _begin_ack(self, recipient: str, sender_id: str, msg_id: Optional[bytes], *, wait_for_recipient: bool) -> None: + if msg_id is None: + return + loop = self.backend.loop + if wait_for_recipient and self._recipient_acks(recipient): + delay = self.ACK_FALLBACK_DELAY + else: + delay = self.ACK_MIN_DELAY + self._pending_acks()[msg_id] = { + 'recipient': recipient, + 'sender': sender_id, + 'at': loop.time(), + 'handle': loop.call_later(delay, self._send_ack, msg_id), + } + + def _on_recipient_ack(self, msg_id: bytes) -> None: + entry = self._pending_acks().get(msg_id) + if entry is None: + return + loop = self.backend.loop + entry['handle'].cancel() + remaining = max(0.0, self.ACK_MIN_DELAY - (loop.time() - entry['at'])) + entry['handle'] = loop.call_later(remaining, self._send_ack, msg_id) + + def _send_ack(self, msg_id: bytes) -> None: + try: + if self.bs is None or self.closed: + return + entry = self._pending_acks().pop(msg_id, None) + if entry is None: + return + self.send_reply(YMSGService.MessageAck, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(entry['recipient'])), + (b'5', arbitrary_encode(entry['sender'])), + (b'302', b'430'), + (b'430', msg_id), + (b'303', b'430'), + ])) + except Exception: + traceback.print_exc() + + def _is_duplicate_message(self, recipient: str, msg_id: Optional[bytes]) -> bool: + if msg_id is None: + return False + bs = self.bs + assert bs is not None + seen = bs.front_data.setdefault('ymsg_seen_msgs', {}) # type: Dict[Tuple[str, bytes], float] + now = time.monotonic() + for key in [k for (k, t) in seen.items() if now - t > 300]: + del seen[key] + key = (recipient.lower(), msg_id) + if key in seen: + return True + seen[key] = now + return False + + def _clear_pending(self, user: User, ctc: Contact) -> None: + if ctc.pending: + ctc.pending = False + self.backend._mark_modified(user, detail = user.detail) + + def _send_contact_request(self, adder: User, *, adder_id: Optional[str] = None, message: Optional[TextWithData] = None) -> None: + bs = self.bs + assert bs is not None + user_me = bs.user + + if self.dialect >= 16: + self.send_reply(YMSGService.BuddyAuthorize, YMSGStatus.NotAtHome, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(adder_id or adder.username)), + (b'5', arbitrary_encode(user_me.username)), + (b'241', b'0'), + (b'14', arbitrary_encode(message.text if message is not None else '')), + (b'216', b''), + (b'254', b''), + ])) + return + + contact_request_data = MultiDict([ + (b'1', arbitrary_encode(user_me.username)), + (b'3', arbitrary_encode(adder_id or adder.username)), + ]) # type: MultiDict[bytes, bytes] + + if message is not None: + contact_request_data.add(b'14', arbitrary_encode(message.text)) + if message.yahoo_utf8 is not None: + contact_request_data.add(b'97', arbitrary_encode(message.yahoo_utf8)) + + contact_request_data.add(b'15', arbitrary_encode(str(time.time()))) + + self.send_reply(YMSGService.ContactNew, YMSGStatus.NotAtHome, self.sess_id, contact_request_data) + + def _send_authorize_response(self, buddy: User, accepted: bool, message: str = '') -> None: + if self.dialect < 16: + return + bs = self.bs + assert bs is not None + self.send_reply(YMSGService.BuddyAuthorize, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(buddy.username)), + (b'5', arbitrary_encode(bs.user.username)), + (b'241', b'0'), + (b'14', arbitrary_encode(message)), + (b'13', (b'1' if accepted else b'2')), + ])) + + def _send_pending_requests(self, user: User) -> None: + detail = user.detail + if detail is None: + return + for ctc in list(detail.contacts.values()): + if not (ctc.lists & ContactList.RL and ctc.pending): + continue + if ctc.lists & (ContactList.FL | ContactList.AL | ContactList.BL): + self._clear_pending(user, ctc) + continue + self._send_contact_request(ctc.head) + + def _peer_sessions(self, yahoo_id: Optional[str]) -> list: + if not yahoo_id: + return [] + backend = self.backend + uuid = backend.util_get_uuid_from_username(yahoo_id) + if uuid is None: + return [] + head = backend._load_user_record(uuid) + if head is None: + return [] + return backend.util_get_sessions_by_user(head) + + def _peer_id(self, yahoo_data: Any, key: bytes = b'5') -> Optional[str]: + raw = yahoo_data.get(key) + return arbitrary_decode(raw) if raw is not None else None + def _get_private_chat_with(self, other_user_uuid: str) -> Tuple[ChatSession, 'ChatEventHandler']: bs = self.bs assert bs is not None @@ -1190,6 +1788,9 @@ class YMSGCtrlPager(YMSGCtrlBase): ignore_list = [c for c in cs if c.lists & ContactList.BL] if self.dialect >= 16: + if on_login: + self._send_prelogin_data(user, cached_y, cached_t) + self._send_preference() self.generate_buddy_list_assnew(user, detail, cs_fl, ignore_list) else: self.generate_buddy_list_assold(backend, user, detail, cs_fl, ignore_list, cached_y, cached_t) @@ -1197,7 +1798,7 @@ class YMSGCtrlPager(YMSGCtrlBase): if on_login: me_status_update(bs, YMSGStatus.Available) - if not after_login: + if not after_login and self.dialect < 16: self.send_reply(YMSGService.LogOn, YMSGStatus.Available, self.sess_id, self._gen_multi_user_status_dict(user)) def generate_buddy_list_assnew(self, user: User, detail: Any, cs_fl: list, ignore_list: list) -> None: @@ -1470,8 +2071,8 @@ class YMSGCtrlPager(YMSGCtrlBase): t_expiry = 0 try: - _, y_expiry = auth_service.create_token('ymsg/cookie', user.username, token=y_cookie, lifetime=86400) - _, t_expiry = auth_service.create_token('ymsg/cookie', self.bs, token=t_cookie, lifetime=86400) + _, y_expiry = auth_service.create_token('ymsg/cookie', user.username, token=y_cookie, lifetime=misc.TOKEN_LIFETIME) + _, t_expiry = auth_service.create_token('ymsg/cookie', self.bs, token=t_cookie, lifetime=misc.TOKEN_LIFETIME) except: return None @@ -1565,10 +2166,46 @@ def add_contact_status_to_data( data.add(b'19', arbitrary_encode(message)) is_away_message = (status.substatus is not Substatus.Online) data.add(b'47', str(int(is_away_message)).encode('utf-8')) - + + checksum = misc.yahoo_avatar_checksum(contact) + if checksum is not None and not is_offlineish: + data.add(b'213', b'2') + data.add(b'192', checksum) data.add(b'17', b'0') data.add(b'13', (b'0' if is_offlineish else b'1')) - + +def add_contact_status_to_data_v16(data: Any, status: UserStatus, contact: User) -> None: + is_offlineish = status.is_offlineish() + + data.add(b'241', b'0') + data.add(b'302', b'315') + data.add(b'300', b'315') + data.add(b'7', arbitrary_encode(contact.username)) + data.add(b'241', b'0') + + if is_offlineish or not status.message: + data.add(b'10', str(int(YMSGStatus.Available if is_offlineish else YMSGStatus.FromSubstatus(status.substatus))).encode('utf-8')) + data.add(b'19', b'') + data.add(b'47', b'0') + else: + data.add(b'10', str(int(YMSGStatus.Custom)).encode('utf-8')) + data.add(b'19', arbitrary_encode(status.message)) + data.add(b'47', str(int(status.substatus is not Substatus.Online)).encode('utf-8')) + + data.add(b'187', b'0') + data.add(b'283', b'0') + data.add(b'60', b'0') + data.add(b'244', b'3071031') + + checksum = misc.yahoo_avatar_checksum(contact) + data.add(b'213', (b'2' if checksum is not None else b'0')) + data.add(b'198', b'0') + if checksum is not None: + data.add(b'192', checksum) + + data.add(b'301', b'315') + data.add(b'303', b'315') + class BackendEventHandler(event.BackendEventHandler): __slots__ = ('loop', 'ctrl', 'dialect', 'sess_id', 'bs') @@ -1594,13 +2231,14 @@ class BackendEventHandler(event.BackendEventHandler): ]) # type: MultiDict[bytes, bytes] self.ctrl.send_reply(YMSGService.SystemMessage, YMSGStatus.BRB, self.sess_id, kvs) - def on_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None: - msg = message + def on_client_alert(self, alert: Alert) -> bool: + msg = alert.plain_with_link() kvs = MultiDict([ (b'14', msg.encode('utf-8')), (b'15', str(time.time()).encode('utf-8')), ]) # type: MultiDict[bytes, bytes] self.ctrl.send_reply(YMSGService.SystemMessage, YMSGStatus.BRB, self.sess_id, kvs) + return True def on_maintenance_boot(self) -> None: # No maintenance-specific booting packets known as of now. Use generic booting procedure. @@ -1622,6 +2260,19 @@ class BackendEventHandler(event.BackendEventHandler): if update_status or update_info_other: if not ctc.lists & ContactList.FL: return + if self.ctrl.dialect >= 16: + if ctc.status.is_offlineish(): + if not old_substatus.is_offlineish(): + self.ctrl.send_reply(YMSGService.LogOff, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'7', arbitrary_encode(ctc.head.username)), + ])) + return + if old_substatus.is_offlineish(): + self.ctrl.send_reply(YMSGService.LogOn, YMSGStatus.BRB, self.sess_id, misc.build_user_login_v16(ctc)) + else: + self.ctrl.send_reply(YMSGService.BuddyInfo, YMSGStatus.BRB, self.sess_id, misc.build_buddy_info_v16([ctc])) + return + if ctc.status.is_offlineish() and not old_substatus.is_offlineish(): service = YMSGService.LogOff elif not old_substatus.is_offlineish() and ctc.status.substatus is Substatus.Online and not ctc.status.message: @@ -1661,6 +2312,10 @@ class BackendEventHandler(event.BackendEventHandler): assert bs is not None user = bs.user + if self.ctrl.dialect >= 16: + self.ctrl._send_authorize_response(user_added, False, message or '') + return + self.ctrl.send_reply(YMSGService.ContactNew, YMSGStatus.OnVacation, self.sess_id, MultiDict([ (b'1', arbitrary_encode(user.username)), (b'3', arbitrary_encode(contact_id or user_added.username)), @@ -1780,28 +2435,169 @@ class BackendEventHandler(event.BackendEventHandler): detail = user_me.detail assert detail is not None - contacts = detail.contacts - - ctc = contacts.get(user.uuid) + ctc = detail.contacts.get(user.uuid) if ctc is not None: if ctc.lists & ContactList.BL: return - if ctc.pending: - bs.me_contact_remove(ctc.head.uuid, ContactList.PL) + if ctc.lists & ContactList.FL: + self.ctrl._clear_pending(user_me, ctc) + self.ctrl._send_authorize_response(user, True) + return - contact_request_data = MultiDict([ - (b'1', arbitrary_encode(user_me.username)), - (b'3', arbitrary_encode(adder_id or user.username)), + self.ctrl._send_contact_request(user, adder_id = adder_id, message = message) + + def ymsg_on_friend_icon(self, yahoo_id_sender: str, yahoo_id_receiver: str, checksum: bytes) -> None: + self.ctrl.send_reply(YMSGService.FriendIcon, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(yahoo_id_sender)), + (b'5', arbitrary_encode(yahoo_id_receiver)), + (b'192', checksum), + ])) + + def ymsg_on_friend_icon_download(self, yahoo_id_sender: str, yahoo_id_receiver: str, url: str, checksum: bytes) -> None: + self.ctrl.send_reply(YMSGService.FriendIconDownload, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(yahoo_id_sender)), + (b'5', arbitrary_encode(yahoo_id_receiver)), + (b'13', b'2'), + (b'20', arbitrary_encode(url)), + (b'192', checksum), + ])) + + def ymsg_on_friend_icon_file_transfer(self, yahoo_id_sender: str, yahoo_id_receiver: str, url: str, filename: str, ts: str) -> None: + self.ctrl.send_reply(YMSGService.FriendIconFileTransfer, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'5', arbitrary_encode(yahoo_id_receiver)), + (b'20', arbitrary_encode(url)), + (b'27', arbitrary_encode(filename)), + (b'38', arbitrary_encode(ts)), + ])) + + def ymsg_on_friend_icon_flag(self, yahoo_id_sender: str, yahoo_id_receiver: str, icon_flag: bytes) -> None: + self.ctrl.send_reply(YMSGService.DisplayTypeChanged, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(yahoo_id_sender)), + (b'5', arbitrary_encode(yahoo_id_receiver)), + (b'206', icon_flag), + ])) + + def ymsg_on_audible(self, sender: str, receiver: str, audible_id: bytes, text: bytes, checksum: bytes) -> None: + self.ctrl.send_reply(YMSGService.Audible, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'230', audible_id), + (b'231', text), + (b'232', checksum), + ])) + + def ymsg_on_im_panel_feature(self, sender: str, receiver: str, feature: bytes, state: bytes) -> None: + self.ctrl.send_reply(YMSGService.IMPanelFeature, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'221', feature), + (b'222', state), + ])) + + def ymsg_on_im_session(self, sender: str, receiver: str, flag: bytes) -> None: + self.ctrl.send_reply(YMSGService.IMSession, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'13', flag), + ])) + + def ymsg_on_message_ack(self, sender: str, receiver: str, msg_id: bytes) -> None: + self.ctrl._on_recipient_ack(msg_id) + + def ymsg_on_imvironment(self, sender: str, receiver: str, imv: bytes, state: bytes) -> None: + self.ctrl.send_reply(YMSGService.P2PFileXfer, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'1', arbitrary_encode(receiver)), + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'49', b'IMVIRONMENT'), + (b'63', imv), + ])) + + def ymsg_on_photo_add( + self, sender: str, receiver: str, photo_id: bytes, + name: bytes | None, thumbnail: bytes | None, url: bytes | None, + ) -> None: + for y in misc.build_photo_notify_packet(sender, receiver, photo_id, name = name, thumbnail = thumbnail, url = url): + self.ctrl.send_reply(y[0], y[1], self.sess_id, y[2]) + + def ymsg_on_photo_ack(self, sender: str, receiver: str, photo_id: bytes) -> None: + self.ctrl.send_reply(YMSGService.PhotoAdd, YMSGStatus.Ack, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'245', photo_id), + ])) + + def ymsg_on_photo_select(self, sender: str, receiver: str, photo_id: bytes, action: bytes) -> None: + self.ctrl.send_reply(YMSGService.PhotoSelect, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'245', photo_id), + (b'194', action), + ])) + + def ymsg_on_photo_relay( + self, sender: str, receiver: str, photo_id: bytes, token: bytes, *, + relay_host: bytes, filesize: bytes | None, ack: bool, + ) -> None: + status = YMSGStatus.Ack if ack else YMSGStatus.BRB + for y in misc.build_photo_relay_packet( + sender, receiver, photo_id, token, relay_host = relay_host, filesize = filesize, status = status, + ): + self.ctrl.send_reply(y[0], y[1], self.sess_id, y[2]) + + def ymsg_on_ft_invite(self, sender: str, receiver: str, cookie: bytes, yahoo_data: MultiDict[bytes, bytes]) -> None: + kvs = MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'265', cookie), + (b'222', yahoo_data.get(b'222') or b'1'), ]) # type: MultiDict[bytes, bytes] - if message is not None: - contact_request_data.add(b'14', arbitrary_encode(message.text)) - if message.yahoo_utf8 is not None: - contact_request_data.add(b'97', arbitrary_encode(message.yahoo_utf8)) + if (yahoo_data.get(b'222') or b'1') == b'1': + kvs.add(b'266', yahoo_data.get(b'266') or b'1') + kvs.add(b'302', b'268') + kvs.add(b'300', b'268') + if yahoo_data.get(b'27') is not None: kvs.add(b'27', yahoo_data.get(b'27') or b'') + if yahoo_data.get(b'28') is not None: kvs.add(b'28', yahoo_data.get(b'28') or b'') + kvs.add(b'301', b'268') + kvs.add(b'303', b'268') + if yahoo_data.get(b'267') is not None: kvs.add(b'267', yahoo_data.get(b'267') or b'') - contact_request_data.add(b'15', arbitrary_encode(str(time.time()))) - - self.ctrl.send_reply(YMSGService.ContactNew, YMSGStatus.NotAtHome, self.sess_id, contact_request_data) + self.ctrl.send_reply(YMSGService.FileTransferInvite, YMSGStatus.BRB, self.sess_id, kvs) + def ymsg_on_ft_setup( + self, sender: str, receiver: str, cookie: bytes, *, + filename: bytes, relay_host: bytes, peer_path: bytes, transfer_type: bytes, + ) -> None: + self.ctrl.send_reply(YMSGService.PeerSetup, YMSGStatus.BRB, self.sess_id, MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'265', cookie), + (b'27', filename), + (b'249', transfer_type), + (b'250', relay_host), + (b'251', peer_path), + ])) + + def ymsg_on_ft_init( + self, sender: str, receiver: str, cookie: bytes, yahoo_data: MultiDict[bytes, bytes], *, cancelled: bool = False, + ) -> None: + kvs = MultiDict([ + (b'4', arbitrary_encode(sender)), + (b'5', arbitrary_encode(receiver)), + (b'265', cookie), + ]) # type: MultiDict[bytes, bytes] + if cancelled: + kvs.add(b'66', b'-1') + self.ctrl.send_reply(YMSGService.PeerInit, YMSGStatus.LoginError, self.sess_id, kvs) + return + if yahoo_data.get(b'27') is not None: kvs.add(b'27', yahoo_data.get(b'27') or b'') + if yahoo_data.get(b'249') is not None: kvs.add(b'249', yahoo_data.get(b'249') or b'3') + if yahoo_data.get(b'251') is not None: kvs.add(b'251', yahoo_data.get(b'251') or b'') + self.ctrl.send_reply(YMSGService.PeerInit, YMSGStatus.BRB, self.sess_id, kvs) + + def ymsg_on_buddy_response(self, buddy: User, accepted: bool, message: str = '') -> None: + self.ctrl._send_authorize_response(buddy, accepted, message) + def on_removed_me(self, user: User) -> None: pass @@ -1897,20 +2693,33 @@ class ChatEventHandler(event.ChatEventHandler): if data.type in (MessageType.Chat,MessageType.Nudge): if self.cs.chat.front_data.get('ymsg_twoway_only') or len(roster) <= 2: - message_to_dict = MultiDict([ - (b'5', yahoo_data.get(b'5') or arbitrary_encode(user.username)), - (b'4', yahoo_data.get(b'1') or arbitrary_encode(sender.username)), - (b'14', yahoo_data.get(b'14') or arbitrary_encode(data.text or '')), - ]) # type: MultiDict[bytes, bytes] - - if yahoo_data.get(b'63') is not None: - message_to_dict.add(b'63', yahoo_data.get(b'63') or b'') - - if yahoo_data.get(b'64') is not None: - message_to_dict.add(b'64', yahoo_data.get(b'64') or b'') - - if yahoo_data.get(b'97') is not None: - message_to_dict.add(b'97', yahoo_data.get(b'97') or b'') + if self.ctrl.dialect >= 16: + message_to_dict = MultiDict([ + (b'4', yahoo_data.get(b'1') or arbitrary_encode(sender.username)), + (b'5', yahoo_data.get(b'5') or arbitrary_encode(user.username)), + (b'97', yahoo_data.get(b'97') or b'1'), + (b'63', yahoo_data.get(b'63') or b';0'), + (b'64', yahoo_data.get(b'64') or b'0'), + (b'206', yahoo_data.get(b'206') or b'2'), + (b'14', yahoo_data.get(b'14') or arbitrary_encode(data.text or '')), + ]) # type: MultiDict[bytes, bytes] + if yahoo_data.get(b'429') is not None: + message_to_dict.add(b'429', yahoo_data.get(b'429') or b'') + else: + message_to_dict = MultiDict([ + (b'5', yahoo_data.get(b'5') or arbitrary_encode(user.username)), + (b'4', yahoo_data.get(b'1') or arbitrary_encode(sender.username)), + (b'14', yahoo_data.get(b'14') or arbitrary_encode(data.text or '')), + ]) + + if yahoo_data.get(b'63') is not None: + message_to_dict.add(b'63', yahoo_data.get(b'63') or b'') + + if yahoo_data.get(b'64') is not None: + message_to_dict.add(b'64', yahoo_data.get(b'64') or b'') + + if yahoo_data.get(b'97') is not None: + message_to_dict.add(b'97', yahoo_data.get(b'97') or b'') self.ctrl.send_reply(YMSGService.Message, YMSGStatus.BRB, self.ctrl.sess_id, message_to_dict) else: if data.type is not MessageType.Nudge: @@ -1927,12 +2736,13 @@ class ChatEventHandler(event.ChatEventHandler): self.ctrl.send_reply(YMSGService.ConfMsg, YMSGStatus.BRB, self.ctrl.sess_id, conf_message_dict) elif data.type in (MessageType.Typing,MessageType.TypingDone): if self.cs.chat.front_data.get('ymsg_twoway_only') or len(roster) <= 2: - self.ctrl.send_reply(YMSGService.Notify, YMSGStatus.BRB if self.ctrl.dialect <= 12 else YMSGStatus.Typing, self.ctrl.sess_id, MultiDict([ - (b'5', yahoo_data.get(b'5') or arbitrary_encode(user.username)), + typing_status = YMSGStatus.BRB if (self.ctrl.dialect <= 12 or self.ctrl.dialect >= 16) else YMSGStatus.Typing + self.ctrl.send_reply(YMSGService.Notify, typing_status, self.ctrl.sess_id, MultiDict([ (b'4', yahoo_data.get(b'1') or arbitrary_encode(sender.username)), - (b'49', b'TYPING'), + (b'5', yahoo_data.get(b'5') or arbitrary_encode(user.username)), + (b'13', yahoo_data.get(b'13') or (b'0' if data.type is MessageType.TypingDone else b'1')), (b'14', yahoo_data.get(b'14') or arbitrary_encode(data.text or ' ')), - (b'13', yahoo_data.get(b'13') or (b'0' if data.type is MessageType.TypingDone else b'1')) + (b'49', b'TYPING'), ])) elif data.type is MessageType.Webcam: kvs = MultiDict([ diff --git a/front/ymsg/tmpl/Yinsider/Yinsider..xml b/front/ymsg/tmpl/Yinsider/Yinsider..xml new file mode 100644 index 0000000..6d6cb9a --- /dev/null +++ b/front/ymsg/tmpl/Yinsider/Yinsider..xml @@ -0,0 +1 @@ +< \ No newline at end of file diff --git a/front/ymsg/tmpl/layout/nofriends.html b/front/ymsg/tmpl/layout/nofriends.html index 9501a05..b1d9ec8 100644 --- a/front/ymsg/tmpl/layout/nofriends.html +++ b/front/ymsg/tmpl/layout/nofriends.html @@ -2,6 +2,7 @@ -

    i'm gay

    +

    Welcome to Yahoo! Messenger on CrossTalk!

    +

    You currently have no contacts. To get started, add one!

    \ No newline at end of file diff --git a/front/ymsg/ymsg_ctrl.py b/front/ymsg/ymsg_ctrl.py index c13ebb6..c97b5c4 100644 --- a/front/ymsg/ymsg_ctrl.py +++ b/front/ymsg/ymsg_ctrl.py @@ -1,4 +1,4 @@ -import io, asyncio, binascii, struct, settings +import io, asyncio, binascii, struct, settings, traceback from abc import ABCMeta, abstractmethod from typing import Tuple, Any, Optional, Callable, Iterable @@ -8,6 +8,7 @@ from .misc import YMSGStatus, YMSGService KVS = MultiDict[bytes, bytes] +YMSG_VENDOR_ID = 1337 class YMSGCtrlBase(metaclass = ABCMeta): __slots__ = ('logger', 'decoder', 'encoder', 'peername', 'closed', 'close_callback', 'transport', 'session_id') @@ -30,6 +31,9 @@ class YMSGCtrlBase(metaclass = ABCMeta): self.transport = None self.session_id = 0 + def set_dialect(self, dialect: int) -> None: + self.encoder.dialect = dialect + def data_received(self, data: bytes, *, transport: Optional[asyncio.BaseTransport] = None) -> None: if transport is None: transport = self.transport @@ -73,14 +77,18 @@ class YMSGCtrlBase(metaclass = ABCMeta): def _on_close(self, remove_sess_id: bool = True) -> None: pass class YMSGEncoder: - __slots__ = ('_logger', '_buf') + __slots__ = ('_logger', '_buf', 'dialect', 'vendor_id') _logger: Logger _buf: io.BytesIO + dialect: int + vendor_id: int - def __init__(self, logger: Logger) -> None: + def __init__(self, logger: Logger, *, dialect: int = 0, vendor_id: int = YMSG_VENDOR_ID) -> None: self._logger = logger self._buf = io.BytesIO() + self.dialect = dialect + self.vendor_id = vendor_id def encode(self, service: YMSGService, status: YMSGStatus, session_id: int, kvs: Optional[KVS] = None) -> None: payload_list = [] @@ -100,8 +108,7 @@ class YMSGEncoder: w = self._buf.write w(PRE) - # version number and vendor id are replaced with 0x00000000 - w(b'\x00\x00\x00\x00') + w(struct.pack('!HH', self.dialect, self.vendor_id)) # Have to call `int` on these because they might be an IntEnum, which # get `repr`'d to `EnumName.ValueName`. Grr. @@ -156,6 +163,15 @@ class YMSGDecoder: _truncated_kvs(y[0], y[5]) return y +def _decode_version(raw: bytes) -> int: + version_le = struct.unpack(' Tuple[DecodedYMSG, int]: kvs = MultiDict() # type: KVS @@ -163,22 +179,28 @@ def _try_decode_ymsg(d: bytes, i: int) -> Tuple[DecodedYMSG, int]: assert len(d[i:]) >= e assert d[i:i+4] == PRE header = d[i+4:i+e] - if header[:2] in (b'\x08\x00',b'\x09\x00',b'\x0a\x00'): - version = struct.unpack(' None: restricted_keys = set() @@ -204,7 +226,7 @@ SEP = b'\xC0\x80' YMSG_DIALECTS = [ # Not actually supported - 18, 17, 16, 8, + 19, 18, 17, # Actually supported - 15, 14, 13, 12, 11, 10, 9 + 16, 15, 14, 13, 12, 11, 10, 9, 8 ] \ No newline at end of file diff --git a/run_all.py b/run_all.py index 35cacf3..883d41d 100644 --- a/run_all.py +++ b/run_all.py @@ -26,7 +26,7 @@ def main(*, devmode: bool = False) -> None: """) print(f"===== AZUL {settings.VERSION} =====") - print(f"""2023 - 2026 the undergr0und + print(f"""2023 - 2026 hiden """) print(f"""Running on Python {sys.version} on {platform.platform()} """) @@ -35,6 +35,11 @@ def main(*, devmode: bool = False) -> None: """) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) + + from core import db + schema_changes = db.ensure_schema(db.engine) + if schema_changes: + print(f"Database brought up to date ({', '.join(schema_changes)})") user_service = UserService(Conn(settings.DB)) auth_service = AuthService() @@ -55,26 +60,22 @@ def main(*, devmode: bool = False) -> None: if settings.ENABLE_FRONT_OSCAR: import front.oscar front.oscar.register(loop, backend) + if getattr(settings, 'ENABLE_FRONT_ICQ', False): + import front.icq + front.icq.register(loop, backend) + if settings.ENABLE_FRONT_TOC: + import front.toc + front.toc.register(loop, backend) if settings.ENABLE_FRONT_MSIM: import front.msim front.msim.register(loop, backend, http_app) - if settings.ENABLE_FRONT_API: - import front.api - front.api.register(http_app) - if settings.ENABLE_FRONT_BOT: - import front.bot - front.bot.register(loop, backend) + ins_registry = None if settings.ENABLE_INS: import core.interservice - core.interservice.register(loop, backend) - - if devmode: - if settings.ENABLE_FRONT_DEVBOTS: - import front.devbots - front.devbots.register(loop, backend) - - import dev.webconsole - dev.webconsole.register(loop, backend, http_app) + ins_registry = core.interservice.register(loop, backend) + if settings.ENABLE_ADMIN: + import front.admin + front.admin.register(loop, backend, ins_registry) backend.run_forever() diff --git a/script/delcircles.py b/script/delcircles.py deleted file mode 100644 index 2bad295..0000000 --- a/script/delcircles.py +++ /dev/null @@ -1,30 +0,0 @@ -from core import db -from core.conn import Conn -import settings - -# TODO: INS-ize this -def main(*ids: str) -> None: - if not ids: - print("Nothing to do.") - return - print("Deleting {} circles:".format(len(ids))) - for i in ids: - print('=>', i) - ans = input("Are you sure? (y/N) ") - if ans.lower() != 'y': - print("Operation cancelled.") - return - print("Deleting.") - - conn = Conn(settings.DB) - with conn.session() as sess: - circles = sess.query(db.Circle).filter(db.Circle.chat_id.in_(ids)) - circlememberships = sess.query(db.CircleMembership).filter(db.CircleMembership.chat_id.in_(ids)) - print("delete circles", len(ids)) - circlememberships.delete(synchronize_session = False) - circles.delete(synchronize_session = False) - sess.flush() - -if __name__ == '__main__': - import funcli - funcli.main() diff --git a/script/listcircles.py b/script/listcircles.py deleted file mode 100644 index 48f9e29..0000000 --- a/script/listcircles.py +++ /dev/null @@ -1,19 +0,0 @@ -from core import db -from core.conn import Conn -import settings - -# TODO: INS-ize this -def main(*, verbose: bool = False) -> None: - total = 0 - conn = Conn(settings.DB) - with conn.session() as sess: - for circle in sess.query(db.Circle).all(): - total += 1 - if verbose: - print(circle.chat_id, circle.name) - - print("Total:", total) - -if __name__ == '__main__': - import funcli - funcli.main() diff --git a/script/listusers.py b/script/listusers.py deleted file mode 100644 index b0f6c05..0000000 --- a/script/listusers.py +++ /dev/null @@ -1,27 +0,0 @@ -from datetime import datetime, timedelta -from core import db -from core.conn import Conn -import settings - -# TODO: INS-ize this -def main(*, since: int = 60, verbose: bool = False) -> None: - online_since = datetime.utcnow() - timedelta(minutes = since) - total = 0 - total_online = 0 - - conn = Conn(settings.DB) - with conn.session() as sess: - for u in sess.query(db.User).all(): - total += 1 - if verbose: - print(u.email) - if online_since is not None and u.date_login is not None: - total_online += (1 if u.date_login >= online_since else 0) - - print("Total:", total) - if online_since is not None: - print("Online:", total_online) - -if __name__ == '__main__': - import funcli - funcli.main() diff --git a/script/maintenance.py b/script/maintenance.py deleted file mode 100644 index 8d25b51..0000000 --- a/script/maintenance.py +++ /dev/null @@ -1,15 +0,0 @@ -import asyncio, settings -from insclient.cmds import maintenance - -async def main(minutes: str): - try: - resp = await maintenance(minutes, b'AzuL-SERV', settings.INS_LINK_PASSWORD) - print("Operation successful!") - except Exception as e: - print("Operation failed:", e) - - -if __name__ == '__main__': - import sys - _, minutes = sys.argv - asyncio.run(main(minutes)) diff --git a/script/makeadmin.py b/script/makeadmin.py new file mode 100644 index 0000000..76b9f8c --- /dev/null +++ b/script/makeadmin.py @@ -0,0 +1,34 @@ +import getpass, hashlib, sys +import settings +from core import db + +def main() -> None: + args = sys.argv[1:] + if args[:1] == ['--hash-key']: + key = getpass.getpass('Admin key: ') + if len(key) < 12: + print('Use at least 12 characters.') + return + if key != getpass.getpass('Again: '): + print('Those don\'t match.') + return + print('ADMIN_KEY = \'{}\''.format(hashlib.sha256(key.encode('utf-8')).hexdigest())) + return + off = '--off' in args + logins = [arg for arg in args if not arg.startswith('--')] + if len(logins) != 1: + print('Usage: python script/makeadmin.py [--off]') + print(' python script/makeadmin.py --hash-key') + return + db.ensure_schema(db.engine) + login = logins[0] + with db.Session() as sess: + row = sess.query(db.User).filter((db.User.email == login) | (db.User.username == login)).one_or_none() + if row is None: + print('No account is called {}.'.format(login)) + return + row.is_admin = not off + print('{} ({}) is {} an administrator.'.format(row.username, row.email, 'no longer' if off else 'now')) + +if __name__ == '__main__': + main() diff --git a/script/managecircle.py b/script/managecircle.py deleted file mode 100644 index 34f415a..0000000 --- a/script/managecircle.py +++ /dev/null @@ -1,105 +0,0 @@ -from core import db -from core.conn import Conn -import settings - -# TODO: INS-ize this -def main(id: str, action: str, *args: str) -> None: - memberships_to_add = [] - conn = Conn(settings.DB) - with conn.session() as sess: - circle = sess.query(db.Circle).filter(db.Circle.chat_id == id).one_or_none() - if circle is None: - print('Circle {} does not exist'.format(id)) - return - if action.lower() == 'role': - if len(args) < 2: - print('Insufficient arguments for action role') - return - email = args[0] - role = args[1] - - user = sess.query(db.User).filter(db.User.email == email).one_or_none() - if user is None: - print('role: User {} does not exist'.format(email)) - return - m = sess.query(db.CircleMembership).filter(db.CircleMembership.chat_id == circle.chat_id, db.CircleMembership.member_id == user.id).one_or_none() - if m is None: - print('role: User {} not a member of this circle'.format(user.email)) - return - - if m.state != 3: - print('role: User {}\'s role in this circle is not set to accepted'.format(user.email)) - return - elif m.role == 1: - print('role: User {} is an owner of this circle and cannot be set to any other role. Use "owner" to transfer their ownership to someone else'.format(user.email)) - return - if role not in ('2','3'): - if role == '1': - print('role: Cannot set user {}\'s circle role to owner with this command. Use "owner" to perform this action'.format(user.email)) - else: - print('role: Role specified is not valid. Accepted values are 2 (co-owner) and 3 (member)') - return - - m.role = int(role) - memberships_to_add.append(m) - elif action.lower() == 'owner': - if len(args) < 1: - print('Insufficient arguments for action owner') - return - email = args[0] - - user = sess.query(db.User).filter(db.User.email == email).one_or_none() - if user is None: - print('owner: User {} does not exist'.format(email)) - return - m = sess.query(db.CircleMembership).filter(db.CircleMembership.chat_id == circle.chat_id, db.CircleMembership.member_id == user.id).one_or_none() - if m is None: - print('role: User {} not a member in this circle'.format(user.email)) - return - - if m.state != 3: - print('owner: User {}\'s role in circle is not set to accepted'.format(user.email)) - return - if m.role == 1: - print('owner: User {} is already owner'.format(user.email)) - return - - m_owner = sess.query(db.CircleMembership).filter(db.CircleMembership.chat_id == circle.chat_id, db.CircleMembership.role == 1).one_or_none() - if m_owner is not None: - m_owner.role = 3 - m.role = 1 - memberships_to_add.append(m) - if m_owner is not None: - memberships_to_add.append(m_owner) - elif action.lower() == 'remove': - if len(args) < 1: - print('Insufficient arguments for action remove') - return - email = args[0] - - user = sess.query(db.User).filter(db.User.email == email).one_or_none() - if user is None: - print('remove: User {} does not exist'.format(email)) - return - m = sess.query(db.CircleMembership).filter(db.CircleMembership.chat_id == circle.chat_id, db.CircleMembership.member_id == user.id).one_or_none() - if m is None or m.state == 0: - print('remove: User {} not a member in this circle'.format(user.email)) - return - if m.role == 1: - print('remove: User {} is an owner and cannot be removed from circle'.format(user.email)) - return - - m.role = 3 - m.state = 0 - memberships_to_add.append(m) - else: - print('Invalid action') - - if memberships_to_add: - sess.add_all(memberships_to_add) - sess.flush() - print('Action successfully performed') - -if __name__ == '__main__': - import funcli - funcli.main() diff --git a/script/managesess.py b/script/managesess.py deleted file mode 100644 index 2b5c59b..0000000 --- a/script/managesess.py +++ /dev/null @@ -1,125 +0,0 @@ -import asyncio, ast, json, settings -from insclient.cmds import list_sessions, session_detail, session_delete - -async def main(action: str, id: str | None): - try: - def _print_sessions(resp): - if not resp or resp[0] != 'ALLTHESESSIONS': - print("No sessions returned or unexpected response format") - return - tokens = resp[2:] - buf = [] - sessions = [] - i = 0 - while i < len(tokens): - tok = tokens[i] - if tok.startswith('"'): - buf = [tok] - while not buf[-1].endswith('"') and i + 1 < len(tokens): - i += 1 - buf.append(tokens[i]) - raw = " ".join(buf).strip('"') - try: - sid, uuid, email, raw_meta = raw.split('|', 3) - meta = ast.literal_eval(raw_meta) - sessions.append((sid, uuid, email, meta)) - except Exception: - pass - else: - buf = [tok] - if tok.endswith('}'): - raw = " ".join(buf) - try: - sid, uuid, email, raw_meta = raw.split('|', 3) - meta = ast.literal_eval(raw_meta) - sessions.append((sid, uuid, email, meta)) - except Exception: - pass - i += 1 - - for sid, uuid, email, meta in sessions: - print( - f" Session ID:\t {sid}\n" - f" UUID:\t\t {uuid}\n" - f" Email:\t {email}\n" - f" Client:\t {meta.get('program')}\n" - f" Version:\t {meta.get('version')}\n" - f" Method:\t {meta.get('via')}\n" - ) - - if action == 'list_all': - resp = await list_sessions(None, b'AzuL-SERV', settings.INS_LINK_PASSWORD) - _print_sessions(resp) - return - - elif action == 'list_by_user': - resp = await list_sessions(id, b'AzuL-SERV', settings.INS_LINK_PASSWORD) - _print_sessions(resp) - return - - elif action == 'details': - resp = await session_detail(id, b'AzuL-SERV', settings.INS_LINK_PASSWORD) - if not resp or resp[0] != 'SESSION': - print("No such session or unexpected response") - return - - if len(resp) >= 3 and resp[2] == 'KILLED': - print(f"Session {id} was killed") - return - - _, ts, sess_id, username, uuid, email, uin = resp[:7] - chat_enabled = resp[-1] - meta_tokens = resp[7:-1] - - raw_client = '' - if not meta_tokens: - raw_client = '' - elif len(meta_tokens) == 1: - token = meta_tokens[0] - if token.startswith('"') and token.endswith('"'): - raw_client = token.strip('"') - else: - raw_client = token - else: - combined = " ".join(meta_tokens) - if combined.startswith('"') and combined.endswith('"'): - raw_client = combined.strip('"') - else: - raw_client = combined - - try: - client_meta = ast.literal_eval(raw_client) if raw_client else {} - except Exception: - client_meta = {} - - print(f" Details for session {sess_id}:") - print(f" Username:\t {username}") - print(f" UUID:\t\t {uuid}") - print(f" Email:\t {email}") - print(f" UIN:\t\t {uin}") - print(f" Chat enabled:\t {chat_enabled}") - print(" Client info:") - for k, v in client_meta.items(): - print(f"\t{k}: {v}") - return - - elif action in ('close', 'kill'): - await session_delete(id, b'AzuL-SERV', settings.INS_LINK_PASSWORD) - print("Operation successful") - return - - else: - print('Unknown action. Valid actions: list_all, list_by_user, details, close, kill') - return - - except Exception as e: - print("Operation failed:", e) - - -if __name__ == '__main__': - import sys - - _, action, *rest = sys.argv - id_arg = rest[0] if rest else None - - asyncio.run(main(action, id_arg)) \ No newline at end of file diff --git a/script/manageuser.py b/script/manageuser.py deleted file mode 100644 index 82083ae..0000000 --- a/script/manageuser.py +++ /dev/null @@ -1,101 +0,0 @@ -# TODO: holy shit clean this up this is awful -import argparse, asyncio, getpass, settings -from insclient.cmds import usercreate, userupdate, userdelete -from core.conn import Conn -from core import db - -def _parse_args(): - p = argparse.ArgumentParser(prog='manageuser.py') - sub = p.add_subparsers(dest='cmd', required=True) - - sc_create = sub.add_parser('create') - sc_create.add_argument('email') - sc_create.add_argument('username') - sc_create.add_argument('first_name') - sc_create.add_argument('last_name') - sc_create.add_argument('uin', type=int) - sc_create.add_argument('--password', '-p', help='user password (if omitted, prompted)') - sc_create.add_argument('--oldmsn', action='store_true') - sc_create.add_argument('--yahoo', action='store_true') - sc_create.add_argument('--oldaim', action='store_true') - sc_create.add_argument('--msim', action='store_true') - - sc_mod = sub.add_parser('modify') - sc_mod.add_argument('email') - sc_mod.add_argument('field') - sc_mod.add_argument('value') - sc_mod.add_argument('--oldmsn', action='store_true', help='also (re)generate legacy MSN MD5 hash when changing password') - sc_mod.add_argument('--yahoo', action='store_true', help='also (re)generate legacy Yahoo hashes when changing password') - sc_mod.add_argument('--oldaim', action='store_true', help='also (re)generate legacy AIM MD5 hash when changing password') - sc_mod.add_argument('--msim', action='store_true', help='also (re)generate legacy MSIM SHA-1 hash when changing password') - - sc_del = sub.add_parser('delete') - sc_del.add_argument('email', help='email of the user to delete') - - return p.parse_args() - -async def _do_create(email: str, username: str, first_name: str, last_name: str, uin: int, user_password: str, oldmsn: bool, yahoo: bool, oldaim: bool, msim: bool) -> None: - try: - await usercreate( - email, username, first_name, last_name, uin, user_password, - oldmsn, yahoo, oldaim, msim, b'AzuL-SERV', settings.INS_LINK_PASSWORD - ) - print("Operation successful!") - except Exception as e: - print("Operation failed:", e) - -async def _do_modify(email: str, field: str, value: str, oldmsn: bool, yahoo: bool, oldaim: bool, msim: bool) -> None: - conn = Conn(settings.DB) - with conn.session() as sess: - user = sess.query(db.User).filter(db.User.email == email).first() - if not user: - print('User does not exist.') - return - uuid = user.uuid - - if field == 'password' and value == '-': - value = getpass.getpass('Password: ') - - try: - if field == 'password': - await userupdate(uuid, field, value, b'AzuL-SERV', settings.INS_LINK_PASSWORD, support_old_msn=oldmsn, support_yahoo=yahoo, support_aim=oldaim, support_msim=msim) - else: - await userupdate(uuid, field, value, b'AzuL-SERV', settings.INS_LINK_PASSWORD) - print("Operation successful!") - except Exception as e: - print("Operation failed:", e) - -async def _do_delete(email: str) -> None: - conn = Conn(settings.DB) - with conn.session() as sess: - user = sess.query(db.User).filter(db.User.email == email).first() - if not user: - print('User does not exist.') - return - uuid = user.uuid - - try: - await userdelete(uuid, b'AzuL-SERV', settings.INS_LINK_PASSWORD) - print("Operation successful!") - except Exception as e: - print("Operation failed:", e) - -def main(): - args = _parse_args() - if args.cmd == 'create': - pw = args.password - if not pw: - pw = getpass.getpass('Password: ') - asyncio.run(_do_create( - args.email, args.username, args.first_name, args.last_name, args.uin, - pw, args.oldmsn, args.yahoo, args.oldaim, args.msim - )) - elif args.cmd == 'modify': - asyncio.run(_do_modify( - args.email, args.field, args.value, args.oldmsn, args.yahoo, args.oldaim, args.msim - )) - elif args.cmd == 'delete': - asyncio.run(_do_delete(args.email)) - -if __name__ == '__main__': - main() diff --git a/script/sendalert.py b/script/sendalert.py deleted file mode 100644 index beee182..0000000 --- a/script/sendalert.py +++ /dev/null @@ -1,24 +0,0 @@ -import asyncio, settings -from insclient.cmds import alert - -async def main(emails: str): - message = input('Enter alert message: ').strip() - if not message: - print('Message is required.') - return - - url = input('Enter a URL (or leave blank): ').strip() or '' - icon = input('Enter an icon URL (or leave blank): ').strip() or '' - targets = emails if emails.strip() and emails.strip() != '*' else 'all' - - try: - await alert(message, b'AzuL-SERV', settings.INS_LINK_PASSWORD, url, icon, targets) - print("Operation successful!") - except Exception as e: - print("Operation failed:", e) - - -if __name__ == '__main__': - import sys - _, emails = sys.argv - asyncio.run(main(emails)) diff --git a/settings.py b/settings.py index 1e59b4a..c799f41 100644 --- a/settings.py +++ b/settings.py @@ -3,36 +3,59 @@ # DB = 'sqlite:///../crosstalk.sqlite' # STATS_DB = 'sqlite:///../stats.sqlite' # Current - MySQL/MariaDB +VERSION = '0.6.0' DB = 'mysql+pymysql://username:password@127.0.0.1/crosstalk?charset=utf8mb4' STATS_DB = 'mysql+pymysql://username:password@127.0.0.1/ctstats?charset=utf8mb4' + DEBUG = False DEBUG_FULL = False DEBUG_LOG_SQL_QUERIES = False -FORCE_HOSTS_UPDATE = False + CERT_DIR = 'path/to/cert' CERT_ROOT = 'CERT_ROOT' -TARGET_HOST = 'ms.msgrsvcs.ctsrv.gay' -APPDIR_HOST = 'mactivites.msgrsvcs.ctsrv.gay' -LOGIN_HOST = 'ctas.login.ugnet.gay' -ADDRESSBOOK_HOST = 'ctsvcs.addressbook.ugnet.gay' -USERSTORAGE_HOST = 'cts.storage.ugnet.gay' -STORAGE_HOST = 'storage.ugnet.gay' -STATIC_HOST = 'static.ugnet.gay' -AD_HOST = 'ctsvcs.advertising.ugnet.gay' -TODAY_HOST = 'today.msgrsvcs.ctsrv.gay' -SOCIAL_HOST = 'social.ugnet.gay' + +TARGET_HOST = 'ms.msgrsvcs.ctsrv.xyz' +APPDIR_HOST = 'mactivites.msgrsvcs.ctsrv.xyz' +LOGIN_HOST = 'ctas.login.ugnet.xyz' +ADDRESSBOOK_HOST = 'ctsvcs.addressbook.ugnet.xyz' +USERSTORAGE_HOST = 'cts.storage.ugnet.xyz' +STORAGE_HOST = 'storage.ugnet.xyz' +STATIC_HOST = 'static.ugnet.xyz' +AD_HOST = 'ctsvcs.advertising.ugnet.xyz' +TODAY_HOST = 'today.msgrsvcs.ctsrv.xyz' +SOCIAL_HOST = 'social.ugnet.xyz' WEBSITE_HOST = 'crosstalk.im' TARGET_IP = '127.0.0.1' -SMTP_HOST = 'mail-server-here' -SMTP_PORT = 587 -SMTP_USERNAME = 'administration@ugnet.gay' -SMTP_PASSWORD = '' -ENABLE_NAT_RELAY = False -CF_REALTIME_API_KEY = '' -VERSION = '0.6.0-dp2' + # While not necessary for debugging, it is recommended you change the password variables in production for obvious security reasons. INS_LINK_PASSWORD = 'password' -STRESS_TEST_ACTIVE = False + +INS_HOST = '0.0.0.0' +INS_PORT = 4309 +INS_KEY_DIR = 'config/ins' +INS_ALLOWED_IPS = ['127.0.0.1', '::1'] +INS_IDENTIFIERS = ['WEB', 'AzuL-SERV', 'WTV', 'uMaIL', 'sBOOK', 'NOTBAY', 'CrossBot', 'SEARCH', 'WebTalk'] +INS_AUTH_TIMEOUT = 15 +INS_IDLE_TIMEOUT = 180 +INS_PING_INTERVAL = 60 +INS_CHALLENGE_INTERVAL = 900 +INS_CHALLENGE_TIMEOUT = 60 + +ENABLE_ADMIN = True +ADMIN_HOST = '127.0.0.1' +ADMIN_PORT = 8090 +ADMIN_KEY = '' +ADMIN_SESSION_LIFETIME = 8 * 3600 +ADMIN_COOKIE_SECURE = False + +ALERT_SITE_URL = 'https://crosstalk.im/' +SUSPENDED_ACCOUNT_DAYS = 30 + +# SMTP +SMTP_HOST = 'mail-server-here' +SMTP_PORT = 587 +SMTP_USERNAME = 'administration@ugnet.xyz' +SMTP_PASSWORD = '' # What frontends are enabled ENABLE_INS = True @@ -41,16 +64,28 @@ ENABLE_FRONT_YMSG = True ENABLE_FRONT_IRC = False ENABLE_FRONT_IRC_SSL = False ENABLE_FRONT_OSCAR = True +# the pre-OSCAR ICQ protocols (V1-V5) over UDP +ENABLE_FRONT_ICQ = True +ENABLE_FRONT_TOC = True ENABLE_FRONT_MSIM = False -ENABLE_FRONT_API = True -ENABLE_FRONT_BOT = False -ENABLE_FRONT_DEVBOTS = False + + +CF_REALTIME_API_KEY = '' +FORCE_HOSTS_UPDATE = False +STRESS_TEST_ACTIVE = False +ENABLE_NAT_RELAY = True # Frontend-specific settings YAHOOHELPER_MSG = "CHANGE ME" +YMSG_TOKEN_LIFETIME = 86400 OSCAR_MOTD_ENABLED = False +ICQ_LEGACY_PORT = 4000 +# hand V5 clients each other's IP address and port for direct connections (file transfers, chat); off, it stays private +ICQ_DIRECT_CONNECTIONS = False HTTP_PORT = 80 + + SERVICE_KEYS = [] # type: ignore try: diff --git a/util/avatar.py b/util/avatar.py index 965bd3f..7a8a24d 100644 --- a/util/avatar.py +++ b/util/avatar.py @@ -6,9 +6,10 @@ from pathlib import Path from typing import Optional, Tuple STORAGE_BASE = Path('storage/dp') +PHOTO_STORAGE_BASE = Path('storage/photos') THUMB_SIZE = (21, 21) -MSN_SIZE = (96, 96) -1 +IM_SIZE = (96, 96) + def compute_md5(data: bytes) -> str: return hashlib.md5(data).hexdigest()[:16] @@ -33,30 +34,50 @@ def store_avatar_file(uuid: str, data: bytes, ext: str) -> str: full_path = avatar_dir / f'{md5}.{ext}' thumb_path = avatar_dir / f'{md5}_thumb.png' - msn_path = avatar_dir / f'{md5}_msn.png' + im_path = avatar_dir / f'{md5}_im.png' if not full_path.exists(): full_path.write_bytes(data) - if not thumb_path.exists() or not msn_path.exists(): + if not thumb_path.exists() or not im_path.exists(): try: img = Image.open(BytesIO(data)) if not thumb_path.exists(): img.resize(THUMB_SIZE).save(str(thumb_path)) - if not msn_path.exists(): - img.resize(MSN_SIZE).save(str(msn_path)) + if not im_path.exists(): + img.resize(IM_SIZE).save(str(im_path)) except Exception: pass return md5 +def store_photo_file(uuid: str, data: bytes, ext: str) -> str: + photo_dir = PHOTO_STORAGE_BASE / uuid + photo_dir.mkdir(parents=True, exist_ok=True) + name = f'{compute_md5(data)}.{ext}' + path = photo_dir / name + if not path.exists(): + path.write_bytes(data) + return name + +def get_photo_data(uuid: str, name: str) -> Optional[Tuple[bytes, str]]: + path = PHOTO_STORAGE_BASE / uuid / name + if not path.is_file(): + return None + try: + data = path.read_bytes() + except OSError: + return None + return data, 'image/' + path.suffix.lstrip('.').lower() + + def find_avatar_file( uuid: str, md5: str, *, small: bool = False, - msn: bool = False, + im: bool = False, ) -> Optional[Path]: avatar_dir = get_avatar_dir(uuid) if not avatar_dir.is_dir(): @@ -67,10 +88,10 @@ def find_avatar_file( if thumb.is_file(): return thumb - elif msn: - msn_file = avatar_dir / f'{md5}_msn.png' - if msn_file.is_file(): - return msn_file + elif im: + im_file = avatar_dir / f'{md5}_im.png' + if im_file.is_file(): + return im_file for p in avatar_dir.iterdir(): if p.is_file() and p.stem == md5: @@ -84,12 +105,12 @@ def get_avatar_data( md5: Optional[str], *, small: bool = False, - msn: bool = False, + im: bool = False, ) -> Optional[Tuple[bytes, str]]: if not md5: return None - path = find_avatar_file(uuid, md5, small=small, msn=msn) + path = find_avatar_file(uuid, md5, small=small, im=im) if path is None: return None diff --git a/util/hash.py b/util/hash.py index a12c000..6cf85b4 100644 --- a/util/hash.py +++ b/util/hash.py @@ -76,33 +76,8 @@ class Argon2PasswordHasher(Hasher): cls.impl.verify(hash_str, password + salt) return True except (ValueError, VerifyMismatchError, binascii.Error): - # PBKDF2 fallback, migrate hash to Argon2 - try: - parts = encoded.split(cls.separator) - alg = parts[0] - if alg != PBKDF2PasswordHasher.algorithm: - return False - _, *stuff, salt, _ = parts - if PBKDF2PasswordHasher.verify(password, encoded): - return 'MIGRATEMEPLSTHX' - except Exception: - return False return False -class PBKDF2PasswordHasher(Hasher): - algorithm = 'pbkdf2_sha256' - iterations = 24000 - - @classmethod - def _encode_impl(cls, password: str, *stuff: Any, salt: str) -> Tuple[bytes, List[str]]: - assert len(stuff) <= 1 - iterations: Optional[int] = (stuff[0] if stuff else None) - if iterations is None: - iterations = cls.iterations - iterations = int(iterations) - hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), iterations, None) - return hash, [str(iterations)] - class MD5PasswordHasher(Hasher): algorithm = 'md5' digest = hashlib.md5 @@ -204,7 +179,6 @@ class SHA1PasswordHasher(Hasher): return secrets.compare_digest(encoded, encoded_2) HASHERS[Argon2PasswordHasher.algorithm] = Argon2PasswordHasher -HASHERS[PBKDF2PasswordHasher.algorithm] = PBKDF2PasswordHasher HASHERS[MD5PasswordHasher.algorithm] = MD5PasswordHasher HASHERS[MD5CryptPasswordHasher.algorithm] = MD5CryptPasswordHasher HASHERS[SHA1PasswordHasher.algorithm] = SHA1PasswordHasher @@ -213,7 +187,6 @@ def gen_salt(length: int = 15) -> str: return secrets.token_hex(length)[:length] hasher = Argon2PasswordHasher -hasher_pbkdf2 = PBKDF2PasswordHasher hasher_md5 = MD5PasswordHasher hasher_md5crypt = MD5CryptPasswordHasher hasher_sha1 = SHA1PasswordHasher \ No newline at end of file diff --git a/util/icq.py b/util/icq.py new file mode 100644 index 0000000..fd28f64 --- /dev/null +++ b/util/icq.py @@ -0,0 +1,197 @@ +from datetime import date, datetime +from typing import Any, TYPE_CHECKING + +if TYPE_CHECKING: + from core.backend import Backend + from core.models import User + +ICQ_INFO_KEY = 'ICQ_INFO' + +INTEREST_SLOTS = 4 +AFFILIATION_SLOTS = 3 + +MAX_QUEUED_AUTH_EVENTS = 50 + +_BASIC_FIELDS = ('nick', 'first', 'last', 'email', 'city', 'state', 'phone', 'fax', 'address', 'cell', 'zip') +_WORK_FIELDS = ('city', 'state', 'phone', 'fax', 'address', 'zip', 'company', 'department', 'position', 'webpage') + + +def _store(user: 'User') -> dict[str, Any]: + store = user.settings.get(ICQ_INFO_KEY) + if not isinstance(store, dict): + store = {} + user.settings[ICQ_INFO_KEY] = store + return store + +def _section(user: 'User', name: str) -> dict[str, Any]: + store = _store(user) + section = store.get(name) + if not isinstance(section, dict): + section = {} + store[name] = section + return section + +def _text(value: Any) -> str: + return '' if value is None else str(value) + +def save(backend: 'Backend', user: 'User') -> None: + if user.detail is not None: + backend._mark_modified(user) + else: + backend._mark_modified(user, detail = backend._load_detail(user)) + +def nickname(user: 'User') -> str: + nick = _section(user, 'basic').get('nick') + if nick: + return str(nick) + name = user.status.name or '' + if not name or '@' in name: + return user.username + return name + +def basic_info(user: 'User') -> dict[str, Any]: + stored = _section(user, 'basic') + profile = user.profile + info = { + 'nick': nickname(user), + 'first': stored.get('first', user.first_name or ''), + 'last': stored.get('last', user.last_name or ''), + 'email': stored.get('email', ''), + 'city': stored.get('city', (profile.city if profile is not None else None) or ''), + 'state': stored.get('state', (profile.state if profile is not None else None) or ''), + 'phone': stored.get('phone', ''), + 'fax': stored.get('fax', ''), + 'address': stored.get('address', ''), + 'cell': stored.get('cell', ''), + 'zip': stored.get('zip', _text(profile.zip if profile is not None else None)), + 'country': int(stored.get('country', 0) or 0), + 'gmt': int(stored.get('gmt', 0) or 0), + # ICQ only ever shows an e-mail address its owner chose to publish + 'publish_email': bool(stored.get('publish_email', False)), + } + for field in _BASIC_FIELDS: + info[field] = _text(info[field]) + return info + +def more_info(user: 'User') -> dict[str, Any]: + stored = _section(user, 'more') + profile = user.profile + return { + 'gender': int(stored.get('gender', 0) or 0), + 'homepage': _text(stored.get('homepage', (profile.website if profile is not None else None) or '')), + 'birth_year': int(stored.get('birth_year', 0) or 0), + 'birth_month': int(stored.get('birth_month', 0) or 0), + 'birth_day': int(stored.get('birth_day', 0) or 0), + 'lang1': int(stored.get('lang1', 0) or 0), + 'lang2': int(stored.get('lang2', 0) or 0), + 'lang3': int(stored.get('lang3', 0) or 0), + } + +def work_info(user: 'User') -> dict[str, Any]: + stored = _section(user, 'work') + info = { field: _text(stored.get(field, '')) for field in _WORK_FIELDS } + info['country'] = int(stored.get('country', 0) or 0) + info['occupation'] = int(stored.get('occupation', 0) or 0) + return info + +def notes(user: 'User') -> str: + stored = _store(user).get('notes') + if stored is not None: + return _text(stored) + profile = user.profile + return (profile.bio if profile is not None else None) or '' + +def _pairs(user: 'User', name: str, slots: int) -> list[list[Any]]: + stored = _store(user).get(name) + pairs = [] + if isinstance(stored, list): + for entry in stored[:slots]: + if isinstance(entry, (list, tuple)) and len(entry) == 2: + pairs.append([int(entry[0] or 0), _text(entry[1])]) + while len(pairs) < slots: + pairs.append([0, '']) + return pairs + +def interests(user: 'User') -> list[list[Any]]: + return _pairs(user, 'interests', INTEREST_SLOTS) + +def affiliations(user: 'User') -> dict[str, list[list[Any]]]: + return { + 'past': _pairs(user, 'past_affiliations', AFFILIATION_SLOTS), + 'current': _pairs(user, 'affiliations', AFFILIATION_SLOTS), + } + +def age(user: 'User', today: date | None = None) -> int: + more = more_info(user) + year, month, day = more['birth_year'], more['birth_month'], more['birth_day'] + if not year or not month or not day: + return 0 + today = today or datetime.utcnow().date() + try: + born = date(year, month, day) + except ValueError: + return 0 + years = today.year - born.year - ((today.month, today.day) < (born.month, born.day)) + return max(0, years) + +def set_basic(user: 'User', fields: dict[str, Any]) -> None: + _section(user, 'basic').update(fields) + +def set_more(user: 'User', fields: dict[str, Any]) -> None: + _section(user, 'more').update(fields) + +def set_work(user: 'User', fields: dict[str, Any]) -> None: + _section(user, 'work').update(fields) + +def set_notes(user: 'User', text: str) -> None: + _store(user)['notes'] = text + +def set_interests(user: 'User', pairs: list[list[Any]]) -> None: + _store(user)['interests'] = [[int(code), _text(keyword)] for code, keyword in pairs[:INTEREST_SLOTS]] + +def set_affiliations(user: 'User', past: list[list[Any]], current: list[list[Any]]) -> None: + _store(user)['past_affiliations'] = [[int(code), _text(keyword)] for code, keyword in past[:AFFILIATION_SLOTS]] + _store(user)['affiliations'] = [[int(code), _text(keyword)] for code, keyword in current[:AFFILIATION_SLOTS]] + +def permissions(user: 'User') -> dict[str, bool]: + stored = _section(user, 'perms') + return { + 'auth_required': bool(stored.get('auth_required', False)), + 'web_aware': bool(stored.get('web_aware', False)), + } + +def set_permissions(user: 'User', *, auth_required: bool | None = None, web_aware: bool | None = None) -> None: + stored = _section(user, 'perms') + if auth_required is not None: + stored['auth_required'] = auth_required + if web_aware is not None: + stored['web_aware'] = web_aware + +def requires_authorization(owner: 'User', requester: 'User') -> bool: + if owner is requester or not permissions(owner)['auth_required']: + return False + return requester.uuid not in (_store(owner).get('preauth') or []) + +def record_preauth(owner: 'User', requester_uuid: str) -> None: + preauth = _store(owner).setdefault('preauth', []) + if requester_uuid not in preauth: + preauth.append(requester_uuid) + +def queue_auth_event(user: 'User', event: dict[str, Any]) -> None: + queue = _store(user).setdefault('auth_events', []) + queue.append(event) + del queue[:-MAX_QUEUED_AUTH_EVENTS] + +def take_auth_events(user: 'User') -> list[dict[str, Any]]: + store = _store(user) + queue = store.pop('auth_events', None) + return queue if isinstance(queue, list) else [] + +def latin1(text: str) -> bytes: + return text.encode('cp1252', errors = 'replace') + +def from_latin1(data: bytes) -> str: + try: + return data.decode('cp1252') + except UnicodeDecodeError: + return data.decode('latin-1') diff --git a/util/ins_link.py b/util/ins_link.py new file mode 100644 index 0000000..eaf3153 --- /dev/null +++ b/util/ins_link.py @@ -0,0 +1,11 @@ +import os +from insclient import INSClient +import settings + +def ins_client(identifier: str = 'AzuL-SERV') -> INSClient: + host = ('127.0.0.1' if settings.INS_HOST in ('0.0.0.0', '::', '') else settings.INS_HOST) + return INSClient( + identifier, key_file = os.path.join(settings.INS_KEY_DIR, '{}.client.key'.format(identifier.lower())), + enrollment_code = os.environ.get('INS_ENROLLMENT_CODE') or None, host = host, port = settings.INS_PORT, keepalive = False, + client_name = 'azul-script', client_version = settings.VERSION, label = 'azul scripts', + ) diff --git a/util/misc.py b/util/misc.py index 55ccb34..1d82fe1 100644 --- a/util/misc.py +++ b/util/misc.py @@ -1,6 +1,6 @@ from typing import FrozenSet, Any, Iterable, Optional, TypeVar, List, Dict, Tuple, Generic, TYPE_CHECKING from abc import ABCMeta, abstractmethod -import asyncio, functools, itertools, traceback, ssl, jinja2, settings, sys, platform +import asyncio, functools, itertools, traceback, ssl, jinja2, settings, sys, platform, re from datetime import datetime from uuid import uuid4 from aiohttp import web @@ -16,6 +16,11 @@ else: def gen_uuid() -> str: return str(uuid4()) +_VALID_OSCAR_RE = re.compile(r'^[A-Za-z0-9]+$') + +def is_valid_oscar_screenname(name: str) -> bool: + return bool(name) and _VALID_OSCAR_RE.match(name) is not None + T = TypeVar('T') def first_in_iterable(iterable: Iterable[T]) -> Optional[T]: for x in iterable: return x @@ -73,6 +78,39 @@ class ProtocolRunner(Runner): def create_servers(self, loop: asyncio.AbstractEventLoop) -> List[Any]: return [loop.create_server(self._protocol, self.host, self.port, ssl = self.ssl_context)] +class DatagramRunner(Runner): + __slots__ = ('_protocol',) + + _protocol: Any + + def __init__(self, host: str, port: int, protocol: Any, *, args: Optional[List[Any]] = None, service: str) -> None: + super().__init__(host, port, service = service) + if args: + protocol = functools.partial(protocol, *args) + self._protocol = protocol + + def create_servers(self, loop: asyncio.AbstractEventLoop) -> List[Any]: + return [self._create_endpoint(loop)] + + async def _create_endpoint(self, loop: asyncio.AbstractEventLoop) -> 'DatagramServer': + transport, _ = await loop.create_datagram_endpoint(self._protocol, local_addr = (self.host, self.port)) + return DatagramServer(transport) + +class DatagramServer: + __slots__ = ('_transport',) + + _transport: asyncio.BaseTransport + + def __init__(self, transport: asyncio.BaseTransport) -> None: + self._transport = transport + + def close(self) -> None: + self._transport.close() + + async def wait_closed(self) -> None: + # a datagram endpoint has nothing to drain once it's closed + return None + class AIOHTTPRunner(Runner): __slots__ = ('app', '_handler')