Compare commits

..
9 Commits
Author SHA1 Message Date
Athena Funderburg a571f416df discontinuing discord server 2026-07-09 20:24:50 +00:00
Athena Funderburg db9245c0b2 fix: INS has missing auth checks 2026-06-30 17:20:03 +00:00
Athena Funderburg 71448a01db h 2026-06-22 17:47:21 +00:00
Athena Funderburg ce124af489 0.5.23 - remove restriction on adding yourself and add more emails to the blocklist 2026-06-22 17:43:21 +00:00
HIDEN be5a41311d band-aid 2026-06-09 21:45:37 -05:00
HIDEN 285a82169c fix indentation 2026-06-09 21:43:01 -05:00
HIDEN 0fad32e6e5 band-aid 2026-06-09 21:41:00 -05:00
dxuser514 b9b9437d28 Fix Mercury Messenger sync contacts failed 2026-05-31 18:17:21 +00:00
Athena Funderburg 21f38ee3e1 production init 2026-05-26 16:41:23 +00:00
164 changed files with 4827 additions and 21419 deletions

No files matched your search

+7 -2
View File
@@ -3,6 +3,12 @@ __pycache__
.mypy_cache .mypy_cache
*.sqlite *.sqlite
settings_local.py settings_local.py
etc/Caddyfile
dev/cert
tmp
hosts.lnk
storage
front/ymsg/todo
.mypy_cache .mypy_cache
.brutus_cache .brutus_cache
*.old *.old
@@ -10,9 +16,8 @@ settings_local.py
.vs/ .vs/
.*_cache .*_cache
.DS_Store .DS_Store
core/static/sounds/user/
Thumbs.db Thumbs.db
.idea .idea
*.swp *.swp
*.pem *.pem
config/ins/
storage/
+9 -18
View File
@@ -1,6 +1,6 @@
# AZUL # Azul
AZUL is the main server software for the CrossTalk service; a chat service planning to support as many messaging protocols as possible, both retro and modern. Based on the legacy Escargot codebase. Azul is the main server software for the CrossTalk service; a chat service planning to support as many messaging protocols as possible, both retro and modern. This service acts as the backbone for all chat-related services that are a part of the undergr0und.
## Protocol support ## Protocol support
@@ -10,38 +10,29 @@ 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 - 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 usethe admin panel to perform a few actions on a Circle and its users - 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)
- 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. - Windows Live Messenger 2011/2012 supports authentication, viewing your contacts list, presence updates, and MsgrConfig. Most other functionality is either unimplemented or untested
### YMSG (used by Yahoo! Messenger) ### YMSG (used by Yahoo! Messenger)
As of now, YMSG9 through YMSG15 are implemented, with some caveats: As of now, only YMSG9 through YMSG15 are implemented, with some caveats:
- If you want to log in, an MD5crypt-encoded password hash must be stored - If you want to log in to Yahoo! Messenger < 7.0, an MD5crypt-encoded password hash must be stored
- Conferences are currently not working - Conferences are currently not working
- Yahoo! Messenger 7.0 does not log in for currently unknown reasons. 5.0, 5.5, 5.6, 6.0, 7.5, 8.0, and 8.1 were all tested to work, however - Yahoo! Messenger 7.0 does not log in for currently unknown reasons. 5.0, 5.5, 5.6, 6.0, 7.5, 8.0, and 8.1 were all tested to work, however
- Yahoo! Messneger for Vista also does not work for currently unknown reasons - Yahoo! Messneger for Vista is untested, but should work
### IRC ### IRC
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. IRC support 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.
### OSCAR (used by AOL Instant Messenger and ICQ 2000 - 8) ### OSCAR (used by AOL Instant Messenger and ICQ 2000 - 8)
- If you want to log in, an MD5-encoded password hash must be stored OSCAR support is basic. Right now, only `FEEDBAG`, `BUDDY`, et cetera are partially implemented, and it supports showing your buddy list as well as presence updates. Messaging currently isn't supported yet. Only the FLAP authentication method and BUCP with the older hashing method (used by AIM 3.5 & 4.x) is implemented. It has been tested to work with AIM 4.3 and 4.8; older versions may be hit or miss. AIM 5.x - 7.x, TOC/TOC2, WebAPI, and ICQ are not supported yet, but support for them is planned and will come in the future.
- 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 ## Developers
+44 -24
View File
@@ -21,52 +21,72 @@
}, },
{ {
"id": 5, "id": 5,
"image": "banner/cobbclub.png",
"link": "http://cobb.club"
},
{
"id": 6,
"image": "banner/maymundere.gif", "image": "banner/maymundere.gif",
"link": "https://maymundere.org" "link": "https://maymundere.org"
}, },
{ {
"id": 6, "id": 7,
"image": "banner/macsecret.png",
"link": "http://macsecret.com"
},
{
"id": 8,
"image": "banner/leefy.png", "image": "banner/leefy.png",
"link": "https://leefymoons-room.net" "link": "https://leefymoons-room.net"
}, },
{ {
"id": 7, "id": 9,
"image": "banner/srcfreak.jpg",
"link": "http://srcfreaks.ddns.net"
},
{
"id": 10,
"image": "banner/kakworm.gif", "image": "banner/kakworm.gif",
"link": "https://fusionstrike.neocities.org" "link": "https://fusionstrike.neocities.org"
}, },
{ {
"id": 8, "id": 11,
"image": "banner/gdsk.gif", "image": "banner/gdsk.gif",
"link": "https://gdsk.retrosite.org" "link": "https://gdsk.retrosite.org"
}, },
{ {
"id": 9, "id": 12,
"image": "banner/kooper.png", "image": "banner/kooper.png",
"link": "http://kooper.online" "link": "http://kooper.online"
}, },
{
"id": 10,
"image": "banner/aomeix.jpg",
"link": "http://aomeix.eu.org"
},
{
"id": 11,
"image": "banner/bluebrixhq.gif",
"link": "https://brix.neocities.org"
},
{
"id": 12,
"image": "banner/action97.gif",
"link": "https://bloxy97.nekoweb.org"
},
{ {
"id": 13, "id": 13,
"image": "banner/barco.gif", "image": "banner/imsnp.png",
"link": "https://barcohot.nekoweb.org" "link": "http://kooper.online/blog/pages/imsnp.html"
}, },
{ {
"id": 14, "id": 14,
"image": "banner/pentralink.gif", "image": "banner/aomeix.jpg",
"link": "https://pentalink.yooco.org/" "link": "http://aomeix.eu.org"
} },
{
"id": 15,
"image": "banner/bluebrixhq.gif",
"link": "https://brix.neocities.org"
},
{
"id": 16,
"image": "banner/thebrothers.png",
"link": "https://the-brothers.neocities.org"
},
{
"id": 17,
"image": "banner/action97.gif",
"link": "https://bloxy97.nekoweb.org"
},
{
"id": 18,
"image": "banner/barco.gif",
"link": "https://barcohot.nekoweb.org"
}
] ]
+8 -8
View File
@@ -1,10 +1,10 @@
[ [
"crosstalk.im", "crosstalk.im",
"ct.chat", "ct.chat",
"crosstalk.chat", "crosstalk.chat",
"crosstalk.com", "crosstalk.com",
"gamening.com", "gamening.com",
"escargot.chat", "escargot.chat",
"escargot.com", "escargot.com",
"nina.chat" "nina.chat"
] ]
+3 -3
View File
@@ -2,19 +2,19 @@
{ {
"id": 1, "id": 1,
"url": "http://wiby.me/", "url": "http://wiby.me/",
"image": "http://static.ugnet.xyz/svc/tab/wiby.png", "image": "http://static.ugnet.gay/svc/tab/wiby.png",
"tooltip": "Wiby" "tooltip": "Wiby"
}, },
{ {
"id": 2, "id": 2,
"url": "http://theoldnet.com", "url": "http://theoldnet.com",
"image": "http://static.ugnet.xyz/svc/tab/theoldnet.png", "image": "http://static.ugnet.gay/svc/tab/theoldnet.png",
"tooltip": "TheOldNet" "tooltip": "TheOldNet"
}, },
{ {
"id": 3, "id": 3,
"url": "http://classicconnect.net", "url": "http://classicconnect.net",
"image": "http://static.ugnet.xyz/svc/tab/classicconnect.png", "image": "http://static.ugnet.gay/svc/tab/classicconnect.png",
"tooltip": "ClassicConnect" "tooltip": "ClassicConnect"
} }
] ]
+16
View File
@@ -19,6 +19,10 @@
"caption": "Wiby - The search engine for the classic web.", "caption": "Wiby - The search engine for the classic web.",
"url": "http://wiby.me" "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.", "caption": "Arch Linux - A simple, lightweight Linux distribution.",
"url": "https://archlinux.org" "url": "https://archlinux.org"
@@ -27,6 +31,14 @@
"caption": "Gentoo - A highly flexible, source-based Linux distribution.", "caption": "Gentoo - A highly flexible, source-based Linux distribution.",
"url": "https://www.gentoo.org" "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!", "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" "url": "http://webtv.zone"
@@ -75,6 +87,10 @@
"caption": "GrapheneOS is a private and secure Android-based operating system.", "caption": "GrapheneOS is a private and secure Android-based operating system.",
"url": "https://grapheneos.org/" "url": "https://grapheneos.org/"
}, },
{
"caption": "BitView - Express Yourself.",
"url": "https://www.bitview.net/"
},
{ {
"caption": "SpaceHey - a space for friends.", "caption": "SpaceHey - a space for friends.",
"url": "https://spacehey.com" "url": "https://spacehey.com"
+7
View File
@@ -0,0 +1,7 @@
[{
"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 username aliasing/email masking system."
}]
-154
View File
@@ -1,154 +0,0 @@
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] <Info> {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] <Info> {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)
-243
View File
@@ -1,243 +0,0 @@
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 = '<I>' + part + '</I>'
if bold:
part = '<B>' + part + '</B>'
parts.append(part)
lines.append(''.join(parts))
out.append('<P{}>{}</P>'.format(attrs, '<BR/>'.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 = ['<TEXT>{}</TEXT>'.format(escape(self.text))]
if emailed and self.email_text:
parts.append('<EMAILTEXT>{}</EMAILTEXT>'.format(escape(self.email_text)))
if dialect >= MSNP_TEXTX and (self.rich or self.align != 'left'):
parts.append('<TEXTX>{}</TEXTX>'.format(escape(textx_document(self.paragraphs, self.align))))
return '<BODY{}>\n\t\t\t{}\n\t\t</BODY>'.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 = '<TO {}>\n\t\t<VIA agent={} />\n\t</TO>'.format(to_attrs, quoteattr(self.via))
else:
to = '<TO {} />'.format(to_attrs)
doc = (
'<NOTIFICATION ver="1" id="{id}" siteid="{siteid}" siteurl={siteurl}>\n'
'\t{to}\n'
'\t<MSG pri="{pri}" id="{mid}">\n'
'\t\t<ACTION url={action} />\n'
'\t\t<SUBSCR url={subscr} />\n'
'\t\t{body}\n'
'\t</MSG>\n'
'</NOTIFICATION>'
).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)
+44 -442
View File
@@ -1,8 +1,7 @@
from typing import Dict, List, Set, Any, Tuple, Optional, Iterable, Callable from typing import Dict, List, Set, Any, Tuple, Optional, Iterable
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
from datetime import datetime import asyncio, traceback, settings, smtplib, pprint
import asyncio, traceback, settings, smtplib, pprint, re from collections import defaultdict
from collections import defaultdict, deque
from enum import IntFlag from enum import IntFlag
from util.misc import gen_uuid, first_in_iterable, run_loop, Runner, server_temp_cleanup from util.misc import gen_uuid, first_in_iterable, run_loop, Runner, server_temp_cleanup
@@ -11,13 +10,11 @@ from .user import UserService
from .auth import AuthService, LoginAuthService, GenTokenStr from .auth import AuthService, LoginAuthService, GenTokenStr
from .stats import Stats from .stats import Stats
from .client import Client from .client import Client
from .abuse import AbuseService, RATED_MESSAGE_TYPES
from .models import ( from .models import (
User, UserDetail, Group, ContactList, OIM, Contact, ContactDetail, Circle, CircleRole, CircleState, User, UserDetail, Group, ContactList, OIM, Contact, ContactDetail, Circle, CircleRole, CircleState,
CircleMembership, Chatroom, UserStatus, TextWithData, MessageData, MessageType, Substatus, LoginOption, _is_blocking, CircleMembership, Chatroom, UserStatus, TextWithData, MessageData, Substatus, LoginOption, _is_blocking,
) )
from . import error, event from . import error, event
from .alerts import Alert
class Ack(IntFlag): class Ack(IntFlag):
Zero = 0 Zero = 0
@@ -29,8 +26,7 @@ class Backend:
__slots__ = ( __slots__ = (
'user_service', 'auth_service', 'login_auth_service', 'loop', 'notify_maintenance', 'maintenance_mode', 'maintenance_mins', '_stats', '_sc', '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', '_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', 'recent_alerts', 'on_user_deleted', '_worklist_notify', '_worklist_notify_self', '_runners', '_linked', '_dev',
'_watches', 'abuse',
) )
user_service: UserService user_service: UserService
@@ -52,11 +48,7 @@ class Backend:
_runners: List[Runner] _runners: List[Runner]
_linked: bool _linked: bool
_dev: Optional[Any] _dev: Optional[Any]
recent_alerts: 'deque[Dict[str, Any]]'
on_user_deleted: Optional[Callable[[str, str], None]]
_watches: '_WatchRegistry'
abuse: AbuseService
def __init__(self, def __init__(self,
loop: asyncio.AbstractEventLoop, *, loop: asyncio.AbstractEventLoop, *,
user_service: UserService, login_auth_service: LoginAuthService, auth_service: AuthService, stats_service: Stats, user_service: UserService, login_auth_service: LoginAuthService, auth_service: AuthService, stats_service: Stats,
@@ -80,11 +72,7 @@ class Backend:
self._runners = [] self._runners = []
self._linked = False self._linked = False
self._dev = None self._dev = None
self.recent_alerts = deque(maxlen = 50)
self.on_user_deleted = None
self._watches = _WatchRegistry()
self.abuse = AbuseService(self)
server_temp_cleanup() server_temp_cleanup()
for circle in self.user_service.get_all_circles(): for circle in self.user_service.get_all_circles():
self.chat_create(circle = circle) self.chat_create(circle = circle)
@@ -97,15 +85,11 @@ class Backend:
loop.create_task(self._worker_sync_stats()) loop.create_task(self._worker_sync_stats())
loop.create_task(self._worker_notify()) loop.create_task(self._worker_notify())
loop.create_task(self._worker_notify_self()) loop.create_task(self._worker_notify_self())
loop.create_task(self._worker_purge_suspended())
def push_client_alert(self, alert: Alert) -> int: def push_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None:
print(f"[Backend] Pushing system alert") print(f"[Backend] Pushing system alert")
delivered = 0
for bs in self._sc.iter_sessions(): for bs in self._sc.iter_sessions():
if bs.evt.on_client_alert(alert): bs.evt.on_client_alert(icon_url, url, message)
delivered += 1
return delivered
def push_maintenance_message(self, *args: Any, **kwargs: Any) -> None: 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") print(f"[Backend] Server going down for maintenance in {args[1]} minutes. Pushing system alert")
@@ -140,8 +124,6 @@ class Backend:
old_substatus = user.status.substatus old_substatus = user.status.substatus
self._stats.on_logout() self._stats.on_logout()
self._sc.remove_session(sess) self._sc.remove_session(sess)
# a closed session's client-side buddy list goes with it
self._watches.remove_session(sess)
print(f"[Presence] <Info> BackendSession {str(id(sess))} belonging to {user.username} ({user.email}) has been closed") print(f"[Presence] <Info> BackendSession {str(id(sess))} belonging to {user.username} ({user.email}) has been closed")
if self._sc.get_sessions_by_user(user): if self._sc.get_sessions_by_user(user):
# There are still other people logged in as this user, # There are still other people logged in as this user,
@@ -180,7 +162,6 @@ class Backend:
self._stats.on_login() self._stats.on_login()
self._stats.on_user_active(user, client) self._stats.on_user_active(user, client)
self._sc.add_session(bs) self._sc.add_session(bs)
self._stats.on_online(self._sc.session_count())
user.detail = self._load_detail(user) user.detail = self._load_detail(user)
print(f"[Presence] <Info> {user.username} ({user.email}) has logged in with BackendSession ID {str(id(bs))}") print(f"[Presence] <Info> {user.username} ({user.email}) has logged in with BackendSession ID {str(id(bs))}")
print(f"[Presence] <Info> They are using {client.program.upper()} {client.version} via {client.via}") print(f"[Presence] <Info> They are using {client.program.upper()} {client.version} via {client.via}")
@@ -196,8 +177,6 @@ class Backend:
def _load_detail(self, user: User) -> UserDetail: def _load_detail(self, user: User) -> UserDetail:
if user.detail: return user.detail 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) detail = self.user_service.get_detail(user.uuid)
assert detail is not None assert detail is not None
return detail return detail
@@ -260,20 +239,6 @@ class Backend:
def _notify_self(self, bs: 'BackendSession', old_substatus: Substatus, *, update_status: bool = True, update_info: bool = True) -> None: 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)) 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: def _mark_modified(self, user: User, *, detail: Optional[UserDetail] = None) -> None:
ud = user.detail or detail ud = user.detail or detail
if detail: assert ud is detail if detail: assert ud is detail
@@ -283,14 +248,8 @@ class Backend:
def _mark_circle_modified(self, circle: Circle) -> None: def _mark_circle_modified(self, circle: Circle) -> None:
self._worklist_sync_circles[circle.chat_id] = circle self._worklist_sync_circles[circle.chat_id] = circle
def util_get_user_email(self, user: User) -> str:
return self.user_service.get_user_email(user)
def util_get_display_email(self, user: User) -> str:
return self.user_service.get_display_email(user)
def util_get_uuid_from_email(self, email: str) -> Optional[str]: def util_get_uuid_from_email(self, email: str) -> Optional[str]:
return self.user_service.lookup_uuid_by_email(email) return self.user_service.get_uuid(email)
def util_get_uuid_from_username(self, username: str) -> Optional[str]: def util_get_uuid_from_username(self, username: str) -> Optional[str]:
return self.user_service.get_uuid_username(username) return self.user_service.get_uuid_username(username)
@@ -298,54 +257,6 @@ class Backend:
def util_get_uuid_from_user_id(self, uid: int) -> Optional[str]: def util_get_uuid_from_user_id(self, uid: int) -> Optional[str]:
return self.user_service.get_uuid_user_id(uid) 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: def util_set_sess_token(self, sess: 'BackendSession', token: str) -> None:
self._sc.set_nc_by_token(sess, token) self._sc.set_nc_by_token(sess, token)
@@ -355,177 +266,6 @@ class Backend:
def util_get_sessions_by_user(self, user: User) -> List['BackendSession']: def util_get_sessions_by_user(self, user: User) -> List['BackendSession']:
return self._sc.get_sessions_by_user(user) 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] <Info> {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] <Info> {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] <Info> {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]: 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] return [membership for membership in circle.memberships.values() if membership.role == role]
@@ -604,7 +344,6 @@ class Backend:
membership.role = CircleRole.Member membership.role = CircleRole.Member
membership.state = CircleState.Empty membership.state = CircleState.Empty
membership_inviter_email = membership.inviter_email
if membership.inviter_uuid is not None: if membership.inviter_uuid is not None:
membership.inviter_uuid = None membership.inviter_uuid = None
if membership.inviter_email is not None: if membership.inviter_email is not None:
@@ -616,7 +355,7 @@ class Backend:
for bs_other in self.util_get_sessions_by_user(user): for bs_other in self.util_get_sessions_by_user(user):
print(f"[Circle] <Info> {user.username} ({user.email})'s invitation to {circle.name} (ID: {circle.chat_id}) has been revoked") print(f"[Circle] <Info> {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] <Info> It was sent by {membership_inviter_email}") if membership_inviter_email is not None: print(f"[Circle] <Info> It was sent by {membership.inviter_email}")
bs_other.evt.on_circle_invite_revoked(circle.chat_id) bs_other.evt.on_circle_invite_revoked(circle.chat_id)
if chat is not None: if chat is not None:
@@ -711,7 +450,7 @@ class Backend:
async def _worker_sync_db(self) -> None: async def _worker_sync_db(self) -> None:
while True: while True:
await asyncio.sleep(0.04) await asyncio.sleep(0.0125)
self._sync_db_impl() self._sync_db_impl()
def _sync_db_impl(self) -> None: def _sync_db_impl(self) -> None:
@@ -729,7 +468,7 @@ class Backend:
async def _worker_remove_expired_login_tokens(self) -> None: async def _worker_remove_expired_login_tokens(self) -> None:
while True: while True:
await asyncio.sleep(0.04) await asyncio.sleep(0.0125)
self._remove_expired_login_tokens() self._remove_expired_login_tokens()
def _remove_expired_login_tokens(self) -> None: def _remove_expired_login_tokens(self) -> None:
@@ -738,18 +477,9 @@ class Backend:
except: except:
traceback.print_exc() 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: async def _worker_sync_circles(self) -> None:
while True: while True:
await asyncio.sleep(0.04) await asyncio.sleep(0.0125)
self._sync_circle_impl() self._sync_circle_impl()
def _sync_circle_impl(self) -> None: def _sync_circle_impl(self) -> None:
@@ -767,7 +497,7 @@ class Backend:
async def _worker_clean_sessions(self) -> None: async def _worker_clean_sessions(self) -> None:
while True: while True:
await asyncio.sleep(0.04) await asyncio.sleep(0.0125)
closed = [] closed = []
try: try:
@@ -784,14 +514,14 @@ class Backend:
while True: while True:
await asyncio.sleep(60) await asyncio.sleep(60)
try: try:
self._stats.flush(online = self._sc.session_count()) self._stats.flush()
except: except:
traceback.print_exc() traceback.print_exc()
async def _worker_notify(self) -> None: async def _worker_notify(self) -> None:
# Notify relevant `BackendSession`s of status, name, message, media, etc. changes # Notify relevant `BackendSession`s of status, name, message, media, etc. changes
while True: while True:
await asyncio.sleep(0.04) await asyncio.sleep(0.0125)
try: try:
self._handle_worklist_notify() self._handle_worklist_notify()
except: except:
@@ -803,7 +533,8 @@ class Backend:
for bs, sess_id, on_contact_add, old_substatus, updated_phone_info, update_status, update_info_other, for_logout in worklist: for bs, sess_id, on_contact_add, old_substatus, updated_phone_info, update_status, update_info_other, for_logout in worklist:
user = bs.user user = bs.user
detail = user.detail detail = user.detail
for ctc in (detail.contacts.values() if detail is not None else ()): assert detail is not None
for ctc in detail.contacts.values():
for bs_other in self._sc.get_sessions_by_user(ctc.head): for bs_other in self._sc.get_sessions_by_user(ctc.head):
if bs_other.user is user: continue if bs_other.user is user: continue
detail_other = bs_other.user.detail detail_other = bs_other.user.detail
@@ -817,15 +548,6 @@ class Backend:
ctc_me, on_contact_add, old_substatus, sess_id = sess_id, updated_phone_info = updated_phone_info, 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, 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): 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 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 if bs not in self._cses_by_bs_by_circle_id[circle.chat_id]: continue
@@ -844,7 +566,7 @@ class Backend:
# Notify relevant `BackendSession`s of status, name, message, media, etc. changes # Notify relevant `BackendSession`s of status, name, message, media, etc. changes
worklist = self._worklist_notify_self worklist = self._worklist_notify_self
while True: while True:
await asyncio.sleep(0.04) await asyncio.sleep(0.0125)
try: try:
for bs, old_substatus, update_status, update_info in worklist: for bs, old_substatus, update_status, update_info in worklist:
user = bs.user user = bs.user
@@ -871,19 +593,6 @@ class Session(metaclass = ABCMeta):
@abstractmethod @abstractmethod
def _on_close(self, **kwargs: Any) -> None: pass 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): class BackendSession(Session):
__slots__ = ('backend', 'user', 'client', 'chat_enabled', 'evt', 'front_data') __slots__ = ('backend', 'user', 'client', 'chat_enabled', 'evt', 'front_data')
@@ -1018,44 +727,7 @@ class BackendSession(Session):
) )
if notify_self: if notify_self:
self.backend._notify_self(self, old_substatus, update_status = notify_status, update_info = notify_info_other) 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: def me_group_add(self, name: str, *, is_favorite: Optional[bool] = None) -> Group:
if len(name) > MAX_GROUP_NAME_LENGTH: if len(name) > MAX_GROUP_NAME_LENGTH:
raise error.GroupNameTooLong() raise error.GroupNameTooLong()
@@ -1085,7 +757,7 @@ class BackendSession(Session):
detail.delete_group(group) detail.delete_group(group)
for ctc in detail.contacts.values(): for ctc in detail.contacts.values():
ctc.remove_from_group(group) ctc.remove_from_group(group)
print(f'[Contacts] <Info> {user.username} ({user.email}) has deleted group {group.name} (ID: {group_id})') print(f'[Contacts] <Info> {user.username} ({user.email}) has deleted group {name} (ID: {group_id})')
self.backend._mark_modified(user) self.backend._mark_modified(user)
def me_group_edit(self, group_id: str, *, new_name: Optional[str] = None, is_favorite: Optional[bool] = None) -> None: def me_group_edit(self, group_id: str, *, new_name: Optional[str] = None, is_favorite: Optional[bool] = None) -> None:
@@ -1365,7 +1037,7 @@ class BackendSession(Session):
invite_msg = f"""\ invite_msg = f"""\
Subject: {sender_email} wants to talk to you using CrossTalk! Subject: {sender_email} wants to talk to you using CrossTalk!
To: {email} To: {email}
From: CrossTalk network administration <administration@ugnet.xyz> From: undergr0und network administration <administration@ugnet.gay>
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. 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.
@@ -1388,7 +1060,7 @@ They've attached this message, as well:
with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) as server: with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) as server:
server.starttls() server.starttls()
server.login(settings.SMTP_USERNAME, settings.SMTP_PASSWORD) server.login(settings.SMTP_USERNAME, settings.SMTP_PASSWORD)
server.sendmail("administration@ugnet.xyz", email, invite_msg) server.sendmail("administration@ugnet.gay", email, invite_msg)
else: else:
print(f"[Mailer] <Info> {sender_email} already has an account. Not sending an invitation e-mail.") print(f"[Mailer] <Info> {sender_email} already has an account. Not sending an invitation e-mail.")
@@ -1624,9 +1296,6 @@ class _SessionCollection:
def iter_sessions(self) -> Iterable[BackendSession]: def iter_sessions(self) -> Iterable[BackendSession]:
yield from self._sessions yield from self._sessions
def session_count(self) -> int:
return len(self._sessions)
def set_nc_by_token(self, sess: BackendSession, token: str) -> None: def set_nc_by_token(self, sess: BackendSession, token: str) -> None:
self._sess_by_token[token] = sess self._sess_by_token[token] = sess
self._tokens_by_sess[sess].add(token) self._tokens_by_sess[sess].add(token)
@@ -1789,6 +1458,13 @@ class Chat:
last_pop = False 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]] sess_others = [sess_other for sess_other in self._users_by_sess.keys() if sess_other.user is su[0]]
if sess_others: if sess_others:
@@ -1799,9 +1475,7 @@ class Chat:
break break
if no_primary_pop: if no_primary_pop:
sess_others[-1].primary_pop = True sess_others[-1].primary_pop = True
else: elif last_pop:
# `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 last_pop = True
# Notify others that `sess` has left # Notify others that `sess` has left
@@ -1863,57 +1537,37 @@ class ChatSession(Session):
if len(ctc_sessions) == len(disabled_sessions): raise error.ContactNotOnline() if len(ctc_sessions) == len(disabled_sessions): raise error.ContactNotOnline()
if len(ctc_sessions) == len(already_invited_sessions): raise error.ContactAlreadyOnContactList() if len(ctc_sessions) == len(already_invited_sessions): raise error.ContactAlreadyOnContactList()
def send_message_to_everyone(self, data: MessageData) -> bool: def send_message_to_everyone(self, data: MessageData) -> None:
stats = self.chat._stats stats = self.chat._stats
client = self.bs.client client = self.bs.client
backend = self.bs.backend
if stats:
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_message_sent(self.user, client)
stats.on_user_active(self.user, client) stats.on_user_active(self.user, client)
tracked: Set[str] = set() for cs_other in self.chat._users_by_sess.keys():
for cs_other in list(self.chat._users_by_sess.keys()):
if cs_other is self: continue if cs_other is self: continue
if self.chat.circle is not None and self.chat.circle.memberships[cs_other.user.uuid].blocking: 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) cs_other.evt.on_message(data)
print(f"[Chat] <Info> {self.user.username} ({self.user.email}) has sent a messasge to {cs_other.user.username} ({cs_other.user.email}) of type {data.type}") print(f"[Chat] <Info> {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: if stats:
stats.on_message_received(cs_other.user, client) stats.on_message_received(cs_other.user, client)
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) def send_message_to_user(self, user_uuid: str, data: MessageData) -> None:
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 stats = self.chat._stats
client = self.bs.client client = self.bs.client
backend = self.bs.backend
if stats:
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_message_sent(self.user, client)
stats.on_user_active(self.user, client) stats.on_user_active(self.user, client)
tracked = False for cs_other in self.chat._users_by_sess.keys():
for cs_other in list(self.chat._users_by_sess.keys()):
if cs_other is self: continue if cs_other is self: continue
if cs_other.user.uuid != user_uuid: continue if cs_other.user.uuid != user_uuid: continue
print(f"[Chat] <Info> {self.user.username} ({self.user.email}) has sent a messasge to {cs_other.user.username} ({cs_other.user.email}) of type {data.type}") print(f"[Chat] <Info> {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) cs_other.evt.on_message(data)
if stats and data.type in _STATS_MESSAGE_TYPES: if stats:
stats.on_message_received(cs_other.user, client) 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: def _gen_group_id(detail: UserDetail) -> str:
id = 1 id = 1
@@ -1935,62 +1589,10 @@ def _gen_contact_id(detail: UserDetail) -> str:
MAX_GROUP_NAME_LENGTH = 61 MAX_GROUP_NAME_LENGTH = 61
_STATS_MESSAGE_TYPES = (MessageType.Chat, MessageType.Nudge, MessageType.Emoticon, MessageType.Ink)
# TODO: PL # TODO: PL
LST_LIMITS = { LST_LIMITS = {
ContactList.FL: 1000, ContactList.FL: 1000,
ContactList.AL: 1500, ContactList.AL: 1500,
ContactList.BL: 1200, ContactList.BL: 1200,
ContactList.RL: 1500, ContactList.RL: 1500,
} }
_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
+5 -93
View File
@@ -46,11 +46,11 @@ class User(WithFrontData):
date_created = Col(sa.DateTime, default = datetime.utcnow) date_created = Col(sa.DateTime, default = datetime.utcnow)
date_login = Col(sa.DateTime, nullable = True) date_login = Col(sa.DateTime, nullable = True)
uuid = Col(sa.String(50), unique = True) uuid = Col(sa.String(50), unique = True)
email = Col(sa.String(80, collation='utf8mb4_unicode_ci'), nullable=False, unique=True) email = Col(sa.String(80))
username = Col(sa.String(40, collation='utf8mb4_unicode_ci'), nullable=False, unique=True) username = Col(sa.String(40))
first_name = Col(sa.String(50), nullable = True) first_name = Col(sa.String(50), default = 'John')
middle_name = Col(sa.String(50), nullable = True) middle_name = Col(sa.String(50), nullable = True)
last_name = Col(sa.String(50), nullable = True) last_name = Col(sa.String(50), default = 'Doe')
# specifically used for social features/member directory # specifically used for social features/member directory
nickname = Col(sa.String(60), nullable = True) nickname = Col(sa.String(60), nullable = True)
uin = Col(sa.BigInteger, nullable = True) uin = Col(sa.BigInteger, nullable = True)
@@ -68,7 +68,6 @@ class User(WithFrontData):
groups = Col(JSONType) groups = Col(JSONType)
settings = Col(JSONType) settings = Col(JSONType)
suspended = Col(sa.Boolean) suspended = Col(sa.Boolean)
suspended_at = Col(sa.DateTime, nullable = True)
is_tester = Col(sa.Boolean) is_tester = Col(sa.Boolean)
is_mvp = Col(sa.Boolean) is_mvp = Col(sa.Boolean)
show_in_dir = Col(sa.Boolean) show_in_dir = Col(sa.Boolean)
@@ -77,9 +76,7 @@ class User(WithFrontData):
alias_active = Col(sa.Boolean, default=False) alias_active = Col(sa.Boolean, default=False)
did_firsttime_email_change = 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 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) 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") profile = relationship("UserProfile", backref="user", uselist=False, cascade="all, delete-orphan")
__table_args__ = (sa.Index('email_ci_index', sa.text('(LOWER(email))'), unique = True), sa.Index('username_ci_index', sa.text('(LOWER(username))'), unique = True)) __table_args__ = (sa.Index('email_ci_index', sa.text('(LOWER(email))'), unique = True), sa.Index('username_ci_index', sa.text('(LOWER(username))'), unique = True))
@@ -133,7 +130,7 @@ class UserProfile(WithFrontData):
state = Col(sa.String(80), nullable = True) state = Col(sa.String(80), nullable = True)
zip = Col(sa.Integer, nullable = True) zip = Col(sa.Integer, nullable = True)
country = Col(sa.String(60), nullable = True) country = Col(sa.String(60), nullable = True)
language = Col(JSONType, nullable = True) language = Col(sa.String(50), nullable = True)
interests = Col(JSONType, nullable = True, default = {}) interests = Col(JSONType, nullable = True, default = {})
visibility = Col(sa.String(25), default='public') visibility = Col(sa.String(25), default='public')
@@ -174,68 +171,6 @@ class Sound(Base):
is_public = Col(sa.Boolean) is_public = Col(sa.Boolean)
hits = Col(sa.Integer, default = 0) 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): class LoginToken(Base):
__tablename__ = 'login_token' __tablename__ = 'login_token'
@@ -259,29 +194,6 @@ def _simplify_json_data(data: Any) -> Any:
return [_simplify_json_data(x) for x in data] return [_simplify_json_data(x) for x in data]
return 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) 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) session_factory = sessionmaker(bind = engine)
+5 -82
View File
@@ -2,7 +2,6 @@ from typing import TYPE_CHECKING, Optional, Dict, Any, List
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
from .models import User, Contact, OIM, Circle, CircleRole, MessageData, TextWithData, Substatus, LoginOption from .models import User, Contact, OIM, Circle, CircleRole, MessageData, TextWithData, Substatus, LoginOption
from .alerts import Alert
from util.misc import MultiDict from util.misc import MultiDict
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -27,15 +26,12 @@ class BackendEventHandler(metaclass = ABCMeta):
def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None: def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None:
pass pass
def on_client_alert(self, alert: Alert) -> bool: def on_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None:
return False pass
def on_maintenance_boot(self) -> None: def on_maintenance_boot(self) -> None:
pass pass
def on_warning_level_changed(self, level: int, warner: Optional[User]) -> None:
pass
@abstractmethod @abstractmethod
def on_presence_notification( def on_presence_notification(
self, ctc: Contact, on_contact_add: bool, old_substatus: Substatus, *, self, ctc: Contact, on_contact_add: bool, old_substatus: Substatus, *,
@@ -96,23 +92,17 @@ class BackendEventHandler(metaclass = ABCMeta):
pass pass
def msn_on_uun_sent( def msn_on_uun_sent(
self, sender: User, type: Optional[int], data: Optional[bytes], *, self, sender: User, type: int, data: Optional[bytes], *,
pop_id_sender: Optional[str] = None, pop_id: Optional[str] = None, sdg: Optional[bytes] = None, pop_id_sender: Optional[str] = None, pop_id: Optional[str] = None,
) -> None: ) -> None:
pass pass
def msn_on_notify_ab(self) -> None: def msn_on_notify_ab(self) -> None:
pass pass
def msn_on_whats_new(self, publisher: User) -> None:
pass
def msn_on_notify_circle_ab(self, chat_id: str) -> None: def msn_on_notify_circle_ab(self, chat_id: str) -> None:
pass 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: def ymsg_on_p2p_msg_request(self, sess_id: int, yahoo_data: MultiDict[bytes, bytes]) -> None:
pass pass
@@ -125,74 +115,7 @@ class BackendEventHandler(metaclass = ABCMeta):
def ymsg_on_upload_file_ft(self, recipient: str, message: str) -> None: def ymsg_on_upload_file_ft(self, recipient: str, message: str) -> None:
pass 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): class ChatEventHandler(metaclass = ABCMeta):
__slots__ = ('cs',) __slots__ = ('cs',)
+41 -34
View File
@@ -3,8 +3,7 @@ from typing import Any, Dict, Optional
from aiohttp import web, ClientSession, ClientTimeout, ClientError from aiohttp import web, ClientSession, ClientTimeout, ClientError
from pathlib import Path from pathlib import Path
from util.misc import AIOHTTPRunner from util.misc import AIOHTTPRunner, _get_avatar_path
from util.avatar import get_avatar_data
from core.backend import Backend from core.backend import Backend
from brutus import Brutus from brutus import Brutus
@@ -25,9 +24,7 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, *, devmode: bool
backend.add_runner(AIOHTTPRunner(http_host, http_port, app, ssl_context=ssl_context, service='HTTP')) 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_get('/', handle_misc_conns)
app.router.add_post('/', handle_blankok) app.router.add_post('/', handle_blankok)
# TODO: migrate to static.ugnet.xyz
app.router.add_static('/static', 'core/static') 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/txt', handle_textad)
app.router.add_get('/ads/banner', handle_bannerad) app.router.add_get('/ads/banner', handle_bannerad)
app.router.add_get('/ads/banner-lg', lambda req: handle_bannerad(req, yuge=True)) app.router.add_get('/ads/banner-lg', lambda req: handle_bannerad(req, yuge=True))
@@ -35,8 +32,8 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, *, devmode: bool
app.router.add_get('/ads/GetMSNAdImage.asmx', handle_msnbannerimg) app.router.add_get('/ads/GetMSNAdImage.asmx', handle_msnbannerimg)
app.router.add_get('/svcs/mms/adxml_main.asp', lambda req: handle_bannerad(req, msnxml=True)) 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}/static', handle_avatar)
app.router.add_get('/avatar/{uuid}/small', lambda req: handle_avatar(req, small=True)) app.router.add_get('/avatar/{uuid}/small', lambda req: handle_avatar(req, small = True))
app.router.add_get('/avatar/{uuid}/im', lambda req: handle_avatar(req, im=True)) app.router.add_route('*', '/{path:.*}', handle_notfound)
return app return app
@@ -49,18 +46,11 @@ def create_app(loop: asyncio.AbstractEventLoop, backend: Backend) -> Any:
) )
app.on_response_prepare.append(on_response_prepare) app.on_response_prepare.append(on_response_prepare)
app.middlewares.append(notfound_middleware)
util.misc.add_to_jinja_env(app, 'misc', MISC_TMPL_DIR) util.misc.add_to_jinja_env(app, 'misc', MISC_TMPL_DIR)
return app 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: async def on_response_prepare(req: web.Request, res: web.StreamResponse) -> None:
res.headers['X-Azul-Version'] = settings.VERSION res.headers['X-Azul-Version'] = settings.VERSION
@@ -94,7 +84,7 @@ async def handle_notfound(req: web.Request) -> web.Response:
return render(req, 'misc:miscconns.html', { return render(req, 'misc:miscconns.html', {
'settings': settings 'settings': settings
}, status=404) }, status=404)
async def handle_bannerad(req: web.Request, yuge: bool = False, sq: bool = False, msnxml: bool = False) -> web.Response: 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: 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) data = json.load(json_file)
@@ -110,8 +100,8 @@ async def handle_bannerad(req: web.Request, yuge: bool = False, sq: bool = False
'Content-Type': 'text/xml' if msnxml else 'text/html', 'Content-Type': 'text/xml' if msnxml else 'text/html',
} }
html_response = f'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html style="-ms-overflow-style: none;"><body style="-ms-overflow-style: none;overflow: hidden;padding:0;margin:0;overflow:hidden;-ms-scroll-limit: 0 0 0 0;" scroll=no><a href="{image_link}" style="text-decoration:none;" target="_blank"><img border="0" src="http://{settings.STATIC_HOST}/svc/ads/ct/{random_entry["image"]}"></a></body></html>' html_response = f'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html style="-ms-overflow-style: none;"><body style="-ms-overflow-style: none;overflow: hidden;padding:0;margin:0;overflow:hidden;-ms-scroll-limit: 0 0 0 0;" scroll=no><a href="{image_link}" style="text-decoration:none;" target="_blank"><img border="0" src="http://static.ugnet.gay/svc/ads/ct/{random_entry["image"]}"></a></body></html>'
msn_response = f'<?xml version="1.0"?><ADRSP V="{version}"><image IMG="http://{settings.AD_HOST}/ads/GetMSNAdImage.asmx?id={id}" ALT="Advertisement" HEIGHT="60" WIDTH="234"/><click CLK="{image_link}" TARGET="_NEW"/></ADRSP>' msn_response = f'<?xml version="1.0"?><ADRSP V="{version}"><image IMG="http://ctsvcs.advertising.ugnet.gay/ads/GetMSNAdImage.asmx?id={id}" ALT="Advertisement" HEIGHT="60" WIDTH="234"/><click CLK="{image_link}" TARGET="_NEW"/></ADRSP>'
return web.HTTPOk(body=msn_response if msnxml else html_response, headers=headers) return web.HTTPOk(body=msn_response if msnxml else html_response, headers=headers)
async def handle_msnbannerimg(req: web.Request) -> web.Response: async def handle_msnbannerimg(req: web.Request) -> web.Response:
@@ -129,7 +119,7 @@ async def handle_msnbannerimg(req: web.Request) -> web.Response:
else: else:
entry = random.choice(data) entry = random.choice(data)
image_url = f"http://{settings.STATIC_HOST}/svc/ads/ct/{entry['image']}" image_url = f"http://static.ugnet.gay/svc/ads/ct/{entry['image']}"
async with ClientSession() as sess: async with ClientSession() as sess:
async with sess.get(image_url) as resp: async with sess.get(image_url) as resp:
@@ -162,29 +152,46 @@ 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. # 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) return web.Response(status = 200)
async def handle_avatar(req: web.Request, small: bool = False, im: bool = False) -> web.Response: async def handle_avatar(req: web.Request, small: bool = False) -> web.Response:
uuid = req.match_info['uuid'] uuid = req.match_info['uuid']
backend: Backend = req.app['backend'] storage_path: Path = _get_avatar_path(uuid)
user = backend.user_service.get(uuid) if not (storage_path.exists() and storage_path.is_dir()):
avatar_md5 = user.avatar if user else None return await _get_default_avatar(small)
else:
chosen: Path | None = None
for p in storage_path.iterdir():
if not p.is_file():
continue
if not p.name.startswith(uuid):
continue
has_thumb = "_thumb" in p.stem
if has_thumb == small:
chosen = p
break
md5_query = req.query.get('md5') or '' if chosen is None:
if user is not None and 8 <= len(md5_query) <= 32 and all(c in '0123456789abcdef' for c in md5_query): for p in storage_path.iterdir():
result = get_avatar_data(uuid, md5_query, small=small, im=im) if p.is_file() and p.name.startswith(uuid):
if result is not None: chosen = p
data, content_type = result break
return web.Response(status=200, body=data, content_type=content_type)
result = get_avatar_data(uuid, avatar_md5, small=small, im=im) if chosen is not None and chosen.exists():
if result is not None: try:
data, content_type = result data = chosen.read_bytes()
return web.Response(status=200, body=data, content_type=content_type) if not data:
chosen = None
else:
ext = chosen.suffix.lstrip(".").lower() or "png"
content_type = f"image/{ext}"
return web.Response(status=200, body=data, content_type=content_type)
except (PermissionError, IsADirectoryError, OSError):
chosen = None
return await _get_default_avatar(small) return await _get_default_avatar(small)
async def _get_default_avatar(small: bool) -> web.Response: async def _get_default_avatar(small: bool) -> web.Response:
default_url = f"https://{settings.STATIC_HOST}/svc/userstore/avatar/default-sm.png" if small else f"https://{settings.STATIC_HOST}/svc/userstore/avatar/default.png" default_url = "https://static.ugnet.gay/svc/userstore/avatar/default-sm.png" if small else "https://static.ugnet.gay/svc/userstore/avatar/default.png"
timeout = ClientTimeout(total=5) timeout = ClientTimeout(total=5)
try: try:
async with ClientSession(timeout=timeout) as session: async with ClientSession(timeout=timeout) as session:
@@ -204,4 +211,4 @@ def render(req: web.Request, tmpl_name: str, ctxt: Optional[Dict[str, Any]] = No
content_type = 'text/html' content_type = 'text/html'
tmpl = req.app['jinja_env'].get_template(tmpl_name) tmpl = req.app['jinja_env'].get_template(tmpl_name)
content = tmpl.render(**(ctxt or {})) content = tmpl.render(**(ctxt or {}))
return web.Response(status=status, content_type=content_type, text=content) return web.Response(status=status, content_type=content_type, text=content)
-547
View File
@@ -1,547 +0,0 @@
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)
+610 -1652
View File
File diff suppressed because it is too large. Load diff
+5 -51
View File
@@ -1,90 +1,44 @@
from typing import Optional, Callable from typing import Optional, Callable
import asyncio, ipaddress import asyncio
from core.backend import Backend from core.backend import Backend
from util.misc import Logger from util.misc import Logger
import settings import settings
from .crypto import load_or_generate_server_keys, fingerprint
from .ctrl import INSCtrl from .ctrl import INSCtrl
from .registry import ClientRegistry
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None:
def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> ClientRegistry:
from util.misc import ProtocolRunner from util.misc import ProtocolRunner
keys = load_or_generate_server_keys(settings.INS_KEY_DIR) backend.add_runner(ProtocolRunner('0.0.0.0', 4309, ListenerINS, args = ['InterService', backend, INSCtrl], service = 'InterService'))
if keys.generated:
print(f'[InterService] <Info> Generated the InterService host key in {settings.INS_KEY_DIR}')
print(f'[InterService] <Info> 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] <Info> No clients are enrolled yet. Make an enrollment code for each one in the admin panel (InterService)')
else:
print(f'[InterService] <Info> {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): class ListenerINS(asyncio.Protocol):
logger: Logger logger: Logger
backend: Backend backend: Backend
controller: INSCtrl controller: INSCtrl
transport: Optional[asyncio.WriteTransport] transport: Optional[asyncio.WriteTransport]
allowed: list[IPNetwork]
def __init__( def __init__(self, logger_prefix: str, backend: Backend, controller_factory: Callable[[Logger, str, Backend], INSCtrl]) -> None:
self, logger_prefix: str, backend: Backend, controller_factory: Callable[[Logger, str, Backend], INSCtrl], allowed: list[IPNetwork],
) -> None:
super().__init__() super().__init__()
self.logger = Logger(logger_prefix, self) self.logger = Logger(logger_prefix, self)
self.backend = backend self.backend = backend
self.controller = controller_factory(self.logger, 'direct', backend) self.controller = controller_factory(self.logger, 'direct', backend)
self.controller.close_callback = self._on_close self.controller.close_callback = self._on_close
self.transport = None self.transport = None
self.allowed = allowed
def connection_made(self, transport: asyncio.BaseTransport) -> None: def connection_made(self, transport: asyncio.BaseTransport) -> None:
assert isinstance(transport, asyncio.WriteTransport) 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.transport = transport
self.logger.log_connect() self.logger.log_connect()
self.controller.connection_made(transport)
def connection_lost(self, exc: Optional[Exception]) -> None: def connection_lost(self, exc: Optional[Exception]) -> None:
if self.transport is None:
return
self.controller.close() self.controller.close()
self.logger.log_disconnect() self.logger.log_disconnect()
self.transport = None self.transport = None
def data_received(self, data: bytes) -> None: def data_received(self, data: bytes) -> None:
transport = self.transport transport = self.transport
if transport is None: assert transport is not None
return
if self.backend.maintenance_mode: if self.backend.maintenance_mode:
transport.close() transport.close()
return return
-72
View File
@@ -1,72 +0,0 @@
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
-313
View File
@@ -1,313 +0,0 @@
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
+2 -65
View File
@@ -12,8 +12,6 @@ class User:
'last_name', 'last_name',
'uin', 'uin',
'verified_to_login', 'verified_to_login',
'account_verified',
'alias_active',
'status', 'status',
'detail', 'detail',
'settings', 'settings',
@@ -25,7 +23,6 @@ class User:
'show_in_dir', 'show_in_dir',
'evil_permanent', 'evil_permanent',
'evil_temporary', 'evil_temporary',
'avatar',
'profile' 'profile'
) )
@@ -37,8 +34,6 @@ class User:
last_name: str last_name: str
uin: int uin: int
verified_to_login: bool verified_to_login: bool
account_verified: bool
alias_active: bool
status: 'UserStatus' status: 'UserStatus'
detail: Optional['UserDetail'] detail: Optional['UserDetail']
settings: Dict[str, Any] settings: Dict[str, Any]
@@ -50,12 +45,11 @@ class User:
show_in_dir: bool show_in_dir: bool
evil_permanent: int evil_permanent: int
evil_temporary: int evil_temporary: int
avatar: str
profile: 'UserProfile' profile: 'UserProfile'
def __init__( def __init__(
self, id: int, uuid: str, email: str, username: str, first_name: str, last_name: str, uin: int, verified_to_login: bool, account_verified: bool, alias_active: bool, status: 'UserStatus', self, id: int, uuid: str, email: str, username: str, first_name: str, last_name: str, uin: int, verified_to_login: bool, status: 'UserStatus',
settings: Dict[str, Any], date_created: datetime, date_login: datetime, suspended: bool, is_tester: bool, is_mvp: bool, show_in_dir: bool, evil_permanent: int, evil_temporary: int, avatar: str, profile: 'UserProfile' settings: Dict[str, Any], date_created: datetime, date_login: datetime, suspended: bool, is_tester: bool, is_mvp: bool, show_in_dir: bool, evil_permanent: int, evil_temporary: int, profile: 'UserProfile'
) -> None: ) -> None:
self.id = id self.id = id
self.uuid = uuid self.uuid = uuid
@@ -65,8 +59,6 @@ class User:
self.last_name = last_name self.last_name = last_name
self.uin = uin self.uin = uin
self.verified_to_login = verified_to_login self.verified_to_login = verified_to_login
self.account_verified = account_verified
self.alias_active = alias_active
# `status`: true status of user # `status`: true status of user
self.status = status self.status = status
self.detail = None self.detail = None
@@ -79,7 +71,6 @@ class User:
self.show_in_dir = show_in_dir self.show_in_dir = show_in_dir
self.evil_permanent = evil_permanent self.evil_permanent = evil_permanent
self.evil_temporary = evil_temporary self.evil_temporary = evil_temporary
self.avatar = avatar
self.profile = profile self.profile = profile
class Contact: class Contact:
@@ -144,36 +135,11 @@ class Contact:
if found_group is not None: if found_group is not None:
self._groups.discard(group) 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: def _is_blocking(blocker: User, blockee: User) -> bool:
detail = blocker.detail detail = blocker.detail
assert detail is not None assert detail is not None
contact = detail.contacts.get(blockee.uuid) contact = detail.contacts.get(blockee.uuid)
lists = (contact and contact.lists or 0) 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.BL: return True
if lists & ContactList.AL: return False if lists & ContactList.AL: return False
return (blocker.settings.get('BLP', 'AL') == 'BL') return (blocker.settings.get('BLP', 'AL') == 'BL')
@@ -424,35 +390,6 @@ class TextWithData:
self.text = text self.text = text
self.yahoo_utf8 = yahoo_utf8 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: class RoamingInfo:
__slots__ = ('name', 'name_last_modified', 'message', 'message_last_modified') __slots__ = ('name', 'name_last_modified', 'message', 'message_last_modified')
+8 -293
View File
@@ -1,6 +1,5 @@
from typing import Dict, Any, Optional, List, Iterable, Tuple from typing import Dict, Any, Optional
from datetime import datetime, timedelta from datetime import datetime
import base64, time
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy.orm import declarative_base from sqlalchemy.orm import declarative_base
from HLL import HyperLogLog from HLL import HyperLogLog
@@ -10,43 +9,19 @@ from core.client import Client
from core.models import User from core.models import User
from util.json_type import JSONType from util.json_type import JSONType
HOURS_KEPT = 48
DAYS_KEPT = 35
class Stats: class Stats:
__slots__ = ( __slots__ = ('logged_in', 'by_client', '_conn', '_client_id_cache')
'logged_in', 'by_client', '_conn', '_client_id_cache', 'started', '_day', '_day_stats', '_pending_days', '_past_days',
'_hours', '_peak_record', '_collect_hour',
)
logged_in: int logged_in: int
by_client: Dict[int, Dict[str, Any]] by_client: Dict[int, Dict[str, Any]]
_conn: Conn _conn: Conn
_client_id_cache: Optional[Dict[Client, int]] _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: def __init__(self, conn: Conn) -> None:
self.logged_in = 0 self.logged_in = 0
self.by_client = {} self.by_client = {}
self._conn = conn self._conn = conn
self._client_id_cache = None 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() hour = _current_hour()
with self._conn.session() as sess: with self._conn.session() as sess:
@@ -60,44 +35,12 @@ class Stats:
for client_id, stats in current.value['by_client'].items() 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: def on_login(self) -> None:
self._roll_day()
self.logged_in += 1 self.logged_in += 1
self._day_stats['logins'] += 1
def on_logout(self) -> None: def on_logout(self) -> None:
self.logged_in -= 1 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: def on_user_active(self, user: User, client: Client) -> None:
self._collect('users_active', user, client) self._collect('users_active', user, client)
@@ -125,42 +68,17 @@ class Stats:
if stat not in bhc: if stat not in bhc:
bhc[stat] = 0 bhc[stat] = 0
bhc[stat] += 1 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 _roll_day(self) -> None: def flush(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() hour = _current_hour()
now = datetime.utcnow() now = datetime.utcnow()
if online is not None:
self.on_online(online)
self._roll_day()
with self._conn.session() as sess: with self._conn.session() as sess:
current = sess.query(CurrentStats).filter(CurrentStats.key == 'logged_in').one_or_none() current = sess.query(CurrentStats).filter(CurrentStats.key == 'logged_in').one_or_none()
if not current: if not current:
current = CurrentStats(key = 'logged_in') current = CurrentStats(key = 'logged_in')
current.date_updated = now current.date_updated = now
current.value = (online if online is not None else self.logged_in) current.value = self.logged_in
sess.add(current) sess.add(current)
sess.flush() sess.flush()
@@ -170,37 +88,11 @@ class Stats:
cs_hour = current.value['hour'] cs_hour = current.value['hour']
current.date_updated = now current.date_updated = now
current.value = self._flush_to_hourly(sess, cs_hour) current.value = self._flush_to_hourly(sess, hour)
self._update_hour_totals(cs_hour) sess.add(current)
if cs_hour != hour: if cs_hour != hour:
self.by_client = {} 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]: def _flush_to_hourly(self, sess: Any, hour: int) -> Dict[str, Any]:
for client_id, stats in self.by_client.items(): for client_id, stats in self.by_client.items():
@@ -224,76 +116,6 @@ 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: def _get_client_id(self, client: Client) -> int:
if self._client_id_cache is None: if self._client_id_cache is None:
with self._conn.session() as sess: with self._conn.session() as sess:
@@ -309,110 +131,6 @@ class Stats:
self._client_id_cache[client] = dbobj.id self._client_id_cache[client] = dbobj.id
return self._client_id_cache[client] 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]: def _stats_to_json(stats: Dict[str, Any]) -> Dict[str, Any]:
json = {} json = {}
if 'messages_sent' in stats: if 'messages_sent' in stats:
@@ -440,9 +158,6 @@ def _current_hour() -> int:
ts = now.timestamp() ts = now.timestamp()
return int(ts // 3600) return int(ts // 3600)
def _current_day() -> int:
return _current_hour() // 24
class Base(declarative_base()): # type: ignore class Base(declarative_base()): # type: ignore
__abstract__ = True __abstract__ = True
@@ -470,4 +185,4 @@ class CurrentStats(Base):
key = sa.Column(sa.String(255), nullable = False, primary_key = True) 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')) date_updated = sa.Column(sa.DateTime, nullable = False, server_default = sa.text('CURRENT_TIMESTAMP'))
value = sa.Column(JSONType, nullable = False, default = {}) value = sa.Column(JSONType, nullable = False, default = {})
+2 -2
View File
@@ -1,7 +1,7 @@
from typing import Dict, Tuple, Any, Optional from typing import Dict, Tuple, Any, Optional
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from pathlib import Path from pathlib import Path
import ssl, settings import ssl
from cryptography import x509 from cryptography import x509
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.backends import default_backend
@@ -48,7 +48,7 @@ class TLSContext:
p_key = self.cert_dir / '{}'.format(self.cert_root) p_key = self.cert_dir / '{}'.format(self.cert_root)
if not exists_and_valid(p_crt, p_key): if not exists_and_valid(p_crt, p_key):
if not settings.DEBUG: raise ssl.CertificateError() raise ssl.CertificateError()
return p_crt, p_key return p_crt, p_key
+2 -2
View File
@@ -1,7 +1,7 @@
<html> <html>
<body> <body>
<h1>Here be dragons!</h1> <h1>Here be dragons!</h1>
<p>You appear to be lost, go <a href="https://{{ settings.WEBSITE_HOST }}">here</a>.</p> <p>You appear to be lost, go <a href="https://crosstalk.im">here</a>.</p>
<i><small>Powered by Azul <b>{{ settings.VERSION }} ({% if settings.DEBUG %}DEBUG{% else %}PROD{% endif %})</b></small></i> <i><small>Powered by Azul <b>{{ settings.VERSION }}-{% if settings.DEBUG %}DEBUG{% else %}PROD{% endif %}</b></small></i>
</body> </body>
</html> </html>
+19 -313
View File
@@ -1,24 +1,22 @@
from typing import Dict, Optional, List, Tuple, Any, TYPE_CHECKING from typing import Dict, Optional, List, Tuple, Any, TYPE_CHECKING
from datetime import datetime, timedelta from datetime import datetime
from dateutil import parser as iso_parser from dateutil import parser as iso_parser
from pathlib import Path from pathlib import Path
from sqlalchemy import func, or_ from sqlalchemy import func
from sqlalchemy.orm import joinedload from sqlalchemy.orm import joinedload
import json, traceback import json, traceback
from util.hash import gen_salt, hasher, hasher_md5, hasher_md5crypt from util.hash import gen_salt, hasher, hasher_md5, hasher_md5crypt
from util import misc from util import misc
from util.avatar import store_avatar_file, get_img_type
from .conn import Conn from .conn import Conn
from .db import ( from .db import (
User as DBUser, UserContact as DBUserContact, Circle as DBCircle, User as DBUser, UserContact as DBUserContact, Circle as DBCircle,
CircleMembership as DBCircleMembership, UserProfile as DBUserProfile, Activity as DBActivity, CircleMembership as DBCircleMembership, UserProfile as DBUserProfile
ActivityReaction as DBActivityReaction, ActivityComment as DBActivityComment
) )
from .models import ( from .models import (
User, Contact, ContactDetail, ContactLocation, ContactGroupEntry, UserStatus, UserDetail, Circle, User, Contact, ContactDetail, ContactLocation, ContactGroupEntry, UserStatus, UserDetail, Circle,
CircleMembership, CircleRole, CircleState, Group, RoamingInfo, OIM, UserProfile, Activity, ActivityType CircleMembership, CircleRole, CircleState, Group, RoamingInfo, OIM, UserProfile
) )
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -44,6 +42,11 @@ class UserService:
status = hasher.verify(pwd, dbuser.password) status = hasher.verify(pwd, dbuser.password)
if status is True: if status is True:
return dbuser.uuid 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 return None
def login_with_username(self, username: str, pwd: str) -> Optional[str]: def login_with_username(self, username: str, pwd: str) -> Optional[str]:
@@ -54,25 +57,13 @@ class UserService:
status = hasher.verify(pwd, dbuser.password) status = hasher.verify(pwd, dbuser.password)
if status is True: if status is True:
return dbuser.uuid return dbuser.uuid
return None elif status == 'MIGRATEMEPLSTHX':
new_hash = hasher.encode(pwd, salt=gen_salt())
def login_with_uin(self, uin: int, pwd: str) -> Optional[str]: dbuser.password = new_hash
uuid = self.get_uuid_uin(uin) sess.add(dbuser)
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 dbuser.uuid
return None return None
def msn_login_md5(self, email: str, md5_hash: str) -> Optional[str]: def msn_login_md5(self, email: str, md5_hash: str) -> Optional[str]:
with self._conn.session() as sess: with self._conn.session() as sess:
dbuser = sess.query(DBUser).filter(func.lower(DBUser.email) == email.lower()).one_or_none() dbuser = sess.query(DBUser).filter(func.lower(DBUser.email) == email.lower()).one_or_none()
@@ -108,14 +99,6 @@ class UserService:
return hasher_md5.extract_hash(dbuser.get_front_data('aim', 'pw_md5') or '') return hasher_md5.extract_hash(dbuser.get_front_data('aim', 'pw_md5') or '')
def aim_get_md5_password_bucp2(self, screen_name: str) -> Optional[bytes]:
with self._conn.session() as sess:
dbuser = sess.query(DBUser).filter(func.lower(DBUser.username) == screen_name.lower()).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(self, screen_name: str) -> Optional[str]: def aim_get_md5_salt(self, screen_name: str) -> Optional[str]:
with self._conn.session() as sess: with self._conn.session() as sess:
dbuser = sess.query(DBUser).filter(func.lower(DBUser.username) == screen_name.lower()).one_or_none() dbuser = sess.query(DBUser).filter(func.lower(DBUser.username) == screen_name.lower()).one_or_none()
@@ -126,32 +109,6 @@ class UserService:
return hasher.extract_salt(pw_md5) if pw_md5 else None 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]: def msim_get_sha1_password(self, email: str) -> Optional[bytes]:
with self._conn.session() as sess: with self._conn.session() as sess:
dbuser = sess.query(DBUser).filter(DBUser.email == email).one_or_none() dbuser = sess.query(DBUser).filter(DBUser.email == email).one_or_none()
@@ -185,67 +142,11 @@ class UserService:
return None return None
return dbuser.uuid 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]: def get(self, uuid: str) -> Optional[User]:
if uuid not in self._cache_by_uuid: if uuid not in self._cache_by_uuid:
self._cache_by_uuid[uuid] = self._get_uncached(uuid) self._cache_by_uuid[uuid] = self._get_uncached(uuid)
return self._cache_by_uuid[uuid] return self._cache_by_uuid[uuid]
def get_user_email(self, user: User) -> str:
return user.email.lower()
def get_display_email(self, user: User) -> str:
if user.alias_active:
return '{}@crosstalk.im'.format(user.username).lower()
return user.email.lower()
def lookup_uuid_by_email(self, email: str) -> Optional[str]:
uuid = self.get_uuid(email)
if uuid is not None:
return uuid
lower = email.lower()
if lower.endswith('@crosstalk.im'):
username = lower[:-len('@crosstalk.im')]
uuid = self.get_uuid_username(username)
if uuid is not None:
return uuid
else:
local = email.split('@')[0]
uuid = self.get_uuid_username(local)
return uuid
def _get_uncached(self, uuid: str) -> Optional[User]: def _get_uncached(self, uuid: str) -> Optional[User]:
with self._conn.session() as sess: with self._conn.session() as sess:
dbuser = sess.query(DBUser).options(joinedload(DBUser.profile)).filter(DBUser.uuid == uuid).one_or_none() dbuser = sess.query(DBUser).options(joinedload(DBUser.profile)).filter(DBUser.uuid == uuid).one_or_none()
@@ -271,25 +172,11 @@ class UserService:
status = UserStatus(dbuser.friendly_name or dbuser.email) status = UserStatus(dbuser.friendly_name or dbuser.email)
return User( return User(
dbuser.id, dbuser.uuid, dbuser.email, dbuser.username, dbuser.first_name, dbuser.last_name, dbuser.uin, dbuser.id, dbuser.uuid, dbuser.email, dbuser.username, dbuser.first_name, dbuser.last_name, dbuser.uin,
dbuser.verified_to_login, dbuser.account_verified, dbuser.alias_active, status, dbuser.settings, dbuser.date_created, dbuser.date_login, dbuser.suspended, dbuser.verified_to_login, status, dbuser.settings, dbuser.date_created, dbuser.date_login, dbuser.suspended,
dbuser.is_tester, dbuser.is_mvp, dbuser.show_in_dir, dbuser.evil_permanent, dbuser.evil_temporary, dbuser.avatar, dbuser.is_tester, dbuser.is_mvp, dbuser.show_in_dir, dbuser.evil_permanent, dbuser.evil_temporary,
profile=user_profile profile=user_profile
) )
def save_avatar(self, user: User, data: bytes, ext: str) -> str:
md5 = store_avatar_file(user.uuid, data, ext)
with self._conn.session() as sess:
sess.query(DBUser).filter(DBUser.uuid == user.uuid).update({'avatar': md5})
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]: def get_detail(self, uuid: str) -> Optional[UserDetail]:
with self._conn.session() as sess: with self._conn.session() as sess:
dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none() dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none()
@@ -476,49 +363,6 @@ class UserService:
return circle 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]: def get_all_circles(self) -> List[Circle]:
circles = [] circles = []
@@ -659,10 +503,8 @@ class UserService:
if dbusercontacts_to_add: if dbusercontacts_to_add:
sess.add_all(dbusercontacts_to_add) sess.add_all(dbusercontacts_to_add)
def save_single_roaming(self, user: User, to_save: Dict[str, Any]) -> bool: def save_single_roaming(self, user: User, to_save: Dict[str, Any]) -> None:
# Returns whether a "What's New" activity was added
updated = False updated = False
activity_added = False
with self._conn.session() as sess: with self._conn.session() as sess:
dbuser = sess.query(DBUser).filter(DBUser.uuid == user.uuid).one() dbuser = sess.query(DBUser).filter(DBUser.uuid == user.uuid).one()
@@ -671,149 +513,13 @@ class UserService:
dbuser.name_last_modified = datetime.utcnow() dbuser.name_last_modified = datetime.utcnow()
updated = True updated = True
if 'message' in to_save: 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 = to_save['message']
dbuser.message_last_modified = datetime.utcnow() dbuser.message_last_modified = datetime.utcnow()
updated = True updated = True
if updated: if updated:
sess.add(dbuser) 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: def _get_oim_path(recipient_uuid: str) -> Path:
return Path('storage/oim') / recipient_uuid return Path('storage/oim') / recipient_uuid
+3 -4
View File
@@ -6,8 +6,8 @@ pillow
MarkupSafe MarkupSafe
HLL==1.3.1 HLL==1.3.1
funcli funcli
git+https://git.ugnet.gay/CrossTalk/brutus.git git+https://git.hiden.cc/CrossTalk/brutus.git
git+https://git.ugnet.gay/CrossTalk/ins-client.git git+https://git.hiden.cc/CrossTalk/ins-client.git
pytz pytz
cryptography cryptography
arc4 arc4
@@ -19,5 +19,4 @@ argon2
argon2-cffi argon2-cffi
PyRSS2Gen PyRSS2Gen
pymysql pymysql
disposable-email-domains disposable-email-domains
emoji
+4 -4
View File
@@ -10,8 +10,8 @@ http://web.archive.org/web/20100924153734/http://www.ycoderscookbook.com/tutoria
https://github.com/afallenhope/web-ymsg https://github.com/afallenhope/web-ymsg
http://web.archive.org/web/20090623064155/carbonize.co.uk/ymsg16.html http://web.archive.org/web/20090623064155/carbonize.co.uk/ymsg16.html
http://web.archive.org/web/20040803082402/http://www.carbonize.co.uk:80/Tutorials/Vb/ycht.php http://web.archive.org/web/20040803082402/http://www.carbonize.co.uk:80/Tutorials/Vb/ycht.php
https://ninawiki.preloading.dev/wiki/Protocols/YMSG https://wiki.nina.chat/wiki/Protocols/YMSG
https://ninawiki.preloading.dev/wiki/Protocols/YMSG/Packet_Structure https://wiki.nina.chat/wiki/Protocols/YMSG/Packet_Structure
YMSG8: YMSG8:
http://web.archive.org/web/20010801212305/http://www.venkydude.com:80/articles/yahoo.htm 1 http://web.archive.org/web/20010801212305/http://www.venkydude.com:80/articles/yahoo.htm 1
YMSG9: YMSG9:
@@ -23,7 +23,7 @@ http://web.archive.org/web/20091229030156/http://www.venkydude.com/articles/yaho
MSNP: MSNP:
https://github.com/Richie-Zhang/Instant_Messenger/blob/master/documents/Internet%20Draft%20MSNP%201.0 https://github.com/Richie-Zhang/Instant_Messenger/blob/master/documents/Internet%20Draft%20MSNP%201.0
https://ninawiki.preloading.dev/wiki/Protocols/MSNP/Documents https://wiki.nina.chat/wiki/Protocols/MSNP/Documents
http://www.hypothetic.org/docs/msn/ http://www.hypothetic.org/docs/msn/
https://protogined.wordpress.com/msnp2/ https://protogined.wordpress.com/msnp2/
https://protogined.wordpress.com/msnp3/ https://protogined.wordpress.com/msnp3/
@@ -71,7 +71,7 @@ http://web.archive.org/web/20061116183306/http://www.therisenrealm.com/scripts/b
http://plaza.ufl.edu/dmitrid/perl/ http://plaza.ufl.edu/dmitrid/perl/
https://github.com/wiseman/claim https://github.com/wiseman/claim
https://metacpan.org/pod/Net::AOLIM https://metacpan.org/pod/Net::AOLIM
https://ninawiki.preloading.dev/wiki/Protocols/TOC/1.0 https://wiki.nina.chat/wiki/Protocols/TOC/1.0
OSCAR: OSCAR:
https://web.archive.org/web/20060819080319/http://www.oilcan.org/oscar/ https://web.archive.org/web/20060819080319/http://www.oilcan.org/oscar/
-127
View File
@@ -1,127 +0,0 @@
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)
-625
View File
@@ -1,625 +0,0 @@
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] <Info> ADMIN_KEY is not set, so nobody can sign into the admin panel yet (see settings.py)')
print(f'[Admin] <Info> 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.')
-71
View File
@@ -1,71 +0,0 @@
{% macro hub(title, sub=None) -%}
<header class="ct-hub adm-hub">
<h1 class="ct-hub-title">{{ title }}</h1>
{% if sub %}<p class="ct-hub-sub">{{ sub }}</p>{% endif %}
{% if caller %}{{ caller() }}{% endif %}
</header>
{%- endmacro %}
{% macro flash_list(flashes) -%}
{% for kind, text in flashes %}
<div class="alert alert-{{ kind }}" role="{{ 'alert' if kind == 'danger' else 'status' }}">
<i class="bi bi-{{ 'exclamation-triangle-fill' if kind == 'danger' else ('info-circle-fill' if kind == 'info' else 'check-circle-fill') }}" aria-hidden="true"></i>
<div>{{ text }}</div>
</div>
{% endfor %}
{%- endmacro %}
{% macro csrf_field(csrf) -%}
<input type="hidden" name="csrf" value="{{ csrf }}">
{%- endmacro %}
{% macro copy_field(id, value, label) -%}
<div class="adm-copy">
<label class="visually-hidden" for="{{ id }}">{{ label }}</label>
<input class="form-control" id="{{ id }}" value="{{ value }}" readonly spellcheck="false">
<button type="button" class="btn btn-primary" data-ct-copy="{{ value }}" aria-label="Copy the {{ label | lower }}">Copy</button>
</div>
{%- endmacro %}
{% macro flags(user) -%}
{%- if user.is_admin %}<span class="ct-chip ct-chip-accent">admin</span>{% endif -%}
{%- if user.suspended %}<span class="ct-chip ct-chip-danger">suspended</span>{% endif -%}
{#{%- if not user.verified_to_login %}<span class="ct-chip ct-chip-warning">can't sign in</span>{% endif -%}#}
{%- if not user.account_verified %}<span class="ct-chip">unverified e-mail</span>{% endif -%}
{%- if user.show_in_dir %}<span class="ct-chip">listed in directory</span>{% endif -%}
{%- if user.is_tester %}<span class="ct-chip">tester</span>{% endif -%}
{%- if user.is_mvp %}<span class="ct-chip">MVP</span>{% endif -%}
{%- endmacro %}
{% macro pager(page, pages, base) -%}
{% if pages > 1 %}
<nav class="mt-4" aria-label="Pages">
<ul class="pagination flex-wrap">
<li class="page-item {% if page <= 1 %}disabled{% endif %}"><a class="page-link" href="{{ base }}page={{ page - 1 }}" aria-label="Previous page"{% if page <= 1 %} aria-disabled="true" tabindex="-1"{% endif %} data-ct-swap-link>«</a></li>
{% for p in range([1, page - 2] | max, [pages, page + 2] | min + 1) %}
<li class="page-item {% if p == page %}active{% endif %}"><a class="page-link" href="{{ base }}page={{ p }}"{% if p == page %} aria-current="page"{% endif %} data-ct-swap-link>{{ p }}</a></li>
{% endfor %}
<li class="page-item {% if page >= pages %}disabled{% endif %}"><a class="page-link" href="{{ base }}page={{ page + 1 }}" aria-label="Next page"{% if page >= pages %} aria-disabled="true" tabindex="-1"{% endif %} data-ct-swap-link>»</a></li>
</ul>
</nav>
{% endif %}
{%- endmacro %}
{% macro tile(href, icon, big, name, note=None, tone=1, wide=False) -%}
<a class="ct-tile adm-tile {{ 'adm-tile-hero' if tone == 'hero' else 'ct-tile-' ~ tone }}{% if wide %} ct-tile-wide{% endif %}" href="{{ href }}" data-ct-swap-link>
<i class="bi {{ icon }} ct-tile-icon" aria-hidden="true"></i>
<span class="adm-tile-big">{{ big }}</span>
<span class="adm-tile-name">{{ name }}</span>
{% if note %}<span class="adm-tile-note">{{ note }}</span>{% endif %}
</a>
{%- endmacro %}
{% macro alert_row(alert) -%}
<li class="adm-alert">
<span class="adm-alert-icon" aria-hidden="true">{% if alert.icon %}<img src="{{ alert.icon }}" alt="" width="32" height="32" loading="lazy">{% else %}<i class="bi {{ {'stocks': 'bi-graph-up-arrow', 'calendar': 'bi-calendar-event-fill'}.get(alert.kind, 'bi-bell-fill') }}"></i>{% endif %}</span>
<div class="adm-alert-body">
<p class="adm-alert-text">{{ alert.text }}</p>
<p class="adm-alert-meta">{{ alert.date | ago }} by {{ alert.by }} · {{ alert.reach }}{% if alert.url %} · <a href="{{ alert.url }}" rel="noreferrer" target="_blank">link<span class="visually-hidden"> (opens in a new tab)</span></a>{% endif %}</p>
</div>
</li>
{%- endmacro %}
-81
View File
@@ -1,81 +0,0 @@
{% from '_ui.html' import flash_list -%}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<meta name="robots" content="noindex, nofollow">
<link rel="icon" href="https://{{ settings.STATIC_HOST }}/svc/ct/logo/favicon.ico"/>
<link rel="stylesheet" href="https://{{ settings.STATIC_HOST }}/sites/ct/style/style.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.css">
<script src="https://{{ settings.STATIC_HOST }}/sites/ct/style/style.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://{{ settings.STATIC_HOST }}/sites/ct/bootstrap/bootstrap.bundle.min.js"></script>
<title>{% if title %}{{ title }} | {% endif %}azul admin</title>
</head>
<body class="light-mode adm-body">
<a class="visually-hidden-focusable ct-skip" href="#main">Skip to main content</a>
<header>
<nav class="navbar navbar-dark bg-primary fixed-top adm-bar" aria-label="Admin">
<div class="container-fluid">
<a class="navbar-brand" href="/" style="color:white;">
<img src="https://{{ settings.STATIC_HOST }}/svc/ct/logo/shadow.svg" height="28" alt="">
CrossTalk <span class="adm-brand-tag">admin</span>
</a>
<form method="get" action="/users" class="adm-find" role="search" aria-label="Find an account" data-ct-swap-form>
<i class="bi bi-search" aria-hidden="true"></i>
<label for="admFind" class="visually-hidden">Find an account by username, e-mail or UUID</label>
<input type="search" class="form-control form-control-sm" id="admFind" name="q" placeholder="find an account" autocomplete="off" spellcheck="false">
</form>
<div class="adm-bar-end">
<button type="button" class="ct-icon-btn adm-bar-btn" id="mode-toggle-anchor" role="switch" aria-checked="false" aria-label="Dark theme"><i id="mode-toggle-icon" class="bi" aria-hidden="true"></i><span id="mode-toggle-label" class="visually-hidden">Dark theme</span></button>
<div class="dropdown">
<button type="button" class="adm-who dropdown-toggle" id="admWho" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Account menu for {{ admin.username }}">
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ admin.uuid }}/im" alt="" width="28" height="28">
<span class="adm-who-name">{{ admin.username }}</span>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="admWho">
<li class="ct-menu-head">
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ admin.uuid }}/im" alt="" width="36" height="36">
<span><strong>{{ admin.username }}</strong>administrator</span>
</li>
<li><a class="dropdown-item" href="/users/{{ admin.uuid }}" data-ct-swap-link><i class="bi bi-person-fill" aria-hidden="true"></i>Your account</a></li>
<li><hr class="dropdown-divider"></li>
<li>
<form method="post" action="/logout" class="m-0">
<input type="hidden" name="csrf" value="{{ csrf }}">
<button type="submit" class="dropdown-item text-danger"><i class="bi bi-box-arrow-right" aria-hidden="true"></i>Sign out</button>
</form>
</li>
</ul>
</div>
</div>
</div>
</nav>
</header>
<div class="adm-shell">
<nav class="adm-nav" aria-label="Sections" data-ct-pivot-nav>
<ul>
{% for href, label, icon in sections %}
{% set current = (path == href) or (href != '/' and path.startswith(href)) %}
<li>
<a href="{{ href }}"{% if current %} aria-current="page" class="is-current"{% endif %}>
<i class="bi {{ icon }}" aria-hidden="true"></i><span class="adm-nav-label">{{ label }}</span>
{% if href == '/sessions' %}<span class="adm-nav-count" id="admNavSessions" data-ct-swap-sync>{{ nav.sessions }}<span class="visually-hidden"> open</span></span>{% endif %}
{% if href == '/broadcast' %}<span class="adm-nav-mark" id="admNavMaintenance" data-ct-swap-sync>{% if nav.maintenance %}<span class="ct-dot" aria-hidden="true"></span><span class="visually-hidden">, maintenance announced</span>{% endif %}</span>{% endif %}
</a>
</li>
{% endfor %}
</ul>
<p class="adm-nav-foot">azul {{ settings.VERSION }}</p>
</nav>
<main class="adm-main" id="main" tabindex="-1" data-ct-swap>
{{ flash_list(flashes) }}
{% block content %}{% endblock %}
</main>
</div>
</body>
</html>
-190
View File
@@ -1,190 +0,0 @@
{% 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.') }}
<div class="ct-pivot adm-broadcast-pivot" role="tablist" aria-label="Broadcast" data-ct-tabs data-ct-tabs-hash>
<button type="button" role="tab" id="bcTabAlert" aria-controls="bcAlert" aria-selected="true" data-hash="alert">alert</button>
<button type="button" role="tab" id="bcTabAnnounce" aria-controls="bcAnnounce" aria-selected="false" tabindex="-1" data-hash="announcement">announcement</button>
<button type="button" role="tab" id="bcTabMaintenance" aria-controls="bcMaintenance" aria-selected="false" tabindex="-1" data-hash="maintenance">maintenance{% if maintenance.active or maintenance.pending %} <span class="ct-dot" style="--ct-tone: var(--ct-info)" aria-hidden="true"></span><span class="visually-hidden">, announced</span>{% endif %}</button>
<button type="button" role="tab" id="bcTabHistory" aria-controls="bcHistory" aria-selected="false" tabindex="-1" data-hash="history">history <span class="ct-count">{{ alerts | length }}</span></button>
</div>
<section class="ct-pane" role="tabpanel" id="bcAlert" aria-labelledby="bcTabAlert">
<form method="post" class="adm-composer" data-ct-alert-composer data-max-body="{{ max_body }}" data-site-url="{{ site_url }}">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="alert">
<input type="hidden" name="networks_shown" value="1">
<div class="adm-composer-form ct-card">
<div class="ct-field">
<div class="adm-label-row">
<label for="alertMessage" class="form-label">Message</label>
<div class="adm-tools" role="toolbar" aria-label="Formatting" aria-controls="alertMessage">
<button type="button" class="ct-icon-btn ct-icon-btn-sm" data-alert-wrap="**" aria-label="Bold" title="Bold (**text**)"><i class="bi bi-type-bold" aria-hidden="true"></i></button>
<button type="button" class="ct-icon-btn ct-icon-btn-sm" data-alert-wrap="*" aria-label="Italic" title="Italic (*text*)"><i class="bi bi-type-italic" aria-hidden="true"></i></button>
<span class="adm-tools-gap" aria-hidden="true"></span>
{% for align, icon in [('left', 'bi-text-left'), ('center', 'bi-text-center'), ('right', 'bi-text-right')] %}
<input type="radio" class="btn-check" name="align" id="alertAlign-{{ align }}" value="{{ align }}" autocomplete="off"{% if loop.first %} checked{% endif %}>
<label class="ct-icon-btn ct-icon-btn-sm adm-tool-toggle" for="alertAlign-{{ align }}" title="Align {{ align }}"><i class="bi {{ icon }}" aria-hidden="true"></i><span class="visually-hidden">Align {{ align }}</span></label>
{% endfor %}
</div>
</div>
<textarea class="form-control" id="alertMessage" name="message" rows="5" maxlength="1000" required aria-describedby="alertMarkup"></textarea>
<small class="form-text" id="alertMarkup">**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.</small>
</div>
<div class="row g-3 mt-1">
<div class="col-sm-6 ct-field mb-0">
<label for="alertUrl" class="form-label">Link</label>
<input type="url" class="form-control" id="alertUrl" name="url" inputmode="url" placeholder="{{ site_url }}" aria-describedby="alertUrlHelp">
<small class="form-text" id="alertUrlHelp">Where clicking the alert goes. Empty goes to {{ site_url }}.</small>
</div>
<fieldset class="col-sm-6 ct-field mb-0">
<legend class="form-label">Icon</legend>
<div class="adm-choices">
{% 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')] %}
<input type="radio" class="btn-check" name="kind" id="alertKind-{{ kind }}" value="{{ kind }}" autocomplete="off"{% if loop.first %} checked{% endif %}>
<label class="adm-choice" for="alertKind-{{ kind }}"><i class="bi {{ icon }}" aria-hidden="true"></i>{{ label }}</label>
{% endfor %}
</div>
</fieldset>
</div>
<div class="ct-field mt-3" data-alert-when="kind=custom">
<label for="alertIcon" class="form-label">Icon address</label>
<input type="url" class="form-control" id="alertIcon" name="icon" inputmode="url" placeholder="https://example.com/alert_32x32.png" aria-describedby="alertIconHelp">
<small class="form-text" id="alertIconHelp">A 32×32 PNG. Messenger 6 and later swap <code>_32x32</code> in its name for <code>_48x32</code> and use that one if it's there.</small>
</div>
<fieldset class="ct-field mt-3">
<legend class="form-label">Who</legend>
<div class="adm-choices">
<input type="radio" class="btn-check" name="who" id="alertWho-everyone" value="everyone" autocomplete="off" checked>
<label class="adm-choice" for="alertWho-everyone"><i class="bi bi-globe2" aria-hidden="true"></i>everyone signed in</label>
<input type="radio" class="btn-check" name="who" id="alertWho-people" value="people" autocomplete="off">
<label class="adm-choice" for="alertWho-people"><i class="bi bi-person-lines-fill" aria-hidden="true"></i>certain people</label>
</div>
</fieldset>
<div data-alert-when="who=people">
<div class="ct-field">
<label for="alertTargets" class="form-label">Their usernames or e-mail addresses</label>
<textarea class="form-control" id="alertTargets" name="targets" rows="2" spellcheck="false" aria-describedby="alertTargetsHelp"></textarea>
<small class="form-text" id="alertTargetsHelp">Separated with commas or on lines of their own.</small>
</div>
<div class="form-check form-switch mb-2">
<input class="form-check-input" type="checkbox" role="switch" id="alertEmail" name="email"{% if not email_available %} disabled aria-describedby="alertEmailHelp"{% endif %}>
<label class="form-check-label" for="alertEmail">Also e-mail it to them</label>
</div>
{% if not email_available %}<p class="form-text mt-0" id="alertEmailHelp">The website isn't linked right now, so it can't send e-mail.</p>{% endif %}
<div class="ct-field" data-alert-when="email">
<label for="alertEmailText" class="form-label">The e-mail's text <span class="ct-muted">(optional)</span></label>
<textarea class="form-control" id="alertEmailText" name="email_text" rows="3" aria-describedby="alertEmailTextHelp"></textarea>
<small class="form-text" id="alertEmailTextHelp">Empty sends the alert's words and its link. Messenger also gets it as the alert's <code>EMAILTEXT</code>.</small>
</div>
</div>
<fieldset class="ct-field mt-3">
<legend class="form-label">Clients</legend>
<div class="adm-choices">
{% for network in networks %}
<input type="checkbox" class="btn-check" name="network_{{ network }}" id="alertNetwork-{{ network }}" autocomplete="off" checked>
<label class="adm-choice adm-choice-name" for="alertNetwork-{{ network }}"><i class="bi bi-check-lg adm-choice-tick" aria-hidden="true"></i>{{ network_names.get(network, network) }}</label>
{% endfor %}
</div>
</fieldset>
<details class="ct-details adm-more">
<summary>more .NET Alerts options</summary>
<div class="ct-details-body">
<div class="row g-3">
<div class="col-sm-6 ct-field mb-0">
<label for="alertSubscr" class="form-label">"Change alert" link</label>
<input type="url" class="form-control" id="alertSubscr" name="subscr_url" inputmode="url" aria-describedby="alertSubscrHelp">
<small class="form-text" id="alertSubscrHelp">Messenger's option to change the alert (<code>SUBSCR</code>). Empty uses the link.</small>
</div>
<div class="col-sm-6 ct-field mb-0">
<label for="alertLang" class="form-label">Language</label>
<select class="form-select" id="alertLang" name="lang">
{% for lcid, name in languages %}<option value="{{ lcid }}"{% if lcid == 1033 %} selected{% endif %}>{{ name }} ({{ lcid }})</option>{% endfor %}
</select>
</div>
<div class="col-sm-4 ct-field mb-0">
<label for="alertPriority" class="form-label">Priority</label>
<input type="number" class="form-control" id="alertPriority" name="priority" min="0" max="4294967295" value="1">
</div>
<div class="col-sm-4 ct-field mb-0">
<label for="alertMessageId" class="form-label">Message ID</label>
<input type="number" class="form-control" id="alertMessageId" name="message_id" min="0" max="4294967295" value="0">
</div>
<div class="col-sm-4 ct-field mb-0">
<label for="alertVia" class="form-label">Sent via</label>
<select class="form-select" id="alertVia" name="via">
<option value="">nothing said</option>
{% for agent in agents %}<option value="{{ agent }}">{{ agent }}</option>{% endfor %}
</select>
</div>
</div>
<div class="ct-field mt-3 mb-0">
<label for="alertPlain" class="form-label">Plain-text version <span class="ct-muted">(optional)</span></label>
<textarea class="form-control" id="alertPlain" name="plain" rows="2" aria-describedby="alertPlainHelp"></textarea>
<small class="form-text" id="alertPlainHelp">What Messenger 5 and older, Yahoo!, AIM and IRC show when the message has formatting. Empty takes the message's words.</small>
</div>
</div>
</details>
<div class="ct-form-actions"><button type="submit" class="btn btn-primary">Send alert</button></div>
</div>
</form>
</section>
<section class="ct-pane ct-card" role="tabpanel" id="bcAnnounce" aria-labelledby="bcTabAnnounce" data-ct-later>
<p class="ct-muted">A news item on CrossTalk Beacon and in Windows Live Messenger's What's New.</p>
<form method="post" class="adm-narrow-form">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="announce">
<div class="ct-field">
<label for="ancTitle" class="form-label">Title</label>
<input type="text" class="form-control" id="ancTitle" name="title" maxlength="100" required>
</div>
<div class="ct-field">
<label for="ancText" class="form-label">Text</label>
<textarea class="form-control" id="ancText" name="text" rows="3" maxlength="255" required></textarea>
</div>
<div class="ct-field">
<label for="ancUrl" class="form-label">Link <span class="ct-muted">(optional)</span></label>
<input type="url" class="form-control" id="ancUrl" name="url" inputmode="url">
</div>
<button type="submit" class="btn btn-primary">Post announcement</button>
</form>
</section>
<section class="ct-pane ct-card" role="tabpanel" id="bcMaintenance" aria-labelledby="bcTabMaintenance" data-ct-later>
{% if maintenance.active %}
<p class="mb-0">The server is in maintenance mode right now.</p>
{% elif maintenance.pending %}
<p class="mb-0">Maintenance is already announced, in about {{ maintenance.minutes }} minute{{ 's' if maintenance.minutes != 1 else '' }}.</p>
{% else %}
<p>Tells everyone signed in that the server is going down, with a countdown. The website's status page shows it too.</p>
<form method="post" class="d-flex flex-wrap align-items-end gap-2">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="maintenance">
<div>
<label for="mntMinutes" class="form-label">In how many minutes</label>
<input type="number" class="form-control adm-narrow" id="mntMinutes" name="minutes" min="0" max="1440" value="10" required>
</div>
<button type="submit" class="btn btn-outline-danger">Announce maintenance</button>
</form>
{% endif %}
</section>
<section class="ct-pane ct-card" role="tabpanel" id="bcHistory" aria-labelledby="bcTabHistory" data-ct-later>
{% if alerts %}
<p class="ct-muted">The last {{ alerts | length }} alert{{ 's' if alerts | length != 1 else '' }} since azul started, newest first.</p>
<ul class="adm-alerts">
{% for alert in alerts %}{{ alert_row(alert) }}{% endfor %}
</ul>
{% else %}
<p class="ct-muted">No alerts since azul started.</p>
{% endif %}
</section>
{% endblock %}
-77
View File
@@ -1,77 +0,0 @@
{% extends 'base.html' %}
{% from '_ui.html' import csrf_field %}
{% block content %}
<p class="ct-back"><a href="/circles" data-ct-swap-link>Circles</a></p>
<section class="ct-card adm-identity" aria-labelledby="circleName">
<span class="adm-glyph adm-glyph-lg" aria-hidden="true">{{ (circle.name or '?')[:1] }}</span>
<div class="min-w-0 flex-grow-1">
<h1 class="adm-identity-name" id="circleName">{{ circle.name }}</h1>
<p class="ct-muted mb-0">{{ members | length }} member{{ 's' if members | length != 1 else '' }} · {{ members | selectattr('in_chat') | list | length }} in the conversation now · <code>{{ circle.chat_id }}</code></p>
</div>
</section>
<section class="ct-card" aria-labelledby="circleMembers">
<h2 class="ct-card-title" id="circleMembers">members</h2>
<ul class="adm-roster">
{% for m in members %}
{% set invited = m.role == 4 and m.state == 1 %}
<li class="adm-roster-row">
<a class="adm-roster-who" href="/users/{{ m.uuid }}" data-ct-swap-link>
<span class="adm-avatar">
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ m.uuid }}/im" alt="" width="36" height="36" loading="lazy">
{% if m.online %}<span class="ct-presence" aria-hidden="true"></span>{% endif %}
</span>
<span class="adm-person-body">
<span class="adm-person-name">{{ m.username }}</span>
<span class="adm-person-meta">{% if invited %}invited{% if m.inviter_email %} by {{ m.inviter_email }}{% endif %}{% elif m.in_chat %}in the conversation{% elif m.online %}signed in{% else %}{{ m.email }}{% endif %}</span>
</span>
</a>
<div class="adm-roster-actions">
{% if invited %}
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="revoke">
<input type="hidden" name="uuid" value="{{ m.uuid }}">
<button type="submit" class="btn btn-sm btn-outline-secondary">Withdraw invite<span class="visually-hidden"> for {{ m.username }}</span></button>
</form>
{% else %}
<form method="post" class="d-flex align-items-center gap-2 m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="role">
<input type="hidden" name="uuid" value="{{ m.uuid }}">
<label class="visually-hidden" for="role-{{ loop.index }}">Role for {{ m.username }}</label>
<select class="form-select form-select-sm" id="role-{{ loop.index }}" name="role">
{% for value, name in [(1, 'owner'), (2, 'administrator'), (3, 'member')] %}
<option value="{{ value }}"{% if m.role == value %} selected{% endif %}>{{ name }}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-sm btn-outline-secondary">Set<span class="visually-hidden"> the role for {{ m.username }}</span></button>
</form>
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="remove">
<input type="hidden" name="uuid" value="{{ m.uuid }}">
<button type="submit" class="btn btn-sm btn-outline-danger">Remove<span class="visually-hidden"> {{ m.username }}</span></button>
</form>
{% endif %}
</div>
</li>
{% endfor %}
</ul>
</section>
<section class="ct-card adm-danger" aria-labelledby="circleDelete">
<h2 class="ct-card-title" id="circleDelete">delete this circle</h2>
<p>Ends the conversation for everyone and takes the circle off every member's contact list. It can't be undone.</p>
<form method="post" class="adm-confirm">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="delete">
<label for="circleConfirm" class="form-label">Type <strong>{{ circle.name }}</strong> to confirm</label>
<div class="d-flex flex-wrap gap-2">
<input type="text" class="form-control" id="circleConfirm" name="confirm" autocomplete="off" spellcheck="false" required>
<button type="submit" class="btn btn-danger">Delete circle</button>
</div>
</form>
</section>
{% endblock %}
-24
View File
@@ -1,24 +0,0 @@
{% extends 'base.html' %}
{% from '_ui.html' import hub %}
{% block content %}
{{ hub('circles', '{:,}'.format(circles | length) ~ ' group chats on the server.') }}
{% if circles %}
<ul class="adm-people ct-card">
{% for c in circles %}
<li>
<a class="adm-person" href="/circles/{{ c.chat_id }}" data-ct-swap-link>
<span class="adm-glyph" aria-hidden="true">{{ (c.name or '?')[:1] }}</span>
<span class="adm-person-body">
<span class="adm-person-name">{{ c.name }}</span>
<span class="adm-person-meta">started by {{ c.owner_friendly or c.owner_uuid }}</span>
</span>
<span class="adm-person-when ct-muted">{{ c.members_count }} member{{ 's' if c.members_count != 1 else '' }}<br><code>{{ c.chat_id }}</code></span>
</a>
</li>
{% endfor %}
</ul>
{% else %}
<p class="ct-muted">No circles yet.</p>
{% endif %}
{% endblock %}
-133
View File
@@ -1,133 +0,0 @@
{% 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 %}
<p class="ct-muted">InterService is turned off on this server (<code>ENABLE_INS</code>).</p>
{% else %}
{% if reveal and reveal.kind == 'code' %}
<section class="ct-card adm-reveal" aria-labelledby="newCode">
<h2 class="ct-card-title" id="newCode">enrollment code for {{ reveal['for'] }}</h2>
<p>Put it in the service's settings (the website's is <code>INS_ENROLLMENT_CODE</code>) before {{ reveal.expires }}. It works once, and this is the only time it's shown.</p>
{{ copy_field('enrollCodeValue', reveal.value, 'Enrollment code') }}
</section>
{% endif %}
<section aria-labelledby="insClients">
<h2 class="ct-section" id="insClients">enrolled services</h2>
{% if clients %}
<ul class="adm-keys">
{% for c in clients %}
{% set link = linked.get(c.id) %}
<li class="ct-card adm-key{% if c.revoked %} is-revoked{% endif %}">
<div class="adm-key-head">
<span class="ct-dot adm-key-state" aria-hidden="true" style="--ct-tone: {{ 'var(--ct-danger)' if c.revoked else ('var(--ct-online)' if link else '#8a8494') }}"></span>
<div class="min-w-0 flex-grow-1">
<h3 class="adm-key-name">{{ c.label or c.identifier }}</h3>
<p class="ct-muted mb-0">{{ c.identifier }} · {% if c.revoked %}revoked {{ c.revoked_at | ago }}{% elif link %}linked now{% else %}last seen {{ c.last_seen | ago }}{% endif %}</p>
</div>
{% if not c.revoked %}
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="revoke">
<input type="hidden" name="client" value="{{ c.id }}">
<button type="submit" class="btn btn-sm btn-outline-danger">Revoke<span class="visually-hidden"> {{ c.label }}</span></button>
</form>
{% else %}
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="delete">
<input type="hidden" name="client" value="{{ c.id }}">
<button type="submit" class="btn btn-sm btn-outline-secondary">Delete<span class="visually-hidden"> {{ c.label }}</span></button>
</form>
{% endif %}
</div>
<dl class="adm-key-facts">
<div><dt>key</dt><dd><code>{{ c.fingerprint }}</code></dd></div>
<div><dt>enrolled</dt><dd>{{ c.created | when }}</dd></div>
<div><dt>last address</dt><dd>{{ c.last_address or '-' }}</dd></div>
</dl>
{% if not c.revoked %}
<form method="post" class="adm-key-addresses">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="addresses">
<input type="hidden" name="client" value="{{ c.id }}">
<label for="addr-{{ c.id }}" class="form-label">Works from</label>
<div class="d-flex flex-wrap gap-2">
<input type="text" class="form-control" id="addr-{{ c.id }}" name="addresses" value="{{ c.addresses | join(', ') }}" spellcheck="false" aria-describedby="addrHelp-{{ c.id }}">
<button type="submit" class="btn btn-outline-secondary">Save</button>
</div>
<small class="form-text" id="addrHelp-{{ c.id }}">Addresses or networks (CIDR), separated with commas. Anything else is turned away, even with the right keys.</small>
</form>
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<p class="ct-muted">Nothing has enrolled yet. Make a code below for the website first.</p>
{% endif %}
</section>
<div class="adm-columns">
<section class="ct-card" id="enroll" aria-labelledby="insEnroll">
<h2 class="ct-card-title" id="insEnroll">enroll a service</h2>
<p class="ct-muted">A one-time code. The service makes its own keys the first time it connects with it, and they never leave that machine.</p>
<form method="post">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="code">
<div class="row g-3">
<div class="col-sm-6 ct-field mb-0">
<label for="codeIdentifier" class="form-label">Identifier</label>
<select class="form-select" id="codeIdentifier" name="identifier">
{% for identifier in identifiers %}<option value="{{ identifier }}">{{ identifier }}</option>{% endfor %}
</select>
</div>
<div class="col-sm-6 ct-field mb-0">
<label for="codeLabel" class="form-label">Name it</label>
<input type="text" class="form-control" id="codeLabel" name="label" maxlength="100" placeholder="CrossTalk website">
</div>
<div class="col-sm-6 ct-field mb-0">
<label for="codeAddress" class="form-label">Only from <span class="ct-muted">(optional)</span></label>
<input type="text" class="form-control" id="codeAddress" name="address" placeholder="Any address" spellcheck="false">
</div>
<div class="col-sm-6 ct-field mb-0">
<label for="codeHours" class="form-label">Valid for (hours)</label>
<input type="number" class="form-control" id="codeHours" name="hours" min="1" max="720" value="24" required>
</div>
</div>
<button type="submit" class="btn btn-primary mt-3">Make a code</button>
</form>
</section>
<section class="ct-card" aria-labelledby="insCodes">
<h2 class="ct-card-title" id="insCodes">codes</h2>
{% set shown = codes[:12] %}
{% if shown %}
<ul class="ct-list">
{% for code in shown %}
<li class="ct-list-item">
<span class="ct-list-body">
<span class="ct-list-title">{{ code.label or code.identifier }}</span>
<span class="ct-list-meta">{{ 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 %}</span>
</span>
{% if code.state == 'waiting' %}
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="cancel-code">
<input type="hidden" name="code" value="{{ code.id }}">
<button type="submit" class="btn btn-sm btn-outline-secondary">Cancel</button>
</form>
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<p class="ct-muted">None made yet.</p>
{% endif %}
<p class="ct-muted small mt-3 mb-0">Server host key <code>{{ fingerprint }}</code></p>
</section>
</div>
{% endif %}
{% endblock %}
-68
View File
@@ -1,68 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<meta name="robots" content="noindex, nofollow">
<link rel="icon" href="https://{{ settings.STATIC_HOST }}/svc/ct/logo/favicon.ico"/>
<link rel="stylesheet" href="https://{{ settings.STATIC_HOST }}/sites/ct/style/style.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.css">
<script src="https://{{ settings.STATIC_HOST }}/sites/ct/style/style.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<title>Sign in | azul admin</title>
</head>
<body class="light-mode adm-body adm-login-body">
<header>
<nav class="navbar navbar-dark bg-primary fixed-top adm-bar" aria-label="Admin">
<div class="container-fluid">
<a class="navbar-brand" href="/login" style="color:white;">
<img src="https://{{ settings.STATIC_HOST }}/svc/ct/logo/shadow.svg" height="28" alt="">
CrossTalk <span class="adm-brand-tag">admin</span>
</a>
<div class="adm-bar-end">
<button type="button" class="ct-icon-btn adm-bar-btn" id="mode-toggle-anchor" role="switch" aria-checked="false" aria-label="Dark theme"><i id="mode-toggle-icon" class="bi" aria-hidden="true"></i><span id="mode-toggle-label" class="visually-hidden">Dark theme</span></button>
</div>
</div>
</nav>
</header>
<main class="container my-4" id="main" tabindex="-1">
<section class="au-card ct-card" aria-labelledby="adminSignIn">
<header class="au-head">
<h1 class="au-title" id="adminSignIn">sign in</h1>
<p class="au-sub">sign in to manage azul {{ settings.VERSION }}</p>
</header>
{% if not configured %}
<div class="alert alert-warning" role="status"><i class="bi bi-exclamation-triangle-fill" aria-hidden="true"></i><div>No admin key is set up yet. Put the SHA-256 hash of one in <code>ADMIN_KEY</code> and restart azul.</div></div>
{% endif %}
{% if error %}
<div class="alert alert-danger" role="alert"><i class="bi bi-exclamation-triangle-fill" aria-hidden="true"></i><div>{{ error }}</div></div>
{% elif next and next != '/' %}
<div class="alert alert-info" role="status"><i class="bi bi-lock-fill" aria-hidden="true"></i><div>Sign in to carry on where you were.</div></div>
{% endif %}
<form method="post" action="/login?next={{ next | urlencode }}" aria-labelledby="adminSignIn">
<div class="ct-field">
<label for="login" class="form-label">E-mail or username</label>
<input type="text" class="form-control" id="login" name="login" value="{{ login }}" placeholder="E-mail or username" autocomplete="username" autocapitalize="none" spellcheck="false" required autofocus>
</div>
<div class="ct-field">
<label for="password" class="form-label">Password</label>
<div class="ct-password">
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="current-password" required>
<button type="button" class="ct-icon-btn" data-ct-reveal="password" aria-pressed="false" aria-label="Show password"><i class="bi bi-eye-fill" aria-hidden="true"></i></button>
</div>
</div>
<div class="ct-field">
<label for="key" class="form-label">Admin key</label>
<div class="ct-password">
<input type="password" class="form-control" id="key" name="key" placeholder="The server's admin key" autocomplete="off" spellcheck="false" required aria-describedby="keyHelp">
<button type="button" class="ct-icon-btn" data-ct-reveal="key" aria-pressed="false" aria-label="Show admin key"><i class="bi bi-eye-fill" aria-hidden="true"></i></button>
</div>
</div>
<button type="submit" class="btn btn-primary w-100 au-submit">Sign in</button>
</form>
<p class="au-alt">not an administrator? this panel is only for the people who run this server, so shoo, go away.</p>
</section>
</main>
</body>
</html>
-139
View File
@@ -1,139 +0,0 @@
{% 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 %}
<div class="alert alert-info" role="status"><i class="bi bi-cone-striped" aria-hidden="true"></i><div>{% 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 %}</div></div>
{% endif %}
<section aria-labelledby="admNow">
<h2 class="visually-hidden" id="admNow">Right now</h2>
<div class="ct-tiles adm-tiles">
{{ 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 %}
</div>
</section>
<div class="adm-columns">
<section class="ct-card" aria-labelledby="admDay">
<h2 class="ct-card-title" id="admDay">the last 24 hours</h2>
{% if hourly %}
{% set busiest = hourly | map(attribute='value') | max %}
<div class="ct-chart-wrap">
<div class="ct-chart" style="--n: {{ hourly | length }}" role="img" aria-label="People active per hour over the last 24 hours. The busiest hour had {{ busiest }}.">
{% for h in hourly %}
<div class="ct-chart-col{% if h.is_now %} is-now{% endif %}" data-tip="{{ h.label }}: {{ h.value }} active"><div class="ct-chart-bar" style="--h: {{ h.pct }}%; --i: {{ loop.index0 }}"></div></div>
{% endfor %}
</div>
<div class="ct-chart-axis" aria-hidden="true"><span>{{ hourly[0].label }}</span><span>{{ hourly[(hourly | length) // 2].label }}</span><span>now</span></div>
</div>
<details class="ct-details adm-table-details">
<summary>show as a table</summary>
<div class="ct-details-body">
<div class="table-responsive">
<table class="ct-table">
<caption>Every hour of the last 24, times in UTC</caption>
<thead><tr><th scope="col">hour</th><th scope="col">active</th><th scope="col">most online</th><th scope="col">messages sent</th></tr></thead>
<tbody>
{% for h in hourly | reverse %}
<tr><th scope="row" class="fw-normal">{{ h.label }}{% if h.is_now %} <span class="ct-chip ct-chip-success">now</span>{% endif %}</th><td>{{ h.value }}</td><td>{{ h.peak }}</td><td>{{ h.messages }}</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</details>
{% else %}
<p class="ct-muted mb-0">Nothing counted yet.</p>
{% endif %}
</section>
<section class="ct-card" aria-labelledby="admClients">
<h2 class="ct-card-title" id="admClients">clients</h2>
{% if programs %}
<ul class="ct-bars">
{% for p in programs %}
<li>
<div class="ct-bar-head"><strong>{{ p.name }}</strong><span>{{ '{:,}'.format(p.sessions) }} session{{ 's' if p.sessions != 1 else '' }} · {{ p.pct }}%</span></div>
<div class="ct-bar-track" aria-hidden="true"><div class="ct-bar-fill" style="--w: {{ p.pct }}%"></div></div>
</li>
{% endfor %}
</ul>
{% else %}
<p class="ct-muted">Nobody is signed in right now.</p>
{% endif %}
<dl class="ct-facts mt-3">
<div><dt>active today</dt><dd>{{ '{:,}'.format((stats.active or {}).today or 0) }}</dd></div>
<div><dt>sign-ins today</dt><dd>{{ '{:,}'.format(stats.logins_today or 0) }}</dd></div>
<div><dt>messages today</dt><dd>{{ '{:,}'.format(((stats.messages or {}).today or {}).sent or 0) }}</dd></div>
<div><dt>most online today</dt><dd>{{ '{:,}'.format((stats.peak_today or {}).value or 0) }}</dd></div>
</dl>
</section>
<section class="ct-card" aria-labelledby="admAlerts">
<h2 class="ct-card-title" id="admAlerts">latest alerts</h2>
{% if alerts %}
<ul class="adm-alerts">
{% for alert in alerts %}{{ alert_row(alert) }}{% endfor %}
</ul>
<p class="mt-3 mb-0"><a href="/broadcast#history" data-ct-swap-link>Every alert since azul started</a></p>
{% else %}
<p class="ct-muted mb-0">None sent since azul started.</p>
{% endif %}
</section>
<section class="ct-card" aria-labelledby="admLinks">
<h2 class="ct-card-title" id="admLinks">linked services</h2>
{% if links %}
<ul class="ct-list">
{% for link in links %}
<li class="ct-list-item">
<span class="ct-presence" aria-hidden="true"></span>
<span class="ct-list-body">
<span class="ct-list-title">{{ link.label or link.identifier }}</span>
<span class="ct-list-meta">{{ link.identifier }} from {{ link.peer }}{% if link.client and link.client.program %} · {{ link.client.program }} {{ link.client.version }}{% endif %}</span>
</span>
</li>
{% endfor %}
</ul>
{% else %}
<p class="ct-muted">Nothing is linked over InterService right now. The website needs its own link for accounts, the directory and CrossTalk Beacon.</p>
{% endif %}
<h3 class="ct-aside-title mt-3" id="admServices">listening</h3>
{% if info.services %}
<dl class="ct-facts">
{% for service in info.services %}
<div><dt>{{ service.name }}</dt><dd>{{ service.ports | join(', ') }}</dd></div>
{% endfor %}
</dl>
{% else %}
<p class="ct-muted mb-0">No IM services are listening (none are turned on in the settings).</p>
{% endif %}
</section>
</div>
<section class="mt-4" aria-labelledby="admQuick">
<h2 class="ct-section mt-0" id="admQuick">quick jobs</h2>
<div class="ct-actions">
<a class="btn btn-primary btn-sm" href="/broadcast#alert" data-ct-swap-link>Send an alert</a>
<a class="btn btn-outline-secondary btn-sm" href="/broadcast#maintenance" data-ct-swap-link>Schedule maintenance</a>
<a class="btn btn-outline-secondary btn-sm" href="/interservice#enroll" data-ct-swap-link>Enroll a service</a>
<a class="btn btn-outline-secondary btn-sm" href="/users?show=online" data-ct-swap-link>Who's signed in</a>
</div>
</section>
{% endblock %}
-41
View File
@@ -1,41 +0,0 @@
{% 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 %}
<nav class="ct-pivot ct-pivot-sm mb-3" aria-label="Filter by client" data-ct-swap-pivot>
<a href="/sessions" data-ct-swap-link{% if not program %} aria-current="page"{% endif %}>everything <span class="ct-count">{{ total }}</span></a>
{% for p, name in programs %}<a href="/sessions?program={{ p | urlencode }}" data-ct-swap-link{% if p == program %} aria-current="page"{% endif %}>{{ name | lower }}</a>{% endfor %}
</nav>
{% endif %}
{% if sessions %}
<div class="ct-card adm-table-card">
<div class="table-responsive">
<table class="ct-table ct-table-stack">
<thead><tr><th scope="col">who</th><th scope="col">client</th><th scope="col">status</th><th scope="col" class="text-end"><span class="visually-hidden">actions</span></th></tr></thead>
<tbody>
{% for s in sessions %}
<tr>
<td><a href="/users/{{ s.uuid }}" data-ct-swap-link><strong>{{ s.username }}</strong></a><br><small class="ct-muted">{{ s.email }}</small></td>
<td data-label="client">{{ program_names.get(s.client.program, s.client.program) }} {{ s.client.version }}<br><small class="ct-muted">{{ s.client.via }}</small></td>
<td data-label="status">{% if s.visible %}<span class="ct-presence me-1" aria-hidden="true"></span>{% endif %}{{ s.status | lower }}</td>
<td class="text-end">
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="session" value="{{ s.id }}">
<input type="hidden" name="program" value="{{ program }}">
<button type="submit" class="btn btn-sm btn-outline-danger">Sign out<span class="visually-hidden"> {{ s.username }} from {{ s.client.program }}</span></button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% else %}
<p class="ct-muted">Nobody is signed in{% if program %} with {{ program_names.get(program, program) }}{% endif %}.</p>
{% endif %}
{% endblock %}
-181
View File
@@ -1,181 +0,0 @@
{% extends 'base.html' %}
{% from '_ui.html' import flags as flag_chips, csrf_field, copy_field %}
{% block content %}
<p class="ct-back"><a href="/users" data-ct-swap-link>Users</a></p>
<section class="ct-card adm-identity" aria-labelledby="userName">
<span class="adm-avatar adm-avatar-lg">
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ user.uuid }}/static" alt="" width="72" height="72">
{% if user.online %}<span class="ct-presence" aria-hidden="true"></span>{% endif %}
</span>
<div class="min-w-0 flex-grow-1">
<h1 class="adm-identity-name" id="userName">{{ user.username }}</h1>
<p class="ct-muted mb-1 text-truncate">{{ user.email }}{% if user.uin %} · UIN {{ user.uin }}{% endif %}</p>
<p class="mb-0">{{ flag_chips(user) }}</p>
</div>
<dl class="adm-identity-facts">
<div><dt>status</dt><dd>{% if user.online %}{{ user.status | lower }}, {{ user.sessions }} session{{ 's' if user.sessions != 1 else '' }}{% if programs %} ({{ programs | join(', ') }}){% endif %}{% else %}signed out{% endif %}</dd></div>
<div><dt>joined</dt><dd>{{ user.date_created | when }}</dd></div>
<div><dt>last signed in</dt><dd>{{ user.date_login | when }}</dd></div>
<div><dt>UUID</dt><dd><code class="adm-uuid">{{ user.uuid }}</code><button type="button" class="ct-icon-btn ct-icon-btn-sm" data-ct-copy="{{ user.uuid }}" aria-label="Copy the UUID" title="Copy"><i class="bi bi-copy" aria-hidden="true"></i></button></dd></div>
</dl>
</section>
{% if user.suspended %}
<section class="ct-card adm-suspended" aria-labelledby="userSuspended">
<div>
<h2 class="adm-suspended-title" id="userSuspended">suspended{% if user.suspended_at %} {{ user.suspended_at | ago }}{% endif %}</h2>
{% if user.deleted_at is none or suspended_days is none %}
<p class="mb-0">{% if user.suspended_at %}Since {{ user.suspended_at | when }}. {% endif %}Suspended accounts are kept on this server.</p>
{% elif user.suspended_at %}
<p class="mb-0">Since {{ user.suspended_at | when }}. The account is deleted <strong>{{ user.deleted_at | until }}</strong> ({{ user.deleted_at | when }}), {{ suspended_days }} days after it was suspended, unless it's unsuspended before then.</p>
{% else %}
<p class="mb-0">It was suspended before azul kept the date, so it's deleted <strong>at the next hourly check</strong>, unless it's unsuspended first.</p>
{% endif %}
</div>
</section>
{% endif %}
{% if reveal and reveal.kind == 'password' %}
<section class="ct-card adm-reveal" aria-labelledby="tempPassword">
<h2 class="ct-card-title" id="tempPassword">temporary password for {{ reveal['for'] }}</h2>
<p>Give it to them however you can reach them. It won't be shown again, and they should change it once they're in.</p>
{{ copy_field('tempPasswordValue', reveal.value, 'Temporary password') }}
</section>
{% endif %}
<div class="adm-columns">
<section class="ct-card" aria-labelledby="userFlags">
<h2 class="ct-card-title" id="userFlags">account</h2>
<form method="post">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="flags">
<div class="ct-switches">
{% for key, label, desc in flags %}
<label class="ct-switch-row form-switch" for="flag-{{ key }}">
<span>
<span class="ct-switch-title">{{ label }}</span>
<span class="ct-switch-desc">{{ desc }}{% if key == 'is_admin' and is_self %} You can't turn this off for yourself.{% endif %}{% if key == 'suspended' and suspended_days is not none %} Suspended accounts are deleted after {{ suspended_days }} days.{% endif %}</span>
</span>
<input class="form-check-input" type="checkbox" role="switch" id="flag-{{ key }}" name="{{ key }}"{% if user[key] %} checked{% endif %}{% if key == 'is_admin' and is_self %} disabled{% endif %}>
</label>
{% if key == 'is_admin' and is_self and user[key] %}<input type="hidden" name="is_admin" value="on">{% endif %}
{% endfor %}
</div>
<div class="ct-form-actions"><button type="submit" class="btn btn-primary">Save</button></div>
</form>
</section>
<div>
<section class="ct-card" aria-labelledby="userAlert">
<h2 class="ct-card-title" id="userAlert">alert</h2>
<form method="post" class="adm-mini-alert">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="alert">
<div class="ct-field">
<label for="alertMessage" class="form-label">Message</label>
<textarea class="form-control" id="alertMessage" name="message" rows="3" maxlength="1000" required aria-describedby="alertMarkup"></textarea>
<small class="form-text" id="alertMarkup">**bold**, *italic*, and a blank line for a new paragraph: Messenger 6 and later show them, the rest get the words.</small>
</div>
<div class="ct-field">
<label for="alertUrl" class="form-label">Link <span class="ct-muted">(optional)</span></label>
<input type="url" class="form-control" id="alertUrl" name="url" inputmode="url" placeholder="https://">
</div>
{% if email_available %}
<div class="form-check form-switch my-3">
<input class="form-check-input" type="checkbox" role="switch" id="alertEmail" name="email">
<label class="form-check-label" for="alertEmail">Also e-mail it to {{ user.email }}</label>
</div>
{% endif %}
<button type="submit" class="btn btn-outline-secondary"{% if not user.online and not email_available %} disabled aria-describedby="alertOffline"{% endif %}>Send alert</button>
{% if not user.online %}<p class="form-text" id="alertOffline">{{ 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 %}.</p>{% endif %}
</form>
</section>
<section class="ct-card" aria-labelledby="userSessions">
<h2 class="ct-card-title" id="userSessions">sessions</h2>
{% if sessions %}
<ul class="ct-list">
{% for s in sessions %}
<li class="ct-list-item">
<span class="ct-list-body">
<span class="ct-list-title">{{ program_names.get(s.client.program, s.client.program) }} {{ s.client.version }}</span>
<span class="ct-list-meta">{{ s.status | lower }} via {{ s.client.via }}</span>
</span>
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="kill">
<input type="hidden" name="session" value="{{ s.id }}">
<button type="submit" class="btn btn-sm btn-outline-danger">Sign out<span class="visually-hidden"> {{ s.client.program }}</span></button>
</form>
</li>
{% endfor %}
</ul>
<form method="post" class="mt-2">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="kill-all">
<button type="submit" class="btn btn-outline-danger">Sign out everywhere</button>
</form>
{% else %}
<p class="ct-muted">Not signed in anywhere.</p>
{% endif %}
</section>
<section class="ct-card" aria-labelledby="userPassword">
<h2 class="ct-card-title" id="userPassword">password</h2>
<form method="post" class="mb-3">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="password">
<div class="ct-field">
<label for="newPassword" class="form-label">New password</label>
<div class="ct-password">
<input type="password" class="form-control" id="newPassword" name="password" minlength="6" autocomplete="new-password" required>
<button type="button" class="ct-icon-btn" data-ct-reveal="newPassword" aria-pressed="false" aria-label="Show password"><i class="bi bi-eye-fill" aria-hidden="true"></i></button>
</div>
</div>
<fieldset class="adm-inline-checks">
<legend class="form-label">Keep working in</legend>
{% for flag, name in legacy_clients %}
<div class="form-check">
<input class="form-check-input" type="checkbox" id="client-{{ flag }}" name="client_{{ flag }}"{% if flag in (user.clients or []) %} checked{% endif %}>
<label class="form-check-label" for="client-{{ flag }}">{{ name }}</label>
</div>
{% endfor %}
</fieldset>
<button type="submit" class="btn btn-primary">Set password</button>
</form>
<div class="ct-actions">
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="temp-password">
<button type="submit" class="btn btn-outline-secondary">Make a temporary one</button>
</form>
<form method="post" class="m-0">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="reset-email">
<button type="submit" class="btn btn-outline-secondary"{% if not reset_available %} disabled aria-describedby="resetHelp"{% endif %}>E-mail them a reset link</button>
</form>
</div>
{% if not reset_available %}<p class="form-text" id="resetHelp">The website isn't linked right now, so it can't send the e-mail.</p>{% endif %}
</section>
</div>
</div>
<section class="ct-card adm-danger" aria-labelledby="userDelete">
<h2 class="ct-card-title" id="userDelete">delete this account</h2>
{% if is_self %}
<p class="ct-muted mb-0">You can't delete your own account from the admin panel.</p>
{% else %}
<p>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.</p>
<form method="post" class="adm-confirm">
{{ csrf_field(csrf) }}
<input type="hidden" name="action" value="delete">
<label for="deleteConfirm" class="form-label">Type <strong>{{ user.username }}</strong> to confirm</label>
<div class="d-flex flex-wrap gap-2">
<input type="text" class="form-control" id="deleteConfirm" name="confirm" autocomplete="off" spellcheck="false" required>
<button type="submit" class="btn btn-danger">Delete account</button>
</div>
</form>
{% endif %}
</section>
{% endblock %}
-50
View File
@@ -1,50 +0,0 @@
{% 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.') }}
<form method="get" action="/users" class="adm-search" role="search" aria-label="Search users" data-ct-swap-form>
{% if show %}<input type="hidden" name="show" value="{{ show }}">{% endif %}
<div class="ct-search flex-grow-1">
<i class="bi bi-search" aria-hidden="true"></i>
<label for="userSearch" class="visually-hidden">Search by username, e-mail or UUID</label>
<input type="search" class="form-control" id="userSearch" name="q" value="{{ q }}" placeholder="Username, e-mail or UUID" autocomplete="off" spellcheck="false">
</div>
<button type="submit" class="btn btn-primary">Search</button>
{% if q %}<a class="btn btn-outline-secondary" href="/users{% if show %}?show={{ show }}{% endif %}" data-ct-swap-link>Clear</a>{% endif %}
</form>
{% set query = ('&q=' ~ (q | urlencode)) if q else '' %}
<nav class="ct-pivot ct-pivot-sm adm-filters" aria-label="Show" data-ct-swap-pivot>
<a href="/users{% if q %}?q={{ q | urlencode }}{% endif %}" data-ct-swap-link{% if not show %} aria-current="page"{% endif %}>everyone</a>
{% for name, label, _ in filters %}
<a href="/users?show={{ name }}{{ query }}" data-ct-swap-link{% if show == name %} aria-current="page"{% endif %}>{{ label }}</a>
{% endfor %}
</nav>
{% if q or show %}<p class="ct-muted mb-3">{{ '{:,}'.format(matched) }} {{ 'account' if matched == 1 else 'accounts' }}{% if q %} matching "{{ q }}"{% endif %}</p>{% endif %}
{% if users %}
<ul class="adm-people ct-card">
{% for u in users %}
<li>
<a class="adm-person" href="/users/{{ u.uuid }}" data-ct-swap-link>
<span class="adm-avatar">
<img src="http://{{ settings.USERSTORAGE_HOST }}/avatar/{{ u.uuid }}/im" alt="" width="36" height="36" loading="lazy">
{% if u.online %}<span class="ct-presence" aria-hidden="true"></span>{% endif %}
</span>
<span class="adm-person-body">
<span class="adm-person-name">{{ u.username }}{% if u.online %}<span class="visually-hidden">, signed in</span>{% endif %}</span>
<span class="adm-person-meta">{{ u.email }}{% if u.suspended and u.deleted_at %} · <span class="adm-doomed">deleted {{ u.deleted_at | until }}</span>{% endif %}</span>
</span>
<span class="adm-person-flags">{{ flags(u) }}</span>
<span class="adm-person-when ct-muted">joined {{ u.date_created | ago }}<br>last in {{ u.date_login | ago }}</span>
</a>
</li>
{% endfor %}
</ul>
{{ pager(page, pages, '/users?' ~ ('show=' ~ show ~ '&' if show else '') ~ ('q=' ~ (q | urlencode) ~ '&' if q else '')) }}
{% else %}
<p class="ct-muted">{% if q or show %}Nobody matches that.{% else %}There are no accounts yet.{% endif %}</p>
{% endif %}
{% endblock %}
File renamed without changes.
+67
View File
@@ -0,0 +1,67 @@
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')
+36
View File
@@ -0,0 +1,36 @@
<html>
<body>
<h1>IRC Chats</h1>
<div id="chats">
</div>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/ircChats', true);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
chats_div = document.getElementById('chats');
innerHtml = '';
response = JSON.parse(this.responseText);
for (i in response) {
channel = response[i]
users = channel['users'];
innerHtml += '<h3>' + channel['channel'] + '</h3>';
innerHtml += '<br/>';
innerHtml += 'Total users: ' + users.length.toString();
innerHtml += '<br/><br/>';
innerHtml += 'Users:';
innerHtml += '<ul>';
for (j in users) {
innerHtml += '<li>' + users[j] + '</li>';
}
innerHtml += '</ul>';
}
chats_div.innerHTML = innerHtml;
}
}
xhr.send();
</script>
</body>
</html>
File renamed without changes.
+177
View File
@@ -0,0 +1,177 @@
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
+1
View File
@@ -0,0 +1 @@
from .entry import register
+170
View File
@@ -0,0 +1,170 @@
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
-122
View File
@@ -1,122 +0,0 @@
import random
import struct
# the V5 scrambling table: V5 packets are encrypted with it, and V3/V4/V5
# checkcodes point into it
V5_TABLE = bytes((
0x59, 0x60, 0x37, 0x6B, 0x65, 0x62, 0x46, 0x48, 0x53, 0x61, 0x4C, 0x59, 0x60, 0x57, 0x5B, 0x3D,
0x5E, 0x34, 0x6D, 0x36, 0x50, 0x3F, 0x6F, 0x67, 0x53, 0x61, 0x4C, 0x59, 0x40, 0x47, 0x63, 0x39,
0x50, 0x5F, 0x5F, 0x3F, 0x6F, 0x47, 0x43, 0x69, 0x48, 0x33, 0x31, 0x64, 0x35, 0x5A, 0x4A, 0x42,
0x56, 0x40, 0x67, 0x53, 0x41, 0x07, 0x6C, 0x49, 0x58, 0x3B, 0x4D, 0x46, 0x68, 0x43, 0x69, 0x48,
0x33, 0x31, 0x44, 0x65, 0x62, 0x46, 0x48, 0x53, 0x41, 0x07, 0x6C, 0x69, 0x48, 0x33, 0x51, 0x54,
0x5D, 0x4E, 0x6C, 0x49, 0x38, 0x4B, 0x55, 0x4A, 0x62, 0x46, 0x48, 0x33, 0x51, 0x34, 0x6D, 0x36,
0x50, 0x5F, 0x5F, 0x5F, 0x3F, 0x6F, 0x47, 0x63, 0x59, 0x40, 0x67, 0x33, 0x31, 0x64, 0x35, 0x5A,
0x6A, 0x52, 0x6E, 0x3C, 0x51, 0x34, 0x6D, 0x36, 0x50, 0x5F, 0x5F, 0x3F, 0x4F, 0x37, 0x4B, 0x35,
0x5A, 0x4A, 0x62, 0x66, 0x58, 0x3B, 0x4D, 0x66, 0x58, 0x5B, 0x5D, 0x4E, 0x6C, 0x49, 0x58, 0x3B,
0x4D, 0x66, 0x58, 0x3B, 0x4D, 0x46, 0x48, 0x53, 0x61, 0x4C, 0x59, 0x40, 0x67, 0x33, 0x31, 0x64,
0x55, 0x6A, 0x32, 0x3E, 0x44, 0x45, 0x52, 0x6E, 0x3C, 0x31, 0x64, 0x55, 0x6A, 0x52, 0x4E, 0x6C,
0x69, 0x48, 0x53, 0x61, 0x4C, 0x39, 0x30, 0x6F, 0x47, 0x63, 0x59, 0x60, 0x57, 0x5B, 0x3D, 0x3E,
0x64, 0x35, 0x3A, 0x3A, 0x5A, 0x6A, 0x52, 0x4E, 0x6C, 0x69, 0x48, 0x53, 0x61, 0x6C, 0x49, 0x58,
0x3B, 0x4D, 0x46, 0x68, 0x63, 0x39, 0x50, 0x5F, 0x5F, 0x3F, 0x6F, 0x67, 0x53, 0x41, 0x25, 0x41,
0x3C, 0x51, 0x54, 0x3D, 0x5E, 0x54, 0x5D, 0x4E, 0x4C, 0x39, 0x50, 0x5F, 0x5F, 0x5F, 0x3F, 0x6F,
0x47, 0x43, 0x69, 0x48, 0x33, 0x51, 0x54, 0x5D, 0x6E, 0x3C, 0x31, 0x64, 0x35, 0x5A, 0x00, 0x00,
))
# the V4 table is the first 256 bytes of the tips text ICQ 98a ships with
V4_TABLE = (
b'\n[1] You can modify the sounds ICQ makes. Just select "Sounds" from the "preferences/misc" in ICQ or from the '
b'"Sounds" in the control panel. Credit: Eran\n[2] Can\'t remember what was said? Double-click on a user to get a '
b'dialog of all messages sent incomin'
)
assert len(V5_TABLE) == 256 and len(V4_TABLE) == 256
# a V5 client packet's checkcode sits at 0x14, a server packet's at 0x11
V5_CLIENT_CHECKCODE_OFFSET = 0x14
V5_SERVER_CHECKCODE_OFFSET = 0x11
# a V4 client packet's checkcode sits at 0x10, after the header it stands in for
V4_CLIENT_CHECKCODE_OFFSET = 0x10
def _u32(value: int) -> int:
return value & 0xFFFFFFFF
def _descramble_v5_checkcode(check: int) -> int:
# the checkcode's bits are shuffled before it goes into the key
a1 = (check & 0x0001F000) >> 0x0C
a2 = (check & 0x07C007C0) >> 0x01
a3 = _u32((check & 0x003E0001) << 0x0A)
a4 = (check & 0xF8000000) >> 0x10
a5 = _u32((check & 0x0000083E) << 0x0F)
return _u32(a5 + a1 + a2 + a3 + a4)
def decrypt_v5(packet: bytes) -> bytes:
# a V5 client packet is encrypted from 0x0A on with a key made from its length and checkcode; the checkcode itself
# (0x14..0x17) is left as it is
if len(packet) < 0x18:
return packet
data = bytearray(packet)
length = len(data)
check = struct.unpack_from('<L', data, V5_CLIENT_CHECKCODE_OFFSET)[0]
key = _u32(length * 0x68656C6C + _descramble_v5_checkcode(check))
for i in range(0x0A, length + 3, 4):
k = _u32(key + V5_TABLE[i & 0xFF])
if i != 0x16:
if i < length:
data[i] ^= k & 0xFF
if i + 1 < length:
data[i + 1] ^= (k >> 8) & 0xFF
if i != 0x12:
if i + 2 < length:
data[i + 2] ^= (k >> 16) & 0xFF
if i + 3 < length:
data[i + 3] ^= (k >> 24) & 0xFF
return bytes(data)
def v5_checkcode(packet: bytes) -> int:
# bytes 8, 4, 2 and 6 of the packet, against a random byte of the packet's first 16 and a random table entry
b2, b4, b6, b8 = packet[2], packet[4], packet[6], packet[8]
number1 = (b8 << 24) | (b4 << 16) | (b2 << 8) | b6
x4 = random.randrange(0x10)
x3 = packet[x4]
x2 = random.randrange(0xFF)
x1 = V5_TABLE[x2]
number2 = ((x4 << 24) | (x3 << 16) | (x2 << 8) | x1) ^ 0x00FF00FF
return _u32(number1 ^ number2)
def add_v5_server_checkcode(packet: bytearray) -> None:
# server packets aren't encrypted, only stamped with a checkcode at 0x11 the client verifies
struct.pack_into('<L', packet, V5_SERVER_CHECKCODE_OFFSET, v5_checkcode(bytes(packet)))
def decrypt_v4(packet: bytes) -> bytes:
# V4 only encrypts the first quarter of a packet, a dword at a time with a key made from its length and checkcode; the
# checkcode dword (the fifth) is skipped, and the version (never really encrypted) is put back
if len(packet) < 0x14:
return packet
data = bytearray(packet)
length = len(data)
check = struct.unpack_from('<L', data, V4_CLIENT_CHECKCODE_OFFSET)[0]
key = _u32(length * 0x66756B65 + check)
count = ((length + 3) // 4 + 3) // 4
for i in range(count):
if i == 4:
continue
pos = i * 4
if pos >= length:
break
k = _u32(key + V4_TABLE[pos & 0xFF])
for j in range(4):
if pos + j < length:
data[pos + j] ^= (k >> (j * 8)) & 0xFF
data[0:2] = b'\x04\x00'
return bytes(data)
def v3_header_checkcode(header: bytes) -> int:
# what a V4 client checks a server packet's V3 header against: bytes 8, 4, 2 and 6 of it, xored with an offset into the
# header and the inverse of the byte there, and an offset into the V4 table and the inverse of that entry (the offsets
# are the server's to pick; the first byte of seq1 and the first entry)
check_a = (header[8] << 24) | (header[4] << 16) | (header[2] << 8) | header[6]
packet_offset = 4
table_offset = 0
check_b = (packet_offset << 24) | ((~header[packet_offset] & 0xFF) << 16) | (table_offset << 8) | (~V4_TABLE[table_offset] & 0xFF)
return _u32(check_a ^ check_b)
-1075
View File
File diff suppressed because it is too large. Load diff
-98
View File
@@ -1,98 +0,0 @@
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]
-139
View File
@@ -1,139 +0,0 @@
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]
-160
View File
@@ -1,160 +0,0 @@
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))
-709
View File
@@ -1,709 +0,0 @@
import struct
from datetime import datetime
from enum import IntEnum
from typing import Any
from core.models import OIM, User
from util import icq
from util.misc import Logger
from ..proto import names
from ..proto.snac import OSCARClient, OSCARContext, SNACMessage, Foodgroup, Subgroup
from ..proto.tlv import TLV, unmarshal_tlvs, find_tlv
class ICQRequest(IntEnum):
# ICQ__DB_QUERY request types (the u16 after the UIN in the little-endian envelope)
OfflineMessages = 0x003C
DeleteOfflineMessages = 0x003E
Meta = 0x07D0
class ICQReply(IntEnum):
OfflineMessage = 0x0041
OfflineMessagesDone = 0x0042
Meta = 0x07DA
class ICQResult(IntEnum):
Ok = 0x0A
Fail = 0x32
Error = 0x14
class ICQMeta(IntEnum):
# requests
SetBasicInfo = 0x03EA
SetWorkInfo = 0x03F3
SetMoreInfo = 0x03FD
SetNotes = 0x0406
SetEmails = 0x040B
SetInterests = 0x0410
SetAffiliations = 0x041A
SetPermissions = 0x0424
FullInfo = 0x04B2
ShortInfo = 0x04BA
FullInfo2 = 0x04D0
SearchByDetails = 0x0515
SearchByUin = 0x051F
SearchByEmail = 0x0529
SearchWhitePages = 0x0533
SearchWhitePages2 = 0x055F
SearchByUin2 = 0x0569
SearchByEmail3 = 0x0573
SetIcqPhone = 0x0654
XmlRequest = 0x0898
SetFullInfo = 0x0C3A
DirectoryQuery = 0x0FA0
# replies
SetBasicInfoAck = 0x0064
SetWorkInfoAck = 0x006E
SetMoreInfoAck = 0x0078
SetNotesAck = 0x0082
SetEmailsAck = 0x0087
SetInterestsAck = 0x008C
SetAffiliationsAck = 0x0096
SetPermissionsAck = 0x00A0
BasicInfo = 0x00C8
WorkInfo = 0x00D2
MoreInfo = 0x00DC
Notes = 0x00E6
ExtEmails = 0x00EB
Interests = 0x00F0
Affiliations = 0x00FA
ShortInfoReply = 0x0104
HomepageCategory = 0x010E
UserFound = 0x01A4
LastUserFound = 0x01AE
SetIcqPhoneAck = 0x031E
SetFullInfoAck = 0x0C3F
XmlReply = 0x08A2
DirectoryResponse = 0x0FB4
# ICQ__TLV tags for the TLV-based requests (white pages 2, search by UIN 2/e-mail 3, set full info); values little endian
class ICQTag(IntEnum):
Uin = 0x0136
FirstName = 0x0140
LastName = 0x014A
Nickname = 0x0154
Email = 0x015E
Gender = 0x017C
HomeCity = 0x0190
HomeState = 0x019A
HomeCountry = 0x01A4
WorkCompany = 0x01AE
WorkDepartment = 0x01B8
WorkPosition = 0x01C2
WorkOccupation = 0x01CC
HomepageUrl = 0x0213
OnlineOnly = 0x0230
Birthday = 0x023A
Notes = 0x0258
HomeAddress = 0x0262
HomeZip = 0x026C
HomePhone = 0x0276
HomeFax = 0x0280
HomeCell = 0x028A
WorkAddress = 0x0294
WorkCity = 0x029E
WorkState = 0x02A8
WorkCountry = 0x02B2
WorkZip = 0x02BC
WorkPhone = 0x02C6
WorkFax = 0x02D0
WorkWebpage = 0x02DA
Authorization = 0x02F8
WebAware = 0x030C
GmtOffset = 0x0316
# search hits' online status
DIR_STATUS_OFFLINE = 0
DIR_STATUS_ONLINE = 1
DIR_STATUS_HIDDEN = 2
MAX_SEARCH_RESULTS = 20
class LE:
# a little-endian writer, the byte order the ICQ envelope inside foodgroup 0x15 uses
__slots__ = ('data',)
def __init__(self) -> None:
self.data = b''
def u8(self, value: int) -> 'LE':
self.data += struct.pack('<B', value & 0xFF)
return self
def u16(self, value: int) -> 'LE':
self.data += struct.pack('<H', value & 0xFFFF)
return self
def u32(self, value: int) -> 'LE':
self.data += struct.pack('<L', value & 0xFFFFFFFF)
return self
def raw(self, value: bytes) -> 'LE':
self.data += value
return self
def string(self, value: str) -> 'LE':
# u16 length, then the text and its NUL; an empty string is just a zero length
if not value:
return self.u16(0)
encoded = icq.latin1(value) + b'\x00'
return self.u16(len(encoded)).raw(encoded)
class LEReader:
__slots__ = ('data', 'pos')
def __init__(self, data: bytes) -> None:
self.data = data
self.pos = 0
def remaining(self) -> int:
return len(self.data) - self.pos
def _take(self, length: int) -> bytes:
if self.pos + length > len(self.data):
raise ValueError('truncated ICQ request')
chunk = self.data[self.pos:self.pos + length]
self.pos += length
return chunk
def u8(self) -> int:
return self._take(1)[0]
def u16(self) -> int:
return struct.unpack('<H', self._take(2))[0]
def u32(self) -> int:
return struct.unpack('<L', self._take(4))[0]
def string(self) -> str:
raw = self._take(self.u16())
if b'\x00' in raw:
raw = raw[:raw.index(b'\x00')]
return icq.from_latin1(raw)
def rest(self) -> bytes:
chunk = self.data[self.pos:]
self.pos = len(self.data)
return chunk
def parse_le_tlvs(data: bytes) -> list[tuple[int, bytes]]:
# the TLV-based ICQ requests use little-endian TLVs
tlvs = []
reader = LEReader(data)
while reader.remaining() >= 4:
tag = reader.u16()
length = reader.u16()
if reader.remaining() < length:
break
tlvs.append((tag, reader._take(length)))
return tlvs
def tlv_string(value: bytes) -> str:
try:
return LEReader(value).string()
except ValueError:
return ''
def tlv_int(value: bytes) -> int:
if len(value) >= 4:
return struct.unpack('<L', value[:4])[0]
if len(value) >= 2:
return struct.unpack('<H', value[:2])[0]
return value[0] if value else 0
class ICQContext:
# one ICQ__DB_QUERY being answered: who asked, under which SNAC request id and ICQ sequence number
__slots__ = ('client', 'context', 'request_id', 'seq', 'uin')
def __init__(self, client: OSCARClient, context: OSCARContext, request_id: int, seq: int) -> None:
self.client = client
self.context = context
self.request_id = request_id
self.seq = seq
self.uin = names.uin_of(context.user) or 0
def reply(self, reply_type: int, body: bytes, *, more: bool = False) -> None:
# ICQ__DB_REPLY: TLV 0x01 holding a u16 (LE) length, then u32 UIN, u16 reply type, u16 sequence and the body
envelope = LE().u32(self.uin).u16(reply_type).u16(self.seq).raw(body).data
msg = SNACMessage(0x0015, 0x0003, 0x0001 if more else 0x0000, self.request_id)
msg.write_tlv(TLV(0x0001, LE().u16(len(envelope)).raw(envelope).data))
self.client.send_snac(msg)
def meta(self, subtype: int, result: int, body: bytes = b'', *, more: bool = False) -> None:
self.reply(ICQReply.Meta, LE().u16(subtype).u8(result).raw(body if result == ICQResult.Ok else b'').data, more = more)
@Foodgroup(0x0015)
class ICQFoodgroup:
logger: Logger
@Subgroup(0x0002)
def db_query(self, client: OSCARClient, context: OSCARContext, message: SNACMessage) -> None:
tlvs = unmarshal_tlvs(message.data)
envelope_tlv = find_tlv(tlvs, 0x0001)
if envelope_tlv is None or len(envelope_tlv.data) < 2:
self.logger.info('[Client] ICQ__DB_QUERY without its envelope')
return
# TLV 0x01: u16 (LE) length, u32 UIN, u16 request type, u16 sequence, [u16 meta subtype], request data
reader = LEReader(envelope_tlv.data)
try:
length = reader.u16()
reader = LEReader(reader._take(min(length, reader.remaining())))
reader.u32()
request_type = reader.u16()
seq = reader.u16()
except ValueError:
self.logger.info('[Client] Truncated ICQ__DB_QUERY')
return
query = ICQContext(client, context, message.request_id, seq)
if request_type == ICQRequest.OfflineMessages:
self.logger.info('[Client] ICQ__DB_QUERY offline messages')
offline_messages(query)
elif request_type == ICQRequest.DeleteOfflineMessages:
self.logger.info('[Client] ICQ__DB_QUERY delete offline messages')
delete_offline_messages(query)
elif request_type == ICQRequest.Meta:
try:
subtype = reader.u16()
except ValueError:
return
self.logger.info('[Client] ICQ__DB_QUERY meta', hex(subtype))
handler = META_HANDLERS.get(subtype)
if handler is None:
self.logger.info('[Client] Unsupported ICQ meta request', hex(subtype))
return
try:
handler(query, reader)
except ValueError:
self.logger.info('[Client] Malformed ICQ meta request', hex(subtype))
else:
self.logger.info('[Client] Unknown ICQ__DB_QUERY request type', hex(request_type))
# offline messages
def offline_messages(query: ICQContext) -> None:
# reading the store is file work, done off the event loop
query.context.backend.loop.create_task(_offline_messages(query))
async def _offline_messages(query: ICQContext) -> None:
# each stored message from someone with a UIN goes back as an offline message record (0x41); the rest only an ICBM
# can carry, since 0x41 has no room for a screen name. 0x42 ends it, and the messages go once the client deletes them
context = query.context
backend = context.backend
bs = context.bs
from .icbm import deliver_offline_messages
oims = await backend.loop.run_in_executor(None, backend.user_service.get_oim_batch, context.user)
if bs.closed:
return
pending = bs.front_data.setdefault('oscar0_offline_delivered', [])
for oim in oims:
sender = _oim_sender(backend, oim)
uin = names.uin_of(sender) if sender is not None else None
if uin is None:
deliver_offline_messages(query.client.ctrl, [oim])
continue
sent = oim.sent if isinstance(oim.sent, datetime) else datetime.utcnow()
body = LE().u32(uin).u16(sent.year).u8(sent.month).u8(sent.day).u8(sent.hour).u8(sent.minute)
body.u8(0x01).u8(0x00).string((oim.message or '').replace('\r\n', '\n').replace('\n', '\r\n'))
query.reply(ICQReply.OfflineMessage, body.data, more = True)
pending.append(oim.uuid)
query.reply(ICQReply.OfflineMessagesDone, LE().u8(0).data)
def delete_offline_messages(query: ICQContext) -> None:
context = query.context
delivered = context.bs.front_data.pop('oscar0_offline_delivered', [])
if delivered:
from .icbm import delete_stored_messages
context.backend.loop.create_task(delete_stored_messages(context.backend, context.user.uuid, delivered))
def _oim_sender(backend: Any, oim: OIM) -> User | None:
uuid = backend.util_get_uuid_from_username(oim.from_username) if oim.from_username else None
if uuid is None and oim.from_email:
uuid = backend.util_get_uuid_from_email(oim.from_email)
return backend._load_user_record(uuid) if uuid is not None else None
# user info
def _find(backend: Any, uin: int) -> User | None:
uuid = backend.util_get_uuid_from_uin(uin)
return backend._load_user_record(uuid) if uuid is not None else None
def _listed(user: User, viewer: User | None = None) -> bool:
# the white pages only show someone who listed themselves in the member directory (or themselves, to themselves)
return user is viewer or bool(getattr(user, 'show_in_dir', False))
def _auth_flag(user: User) -> int:
# 0 means authorization required, 1 that anyone may add this user
return 0 if icq.permissions(user)['auth_required'] else 1
def basic_info_body(user: User, viewer: User | None = None) -> bytes:
info = icq.basic_info(user)
perms = icq.permissions(user)
listed = _listed(user, viewer)
body = LE().string(info['nick'])
# real names and contact details only for people listed in the directory
for field in ('first', 'last'):
body.string(info[field] if listed else '')
body.string(info['email'] if info['publish_email'] or user is viewer else '')
for field in ('city', 'state', 'phone', 'fax', 'address', 'cell', 'zip'):
body.string(info[field] if listed else '')
body.u16(info['country'] if listed else 0).u8(info['gmt'])
body.u8(_auth_flag(user)).u8(1 if perms['web_aware'] else 0).u8(0)
# publish e-mail: 0 yes, 1 no
body.u8(0 if info['publish_email'] else 1)
return body.data
def more_info_body(user: User, viewer: User | None = None) -> bytes:
more = icq.more_info(user)
info = icq.basic_info(user)
listed = _listed(user, viewer)
body = LE().u16(icq.age(user) if listed else 0).u8(more['gender'] if listed else 0).string(more['homepage'] if listed else '')
body.u16(more['birth_year'] if listed else 0).u8(more['birth_month'] if listed else 0).u8(more['birth_day'] if listed else 0)
body.u8(more['lang1']).u8(more['lang2']).u8(more['lang3']).u16(0)
body.string(info['city'] if listed else '').string(info['state'] if listed else '').u16(info['country'] if listed else 0)
body.u8(info['gmt'])
# trailing bytes ICQ 5 wants, or it reports "error 117"
body.raw(bytes(4))
return body.data
def work_info_body(user: User, viewer: User | None = None) -> bytes:
work = icq.work_info(user) if _listed(user, viewer) else { field: '' for field in ('city', 'state', 'phone', 'fax', 'address', 'zip', 'company', 'department', 'position', 'webpage') }
body = LE()
for field in ('city', 'state', 'phone', 'fax', 'address', 'zip'):
body.string(work[field])
body.u16(work.get('country', 0) or 0)
for field in ('company', 'department', 'position'):
body.string(work[field])
body.u16(work.get('occupation', 0) or 0).string(work['webpage'])
return body.data
def _pairs_body(pairs: list[list[Any]]) -> LE:
body = LE().u8(len(pairs))
for code, keyword in pairs:
body.u16(int(code)).string(keyword)
return body
def short_info_body(user: User, viewer: User | None = None) -> bytes:
info = icq.basic_info(user)
listed = _listed(user, viewer)
body = LE().string(info['nick']).string(info['first'] if listed else '').string(info['last'] if listed else '')
body.string(info['email'] if info['publish_email'] or user is viewer else '').u8(_auth_flag(user)).u8(0)
body.u8(icq.more_info(user)['gender'] if listed else 0)
return body.data
def search_record(query: ICQContext, user: User) -> bytes:
# a search hit: u16 length, then UIN, nick, first, last, e-mail, auth flag, online status, gender, age
info = icq.basic_info(user)
listed = _listed(user, query.context.user)
record = LE().u32(names.uin_of(user) or 0).string(info['nick'])
record.string(info['first'] if listed else '').string(info['last'] if listed else '')
record.string(info['email'] if info['publish_email'] else '')
record.u8(_auth_flag(user)).u16(_search_status(query, user))
record.u8(icq.more_info(user)['gender'] if listed else 0).u16(icq.age(user) if listed else 0)
return LE().u16(len(record.data)).raw(record.data).data
def _search_status(query: ICQContext, user: User) -> int:
# someone not "web aware" shows as hidden whether or not they're on
if not icq.permissions(user)['web_aware']:
return DIR_STATUS_HIDDEN
sessions = query.context.backend.util_get_sessions_by_user(user)
return DIR_STATUS_ONLINE if sessions and not user.status.is_offlineish() else DIR_STATUS_OFFLINE
def search_results(query: ICQContext, users: list[User]) -> None:
# every hit but the last is "user found" (with the trailing bytes ICQ 5 wants); the last says how many are left
users = [user for user in users if names.uin_of(user) is not None][:MAX_SEARCH_RESULTS]
if not users:
query.meta(ICQMeta.LastUserFound, ICQResult.Fail)
return
for index, user in enumerate(users):
if index < len(users) - 1:
query.meta(ICQMeta.UserFound, ICQResult.Ok, search_record(query, user) + bytes(12), more = True)
else:
query.meta(ICQMeta.LastUserFound, ICQResult.Ok, search_record(query, user) + LE().u32(0).data + bytes(8))
def _users(backend: Any, uuids: list[str]) -> list[User]:
users = []
for uuid in uuids:
user = backend._load_user_record(uuid)
if user is not None:
users.append(user)
return users
def meta_short_info(query: ICQContext, reader: LEReader) -> None:
user = _find(query.context.backend, reader.u32())
if user is None:
query.meta(ICQMeta.ShortInfoReply, ICQResult.Error)
return
query.meta(ICQMeta.ShortInfoReply, ICQResult.Ok, short_info_body(user, query.context.user))
def meta_full_info(query: ICQContext, reader: LEReader) -> None:
# basic, more, extra e-mails, homepage category, work, notes, interests, affiliations: each part says more follow
user = _find(query.context.backend, reader.u32())
if user is None:
query.meta(ICQMeta.BasicInfo, ICQResult.Error)
return
viewer = query.context.user
listed = _listed(user, viewer)
parts = [
(ICQMeta.BasicInfo, basic_info_body(user, viewer)),
(ICQMeta.MoreInfo, more_info_body(user, viewer)),
(ICQMeta.ExtEmails, LE().u8(0).data),
(ICQMeta.HomepageCategory, LE().u8(0).u16(0).string('').u8(0).data),
(ICQMeta.WorkInfo, work_info_body(user, viewer)),
(ICQMeta.Notes, LE().string(icq.notes(user) if listed else '').data),
(ICQMeta.Interests, _pairs_body(icq.interests(user) if listed else []).data),
(ICQMeta.Affiliations, (
_pairs_body(icq.affiliations(user)['past'] if listed else []).data
+ _pairs_body(icq.affiliations(user)['current'] if listed else []).data
)),
]
for index, (subtype, body) in enumerate(parts):
query.meta(subtype, ICQResult.Ok, body, more = index < len(parts) - 1)
def meta_search_by_uin(query: ICQContext, reader: LEReader) -> None:
# finding someone by their exact number is how ICQ adds a contact, so it doesn't need a directory listing
user = _find(query.context.backend, reader.u32())
search_results(query, [user] if user is not None else [])
def meta_search_by_uin2(query: ICQContext, reader: LEReader) -> None:
uin = next((tlv_int(value) for tag, value in parse_le_tlvs(reader.rest()) if tag == ICQTag.Uin), 0)
user = _find(query.context.backend, uin) if uin else None
search_results(query, [user] if user is not None else [])
def meta_search_by_email(query: ICQContext, reader: LEReader) -> None:
email = reader.string()
search_results(query, _users(query.context.backend, query.context.backend.user_service.search_uuids(email = email)))
def meta_search_by_email3(query: ICQContext, reader: LEReader) -> None:
email = next((tlv_string(value) for tag, value in parse_le_tlvs(reader.rest()) if tag == ICQTag.Email), '')
search_results(query, _users(query.context.backend, query.context.backend.user_service.search_uuids(email = email)) if email else [])
def meta_search_by_details(query: ICQContext, reader: LEReader) -> None:
first, last, nick = reader.string(), reader.string(), reader.string()
uuids = query.context.backend.user_service.search_uuids(first_name = first, last_name = last, nickname = nick)
search_results(query, _users(query.context.backend, uuids))
def meta_search_white_pages(query: ICQContext, reader: LEReader) -> None:
# the fixed-layout white pages search: first, last, nick and e-mail lead it, the rest narrows (and isn't kept here)
first, last, nick, email = reader.string(), reader.string(), reader.string(), reader.string()
uuids = query.context.backend.user_service.search_uuids(email = email, first_name = first, last_name = last, nickname = nick)
search_results(query, _users(query.context.backend, uuids))
def meta_search_white_pages2(query: ICQContext, reader: LEReader) -> None:
criteria = {}
online_only = False
uin = 0
for tag, value in parse_le_tlvs(reader.rest()):
if tag == ICQTag.Uin:
uin = tlv_int(value)
elif tag == ICQTag.FirstName:
criteria['first_name'] = tlv_string(value)
elif tag == ICQTag.LastName:
criteria['last_name'] = tlv_string(value)
elif tag == ICQTag.Nickname:
criteria['nickname'] = tlv_string(value)
elif tag == ICQTag.Email:
criteria['email'] = tlv_string(value)
elif tag == ICQTag.OnlineOnly:
online_only = bool(tlv_int(value))
backend = query.context.backend
if uin:
user = _find(backend, uin)
users = [user] if user is not None else []
else:
users = _users(backend, backend.user_service.search_uuids(**{ k: v for k, v in criteria.items() if v }))
if online_only:
users = [user for user in users if _search_status(query, user) == DIR_STATUS_ONLINE]
search_results(query, users)
def _save(query: ICQContext) -> None:
icq.save(query.context.backend, query.context.user)
def meta_set_basic_info(query: ICQContext, reader: LEReader) -> None:
fields = { field: reader.string() for field in ('nick', 'first', 'last', 'email', 'city', 'state', 'phone', 'fax', 'address', 'cell', 'zip') }
fields['country'] = reader.u16()
fields['gmt'] = reader.u8()
# publish e-mail: 0 yes, 1 no
fields['publish_email'] = reader.u8() == 0 if reader.remaining() else False
_set_nickname(query, fields['nick'])
icq.set_basic(query.context.user, fields)
_save(query)
query.meta(ICQMeta.SetBasicInfoAck, ICQResult.Ok)
def _set_nickname(query: ICQContext, nick: str) -> None:
# the ICQ nickname is what other people see this account as, which elsewhere is its friendly name
if nick and nick != query.context.user.status.name:
query.context.bs.me_update({ 'name': nick })
def meta_set_work_info(query: ICQContext, reader: LEReader) -> None:
fields: dict[str, Any] = { field: reader.string() for field in ('city', 'state', 'phone', 'fax', 'address', 'zip') }
fields['country'] = reader.u16()
for field in ('company', 'department', 'position'):
fields[field] = reader.string()
fields['occupation'] = reader.u16()
fields['webpage'] = reader.string()
icq.set_work(query.context.user, fields)
_save(query)
query.meta(ICQMeta.SetWorkInfoAck, ICQResult.Ok)
def meta_set_more_info(query: ICQContext, reader: LEReader) -> None:
# u8 age (worked out from the birth date instead), u16 gender, homepage, u16 year, u8 month, u8 day, three languages
reader.u8()
fields = { 'gender': reader.u16() & 0xFF, 'homepage': reader.string(), 'birth_year': reader.u16(), 'birth_month': reader.u8() }
fields['birth_day'] = reader.u8()
for lang in ('lang1', 'lang2', 'lang3'):
fields[lang] = reader.u8() if reader.remaining() else 0
icq.set_more(query.context.user, fields)
_save(query)
query.meta(ICQMeta.SetMoreInfoAck, ICQResult.Ok)
def meta_set_notes(query: ICQContext, reader: LEReader) -> None:
icq.set_notes(query.context.user, reader.string())
_save(query)
query.meta(ICQMeta.SetNotesAck, ICQResult.Ok)
def meta_set_emails(query: ICQContext, reader: LEReader) -> None:
# extra e-mail addresses aren't kept, but the client needs its answer
query.meta(ICQMeta.SetEmailsAck, ICQResult.Ok)
def _read_pairs(reader: LEReader) -> list[list[Any]]:
count = reader.u8()
return [[reader.u16(), reader.string()] for _ in range(count)]
def meta_set_interests(query: ICQContext, reader: LEReader) -> None:
icq.set_interests(query.context.user, _read_pairs(reader))
_save(query)
query.meta(ICQMeta.SetInterestsAck, ICQResult.Ok)
def meta_set_affiliations(query: ICQContext, reader: LEReader) -> None:
past = _read_pairs(reader)
current = _read_pairs(reader)
icq.set_affiliations(query.context.user, past, current)
_save(query)
query.meta(ICQMeta.SetAffiliationsAck, ICQResult.Ok)
def meta_set_permissions(query: ICQContext, reader: LEReader) -> None:
# u8 authorization (0: required, 1: anyone may add), u8 web aware, u8 direct connection permissions, u8 unknown
authorization = reader.u8()
web_aware = reader.u8() if reader.remaining() else 0
icq.set_permissions(query.context.user, auth_required = authorization == 0, web_aware = web_aware == 1)
_save(query)
query.meta(ICQMeta.SetPermissionsAck, ICQResult.Ok)
def meta_set_icq_phone(query: ICQContext, reader: LEReader) -> None:
query.meta(ICQMeta.SetIcqPhoneAck, ICQResult.Ok)
def meta_set_full_info(query: ICQContext, reader: LEReader) -> None:
# ICQ Lite's all-in-one update: only the fields it sends change
basic: dict[str, Any] = {}
more: dict[str, Any] = {}
work: dict[str, Any] = {}
user = query.context.user
strings = {
ICQTag.FirstName: (basic, 'first'), ICQTag.LastName: (basic, 'last'), ICQTag.Nickname: (basic, 'nick'),
ICQTag.HomeCity: (basic, 'city'), ICQTag.HomeState: (basic, 'state'), ICQTag.HomeAddress: (basic, 'address'),
ICQTag.HomePhone: (basic, 'phone'), ICQTag.HomeFax: (basic, 'fax'), ICQTag.HomeCell: (basic, 'cell'),
ICQTag.HomepageUrl: (more, 'homepage'), ICQTag.WorkCompany: (work, 'company'), ICQTag.WorkDepartment: (work, 'department'),
ICQTag.WorkPosition: (work, 'position'), ICQTag.WorkAddress: (work, 'address'), ICQTag.WorkCity: (work, 'city'),
ICQTag.WorkState: (work, 'state'), ICQTag.WorkPhone: (work, 'phone'), ICQTag.WorkFax: (work, 'fax'),
ICQTag.WorkWebpage: (work, 'webpage'),
}
for tag, value in parse_le_tlvs(reader.rest()):
if tag in strings:
section, field = strings[tag]
section[field] = tlv_string(value)
elif tag == ICQTag.Email and len(value) >= 2:
basic['email'] = tlv_string(value)
elif tag == ICQTag.HomeCountry:
basic['country'] = tlv_int(value) & 0xFFFF
elif tag == ICQTag.WorkCountry:
work['country'] = tlv_int(value) & 0xFFFF
elif tag == ICQTag.HomeZip:
basic['zip'] = str(tlv_int(value))
elif tag == ICQTag.WorkZip:
work['zip'] = str(tlv_int(value))
elif tag == ICQTag.WorkOccupation:
work['occupation'] = tlv_int(value) & 0xFFFF
elif tag == ICQTag.GmtOffset and value:
basic['gmt'] = value[0]
elif tag == ICQTag.Gender and value:
more['gender'] = value[0]
elif tag == ICQTag.Birthday and len(value) >= 6:
# u16 year, u16 month, u16 day
more['birth_year'], more['birth_month'], more['birth_day'] = struct.unpack('<HHH', value[:6])
elif tag == ICQTag.Notes:
icq.set_notes(user, tlv_string(value))
elif tag == ICQTag.Authorization and value:
icq.set_permissions(user, auth_required = value[0] == 0)
elif tag == ICQTag.WebAware and value:
icq.set_permissions(user, web_aware = value[0] == 1)
if 'nick' in basic:
_set_nickname(query, basic['nick'])
icq.set_basic(user, basic)
icq.set_more(user, more)
icq.set_work(user, work)
_save(query)
query.meta(ICQMeta.SetFullInfoAck, ICQResult.Ok)
def meta_xml_request(query: ICQContext, reader: LEReader) -> None:
# server-side XML data (Beacon"what's new" and such) isn't something there is any of
query.meta(ICQMeta.XmlReply, ICQResult.Error)
def meta_directory_query(query: ICQContext, reader: LEReader) -> None:
# ICQ 6's directory protocol, a SNAC of its own (family 0x05B9) inside the request; it gets the empty answer Open
# OSCAR Server sends for what it doesn't handle: the request's subtype, result 0, nothing found
payload = reader.rest()
if len(payload) < 2 + 10:
return
body = payload[2:]
subtype, flags = struct.unpack('>HH', body[2:6])
versioned = bool(flags & 0x8000)
nested = struct.pack('>HHHHH', 0x05B9, subtype, 0x8000 if versioned else 0x0000, 0, 0)
if versioned:
# the version block the request came with, mirrored: TLV 0x01 = 2
version = TLV(0x0001, struct.pack('>H', 0x0002)).marshal()
nested += struct.pack('>H', len(version)) + version
# u8 result, string16 error message, 10 bytes nothing, [6 more], u32 total, [u16 pages], u16 block count
nested += struct.pack('>BH', 0, 0) + bytes(10)
if versioned:
nested += bytes(6)
nested += struct.pack('>L', 0)
if versioned:
nested += struct.pack('>H', 0)
nested += struct.pack('>H', 0)
query.reply(ICQReply.Meta, LE().u16(ICQMeta.DirectoryResponse).u8(ICQResult.Ok).u16(len(nested)).raw(nested).data)
META_HANDLERS = {
ICQMeta.ShortInfo: meta_short_info,
ICQMeta.FullInfo: meta_full_info,
ICQMeta.FullInfo2: meta_full_info,
ICQMeta.SearchByUin: meta_search_by_uin,
ICQMeta.SearchByUin2: meta_search_by_uin2,
ICQMeta.SearchByEmail: meta_search_by_email,
ICQMeta.SearchByEmail3: meta_search_by_email3,
ICQMeta.SearchByDetails: meta_search_by_details,
ICQMeta.SearchWhitePages: meta_search_white_pages,
ICQMeta.SearchWhitePages2: meta_search_white_pages2,
ICQMeta.SetBasicInfo: meta_set_basic_info,
ICQMeta.SetWorkInfo: meta_set_work_info,
ICQMeta.SetMoreInfo: meta_set_more_info,
ICQMeta.SetNotes: meta_set_notes,
ICQMeta.SetEmails: meta_set_emails,
ICQMeta.SetInterests: meta_set_interests,
ICQMeta.SetAffiliations: meta_set_affiliations,
ICQMeta.SetPermissions: meta_set_permissions,
ICQMeta.SetIcqPhone: meta_set_icq_phone,
ICQMeta.SetFullInfo: meta_set_full_info,
ICQMeta.XmlRequest: meta_xml_request,
ICQMeta.DirectoryQuery: meta_directory_query,
}
-335
View File
@@ -1,335 +0,0 @@
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,
}
-275
View File
@@ -1,275 +0,0 @@
import struct
from enum import IntEnum
from util import icq
class Version(IntEnum):
V1 = 0x0001
V2 = 0x0002
V3 = 0x0003
V4 = 0x0004
V5 = 0x0005
class Command(IntEnum):
# what clients send (CMD_*)
Ack = 0x000A
ThruServer = 0x010E
Reconnect = 0x015E
Login = 0x03E8
GetDeps = 0x03F2
RegNewUser = 0x03FC
ContactList = 0x0406
SearchUin = 0x041A
SearchUser = 0x0424
KeepAlive = 0x042E
Logoff = 0x0438
SysMsgDoneAck = 0x0442
SysMsgReq = 0x044C
Authorize = 0x0456
InfoReq = 0x0460
ExtInfoReq = 0x046A
SetPassword = 0x049C
UpdateBasic = 0x04A6
UpdateDetail = 0x04B0
GetExternals = 0x04C4
SetStatus = 0x04D8
FirstLogin = 0x04EC
SetBasicInfo = 0x050A
SetAuth = 0x0514
KeepAlive2 = 0x051E
UserAdd = 0x053C
SetWorkInfo = 0x0578
SetHomeInfo = 0x0582
SetHomeWeb = 0x058C
SetNotes = 0x0596
GetNotes = 0x05AA
SetWorkWeb = 0x05BE
SearchStart = 0x05C8
RegRequestInfo = 0x05DC
RegNewUserInfo = 0x05E6
GetDeps1 = 0x05F0
UserGetInfo = 0x05FA
MetaUser = 0x064A
InvisibleList = 0x06A4
VisibleList = 0x06AE
ChangeVILists = 0x06B8
class Server(IntEnum):
# what the server sends (SRV_*)
Ack = 0x000A
SetOffline = 0x0028
DepsList = 0x0032
Hello = 0x005A
WrongPassword = 0x0064
UserOnline = 0x006E
UserOffline = 0x0078
SearchFound = 0x008C
SearchDone = 0x00A0
UpdatedBasic = 0x00B4
UpdateBasicFail = 0x00BE
UpdatedDetail = 0x00C8
UpdateDetailFail = 0x00D2
SysMsgOffline = 0x00DC
SysMsgDone = 0x00E6
NotConnected = 0x00F0
Busy = 0x00FA
SysMsgOnline = 0x0104
InfoReply = 0x0118
ExtInfoReply = 0x0122
InvalidUin = 0x012C
UserStatus = 0x01A4
UpdatedBasicV4 = 0x01E0
UpdateBasicFailV4 = 0x01EA
UserListDone = 0x021C
MetaUser = 0x03DE
class Meta(IntEnum):
# META_USER (0x064A) requests: the u16 that leads the data
SetBasic = 0x03E8
SetBasic2 = 0x03E9
SetWork = 0x03F2
SetWork2 = 0x03F3
SetMore = 0x03FC
SetMore2 = 0x03FD
SetAbout = 0x0406
SetInterests = 0x0410
SetAffiliations = 0x041A
SetSecurity = 0x0424
SetPassword = 0x042E
SetHomepageCategory = 0x0442
FullInfo = 0x04B0
FullInfo2 = 0x04B1
ShortInfo = 0x04BA
Unregister = 0x04C4
LoginInfo = 0x04CE
LoginInfo2 = 0x04CF
SearchName = 0x0514
SearchName2 = 0x0515
SearchUin = 0x051E
SearchUin2 = 0x051F
SearchEmail = 0x0528
SearchEmail2 = 0x0529
SearchWhite = 0x0532
SearchWhite2 = 0x0533
UsageStats = 0x06B8
Login = 0x07D0
class MetaReply(IntEnum):
# SRV_META_USER (0x03DE) replies: the u16 that leads the data, then a u8 result
SetBasicAck = 0x0064
SetWorkAck = 0x006E
SetMoreAck = 0x0078
SetAboutAck = 0x0082
SetInterestsAck = 0x008C
SetAffiliationsAck = 0x0096
SetSecurityAck = 0x00A0
SetPasswordAck = 0x00AA
UnregisterAck = 0x00B4
SetHomepageCategoryAck = 0x00BE
BasicInfo = 0x00C8
WorkInfo = 0x00D2
MoreInfo = 0x00DC
About = 0x00E6
Interests = 0x00F0
Affiliations = 0x00FA
ShortInfo = 0x0104
HomepageCategory = 0x010E
UserFound = 0x0190
LastUserFound = 0x019A
WhiteFound = 0x01A4
WhiteLastFound = 0x01AE
class MetaResult(IntEnum):
Ok = 0x0A
Fail = 0x32
class MessageType(IntEnum):
# the low byte of a message's type
Text = 0x01
Chat = 0x02
File = 0x03
Url = 0x04
AuthRequest = 0x06
AuthDeny = 0x07
AuthGrant = 0x08
Server = 0x09
Added = 0x0C
WebPager = 0x0D
EmailPager = 0x0E
Contacts = 0x13
Plugin = 0x1A
AutoAway = 0xE8
AutoOccupied = 0xE9
AutoNotAvailable = 0xEA
AutoDnd = 0xEB
AutoFreeForChat = 0xEC
# what the client's fixed-size buffers take
MAX_NICK = 20
MAX_NAME = 64
MAX_PHONE = 30
MAX_HOMEPAGE = 127
MAX_ABOUT = 450
# the longest password a client sends; the rest of the packet isn't trusted past it
MAX_PASSWORD = 20
class LE:
# a little-endian writer, the only byte order the pre-OSCAR protocol has
__slots__ = ('data',)
data: bytearray
def __init__(self) -> None:
self.data = bytearray()
def u8(self, value: int) -> 'LE':
self.data += struct.pack('<B', value & 0xFF)
return self
def u16(self, value: int) -> 'LE':
self.data += struct.pack('<H', value & 0xFFFF)
return self
def u32(self, value: int) -> 'LE':
self.data += struct.pack('<L', value & 0xFFFFFFFF)
return self
def raw(self, value: bytes) -> 'LE':
self.data += value
return self
def string(self, value: str, limit: int = 0) -> 'LE':
# u16 length counting the NUL, the text, the NUL; an empty string is still a length of 1 and its NUL
encoded = icq.latin1(value)
if limit:
encoded = encoded[:limit]
return self.u16(len(encoded) + 1).raw(encoded).u8(0)
def bytes(self) -> bytes:
return bytes(self.data)
class Reader:
__slots__ = ('data', 'pos')
data: bytes
pos: int
def __init__(self, data: bytes) -> None:
self.data = data
self.pos = 0
def remaining(self) -> int:
return len(self.data) - self.pos
def take(self, length: int) -> bytes:
if length < 0 or self.pos + length > len(self.data):
raise ValueError('truncated ICQ packet')
chunk = self.data[self.pos:self.pos + length]
self.pos += length
return chunk
def skip(self, length: int) -> None:
self.take(length)
def u8(self) -> int:
return self.take(1)[0]
def u16(self) -> int:
return struct.unpack('<H', self.take(2))[0]
def u32(self) -> int:
return struct.unpack('<L', self.take(4))[0]
def raw_string(self, limit: int = 0) -> bytes:
# u16 length, then that many bytes ending in a NUL; a client's own length is trusted only up to `limit`
length = self.u16()
if limit and length > limit + 1:
raw = self.take(length)[:limit]
else:
raw = self.take(length)
if b'\x00' in raw:
raw = raw[:raw.index(b'\x00')]
return raw
def string(self) -> str:
return icq.from_latin1(self.raw_string())
def rest(self) -> bytes:
chunk = self.data[self.pos:]
self.pos = len(self.data)
return chunk
def uin_list(data: bytes) -> list[int]:
# u8 count, then that many u32 UINs (contact, visible and invisible lists); a short packet ends the list early
reader = Reader(data)
uins = []
try:
count = reader.u8()
for _ in range(count):
uins.append(reader.u32())
except ValueError:
pass
return uins
-91
View File
@@ -1,91 +0,0 @@
import struct
from .crypt import add_v5_server_checkcode, decrypt_v4, decrypt_v5, v3_header_checkcode
from .packets import Command, Version
class Header:
# what every version's client packet header comes down to (the fields a version doesn't have stay 0)
__slots__ = ('version', 'command', 'seq1', 'seq2', 'uin', 'session_id')
version: int
command: int
seq1: int
seq2: int
uin: int
session_id: int
def __init__(self, version: int, command: int, seq1: int, seq2: int, uin: int, session_id: int = 0) -> None:
self.version = version
self.command = command
self.seq1 = seq1
self.seq2 = seq2
self.uin = uin
self.session_id = session_id
def __repr__(self) -> str:
return '<V{} cmd 0x{:04X} seq {}/{} uin {}>'.format(self.version, self.command, self.seq1, self.seq2, self.uin)
def version_of(packet: bytes) -> int | None:
if len(packet) < 2:
return None
return struct.unpack_from('<H', packet)[0]
def parse(packet: bytes) -> tuple[Header, bytes] | None:
# client packet -> (header, data); None for anything too short to be one
version = version_of(packet)
if version == Version.V5:
# u16 version, u32 zero, u32 UIN, then (encrypted) u32 session ID, u16 command, u16 seq1, u16 seq2, u32 checkcode
if len(packet) < 24:
return None
plain = decrypt_v5(packet)
uin, session_id, command, seq1, seq2 = struct.unpack_from('<LLHHH', plain, 6)
return Header(version, command, seq1, seq2, uin, session_id), plain[24:]
if version == Version.V4:
# u16 version, u16 random, then (a quarter of it encrypted) u16 zero, u16 command, u16 seq1, u16 seq2, u32 UIN,
# u32 checkcode
if len(packet) < 20:
return None
plain = decrypt_v4(packet)
command, seq1, seq2, uin = struct.unpack_from('<HHHL', plain, 6)
return Header(version, command, seq1, seq2, uin), plain[20:]
if version == Version.V3:
# u16 version, u16 command, u16 seq1, u16 seq2, u32 UIN, u32 checkcode
if len(packet) < 16:
return None
command, seq1, seq2, uin = struct.unpack_from('<HHHL', packet, 2)
return Header(version, command, seq1, seq2, uin), packet[16:]
if version in (Version.V1, Version.V2):
# u16 version, u16 command, u16 seq, u32 UIN; the commands sent before there's a UIN to put in it leave it out
if len(packet) < 6:
return None
command, seq = struct.unpack_from('<HH', packet, 2)
if command in (Command.FirstLogin, Command.RegNewUser):
return Header(version, command, seq, 0, 0), packet[6:]
if command == Command.GetDeps and version == Version.V2:
# a V2 client sends its pre-login check with a V3 layout: u16 seq1, u16 seq2, u32 UIN
if len(packet) < 12:
return None
seq1, seq2, uin = struct.unpack_from('<HHL', packet, 4)
return Header(version, command, seq1, seq2, uin), packet[12:]
if len(packet) < 10:
return Header(version, command, seq, 0, 0), packet[6:]
uin = struct.unpack_from('<L', packet, 6)[0]
return Header(version, command, seq, 0, uin), packet[10:]
return None
def build(version: int, command: int, data: bytes = b'', *, seq1: int = 0, seq2: int = 0, uin: int = 0, session_id: int = 0) -> bytes:
# server packet for a client of `version`
if version == Version.V5:
# u16 version, u8 zero, u32 session ID, u16 command, u16 seq1, u16 seq2, u32 UIN, u32 checkcode; not encrypted
packet = bytearray(struct.pack('<HBLHHHL', Version.V5, 0, session_id, command, seq1 & 0xFFFF, seq2 & 0xFFFF, uin) + bytes(4) + data)
add_v5_server_checkcode(packet)
return bytes(packet)
if version in (Version.V3, Version.V4):
# V3 and V4 clients both get the V3 header (u16 version 3, u16 command, u16 seq1, u16 seq2, u32 UIN, u32), and a
# V4 client a checkcode in its last field
header = struct.pack('<HHHHL', Version.V3, command, seq1 & 0xFFFF, seq2 & 0xFFFF, uin)
check = v3_header_checkcode(header) if version == Version.V4 else 0
return header + struct.pack('<L', check) + data
# V1 and V2: u16 version, u16 command, u16 seq
return struct.pack('<HHH', version, command, seq1 & 0xFFFF) + data
+10 -7
View File
@@ -12,7 +12,6 @@ from core.models import (
) )
from core.backend import Backend, BackendSession, Chat, ChatSession from core.backend import Backend, BackendSession, Chat, ChatSession
from core.client import Client from core.client import Client
from core.alerts import Alert, irc_lines
class IRCCtrl: class IRCCtrl:
__slots__ = ( __slots__ = (
@@ -170,12 +169,18 @@ class IRCCtrl:
def _m_motd(self) -> None: def _m_motd(self) -> None:
self.send_numeric(RPL.MOTDStart, ": ----- CrossTalk (BETA) -----") self.send_numeric(RPL.MOTDStart, ": ----- CrossTalk (BETA) -----")
self.send_numeric(RPL.MOTD, ": - Welcome to CrossTalk! This frontend is undergoing a massive overhaul, so expect things to be iffy for now.") self.send_numeric(RPL.MOTD, ": - Welcome to CrossTalk! This frontend is undergoing a massive overhaul, so expect things to be iffy for now.")
self.send_numeric(RPL.MOTD, ": - We support MSNP, YMSG, and OSCAR as well.") self.send_numeric(RPL.MOTD, ": - We support MSNP, YMSG, and OSCAR as well, though as of right now, only MSNP and YMSG are in a usable state.")
self.send_numeric(RPL.MOTD, ": - Development is going at a faster pace, so this won't stay the case for long. Stay tuned!") self.send_numeric(RPL.MOTD, ": - Development is going at a faster pace, so this won't stay the case for long. Stay tuned!")
#if settings.PRIVACY_POLICY_UPDATE_NOTIF:
# self.send_numeric(RPL.MOTD, ": - NOTE: We have updated our Privacy Policy. Go here to take a look: https://crosstalk.im/ppolicy")
#if settings.TOS_UPDATE_NOTIF:
# self.send_numeric(RPL.MOTD, ": - NOTE: We have updated our Terms of Service. You must read and agree to these to continue using CrossTalk. Go here to take a look: https://crosstalk.im/tos")
#if settings.REROUTE_UPDATE_NOTIF:
# settings.send_numeric(RPL.MOTD, ": - NOTE for Yahoo! and MSN users: We have updated Reroute. Please download a new copy and replace your existing DLL with it. You can find that here: https://storage.ugnet.gay/crosstalk-dist/client/all/patching/reroute/reroute.dll")
self.send_numeric(RPL.MOTDEnd, ": - End of the MOTD.") self.send_numeric(RPL.MOTDEnd, ": - End of the MOTD.")
def _m_version(self) -> None: def _m_version(self) -> None:
self.send_numeric(RPL.Version, ": - AZUL (BETA) - IRC") self.send_numeric(RPL.Version, ": - Azul (BETA) - IRC Frontend")
def _m_quit(self, reason: Optional[str]) -> None: def _m_quit(self, reason: Optional[str]) -> None:
self.close() self.close()
@@ -242,10 +247,8 @@ class BackendEventHandler(event.BackendEventHandler):
def __init__(self, ctrl: IRCCtrl) -> None: def __init__(self, ctrl: IRCCtrl) -> None:
self.ctrl = ctrl self.ctrl = ctrl
def on_client_alert(self, alert: Alert) -> bool: def on_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None:
for line in irc_lines(alert.paragraphs) + ([alert.url] if alert.url else []): self.ctrl.send_reply('PRIVMSG', '$*', ':' + message, source = "System")
self.ctrl.send_reply('PRIVMSG', '$*', ':' + line, source = "System")
return True
def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None: def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None:
if args[1] is not None: if args[1] is not None:
+1 -1
View File
@@ -226,7 +226,7 @@ class MSIMCtrl:
'GroupID': id, 'GroupID': id,
'GroupName': group, 'GroupName': group,
'Position': id, 'Position': id,
'GroupFlag': 131073 # unclear what GroupFlag does, TODO: figure it out 'GroupFlag': 131073 # unclear what GroupFlag does, TODO(subpurple): figure it out
}) })
# self.send_persist_reply(cmd, dsn, lid, rid, msim_groups) # self.send_persist_reply(cmd, dsn, lid, rid, msim_groups)
+1 -1
View File
@@ -8,4 +8,4 @@ def register(app: web.Application) -> None:
async def handle_client_advert(request: web.Request) -> web.Response: async def handle_client_advert(request: web.Request) -> web.Response:
return web.HTTPFound(f'http://{settings.AD_HOST}y/ads/banner-sq') return web.HTTPFound(f'http://ctsvcs.advertising.ugnet.gay/ads/banner-sq')
+2 -6
View File
@@ -10,8 +10,8 @@ from .msnp import MSNPCtrl
def register(loop: asyncio.AbstractEventLoop, backend: Backend, http_app: web.Application) -> None: def register(loop: asyncio.AbstractEventLoop, backend: Backend, http_app: web.Application) -> None:
from util.misc import ProtocolRunner from util.misc import ProtocolRunner
from . import msnp_dp, msnp_ns, msnp_sb#, spotlife, turn from . import msnp_dp, msnp_ns, msnp_sb
from .http import appdirectory, abservice, gateway, other, schematizedstore, sharingservice from .http import appdirectory, abservice, gateway, other
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', 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')) backend.add_runner(ProtocolRunner('0.0.0.0', 1864, ListenerMSNP, args = ['MSNP Notification', backend, msnp_ns.MSNPCtrlNS], service = 'MSNP Notification'))
@@ -19,11 +19,7 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, http_app: web.Ap
appdirectory.register(http_app) appdirectory.register(http_app)
other.register(http_app) other.register(http_app)
abservice.register(http_app) abservice.register(http_app)
sharingservice.register(http_app)
schematizedstore.register(http_app)
gateway.register(loop, http_app) gateway.register(loop, http_app)
#spotlife.register(loop, backend, http_app)
#turn.register(loop, backend)
class ListenerMSNP(asyncio.Protocol): class ListenerMSNP(asyncio.Protocol):
logger: Logger logger: Logger
File diff suppressed because it is too large. Load diff
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Nine Men's Morris", "name": "Nine Men's Morris",
"description": "A 9 pieces Tic-Tac-Toe spin-off. Originally developed by Doron for games.mess.be", "description": "A 9 pieces Tic-Tac-Toe spin-off. Originally developed by Doron for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/morris/index.en-us.html", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/morris/index.en-us.html",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/morris/imgs/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/morris/imgs/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Nine Men's Morris", "name": "Nine Men's Morris",
"description": "A 9 pieces Tic-Tac-Toe spin-off (Hebrew). Originally developed by Doron for games.mess.be", "description": "A 9 pieces Tic-Tac-Toe spin-off (Hebrew). Originally developed by Doron for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/morris/index.he-il.html", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/morris/index.he-il.html",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/morris/imgs/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/morris/imgs/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Backgammon", "name": "Backgammon",
"description": "The game of luck and skill. Originally developed by Koen for games.mess.be", "description": "The game of luck and skill. Originally developed by Koen for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/backgammon/backgammon.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/backgammon/backgammon.htm",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/backgammon/images/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/backgammon/images/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Battleships", "name": "Battleships",
"description": "Sink your opponent's fleet. Originally developed by Koen for games.mess.be", "description": "Sink your opponent's fleet. Originally developed by Koen for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/battleships/battleships.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/battleships/battleships.htm",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/battleships/images/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/battleships/images/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Chess", "name": "Chess",
"description": "The king's game. Originally developed by Koen for games.mess.be", "description": "The king's game. Originally developed by Koen for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/chess/chess.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/chess/chess.htm",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/chess/images/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/chess/images/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Connect 4", "name": "Connect 4",
"description": "Four in a row. Originally developed by Koen for games.mess.be", "description": "Four in a row. Originally developed by Koen for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/connect4/connect4.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/connect4/connect4.htm",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/connect4/images/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/connect4/images/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Memory", "name": "Memory",
"description": "Find the matching pairs. Originally developed by Koen for games.mess.be", "description": "Find the matching pairs. Originally developed by Koen for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/memory/memory.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/memory/memory.htm",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/memory/images/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/memory/images/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Reversi", "name": "Reversi",
"description": "Also known as Othello. Originally developed by Koen for games.mess.be", "description": "Also known as Othello. Originally developed by Koen for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/reversi/reversi.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/reversi/reversi.htm",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/reversi/images/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/reversi/images/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Tetris", "name": "Tetris",
"description": "The simple, highly addictive, real-time puzzle game. Originally developed by Koen for games.mess.be", "description": "The simple, highly addictive, real-time puzzle game. Originally developed by Koen for games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/tetris/tetris.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/tetris/tetris.htm",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/tetris/images/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/tetris/images/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,8 +5,8 @@
"category_id": 102, "category_id": 102,
"name": "Yahtzee", "name": "Yahtzee",
"description": "The famous dice game. Originally developed by Koen of games.mess.be", "description": "The famous dice game. Originally developed by Koen of games.mess.be",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/yahtzee/yahtzee.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/yahtzee/yahtzee.htm",
"icon_url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/messbe/yahtzee/images/icon.png", "icon_url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/messbe/yahtzee/images/icon.png",
"type": "dir", "type": "dir",
"height": 500, "height": 500,
"width": 500, "width": 500,
@@ -5,7 +5,7 @@
"category_id": 101, "category_id": 101,
"name": "Tic Tac Toe", "name": "Tic Tac Toe",
"description": "Play against your friends in a game of Tic Tac Toe. Originally developed by Microsoft.", "description": "Play against your friends in a game of Tic Tac Toe. Originally developed by Microsoft.",
"url": "http://mactivities.msgrsvcs.ctsrv.xyz/static/app-data/tic-tac-toe/tictactoe.htm", "url": "http://mactivities.msgrsvcs.ctsrv.gay/static/app-data/tic-tac-toe/tictactoe.htm",
"icon_url": null, "icon_url": null,
"type": "dir", "type": "dir",
"height": 500, "height": 500,
+330 -324
View File
@@ -1,4 +1,4 @@
from typing import Optional, Any, Tuple, Literal, List, Dict from typing import Optional, Any, Tuple
from datetime import datetime, timedelta from datetime import datetime, timedelta
from io import BytesIO from io import BytesIO
from email.parser import Parser from email.parser import Parser
@@ -6,23 +6,20 @@ from email.header import decode_header
from email.utils import parsedate_to_datetime from email.utils import parsedate_to_datetime
from urllib.parse import unquote, parse_qsl from urllib.parse import unquote, parse_qsl
from pathlib import Path from pathlib import Path
import asyncio, re, secrets, base64, random, json, mimetypes, uuid, PyRSS2Gen, settings, util.misc import re, secrets, base64, random, json, mimetypes, uuid, PyRSS2Gen, settings, util.misc
from markupsafe import Markup from markupsafe import Markup
from aiohttp import web from aiohttp import web
from core import models from core import models
from core.user import beacon_enabled
from core.backend import Backend, BackendSession from core.backend import Backend, BackendSession
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
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 from .util import find_element, get_tag_localname, render, preprocess_soap, unknown_soap, bool_to_str
LOGIN_PATH = '/login2.srf' LOGIN_PATH = '/login.srf'
TMPL_DIR = 'front/msn/http/tmpl' TMPL_DIR = 'front/msn/http/tmpl'
ETC_DIR = 'front/msn/etc' ETC_DIR = 'front/msn/etc'
PP = 'Passport1.4' PP = 'Passport1.4'
PHOTO_MAX_SIZE = 10 * 1024 * 1024
def register(app: web.Application) -> None: def register(app: web.Application) -> None:
util.misc.add_to_jinja_env(app, 'msn', TMPL_DIR, globals = { util.misc.add_to_jinja_env(app, 'msn', TMPL_DIR, globals = {
'date_format': util.misc.date_format, 'date_format': util.misc.date_format,
@@ -31,7 +28,6 @@ def register(app: web.Application) -> None:
'bool_to_str': bool_to_str, 'bool_to_str': bool_to_str,
'contact_is_favorite': _contact_is_favorite, 'contact_is_favorite': _contact_is_favorite,
'datetime': datetime, 'datetime': datetime,
'settings': settings
}) })
# MSN >= 5 # MSN >= 5
@@ -60,74 +56,253 @@ def register(app: web.Application) -> None:
app.router.add_post('/RST2.srf', lambda req: handle_rst(req, rst2 = True)) app.router.add_post('/RST2.srf', lambda req: handle_rst(req, rst2 = True))
# MSN >= 8 # MSN >= 8
app.router.add_post('/storageservice/SchematizedStore.asmx', handle_storageservice)
app.router.add_post('/ppsecure/sha1auth.srf', handle_sha1auth) app.router.add_post('/ppsecure/sha1auth.srf', handle_sha1auth)
app.router.add_post('/rsi/rsi.asmx', handle_rsi) app.router.add_post('/rsi/rsi.asmx', handle_rsi)
app.router.add_post('/OimWS/oim.asmx', handle_oim) app.router.add_post('/OimWS/oim.asmx', handle_oim)
app.router.add_get('/svcs/msn-video-feeds/', handle_videofeed) app.router.add_get('/svcs/msn-video-feeds/', handle_videofeed) # adding an ending back-slash is required, or else it 404s. ????
app.router.add_get('/svcs/feed', lambda req: handle_videofeed(req, get_videos = True)) app.router.add_get('/svcs/feed', lambda req: handle_videofeed(req, get_videos = True))
# MSN >= 14 # MSN >= 14
app.router.add_post('/whatsnew/whatsnewservice.asmx', handle_whatsnew) app.router.add_post('/whatsnew/whatsnewservice.asmx', handle_whatsnew)
app.router.add_get('/svcs/tab={id}', handle_tabs_newer) app.router.add_get('/svcs/tab={id}', handle_tabs_newer)
# MSN >= 15 # MSN >= 15
app.router.add_post('/sqm/messenger/sqmserver.dll', handle_blankok) app.router.add_post('/sqm/messenger/sqmserver.dll', handle_blankok)
app.router.add_post('/sqm/WindowsLive/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_post('/uploaddata.aspx', handle_blankok)
app.router.add_get('/ppcrlcheck.srf', handle_ppcrlcheck) app.router.add_get('/ppcrlcheck.srf', handle_ppcrlcheck)
app.router.add_post('/profile/profile.asmx', handle_profile) app.router.add_post('/profile/profile.asmx', handle_blankok) # TODO: do the thing
app.router.add_get(r'/~Live.ConfigServer/{junk:.*}/~op-GetClientConfig/{tail:.*}', handle_msgrconfig16) 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.SuiteUpdate/{tail:.*}', handle_suiteupdate)
app.router.add_get(r'/~Live.ConfigServer.PSA/{tail:.*}', handle_socialint) app.router.add_get(r'/~Live.ConfigServer.PSA/{tail:.*}', handle_socialint)
app.router.add_get('/svcs/GameBrowser', handle_gamebrowser) 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 # Misc
app.router.add_get('/{i}meen_{locale}/{id}', handle_msn_redirect) app.router.add_get('/{i}meen_{locale}/{id}', handle_msn_redirect)
async def handle_blankok(req: web.Request) -> web.Response: async def handle_blankok(req: web.Request) -> web.Response:
return web.Response(status = 200) return web.Response(status = 200)
async def handle_profile(req: web.Request) -> web.Response:
backend = req.app['backend']
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()
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) action_str = get_tag_localname(action)
now_str = util.misc.date_format(datetime.utcnow()) now_str = util.misc.date_format(datetime.utcnow())
user = bs.user
cachekey = secrets.token_urlsafe(172) 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
storage_path = _get_storage_path(user.uuid)
files = None
if storage_path.exists() and storage_path.is_dir():
files = [x for x in storage_path.iterdir() if '_thumb' not in x.stem]
mime = None
image_size = 0
image_thumb_size = 0
if files:
ext = files[0].suffix
mime = ext[1:]
image_path = storage_path / '{}{}'.format(user.uuid, ext)
image_thumb_path = storage_path / '{}_thumb{}'.format(user.uuid, ext)
if image_path.exists():
image_size = image_path.stat().st_size
if image_thumb_path.exists():
image_thumb_size = image_thumb_path.stat().st_size
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()] } return render(req, 'msn:storageservice/GetProfileResponse.xml', {
if action_str == 'Get': 'storage_ns': storage_ns,
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]
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()
return render(req, 'msn:profile/ProfileResponse.xml', {
'action': action_str,
'profiles': profiles,
'cachekey': cachekey, 'cachekey': cachekey,
'cid': cid,
'pptoken1': token, 'pptoken1': token,
'user': user,
'now': now_str, 'now': now_str,
'mime': mime,
'size_static': image_size,
'size_small': image_thumb_size,
'roaming_info': roaming_info,
'host': settings.USERSTORAGE_HOST, '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
# ```
# <UpdateProfile xmlns="http://www.msn.com/webservices/storage/w10">
# <profile>
# <ResourceID>862d987eb60b7a63!106</ResourceID>
# <ExpressionProfile>
# <FreeText>Update</FreeText>
# <DisplayName>Society is betrayal</DisplayName>
# <PersonalStatus>Prosperity is the best medicine. :)</PersonalStatus>
# </ExpressionProfile>
# </profile>
# </UpdateProfile>
# ```
# Remove roaming message
# ```
# <UpdateProfile xmlns="http://www.msn.com/webservices/storage/w10">
# <profile>
# <ResourceID>bb4542ce2eacdbde!106</ResourceID>
# <ExpressionProfile>
# <FreeText>Update</FreeText>
# <DisplayName>%walkingphas3r%</DisplayName>
# <Flags>0</Flags>
# </ExpressionProfile>
# </profile>
# <profileAttributesToDelete>
# <ExpressionProfileAttributes>
# <PersonalStatus>true</PersonalStatus>
# </ExpressionProfileAttributes>
# </profileAttributesToDelete>
# </UpdateProfile>
# ```
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'):
return handle_document(req, action, ('Update' if action_str == 'UpdateDocument' else 'Create'), storage_ns, user, cid, token)
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) return unknown_soap(req, header, action)
def handle_document(req: web.Request, action: Any, type: str, storage_ns: str, user: models.User, cid: str, token: str) -> web.Response:
from PIL import Image
# get image data
#name = find_element(action, 'Name')
streamtype = find_element(action, 'DocumentStreamType')
if streamtype == 'UserTileStatic':
mime = find_element(action, 'MimeType')
#mime = None
data = find_element(action, 'Data')
data = base64.b64decode(data)
# WLM sends either `png` or `image/png` as the MIME type no matter what type of file is sent over. Guess image type from header
# TODO: BMPs
if data[:6] in (b'GIF87a',b'GIF89a'):
mime = 'gif'
elif data[:2] == b'\xff\xd8':
mime = 'jpeg'
elif data[:8] == b'\x89PNG\x0d\x0a\x1a\x0a':
mime = 'png'
if mime is not None:
try:
image = Image.open(BytesIO(data))
except:
return web.HTTPInternalServerError(text = '')
# store display picture as file
path = _get_storage_path(user.uuid)
path.mkdir(exist_ok = True, parents = True)
for old_file in path.glob(f'{user.uuid}.*'):
if old_file.is_file():
old_file.unlink()
for old_thumb in path.glob(f'{user.uuid}_thumb.*'):
if old_thumb.is_file():
old_thumb.unlink()
image_path = path / '{uuid}.{mime}'.format(uuid = user.uuid, mime = mime)
image_path.write_bytes(data)
thumb = image.resize((21, 21))
thumb_path = path / '{uuid}_thumb.png'.format(uuid = user.uuid)
thumb.save(str(thumb_path))
return render(req, 'msn:storageservice/{}DocumentResponse.xml'.format(type), {
'storage_ns': storage_ns,
'cid': cid,
'pptoken1': token,
'user': user,
})
async def handle_sha1auth(req: web.Request) -> web.Response: async def handle_sha1auth(req: web.Request) -> web.Response:
# We have no use for any of the actual tokens sent here right now (this is primarily for WLM 8's MSN Today function),
# so just redirect to the URL specified by `ru`
post = await req.post() post = await req.post()
token_data = post.get('token') token_data = post.get('token')
@@ -139,11 +314,11 @@ async def handle_sha1auth(req: web.Request) -> web.Response:
return web.HTTPInternalServerError() return web.HTTPInternalServerError()
return web.HTTPFound(token_fields['ru']) return web.HTTPFound(token_fields['ru'])
async def handle_ppcrlcheck(req: web.Request) -> web.Response: async def handle_ppcrlcheck(req: web.Request) -> web.Response:
response = '<config>\r\n\t<deviceid minversion="16.000.26889.00"/>\r\n\t<mobilecfg minversion="16.000.26208.0"/>\r\n</config>' response = '<config>\r\n\t<deviceid minversion="16.000.26889.00"/>\r\n\t<mobilecfg minversion="16.000.26208.0"/>\r\n</config>'
return web.HTTPOk(body=response) return web.HTTPOk(body=response)
async def handle_rsi(req: web.Request) -> web.Response: async def handle_rsi(req: web.Request) -> web.Response:
_, action, bs, token = await preprocess_soap_rsi(req) _, action, bs, token = await preprocess_soap_rsi(req)
@@ -179,7 +354,7 @@ async def handle_rsi(req: web.Request) -> web.Response:
return render(req, 'msn:oim/DeleteMessagesResponse.xml') return render(req, 'msn:oim/DeleteMessagesResponse.xml')
return render(req, 'msn:Fault.doesnotexist.xml', { 'action': action_str }) return render(req, 'msn:Fault.doesnotexist.xml', { 'action': action_str })
async def handle_oim(req: web.Request) -> web.Response: async def handle_oim(req: web.Request) -> web.Response:
header, _, body_content, bs, _ = await preprocess_soap_oimws(req) header, _, body_content, bs, _ = await preprocess_soap_oimws(req)
soapaction = (req.headers.get('SOAPAction') or '') soapaction = (req.headers.get('SOAPAction') or '')
@@ -213,9 +388,7 @@ async def handle_oim(req: web.Request) -> web.Response:
recipient_uuid = backend.util_get_uuid_from_email(recipient) recipient_uuid = backend.util_get_uuid_from_email(recipient)
user_display_email = backend.util_get_display_email(user) if email != user.email or recipient_uuid is None or not _is_on_al(recipient_uuid, backend, user, detail):
alias_email = '{}@crosstalk.im'.format(user.username).lower()
if email.lower() not in (user.email.lower(), alias_email, user_display_email.lower()) or recipient_uuid is None or not _is_on_al(recipient_uuid, backend, user, detail):
return render(req, 'msn:oim/Fault.unavailable.xml', { return render(req, 'msn:oim/Fault.unavailable.xml', {
'owsns': owsns, 'owsns': owsns,
}, status = 500) }, status = 500)
@@ -306,20 +479,6 @@ async def handle_oim(req: web.Request) -> web.Response:
}, status = 500) }, status = 500)
oim_body_normal = oim_body.strip() oim_body_normal = oim_body.strip()
oim_body_normal = base64.b64decode(oim_body_normal).decode('utf-8') 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( backend.user_service.save_oim(
bs, recipient_uuid, oim_run_id, host, oim_body_normal, True, from_friendly = friendlyname_str, bs, recipient_uuid, oim_run_id, host, oim_body_normal, True, from_friendly = friendlyname_str,
@@ -334,8 +493,6 @@ async def handle_oim(req: web.Request) -> web.Response:
'seq': oim_msg_seq, 'seq': oim_msg_seq,
'owsns': owsns, 'owsns': owsns,
}) })
OIM_MAX_SIZE = 64 * 1024
def _is_on_al(uuid: str, backend: Backend, user: models.User, detail: models.UserDetail) -> bool: def _is_on_al(uuid: str, backend: Backend, user: models.User, detail: models.UserDetail) -> bool:
contact = detail.contacts.get(uuid) contact = detail.contacts.get(uuid)
@@ -354,7 +511,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: if ctc_me is not None and not ctc_me.lists & models.ContactList.BL:
return True return True
return False return False
async def preprocess_soap_rsi(req: web.Request) -> Tuple[Any, Any, Optional[BackendSession], str]: async def preprocess_soap_rsi(req: web.Request) -> Tuple[Any, Any, Optional[BackendSession], str]:
from lxml.objectify import fromstring as parse_xml from lxml.objectify import fromstring as parse_xml
@@ -376,7 +533,7 @@ async def preprocess_soap_rsi(req: web.Request) -> Tuple[Any, Any, Optional[Back
#if settings.DEBUG: print('Action: {}'.format(get_tag_localname(action))) #if settings.DEBUG: print('Action: {}'.format(get_tag_localname(action)))
return header, action, bs, token return header, action, bs, token
async def preprocess_soap_oimws(req: web.Request) -> Tuple[Any, str, str, Optional[BackendSession], str]: async def preprocess_soap_oimws(req: web.Request) -> Tuple[Any, str, str, Optional[BackendSession], str]:
from lxml.objectify import fromstring as parse_xml from lxml.objectify import fromstring as parse_xml
@@ -395,175 +552,28 @@ 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') body_content = str(find_element(root, 'Body/Content')).replace('\r\n', '\n')
return header, body_msgtype, body_content, bs, token return header, body_msgtype, body_content, bs, token
# TODO: Make this actually accurate
async def handle_whatsnew(req: web.Request) -> web.Response: async def handle_whatsnew(req: web.Request) -> web.Response:
backend: Backend = req.app['backend'] whatsnew = ''
header, action, bs, token = await preprocess_soap(req) with open('config/whatsnew.json', 'rb') as f:
user = _get_user_from_token(backend, bs, token) whatsnew_list = json.loads(f.read())
if user is None: f.close()
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'] if len(whatsnew_list) > 0:
user, bs = _get_live_api_user(req) whatsnew_dict = whatsnew_list[0]
cid = req.match_info['cid'] 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']
)
try: return web.HTTPOk(content_type = 'text/xml', text = whatsnew)
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 = (
'<?xml version="1.0" encoding="utf-8"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:live="http://api.live.com/schemas">'
f'<id>{req.url}</id><updated>{util.misc.date_format(datetime.utcnow())}</updated>'
f'<live:legacyPsm>{message_xml}</live:legacyPsm><title>{message_xml}</title>'
f'<author><name>{encode_xml_ne(user.status.name)}</name><live:cid>{cid}</live:cid></author></entry>'
))
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 = (
'<?xml version="1.0" encoding="utf-8"?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:live="http://api.live.com/schemas">'
f'<id>{entry_url}</id><title>{encode_xml_ne(title)}</title><summary>{encode_xml_ne(summary)}</summary>'
f'<published>{now_str}</published><updated>{now_str}</updated>'
f'<author><name>{encode_xml_ne(user.status.name or "")}</name><live:cid>{cid}</live:cid></author>'
f'<link rel="self" type="application/atom+xml" href="{entry_url}"/><link rel="edit" type="application/atom+xml" href="{entry_url}"/>'
f'<link rel="edit-media" type="{mime}" href="{media_url_xml}"/><link rel="alternate" type="{mime}" href="{media_url_xml}"/>'
f'<content type="{mime}" src="{media_url_xml}"/><live:type>photo</live:type></entry>'
))
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: async def handle_today(req: web.Request) -> web.Response:
return render(req, 'msn:svcs/MSNToday.html', { return render(req, 'msn:svcs/MSNToday.html', {
'title': "CrossTalk Today", 'title': "CrossTalk Today",
@@ -571,21 +581,21 @@ async def handle_today(req: web.Request) -> web.Response:
'wlm': req.query.get('wlm') or False, 'wlm': req.query.get('wlm') or False,
'windowslive': req.query.get('windowslive') or False 'windowslive': req.query.get('windowslive') or False
}) })
async def handle_gamebrowser(req: web.Request) -> web.Response: async def handle_gamebrowser(req: web.Request) -> web.Response:
return render(req, 'msn:svcs/GameBrowser.html', { return render(req, 'msn:svcs/GameBrowser.html', {
'title': "Game Browser | CrossTalk", 'title': "Game Browser | CrossTalk",
}) })
async def handle_portal(req: web.Request) -> web.Response: async def handle_portal(req: web.Request) -> web.Response:
return web.HTTPFound(f'http://{settings.TODAY_HOST}/start/msn') return web.HTTPFound(f'http://today.msgrsvcs.ctsrv.gay/start/msn')
async def handle_textadredir(req: web.Request) -> web.Response: async def handle_textadredir(req: web.Request) -> web.Response:
return web.HTTPFound(f'http://{settings.AD_HOST}/ads/txt') return web.HTTPFound(f'http://ctsvcs.advertising.ugnet.gay/ads/txt')
async def handle_banneradredir(req: web.Request) -> web.Response: async def handle_banneradredir(req: web.Request) -> web.Response:
return web.HTTPFound(f'http://{settings.AD_HOST}/ads/banner') return web.HTTPFound(f'http://ctsvcs.advertising.ugnet.gay/ads/banner')
async def handle_msn_redirect(req: web.Request) -> web.Response: async def handle_msn_redirect(req: web.Request) -> web.Response:
i = req.match_info['i'] i = req.match_info['i']
id = req.match_info['id'] id = req.match_info['id']
@@ -597,42 +607,42 @@ async def handle_msn_redirect(req: web.Request) -> web.Response:
return web.HTTPFound('/start') return web.HTTPFound('/start')
return web.HTTPFound('http://g.msn.com{}'.format(req.path_qs)) return web.HTTPFound('http://g.msn.com{}'.format(req.path_qs))
async def handle_msn5ads(req: web.Request) -> web.Response: async def handle_msn5ads(req: web.Request) -> web.Response:
response = '<?xml version="1.0"?><msn-data><RefreshLogin>False</RefreshLogin><RefreshInterval>10080</RefreshInterval></msn-data>' response = '<?xml version="1.0"?><msn-data><RefreshLogin>False</RefreshLogin><RefreshInterval>10080</RefreshInterval></msn-data>'
return web.HTTPOk(body=response) return web.HTTPOk(body=response)
async def handle_suiteupdate(req: web.Request) -> web.Response: async def handle_suiteupdate(req: web.Request) -> web.Response:
return render(req, 'msn:config/SuiteUpdate.xml') return render(req, 'msn:config/SuiteUpdate.xml')
async def handle_socialint(req: web.Request) -> web.Response: async def handle_socialint(req: web.Request) -> web.Response:
return render(req, 'msn:config/Config.PSA.xml') return render(req, 'msn:config/Config.PSA.xml')
async def handle_tabs(req: web.Request) -> web.Response: async def handle_tabs(req: web.Request) -> web.Response:
with open('config/tabs.json') as fh: with open('config/tabs.json') as fh:
tabs_data = json.load(fh) tabs_data = json.load(fh)
tmpl = req.app['jinja_env'].get_template('msn:svcs/svcs_tabs.xml') tmpl = req.app['jinja_env'].get_template('msn:svcs/svcs_tabs.xml')
tab_tmpl = tmpl.render(tabs=tabs_data) tab_tmpl = tmpl.render(tabs=tabs_data)
return web.HTTPOk(content_type='text/xml', text='<?xml version="1.0"?>\n' + tab_tmpl) return web.HTTPOk(content_type='text/xml', text='<?xml version="1.0"?>\n' + tab_tmpl)
# TODO: Unify the tabs handlers so spaghetti code isn't a problem # TODO: Unify the tabs handlers so spaghetti code isn't a problem
async def handle_tabs_newer(req: web.Request) -> web.Response: async def handle_tabs_newer(req: web.Request) -> web.Response:
id = int(req.match_info['id']) id = int(req.match_info['id'])
with open('config/tabs.json') as fh: with open('config/tabs.json') as fh:
tabs_data = json.load(fh) tabs_data = json.load(fh)
tab_data = next((tab for tab in tabs_data if tab["id"] == id), None) tab_data = next((tab for tab in tabs_data if tab["id"] == id), None)
if not tab_data: if not tab_data:
return web.HTTPNotFound(text="Tab not found") return web.HTTPNotFound(text="Tab not found")
tmpl = req.app['jinja_env'].get_template('msn:svcs/svcs_tabs_newer.xml') tmpl = req.app['jinja_env'].get_template('msn:svcs/svcs_tabs_newer.xml')
tab_tmpl = tmpl.render(tab=tab_data) tab_tmpl = tmpl.render(tab=tab_data)
return web.HTTPOk(content_type='text/xml', text=tab_tmpl) return web.HTTPOk(content_type='text/xml', text=tab_tmpl)
async def handle_msgrconfig(req: web.Request) -> web.Response: async def handle_msgrconfig(req: web.Request) -> web.Response:
if req.method == 'POST': if req.method == 'POST':
body = await req.read() # type: Optional[bytes] body = await req.read() # type: Optional[bytes]
@@ -642,14 +652,15 @@ async def handle_msgrconfig(req: web.Request) -> web.Response:
if msgr_config == 'INVALID_VER': if msgr_config == 'INVALID_VER':
return web.Response(status = 500) return web.Response(status = 500)
return web.HTTPOk(content_type = 'text/xml', text = msgr_config) 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: async def handle_msgrconfig16(req: web.Request) -> web.Response:
return web.HTTPOk(content_type = 'text/xml', text = _render_msgr_config(req, 'wlm16')) body = await req.read()
msgr_config = _get_msgr_config_16(req, body)
return web.HTTPOk(content_type = 'text/xml', text = msgr_config)
def _get_msgr_config(req: web.Request, body: Optional[bytes]) -> str: def _get_msgr_config(req: web.Request, body: Optional[bytes]) -> str:
query = req.query query = req.query
result = None # type: Optional[str]
ver = query.get('ver') or '' ver = query.get('ver') or ''
if ver: if ver:
@@ -658,28 +669,56 @@ def _get_msgr_config(req: web.Request, body: Optional[bytes]) -> str:
config_ver = ver.split('.', 4) config_ver = ver.split('.', 4)
if 8 <= int(config_ver[0]) <= 9: if 8 <= int(config_ver[0]) <= 9:
return _render_msgr_config(req, 'wlm8') 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)
elif int(config_ver[0]) >= 14: elif int(config_ver[0]) >= 14:
return _render_msgr_config(req, 'wlm14') 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
elif body is not None: elif body is not None:
# MSN Messenger 6.0 - 7.5 only use the SOAP `GetClientConfig` action with open(TMPL_DIR + '/config/MsgrConfig.msn.envelope.xml') as fh:
return _render_msgr_config(req, 'msn', soap = True) 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))
return '' return result or ''
def _render_msgr_config(req: web.Request, variant: MsgrConfigVariant, *, soap: bool = False) -> str: 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()
with open('config/tabs.json') as fh: with open('config/tabs.json') as fh:
tabs_data = json.load(fh) tabs_data = json.load(fh)
tmpl = req.app['jinja_env'].get_template('msn:config/MsgrConfig.xml') tmpl_before = req.app['jinja_env'].from_string(template)
return tmpl.render(variant = variant, soap = soap, tabs = tabs_data, settings = settings) tmpl = tmpl_before.render(tabs=tabs_data, settings=settings)
result = tmpl
return result or ''
PassportURLs = 'PassportURLs' PassportURLs = 'PassportURLs'
async def handle_nexus(req: web.Request) -> web.Response: async def handle_nexus(req: web.Request) -> web.Response:
return web.HTTPOk(headers = { return web.HTTPOk(headers = {
PassportURLs: 'DALogin=https://{}{}'.format(settings.LOGIN_HOST, LOGIN_PATH), PassportURLs: 'DALogin=https://{}{}'.format(settings.LOGIN_HOST, LOGIN_PATH),
}) })
async def handle_login(req: web.Request) -> web.Response: async def handle_login(req: web.Request) -> web.Response:
tmp = _extract_pp_credentials(req.headers.get('Authorization') or '') tmp = _extract_pp_credentials(req.headers.get('Authorization') or '')
if tmp is None: if tmp is None:
@@ -695,7 +734,7 @@ async def handle_login(req: web.Request) -> web.Response:
return web.HTTPOk(headers={ return web.HTTPOk(headers={
'Authentication-Info': '{}da-status=success,from-PP=\'{}\''.format(PP, token), 'Authentication-Info': '{}da-status=success,from-PP=\'{}\''.format(PP, token),
}) })
async def handle_not_rst(req: web.Request) -> web.Response: async def handle_not_rst(req: web.Request) -> web.Response:
if req.method == 'OPTIONS': if req.method == 'OPTIONS':
return web.HTTPOk(headers = { return web.HTTPOk(headers = {
@@ -718,8 +757,6 @@ async def handle_not_rst(req: web.Request) -> web.Response:
token, _, _ = token_tpl token, _, _ = token_tpl
headers['X-Token'] = token headers['X-Token'] = token
return web.HTTPOk(headers = headers) return web.HTTPOk(headers = headers)
DA_TOKEN_LIFETIME = 86400 * 30
async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response: async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response:
from lxml.objectify import fromstring as parse_xml from lxml.objectify import fromstring as parse_xml
@@ -730,28 +767,18 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response:
except: except:
return render(req, 'msn:RST/{}.error.xml'.format('RST2' if rst2 else 'RST')) return render(req, 'msn:RST/{}.error.xml'.format('RST2' if rst2 else 'RST'))
backend: Backend = req.app['backend']
email = find_element(root, 'Username') email = find_element(root, 'Username')
pwd = str(find_element(root, 'Password')) 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 if email is None or pwd is None:
da_token = find_element(root, 'Security/EncryptedData/CipherData/CipherValue')
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')) 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)
uuid = backend.util_get_uuid_from_email(email)
if token_tpl is not None and uuid is not None: if token_tpl is not None and uuid is not None:
token, expiry, bsecret = token_tpl token, expiry, bsecret = token_tpl
day_before_expiry = expiry - timedelta(days = 1) day_before_expiry = expiry - timedelta(days = 1)
@@ -763,11 +790,6 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response:
cid = cid_format(uuid) cid = cid_format(uuid)
puid = puid_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 assert req.transport is not None
peername = req.transport.get_extra_info('peername') peername = req.transport.get_extra_info('peername')
if peername: if peername:
@@ -803,8 +825,6 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response:
lastname = "Doe", lastname = "Doe",
ip = req.headers.get('X-Forwarded-For', req.remote), ip = req.headers.get('X-Forwarded-For', req.remote),
pptoken1 = token, pptoken1 = token,
datoken = datoken,
dabinarysecret = dabinarysecret,
tokenxml = Markup(''.join(tokenxmls)), tokenxml = Markup(''.join(tokenxmls)),
) if rst2 else tmpl.render( ) if rst2 else tmpl.render(
puidhex = puid, puidhex = puid,
@@ -816,8 +836,6 @@ async def handle_rst(req: web.Request, rst2: bool = False) -> web.Response:
lastname = "Doe", lastname = "Doe",
ip = req.headers.get('X-Forwarded-For', req.remote), ip = req.headers.get('X-Forwarded-For', req.remote),
pptoken1 = token, pptoken1 = token,
datoken = datoken,
dabinarysecret = dabinarysecret,
tokenxml = Markup(''.join(tokenxmls)), tokenxml = Markup(''.join(tokenxmls)),
)), )),
) )
@@ -825,7 +843,10 @@ 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'), { return render(req, 'msn:RST/{}.authfailed.xml'.format('RST2' if rst2 else 'RST'), {
'timez': util.misc.date_format(datetime.utcnow()), 'timez': util.misc.date_format(datetime.utcnow()),
}) })
def _get_storage_path(uuid: str) -> Path:
return Path('storage/dp') / uuid[0:1] / uuid[0:2]
async def handle_videofeed(req: web.Request, get_videos: bool = False) -> web.Response: async def handle_videofeed(req: web.Request, get_videos: bool = False) -> web.Response:
if not get_videos: if not get_videos:
return render(req, 'msn:svcs/videofeedroot.xml') return render(req, 'msn:svcs/videofeedroot.xml')
@@ -858,18 +879,18 @@ async def handle_videofeed(req: web.Request, get_videos: bool = False) -> web.Re
language="en-us", language="en-us",
lastBuildDate=datetime.now(), lastBuildDate=datetime.now(),
ttl=10, ttl=10,
copyright="&copy; 2023 - 2026 hiden", copyright="&copy; 2023 - 2025 the undergr0und",
image=PyRSS2Gen.Image( image=PyRSS2Gen.Image(
url="https://static.ugnet.xyz/svc/ct/logo/shadow.svg", url="http://hiden.cc/static/icon/misc/hidnet.png",
title="CrossTalk Videos", title="CrossTalk Video - InDev",
link="https://crosstalk.im" link="http://crosstalk.im"
), ),
items=rss_items items=rss_items
) )
rss_xml = rss_feed.to_xml(encoding="utf-8") rss_xml = rss_feed.to_xml(encoding="utf-8")
return web.HTTPOk(content_type="text/xml", text=rss_xml) return web.HTTPOk(content_type="text/xml", text=rss_xml)
def _extract_pp_credentials(auth_str: str) -> Optional[Tuple[str, str]]: def _extract_pp_credentials(auth_str: str) -> Optional[Tuple[str, str]]:
if not auth_str: if not auth_str:
return None return None
@@ -882,34 +903,19 @@ def _extract_pp_credentials(auth_str: str) -> Optional[Tuple[str, str]]:
email = auth['sign-in'] email = auth['sign-in']
pwd = auth['pwd'] pwd = auth['pwd']
return email, 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]]]: 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'] backend: Backend = req.app['backend']
uuid = backend.user_service.login(email, pwd) uuid = backend.user_service.login(email, pwd)
if uuid is None and email.lower().endswith('@crosstalk.im'):
username = email.lower()[:-len('@crosstalk.im')]
uuid = backend.user_service.login_with_username(username, pwd)
if uuid is None: return None 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 bsecret = None
if binary_secret: if binary_secret:
bsecret = base64.b64encode(secrets.token_bytes(24)).decode('ascii') bsecret = base64.b64encode(secrets.token_bytes(24)).decode('ascii')
return (*backend.login_auth_service.create_token('ns/login', [uuid, bsecret], lifetime = lifetime), bsecret) 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: def _contact_is_favorite(user_detail: models.UserDetail, ctc: models.Contact) -> bool:
groups = user_detail._groups_by_uuid groups = user_detail._groups_by_uuid
for group in ctc._groups.copy(): for group in ctc._groups.copy():
if group.id not in groups: continue if group.id not in groups: continue
if groups[group.id].is_favorite: return True if groups[group.id].is_favorite: return True
return False return False
-253
View File
@@ -1,253 +0,0 @@
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
# ```
# <UpdateProfile xmlns="http://www.msn.com/webservices/storage/w10">
# <profile>
# <ResourceID>862d987eb60b7a63!106</ResourceID>
# <ExpressionProfile>
# <FreeText>Update</FreeText>
# <DisplayName>Society is betrayal</DisplayName>
# <PersonalStatus>Prosperity is the best medicine. :)</PersonalStatus>
# </ExpressionProfile>
# </profile>
# </UpdateProfile>
# ```
# Remove roaming message
# ```
# <UpdateProfile xmlns="http://www.msn.com/webservices/storage/w10">
# <profile>
# <ResourceID>bb4542ce2eacdbde!106</ResourceID>
# <ExpressionProfile>
# <FreeText>Update</FreeText>
# <DisplayName>%walkingphas3r%</DisplayName>
# <Flags>0</Flags>
# </ExpressionProfile>
# </profile>
# <profileAttributesToDelete>
# <ExpressionProfileAttributes>
# <PersonalStatus>true</PersonalStatus>
# </ExpressionProfileAttributes>
# </profileAttributesToDelete>
# </UpdateProfile>
# ```
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)
-188
View File
@@ -1,188 +0,0 @@
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)
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>{{ faultstring or 'Schema validation error' }}</faultstring>
<faultactor>{{ actor }}</faultactor>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Server was unable to process request.</faultstring>
{% if actor %}<faultactor>{{ actor }}</faultactor>
{% endif %}<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
-2
View File
@@ -1,4 +1,3 @@
<wst:RequestSecurityTokenResponse> <wst:RequestSecurityTokenResponse>
<wst:TokenType>urn:passport:compact</wst:TokenType> <wst:TokenType>urn:passport:compact</wst:TokenType>
<wsp:AppliesTo xmlns:wsa="http://www.w3.org/2005/08/addressing"> <wsp:AppliesTo xmlns:wsa="http://www.w3.org/2005/08/addressing">
@@ -29,4 +28,3 @@
</wst:RequestedProofToken> </wst:RequestedProofToken>
{% endif %} {% endif %}
</wst:RequestSecurityTokenResponse> </wst:RequestSecurityTokenResponse>
+2 -2
View File
@@ -72,7 +72,7 @@
<ds:KeyName>http://Passport.NET/STS</ds:KeyName> <ds:KeyName>http://Passport.NET/STS</ds:KeyName>
</ds:KeyInfo> </ds:KeyInfo>
<CipherData> <CipherData>
<CipherValue>{{ datoken }}</CipherValue> <CipherValue>Cap26AQZrSyMm2SwwTyJKyqLR9/S+vQWQsaBc5Mv7PwtQDMzup/udOOMMvSu99R284pmiD3IepBXrEMLK5rLrXAf2A6vrP6vYuGA45GCqQdoxusHZcjt9P2B8WyCTVT2cM8jtGqGIfRlU/4WzOLxNrDJwDfOsmilduGAGZfvRPW7/jyXXrnGK7/PWkymX4YDD+ygJfMrPAfvAprvw/HVE6tutKVc9cViTVYy8oHjosQlb8MKn3vKDW1O2ZWQUc47JPl7DkjQaanfNBGe6CL7K1nr6Z/jy7Ay7MjV+KQehmvphSEmCzLrpB4WWn2PdpdTrOcDj+aJfWHeGL4sIPwEKgrKnTQg9QD8CCsm5wew9P/br39OuIfsC6/PFBEHmVThqj0aMxYLRD4K2GoRay6Ab7NftoIP5dnFnclfRxETAoNpTPE2F5Q669QySrdXxBpBSk8GLmdCDMlhiyzSiByrhFQaZRcH8n9i+i289otYuJQ7xPyP19KwT4CRyOiIlh3DSdlBfurMwihQGxN2spU7P4MwckrDKeOyYQhvNm/XWId/oXBqpHbo2yRPiOwL9p1J4AxA4RaJuh77vyhn2lFQaxPDqZd5A8RJjpb2NE2N3UncKLW7GAangdoLbRDMqt51VMZ0la+b/moL61fKvFXinKRHc7PybrG3MWzgXxO/VMKAuXOsB9XnOgl2A524cgiwyg==</CipherValue>
</CipherData> </CipherData>
</EncryptedData> </EncryptedData>
</wst:RequestedSecurityToken> </wst:RequestedSecurityToken>
@@ -87,7 +87,7 @@
</wsse:SecurityTokenReference> </wsse:SecurityTokenReference>
</wst:RequestedUnattachedReference> </wst:RequestedUnattachedReference>
<wst:RequestedProofToken> <wst:RequestedProofToken>
<wst:BinarySecret>{{ dabinarysecret }}</wst:BinarySecret> <wst:BinarySecret>tgoPVK67sU36fQKlGLMgWgTXp7oiaQgE</wst:BinarySecret>
</wst:RequestedProofToken> </wst:RequestedProofToken>
</wst:RequestSecurityTokenResponse> </wst:RequestSecurityTokenResponse>
{{ tokenxml }} {{ tokenxml }}
+3 -11
View File
@@ -1,7 +1,7 @@
{% macro contact_entry(ab_id, ctc, detail, now, trust_level = none) %} {% macro contact_entry(ab_id, ctc, detail, now) %}
<contactId>{{ ctc.head.uuid }}</contactId> <contactId>{{ ctc.head.uuid }}</contactId>
<contactInfo> <contactInfo>
{% if ctc.detail.personal_email or ctc.detail.work_email or ctc.detail.im_email or ctc.detail.other_email %} {% if ctc.detail.personal_email or ctc.detail.work_phone or ctc.detail.im_email or ctc.detail.other_email %}
<emails> <emails>
{% if ctc.detail.work_email %} {% if ctc.detail.work_email %}
{{ email_entry('ContactEmailBusiness', 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.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 %}
<phones> <phones>
{% if ctc.detail.work_phone %} {% if ctc.detail.work_phone %}
{{ phone_entry('ContactPhoneBusiness', ctc.detail.work_phone) }} {{ phone_entry('ContactPhoneBusiness', contact.work_phone) }}
{% endif %} {% endif %}
{% if ctc.detail.fax_phone %} {% if ctc.detail.fax_phone %}
{{ phone_entry('ContactPhoneFax', ctc.detail.fax_phone) }} {{ phone_entry('ContactPhoneFax', ctc.detail.fax_phone) }}
@@ -123,11 +123,6 @@
<IsPrivate>false</IsPrivate> <IsPrivate>false</IsPrivate>
<Gender>Unspecified</Gender> <Gender>Unspecified</Gender>
<TimeZone>None</TimeZone> <TimeZone>None</TimeZone>
{% if trust_level is not none %}
<IsAutoUpdateDisabled>false</IsAutoUpdateDisabled>
<IsShellContact>false</IsShellContact>
<TrustLevel>{{ trust_level }}</TrustLevel>
{% endif %}
</contactInfo> </contactInfo>
<propertiesChanged /> <propertiesChanged />
<fDeleted>false</fDeleted> <fDeleted>false</fDeleted>
@@ -217,9 +212,6 @@
<IsPrivate>false</IsPrivate> <IsPrivate>false</IsPrivate>
<Gender>Unspecified</Gender> <Gender>Unspecified</Gender>
<TimeZone>None</TimeZone> <TimeZone>None</TimeZone>
<IsAutoUpdateDisabled>false</IsAutoUpdateDisabled>
<IsShellContact>false</IsShellContact>
<TrustLevel>{{ (user.settings.get('TrustLevels') or {}).get(user.uuid, 0) }}</TrustLevel>
</contactInfo> </contactInfo>
<propertiesChanged /> <propertiesChanged />
<fDeleted>false</fDeleted> <fDeleted>false</fDeleted>
@@ -1,4 +1,4 @@
{% from 'msn:_funcs.xml' import contact_entry, group_entry, generate_me_entry -%} {% from 'msn:_funcs.xml' import contact_entry, group_entry, generate_me_entry, ab_properties -%}
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header> <soap:Header>
@@ -13,88 +13,88 @@
<soap:Body> <soap:Body>
<ABFindContactsPagedResponse xmlns="http://www.msn.com/webservices/AddressBook"> <ABFindContactsPagedResponse xmlns="http://www.msn.com/webservices/AddressBook">
<ABFindContactsPagedResult> <ABFindContactsPagedResult>
{%- if ab_id == '00000000-0000-0000-0000-000000000000' %} {% if ab_id == '00000000-0000-0000-0000-000000000000' %}
<Groups> <Groups>
{%- for group in detail._groups_by_uuid.values() %} {% for group in detail._groups_by_uuid.values() %}
{{ group_entry(group, now) }} {{ group_entry(group, now) }}
{%- endfor %} {% endfor %}
</Groups> </Groups>
{%- endif %} {% endif %}
<Contacts> <Contacts>
{%- if ab_id == '00000000-0000-0000-0000-000000000000' %} {% if ab_id == '00000000-0000-0000-0000-000000000000' %}
{%- for ctc in detail.contacts.values() %} {% for ctc in detail.contacts.values() %}
{%- if ctc.lists.__and__(ContactList.FL) %} {% if ctc.lists.__and__(ContactList.FL) %}
<Contact> <Contact>
{{ contact_entry(ab_id, ctc, detail, now, trust_level = (user.settings.get('TrustLevels') or {}).get(ctc.head.uuid, 0)) }} {{ contact_entry(ab_id, ctc, detail, now) }}
</Contact> </Contact>
{%- endif %} {% endif %}
{%- endfor %} {% endfor %}
{%- for circle in circles %} {% for circle in circles %}
<Contact> <Contact>
<contactId>00000000-0000-0000-0009-{{ circle.chat_id }}</contactId> <contactId>00000000-0000-0000-0009-{{ circle.chat_id }}</contactId>
<contactInfo> <contactInfo>
<contactType>Circle</contactType> <contactType>Circle</contactType>
<quickName>circle</quickName> <quickName>circle</quickName>
<passportName>00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com</passportName> <passportName>00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com</passportName>
<IsPassportNameHidden>false</IsPassportNameHidden> <IsPassportNameHidden>false</IsPassportNameHidden>
<displayName>{% if circle.memberships[user.uuid].role == CircleRole.Admin %}{{ circle.name }}{% else %}00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com{% endif %}</displayName> <displayName>{% if circle.memberships[user.uuid].role == CircleRole.Admin %}{{ circle.name }}{% else %}00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com{% endif %}</displayName>
<puid>{{ puid_format(user.uuid) }}</puid> <puid>{{ puid_format(user.uuid) }}</puid>
<CID>{{ cid_format('00000000-0000-0000-0009-' + circle.chat_id, decimal = True) }}</CID> <CID>{{ cid_format('00000000-0000-0000-0009-' + circle.chat_id, decimal = True) }}</CID>
<IsNotMobileVisible>false</IsNotMobileVisible> <IsNotMobileVisible>false</IsNotMobileVisible>
<isMobileIMEnabled>false</isMobileIMEnabled> <isMobileIMEnabled>false</isMobileIMEnabled>
<isMessengerUser>false</isMessengerUser> <isMessengerUser>false</isMessengerUser>
<isFavorite>false</isFavorite> <isFavorite>false</isFavorite>
<isSmtp>false</isSmtp> <isSmtp>false</isSmtp>
<hasSpace>false</hasSpace> <hasSpace>false</hasSpace>
<spotWatchState>NoDevice</spotWatchState> <spotWatchState>NoDevice</spotWatchState>
<birthdate>0001-01-01T00:00:00</birthdate> <birthdate>0001-01-01T00:00:00</birthdate>
<primaryEmailType>ContactEmailPersonal</primaryEmailType> <primaryEmailType>ContactEmailPersonal</primaryEmailType>
<PrimaryLocation>ContactLocationPersonal</PrimaryLocation> <PrimaryLocation>ContactLocationPersonal</PrimaryLocation>
<PrimaryPhone>ContactPhonePersonal</PrimaryPhone> <PrimaryPhone>ContactPhonePersonal</PrimaryPhone>
<IsPrivate>false</IsPrivate> <IsPrivate>false</IsPrivate>
<IsHidden>true</IsHidden> <IsHidden>true</IsHidden>
<Gender>Unspecified</Gender> <Gender>Unspecified</Gender>
<TimeZone>None</TimeZone> <TimeZone>None</TimeZone>
<NetworkInfoList> <NetworkInfoList>
<NetworkInfo> <NetworkInfo>
<DomainId>1</DomainId> <DomainId>1</DomainId>
<SourceId>WL</SourceId> <SourceId>WL</SourceId>
{%- if circle.memberships[user.uuid].role != CircleRole.Admin %} {% if circle.memberships[user.uuid].role != CircleRole.Admin %}
<DomainTag>00000000-0000-0000-0009-{{ circle.chat_id.upper() }}</DomainTag> <DomainTag>00000000-0000-0000-0009-{{ circle.chat_id.upper() }}</DomainTag>
<DisplayName>00000000-0000-0000-0009-{{ circle.chat_id.upper() }}</DisplayName> <DisplayName>00000000-0000-0000-0009-{{ circle.chat_id.upper() }}</DisplayName>
{%- endif %} {% endif %}
<RelationshipType>5</RelationshipType> <RelationshipType>5</RelationshipType>
<RelationshipState>{{ circle.memberships[user.uuid].state.value }}</RelationshipState> <RelationshipState>{{ circle.memberships[user.uuid].state.value }}</RelationshipState>
<RelationshipStateDate>{{ now }}</RelationshipStateDate> <RelationshipStateDate>{{ now }}</RelationshipStateDate>
<RelationshipRole>{% if circle.memberships[user.uuid].role == CircleRole.StatePendingOutbound %}4{% else %}0{% endif %}</RelationshipRole> <RelationshipRole>{% if circle.memberships[user.uuid].role == CircleRole.StatePendingOutbound %}4{% else %}0{% endif %}</RelationshipRole>
<NDRCount>0</NDRCount> <NDRCount>0</NDRCount>
{%- if circle.memberships[user.uuid].invite_message %} {% if circle.memberships[user.uuid].invite_message %}
<InviterMessage>{{ circle.memberships[user.uuid].invite_message }}</InviterMessage> <InviterMessage>{{ circle.memberships[user.uuid].invite_message }}</InviterMessage>
{%- endif %} {% endif %}
<InviterCID>{% if user.uuid == circle.owner_uuid %}0{% else %}{{ cid_format(circle.memberships[user.uuid].inviter_uuid, decimal = True) }}{% endif %}</InviterCID> <InviterCID>{% if user.uuid == circle.owner_uuid %}0{% else %}{{ cid_format(circle.memberships[user.uuid].inviter_uuid, decimal = True) }}{% endif %}</InviterCID>
{%- if circle.memberships[user.uuid].inviter_name %} {% if circle.memberships[user.uuid].inviter_name %}
<InviterName>{{ circle.memberships[user.uuid].inviter_name }}</InviterName> <InviterName>{{ circle.memberships[user.uuid].inviter_name }}</InviterName>
{%- endif %} {% endif %}
{%- if circle.memberships[user.uuid].inviter_email %} {% if circle.memberships[user.uuid].inviter_email %}
<InviterEmail>{{ circle.memberships[user.uuid].inviter_email }}</InviterEmail> <InviterEmail>{{ circle.memberships[user.uuid].inviter_email }}</InviterEmail>
{%- endif %} {% endif %}
<CreateDate>{{ now }}</CreateDate>
<LastUpdated>{{ now }}</LastUpdated>
<PropertiesChanged />
</NetworkInfo>
</NetworkInfoList>
<IsAutoUpdateDisabled>false</IsAutoUpdateDisabled>
<IsShellContact>false</IsShellContact>
<TrustLevel>0</TrustLevel>
<PropertiesChanged />
</contactInfo>
<propertiesChanged />
<fDeleted>false</fDeleted>
<CreateDate>{{ now }}</CreateDate> <CreateDate>{{ now }}</CreateDate>
<LastUpdated>{{ now }}</LastUpdated> <lastChange>{{ now }}</lastChange>
<PropertiesChanged /> <CreatedBy>96</CreatedBy>
</NetworkInfo> </Contact>
</NetworkInfoList> {% endfor %}
<IsAutoUpdateDisabled>false</IsAutoUpdateDisabled>
<IsShellContact>false</IsShellContact>
<TrustLevel>0</TrustLevel>
<PropertiesChanged />
</contactInfo>
<propertiesChanged />
<fDeleted>false</fDeleted>
<CreateDate>{{ now }}</CreateDate>
<lastChange>{{ now }}</lastChange>
<CreatedBy>96</CreatedBy>
</Contact>
{%- endfor %}
{% else %} {% else %}
{% for membership in circle.memberships.values() %} {% for membership in circle.memberships.values() %}
<Contact> <Contact>
@@ -38,7 +38,7 @@
<TimeZone>None</TimeZone> <TimeZone>None</TimeZone>
<IsAutoUpdateDisabled>false</IsAutoUpdateDisabled> <IsAutoUpdateDisabled>false</IsAutoUpdateDisabled>
<IsShellContact>false</IsShellContact> <IsShellContact>false</IsShellContact>
<TrustLevel>{{ trust_level }}</TrustLevel> <TrustLevel>0</TrustLevel>
<PropertiesChanged /> <PropertiesChanged />
</contactInfo> </contactInfo>
<propertiesChanged /> <propertiesChanged />
@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>{{ faultcode }}</faultcode>
<faultstring>{{ errorstring }}</faultstring>
<faultactor>http://www.msn.com/webservices/AddressBook/{{ action_str }}</faultactor>
<detail>
<errorcode xmlns="http://www.msn.com/webservices/AddressBook">{{ errorcode }}</errorcode>
<errorstring xmlns="http://www.msn.com/webservices/AddressBook">{{ errorstring }}</errorstring>
<machineName xmlns="http://www.msn.com/webservices/AddressBook">BAYABCHWBB133</machineName>
{% if parameter_fault %}<parameterFault xmlns="http://www.msn.com/webservices/AddressBook">{{ parameter_fault }}</parameterFault>
{% endif %}<additionalDetails>
{% if conflict_object_id %}<conflictObjectId>{{ conflict_object_id }}</conflictObjectId>
{% endif %}<originalExceptionErrorMessage>{{ errorstring }}</originalExceptionErrorMessage>
</additionalDetails>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
@@ -19,15 +19,15 @@
{% endif %} {% endif %}
{% if not error %} {% if not error %}
<clientErrorData /> <clientErrorData />
<contactId>{% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}00000000-0000-0000-0009-{{ circle.chat_id }}{% else %}{{ head.uuid }}{% endif %}</contactId> <contactId>{% if ab_id == '00000000-0000-0000-0000-000000000000' %}00000000-0000-0000-0009-{{ circle.chat_id }}{% else %}{{ head.uuid }}{% endif %}</contactId>
<contactInfo> <contactInfo>
<contactType>{% 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 %}</contactType> <contactType>{% 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 %}</contactType>
<quickName>{% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}circle{% else %}{{ head.email }}{% endif %}</quickName> <quickName>{% if ab_id == '00000000-0000-0000-0000-000000000000' %}circle{% else %}{{ head.email }}{% endif %}</quickName>
<passportName>{% 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 %}</passportName> <passportName>{% if ab_id == '00000000-0000-0000-0000-000000000000' %}00000000-0000-0000-0009-{{ circle.chat_id.upper() }}@hotmail.com{% else %}{{ head.email }}{% endif %}</passportName>
<IsPassportNameHidden>false</IsPassportNameHidden> <IsPassportNameHidden>false</IsPassportNameHidden>
<displayName>{% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}{{ circle.name }}{% else %}{{ head.email }}{% endif %}</displayName> <displayName>{% if ab_id == '00000000-0000-0000-0000-000000000000' %}{{ circle.name }}{% else %}{{ head.email }}{% endif %}</displayName>
<puid>{{ puid_format(user.uuid) }}</puid> <puid>{{ puid_format(user.uuid) }}</puid>
<CID>{% if circle is not none %}{{ cid_format('00000000-0000-0000-0009-' + circle.chat_id, decimal = True) }}{% else %}{{ cid_format(head.uuid, decimal = True) }}{% endif %}</CID> <CID>{{ cid_format('00000000-0000-0000-0009-' + circle.chat_id, decimal = True) }}</CID>
<IsNotMobileVisible>false</IsNotMobileVisible> <IsNotMobileVisible>false</IsNotMobileVisible>
<isMobileIMEnabled>false</isMobileIMEnabled> <isMobileIMEnabled>false</isMobileIMEnabled>
<isMessengerUser>false</isMessengerUser> <isMessengerUser>false</isMessengerUser>
@@ -40,10 +40,10 @@
<PrimaryLocation>ContactLocationPersonal</PrimaryLocation> <PrimaryLocation>ContactLocationPersonal</PrimaryLocation>
<PrimaryPhone>ContactPhonePersonal</PrimaryPhone> <PrimaryPhone>ContactPhonePersonal</PrimaryPhone>
<IsPrivate>false</IsPrivate> <IsPrivate>false</IsPrivate>
<IsHidden>{% if circle is not none and ab_id == '00000000-0000-0000-0000-000000000000' %}true{% else %}false{% endif %}</IsHidden> <IsHidden>{% if ab_id == '00000000-0000-0000-0000-000000000000' %}true{% else %}false{% endif %}</IsHidden>
<Gender>Unspecified</Gender> <Gender>Unspecified</Gender>
<TimeZone>None</TimeZone> <TimeZone>None</TimeZone>
{% 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) %} {% 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) %}
<NetworkInfoList> <NetworkInfoList>
<NetworkInfo> <NetworkInfo>
<DomainId>1</DomainId> <DomainId>1</DomainId>
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header>
<ServiceHeader xmlns="http://www.msn.com/webservices/AddressBook">
<Version>15.01.1408.0000</Version>
<CacheKey>12r1:{{ cachekey }}</CacheKey>
<CacheKeyChanged>true</CacheKeyChanged>
<PreferredHostName>{{ host }}</PreferredHostName>
<SessionId>{{ session_id }}</SessionId>
</ServiceHeader>
</soap:Header>
<soap:Body>
<UpdateContactResponse xmlns="http://www.msn.com/webservices/AddressBook" />
</soap:Body>
</soap:Envelope>
+7 -7
View File
@@ -1790,14 +1790,14 @@
</App> </App>
<App DomainId="70"> <App DomainId="70">
<AppId>1140906031</AppId> <AppId>1140906031</AppId>
<ThumbNailUrl>https://{{ settings.USERSTORAGE_HOST }}/static/social/ugnetthumb.gif</ThumbNailUrl> <ThumbNailUrl>https://cts.storage.ugnet.gay/static/social/ugnetthumb.gif</ThumbNailUrl>
<MiniPhotoUrl>https://{{ settings.USERSTORAGE_HOST }}/static/social/mini.gif</MiniPhotoUrl> <MiniPhotoUrl>https://cts.storage.ugnet.gay/static/social/mini.gif</MiniPhotoUrl>
<Domain>^https?://.*\.ugnet\.xyz/.*$</Domain> <Domain>^https?://.*\.hiden\.cc/.*$</Domain>
<EmailDomain>mail.ugnet.xyz</EmailDomain> <EmailDomain>mail.ugnet.gay</EmailDomain>
<WebDomain>ugnet.xyz</WebDomain> <WebDomain>ugnet.gay</WebDomain>
<Name>Testing...</Name> <Name>the undergr0und</Name>
<Summary>Making the internet fun again.</Summary> <Summary>Making the internet fun again.</Summary>
<SiteUrl>http://ugnet.xyz/</SiteUrl> <SiteUrl>http://ugnet.gay/</SiteUrl>
<PSARank>1</PSARank> <PSARank>1</PSARank>
<Connected>true</Connected> <Connected>true</Connected>
<AppState> <AppState>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetClientConfigResponse xmlns="http://www.msn.com/webservices/Messenger/Client">
<GetClientConfigResult><![CDATA[{MsgrConfig}]]></GetClientConfigResult>
</GetClientConfigResponse>
</soap:Body>
</soap:Envelope>
@@ -0,0 +1,102 @@
<MsgrConfig>
<Simple>
<Config>
<ExpiresInDays>0</ExpiresInDays>
</Config>
<DisablePhoneDialer>1</DisablePhoneDialer>
<MinFlashPlayer BuildNumber="60" MajorVersion="7" MinorVersion="0"></MinFlashPlayer>
<Relay>
<Enabled>0</Enabled>
<MaxCallLength>0</MaxCallLength>
</Relay>
<TrustedDomains>
<domain name="hiden.cc"/>
<domain name="ugnet.gay"/>
<domain name="crosstalk.im"/>
<domain name="ctsrv.gay"/>
</TrustedDomains>
<ErrorResponseTable>
<Feature type="0" name="Login">
<Entry hr="0x80072EE7" action="3"></Entry>
<Entry hr="0x81000306" action="3"></Entry>
<Entry hr="0x80072EFD" action="3"></Entry>
<Entry hr="0x81000362" action="3"></Entry>
<Entry hr="0x8100030E" action="3"></Entry>
<Entry hr="0x80072745" action="3"></Entry>
<Entry hr="0x800701F7" action="3"></Entry>
<Entry hr="0x80072EFF" action="3"></Entry>
<Entry hr="0x81000363" action="3"></Entry>
<Entry hr="0x81000395" action="3"></Entry>
<Entry hr="0x800B0001" action="3"></Entry>
<Entry hr="0x81000323" action="3"></Entry>
<Entry hr="0x80072F19" action="3"></Entry>
<Entry hr="0x800701F8" action="3"></Entry>
<Entry hr="0x80072746" action="3"></Entry>
<Entry hr="0x800701F6" action="3"></Entry>
<Entry hr="0x81000377" action="3"></Entry>
<Entry hr="0x81000314" action="3"></Entry>
<Entry hr="0x81000378" action="3"></Entry>
<Entry hr="0x80072EFF" action="3"></Entry>
<Entry hr="0x80070190" action="3"></Entry>
<Entry hr="0x80070197" action="3"></Entry>
<Entry hr="0x80048820" action="3"></Entry>
<Entry hr="0x80048829" action="3"></Entry>
<Entry hr="0x80048834" action="3"></Entry>
<Entry hr="0x80048852" action="3"></Entry>
<Entry hr="0x8004886a" action="3"></Entry>
<Entry hr="0x8004886b" action="3"></Entry>
</Feature>
<Feature type="2" name="MapFile">
<Entry hr="0x810003F0" action="3"></Entry>
<Entry hr="0x810003F1" action="3"></Entry>
<Entry hr="0x810003F2" action="3"></Entry>
<Entry hr="0x810003F3" action="3"></Entry>
<Entry hr="0x810003F4" action="3"></Entry>
<Entry hr="0x810003F5" action="3"></Entry>
<Entry hr="0x810003F6" action="3"></Entry>
<Entry hr="0x810003F7" action="3"></Entry>
</Feature>
</ErrorResponseTable>
</Simple>
<TabConfig>
{tabs}
</TabConfig>
<AbchCfg>
<abchconfig>
<url>https://ctsvcs.addressbook.ugnet.gay/abservice.asmx</url>
</abchconfig>
</AbchCfg>
<LocalizedConfig Market="en-US">
<AdMainConfig>
<TextAdRefresh>1</TextAdRefresh>
<TextAdServer>http://ctsvcs.advertising.ugnet.gay/ads/txt</TextAdServer>
<AdBanner20URL Refresh="300">http://ctsvcs.advertising.ugnet.gay/ads/banner</AdBanner20URL>
</AdMainConfig>
<AppDirConfig>
<AppDirPageURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/Directory.aspx?L=en-us</AppDirPageURL>
<AppDirSeviceURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/AppDirectory.asmx</AppDirSeviceURL>
<AppDirVersionURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/GetAppdirVersion.aspx</AppDirVersionURL>
</AppDirConfig>
<MSNSearch>
<DesktopInstallURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</DesktopInstallURL>
<ImagesURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=images</ImagesURL>
<NearMeURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</NearMeURL>
<NewsURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$+news&amp;ia=news</NewsURL>
<SearchKidsURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SearchKidsURL>
<SearchURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SearchURL>
<SharedSearchURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SharedSearchURL>
<SharedSearchURL2>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SharedSearchURL2>
</MSNSearch>
<MsnTodayConfig>
<MsnTodayURL>http://today.msgrsvcs.ctsrv.gay/start?msn=1</MsnTodayURL>
</MsnTodayConfig>
<MusicIntegration URL="https://www.last.fm/search/tracks?q=$ARTIST$+$TITLE$"/>
<RL>
<ViewProfileURL>https://crosstalk.im/account/settings</ViewProfileURL>
</RL>
<TermsOfUse>
<TermsOfUseSID>956</TermsOfUseSID>
<TermsOfUseURL>https://crosstalk.im/tos</TermsOfUseURL>
</TermsOfUse>
</LocalizedConfig>
</MsgrConfig>
@@ -0,0 +1,239 @@
<?xml version="1.0" encoding="utf-8"?>
<MsgrConfig>
<Simple>
<Config>
<ExpiresInDays>0</ExpiresInDays>
</Config>
<P2PConfig>
<ObjectStore>
<SendDelay>1</SendDelay>
</ObjectStore>
</P2PConfig>
<DisablePhoneDialer>1</DisablePhoneDialer>
<GetItemVersionForUnknown>false</GetItemVersionForUnknown>
<MinFlashPlayer BuildNumber="28" MajorVersion="9" MinorVersion="0" />
<Relay>
<Enabled>0</Enabled>
<MaxCallLength>0</MaxCallLength>
</Relay>
<Contacts>
<Client ZombieServerDetectDelay="1800" ZombieServerDetectInterval="30" ZombieServerDetectResumeDelay="1800" />
<Server ZombieServerDetectDelay="900" ZombieServerDetectResumeDelay="900" ZombieServerDetectConnectDelay="900" ZombieServerDetectLongDelay="900" />
</Contacts>
<TrustedDomains>
<domain name="hiden.cc"/>
<domain name="ugnet.gay"/>
<domain name="crosstalk.im"/>
<domain name="ctsrv.gay"/>
</TrustedDomains>
<ErrorResponseTable>
<Feature type="0" name="Login">
<Entry hr="0x80004002" action="3"/>
<Entry hr="0x80004004" action="3"/>
<Entry hr="0x80004005" action="3"/>
<Entry hr="0x8000402A" action="3"/>
<Entry hr="0x8000FFFF" action="3"/>
<Entry hr="0x8001012E" action="3"/>
<Entry hr="0x80040200" action="3"/>
<Entry hr="0x80048051" action="3"/>
<Entry hr="0x80048820" action="3"/>
<Entry hr="0x80048823" action="3"/>
<Entry hr="0x80070002" action="3"/>
<Entry hr="0x80070005" action="3"/>
<Entry hr="0x8007000E" action="3"/>
<Entry hr="0x80070057" action="3"/>
<Entry hr="0x8007007E" action="3"/>
<Entry hr="0x800702E4" action="3"/>
<Entry hr="0x800706BA" action="3"/>
<Entry hr="0x800706BE" action="3"/>
<Entry hr="0x80071392" action="3"/>
<Entry hr="0x80072745" action="3"/>
<Entry hr="0x80072746" action="3"/>
<Entry hr="0x80072EE2" action="3"/>
<Entry hr="0x80072EF3" action="3"/>
<Entry hr="0x80072EFD" action="3"/>
<Entry hr="0x80072EFF" action="3"/>
<Entry hr="0x80072F06" action="3"/>
<Entry hr="0x80072F7D" action="3"/>
<Entry hr="0x800C013E" action="3"/>
<Entry hr="0x80191002" action="3"/>
<Entry hr="0x81000306" action="3"/>
<Entry hr="0x8100030D" action="3"/>
<Entry hr="0x81000314" action="3"/>
<Entry hr="0x81000362" action="3"/>
<Entry hr="0x81000378" action="3"/>
<Entry hr="0x81000395" action="3"/>
<Entry hr="0x85AE000B" action="3"/>
<Entry hr="0x85AE000F" action="3"/>
<Entry hr="0x85AE001D" action="3"/>
<Entry hr="0x85AE0022" action="3"/>
<Entry hr="0x85AE0024" action="3"/>
<Entry hr="0x85AE0027" action="3"/>
<Entry hr="0x85AE003C" action="3"/>
<Entry hr="0x85AE0053" action="3"/>
<Entry hr="0x8E5E0152" action="3"/>
<Entry hr="0x8E5E0158" action="3"/>
<Entry hr="0x8E5E0211" action="3"/>
<Entry hr="0x8E5E0220" action="3"/>
<Entry hr="0x8E5E0226" action="3"/>
<Entry hr="0x8E5E03FE" action="3"/>
<Entry hr="0x8E5E0408" action="3"/>
<Entry hr="0x8E5E05F6" action="3"/>
<Entry hr="0x8E5E0710" action="3"/>
<Entry hr="0x8E5E0713" action="3"/>
</Feature>
<Feature type="2" name="MapFile">
<Entry hr="0x810003F1" action="3"/>
<Entry hr="0x810003F6" action="3"/>
</Feature>
<Feature type="3" name="P2P">
<Entry hr="0x82000016" action="3"/>
<Entry hr="0x82000017" action="3"/>
<Entry hr="0x82000019" action="3"/>
<Entry hr="0x8200001b" action="3"/>
<Entry hr="0x8200001d" action="3"/>
<Entry hr="0x8200001e" action="3"/>
<Entry hr="0x82000024" action="3"/>
<Entry hr="0x82000026" action="3"/>
</Feature>
</ErrorResponseTable>
<USBDevices>
<Device VID="0x045e" PID="0x0719"/>
<Device VID="0x045e" PID="0x0722"/>
<Device VID="0x041e" PID="0x4080"/>
</USBDevices>
<CirclesWeb General="https://crosstalk.im/circles/$CIRCLECID$/settings/" General-SiteId="73625" Management="https://crosstalk.im/circles/$CIRCLECID$/settings/" Management-SiteId="73625" Membership="https://crosstalk.im/circles/$CIRCLECID$/settings/" Membership-SiteId="73625" Leave="https://crosstalk.im/circles/$CIRCLECID$/settings/" Leave-SiteId="73625" Disc="https://crosstalk.im/" />
<AnonymousIMSettings>
<SettingsPage URL="http://settings.messenger.live.com/applications/WebSettings.aspx" SiteID="76215" />
</AnonymousIMSettings>
</Simple>
<AbchCfg>
<abchconfig>
<url>https://ctsvcs.addressbook.ugnet.gay/abservice.asmx</url>
</abchconfig>
</AbchCfg>
<LocalizedConfig Market="en-US">
<AdMainConfig>
<TextAdRotation>420</TextAdRotation>
<TextAdRefresh>1</TextAdRefresh>
<TextAdServer>http://ctsvcs.advertising.ugnet.gay/ads/txt</TextAdServer>
<AdBanner20URL Refresh="300">http://ctsvcs.advertising.ugnet.gay/ads/banner</AdBanner20URL>
<StdAd AdVisible="60" VideoVisible="120" VideoDldIntvl="0">
<VideoFeeds FeedsListURL="http://ctsvcs.advertising.ugnet.gay/svcs/msn-video-feeds/"/>
</StdAd>
</AdMainConfig>
<AppDirConfig>
<AppDirPageURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/Directory.aspx?L=en-us</AppDirPageURL>
<AppDirSeviceURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/AppDirectory.asmx</AppDirSeviceURL>
<AppDirVersionURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/GetAppdirVersion.aspx</AppDirVersionURL>
</AppDirConfig>
<Contacts>
<ABPendingRequests>
<SiteId>73625</SiteId>
<height>672</height>
<IncludeSNRequests>true</IncludeSNRequests>
<width>808</width>
<urlcid>http://cid-%1!16.16I64X!.profile.live.com/invites?partner=Messenger</urlcid>
</ABPendingRequests>
<EditMyLiveContactProfile>
<url>http://social.ugnet.gay/profile.aspx?action=edit&amp;mode=activecontacts&amp;mkt=en-us&amp;partner=Messenger</url>
<SiteId>73625</SiteId>
</EditMyLiveContactProfile>
<EditMyProfile>
<url>http://profile.live.com/details</url>
<SiteId>73625</SiteId>
</EditMyProfile>
<Import>
<url>http://cid-%1!16.16I64X!.profile.live.com/connect/?partner=Messenger</url>
<SiteId>73625</SiteId>
</Import>
<MessengerInvite>
<url>http://cid-%1.profile.live.com/connect/send.aspx?email=%2</url>
<urlcid>http://cid-%1.profile.live.com/connect/send.aspx?cid=%2</urlcid>
<SiteId>73625</SiteId>
</MessengerInvite>
<Profile>
<url>http://social.ugnet.gay/Profile.aspx?partner=Messenger&amp;mkt=en-us&amp;mem=%ls</url>
<urlcid>http://social.ugnet.gay/Profile.aspx?partner=Messenger&amp;mkt=en-us&amp;cid=%ls</urlcid>
<urlcid2>http://cid-%1!16.16I64X!.profile.live.com</urlcid2>
<SiteId>73625</SiteId>
</Profile>
<SNInvites>
<url>http://cid-%1.profile.live.com/connect/Messenger.aspx?Email=%2</url>
<urlcid>http://cid-%1.profile.live.com/connect/Messenger.aspx?cid=0x%2</urlcid>
<SiteId>73625</SiteId>
</SNInvites>
<ViewMapEnabled>true</ViewMapEnabled>
</Contacts>
<ContactCard>
<AddToMySpaceSiteId>45930</AddToMySpaceSiteId>
<AddToMySpaceUrl>http://social.ugnet.gay/?addblogentry=true&amp;mkt=nl-nl</AddToMySpaceUrl>
<ContactCardDisabled>false</ContactCardDisabled>
<CreateSpaceSiteId>45930</CreateSpaceSiteId>
<CreateSpaceUrl>http://social.ugnet.gay/signup.aspx?mkt=nl-nl</CreateSpaceUrl>
<GetItemVerUrl>http://ctas.storage.ugnet.gay/storageservice/schematizedstore.asmx</GetItemVerUrl>
<GetXmlFeedUrl>http://social.ugnet.gay/contactcard/contactcardservice.asmx</GetXmlFeedUrl>
<MySpaceSiteId>45930</MySpaceSiteId>
<MySpaceUrl>http://social.ugnet.gay/homepage.aspx</MySpaceUrl>
<SpaceBaseSiteId>45930</SpaceBaseSiteId>
<SpaceBaseUrl>http://social.ugnet.gay</SpaceBaseUrl>
<SpaceIntegrationEnabled>true</SpaceIntegrationEnabled>
</ContactCard>
<FlashUpgradeURL>http://storage.ugnet.gay/crosstalk-dist/client/all/tools/flashplayer_10_3r183_48_winax.exe</FlashUpgradeURL>
<GLinkMarket v="en_us" />
<LiveFolders UpsellMessageId="1" />
<MessengerBlogURL>https://crosstalk.im/blog</MessengerBlogURL>
<MSNSearch>
<DesktopInstallURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</DesktopInstallURL>
<ImagesURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=images</ImagesURL>
<NearMeURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</NearMeURL>
<NewsURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$+news&amp;ia=news</NewsURL>
<PeopleSearchURL>http://home.live.com/search?query=$QUERY$</PeopleSearchURL>
<PeopleSearchSiteID>73625</PeopleSearchSiteID>
<SearchKidsURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SearchKidsURL>
<SearchURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SearchURL>
<SharedSearchURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SharedSearchURL>
<SharedSearchURL2>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SharedSearchURL2>
</MSNSearch>
<MsnTodayConfig>
<MsnTodaySiteID>6528</MsnTodaySiteID>
<MsnTodayURL>http://today.msgrsvcs.ctsrv.gay/start?wlm=1</MsnTodayURL>
<Flags>2</Flags>
</MsnTodayConfig>
<MusicIntegration URL="https://www.last.fm/search/tracks?q=$ARTIST$+$TITLE$"/>
<OneCare Enabled="0" />
<PE Tracking=""/>
<PremiumAV Visibility="1" />
<PSTNOut Hidden="0" />
<ReportAbuse>
<ReportAbuseSID />
<ReportAbuseURL>https://crosstalk.im/report</ReportAbuseURL>
</ReportAbuse>
<RL>
<ViewProfileURL>http://g.msn.com/5meen_us/106?%1&amp;Plcid=%2!hs!&amp;%3&amp;Country=%4!hs!&amp;BrandID=%5&amp;passport=%6</ViewProfileURL>
</RL>
<SDrive Enabled="true" />
<TermsOfUse>
<TermsOfUseSID>956</TermsOfUseSID>
<TermsOfUseURL>https://crosstalk.im/tos</TermsOfUseURL>
</TermsOfUse>
<VoiceClip Hidden="0" />
<VoiceVideo>
<DisableSipProxyInviteTest>0</DisableSipProxyInviteTest>
<DisableSipProxyCapability>0</DisableSipProxyCapability>
<DisableSipProxyInvite>0</DisableSipProxyInvite>
<DisableSipProxyCapability2>0</DisableSipProxyCapability2>
<DisableSipProxyInvite2>0</DisableSipProxyInvite2>
</VoiceVideo>
<TabConfig>
<RowNumber>1</RowNumber>
<slots>
{% for tab in tabs %}
<URL id="{{ tab.id }}">
https://ctsvcs.advertising.ugnet.gay/svcs/tab={{ tab.id }}
</URL>
{% endfor %}
</slots>
</TabConfig>
</LocalizedConfig>
</MsgrConfig>
@@ -1,73 +1,5 @@
{%- set is_wlm = variant in ('wlm8', 'wlm14', 'wlm16') -%} <?xml version="1.0" encoding="utf-8" ?>
{%- 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() -%}
<MsgrConfig> <MsgrConfig>
{%- if variant == 'wlm16' %}
<Brands> <Brands>
<Client v="def" bv="1.0.1.0"> <Client v="def" bv="1.0.1.0">
<b i="FT01" v="1.0.5.0" f="FT01_fr-fr_R4.cab" u="http://g.msn.com/0USWLPIT/9" p="FT01" /> <b i="FT01" v="1.0.5.0" f="FT01_fr-fr_R4.cab" u="http://g.msn.com/0USWLPIT/9" p="FT01" />
@@ -77,33 +9,23 @@
<Client v="2" CDNVER="http://cba.domains.live.com/cdn1" CDNCAB="http://cba.domains.live.com/cdn3" CDNPRV="http://cba.domains.live.com/prvw" /> <Client v="2" CDNVER="http://cba.domains.live.com/cdn1" CDNCAB="http://cba.domains.live.com/cdn3" CDNPRV="http://cba.domains.live.com/prvw" />
<Client v="3" CDNVER="http://cba.domains.live.com/cdn1" CDNCAB="http://cba.domains.live.com/cdn3" CDNPRV="http://cba.domains.live.com/prvw" /> <Client v="3" CDNVER="http://cba.domains.live.com/cdn1" CDNCAB="http://cba.domains.live.com/cdn3" CDNPRV="http://cba.domains.live.com/prvw" />
</Brands> </Brands>
{%- endif %}
<Simple> <Simple>
<Config> <Config>
<ExpiresInDays>{{ 2 if variant == 'wlm16' else 0 }}</ExpiresInDays> <ExpiresInDays>2</ExpiresInDays>
</Config> </Config>
{%- if is_wlm14_up %}
<P2PConfig> <P2PConfig>
<ObjectStore> <ObjectStore>
<SendDelay>1</SendDelay> <SendDelay>1</SendDelay>
</ObjectStore> </ObjectStore>
</P2PConfig> </P2PConfig>
{%- endif %} <DisablePhoneDialer>1</DisablePhoneDialer>
<DisablePhoneDialer>{{ 0 if variant == 'wlm8' else 1 }}</DisablePhoneDialer>
{%- if is_wlm %}
<GetItemVersionForUnknown>false</GetItemVersionForUnknown> <GetItemVersionForUnknown>false</GetItemVersionForUnknown>
{%- endif %}
<Logitech> <Logitech>
<PremiumAVConfigServer>http://ms.msgrsvcs.ctsrv.xyz/locate.sxml</PremiumAVConfigServer> <PremiumAVConfigServer>http://mplocate.spotlife.net/locate.sxml</PremiumAVConfigServer>
<PreRollEnabled>1</PreRollEnabled> <PreRollEnabled>1</PreRollEnabled>
<WebcamConfigServer>http://ms.msgrsvcs.ctsrv.xyz/locate.sxml</WebcamConfigServer> <WebcamConfigServer>http://mlocate.spotlife.net/locate.sxml</WebcamConfigServer>
</Logitech> </Logitech>
{%- if variant == 'msn' %}
<MinFlashPlayer BuildNumber="60" MajorVersion="7" MinorVersion="0" />
{%- else %}
<MinFlashPlayer BuildNumber="28" MajorVersion="9" MinorVersion="0" /> <MinFlashPlayer BuildNumber="28" MajorVersion="9" MinorVersion="0" />
{%- endif %}
{%- if variant == 'wlm16' %}
<RadUrl Tracking="http://global.msads.net/ads/abuimg/%PACKID%.xml">http://rad.msn.com/ADSAdClient31.dll?GetAd?PG=</RadUrl> <RadUrl Tracking="http://global.msads.net/ads/abuimg/%PACKID%.xml">http://rad.msn.com/ADSAdClient31.dll?GetAd?PG=</RadUrl>
<ComScoreUrlFormat>http://b.scorecardresearch.com/p?c1=7&amp;c2=3000001&amp;c3=%1!d!&amp;cj=1</ComScoreUrlFormat> <ComScoreUrlFormat>http://b.scorecardresearch.com/p?c1=7&amp;c2=3000001&amp;c3=%1!d!&amp;cj=1</ComScoreUrlFormat>
<Relay> <Relay>
@@ -113,25 +35,11 @@
<RelayDNS>avrelay.msn.com</RelayDNS> <RelayDNS>avrelay.msn.com</RelayDNS>
<TimeoutToFallback>7000</TimeoutToFallback> <TimeoutToFallback>7000</TimeoutToFallback>
</Relay> </Relay>
{%- else %}
<Relay>
<Enabled>0</Enabled>
<MaxCallLength>0</MaxCallLength>
</Relay>
{%- endif %}
{%- if variant == 'wlm14' %}
<Contacts>
<Client ZombieServerDetectDelay="1800" ZombieServerDetectInterval="30" ZombieServerDetectResumeDelay="1800" />
<Server ZombieServerDetectDelay="900" ZombieServerDetectResumeDelay="900" ZombieServerDetectConnectDelay="900" ZombieServerDetectLongDelay="900" />
</Contacts>
{%- elif variant == 'wlm16' %}
<Contacts> <Contacts>
<Client ZombieServerDetectDelay="1800" ZombieServerDetectInterval="30" ZombieServerDetectResumeDelay="1800" ZombieServerDetectDelayW4="180" ZombieServerDetectIntervalW4="30" ZombieServerDetectResumeDelayW4="180" /> <Client ZombieServerDetectDelay="1800" ZombieServerDetectInterval="30" ZombieServerDetectResumeDelay="1800" ZombieServerDetectDelayW4="180" ZombieServerDetectIntervalW4="30" ZombieServerDetectResumeDelayW4="180" />
<Server ZombieServerDetectDelay="900" ZombieServerDetectResumeDelay="900" ZombieServerDetectConnectDelay="900" ZombieServerDetectLongDelay="900" ZombieServerDetectDelayW4="45" ZombieServerDetectResumeDelayW4="600" ZombieServerDetectConnectDelayW4="135" ZombieServerDetectLongDelayW4="450" /> <Server ZombieServerDetectDelay="900" ZombieServerDetectResumeDelay="900" ZombieServerDetectConnectDelay="900" ZombieServerDetectLongDelay="900" ZombieServerDetectDelayW4="45" ZombieServerDetectResumeDelayW4="600" ZombieServerDetectConnectDelayW4="135" ZombieServerDetectLongDelayW4="450" />
</Contacts> </Contacts>
{%- endif %}
<TrustedDomains> <TrustedDomains>
{%- if variant == 'wlm16' %}
<domain name="bluemountaincards.co.uk" /> <domain name="bluemountaincards.co.uk" />
<domain name="bluemountaincards.com.au" /> <domain name="bluemountaincards.com.au" />
<domain name="bmamessenger.com" /> <domain name="bmamessenger.com" />
@@ -228,42 +136,95 @@
<domain name="kiwee.com" /> <domain name="kiwee.com" />
<domain name="live.mundijuegos.com" /> <domain name="live.mundijuegos.com" />
<domain name="skype.com" /> <domain name="skype.com" />
{%- endif %} <domain name="hiden.cc"/>
{%- for domain in trusted_domains %} <domain name="ugnet.gay"/>
<domain name="{{ domain }}" /> <domain name="crosstalk.im"/>
{%- endfor %} <domain name="ctsrv.gay"/>
</TrustedDomains> </TrustedDomains>
<ErrorResponseTable> <ErrorResponseTable>
<Feature type="0" name="Login"> <Feature type="0" name="Login">
{%- for hr, action in error_login[variant] %} <Entry hr="*" action="3" />
<Entry hr="{{ hr }}" action="{{ action }}" /> <Entry hr="0x81000605" action="3" />
{%- endfor %} <Entry hr="0x80048849" action="5" />
<Entry hr="0x8004882A" action="5" />
<Entry hr="0x80048800" action="5" />
<Entry hr="0x8004889C" action="5" />
<Entry hr="0x80048831" action="5" />
<Entry hr="0x81000306" action="5" />
<Entry hr="0x80048862" action="5" />
<Entry hr="0x800488EB" action="5" />
<Entry hr="0x80048848" action="5" />
<Entry hr="0x80004002" action="3" />
<Entry hr="0x80004004" action="3" />
<Entry hr="0x80004005" action="3" />
<Entry hr="0x8000402A" action="3" />
<Entry hr="0x8000FFFF" action="3" />
<Entry hr="0x8001012E" action="3" />
<Entry hr="0x80040200" action="3" />
<Entry hr="0x80048051" action="3" />
<Entry hr="0x80048820" action="5" />
<Entry hr="0x80048823" action="3" />
<Entry hr="0x80070002" action="3" />
<Entry hr="0x80070005" action="3" />
<Entry hr="0x8007000E" action="3" />
<Entry hr="0x80070057" action="3" />
<Entry hr="0x8007007E" action="3" />
<Entry hr="0x800702E4" action="3" />
<Entry hr="0x800706BA" action="3" />
<Entry hr="0x800706BE" action="3" />
<Entry hr="0x80071392" action="3" />
<Entry hr="0x80072745" action="3" />
<Entry hr="0x80072746" action="3" />
<Entry hr="0x80072EE2" action="3" />
<Entry hr="0x80072EF3" action="3" />
<Entry hr="0x80072EFD" action="3" />
<Entry hr="0x80072EFF" action="3" />
<Entry hr="0x80072F06" action="3" />
<Entry hr="0x80072F7D" action="3" />
<Entry hr="0x800C013E" action="3" />
<Entry hr="0x80191002" action="3" />
<Entry hr="0x8100030D" action="3" />
<Entry hr="0x81000314" action="3" />
<Entry hr="0x81000362" action="3" />
<Entry hr="0x81000378" action="3" />
<Entry hr="0x81000395" action="3" />
<Entry hr="0x85AE000B" action="3" />
<Entry hr="0x85AE000F" action="3" />
<Entry hr="0x85AE001D" action="3" />
<Entry hr="0x85AE0022" action="3" />
<Entry hr="0x85AE0024" action="3" />
<Entry hr="0x85AE0027" action="3" />
<Entry hr="0x85AE003C" action="3" />
<Entry hr="0x85AE0053" action="3" />
<Entry hr="0x8E5E0152" action="3" />
<Entry hr="0x8E5E0158" action="3" />
<Entry hr="0x8E5E0211" action="3" />
<Entry hr="0x8E5E0220" action="3" />
<Entry hr="0x8E5E0226" action="3" />
<Entry hr="0x8E5E03FE" action="3" />
<Entry hr="0x8E5E0408" action="3" />
<Entry hr="0x8E5E05F6" action="3" />
<Entry hr="0x8E5E0710" action="3" />
<Entry hr="0x8E5E0713" action="3" />
</Feature> </Feature>
<Feature type="2" name="MapFile"> <Feature type="2" name="MapFile">
{%- for hr, action in error_mapfile[variant] %} <Entry hr="0x810003F1" action="3" />
<Entry hr="{{ hr }}" action="{{ action }}" /> <Entry hr="0x810003F6" action="3" />
{%- endfor %}
</Feature> </Feature>
{%- if variant in error_p2p %}
<Feature type="3" name="P2P"> <Feature type="3" name="P2P">
{%- for hr, action in error_p2p[variant] %} <Entry hr="0x82000016" action="3" />
<Entry hr="{{ hr }}" action="{{ action }}" /> <Entry hr="0x82000017" action="3" />
{%- endfor %} <Entry hr="0x82000019" action="3" />
<Entry hr="0x8200001b" action="3" />
<Entry hr="0x8200001d" action="3" />
<Entry hr="0x8200001e" action="3" />
<Entry hr="0x82000024" action="3" />
<Entry hr="0x82000026" action="3" />
</Feature> </Feature>
{%- endif %}
{%- if variant == 'wlm16' %}
<Feature type="5" name="VoiceVideo"> <Feature type="5" name="VoiceVideo">
<Entry hr="*" action="3" /> <Entry hr="*" action="3" />
</Feature> </Feature>
{%- endif %}
</ErrorResponseTable> </ErrorResponseTable>
{%- if variant == 'wlm14' %}
<USBDevices>
<Device VID="0x045e" PID="0x0719"/>
<Device VID="0x045e" PID="0x0722"/>
<Device VID="0x041e" PID="0x4080"/>
</USBDevices>
{%- elif variant == 'wlm16' %}
<USBDevices> <USBDevices>
<Device VID="0x045e" PID="0x0719" /> <Device VID="0x045e" PID="0x0719" />
<Device VID="0x045e" PID="0x070F" /> <Device VID="0x045e" PID="0x070F" />
@@ -277,14 +238,10 @@
<VoiceVideo> <VoiceVideo>
<Log PeerLogDisable="1" /> <Log PeerLogDisable="1" />
</VoiceVideo> </VoiceVideo>
{%- endif %} <CirclesWeb General="https://crosstalk.im/circles/$CIRCLECID$/settings/" General-SiteId="73625" Management="https://crosstalk.im/circles/$CIRCLECID$/settings/" Management-SiteId="73625" Membership="https://crosstalk.im/circles/$CIRCLECID$/settings/" Membership-SiteId="73625" Leave="https://crosstalk.im/circles/$CIRCLECID$/settings/" Leave-SiteId="73625" Disc="https://crosstalk.im/" />
{%- if is_wlm14_up %}
<CirclesWeb General="https://{{ settings.WEBSITE_HOST }}/circles/$CIRCLECID$/settings/" General-SiteId="73625" Management="https://{{ settings.WEBSITE_HOST }}/circles/$CIRCLECID$/settings/" Management-SiteId="73625" Membership="https://{{ settings.WEBSITE_HOST }}/circles/$CIRCLECID$/settings/" Membership-SiteId="73625" Leave="https://{{ settings.WEBSITE_HOST }}/circles/$CIRCLECID$/settings/" Leave-SiteId="73625" Disc="https://{{ settings.WEBSITE_HOST }}" />
<AnonymousIMSettings> <AnonymousIMSettings>
<SettingsPage URL="http://settings.messenger.live.com/applications/WebSettings.aspx" SiteID="76215" /> <SettingsPage URL="http://settings.messenger.live.com/applications/WebSettings.aspx" SiteID="76215" />
</AnonymousIMSettings> </AnonymousIMSettings>
{%- endif %}
{%- if variant == 'wlm16' %}
<SocialNews> <SocialNews>
<ActivityDisplay PageSize="50" MaxItems="100" /> <ActivityDisplay PageSize="50" MaxItems="100" />
<AlbumDisplay UnderlayImages="2" LeadUnderlayImages="2" /> <AlbumDisplay UnderlayImages="2" LeadUnderlayImages="2" />
@@ -534,135 +491,39 @@
<Entry Flags="10" Options="1" VendorId="8086" Minimum="8.15.10.2104" Version="8.15.10.2142" /> <Entry Flags="10" Options="1" VendorId="8086" Minimum="8.15.10.2104" Version="8.15.10.2142" />
</List> </List>
</HwBlockList> </HwBlockList>
{%- endif %}
</Simple> </Simple>
{%- if variant in ('msn', 'wlm8') %}
<TabConfig>
{% include 'msn:svcs/svcs_tabs.xml' %}
</TabConfig>
{%- endif %}
<AbchCfg> <AbchCfg>
<abchconfig> <abchconfig>
<url>https://{{ settings.ADDRESSBOOK_HOST }}/abservice.asmx</url> <url>https://ctsvcs.addressbook.ugnet.gay/abservice.asmx</url>
</abchconfig> </abchconfig>
</AbchCfg> </AbchCfg>
{%- if variant == 'wlm16' %}
<AdMainConfig> <AdMainConfig>
<AdDownloadTimeInMinutes>120</AdDownloadTimeInMinutes> <AdDownloadTimeInMinutes>120</AdDownloadTimeInMinutes>
<AdMainCfg>http://{{ settings.AD_HOST }}/ads/banner</AdMainCfg> <AdMainCfg>http://ctsvcs.advertising.ugnet.gay/ads/banner</AdMainCfg>
</AdMainConfig> </AdMainConfig>
<AdPhoneConfig>http://{{ settings.AD_HOST }}/ads/banner</AdPhoneConfig> <AdPhoneConfig>http://ctsvcs.advertising.ugnet.gay/ads/banner</AdPhoneConfig>
{%- endif %}
<LocalizedConfig Market="en-US"> <LocalizedConfig Market="en-US">
<AdMainConfig> <AdMainConfig>
{%- if variant == 'wlm16' %} <AdBanner20URL Refresh="390">http://ctsvcs.advertising.ugnet.gay/ads/banner</AdBanner20URL>
<AdBanner20URL Refresh="390">http://{{ settings.AD_HOST }}/ads/banner</AdBanner20URL> <AdBanner300URL Refresh="390" FooterPane="AlwaysShown">http://ctsvcs.advertising.ugnet.gay/ads/banner-lg</AdBanner300URL>
<AdBanner300URL Refresh="390" FooterPane="AlwaysShown">http://{{ settings.AD_HOST }}/ads/banner-lg</AdBanner300URL>
<ConvoWinAd AdVisible="420" FooterPane="CollapsibleAndHideable" /> <ConvoWinAd AdVisible="420" FooterPane="CollapsibleAndHideable" />
<ConvoWinAdBannerURL>http://{{ settings.AD_HOST }}/ads/banner</ConvoWinAdBannerURL> <ConvoWinAdBannerURL>http://ctsvcs.advertising.ugnet.gay/ads/banner</ConvoWinAdBannerURL>
{%- else %}
<AdBanner20URL Refresh="300">http://{{ settings.AD_HOST }}/ads/banner</AdBanner20URL>
{%- endif %}
{%- if is_wlm %}
<StdAd AdVisible="60" VideoVisible="120" VideoDldIntvl="0"> <StdAd AdVisible="60" VideoVisible="120" VideoDldIntvl="0">
<VideoFeeds FeedsListURL="http://{{ settings.AD_HOST }}/svcs/msn-video-feeds/" /> <VideoFeeds FeedsListURL="http://ctsvcs.advertising.ugnet.gay/svcs/msn-video-feeds/"/>
</StdAd> </StdAd>
{%- endif %}
{%- if is_wlm14_up %}
<TextAdRotation>420</TextAdRotation> <TextAdRotation>420</TextAdRotation>
{%- endif %}
<TextAdRefresh>1</TextAdRefresh> <TextAdRefresh>1</TextAdRefresh>
<TextAdServer>{{ 'https' if variant == 'wlm16' else 'http' }}://{{ settings.AD_HOST }}/ads/txt</TextAdServer> <TextAdServer>https://ctsvcs.advertising.ugnet.gay/ads/txt</TextAdServer>
{%- if variant == 'wlm16' %}
<Window Size="680" /> <Window Size="680" />
{%- endif %}
</AdMainConfig> </AdMainConfig>
<AppDirConfig> <AppDirConfig>
{%- set appdir = ('https' if variant == 'wlm16' else 'http') ~ '://' ~ settings.APPDIR_HOST ~ '/AppDirectory' %} <AppDirPageURL>https://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/Directory.aspx?L=en-us</AppDirPageURL>
<AppDirPageURL>{{ appdir }}/Directory.aspx?L=en-us</AppDirPageURL> <AppDirSeviceURL>https://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/AppDirectory.asmx</AppDirSeviceURL>
<AppDirSeviceURL>{{ appdir }}/AppDirectory.asmx</AppDirSeviceURL> <AppDirVersionURL>https://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/GetAppdirVersion.aspx</AppDirVersionURL>
<AppDirVersionURL>{{ appdir }}/GetAppdirVersion.aspx</AppDirVersionURL>
</AppDirConfig> </AppDirConfig>
{%- if variant == 'wlm16' %}
<AVPrerollAd FetchTimeout="6900" IntroLength="3000" MinAdLength="7000" URL="http://rad.msn.com/ADSAdClient31.dll?GetAd=&amp;PG=IMUSV1" /> <AVPrerollAd FetchTimeout="6900" IntroLength="3000" MinAdLength="7000" URL="http://rad.msn.com/ADSAdClient31.dll?GetAd=&amp;PG=IMUSV1" />
<AVPrerollAd2 FetchTimeout="6900" IntroLength="0" MinAdLength="7000" URL="http://rad.msn.com/ADSAdClient31.dll?GetAd=&amp;PG=IMUVD1" /> <AVPrerollAd2 FetchTimeout="6900" IntroLength="0" MinAdLength="7000" URL="http://rad.msn.com/ADSAdClient31.dll?GetAd=&amp;PG=IMUVD1" />
<BuyWebcamLink URL="http://www.logitech.com/msn/index.cfm?c=US&amp;l=EN" /> <BuyWebcamLink URL="http://www.logitech.com/msn/index.cfm?c=US&amp;l=EN" />
{%- endif %}
{%- if variant == 'wlm8' %}
<Contacts>
<ABPendingRequests>
<url>http://{{ settings.SOCIAL_HOST }}/PendingRequests.aspx?mkt=en-us&amp;partner=Messenger</url>
<siteid>73625</siteid>
<height>672</height>
<width>808</width>
</ABPendingRequests>
<BuddysSocialNetwork>
<url>http://{{ settings.SOCIAL_HOST }}/NetworkExplorer.aspx?mkt=en-us&amp;partner=Messenger&amp;cid=%1</url>
<siteid>73625</siteid>
<height>674</height>
<width>808</width>
</BuddysSocialNetwork>
<EditMyLiveContactProfile>
<url>http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&amp;mode=activecontacts&amp;mkt=en-us&amp;partner=Messenger</url>
<siteid>73625</siteid>
</EditMyLiveContactProfile>
<EditMyProfile>
<url>http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&amp;partner=Messenger&amp;mkt=en-us</url>
<siteid>73625</siteid>
</EditMyProfile>
<Profile>
<url>http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&amp;mkt=en-us&amp;mem=%ls</url>
<urlcid>http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&amp;mkt=en-us&amp;cid=%ls</urlcid>
<siteid>73625</siteid>
</Profile>
<SocialNetwork>
<url>http://{{ settings.SOCIAL_HOST }}/NetworkSetup.aspx?mkt=en-us&amp;partner=Messenger</url>
<siteid>73625</siteid>
<height>674</height>
<width>808</width>
</SocialNetwork>
<ViewMapEnabled>false</ViewMapEnabled>
</Contacts>
{%- elif variant == 'wlm14' %}
<Contacts>
<ABPendingRequests>
<SiteId>73625</SiteId>
<height>672</height>
<IncludeSNRequests>true</IncludeSNRequests>
<width>808</width>
<urlcid>http://cid-%1!16.16I64X!.profile.live.com/invites?partner=Messenger</urlcid>
</ABPendingRequests>
<EditMyLiveContactProfile>
<url>http://{{ settings.SOCIAL_HOST }}/profile.aspx?action=edit&amp;mode=activecontacts&amp;mkt=en-us&amp;partner=Messenger</url>
<SiteId>73625</SiteId>
</EditMyLiveContactProfile>
<EditMyProfile>
<url>http://profile.live.com/details</url>
<SiteId>73625</SiteId>
</EditMyProfile>
<Import>
<url>http://cid-%1!16.16I64X!.profile.live.com/connect/?partner=Messenger</url>
<SiteId>73625</SiteId>
</Import>
<MessengerInvite>
<url>http://cid-%1.profile.live.com/connect/send.aspx?email=%2</url>
<urlcid>http://cid-%1.profile.live.com/connect/send.aspx?cid=%2</urlcid>
<SiteId>73625</SiteId>
</MessengerInvite>
<Profile>
<url>http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&amp;mkt=en-us&amp;mem=%ls</url>
<urlcid>http://{{ settings.SOCIAL_HOST }}/Profile.aspx?partner=Messenger&amp;mkt=en-us&amp;cid=%ls</urlcid>
<urlcid2>http://cid-%1!16.16I64X!.profile.live.com</urlcid2>
<SiteId>73625</SiteId>
</Profile>
<SNInvites>
<url>http://cid-%1.profile.live.com/connect/Messenger.aspx?Email=%2</url>
<urlcid>http://cid-%1.profile.live.com/connect/Messenger.aspx?cid=0x%2</urlcid>
<SiteId>73625</SiteId>
</SNInvites>
<ViewMapEnabled>true</ViewMapEnabled>
</Contacts>
{%- elif variant == 'wlm16' %}
<Contacts> <Contacts>
<ABPendingRequests> <ABPendingRequests>
<SiteId>73625</SiteId> <SiteId>73625</SiteId>
@@ -752,59 +613,29 @@
</ViewPhotosWLPersonURL> </ViewPhotosWLPersonURL>
<ViewMapEnabled>true</ViewMapEnabled> <ViewMapEnabled>true</ViewMapEnabled>
</Contacts> </Contacts>
{%- endif %}
{%- if variant in ('wlm8', 'wlm14') %}
<ContactCard>
<AddToMySpaceSiteId>45930</AddToMySpaceSiteId>
<AddToMySpaceUrl>http://{{ settings.SOCIAL_HOST }}/?addblogentry=true&amp;mkt=nl-nl</AddToMySpaceUrl>
<ContactCardDisabled>false</ContactCardDisabled>
<CreateSpaceSiteId>45930</CreateSpaceSiteId>
<CreateSpaceUrl>http://{{ settings.SOCIAL_HOST }}/signup.aspx?mkt=nl-nl</CreateSpaceUrl>
{%- if variant == 'wlm8' %}
<GetItemVerUrl>http://storage.msn.com/storageservice/schematizedstore.asmx</GetItemVerUrl>
<GetXmlFeedUrl>http://services.{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx</GetXmlFeedUrl>
{%- else %}
<GetItemVerUrl>http://ctas.storage.ugnet.xyz/storageservice/schematizedstore.asmx</GetItemVerUrl>
<GetXmlFeedUrl>http://{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx</GetXmlFeedUrl>
{%- endif %}
<MySpaceSiteId>45930</MySpaceSiteId>
<MySpaceUrl>http://{{ settings.SOCIAL_HOST }}/homepage.aspx</MySpaceUrl>
<SpaceBaseSiteId>45930</SpaceBaseSiteId>
<SpaceBaseUrl>http://{{ settings.SOCIAL_HOST }}</SpaceBaseUrl>
<SpaceIntegrationEnabled>true</SpaceIntegrationEnabled>
</ContactCard>
{%- elif variant == 'wlm16' %}
<ContactCard> <ContactCard>
<AddToMySpaceSiteId>73625</AddToMySpaceSiteId> <AddToMySpaceSiteId>73625</AddToMySpaceSiteId>
<AddToMySpaceUrl>http://{{ settings.SOCIAL_HOST }}/?addblogentry=true&amp;mkt=en-us</AddToMySpaceUrl> <AddToMySpaceUrl>http://social.ugnet.gay/?addblogentry=true&amp;mkt=en-us</AddToMySpaceUrl>
<ContactCardDisabled>false</ContactCardDisabled> <ContactCardDisabled>false</ContactCardDisabled>
<CreateSpaceSiteId>73625</CreateSpaceSiteId> <CreateSpaceSiteId>73625</CreateSpaceSiteId>
<CreateSpaceUrl>http://{{ settings.SOCIAL_HOST }}</CreateSpaceUrl> <CreateSpaceUrl>http://social.ugnet.gay</CreateSpaceUrl>
<GetItemVerUrl>http://storage.msn.com/storageservice/schematizedstore.asmx</GetItemVerUrl> <GetItemVerUrl>http://storage.msn.com/storageservice/schematizedstore.asmx</GetItemVerUrl>
<GetXmlFeedUrl>http://cc.services.{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx</GetXmlFeedUrl> <GetXmlFeedUrl>http://cc.services.social.ugnet.gay/contactcard/contactcardservice.asmx</GetXmlFeedUrl>
<GetXmlFeedRpsUrl>http://cc.services.{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx</GetXmlFeedRpsUrl> <GetXmlFeedRpsUrl>http://cc.services.social.ugnet.gay/contactcard/contactcardservice.asmx</GetXmlFeedRpsUrl>
<GetXmlFeedRpsCidUrl>http://cid-%1!16.16I64X!.cc.services.{{ settings.SOCIAL_HOST }}/contactcard/contactcardservice.asmx</GetXmlFeedRpsCidUrl> <GetXmlFeedRpsCidUrl>http://cid-%1!16.16I64X!.cc.services.social.ugnet.gay/contactcard/contactcardservice.asmx</GetXmlFeedRpsCidUrl>
<MySpaceSiteId>73625</MySpaceSiteId> <MySpaceSiteId>73625</MySpaceSiteId>
<MySpaceUrl>http://{{ settings.SOCIAL_HOST }}</MySpaceUrl> <MySpaceUrl>http://social.ugnet.gay</MySpaceUrl>
<SpaceBaseSiteId>73625</SpaceBaseSiteId> <SpaceBaseSiteId>73625</SpaceBaseSiteId>
<SpaceBaseUrl>http://{{ settings.SOCIAL_HOST }}</SpaceBaseUrl> <SpaceBaseUrl>http://social.ugnet.gay</SpaceBaseUrl>
<SpaceIntegrationEnabled>true</SpaceIntegrationEnabled> <SpaceIntegrationEnabled>true</SpaceIntegrationEnabled>
</ContactCard> </ContactCard>
<EditorialConfig>http://www.msn.com/infopane/messenger.armx</EditorialConfig> <EditorialConfig>http://www.msn.com/infopane/messenger.armx</EditorialConfig>
{%- endif %} <FlashUpgradeURL>http://storage.ugnet.gay/crosstalk-dist/client/all/tools/flashplayer_10_3r183_48_winax.exe</FlashUpgradeURL>
{%- if is_wlm %}
<FlashUpgradeURL>http://{{ settings.STORAGE_HOST }}/crosstalk-dist/client/all/tools/flashplayer_10_3r183_48_winax.exe</FlashUpgradeURL>
{%- endif %}
{%- if variant == 'wlm16' %}
<FSS> <FSS>
<SiteID>71659</SiteID> <SiteID>71659</SiteID>
<AddBuddyURL>https://fss.live.com/krl/AddContact.aspx</AddBuddyURL> <AddBuddyURL>https://fss.live.com/krl/AddContact.aspx</AddBuddyURL>
</FSS> </FSS>
{%- endif %}
{%- if is_wlm %}
<GLinkMarket v="en_us" /> <GLinkMarket v="en_us" />
{%- endif %}
{%- if variant == 'wlm16' %}
<Highlight> <Highlight>
<FirstRunURLSet> <FirstRunURLSet>
<FirstRunURL id="1"> <FirstRunURL id="1">
@@ -828,81 +659,42 @@
</Wave> </Wave>
</Highlight> </Highlight>
<IntroConfig /> <IntroConfig />
{%- endif %}
{%- if is_wlm14_up %}
<LiveFolders UpsellMessageId="1" /> <LiveFolders UpsellMessageId="1" />
{%- endif %}
{%- if variant == 'wlm16' %}
<Marketplace> <Marketplace>
<General URL="http://www.microsoft.com/windowslivedevices/marketplace/default.aspx" /> <General URL="http://www.microsoft.com/windowslivedevices/marketplace/default.aspx" />
<Webcam URL="http://www.microsoft.com/windowslivedevices/marketplace/default.aspx" /> <Webcam URL="http://www.microsoft.com/windowslivedevices/marketplace/default.aspx" />
</Marketplace> </Marketplace>
{%- endif %} <MessengerBlogURL>https://crosstalk.im/blog</MessengerBlogURL>
{%- if is_wlm %}
<MessengerBlogURL>https://{{ settings.WEBSITE_HOST }}/blog</MessengerBlogURL>
{%- endif %}
{%- if variant == 'wlm16' %}
<MobileMessaging Mode="RPPNew" CarrierList="" CrossSell="1" CharMax="140" MainWindowButton="true" OperatorPage="http://get.live.com/messenger/mobile" ValidRoutes="US;CA" /> <MobileMessaging Mode="RPPNew" CarrierList="" CrossSell="1" CharMax="140" MainWindowButton="true" OperatorPage="http://get.live.com/messenger/mobile" ValidRoutes="US;CA" />
{%- endif %}
<MSNSearch> <MSNSearch>
{%- if variant != 'wlm8' %} <DesktopInstallURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</DesktopInstallURL>
<DesktopInstallURL>{{ search_url }}&amp;ia=web</DesktopInstallURL> <ImagesURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=images</ImagesURL>
{%- endif %} <NearMeURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</NearMeURL>
<ImagesURL>{{ search_url }}&amp;ia=images</ImagesURL> <NewsURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$+news&amp;ia=news</NewsURL>
{%- if variant != 'wlm8' %}
<NearMeURL>{{ search_url }}&amp;ia=web</NearMeURL>
{%- endif %}
<NewsURL>{{ search_url }}+news&amp;ia=news</NewsURL>
{%- if is_wlm14_up %}
<PeopleSearchURL>http://home.live.com/search?query=$QUERY$</PeopleSearchURL> <PeopleSearchURL>http://home.live.com/search?query=$QUERY$</PeopleSearchURL>
<PeopleSearchSiteID>73625</PeopleSearchSiteID> <PeopleSearchSiteID>73625</PeopleSearchSiteID>
{%- endif %} <SearchKidsURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SearchKidsURL>
{%- if variant != 'wlm8' %} <SearchURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SearchURL>
<SearchKidsURL>{{ search_url }}&amp;ia=web</SearchKidsURL> <SharedSearchURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SharedSearchURL>
{%- endif %} <SharedSearchURL2>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SharedSearchURL2>
<SearchURL>{{ search_url }}&amp;ia=web</SearchURL>
<SharedSearchURL>{{ search_url }}&amp;ia=web</SharedSearchURL>
<SharedSearchURL2>{{ search_url }}&amp;ia=web</SharedSearchURL2>
</MSNSearch> </MSNSearch>
<MsnTodayConfig> <MsnTodayConfig>
{%- if variant == 'msn' %}
<MsnTodayURL>http://{{ settings.TODAY_HOST }}/start?msn=1</MsnTodayURL>
{%- else %}
<MsnTodaySiteID>6528</MsnTodaySiteID> <MsnTodaySiteID>6528</MsnTodaySiteID>
{%- if variant == 'wlm16' %} <MsnTodayURL>https://today.msgrsvcs.ctsrv.gay/start?windowslive=1</MsnTodayURL>
<MsnTodayURL>https://{{ settings.TODAY_HOST }}/start?windowslive=1</MsnTodayURL>
{%- else %}
<MsnTodayURL>http://{{ settings.TODAY_HOST }}/start?wlm=1</MsnTodayURL>
{%- endif %}
<Flags>2</Flags> <Flags>2</Flags>
{%- endif %}
</MsnTodayConfig> </MsnTodayConfig>
<MusicIntegration URL="https://www.last.fm/search/tracks?q=$ARTIST$+$TITLE$" /> <MusicIntegration URL="https://www.last.fm/search/tracks?q=$ARTIST$+$TITLE$"/>
{%- if variant in ('wlm8', 'wlm14') %}
<OneCare Enabled="0" />
{%- endif %}
{%- if variant == 'wlm16' %}
<PartnerFeeds> <PartnerFeeds>
<Feed Name="MSN" URL="https://{{ settings.TODAY_HOST }}/start?windowslive=1" Owner="MSN" /> <Feed Name="MSN" URL="https://today.msgrsvcs.ctsrv.gay/start?windowslive=1" Owner="MSN" />
<Feed Name="GAMES" URL="http://windowsphone.xbox.com/en-US/MessengerGames/TabConfig" Owner="GAMES" /> <Feed Name="GAMES" URL="http://windowsphone.xbox.com/en-US/MessengerGames/TabConfig" Owner="GAMES" />
</PartnerFeeds> </PartnerFeeds>
<PartnerFeedsSSL> <PartnerFeedsSSL>
<Feed Name="MSN" URL="https://{{ settings.TODAY_HOST }}/start?windowslive=1" Owner="MSN" /> <Feed Name="MSN" URL="https://today.msgrsvcs.ctsrv.gay/start?windowslive=1" Owner="MSN" />
<Feed Name="GAMES" URL="http://windowsphone.xbox.com/en-US/MessengerGames/TabConfig" Owner="GAMES" /> <Feed Name="GAMES" URL="http://windowsphone.xbox.com/en-US/MessengerGames/TabConfig" Owner="GAMES" />
</PartnerFeedsSSL> </PartnerFeedsSSL>
{%- endif %}
{%- if variant == 'wlm14' %}
<PE Tracking="" />
{%- elif variant == 'wlm16' %}
<PE Tracking="http://trackingw4.technodesignip.com/?ContentID=$ContentID$&amp;Click=$Click$" /> <PE Tracking="http://trackingw4.technodesignip.com/?ContentID=$ContentID$&amp;Click=$Click$" />
{%- endif %}
{%- if is_wlm14_up %}
<PremiumAV Visibility="1" /> <PremiumAV Visibility="1" />
{%- endif %} <PSTNOut Hidden="0" />
{%- if is_wlm %}
<PSTNOut Hidden="{{ 1 if variant == 'wlm8' else 0 }}" />
{%- endif %}
{%- if variant == 'wlm16' %}
<PublicFederated> <PublicFederated>
<YahooNetwork Enabled="true" OfflineIM="true" /> <YahooNetwork Enabled="true" OfflineIM="true" />
</PublicFederated> </PublicFederated>
@@ -910,25 +702,12 @@
<ReportAbuseSID /> <ReportAbuseSID />
<ReportAbuseURL>http://support.live.com/default.aspx?productkey=wlmessengerabuse</ReportAbuseURL> <ReportAbuseURL>http://support.live.com/default.aspx?productkey=wlmessengerabuse</ReportAbuseURL>
<BiciReportAbuseApiUrl>https://home.live.com/handlers/ReportAbuse.mvc</BiciReportAbuseApiUrl> <BiciReportAbuseApiUrl>https://home.live.com/handlers/ReportAbuse.mvc</BiciReportAbuseApiUrl>
<BiciReportAbuseApiServiceTarget>{{ settings.SOCIAL_HOST }}</BiciReportAbuseApiServiceTarget> <BiciReportAbuseApiServiceTarget>social.ugnet.gay</BiciReportAbuseApiServiceTarget>
</ReportAbuse> </ReportAbuse>
{%- elif is_wlm %}
<ReportAbuse>
<ReportAbuseSID />
<ReportAbuseURL>https://{{ settings.WEBSITE_HOST }}/report</ReportAbuseURL>
</ReportAbuse>
{%- endif %}
<RL> <RL>
{%- if is_wlm14_up %}
<ViewProfileURL>http://g.msn.com/5meen_us/106?%1&amp;Plcid=%2!hs!&amp;%3&amp;Country=%4!hs!&amp;BrandID=%5&amp;passport=%6</ViewProfileURL> <ViewProfileURL>http://g.msn.com/5meen_us/106?%1&amp;Plcid=%2!hs!&amp;%3&amp;Country=%4!hs!&amp;BrandID=%5&amp;passport=%6</ViewProfileURL>
{%- else %}
<ViewProfileURL>https://{{ settings.WEBSITE_HOST }}/account/settings</ViewProfileURL>
{%- endif %}
</RL> </RL>
{%- if is_wlm %}
<SDrive Enabled="true" /> <SDrive Enabled="true" />
{%- endif %}
{%- if variant == 'wlm16' %}
<ServiceAwareness> <ServiceAwareness>
<FindMoreUrl>http://cid-%1!16.16I64X!.profile.live.com/Services/</FindMoreUrl> <FindMoreUrl>http://cid-%1!16.16I64X!.profile.live.com/Services/</FindMoreUrl>
<FindMoreSiteId>73625</FindMoreSiteId> <FindMoreSiteId>73625</FindMoreSiteId>
@@ -966,22 +745,20 @@
<SocialToast> <SocialToast>
<SuppressedEmailDomain>windowslivemail.com</SuppressedEmailDomain> <SuppressedEmailDomain>windowslivemail.com</SuppressedEmailDomain>
</SocialToast> </SocialToast>
{%- endif %}
{%- if is_wlm14_up %}
<TabConfig> <TabConfig>
<RowNumber>1</RowNumber> <RowNumber>1</RowNumber>
<slots> <slots>
{%- for tab in tabs %} {% for tab in tabs %}
<URL id="{{ tab.id }}">https://{{ settings.AD_HOST }}/svcs/tab={{ tab.id }}</URL> <URL id="{{ tab.id }}">
{%- endfor %} https://ctsvcs.advertising.ugnet.gay/svcs/tab={{ tab.id }}
</slots> </URL>
</TabConfig> {% endfor %}
{%- endif %} </slots>
</TabConfig>
<TermsOfUse> <TermsOfUse>
<TermsOfUseSID>956</TermsOfUseSID> <TermsOfUseSID>956</TermsOfUseSID>
<TermsOfUseURL>https://{{ settings.WEBSITE_HOST }}/tos</TermsOfUseURL> <TermsOfUseURL>https://crosstalk.im/tos</TermsOfUseURL>
</TermsOfUse> </TermsOfUse>
{%- if variant == 'wlm16' %}
<UPUX> <UPUX>
<Product id="8" PartnerID="TD" ProductName="Winks" BrandName="Quebles Winks"> <Product id="8" PartnerID="TD" ProductName="Winks" BrandName="Quebles Winks">
<BasePurchaseURL LaunchWindowType="Messenger" SiteID="60025" URL="http://www.mobilemoney.com/partners/msnmessenger/webshop/winks.asp?pos=chatwindow&amp;contentID=$CONTENTID$" /> <BasePurchaseURL LaunchWindowType="Messenger" SiteID="60025" URL="http://www.mobilemoney.com/partners/msnmessenger/webshop/winks.asp?pos=chatwindow&amp;contentID=$CONTENTID$" />
@@ -1012,8 +789,6 @@
<BasePurchaseURL LaunchWindowType="Messenger" SiteID="258666" URL="http://themepackfactory.windowslive.com/default.aspx?tpf.loc=WKGetThis&amp;tpf.cid=$CONTENTID$" /> <BasePurchaseURL LaunchWindowType="Messenger" SiteID="258666" URL="http://themepackfactory.windowslive.com/default.aspx?tpf.loc=WKGetThis&amp;tpf.cid=$CONTENTID$" />
</Product> </Product>
</UPUX> </UPUX>
{%- endif %}
{%- if is_wlm %}
<VoiceClip Hidden="0" /> <VoiceClip Hidden="0" />
<VoiceVideo> <VoiceVideo>
<DisableSipProxyInviteTest>0</DisableSipProxyInviteTest> <DisableSipProxyInviteTest>0</DisableSipProxyInviteTest>
@@ -1021,27 +796,9 @@
<DisableSipProxyInvite>0</DisableSipProxyInvite> <DisableSipProxyInvite>0</DisableSipProxyInvite>
<DisableSipProxyCapability2>0</DisableSipProxyCapability2> <DisableSipProxyCapability2>0</DisableSipProxyCapability2>
<DisableSipProxyInvite2>0</DisableSipProxyInvite2> <DisableSipProxyInvite2>0</DisableSipProxyInvite2>
{%- if variant == 'wlm16' %}
<VideoMessages> <VideoMessages>
<Config EnableRecording="1" Length="30" /> <Config EnableRecording="1" Length="30" />
</VideoMessages> </VideoMessages>
{%- endif %}
</VoiceVideo> </VoiceVideo>
{%- endif %}
</LocalizedConfig> </LocalizedConfig>
</MsgrConfig> </MsgrConfig>
{%- endmacro -%}
{%- if soap -%}
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetClientConfigResponse xmlns="http://www.msn.com/webservices/Messenger/Client">
<GetClientConfigResult><![CDATA[{{ msgr_config() }}]]></GetClientConfigResult>
</GetClientConfigResponse>
</soap:Body>
</soap:Envelope>
{%- else -%}
<?xml version="1.0" encoding="utf-8" ?>
{{ msgr_config() }}
{%- endif -%}
@@ -0,0 +1,180 @@
<?xml version="1.0" encoding="utf-8" ?>
<MsgrConfig>
<Simple>
<Config>
<ExpiresInDays>0</ExpiresInDays>
</Config>
<DisablePhoneDialer>0</DisablePhoneDialer>
<GetItemVersionForUnknown>false</GetItemVersionForUnknown>
<MinFlashPlayer BuildNumber="28" MajorVersion="9" MinorVersion="0"/>
<Relay>
<Enabled>0</Enabled>
<MaxCallLength>0</MaxCallLength>
</Relay>
<TrustedDomains>
<domain name="hiden.cc"/>
<domain name="ugnet.gay"/>
<domain name="crosstalk.im"/>
<domain name="ctsrv.gay"/>
</TrustedDomains>
<ErrorResponseTable>
<Feature type="0" name="Login">
<Entry hr="0x80072EE7" action="3"/>
<Entry hr="0x81000306" action="3"/>
<Entry hr="0x80072EFD" action="3"/>
<Entry hr="0x81000362" action="3"/>
<Entry hr="0x8100030E" action="3"/>
<Entry hr="0x80072745" action="3"/>
<Entry hr="0x800701F7" action="3"/>
<Entry hr="0x80072EFF" action="3"/>
<Entry hr="0x81000363" action="3"/>
<Entry hr="0x81000395" action="3"/>
<Entry hr="0x800B0001" action="3"/>
<Entry hr="0x81000323" action="3"/>
<Entry hr="0x80072F19" action="3"/>
<Entry hr="0x800701F8" action="3"/>
<Entry hr="0x80072746" action="3"/>
<Entry hr="0x800701F6" action="3"/>
<Entry hr="0x81000377" action="3"/>
<Entry hr="0x81000314" action="3"/>
<Entry hr="0x81000378" action="3"/>
<Entry hr="0x80072EFF" action="3"/>
<Entry hr="0x80070190" action="3"/>
<Entry hr="0x80070197" action="3"/>
<Entry hr="0x80048820" action="3"/>
<Entry hr="0x80048829" action="3"/>
<Entry hr="0x80048834" action="3"/>
<Entry hr="0x80048852" action="3"/>
<Entry hr="0x8004886a" action="3"/>
<Entry hr="0x8004886b" action="3"/>
</Feature>
<Feature type="2" name="MapFile">
<Entry hr="0x810003F0" action="3"/>
<Entry hr="0x810003F1" action="3"/>
<Entry hr="0x810003F2" action="3"/>
<Entry hr="0x810003F3" action="3"/>
<Entry hr="0x810003F4" action="3"/>
<Entry hr="0x810003F5" action="3"/>
<Entry hr="0x810003F6" action="3"/>
<Entry hr="0x810003F7" action="3"/>
</Feature>
<Feature type="3" name="P2P">
<Entry hr="0x82000012" action="3"/>
<Entry hr="0x82000013" action="3"/>
<Entry hr="0x82000016" action="3"/>
<Entry hr="0x82000017" action="3"/>
<Entry hr="0x82000018" action="3"/>
<Entry hr="0x82000019" action="3"/>
</Feature>
</ErrorResponseTable>
</Simple>
<TabConfig>
{tabs}
</TabConfig>
<AbchCfg>
<abchconfig>
<url>https://ctsvcs.addressbook.ugnet.gay/abservice.asmx</url>
</abchconfig>
</AbchCfg>
<LocalizedConfig Market="en-US">
<AdMainConfig>
<TextAdRefresh>1</TextAdRefresh>
<TextAdServer>http://ctsvcs.advertising.ugnet.gay/ads/txt</TextAdServer>
<AdBanner20URL Refresh="300">http://ctsvcs.advertising.ugnet.gay/ads/banner</AdBanner20URL>
<StdAd AdVisible="60" VideoVisible="120" VideoDldIntvl="0">
<VideoFeeds FeedsListURL="http://ctsvcs.advertising.ugnet.gay/svcs/msn-video-feeds/"/>
</StdAd>
</AdMainConfig>
<AppDirConfig>
<AppDirPageURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/Directory.aspx?L=en-us</AppDirPageURL>
<AppDirSeviceURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/AppDirectory.asmx</AppDirSeviceURL>
<AppDirVersionURL>http://mactivities.msgrsvcs.ctsrv.gay/AppDirectory/GetAppdirVersion.aspx</AppDirVersionURL>
</AppDirConfig>
<Contacts>
<ABPendingRequests>
<url>http://social.ugnet.gay/PendingRequests.aspx?mkt=en-us&amp;partner=Messenger</url>
<siteid>73625</siteid>
<height>672</height>
<width>808</width>
</ABPendingRequests>
<BuddysSocialNetwork>
<url>http://social.ugnet.gay/NetworkExplorer.aspx?mkt=en-us&amp;partner=Messenger&amp;cid=%1</url>
<siteid>73625</siteid>
<height>674</height>
<width>808</width>
</BuddysSocialNetwork>
<EditMyLiveContactProfile>
<url>http://social.ugnet.gay/profile.aspx?action=edit&amp;mode=activecontacts&amp;mkt=en-us&amp;partner=Messenger</url>
<siteid>73625</siteid>
</EditMyLiveContactProfile>
<EditMyProfile>
<url>http://social.ugnet.gay/profile.aspx?action=edit&amp;partner=Messenger&amp;mkt=en-us</url>
<siteid>73625</siteid>
</EditMyProfile>
<Profile>
<url>http://social.ugnet.gay/Profile.aspx?partner=Messenger&amp;mkt=en-us&amp;mem=%ls</url>
<urlcid>http://social.ugnet.gay/Profile.aspx?partner=Messenger&amp;mkt=en-us&amp;cid=%ls</urlcid>
<siteid>73625</siteid>
</Profile>
<SocialNetwork>
<url>http://social.ugnet.gay/NetworkSetup.aspx?mkt=en-us&amp;partner=Messenger</url>
<siteid>73625</siteid>
<height>674</height>
<width>808</width>
</SocialNetwork>
<ViewMapEnabled>false</ViewMapEnabled>
</Contacts>
<ContactCard>
<AddToMySpaceSiteId>45930</AddToMySpaceSiteId>
<AddToMySpaceUrl>http://social.ugnet.gay/?addblogentry=true&amp;mkt=nl-nl</AddToMySpaceUrl>
<ContactCardDisabled>false</ContactCardDisabled>
<CreateSpaceSiteId>45930</CreateSpaceSiteId>
<CreateSpaceUrl>http://social.ugnet.gay/signup.aspx?mkt=nl-nl</CreateSpaceUrl>
<GetItemVerUrl>http://storage.msn.com/storageservice/schematizedstore.asmx</GetItemVerUrl>
<GetXmlFeedUrl>http://services.social.ugnet.gay/contactcard/contactcardservice.asmx</GetXmlFeedUrl>
<MySpaceSiteId>45930</MySpaceSiteId>
<MySpaceUrl>http://social.ugnet.gay/homepage.aspx</MySpaceUrl>
<SpaceBaseSiteId>45930</SpaceBaseSiteId>
<SpaceBaseUrl>http://social.ugnet.gay</SpaceBaseUrl>
<SpaceIntegrationEnabled>true</SpaceIntegrationEnabled>
</ContactCard>
<FlashUpgradeURL>http://storage.ugnet.gay/crosstalk-dist/client/all/tools/flashplayer_10_3r183_48_winax.exe</FlashUpgradeURL>
<GLinkMarket v="en_us"/>
<MessengerBlogURL>https://crosstalk.im/blog</MessengerBlogURL>
<MSNSearch>
<ImagesURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=images</ImagesURL>
<NewsURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$+news&amp;ia=news</NewsURL>
<SearchURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SearchURL>
<SharedSearchURL>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SharedSearchURL>
<SharedSearchURL2>https://searx.ugnet.gay/searxng/search?q=$QUERY$&amp;ia=web</SharedSearchURL2>
</MSNSearch>
<MsnTodayConfig>
<MsnTodaySiteID>6528</MsnTodaySiteID>
<MsnTodayURL>http://today.msgrsvcs.ctsrv.gay/start?wlm=1</MsnTodayURL>
<Flags>2</Flags>
</MsnTodayConfig>
<MusicIntegration URL="https://www.last.fm/search/tracks?q=$ARTIST$+$TITLE$"/>
<OneCare Enabled="0"/>
<PSTNOut Hidden="1"/>
<ReportAbuse>
<ReportAbuseSID/>
<ReportAbuseURL>https://crosstalk.im/report</ReportAbuseURL>
</ReportAbuse>
<RL>
<ViewProfileURL>https://crosstalk.im/account/settings</ViewProfileURL>
</RL>
<SDrive Enabled="true"/>
<TermsOfUse>
<TermsOfUseSID>956</TermsOfUseSID>
<TermsOfUseURL>https://crosstalk.im/tos</TermsOfUseURL>
</TermsOfUse>
<VoiceClip Hidden="0"/>
<VoiceVideo>
<DisableSipProxyInviteTest>0</DisableSipProxyInviteTest>
<DisableSipProxyCapability>0</DisableSipProxyCapability>
<DisableSipProxyInvite>0</DisableSipProxyInvite>
<DisableSipProxyCapability2>0</DisableSipProxyCapability2>
<DisableSipProxyInvite2>0</DisableSipProxyInvite2>
</VoiceVideo>
</LocalizedConfig>
</MsgrConfig>
@@ -3,10 +3,10 @@
When a certificate is rev'd, a line like the following should be When a certificate is rev'd, a line like the following should be
added to the cfg:Settings section: added to the cfg:Settings section:
<cfg:Certificate expired="true">SLCA_BACKUP.CER</cfg:Certificate> <cfg:Certificate expired="true">SLCA_BACKUP.CER</cfg:Certificate>
--><cfg:Settings><cfg:DeviceDNSSuffix>.devicedns.ugnet.xyz</cfg:DeviceDNSSuffix><cfg:DeviceDNSSuffixOld></cfg:DeviceDNSSuffixOld><cfg:EIDEnumBCSP>Microsoft Base Smart Card Crypto Provider</cfg:EIDEnumBCSP><cfg:EIDEnumRootCAThumbprint>0tOOumDKocEgVaLhyDsVrUUBEMI=</cfg:EIDEnumRootCAThumbprint><cfg:UpdateNeededInterval>604800</cfg:UpdateNeededInterval><cfg:ResolveTimeout>0</cfg:ResolveTimeout><cfg:ConnectTimeout>10000</cfg:ConnectTimeout><cfg:SendTimeout>30000</cfg:SendTimeout><cfg:ReceiveTimeout>30000</cfg:ReceiveTimeout><cfg:MinMinutesBetweenMetaConfigCheck>1440</cfg:MinMinutesBetweenMetaConfigCheck><!--[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")]--><cfg:AndroidSsoCerts>sX6CAbEo4edMwCNRCrfqA6wn3eUNMtgQ6hV3dY8cwJg=,g2b69yfcSDF6LzoMN/oSfz81YZTPuy9LYo7H5qGnXA8=,uSUTbz6nwKGVFpChqzE5ENqB9AmUqFNC7GIoiPEocFE=,oHlCFSeKVn6IevbN4BWl6IQU72QPfas4VaPneWWL53g=,fVOTUco5wnynBkCeWptrBi25v43D2MqmE3Bnrn9otec=,KEg2GpweMt8dPi7Wp7nmelJc+KE7Fk+ABslHlXj3Rt4=,7r0PFuYpr4uDgb/t/dZJYF/pD3Y/XLe6Rz657vlNmvE=,Mb5ACW+THNfxHV4mLSssQ3xEOF+07LwQE9ladDWBb5w=,6EPuPaEZXWr7icqjznQnsI/AH9h4ok+lbpYsNccdXnA=,rQZmwqojBROk1Pc/okKkWGzY7WcmodDdVCUHcv2blgU=</cfg:AndroidSsoCerts><cfg:ConfigServerSslURI>https://go.microsoft.com/fwlink/?LinkId=690512</cfg:ConfigServerSslURI><cfg:ConfigServerCdnURI>http://go.microsoft.com/fwlink/?LinkId=253579</cfg:ConfigServerCdnURI><cfg:ConfigServerURI>http://clientconfig.passport.net/ppcrlconfig.srf</cfg:ConfigServerURI><cfg:TopNonFedDomains>@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.</cfg:TopNonFedDomains><cfg:DIDCOMMetaData><cfg:DIDWithAuth>1</cfg:DIDWithAuth><cfg:AssocPDIDToLDID>1</cfg:AssocPDIDToLDID><cfg:Protocol><cfg:CLSID>{1C109E4C-2F30-4EA3-A57A-A290877A2303}</cfg:CLSID><cfg:DATA><![CDATA[<Input version="1" match="20"><Excluded><Controller>Win32_USBControllerDevice</Controller><Controller>Win32_1394ControllerDevice</Controller><Controller>Win32_PCMCIAControllerDevice</Controller><Controller>Win32_ConnectionShare</Controller></Excluded><Class name="Win32_PhysicalMedia" pos="1" hash="32" match="10"><Data>SerialNumber</Data></Class><Class name="Win32_NetworkAdapter" pos="2" hash="32" match="10"><Data>MACAddress</Data></Class><Class name="Win32_BIOS" pos="3" hash="32" match="10"><Data>Manufacturer</Data><Data>SerialNumber</Data></Class></Input>]]></cfg:DATA><cfg:PREFIX>01</cfg:PREFIX></cfg:Protocol><cfg:Protocol><cfg:CLSID>{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}</cfg:CLSID><cfg:PREFIX>03</cfg:PREFIX><cfg:LOGICAL>1</cfg:LOGICAL><cfg:SYSTEM>1</cfg:SYSTEM></cfg:Protocol><cfg:Protocol><cfg:CLSID>{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}</cfg:CLSID><cfg:PREFIX>02</cfg:PREFIX><cfg:LOGICAL>1</cfg:LOGICAL></cfg:Protocol><cfg:CONSENTVERSION>1</cfg:CONSENTVERSION></cfg:DIDCOMMetaData><cfg:Certificate>MIIDGjCCAtqgAwIBAgIJAL67zDTCqZpDMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTEzMDcwMjIxMTAzN1oXDTE4MDcwMTIxMTAzN1owIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtjCCASsGByqGSM44BAEwggEeAoGBAPPi828dNQiBJ1qnxffow1emUO8g3DK1PKd5hC3L/BUiKMHnZAGcVcp7+KARbMypNjbcaBFhyBiPefmFzOaxqKr0Tf/T6mwtYP2A7v0ITEoJxLl4TPPM9jjKjMqTf7rubUcsrU7i1d3aTmUxhOUS2YRsdwq9xeSUXOVobFE7848VAhUAn9eIFUVj31yox4o1Qnj8cDlON/sCgYA6dp0LN/eExvGvZo/6ey0LU96/rA5k24JE9MF5Pp40ysAgBH098FY93v0XGrL9avSffTYWwoXMQiWQw6bwyuDdOYfD8xCl7+DxJ/QGQW6YPsZJ6DXhAG4vzPSEdLkOgstny2JgjtQvLsRbcYA9Y9vWMQG4pJD9GrCRl270uxdqZQOBhAACgYBu0rix0SuIRsMiNoM3actVS804Cb/WhMi9rPtQDKUAMnGFVgzMg9muE1gPpyqp/Tbsyqn9eYYSRcxZG059zwR4R+gtWUaCljhHOScjYUL5ql2Z7DNxRndJLjl4QmT0hq2msCiDfbWZpY5RLjdsUkcLHLiZF5N4NJnnct5meNsr46OBmDCBlTAdBgNVHQ4EFgQURtLCWz4DNCN5LhccABkoTHEQK2QwUwYDVR0jBEwwSoAURtLCWz4DNCN5LhccABkoTHEQK2ShJ6QlMCMxITAfBgNVBAMTGFRva2VuIFNpZ25pbmcgUHVibGljIEtleYIJAL67zDTCqZpDMBIGA1UdEwEB/wQIMAYBAf8CAQAwCwYDVR0PBAQDAgHGMAkGByqGSM44BAMDLwAwLAIUC3k3NJt95Lh1CFXNQO9Luy0xRakCFBdAihMHEpTBGyyeUZXkEeuGpUhk</cfg:Certificate><cfg:Certificate>MIIDGzCCAtugAwIBAgIJAL6pALeLZHDvMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTE2MDUwOTIwNDA1NVoXDTIxMDUwODIwNDA1NVowIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASwGByqGSM44BAEwggEfAoGBAKmnM6FKnJ1osHWBHd8jHFFMDNwygIcof9EfHW6xJbU2uIzVV5WRu251RbRbmOqozesK44vkeBx9Ntl7PSu0W5RJFCEw9o4RLG0J40MWDNDQ+7iqvIsM6lsgZrDjNoWJ2t/Yrnnp0r3F9YNtj7J4vgLCYNOlkr2kcfGiji+SXotXAhUAqGI2zlbARtjz+simu2PihUPkV1MCgYEAnrIIXPvjKvWiXd3uve7eDS8qRHW7yoAseVLgeEIbS4VSj/9iQqunx1weQGlds75CLZgpcrY4Z5wbkxSjnK1EV30qce4+VzgXYGLZIAvl78wbAMFrG0josXccAbmqVM4LX2Z5yu1TEpPZLvgiaV4gJk4jsYhInqPm3Bw2qQ+gZokDgYQAAoGAFozcPQdM9MmszvEWMXuFrfEA8kVMnKIyA60paSi7CIecSAlsRLyw3D9J9pRW6HHdRZgOrKvnNcY63gKB56SKyj6r3nGqtkwEpu9yw1K+k2aSyJcKPHYVNw1Um5McKJgQJ49ShJFPaWXfDZPOCpgMpdzibnWjMcTak5rz4FHSUtOjgZgwgZUwHQYDVR0OBBYEFKNT6lUDzQppxFhwtv/jkSCRx596MFMGA1UdIwRMMEqAFKNT6lUDzQppxFhwtv/jkSCRx596oSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1Line truncated --><cfg:Settings><cfg:DeviceDNSSuffix>.devicedns.ugnet.gay</cfg:DeviceDNSSuffix><cfg:DeviceDNSSuffixOld></cfg:DeviceDNSSuffixOld><cfg:EIDEnumBCSP>Microsoft Base Smart Card Crypto Provider</cfg:EIDEnumBCSP><cfg:EIDEnumRootCAThumbprint>0tOOumDKocEgVaLhyDsVrUUBEMI=</cfg:EIDEnumRootCAThumbprint><cfg:UpdateNeededInterval>604800</cfg:UpdateNeededInterval><cfg:ResolveTimeout>0</cfg:ResolveTimeout><cfg:ConnectTimeout>10000</cfg:ConnectTimeout><cfg:SendTimeout>30000</cfg:SendTimeout><cfg:ReceiveTimeout>30000</cfg:ReceiveTimeout><cfg:MinMinutesBetweenMetaConfigCheck>1440</cfg:MinMinutesBetweenMetaConfigCheck><!--[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")]--><cfg:AndroidSsoCerts>sX6CAbEo4edMwCNRCrfqA6wn3eUNMtgQ6hV3dY8cwJg=,g2b69yfcSDF6LzoMN/oSfz81YZTPuy9LYo7H5qGnXA8=,uSUTbz6nwKGVFpChqzE5ENqB9AmUqFNC7GIoiPEocFE=,oHlCFSeKVn6IevbN4BWl6IQU72QPfas4VaPneWWL53g=,fVOTUco5wnynBkCeWptrBi25v43D2MqmE3Bnrn9otec=,KEg2GpweMt8dPi7Wp7nmelJc+KE7Fk+ABslHlXj3Rt4=,7r0PFuYpr4uDgb/t/dZJYF/pD3Y/XLe6Rz657vlNmvE=,Mb5ACW+THNfxHV4mLSssQ3xEOF+07LwQE9ladDWBb5w=,6EPuPaEZXWr7icqjznQnsI/AH9h4ok+lbpYsNccdXnA=,rQZmwqojBROk1Pc/okKkWGzY7WcmodDdVCUHcv2blgU=</cfg:AndroidSsoCerts><cfg:ConfigServerSslURI>https://go.microsoft.com/fwlink/?LinkId=690512</cfg:ConfigServerSslURI><cfg:ConfigServerCdnURI>http://go.microsoft.com/fwlink/?LinkId=253579</cfg:ConfigServerCdnURI><cfg:ConfigServerURI>http://clientconfig.passport.net/ppcrlconfig.srf</cfg:ConfigServerURI><cfg:TopNonFedDomains>@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.</cfg:TopNonFedDomains><cfg:DIDCOMMetaData><cfg:DIDWithAuth>1</cfg:DIDWithAuth><cfg:AssocPDIDToLDID>1</cfg:AssocPDIDToLDID><cfg:Protocol><cfg:CLSID>{1C109E4C-2F30-4EA3-A57A-A290877A2303}</cfg:CLSID><cfg:DATA><![CDATA[<Input version="1" match="20"><Excluded><Controller>Win32_USBControllerDevice</Controller><Controller>Win32_1394ControllerDevice</Controller><Controller>Win32_PCMCIAControllerDevice</Controller><Controller>Win32_ConnectionShare</Controller></Excluded><Class name="Win32_PhysicalMedia" pos="1" hash="32" match="10"><Data>SerialNumber</Data></Class><Class name="Win32_NetworkAdapter" pos="2" hash="32" match="10"><Data>MACAddress</Data></Class><Class name="Win32_BIOS" pos="3" hash="32" match="10"><Data>Manufacturer</Data><Data>SerialNumber</Data></Class></Input>]]></cfg:DATA><cfg:PREFIX>01</cfg:PREFIX></cfg:Protocol><cfg:Protocol><cfg:CLSID>{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}</cfg:CLSID><cfg:PREFIX>03</cfg:PREFIX><cfg:LOGICAL>1</cfg:LOGICAL><cfg:SYSTEM>1</cfg:SYSTEM></cfg:Protocol><cfg:Protocol><cfg:CLSID>{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}</cfg:CLSID><cfg:PREFIX>02</cfg:PREFIX><cfg:LOGICAL>1</cfg:LOGICAL></cfg:Protocol><cfg:CONSENTVERSION>1</cfg:CONSENTVERSION></cfg:DIDCOMMetaData><cfg:Certificate>MIIDGjCCAtqgAwIBAgIJAL67zDTCqZpDMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTEzMDcwMjIxMTAzN1oXDTE4MDcwMTIxMTAzN1owIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtjCCASsGByqGSM44BAEwggEeAoGBAPPi828dNQiBJ1qnxffow1emUO8g3DK1PKd5hC3L/BUiKMHnZAGcVcp7+KARbMypNjbcaBFhyBiPefmFzOaxqKr0Tf/T6mwtYP2A7v0ITEoJxLl4TPPM9jjKjMqTf7rubUcsrU7i1d3aTmUxhOUS2YRsdwq9xeSUXOVobFE7848VAhUAn9eIFUVj31yox4o1Qnj8cDlON/sCgYA6dp0LN/eExvGvZo/6ey0LU96/rA5k24JE9MF5Pp40ysAgBH098FY93v0XGrL9avSffTYWwoXMQiWQw6bwyuDdOYfD8xCl7+DxJ/QGQW6YPsZJ6DXhAG4vzPSEdLkOgstny2JgjtQvLsRbcYA9Y9vWMQG4pJD9GrCRl270uxdqZQOBhAACgYBu0rix0SuIRsMiNoM3actVS804Cb/WhMi9rPtQDKUAMnGFVgzMg9muE1gPpyqp/Tbsyqn9eYYSRcxZG059zwR4R+gtWUaCljhHOScjYUL5ql2Z7DNxRndJLjl4QmT0hq2msCiDfbWZpY5RLjdsUkcLHLiZF5N4NJnnct5meNsr46OBmDCBlTAdBgNVHQ4EFgQURtLCWz4DNCN5LhccABkoTHEQK2QwUwYDVR0jBEwwSoAURtLCWz4DNCN5LhccABkoTHEQK2ShJ6QlMCMxITAfBgNVBAMTGFRva2VuIFNpZ25pbmcgUHVibGljIEtleYIJAL67zDTCqZpDMBIGA1UdEwEB/wQIMAYBAf8CAQAwCwYDVR0PBAQDAgHGMAkGByqGSM44BAMDLwAwLAIUC3k3NJt95Lh1CFXNQO9Luy0xRakCFBdAihMHEpTBGyyeUZXkEeuGpUhk</cfg:Certificate><cfg:Certificate>MIIDGzCCAtugAwIBAgIJAL6pALeLZHDvMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTE2MDUwOTIwNDA1NVoXDTIxMDUwODIwNDA1NVowIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASwGByqGSM44BAEwggEfAoGBAKmnM6FKnJ1osHWBHd8jHFFMDNwygIcof9EfHW6xJbU2uIzVV5WRu251RbRbmOqozesK44vkeBx9Ntl7PSu0W5RJFCEw9o4RLG0J40MWDNDQ+7iqvIsM6lsgZrDjNoWJ2t/Yrnnp0r3F9YNtj7J4vgLCYNOlkr2kcfGiji+SXotXAhUAqGI2zlbARtjz+simu2PihUPkV1MCgYEAnrIIXPvjKvWiXd3uve7eDS8qRHW7yoAseVLgeEIbS4VSj/9iQqunx1weQGlds75CLZgpcrY4Z5wbkxSjnK1EV30qce4+VzgXYGLZIAvl78wbAMFrG0josXccAbmqVM4LX2Z5yu1TEpPZLvgiaV4gJk4jsYhInqPm3Bw2qQ+gZokDgYQAAoGAFozcPQdM9MmszvEWMXuFrfEA8kVMnKIyA60paSi7CIecSAlsRLyw3D9J9pRW6HHdRZgOrKvnNcY63gKB56SKyj6r3nGqtkwEpu9yw1K+k2aSyJcKPHYVNw1Um5McKJgQJ49ShJFPaWXfDZPOCpgMpdzibnWjMcTak5rz4FHSUtOjgZgwgZUwHQYDVR0OBBYEFKNT6lUDzQppxFhwtv/jkSCRx596MFMGA1UdIwRMMEqAFKNT6lUDzQppxFhwtv/jkSCRx596oSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1Line truncated
</cfg:PassportSecurityTokenService><cfg:MSNPassportSecurityTokenService>https://ctas.login.ugnet.xyz/RST.srf</cfg:MSNPassportSecurityTokenService><cfg:PassportSHA1Auth>https://ctas.login.ugnet.xyz/ppsecure/SHA1Auth.srf </cfg:PassportSecurityTokenService><cfg:MSNPassportSecurityTokenService>https://ctas.login.ugnet.gay/RST.srf</cfg:MSNPassportSecurityTokenService><cfg:PassportSHA1Auth>https://ctas.login.ugnet.gay/ppsecure/SHA1Auth.srf
</cfg:PassportSHA1Auth><cfg:URL_PasswordReset>https://ctas.login.ugnet.xyz/resetpw.srf </cfg:PassportSHA1Auth><cfg:URL_PasswordReset>https://ctas.login.ugnet.gay/resetpw.srf
</cfg:URL_PasswordReset><cfg:URL_PassportNetwork>http://www.microsoft.com/account/default.aspx </cfg:URL_PasswordReset><cfg:URL_PassportNetwork>http://www.microsoft.com/account/default.aspx
</cfg:URL_PassportNetwork><cfg:URL_AccountServices>https://account.ugnet.xyz </cfg:URL_PassportNetwork><cfg:URL_AccountServices>https://account.ugnet.gay
</cfg:URL_AccountServices><cfg:URL_PaneHelpFrame>http://ctas.login.ugnet.xyz/hp.srf?format=b1 </cfg:URL_AccountServices><cfg:URL_PaneHelpFrame>http://ctas.login.ugnet.gay/hp.srf?format=b1
</cfg:URL_PaneHelpFrame><!-- !!! P L E A S E R E A D !!!! --><!-- IDCRL 4.5 and below cannot load more than 32 items from <cfg:ServiceURIs> node. --><!-- Add any new items in <cfg:ServiceURIs1> node below. --><!-- NOTE: IDCRL 4.5 and below will NOT be able to read items from the new node. --></cfg:ServiceURIs><cfg:ServiceURIs1><cfg:PassportMetaConfig>http://ctas.login.ugnet.xyz/ppcrlcheck.srf</cfg:PassportMetaConfig><cfg:DeviceIdTrustedDomain>*.ugnet.xyz</cfg:DeviceIdTrustedDomain><cfg:DIDManagementDomain>ctas.login.ugnet.xyz,account.ugnet.xyz</cfg:DIDManagementDomain><cfg:PREFBINCookieDomain>c.ugnet.xyz,c.msn.com</cfg:PREFBINCookieDomain><cfg:WLIDSTS_WCF>https://ctas.login.ugnet.xyz/RST2.srf</cfg:WLIDSTS_WCF><cfg:MSNWLIDSTS_WCF>https://ctas.login.ugnet.xyz/RST2.srf</cfg:MSNWLIDSTS_WCF><cfg:URL_DeviceTOU>https://ctas.login.ugnet.xyz/didtou.srf</cfg:URL_DeviceTOU><cfg:DeviceChangeService>https://ctas.login.ugnet.xyz/ppsecure/devicechangecredential.srf</cfg:DeviceChangeService><cfg:DeviceAddService>https://ctas.login.ugnet.xyz/ppsecure/deviceaddcredential.srf</cfg:DeviceAddService><cfg:DeviceRemoveService>https://ctas.login.ugnet.xyz/ppsecure/deviceremovecredential.srf</cfg:DeviceRemoveService><cfg:DeviceAssociateService>https://ctas.login.ugnet.xyz/ppsecure/DeviceAssociate.srf</cfg:DeviceAssociateService><cfg:DeviceDisassociateService>https://ctas.login.ugnet.xyz/ppsecure/DeviceDisassociate.srf</cfg:DeviceDisassociateService><cfg:DeviceQueryService>https://ctas.login.ugnet.xyz/ppsecure/DeviceQuery.srf</cfg:DeviceQueryService><cfg:DeviceUpdateService>https://ctas.login.ugnet.xyz/ppsecure/DeviceUpdate.srf</cfg:DeviceUpdateService><cfg:DeviceEnumerateService>https://ctas.login.ugnet.xyz/ppsecure/EnumerateDevices.srf</cfg:DeviceEnumerateService><cfg:ResolveUserService>https://ctas.login.ugnet.xyz/ppsecure/ResolveUser.srf</cfg:ResolveUserService><cfg:AllowGetProperty>EID</cfg:AllowGetProperty><cfg:RealmInfoService>https://ctas.login.ugnet.xyz/getrealminfo.srf</cfg:RealmInfoService><cfg:RealmInfoService6_0>https://ctas.login.ugnet.xyz/getuserrealm.srf</cfg:RealmInfoService6_0><cfg:URL_Retention>https://ctas.login.ugnet.xyz/retention.srf</cfg:URL_Retention><cfg:URL_Registration>https://signup.ugnet.xyz/signup.aspx</cfg:URL_Registration><cfg:URL_Privacy>http://go.microsoft.com/fwlink/p/?LinkId=253457</cfg:URL_Privacy><cfg:GetUserKeyDataService>https://ctas.login.ugnet.xyz/ppsecure/GetUserKeyData.srf</cfg:GetUserKeyDataService><cfg:OOBESignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80500</cfg:OOBESignIn><cfg:OOBESignUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80500</cfg:OOBESignUp><cfg:OOBEIfExists>https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&amp;id=80500</cfg:OOBEIfExists><cfg:CPSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80501</cfg:CPSignIn><cfg:CPSignUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80501</cfg:CPSignUp><cfg:CPIfExists>https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&amp;id=80501</cfg:CPIfExists><cfg:CPChangePwd>https://account.ugnet.xyz/Wizard/Password/Change?id=80501</cfg:CPChangePwd><cfg:CPAddUserSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80502</cfg:CPAddUserSignIn><cfg:CPAddUserSignUp>https://account.ugnet.xyz/InlineSignup.aspx?iww=1&amp;id=80502</cfg:CPAddUserSignUp><cfg:CPAddUserIfExists>https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&amp;id=80502</cfg:CPAddUserIfExists><!-- Auth-up URLs and all 806XX site IDs are used for versions of connect flows that can handle receiving a DA token during connect. --><cfg:OOBESignInAuthUp>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80600</cfg:OOBESignInAuthUp><cfg:OOBESignUpAuthUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80600</cfg:OOBESignUpAuthUp><cfg:OOBEIfExistsAuthUp>https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&amp;id=80600</cfg:OOBEIfExistsAuthUp><cfg:OOBEConnect>https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80600</cfg:OOBEConnect><cfg:CPSignInAuthUp>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80601</cfg:CPSignInAuthUp><cfg:CPSignUpAuthUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80601</cfg:CPSignUpAuthUp><cfg:CPIfExistsAuthUp>https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&amp;id=80601</cfg:CPIfExistsAuthUp><cfg:CPChangePwdAuthUp>https://account.ugnet.xyz/Wizard/Password/Change?id=80601</cfg:CPChangePwdAuthUp><cfg:CPChangePwdOnline>https://ctas.login.ugnet.xyz/ppsecure/InlinePOPAuth.srf?id=80601&amp;fid=cp</cfg:CPChangePwdOnline><cfg:CPConnect>https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80601</cfg:CPConnect><cfg:OOBEUpgradeSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80603</cfg:OOBEUpgradeSignIn><cfg:OOBEUpgradeSignUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80603</cfg:OOBEUpgradeSignUp><cfg:OOBEUpgradeConnect>https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80603</cfg:OOBEUpgradeConnecLine truncated </cfg:URL_PaneHelpFrame><!-- !!! P L E A S E R E A D !!!! --><!-- IDCRL 4.5 and below cannot load more than 32 items from <cfg:ServiceURIs> node. --><!-- Add any new items in <cfg:ServiceURIs1> node below. --><!-- NOTE: IDCRL 4.5 and below will NOT be able to read items from the new node. --></cfg:ServiceURIs><cfg:ServiceURIs1><cfg:PassportMetaConfig>http://ctas.login.ugnet.gay/ppcrlcheck.srf</cfg:PassportMetaConfig><cfg:DeviceIdTrustedDomain>*.ugnet.gay</cfg:DeviceIdTrustedDomain><cfg:DIDManagementDomain>ctas.login.ugnet.gay,account.ugnet.gay</cfg:DIDManagementDomain><cfg:PREFBINCookieDomain>c.ugnet.gay,c.msn.com</cfg:PREFBINCookieDomain><cfg:WLIDSTS_WCF>https://ctas.login.ugnet.gay/RST2.srf</cfg:WLIDSTS_WCF><cfg:MSNWLIDSTS_WCF>https://ctas.login.ugnet.gay/RST2.srf</cfg:MSNWLIDSTS_WCF><cfg:URL_DeviceTOU>https://ctas.login.ugnet.gay/didtou.srf</cfg:URL_DeviceTOU><cfg:DeviceChangeService>https://ctas.login.ugnet.gay/ppsecure/devicechangecredential.srf</cfg:DeviceChangeService><cfg:DeviceAddService>https://ctas.login.ugnet.gay/ppsecure/deviceaddcredential.srf</cfg:DeviceAddService><cfg:DeviceRemoveService>https://ctas.login.ugnet.gay/ppsecure/deviceremovecredential.srf</cfg:DeviceRemoveService><cfg:DeviceAssociateService>https://ctas.login.ugnet.gay/ppsecure/DeviceAssociate.srf</cfg:DeviceAssociateService><cfg:DeviceDisassociateService>https://ctas.login.ugnet.gay/ppsecure/DeviceDisassociate.srf</cfg:DeviceDisassociateService><cfg:DeviceQueryService>https://ctas.login.ugnet.gay/ppsecure/DeviceQuery.srf</cfg:DeviceQueryService><cfg:DeviceUpdateService>https://ctas.login.ugnet.gay/ppsecure/DeviceUpdate.srf</cfg:DeviceUpdateService><cfg:DeviceEnumerateService>https://ctas.login.ugnet.gay/ppsecure/EnumerateDevices.srf</cfg:DeviceEnumerateService><cfg:ResolveUserService>https://ctas.login.ugnet.gay/ppsecure/ResolveUser.srf</cfg:ResolveUserService><cfg:AllowGetProperty>EID</cfg:AllowGetProperty><cfg:RealmInfoService>https://ctas.login.ugnet.gay/getrealminfo.srf</cfg:RealmInfoService><cfg:RealmInfoService6_0>https://ctas.login.ugnet.gay/getuserrealm.srf</cfg:RealmInfoService6_0><cfg:URL_Retention>https://ctas.login.ugnet.gay/retention.srf</cfg:URL_Retention><cfg:URL_Registration>https://signup.ugnet.gay/signup.aspx</cfg:URL_Registration><cfg:URL_Privacy>http://go.microsoft.com/fwlink/p/?LinkId=253457</cfg:URL_Privacy><cfg:GetUserKeyDataService>https://ctas.login.ugnet.gay/ppsecure/GetUserKeyData.srf</cfg:GetUserKeyDataService><cfg:OOBESignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80500</cfg:OOBESignIn><cfg:OOBESignUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80500</cfg:OOBESignUp><cfg:OOBEIfExists>https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&amp;id=80500</cfg:OOBEIfExists><cfg:CPSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80501</cfg:CPSignIn><cfg:CPSignUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80501</cfg:CPSignUp><cfg:CPIfExists>https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&amp;id=80501</cfg:CPIfExists><cfg:CPChangePwd>https://account.ugnet.gay/Wizard/Password/Change?id=80501</cfg:CPChangePwd><cfg:CPAddUserSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80502</cfg:CPAddUserSignIn><cfg:CPAddUserSignUp>https://account.ugnet.gay/InlineSignup.aspx?iww=1&amp;id=80502</cfg:CPAddUserSignUp><cfg:CPAddUserIfExists>https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&amp;id=80502</cfg:CPAddUserIfExists><!-- Auth-up URLs and all 806XX site IDs are used for versions of connect flows that can handle receiving a DA token during connect. --><cfg:OOBESignInAuthUp>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80600</cfg:OOBESignInAuthUp><cfg:OOBESignUpAuthUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80600</cfg:OOBESignUpAuthUp><cfg:OOBEIfExistsAuthUp>https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&amp;id=80600</cfg:OOBEIfExistsAuthUp><cfg:OOBEConnect>https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80600</cfg:OOBEConnect><cfg:CPSignInAuthUp>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80601</cfg:CPSignInAuthUp><cfg:CPSignUpAuthUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80601</cfg:CPSignUpAuthUp><cfg:CPIfExistsAuthUp>https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&amp;id=80601</cfg:CPIfExistsAuthUp><cfg:CPChangePwdAuthUp>https://account.ugnet.gay/Wizard/Password/Change?id=80601</cfg:CPChangePwdAuthUp><cfg:CPChangePwdOnline>https://ctas.login.ugnet.gay/ppsecure/InlinePOPAuth.srf?id=80601&amp;fid=cp</cfg:CPChangePwdOnline><cfg:CPConnect>https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80601</cfg:CPConnect><cfg:OOBEUpgradeSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80603</cfg:OOBEUpgradeSignIn><cfg:OOBEUpgradeSignUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80603</cfg:OOBEUpgradeSignUp><cfg:OOBEUpgradeConnect>https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80603</cfg:OOBEUpgradeConnecLine truncated
+2 -2
View File
@@ -3,5 +3,5 @@
When a certificate is rev'd, a line like the following should be When a certificate is rev'd, a line like the following should be
added to the cfg:Settings section: added to the cfg:Settings section:
<cfg:Certificate expired="true">SLCA_BACKUP.CER</cfg:Certificate> <cfg:Certificate expired="true">SLCA_BACKUP.CER</cfg:Certificate>
--><cfg:Settings><cfg:DeviceDNSSuffix>.devicedns.ugnet.xyz</cfg:DeviceDNSSuffix><cfg:ResolveTimeout>120000</cfg:ResolveTimeout><cfg:ConnectTimeout>60000</cfg:ConnectTimeout><cfg:SendTimeout>30000</cfg:SendTimeout><cfg:ReceiveTimeout>30000</cfg:ReceiveTimeout><cfg:MinMinutesBetweenMetaConfigCheck>1440</cfg:MinMinutesBetweenMetaConfigCheck><cfg:ConfigServerSslURI>https://go.microsoft.com/fwlink/?LinkId=859524</cfg:ConfigServerSslURI><cfg:DIDCOMMetaData><cfg:DIDWithAuth>1</cfg:DIDWithAuth><cfg:AssocPDIDToLDID>1</cfg:AssocPDIDToLDID><cfg:Protocol><cfg:CLSID>{1C109E4C-2F30-4EA3-A57A-A290877A2303}</cfg:CLSID><cfg:DATA><![CDATA[<Input version="1" match="20"><Excluded><Controller>Win32_USBControllerDevice</Controller><Controller>Win32_1394ControllerDevice</Controller><Controller>Win32_PCMCIAControllerDevice</Controller><Controller>Win32_ConnectionShare</Controller></Excluded><Class name="Win32_PhysicalMedia" pos="1" hash="32" match="10"><Data>SerialNumber</Data></Class><Class name="Win32_NetworkAdapter" pos="2" hash="32" match="10"><Data>MACAddress</Data></Class><Class name="Win32_BIOS" pos="3" hash="32" match="10"><Data>Manufacturer</Data><Data>SerialNumber</Data></Class></Input>]]></cfg:DATA><cfg:PREFIX>01</cfg:PREFIX></cfg:Protocol><cfg:Protocol><cfg:CLSID>{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}</cfg:CLSID><cfg:PREFIX>03</cfg:PREFIX><cfg:LOGICAL>1</cfg:LOGICAL><cfg:SYSTEM>1</cfg:SYSTEM></cfg:Protocol><cfg:Protocol><cfg:CLSID>{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}</cfg:CLSID><cfg:PREFIX>02</cfg:PREFIX><cfg:LOGICAL>1</cfg:LOGICAL></cfg:Protocol><cfg:CONSENTVERSION>1</cfg:CONSENTVERSION></cfg:DIDCOMMetaData><cfg:Certificate>MIIDGzCCAtugAwIBAgIJAL6pALeLZHDvMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTE2MDUwOTIwNDA1NVoXDTIxMDUwODIwNDA1NVowIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASwGByqGSM44BAEwggEfAoGBAKmnM6FKnJ1osHWBHd8jHFFMDNwygIcof9EfHW6xJbU2uIzVV5WRu251RbRbmOqozesK44vkeBx9Ntl7PSu0W5RJFCEw9o4RLG0J40MWDNDQ+7iqvIsM6lsgZrDjNoWJ2t/Yrnnp0r3F9YNtj7J4vgLCYNOlkr2kcfGiji+SXotXAhUAqGI2zlbARtjz+simu2PihUPkV1MCgYEAnrIIXPvjKvWiXd3uve7eDS8qRHW7yoAseVLgeEIbS4VSj/9iQqunx1weQGlds75CLZgpcrY4Z5wbkxSjnK1EV30qce4+VzgXYGLZIAvl78wbAMFrG0josXccAbmqVM4LX2Z5yu1TEpPZLvgiaV4gJk4jsYhInqPm3Bw2qQ+gZokDgYQAAoGAFozcPQdM9MmszvEWMXuFrfEA8kVMnKIyA60paSi7CIecSAlsRLyw3D9J9pRW6HHdRZgOrKvnNcY63gKB56SKyj6r3nGqtkwEpu9yw1K+k2aSyJcKPHYVNw1Um5McKJgQJ49ShJFPaWXfDZPOCpgMpdzibnWjMcTak5rz4FHSUtOjgZgwgZUwHQYDVR0OBBYEFKNT6lUDzQppxFhwtv/jkSCRx596MFMGA1UdIwRMMEqAFKNT6lUDzQppxFhwtv/jkSCRx596oSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQC+qQC3i2Rw7zASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAy8AMCwCFGjnp838qB/wTUdvoRt4G3aW0fv0AhRe8cZDdOveTDCbWane65nlVv0Udw==</cfg:Certificate><cfg:Certificate>MIIDHDCCAtugAwIBAgIJAPVhDwwaTUJrMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTIxMDMxODE4NDIzN1oXDTQxMDMxMzE4NDIzN1owIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASsGByqGSM44BAEwggEeAoGBANwZEes+CsJ6G4/Pe5XmGS9e5qki7KPMh9+IU5JE+z0H0Q4v51cKYCcm0OHtStB4oTF3RqTcYT6wYp/k6CcrGUVKo60tWY3C+ohOABpfoAnstLX/bZmWYQ87KzkRpB21WGCAJsoNQ5V0oQbwnEeeWO5sfZ6T3lfP7YgyeY4NatWhAhUAhFP2mQrVRzurTrsPRs5S1aNUWWUCgYBw3lXgm9xw1G9BSs8mP9sv8IefC87tBupniaUY/lz+AlN0qs6tXPHSesobCFxLDNT0Vhw4fSTJBPlq99tvV6ipEQkBtR3ColMVMq0G7ECW8ojnPWUcwdYUCyky7kyV7EuwnUYoAN4nZWBhN9BOj/nO0Ds5HInryR0RnTEvT0uojwOBhQACgYEA2SDhhPBDnKxvmH9RHvTUW0pvaTyAbFXxQ1WP+rcN608akqKmyMiskxCUySoBGAEbE/szcBqTu4VpvskyOBHY6Li6ewYP5cpVe7mARh27+cuGOzz3JZAVwi79D6u9/6OxnLyfbdRpYFq0qlmtUSbqtp895cs0cLn8TIppt+h6iDKjgZgwgZUwHQYDVR0OBBYEFNggH9qn8tEAK/Xtp75ejkmJcgjwMFMGA1UdIwRMMEqAFNggH9qn8tEAK/Xtp75ejkmJcgjwoSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQD1YQ8MGk1CazASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAzAAMC0CFHDGG3jer0Hzy/Qr08Dx/XpQGPG/AhUAg5mwhsY1EvBXNSor8eaySNirEH0=</cfg:Certificate><cfg:AddressResolutionTTL>900</cfg:AddressResolutionTTL><cfg:ClientTimeOutForRpcCallsNoNetwork>5</cfg:ClientTimeOutForRpcCallsNoNetwork><cfg:ClientTimeoutForRpcCallsWithNetwork>600</cfg:ClientTimeoutForRpcCallsWithNetwork><cfg:LivesspMaxTokenSize>60000</cfg:LivesspMaxTokenSize><cfg:AccountDomain>account.ugnet.xyz</cfg:AccountDomain><cfg:InterruptResolutionDomain>account.ugnet.xyz</cfg:InterruptResolutionDomain><cfg:PasswordReset>account.ugnet.xyz/password/reset</cfg:PasswordReset><cfg:AccountPolicy>sapi</cfg:AccountPolicy><cfg:ConnectAccountPolicy>mbi_ssl</cfg:ConnectAccountPolicy><cfg:StrongAuthPolicy>mbi_ssl_sa</cfg:StrongAuthPolicy><cfg:MinPasswordLength>8</cfg:MinPasswordLength><cfg:MinPasswordCharacterGroups>2</cfg:MinPasswordCharacterGroups><cfg:CookieP3PHeader><![CDATA[CP="CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOCi CNT"]]></cfg:CookieP3PHeader><cfg:ThrottleFlags>1</cfg:ThrottleFlags><cfg:ThrottleMaxRequests>200</cfg:ThrottleMaxRequests><cfg:ThrottleTotalIntervalSeconds>7200</cfg:ThrottleTotalIntervalSeconds><cfg:ThrottledApplications><cfg:ThrottledApp><cfg:ThrottledAppID>dc21Line truncated --><cfg:Settings><cfg:DeviceDNSSuffix>.devicedns.ugnet.gay</cfg:DeviceDNSSuffix><cfg:ResolveTimeout>120000</cfg:ResolveTimeout><cfg:ConnectTimeout>60000</cfg:ConnectTimeout><cfg:SendTimeout>30000</cfg:SendTimeout><cfg:ReceiveTimeout>30000</cfg:ReceiveTimeout><cfg:MinMinutesBetweenMetaConfigCheck>1440</cfg:MinMinutesBetweenMetaConfigCheck><cfg:ConfigServerSslURI>https://go.microsoft.com/fwlink/?LinkId=859524</cfg:ConfigServerSslURI><cfg:DIDCOMMetaData><cfg:DIDWithAuth>1</cfg:DIDWithAuth><cfg:AssocPDIDToLDID>1</cfg:AssocPDIDToLDID><cfg:Protocol><cfg:CLSID>{1C109E4C-2F30-4EA3-A57A-A290877A2303}</cfg:CLSID><cfg:DATA><![CDATA[<Input version="1" match="20"><Excluded><Controller>Win32_USBControllerDevice</Controller><Controller>Win32_1394ControllerDevice</Controller><Controller>Win32_PCMCIAControllerDevice</Controller><Controller>Win32_ConnectionShare</Controller></Excluded><Class name="Win32_PhysicalMedia" pos="1" hash="32" match="10"><Data>SerialNumber</Data></Class><Class name="Win32_NetworkAdapter" pos="2" hash="32" match="10"><Data>MACAddress</Data></Class><Class name="Win32_BIOS" pos="3" hash="32" match="10"><Data>Manufacturer</Data><Data>SerialNumber</Data></Class></Input>]]></cfg:DATA><cfg:PREFIX>01</cfg:PREFIX></cfg:Protocol><cfg:Protocol><cfg:CLSID>{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}</cfg:CLSID><cfg:PREFIX>03</cfg:PREFIX><cfg:LOGICAL>1</cfg:LOGICAL><cfg:SYSTEM>1</cfg:SYSTEM></cfg:Protocol><cfg:Protocol><cfg:CLSID>{B9F1D9B8-1DA6-4F17-962F-69EC82EA2704}</cfg:CLSID><cfg:PREFIX>02</cfg:PREFIX><cfg:LOGICAL>1</cfg:LOGICAL></cfg:Protocol><cfg:CONSENTVERSION>1</cfg:CONSENTVERSION></cfg:DIDCOMMetaData><cfg:Certificate>MIIDGzCCAtugAwIBAgIJAL6pALeLZHDvMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTE2MDUwOTIwNDA1NVoXDTIxMDUwODIwNDA1NVowIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASwGByqGSM44BAEwggEfAoGBAKmnM6FKnJ1osHWBHd8jHFFMDNwygIcof9EfHW6xJbU2uIzVV5WRu251RbRbmOqozesK44vkeBx9Ntl7PSu0W5RJFCEw9o4RLG0J40MWDNDQ+7iqvIsM6lsgZrDjNoWJ2t/Yrnnp0r3F9YNtj7J4vgLCYNOlkr2kcfGiji+SXotXAhUAqGI2zlbARtjz+simu2PihUPkV1MCgYEAnrIIXPvjKvWiXd3uve7eDS8qRHW7yoAseVLgeEIbS4VSj/9iQqunx1weQGlds75CLZgpcrY4Z5wbkxSjnK1EV30qce4+VzgXYGLZIAvl78wbAMFrG0josXccAbmqVM4LX2Z5yu1TEpPZLvgiaV4gJk4jsYhInqPm3Bw2qQ+gZokDgYQAAoGAFozcPQdM9MmszvEWMXuFrfEA8kVMnKIyA60paSi7CIecSAlsRLyw3D9J9pRW6HHdRZgOrKvnNcY63gKB56SKyj6r3nGqtkwEpu9yw1K+k2aSyJcKPHYVNw1Um5McKJgQJ49ShJFPaWXfDZPOCpgMpdzibnWjMcTak5rz4FHSUtOjgZgwgZUwHQYDVR0OBBYEFKNT6lUDzQppxFhwtv/jkSCRx596MFMGA1UdIwRMMEqAFKNT6lUDzQppxFhwtv/jkSCRx596oSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQC+qQC3i2Rw7zASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAy8AMCwCFGjnp838qB/wTUdvoRt4G3aW0fv0AhRe8cZDdOveTDCbWane65nlVv0Udw==</cfg:Certificate><cfg:Certificate>MIIDHDCCAtugAwIBAgIJAPVhDwwaTUJrMAkGByqGSM44BAMwIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MB4XDTIxMDMxODE4NDIzN1oXDTQxMDMxMzE4NDIzN1owIzEhMB8GA1UEAxMYVG9rZW4gU2lnbmluZyBQdWJsaWMgS2V5MIIBtzCCASsGByqGSM44BAEwggEeAoGBANwZEes+CsJ6G4/Pe5XmGS9e5qki7KPMh9+IU5JE+z0H0Q4v51cKYCcm0OHtStB4oTF3RqTcYT6wYp/k6CcrGUVKo60tWY3C+ohOABpfoAnstLX/bZmWYQ87KzkRpB21WGCAJsoNQ5V0oQbwnEeeWO5sfZ6T3lfP7YgyeY4NatWhAhUAhFP2mQrVRzurTrsPRs5S1aNUWWUCgYBw3lXgm9xw1G9BSs8mP9sv8IefC87tBupniaUY/lz+AlN0qs6tXPHSesobCFxLDNT0Vhw4fSTJBPlq99tvV6ipEQkBtR3ColMVMq0G7ECW8ojnPWUcwdYUCyky7kyV7EuwnUYoAN4nZWBhN9BOj/nO0Ds5HInryR0RnTEvT0uojwOBhQACgYEA2SDhhPBDnKxvmH9RHvTUW0pvaTyAbFXxQ1WP+rcN608akqKmyMiskxCUySoBGAEbE/szcBqTu4VpvskyOBHY6Li6ewYP5cpVe7mARh27+cuGOzz3JZAVwi79D6u9/6OxnLyfbdRpYFq0qlmtUSbqtp895cs0cLn8TIppt+h6iDKjgZgwgZUwHQYDVR0OBBYEFNggH9qn8tEAK/Xtp75ejkmJcgjwMFMGA1UdIwRMMEqAFNggH9qn8tEAK/Xtp75ejkmJcgjwoSekJTAjMSEwHwYDVQQDExhUb2tlbiBTaWduaW5nIFB1YmxpYyBLZXmCCQD1YQ8MGk1CazASBgNVHRMBAf8ECDAGAQH/AgEAMAsGA1UdDwQEAwIBxjAJBgcqhkjOOAQDAzAAMC0CFHDGG3jer0Hzy/Qr08Dx/XpQGPG/AhUAg5mwhsY1EvBXNSor8eaySNirEH0=</cfg:Certificate><cfg:AddressResolutionTTL>900</cfg:AddressResolutionTTL><cfg:ClientTimeOutForRpcCallsNoNetwork>5</cfg:ClientTimeOutForRpcCallsNoNetwork><cfg:ClientTimeoutForRpcCallsWithNetwork>600</cfg:ClientTimeoutForRpcCallsWithNetwork><cfg:LivesspMaxTokenSize>60000</cfg:LivesspMaxTokenSize><cfg:AccountDomain>account.ugnet.gay</cfg:AccountDomain><cfg:InterruptResolutionDomain>account.ugnet.gay</cfg:InterruptResolutionDomain><cfg:PasswordReset>account.ugnet.gay/password/reset</cfg:PasswordReset><cfg:AccountPolicy>sapi</cfg:AccountPolicy><cfg:ConnectAccountPolicy>mbi_ssl</cfg:ConnectAccountPolicy><cfg:StrongAuthPolicy>mbi_ssl_sa</cfg:StrongAuthPolicy><cfg:MinPasswordLength>8</cfg:MinPasswordLength><cfg:MinPasswordCharacterGroups>2</cfg:MinPasswordCharacterGroups><cfg:CookieP3PHeader><![CDATA[CP="CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOCi CNT"]]></cfg:CookieP3PHeader><cfg:ThrottleFlags>1</cfg:ThrottleFlags><cfg:ThrottleMaxRequests>200</cfg:ThrottleMaxRequests><cfg:ThrottleTotalIntervalSeconds>7200</cfg:ThrottleTotalIntervalSeconds><cfg:ThrottledApplications><cfg:ThrottledApp><cfg:ThrottledAppID>dc21Line truncated
endpoints above. Client-side policy will determine which endpoint to use in a given situation. --><cfg:EnterpriseWLIDSTS_WCF>https://ctas.login.ugnet.xyz/MSARST2.srf</cfg:EnterpriseWLIDSTS_WCF><cfg:EnterpriseDeviceChangeService>https://ctas.login.ugnet.xyz/ppsecure/devicechangecredential.srf</cfg:EnterpriseDeviceChangeService><cfg:EnterpriseDeviceAddService>https://ctas.login.ugnet.xyz/ppsecure/deviceaddmsacredential.srf</cfg:EnterpriseDeviceAddService><cfg:EnterpriseDeviceRemoveService>https://ctas.login.ugnet.xyz/ppsecure/deviceremovecredential.srf</cfg:EnterpriseDeviceRemoveService><cfg:EnterpriseDeviceAssociateService>https://ctas.login.ugnet.xyz/ppsecure/DeviceAssociate.srf</cfg:EnterpriseDeviceAssociateService><cfg:EnterpriseDeviceDisassociateService>https://ctas.login.ugnet.xyz/ppsecure/DeviceDisassociate.srf</cfg:EnterpriseDeviceDisassociateService><cfg:EnterpriseDeviceQueryService>https://ctas.login.ugnet.xyz/ppsecure/DeviceQuery.srf</cfg:EnterpriseDeviceQueryService><cfg:EnterpriseDeviceUpdateService>https://ctas.login.ugnet.xyz/ppsecure/DeviceUpdate.srf</cfg:EnterpriseDeviceUpdateService><cfg:EnterpriseDeviceEnumerateService>https://ctas.login.ugnet.xyz/ppsecure/EnumerateDevices.srf</cfg:EnterpriseDeviceEnumerateService><cfg:EnterpriseResolveUserService>https://ctas.login.ugnet.xyz/ppsecure/ResolveUser.srf</cfg:EnterpriseResolveUserService><cfg:AllowGetProperty>EID</cfg:AllowGetProperty><cfg:RealmInfoService>https://ctas.login.ugnet.xyz/getrealminfo.srf</cfg:RealmInfoService><cfg:RealmInfoService6_0>https://ctas.login.ugnet.xyz/getuserrealm.srf</cfg:RealmInfoService6_0><cfg:URL_Retention>https://ctas.login.ugnet.xyz/retention.srf</cfg:URL_Retention><cfg:URL_Registration>https://signup.ugnet.xyz/signup.aspx</cfg:URL_Registration><cfg:URL_Privacy>http://go.microsoft.com/fwlink/p/?LinkId=253457</cfg:URL_Privacy><cfg:GetUserKeyDataService>https://ctas.login.ugnet.xyz/ppsecure/GetUserKeyData.srf</cfg:GetUserKeyDataService><cfg:CPAddUserSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80502</cfg:CPAddUserSignIn><cfg:CPAddUserSignUp>https://account.ugnet.xyz/InlineSignup.aspx?iww=1&amp;id=80502</cfg:CPAddUserSignUp><cfg:CPAddUserIfExists>https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&amp;id=80502</cfg:CPAddUserIfExists><!-- Auth-up URLs and all 806XX site IDs are used for versions of connect flows that can handle receiving a DA token during connect. --><cfg:OOBESignInAuthUp>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80600</cfg:OOBESignInAuthUp><cfg:OOBESignUpAuthUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80600</cfg:OOBESignUpAuthUp><cfg:OOBEIfExistsAuthUp>https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&amp;id=80600</cfg:OOBEIfExistsAuthUp><cfg:OOBEConnect>https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80600</cfg:OOBEConnect><cfg:CPSignInAuthUp>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80601</cfg:CPSignInAuthUp><cfg:CPSignUpAuthUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80601</cfg:CPSignUpAuthUp><cfg:CPIfExistsAuthUp>https://ctas.login.ugnet.xyz/IfExists.srf?uiflavor=4&amp;id=80601</cfg:CPIfExistsAuthUp><cfg:CPChangePwdAuthUp>https://account.ugnet.xyz/Wizard/Password/Change?id=80601</cfg:CPChangePwdAuthUp><cfg:CPChangePwdOnline>https://ctas.login.ugnet.xyz/ppsecure/InlinePOPAuth.srf?id=80601&amp;fid=cp</cfg:CPChangePwdOnline><cfg:CPConnect>https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80601</cfg:CPConnect><cfg:OOBEUpgradeSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80603</cfg:OOBEUpgradeSignIn><cfg:OOBEUpgradeSignUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80603</cfg:OOBEUpgradeSignUp><cfg:OOBEUpgradeConnect>https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80603</cfg:OOBEUpgradeConnect><cfg:CompleteAccountSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80604</cfg:CompleteAccountSignIn><cfg:CompleteAccountSignUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80604</cfg:CompleteAccountSignUp><cfg:CompleteAccountConnect>https://ctas.login.ugnet.xyz/ppsecure/InlineConnect.srf?id=80604</cfg:CompleteAccountConnect><cfg:CXHSignInUpsell>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80604</cfg:CXHSignInUpsell><cfg:NthUserSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80605</cfg:NthUserSignIn><cfg:NthUserSignUp>https://account.ugnet.xyz/inlinesignup.aspx?iww=1&amp;id=80605</cfg:NthUserSignUp><cfg:NthUserConnect>https://ctas.login.ugnet.xyz/ppsecure/InlinePOPAuth.srf?id=80605</cfg:NthUserConnect><cfg:CXHSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80606</cfg:CXHSignIn><cfg:CXHTransientSignIn>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80607</cfg:CXHTransientSignIn><cfg:CXHReAuth>https://ctas.login.ugnet.xyz/ppsecure/InlineLogin.srf?id=80608</cfg:CXHReAuth><cfg:CXHNGCUpsell>https://account.ugnet.xyz/msangcwam</cfg:CXHNGCUpsell><cfg:URL_AccountSettings>https://account.miLine truncated endpoints above. Client-side policy will determine which endpoint to use in a given situation. --><cfg:EnterpriseWLIDSTS_WCF>https://ctas.login.ugnet.gay/MSARST2.srf</cfg:EnterpriseWLIDSTS_WCF><cfg:EnterpriseDeviceChangeService>https://ctas.login.ugnet.gay/ppsecure/devicechangecredential.srf</cfg:EnterpriseDeviceChangeService><cfg:EnterpriseDeviceAddService>https://ctas.login.ugnet.gay/ppsecure/deviceaddmsacredential.srf</cfg:EnterpriseDeviceAddService><cfg:EnterpriseDeviceRemoveService>https://ctas.login.ugnet.gay/ppsecure/deviceremovecredential.srf</cfg:EnterpriseDeviceRemoveService><cfg:EnterpriseDeviceAssociateService>https://ctas.login.ugnet.gay/ppsecure/DeviceAssociate.srf</cfg:EnterpriseDeviceAssociateService><cfg:EnterpriseDeviceDisassociateService>https://ctas.login.ugnet.gay/ppsecure/DeviceDisassociate.srf</cfg:EnterpriseDeviceDisassociateService><cfg:EnterpriseDeviceQueryService>https://ctas.login.ugnet.gay/ppsecure/DeviceQuery.srf</cfg:EnterpriseDeviceQueryService><cfg:EnterpriseDeviceUpdateService>https://ctas.login.ugnet.gay/ppsecure/DeviceUpdate.srf</cfg:EnterpriseDeviceUpdateService><cfg:EnterpriseDeviceEnumerateService>https://ctas.login.ugnet.gay/ppsecure/EnumerateDevices.srf</cfg:EnterpriseDeviceEnumerateService><cfg:EnterpriseResolveUserService>https://ctas.login.ugnet.gay/ppsecure/ResolveUser.srf</cfg:EnterpriseResolveUserService><cfg:AllowGetProperty>EID</cfg:AllowGetProperty><cfg:RealmInfoService>https://ctas.login.ugnet.gay/getrealminfo.srf</cfg:RealmInfoService><cfg:RealmInfoService6_0>https://ctas.login.ugnet.gay/getuserrealm.srf</cfg:RealmInfoService6_0><cfg:URL_Retention>https://ctas.login.ugnet.gay/retention.srf</cfg:URL_Retention><cfg:URL_Registration>https://signup.ugnet.gay/signup.aspx</cfg:URL_Registration><cfg:URL_Privacy>http://go.microsoft.com/fwlink/p/?LinkId=253457</cfg:URL_Privacy><cfg:GetUserKeyDataService>https://ctas.login.ugnet.gay/ppsecure/GetUserKeyData.srf</cfg:GetUserKeyDataService><cfg:CPAddUserSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80502</cfg:CPAddUserSignIn><cfg:CPAddUserSignUp>https://account.ugnet.gay/InlineSignup.aspx?iww=1&amp;id=80502</cfg:CPAddUserSignUp><cfg:CPAddUserIfExists>https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&amp;id=80502</cfg:CPAddUserIfExists><!-- Auth-up URLs and all 806XX site IDs are used for versions of connect flows that can handle receiving a DA token during connect. --><cfg:OOBESignInAuthUp>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80600</cfg:OOBESignInAuthUp><cfg:OOBESignUpAuthUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80600</cfg:OOBESignUpAuthUp><cfg:OOBEIfExistsAuthUp>https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&amp;id=80600</cfg:OOBEIfExistsAuthUp><cfg:OOBEConnect>https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80600</cfg:OOBEConnect><cfg:CPSignInAuthUp>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80601</cfg:CPSignInAuthUp><cfg:CPSignUpAuthUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80601</cfg:CPSignUpAuthUp><cfg:CPIfExistsAuthUp>https://ctas.login.ugnet.gay/IfExists.srf?uiflavor=4&amp;id=80601</cfg:CPIfExistsAuthUp><cfg:CPChangePwdAuthUp>https://account.ugnet.gay/Wizard/Password/Change?id=80601</cfg:CPChangePwdAuthUp><cfg:CPChangePwdOnline>https://ctas.login.ugnet.gay/ppsecure/InlinePOPAuth.srf?id=80601&amp;fid=cp</cfg:CPChangePwdOnline><cfg:CPConnect>https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80601</cfg:CPConnect><cfg:OOBEUpgradeSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80603</cfg:OOBEUpgradeSignIn><cfg:OOBEUpgradeSignUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80603</cfg:OOBEUpgradeSignUp><cfg:OOBEUpgradeConnect>https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80603</cfg:OOBEUpgradeConnect><cfg:CompleteAccountSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80604</cfg:CompleteAccountSignIn><cfg:CompleteAccountSignUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80604</cfg:CompleteAccountSignUp><cfg:CompleteAccountConnect>https://ctas.login.ugnet.gay/ppsecure/InlineConnect.srf?id=80604</cfg:CompleteAccountConnect><cfg:CXHSignInUpsell>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80604</cfg:CXHSignInUpsell><cfg:NthUserSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80605</cfg:NthUserSignIn><cfg:NthUserSignUp>https://account.ugnet.gay/inlinesignup.aspx?iww=1&amp;id=80605</cfg:NthUserSignUp><cfg:NthUserConnect>https://ctas.login.ugnet.gay/ppsecure/InlinePOPAuth.srf?id=80605</cfg:NthUserConnect><cfg:CXHSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80606</cfg:CXHSignIn><cfg:CXHTransientSignIn>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80607</cfg:CXHTransientSignIn><cfg:CXHReAuth>https://ctas.login.ugnet.gay/ppsecure/InlineLogin.srf?id=80608</cfg:CXHReAuth><cfg:CXHNGCUpsell>https://account.ugnet.gay/msangcwam</cfg:CXHNGCUpsell><cfg:URL_AccountSettings>https://account.miLine truncated
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header>
<Machine xmlns="{{ owsns }}" name="BAYM-OW15" ver="12.30.1623.0"/>
</soap:Header>
<soap:Body>
<soap:Fault>
<faultcode xmlns:q0="{{ owsns }}">q0:MessageTooLarge</faultcode>
<faultstring>Exception of type 'System.Web.Services.Protocols.SoapException' was thrown.</faultstring>
<detail/>
</soap:Fault>
</soap:Body>
</soap:Envelope>
+1 -1
View File
@@ -4,7 +4,7 @@
<soap:Fault> <soap:Fault>
<faultcode>soap:Client</faultcode> <faultcode>soap:Client</faultcode>
<faultstring>Schema validation error</faultstring> <faultstring>Schema validation error</faultstring>
<faultactor>https://{{ settings.USERSTORAGE_HOST }}/rsi/rsi.asmx</faultactor> <faultactor>https://cts.storage.ugnet.gay/rsi/rsi.asmx</faultactor>
<detail /> <detail />
</soap:Fault> </soap:Fault>
</soap:Body> </soap:Body>
@@ -1,64 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
{%- macro profile_id(profile) %}
<Ns1>Cid</Ns1>
<V1 xsi:type="xsd:long">{{ cid_format(profile.user.uuid, decimal = True) }}</V1>
{%- if profile.puid is none %}
<Ns2>Unspecified</Ns2>
<V2 xsi:nil="true"/>
{%- else %}
<Ns2>Puid</Ns2>
<V2 xsi:type="xsd:long">{{ profile.puid }}</V2>
{%- endif %}
<Ns3>Unspecified</Ns3>
<V3 xsi:nil="true"/>
{%- endmacro %}
{%- macro profile_view(profile) %}
<View>
<ViewName>WLX.DC.CoreProfile</ViewName>
<ViewVersion>1</ViewVersion>
<Attributes>
<A><N>PublicProfile.ResourceId</N><V xsi:type="xsd:string">{{ profile.cid }}!106</V></A>
<A><N>PublicProfile.DisplayName</N><V xsi:type="xsd:string">{{ (profile.user.first_name or '')|e }}</V></A>
<A><N>PublicProfile.DisplayName.LastModified</N><V xsi:type="xsd:string">{{ now }}</V></A>
<A><N>PublicProfile.DisplayLastName</N><V xsi:type="xsd:string">{{ (profile.user.last_name or '')|e }}</V></A>
<A><N>PublicProfile.DisplayLastName.LastModified</N><V xsi:type="xsd:string">{{ now }}</V></A>
<A><N>ExpressionProfile.ResourceId</N><V xsi:type="xsd:string">{{ profile.cid }}!118</V></A>
<A><N>ExpressionProfile.DisplayName</N><V xsi:type="xsd:string">{{ (profile.roaming_info.name or profile.user.status.name or '')|e }}</V></A>
<A><N>ExpressionProfile.DisplayName.LastModified</N><V xsi:type="xsd:string">{{ date_format(profile.roaming_info.name_last_modified) }}</V></A>
<A><N>ExpressionProfile.PersonalStatus</N><V xsi:type="xsd:string">{{ (profile.roaming_info.message or '')|e }}</V></A>
<A><N>ExpressionProfile.PersonalStatus.LastModified</N><V xsi:type="xsd:string">{{ date_format(profile.roaming_info.message_last_modified) }}</V></A>
<A><N>ExpressionProfile.StaticUserTilePublicURL</N><V xsi:type="xsd:string">https://{{ host }}/avatar/{{ profile.user.uuid }}/im</V></A>
<A><N>UserTileStaticUrl</N><V xsi:type="xsd:string">https://{{ host }}/avatar/{{ profile.user.uuid }}/im</V></A>
<A><N>PictureProfile.UserTileStatic.ResourceId</N><V xsi:type="xsd:string">{{ profile.cid }}!205</V></A>
<A><N>LastModified</N><V xsi:type="xsd:string">{{ now }}</V></A>
</Attributes>
</View>
{%- endmacro %}
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<{{ action }}Response xmlns="http://profile.live.com/">
<{{ action }}Result>
<CallStatistics>
<ServerName>{{ host }}</ServerName>
<ElapsedMilliseconds>0</ElapsedMilliseconds>
</CallStatistics>
{%- if action == 'GetMany' %}
<Ids>
{%- for profile in profiles %}
<ProfileId>{{ profile_id(profile) }}
</ProfileId>
{%- endfor %}
</Ids>
{%- else %}
<Id>{{ profile_id(profiles[0]) }}
</Id>
{%- endif %}
{%- if action == 'GetMany' %}
<Views>
{%- for profile in profiles %}{{ profile_view(profile) }}{%- endfor %}
</Views>
{%- else %}{{ profile_view(profiles[0]) }}{%- endif %}
</{{ action }}Result>
</{{ action }}Response>
</soap:Body>
</soap:Envelope>
@@ -15,56 +15,56 @@
<Services> <Services>
<Service> <Service>
<Memberships> <Memberships>
{%- for lst in lists %} {% for lst in lists %}
<Membership> <Membership>
<MemberRole>{{ lst.label }}</MemberRole> <MemberRole>{{ lst.label }}</MemberRole>
<Members> <Members>
{%- for contact in detail.contacts.values() %} {% 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) %} {% 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) %}
<Member xsi:type="PassportMember"> <Member xsi:type="PassportMember">
<MembershipId>{{ lst.label }}/{{ contact.head.uuid }}</MembershipId> <MembershipId>{{ lst.label }}/{{ contact.head.uuid }}</MembershipId>
<Type>Passport</Type> <Type>Passport</Type>
<State>Accepted</State> <State>Accepted</State>
<Deleted>false</Deleted> <Deleted>false</Deleted>
<LastChanged>{{ now }}</LastChanged> <LastChanged>{{ now }}</LastChanged>
<JoinedDate>{{ date_format(contact.head.date_created) }}</JoinedDate> <JoinedDate>{{ date_format(contact.head.date_created) }}</JoinedDate>
<ExpirationDate>0001-01-01T00:00:00</ExpirationDate> <ExpirationDate>0001-01-01T00:00:00</ExpirationDate>
<Changes /> <Changes />
<PassportName>{{ contact.head.email }}</PassportName> <PassportName>{{ contact.head.email }}</PassportName>
<IsPassportNameHidden>false</IsPassportNameHidden> <IsPassportNameHidden>false</IsPassportNameHidden>
<PassportId>0</PassportId> <PassportId>0</PassportId>
<CID>{{ cid_format(contact.head.uuid, decimal = True) }}</CID> <CID>{{ cid_format(contact.head.uuid, decimal = True) }}</CID>
<PassportChanges /> <PassportChanges />
<LookedupByCID>false</LookedupByCID> <LookedupByCID>false</LookedupByCID>
</Member> </Member>
{%- endif %} {% endif %}
{%- endfor %} {% endfor %}
{%- if lst == ContactList.BL %} {% if lst == ContactList.BL %}
{%- for circle in circles %} {% for circle in circles %}
{%- if circle.memberships[user.uuid].blocking %} {% if circle.memberships[user.uuid].blocking %}
<Member xsi:type="CircleMember"> <Member xsi:type="CircleMember">
<MembershipId>Block/00000000-0000-0000-0009-{{ circle.chat_id }}</MembershipId> <MembershipId>Block/00000000-0000-0000-0009-{{ circle.chat_id }}</MembershipId>
<Type>Circle</Type> <Type>Circle</Type>
<State>Accepted</State> <State>Accepted</State>
<Deleted>false</Deleted> <Deleted>false</Deleted>
<LastChanged>{{ now }}</LastChanged> <LastChanged>{{ now }}</LastChanged>
<JoinedDate>{{ now }}</JoinedDate> <JoinedDate>{{ now }}</JoinedDate>
<ExpirationDate>0001-01-01T00:00:00</ExpirationDate> <ExpirationDate>0001-01-01T00:00:00</ExpirationDate>
<Changes /> <Changes />
<CircleId>00000000-0000-0000-0009-{{ circle.chat_id }}</CircleId> <CircleId>00000000-0000-0000-0009-{{ circle.chat_id }}</CircleId>
</Member> </Member>
{%- endif %} {% endif %}
{%- endfor %} {% endfor %}
{%- endif %} {% endif %}
</Members> </Members>
<MembershipIsComplete>true</MembershipIsComplete> <MembershipIsComplete>true</MembershipIsComplete>
</Membership> </Membership>
{%- endfor %} {% endfor %}
<Membership> <Membership>
<MemberRole>Pending</MemberRole> <MemberRole>Pending</MemberRole>
<Members> <Members>
{%- for contact in detail.contacts.values() %} {% for contact in detail.contacts.values() %}
{%- if contact.pending and not contact.lists.__and__(ContactList.FL) %} {% if contact.pending and not contact.lists.__and__(ContactList.FL) %}
<Member xsi:type="PassportMember"> <Member xsi:type="PassportMember">
<MembershipId>Pending/{{ contact.head.uuid }}</MembershipId> <MembershipId>Pending/{{ contact.head.uuid }}</MembershipId>
<Type>Passport</Type> <Type>Passport</Type>
@@ -81,8 +81,8 @@
<PassportChanges /> <PassportChanges />
<LookedupByCID>false</LookedupByCID> <LookedupByCID>false</LookedupByCID>
</Member> </Member>
{%- endif %} {% endif %}
{%- endfor %} {% endfor %}
</Members> </Members>
<MembershipIsComplete>true</MembershipIsComplete> <MembershipIsComplete>true</MembershipIsComplete>
</Membership> </Membership>
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>{{ errorstring }}</faultstring>
<faultactor>http://www.msn.com/webservices/storage/{{ storage_ns }}/{{ action_str }}</faultactor>
<detail>
<errorcode xmlns="http://www.msn.com/webservices/storage/v1">{{ errorcode }}</errorcode>
<errorstring xmlns="http://www.msn.com/webservices/storage/v1">{{ errorstring }}</errorstring>
<machineName xmlns="http://www.msn.com/webservices/storage/v1">BL2STRWBA103</machineName>
</detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
@@ -34,7 +34,7 @@
<DocumentStreamName>UserTileStatic</DocumentStreamName> <DocumentStreamName>UserTileStatic</DocumentStreamName>
<MimeType>image/{{ mime }}</MimeType> <MimeType>image/{{ mime }}</MimeType>
<DataSize>{{ size_static }}</DataSize> <DataSize>{{ size_static }}</DataSize>
<PreAuthURL>https://{{ host }}/avatar/{{ user.uuid }}/im</PreAuthURL> <PreAuthURL>https://{{ host }}/avatar/{{ user.uuid }}/static</PreAuthURL>
<WriteMode>Overwrite</WriteMode> <WriteMode>Overwrite</WriteMode>
<StreamDataStatus>None</StreamDataStatus> <StreamDataStatus>None</StreamDataStatus>
<StreamStatus>None</StreamStatus> <StreamStatus>None</StreamStatus>
@@ -68,7 +68,7 @@
<DisplayName>{{ roaming_info.name }}</DisplayName> <DisplayName>{{ roaming_info.name }}</DisplayName>
<DisplayNameLastModified>{{ date_format(roaming_info.name_last_modified) }}</DisplayNameLastModified> <DisplayNameLastModified>{{ date_format(roaming_info.name_last_modified) }}</DisplayNameLastModified>
{% endif %} {% endif %}
<StaticUserTilePublicURL>https://{{ host }}/avatar/{{ user.uuid }}/im</StaticUserTilePublicURL> <StaticUserTilePublicURL>https://{{ host }}/avatar/{{ user.uuid }}/static</StaticUserTilePublicURL>
</ExpressionProfile> </ExpressionProfile>
</GetProfileResult> </GetProfileResult>
</GetProfileResponse> </GetProfileResponse>
+3 -3
View File
@@ -2,16 +2,16 @@
<rss version="2.0"> <rss version="2.0">
<channel> <channel>
<title>CrossTalk Video</title> <title>CrossTalk Video</title>
<link>https://{{ settings.WEBSITE_HOST }}</link> <link>https://crosstalk.im</link>
<description>CrossTalk Video</description> <description>CrossTalk Video</description>
<language>en-us</language> <language>en-us</language>
<copyright>2023 - 2026 hiden</copyright> <copyright>2023 - 2026 the undergr0und</copyright>
<lastBuildDate>Thu, 05 Sep 2024 5:48:54 GMT</lastBuildDate> <lastBuildDate>Thu, 05 Sep 2024 5:48:54 GMT</lastBuildDate>
<category>MSN_Microsoft</category> <category>MSN_Microsoft</category>
<ttl>0</ttl> <ttl>0</ttl>
<item> <item>
<title>Testing</title> <title>Testing</title>
<link>http://{{ settings.AD_HOST }}/svcs/feed</link> <link>http://ctsvcs.advertising.ugnet.gay/svcs/feed</link>
<description>Test feed</description> <description>Test feed</description>
<pubDate>Thu, 05 Sep 2024 00:00:00 GMT</pubDate> <pubDate>Thu, 05 Sep 2024 00:00:00 GMT</pubDate>
<category>MSN_Microsoft</category> <category>MSN_Microsoft</category>
+26 -199
View File
@@ -4,231 +4,58 @@
xmlns:xsd="http://www.w3.org/2001/XMLSchema"> xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header> <soap:Header>
<WNServiceHeader xmlns="http://www.msn.com/webservices/AddressBook"> <WNServiceHeader xmlns="http://www.msn.com/webservices/AddressBook">
<Version>17.4.0.0</Version> <Version>15.1.1216.0</Version>
<InExperimentalSample>false</InExperimentalSample>
</WNServiceHeader> </WNServiceHeader>
</soap:Header> </soap:Header>
<soap:Body> <soap:Body>
<{{ action }}Response xmlns="http://www.msn.com/webservices/AddressBook"> <GetContactsRecentActivityResponse xmlns="http://www.msn.com/webservices/AddressBook">
<{{ action }}Result> <GetContactsRecentActivityResult>
<Activities> <Activities>
{%- 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 %}
<ActivityDetails> <ActivityDetails>
<OwnerCID>{{ owner_cid }}</OwnerCID> <OwnerCID>0</OwnerCID>
<ObjectId>{% 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 %}</ObjectId> <ObjectId>Fri, 08 Jan 2025 4:59:43 CDT</ObjectId>
<ApplicationId>{{ 1275182653 if activity.user else 420 }}</ApplicationId> <ApplicationId>420</ApplicationId>
<ChangeType>{{ activity.type|int }}</ChangeType> <ChangeType>20</ChangeType>
<PublishDate>{{ date_format(activity.date_created) }}</PublishDate> <PublishDate>{date}</PublishDate>
<TemplateVariables> <TemplateVariables>
{%- if activity.user %}
<TemplateVariable xsi:type="PublisherIdTemplateVariable">
<Notations>
<Notation><Name>Live.RecentActivity.UserTileM</Name><Value>{{ tile }}</Value></Notation>
<Notation><Name>Live.RecentActivity.UserTileL</Name><Value>{{ tile }}</Value></Notation>
<Notation><Name>Live.RecentActivity.UserTileXL</Name><Value>{{ tile }}</Value></Notation>
</Notations>
<Name>publisher</Name>
<Id>{{ cid_format(activity.user.uuid, decimal = True) }}</Id>
<NameHint>{{ activity.user.status.name|e }}</NameHint>
<ProfilePictureUrl>{{ tile }}</ProfilePictureUrl>
<ProfileUrlHint>{{ profile }}</ProfileUrlHint>
<IsFavorite>{{ bool_to_str(activity.user.uuid in detail.contacts and contact_is_favorite(detail, detail.contacts[activity.user.uuid])) }}</IsFavorite>
</TemplateVariable>
<TemplateVariable xsi:type="HlinkTemplateVariable">
<Notations>
<Notation><Name>Live.RecentActivity.IsSelfPageUrl</Name><Value>true</Value></Notation>
</Notations>
<Name>AppName</Name>
<Value>{{ profile }}</Value>
<ValueAsSafeLink>{{ profile }}</ValueAsSafeLink>
</TemplateVariable>
{%- if activity.type == 3 %}
<TemplateVariable xsi:type="TextTemplateVariable"> <TemplateVariable xsi:type="TextTemplateVariable">
<Name>StatusText</Name> <Name>Name</Name>
<Value>has a new display picture</Value> <Value>{title}</Value>
</TemplateVariable> </TemplateVariable>
<TemplateVariable xsi:type="ImageTemplateVariable"> <TemplateVariable xsi:type="HlinkTemplateVariable">
<Name>DisplayPicture</Name> <Name>Url</Name>
<Value>{{ tile }}</Value> <Value>{url}</Value>
<Href>{{ profile }}</Href> </TemplateVariable>
<HrefAsSafeLink>{{ profile }}</HrefAsSafeLink>
</TemplateVariable>
{%- elif activity.type == 2 %}
<TemplateVariable xsi:type="TextTemplateVariable">
<Name>CanonicalStatusText</Name>
<Value>{{ (activity.text or 'shared a photo')|e }}</Value>
</TemplateVariable>
<TemplateVariable xsi:type="ImageTemplateVariable">
<Name>Photo</Name>
<Value>{{ activity.url|e }}</Value>
<Href>{{ activity.url|e }}</Href>
<HrefAsSafeLink>{{ activity.url|e }}</HrefAsSafeLink>
</TemplateVariable>
{%- else %}
<TemplateVariable xsi:type="TextTemplateVariable">
<Name>CanonicalStatusText</Name>
<Value>{{ activity.text|e }}</Value>
</TemplateVariable>
{%- endif %}
{%- else %}
<TemplateVariable xsi:type="PublisherIdTemplateVariable">
<Name>publisher</Name>
<Id>0</Id>
<NameHint>{{ activity.title|e }}</NameHint>
<ProfilePictureUrl></ProfilePictureUrl>
<ProfileUrlHint>{{ profile|e }}</ProfileUrlHint>
<IsFavorite>false</IsFavorite>
</TemplateVariable>
<TemplateVariable xsi:type="HlinkTemplateVariable">
<Name>AppName</Name>
<Value>{{ profile|e }}</Value>
<Text>Announcements</Text>
<ValueAsSafeLink>{{ profile|e }}</ValueAsSafeLink>
</TemplateVariable>
<TemplateVariable xsi:type="TextTemplateVariable">
<Name>CanonicalStatusText</Name>
<Value>{{ activity.text|e }}</Value>
</TemplateVariable>
{%- endif %}
</TemplateVariables> </TemplateVariables>
<ActivityID>1000000{{ activity.type|int if activity.user else 0 }}-0000-4000-8000-{{ '%012x'|format(activity.id) }}</ActivityID>
<CommentInfo>
<CommentCount>0</CommentCount>
</CommentInfo>
<RelevanceInfo>
<TimeWeightedScore>{{ '%.7f'|format(1 / (1 + (now - activity.date_created).total_seconds() / 86400)) }}</TimeWeightedScore>
</RelevanceInfo>
<CanPublishComments>false</CanPublishComments>
<VisibilityHint>0</VisibilityHint>
<CanPublishCommentsSet>false</CanPublishCommentsSet>
</ActivityDetails> </ActivityDetails>
{%- endfor %}
</Activities> </Activities>
<Templates> <Templates>
{%- if 3 in types %}
<RecentActivityTemplateContainer> <RecentActivityTemplateContainer>
<ApplicationId>1275182653</ApplicationId> <ApplicationId>420</ApplicationId>
<ApplicationName>Messenger</ApplicationName> <ApplicationName>{appName}</ApplicationName>
<MiniIconSizeX>0</MiniIconSizeX> <MiniIconSizeX>0</MiniIconSizeX>
<MiniIconSizeY>0</MiniIconSizeY> <MiniIconSizeY>0</MiniIconSizeY>
<ChangeType>3</ChangeType> <ChangeType>20</ChangeType>
<Locale>{{ locale|e }}</Locale> <Locale>en-us</Locale>
<RequestedLocales> <RequestedLocales>
<string>{{ locale|e }}</string> <string>en-US</string>
</RequestedLocales> </RequestedLocales>
<TemplateRevision>2116</TemplateRevision> <TemplateRevision>1</TemplateRevision>
<Templates> <Templates>
<RecentActivityTemplate> <RecentActivityTemplate>
<Cardinality>One</Cardinality> <Cardinality>One</Cardinality>
<Data>{image:DisplayPicture style=&quot;floatleft&quot;}</Data> <Data>CrossTalk News</Data>
<Title>{publisher-id:publisher} {text:StatusText=&quot;has a new display picture&quot;}</Title> <Title>{content}</Title>
<LayoutDetails>
<TemplateTypeDetails>
<TemplateType>MessengerGrid</TemplateType>
<LayoutProperties>
<LayoutProperty><Name>Type</Name><Value>Photo</Value></LayoutProperty>
<LayoutProperty><Name>PrimaryImage</Name><Value>{image:DisplayPicture}</Value></LayoutProperty>
<LayoutProperty><Name>Publisher</Name><Value>{publisher-id:publisher}</Value></LayoutProperty>
<LayoutProperty><Name>Action</Name><Value>{text:StatusText=&quot;has a new display picture&quot;}</Value></LayoutProperty>
</LayoutProperties>
</TemplateTypeDetails>
</LayoutDetails>
</RecentActivityTemplate> </RecentActivityTemplate>
</Templates> </Templates>
<ActivityType> <ActivityType>
<string>status</string> <string>blog</string>
<string>photo</string>
</ActivityType> </ActivityType>
<CanMergeItemsWithSameObjectID>false</CanMergeItemsWithSameObjectID> <CanMergeItemsWithSameObjectID>false</CanMergeItemsWithSameObjectID>
<RequiresNotification>false</RequiresNotification>
</RecentActivityTemplateContainer> </RecentActivityTemplateContainer>
{%- endif %}
{%- if 2 in types %}
<RecentActivityTemplateContainer>
<ApplicationId>1275182653</ApplicationId>
<ApplicationName>Messenger</ApplicationName>
<MiniIconSizeX>0</MiniIconSizeX>
<MiniIconSizeY>0</MiniIconSizeY>
<ChangeType>2</ChangeType>
<Locale>{{ locale|e }}</Locale>
<RequestedLocales>
<string>{{ locale|e }}</string>
</RequestedLocales>
<TemplateRevision>2116</TemplateRevision>
<Templates>
<RecentActivityTemplate>
<Cardinality>One</Cardinality>
<Data>{image:Photo style=&quot;floatleft&quot;}</Data>
<Title>{publisher-id:publisher} {text:CanonicalStatusText}</Title>
<LayoutDetails>
<TemplateTypeDetails>
<TemplateType>MessengerGrid</TemplateType>
<LayoutProperties>
<LayoutProperty><Name>Type</Name><Value>Photo</Value></LayoutProperty>
<LayoutProperty><Name>PrimaryImage</Name><Value>{image:Photo}</Value></LayoutProperty>
<LayoutProperty><Name>Publisher</Name><Value>{publisher-id:publisher}</Value></LayoutProperty>
<LayoutProperty><Name>Action</Name><Value>{text:CanonicalStatusText}</Value></LayoutProperty>
</LayoutProperties>
</TemplateTypeDetails>
</LayoutDetails>
</RecentActivityTemplate>
</Templates>
<ActivityType>
<string>status</string>
<string>photo</string>
</ActivityType>
<CanMergeItemsWithSameObjectID>false</CanMergeItemsWithSameObjectID>
<RequiresNotification>false</RequiresNotification>
</RecentActivityTemplateContainer>
{%- endif %}
{%- for change_type, application_id, application_name in ((1, 1275182653, 'Messenger'), (20, 420, 'Announcements')) if change_type in types %}
<RecentActivityTemplateContainer>
<ApplicationId>{{ application_id }}</ApplicationId>
<ApplicationName>{{ application_name }}</ApplicationName>
<MiniIconSizeX>0</MiniIconSizeX>
<MiniIconSizeY>0</MiniIconSizeY>
<ChangeType>{{ change_type }}</ChangeType>
<Locale>{{ locale|e }}</Locale>
<RequestedLocales>
<string>{{ locale|e }}</string>
</RequestedLocales>
<TemplateRevision>2116</TemplateRevision>
<Templates>
<RecentActivityTemplate>
<Cardinality>One</Cardinality>
<Data></Data>
<Title>{publisher-id:publisher} {text:CanonicalStatusText}</Title>
<LayoutDetails>
<TemplateTypeDetails>
<TemplateType>MessengerGrid</TemplateType>
<LayoutProperties>
<LayoutProperty><Name>Type</Name><Value>Status</Value></LayoutProperty>
<LayoutProperty><Name>Publisher</Name><Value>{publisher-id:publisher}</Value></LayoutProperty>
<LayoutProperty><Name>Action</Name><Value>{text:CanonicalStatusText}</Value></LayoutProperty>
{%- if change_type == 20 %}
<LayoutProperty><Name>Footer</Name><Value>via {hlink:AppName}</Value></LayoutProperty>
{%- endif %}
</LayoutProperties>
</TemplateTypeDetails>
</LayoutDetails>
</RecentActivityTemplate>
</Templates>
<ActivityType>
<string>status</string>
</ActivityType>
<CanMergeItemsWithSameObjectID>false</CanMergeItemsWithSameObjectID>
<RequiresNotification>false</RequiresNotification>
</RecentActivityTemplateContainer>
{%- endfor %}
</Templates> </Templates>
<FeedUrl>https://{{ settings.SOCIAL_HOST }}</FeedUrl> <FeedUrl>http://crosstalk.im</FeedUrl>
</{{ action }}Result> </GetContactsRecentActivityResult>
</{{ action }}Response> </GetContactsRecentActivityResponse>
</soap:Body> </soap:Body>
</soap:Envelope> </soap:Envelope>
+1 -84
View File
@@ -20,7 +20,7 @@ async def preprocess_soap(req: web.Request) -> Tuple[Any, Any, Optional[BackendS
mspauth = False mspauth = False
body = await req.read() body = await req.read()
root = parse_xml(body[:body.rfind(b'>') + 1]) root = parse_xml(body)
token = find_element(root, 'TicketToken') token = find_element(root, 'TicketToken')
if token is None: if token is None:
@@ -48,66 +48,6 @@ async def preprocess_soap(req: web.Request) -> Tuple[Any, Any, Optional[BackendS
return header, action, backend_sess, token return header, action, backend_sess, token
# What the Address Book and Contact Sharing services say for each of their error codes (`<errorcode>` in a fault's `<detail>`)
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: def get_tag_localname(elm: Any) -> str:
return lxml.etree.QName(elm.tag).localname return lxml.etree.QName(elm.tag).localname
@@ -150,26 +90,3 @@ def parse_cookies(cookie_string: Optional[str]) -> Dict[str, Any]:
cookie_dict[cookie_kv[0]] = cookie_data cookie_dict[cookie_kv[0]] = cookie_data
return cookie_dict 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))
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more