| 1 | use std::collections::HashMap; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 4 | |
| 5 | use futures_util::{SinkExt, StreamExt}; |
| 6 | use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode}; |
| 7 | use serde_json::{Map, Value, json}; |
| 8 | use session::{App, Method, Request, Session}; |
| 9 | use tokio::net::TcpStream; |
| 10 | use tokio::sync::{Notify, mpsc, oneshot, watch}; |
| 11 | use tokio::time::{MissedTickBehavior, interval, sleep, sleep_until, timeout}; |
| 12 | use tokio_tungstenite::tungstenite::Message; |
| 13 | use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, client_async_tls_with_config}; |
| 14 | |
| 15 | use super::RealtimeConfig; |
| 16 | use super::callback::{CallbackReply, decode_callback}; |
| 17 | use super::event::{RealtimeEvent, StatusEvent, StatusKind, decode_payload}; |
| 18 | use super::host::ic3_scope; |
| 19 | use super::runner::CallbackPipes; |
| 20 | |
| 21 | const REGISTRAR: &str = "https://teams.cloud.microsoft/registrar/prod/V2/registrations"; |
| 22 | const UI_VERSION: &str = "1415/26091712213"; |
| 23 | const CLIENT_VERSION: &str = "2026.36.01.1"; |
| 24 | const PING_EVERY: Duration = Duration::from_secs(30); |
| 25 | const SILENCE_LIMIT: Duration = Duration::from_secs(100); |
| 26 | const REREGISTER_AFTER: Duration = Duration::from_secs(40 * 60); |
| 27 | const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); |
| 28 | const ADDRESS_TIMEOUT: Duration = Duration::from_secs(5); |
| 29 | const MAX_BACKOFF: Duration = Duration::from_secs(30); |
| 30 | const ACTIVITY_DEBOUNCE: Duration = Duration::from_secs(1); |
| 31 | const ACTIVITY_ACK_TIMEOUT: Duration = Duration::from_secs(10); |
| 32 | const CALLBACK_REPLY_TIMEOUT: Duration = Duration::from_secs(5); |
| 33 | const STOP_STEP_TIMEOUT: Duration = Duration::from_secs(10); |
| 34 | const CALLBACK_PREFIX: &str = "callAgent/"; |
| 35 | const MAX_PRESENCE_ENTRIES: usize = 1000; |
| 36 | const MAX_PRESENCE_FIELD: usize = 128; |
| 37 | const MAX_SENDER_NAME: usize = 256; |
| 38 | const MAX_RESOURCE_TYPE: usize = 64; |
| 39 | const MAX_LOSS_DETAIL: usize = 200; |
| 40 | const TOKEN_BODY: &str = "return token;"; |
| 41 | |
| 42 | type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>; |
| 43 | |
| 44 | /// One Trouter frame: `type:id:endpoint:data`. |
| 45 | #[derive(Debug, PartialEq, Eq)] |
| 46 | pub(super) struct Frame<'a> { |
| 47 | pub kind: char, |
| 48 | pub data: &'a str, |
| 49 | } |
| 50 | |
| 51 | pub(super) fn parse_frame(text: &str) -> Option<Frame<'_>> { |
| 52 | let mut parts = text.splitn(4, ':'); |
| 53 | let kind = parts.next()?; |
| 54 | let (Some(_id), Some(_endpoint)) = (parts.next(), parts.next()) else { |
| 55 | return None; |
| 56 | }; |
| 57 | let mut chars = kind.chars(); |
| 58 | let kind = chars |
| 59 | .next() |
| 60 | .filter(|kind| kind.is_ascii_digit() && chars.next().is_none())?; |
| 61 | Some(Frame { |
| 62 | kind, |
| 63 | data: parts.next().unwrap_or(""), |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | pub(super) fn socket_url(host: &str, endpoint_id: &str, correlation: &str, now_ms: u128) -> String { |
| 68 | let client_info = |
| 69 | json!({"cv": CLIENT_VERSION, "ua": "TeamsCDL", "hr": "", "v": UI_VERSION}).to_string(); |
| 70 | format!( |
| 71 | "wss://{host}/v4/c?tc={}&timeout=40&epid={endpoint_id}&ccid=&cor_id={correlation}&con_num={now_ms}_0", |
| 72 | percent_encode(&client_info) |
| 73 | ) |
| 74 | } |
| 75 | |
| 76 | const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC |
| 77 | .remove(b'-') |
| 78 | .remove(b'_') |
| 79 | .remove(b'.') |
| 80 | .remove(b'!') |
| 81 | .remove(b'~') |
| 82 | .remove(b'*') |
| 83 | .remove(b'\'') |
| 84 | .remove(b'(') |
| 85 | .remove(b')'); |
| 86 | |
| 87 | fn percent_encode(text: &str) -> String { |
| 88 | utf8_percent_encode(text, URI_COMPONENT).to_string() |
| 89 | } |
| 90 | |
| 91 | pub(super) fn registration_body(ringable: bool, endpoint_id: &str, surl: &str) -> Value { |
| 92 | let (app_id, template_key) = if ringable { |
| 93 | ("SkypeSpacesWeb", "SkypeSpacesWeb_2.6") |
| 94 | } else { |
| 95 | ("TeamsCDLWebWorker", "TeamsCDLWebWorker_2.6") |
| 96 | }; |
| 97 | let mut description = json!({ |
| 98 | "appId": app_id, "aesKey": "", "languageId": "en-US", "platform": "chrome", |
| 99 | "templateKey": template_key, "platformUIVersion": UI_VERSION, |
| 100 | }); |
| 101 | if ringable { |
| 102 | description["productContext"] = json!(""); |
| 103 | } |
| 104 | json!({ |
| 105 | "clientDescription": description, |
| 106 | "registrationId": endpoint_id, "nodeId": "", |
| 107 | "transports": {"TROUTER": [{"context": "", "path": surl, "ttl": 3600}]}, |
| 108 | }) |
| 109 | } |
| 110 | |
| 111 | fn header_value(headers: &Value, name: &str) -> Option<String> { |
| 112 | let headers = headers.as_object()?; |
| 113 | headers |
| 114 | .iter() |
| 115 | .find(|(key, _)| key.eq_ignore_ascii_case(name)) |
| 116 | .map(|(_, value)| match value { |
| 117 | Value::String(text) => text.clone(), |
| 118 | other => other.to_string(), |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | /// Headers a callback reply echoes back to Trouter. |
| 123 | pub(super) fn echoed_headers(headers: &Value) -> Value { |
| 124 | let mut echoed = Map::new(); |
| 125 | for name in ["X-Microsoft-Skype-Chain-ID", "trouter-request"] { |
| 126 | if let Some(value) = header_value(headers, name) { |
| 127 | echoed.insert(name.to_owned(), Value::String(value)); |
| 128 | } |
| 129 | } |
| 130 | if let Some(correlation) = header_value(headers, "MS-CV") { |
| 131 | echoed.insert( |
| 132 | "MS-CV".to_owned(), |
| 133 | Value::String(format!("{correlation}.0")), |
| 134 | ); |
| 135 | } |
| 136 | Value::Object(echoed) |
| 137 | } |
| 138 | |
| 139 | fn request_path(url: &str) -> String { |
| 140 | let Some(rest) = url.strip_prefix("/v4/f/") else { |
| 141 | return url.to_owned(); |
| 142 | }; |
| 143 | match rest.split_once('/') { |
| 144 | Some((_, path)) => path.to_owned(), |
| 145 | None => url.to_owned(), |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | fn conversation_of(resource: &Value) -> String { |
| 150 | let link = ["conversationLink", "to", "id"] |
| 151 | .iter() |
| 152 | .find_map(|key| { |
| 153 | resource |
| 154 | .get(key) |
| 155 | .and_then(Value::as_str) |
| 156 | .filter(|value| !value.is_empty()) |
| 157 | }) |
| 158 | .unwrap_or(""); |
| 159 | let raw = match link.find("conversations/") { |
| 160 | Some(start) => { |
| 161 | let after = &link[start + "conversations/".len()..]; |
| 162 | after.split([';', '/', '?']).next().unwrap_or("") |
| 163 | } |
| 164 | None => link.split(';').next().unwrap_or(""), |
| 165 | }; |
| 166 | percent_decode(raw).unwrap_or_else(|| raw.to_owned()) |
| 167 | } |
| 168 | |
| 169 | fn percent_decode(text: &str) -> Option<String> { |
| 170 | percent_decode_str(text) |
| 171 | .decode_utf8() |
| 172 | .ok() |
| 173 | .map(|decoded| decoded.into_owned()) |
| 174 | } |
| 175 | |
| 176 | fn classify(resource_type: &str, message_type: &str) -> &'static str { |
| 177 | match resource_type { |
| 178 | "NewMessage" => { |
| 179 | if message_type.starts_with("Control/Typing") |
| 180 | || message_type.starts_with("Control/ClearTyping") |
| 181 | { |
| 182 | "typing" |
| 183 | } else if message_type == "ThreadActivity/MemberConsumptionHorizonUpdate" { |
| 184 | "read_receipt" |
| 185 | } else if message_type == "ThreadActivity/PinnedItemsUpdate" { |
| 186 | "pins_changed" |
| 187 | } else if message_type.starts_with("ThreadActivity/") { |
| 188 | "thread_activity" |
| 189 | } else if message_type.starts_with("Control/") { |
| 190 | "control" |
| 191 | } else { |
| 192 | "new_message" |
| 193 | } |
| 194 | } |
| 195 | "MessageUpdate" => "message_update", |
| 196 | "ThreadUpdate" => "thread_update", |
| 197 | _ => "other", |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | fn cut(text: &str, limit: usize) -> String { |
| 202 | text.chars().take(limit).collect() |
| 203 | } |
| 204 | |
| 205 | fn typing_sender(from: &str) -> Option<String> { |
| 206 | let lower = from.to_ascii_lowercase(); |
| 207 | let start = lower.rfind("/contacts/8:orgid:")? + "/contacts/8:orgid:".len(); |
| 208 | let id = from[start..].trim_end_matches('/'); |
| 209 | (!id.is_empty() |
| 210 | && id.len() <= 64 |
| 211 | && id |
| 212 | .chars() |
| 213 | .all(|character| character.is_ascii_hexdigit() || character == '-')) |
| 214 | .then(|| id.to_owned()) |
| 215 | } |
| 216 | |
| 217 | /// The same message the page worker forwards for a Trouter notification. |
| 218 | pub(super) fn notification_payload( |
| 219 | path: &str, |
| 220 | body: Option<&Value>, |
| 221 | received_at_ms: i64, |
| 222 | ) -> Option<Value> { |
| 223 | if path == "unifiedPresenceService" { |
| 224 | let entries: Vec<Value> = body |
| 225 | .and_then(|body| body.get("presence")) |
| 226 | .and_then(Value::as_array) |
| 227 | .into_iter() |
| 228 | .flatten() |
| 229 | .take(MAX_PRESENCE_ENTRIES) |
| 230 | .filter_map(|entry| { |
| 231 | let text = |pointer: &str| entry.pointer(pointer).and_then(Value::as_str).map(|value| cut(value, MAX_PRESENCE_FIELD)); |
| 232 | let mri = text("/mri")?; |
| 233 | let availability = text("/presence/availability")?; |
| 234 | Some(json!({ |
| 235 | "mri": mri, "availability": availability, "activity": text("/presence/activity"), |
| 236 | "outOfOffice": entry.pointer("/presence/calendarData/isOutOfOffice").and_then(Value::as_bool).unwrap_or(false), |
| 237 | })) |
| 238 | }) |
| 239 | .collect(); |
| 240 | return (!entries.is_empty()).then(|| json!({"channel": "presence", "entries": entries})); |
| 241 | } |
| 242 | let resource = body |
| 243 | .and_then(|body| body.get("resource")) |
| 244 | .filter(|resource| !resource.is_null()); |
| 245 | let resource_type = body |
| 246 | .and_then(|body| body.get("resourceType")) |
| 247 | .and_then(Value::as_str) |
| 248 | .filter(|value| !value.is_empty()) |
| 249 | .unwrap_or(if path.is_empty() { "unknown" } else { path }); |
| 250 | let resource_type = cut(resource_type, MAX_RESOURCE_TYPE); |
| 251 | let message_type = resource |
| 252 | .and_then(|resource| resource.get("messagetype")) |
| 253 | .and_then(Value::as_str) |
| 254 | .unwrap_or(""); |
| 255 | let event_kind = if path == "messaging" { |
| 256 | classify(&resource_type, message_type) |
| 257 | } else { |
| 258 | "other" |
| 259 | }; |
| 260 | let message_like = matches!(event_kind, "new_message" | "message_update"); |
| 261 | let mut payload = json!({ |
| 262 | "channel": "event", "resourceType": resource_type, "eventKind": event_kind, "receivedAt": received_at_ms, |
| 263 | "conversationId": resource.map(conversation_of).filter(|id| !id.is_empty()), |
| 264 | "messageId": resource.filter(|_| message_like).and_then(|resource| resource.get("id")).map(|id| match id { |
| 265 | Value::String(text) => text.clone(), |
| 266 | other => other.to_string(), |
| 267 | }), |
| 268 | }); |
| 269 | if event_kind == "typing" |
| 270 | && let Some(resource) = resource |
| 271 | { |
| 272 | payload["typing"] = json!(if message_type.starts_with("Control/ClearTyping") { |
| 273 | "clear" |
| 274 | } else { |
| 275 | "start" |
| 276 | }); |
| 277 | payload["senderId"] = json!( |
| 278 | resource |
| 279 | .get("from") |
| 280 | .and_then(Value::as_str) |
| 281 | .and_then(typing_sender) |
| 282 | ); |
| 283 | payload["senderName"] = json!( |
| 284 | resource |
| 285 | .get("imdisplayname") |
| 286 | .and_then(Value::as_str) |
| 287 | .map(|name| cut(name, MAX_SENDER_NAME)) |
| 288 | ); |
| 289 | } |
| 290 | Some(payload) |
| 291 | } |
| 292 | |
| 293 | fn now_ms() -> i64 { |
| 294 | SystemTime::now() |
| 295 | .duration_since(UNIX_EPOCH) |
| 296 | .map_or(0, |elapsed| elapsed.as_millis() as i64) |
| 297 | } |
| 298 | |
| 299 | fn status_payload(kind: &str, detail: &str) -> String { |
| 300 | json!({"channel": "status", "kind": kind, "detail": detail}).to_string() |
| 301 | } |
| 302 | |
| 303 | struct PendingReply { |
| 304 | headers: Value, |
| 305 | deadline: tokio::time::Instant, |
| 306 | } |
| 307 | |
| 308 | enum Ended { |
| 309 | Stopped(Option<oneshot::Sender<()>>), |
| 310 | Lost { was_ready: bool }, |
| 311 | } |
| 312 | |
| 313 | /// Trouter over a websocket of its own; only the token lookup and the registrar calls run in the app tab, which may stay parked. |
| 314 | pub(super) struct NativeTrouter { |
| 315 | pub session: Session, |
| 316 | pub config: RealtimeConfig, |
| 317 | pub host: String, |
| 318 | pub output: mpsc::UnboundedSender<RealtimeEvent>, |
| 319 | pub callbacks: CallbackPipes, |
| 320 | pub activity: watch::Receiver<bool>, |
| 321 | pub resend: Arc<Notify>, |
| 322 | pub endpoint_id: String, |
| 323 | force_refresh: bool, |
| 324 | retry: u32, |
| 325 | retry_signal: Option<Arc<Notify>>, |
| 326 | ack_counter: u64, |
| 327 | surl: String, |
| 328 | registered_at: Option<Instant>, |
| 329 | } |
| 330 | |
| 331 | struct Connection { |
| 332 | socket: Socket, |
| 333 | token: String, |
| 334 | ready: bool, |
| 335 | last_frame: Instant, |
| 336 | sent_activity: Option<bool>, |
| 337 | activity_ack_id: u64, |
| 338 | activity_due: Option<tokio::time::Instant>, |
| 339 | activity_resend_due: Option<tokio::time::Instant>, |
| 340 | pending: HashMap<i64, PendingReply>, |
| 341 | } |
| 342 | |
| 343 | fn far_future() -> tokio::time::Instant { |
| 344 | tokio::time::Instant::now() + Duration::from_secs(365 * 24 * 3600) |
| 345 | } |
| 346 | |
| 347 | impl NativeTrouter { |
| 348 | pub(super) fn new( |
| 349 | session: Session, |
| 350 | config: RealtimeConfig, |
| 351 | host: String, |
| 352 | output: mpsc::UnboundedSender<RealtimeEvent>, |
| 353 | callbacks: CallbackPipes, |
| 354 | activity: watch::Receiver<bool>, |
| 355 | resend: Arc<Notify>, |
| 356 | ) -> Self { |
| 357 | let retry_signal = config.retry.clone(); |
| 358 | NativeTrouter { |
| 359 | session, |
| 360 | config, |
| 361 | host, |
| 362 | output, |
| 363 | callbacks, |
| 364 | activity, |
| 365 | resend, |
| 366 | endpoint_id: uuid::Uuid::new_v4().to_string(), |
| 367 | force_refresh: false, |
| 368 | retry: 0, |
| 369 | retry_signal, |
| 370 | ack_counter: 0, |
| 371 | surl: String::new(), |
| 372 | registered_at: None, |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | pub(super) async fn token(&mut self) -> session::Result<String> { |
| 377 | let value = self |
| 378 | .session |
| 379 | .run_with_token( |
| 380 | App::Teams, |
| 381 | &ic3_scope(), |
| 382 | TOKEN_BODY, |
| 383 | &json!({}), |
| 384 | self.force_refresh, |
| 385 | ) |
| 386 | .await?; |
| 387 | self.force_refresh = false; |
| 388 | value |
| 389 | .as_str() |
| 390 | .map(str::to_owned) |
| 391 | .ok_or_else(|| session::Error::Cdp("token lookup gave no text".into())) |
| 392 | } |
| 393 | |
| 394 | pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) { |
| 395 | let retry_signal = self.retry_signal.clone(); |
| 396 | loop { |
| 397 | let connected = tokio::select! { |
| 398 | connected = self.connect() => connected, |
| 399 | done = &mut stop => Err(done.ok()), |
| 400 | }; |
| 401 | let ended = match connected { |
| 402 | Ok(connection) => self.drive(connection, &mut stop).await, |
| 403 | Err(Some(done)) => Ended::Stopped(Some(done)), |
| 404 | Err(None) => Ended::Lost { was_ready: false }, |
| 405 | }; |
| 406 | match ended { |
| 407 | Ended::Stopped(done) => { |
| 408 | self.unregister().await; |
| 409 | if let Some(done) = done { |
| 410 | let _ = done.send(()); |
| 411 | } |
| 412 | return; |
| 413 | } |
| 414 | Ended::Lost { was_ready } => { |
| 415 | if was_ready { |
| 416 | self.forward(&status_payload("disconnected", "closed")); |
| 417 | } |
| 418 | self.retry += 1; |
| 419 | let delay = Duration::from_secs(1u64 << self.retry.min(5)).min(MAX_BACKOFF); |
| 420 | tokio::select! { |
| 421 | _ = sleep(delay) => {} |
| 422 | done = &mut stop => { |
| 423 | self.unregister().await; |
| 424 | if let Ok(done) = done { |
| 425 | let _ = done.send(()); |
| 426 | } |
| 427 | return; |
| 428 | } |
| 429 | _ = async { |
| 430 | match &retry_signal { |
| 431 | Some(signal) => signal.notified().await, |
| 432 | None => std::future::pending().await, |
| 433 | } |
| 434 | } => self.retry = 0, |
| 435 | _ = self.output.closed() => return, |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | async fn connect(&mut self) -> Result<Connection, Option<oneshot::Sender<()>>> { |
| 443 | let token = match self.token().await { |
| 444 | Ok(token) => token, |
| 445 | Err(error) => { |
| 446 | self.forward(&status_payload( |
| 447 | "disconnected", |
| 448 | &format!("token_failed: {}", short(&error.to_string())), |
| 449 | )); |
| 450 | return Err(None); |
| 451 | } |
| 452 | }; |
| 453 | session::ensure_crypto_provider(); |
| 454 | let url = socket_url( |
| 455 | &self.host, |
| 456 | &self.endpoint_id, |
| 457 | &uuid::Uuid::new_v4().to_string(), |
| 458 | now_ms() as u128, |
| 459 | ); |
| 460 | let socket = match timeout(CONNECT_TIMEOUT, open_socket(&self.host, &url)).await { |
| 461 | Ok(Ok(socket)) => socket, |
| 462 | Ok(Err(error)) => { |
| 463 | self.forward(&status_payload( |
| 464 | "disconnected", |
| 465 | &format!("connect_failed: {}", short(&error.to_string())), |
| 466 | )); |
| 467 | return Err(None); |
| 468 | } |
| 469 | Err(_) => { |
| 470 | self.forward(&status_payload("disconnected", "connect_failed: timed out")); |
| 471 | return Err(None); |
| 472 | } |
| 473 | }; |
| 474 | Ok(Connection { |
| 475 | socket, |
| 476 | token, |
| 477 | ready: false, |
| 478 | last_frame: Instant::now(), |
| 479 | sent_activity: None, |
| 480 | activity_ack_id: 0, |
| 481 | activity_due: None, |
| 482 | activity_resend_due: None, |
| 483 | pending: HashMap::new(), |
| 484 | }) |
| 485 | } |
| 486 | |
| 487 | async fn drive( |
| 488 | &mut self, |
| 489 | mut connection: Connection, |
| 490 | stop: &mut oneshot::Receiver<oneshot::Sender<()>>, |
| 491 | ) -> Ended { |
| 492 | let mut ping = interval(PING_EVERY); |
| 493 | ping.set_missed_tick_behavior(MissedTickBehavior::Delay); |
| 494 | ping.tick().await; |
| 495 | let connect_deadline = tokio::time::Instant::now() + CONNECT_TIMEOUT; |
| 496 | loop { |
| 497 | let next_reply = connection |
| 498 | .pending |
| 499 | .values() |
| 500 | .map(|pending| pending.deadline) |
| 501 | .min() |
| 502 | .unwrap_or_else(far_future); |
| 503 | tokio::select! { |
| 504 | frame = connection.socket.next() => { |
| 505 | let Some(Ok(message)) = frame else { return Ended::Lost { was_ready: connection.ready } }; |
| 506 | let text = match message { |
| 507 | Message::Text(text) => text.to_string(), |
| 508 | Message::Close(_) => return Ended::Lost { was_ready: connection.ready }, |
| 509 | _ => continue, |
| 510 | }; |
| 511 | connection.last_frame = Instant::now(); |
| 512 | if !self.on_frame(&mut connection, &text).await { |
| 513 | let _ = connection.socket.close(None).await; |
| 514 | return Ended::Lost { was_ready: connection.ready }; |
| 515 | } |
| 516 | } |
| 517 | _ = sleep_until(connect_deadline), if !connection.ready => { |
| 518 | let _ = connection.socket.close(None).await; |
| 519 | return Ended::Lost { was_ready: false }; |
| 520 | } |
| 521 | _ = ping.tick() => { |
| 522 | if connection.last_frame.elapsed() > SILENCE_LIMIT { |
| 523 | let _ = connection.socket.close(None).await; |
| 524 | return Ended::Lost { was_ready: connection.ready }; |
| 525 | } |
| 526 | self.send_event(&mut connection, "ping", json!([])).await; |
| 527 | if connection.ready && self.registered_at.is_some_and(|at| at.elapsed() > REREGISTER_AFTER) { |
| 528 | let surl = self.surl.clone(); |
| 529 | if let Err(detail) = self.register(&surl).await { |
| 530 | self.forward(&status_payload("error", &detail)); |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | changed = self.activity.changed() => { |
| 535 | if changed.is_ok() { |
| 536 | let wanted = *self.activity.borrow_and_update(); |
| 537 | connection.activity_due = (connection.ready && connection.sent_activity != Some(wanted)).then(|| tokio::time::Instant::now() + ACTIVITY_DEBOUNCE); |
| 538 | } |
| 539 | } |
| 540 | _ = sleep_until(connection.activity_due.unwrap_or_else(far_future)), if connection.activity_due.is_some() => { |
| 541 | self.transmit_activity(&mut connection, false).await; |
| 542 | } |
| 543 | _ = sleep_until(connection.activity_resend_due.unwrap_or_else(far_future)), if connection.activity_resend_due.is_some() => { |
| 544 | self.transmit_activity(&mut connection, true).await; |
| 545 | } |
| 546 | _ = self.resend.notified() => self.transmit_activity(&mut connection, false).await, |
| 547 | Some(reply) = self.callbacks.replies.recv() => self.answer(&mut connection, reply).await, |
| 548 | _ = sleep_until(next_reply), if !connection.pending.is_empty() => { |
| 549 | let now = tokio::time::Instant::now(); |
| 550 | let due: Vec<i64> = connection.pending.iter().filter(|(_, pending)| pending.deadline <= now).map(|(id, _)| *id).collect(); |
| 551 | for request_id in due { |
| 552 | self.answer(&mut connection, CallbackReply { request_id, status: 200, body: String::new() }).await; |
| 553 | } |
| 554 | } |
| 555 | done = &mut *stop => { |
| 556 | let _ = connection.socket.close(None).await; |
| 557 | return Ended::Stopped(done.ok()); |
| 558 | } |
| 559 | _ = self.output.closed() => { |
| 560 | let _ = connection.socket.close(None).await; |
| 561 | return Ended::Stopped(None); |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | /// Answers whether the connection should stay open. |
| 568 | async fn on_frame(&mut self, connection: &mut Connection, text: &str) -> bool { |
| 569 | let Some(frame) = parse_frame(text) else { |
| 570 | return true; |
| 571 | }; |
| 572 | match frame.kind { |
| 573 | '1' => { |
| 574 | let authenticate = json!({"name": "user.authenticate", "args": [{"headers": { |
| 575 | "X-Ms-Test-User": "False", "Authorization": format!("Bearer {}", connection.token), "X-MS-Migration": "True", |
| 576 | }}]}); |
| 577 | send(connection, format!("5:::{authenticate}")).await; |
| 578 | } |
| 579 | '2' => send(connection, "2::".to_owned()).await, |
| 580 | '5' => { |
| 581 | let Ok(event) = serde_json::from_str::<Value>(frame.data) else { |
| 582 | return true; |
| 583 | }; |
| 584 | match event.get("name").and_then(Value::as_str) { |
| 585 | Some("trouter.connected") => { |
| 586 | let surl = event |
| 587 | .pointer("/args/0/surl") |
| 588 | .and_then(Value::as_str) |
| 589 | .unwrap_or_default() |
| 590 | .to_owned(); |
| 591 | if let Err(detail) = self.register(&surl).await { |
| 592 | self.forward(&status_payload("error", &detail)); |
| 593 | return false; |
| 594 | } |
| 595 | connection.ready = true; |
| 596 | self.retry = 0; |
| 597 | self.transmit_activity(connection, false).await; |
| 598 | let endpoint = json!({"channel": "endpoint", "endpointId": self.endpoint_id, "trouterUri": format!("{}/unifiedPresenceService", self.surl)}); |
| 599 | self.forward(&endpoint.to_string()); |
| 600 | self.forward(&status_payload("connected", "")); |
| 601 | } |
| 602 | Some("trouter.message_loss") => { |
| 603 | let args = event.get("args").cloned().unwrap_or(Value::Null); |
| 604 | let dropped: Vec<String> = args |
| 605 | .pointer("/0/droppedIndicators") |
| 606 | .and_then(Value::as_array) |
| 607 | .into_iter() |
| 608 | .flatten() |
| 609 | .map(|indicator| { |
| 610 | indicator |
| 611 | .get("tag") |
| 612 | .map(|tag| { |
| 613 | tag.as_str().map_or_else(|| tag.to_string(), str::to_owned) |
| 614 | }) |
| 615 | .unwrap_or_default() |
| 616 | }) |
| 617 | .collect(); |
| 618 | self.send_event(connection, "trouter.processed_message_loss", args) |
| 619 | .await; |
| 620 | self.forward(&status_payload( |
| 621 | "message_loss", |
| 622 | &cut(&dropped.join(","), MAX_LOSS_DETAIL), |
| 623 | )); |
| 624 | } |
| 625 | _ => {} |
| 626 | } |
| 627 | } |
| 628 | '6' => { |
| 629 | if frame |
| 630 | .data |
| 631 | .split('+') |
| 632 | .next() |
| 633 | .and_then(|id| id.parse::<u64>().ok()) |
| 634 | == Some(connection.activity_ack_id) |
| 635 | { |
| 636 | connection.activity_resend_due = None; |
| 637 | } |
| 638 | } |
| 639 | '3' => { |
| 640 | let Ok(request) = serde_json::from_str::<Value>(frame.data) else { |
| 641 | return true; |
| 642 | }; |
| 643 | let Some(request_id) = request.get("id").and_then(Value::as_i64) else { |
| 644 | return true; |
| 645 | }; |
| 646 | let path = request_path(request.get("url").and_then(Value::as_str).unwrap_or("")); |
| 647 | let raw_body = match request.get("body") { |
| 648 | Some(Value::String(text)) => text.clone(), |
| 649 | Some(Value::Null) | None => "null".to_owned(), |
| 650 | Some(other) => other.to_string(), |
| 651 | }; |
| 652 | let headers = request.get("headers").cloned().unwrap_or(Value::Null); |
| 653 | if self.config.forward_callbacks && path.starts_with(CALLBACK_PREFIX) { |
| 654 | connection.pending.insert( |
| 655 | request_id, |
| 656 | PendingReply { |
| 657 | headers: echoed_headers(&headers), |
| 658 | deadline: tokio::time::Instant::now() + CALLBACK_REPLY_TIMEOUT, |
| 659 | }, |
| 660 | ); |
| 661 | let callback = json!({"channel": "callback", "requestId": request_id, "path": path, |
| 662 | "contentEncoding": header_value(&headers, "X-Microsoft-Skype-Content-Encoding"), "body": raw_body}); |
| 663 | self.forward(&callback.to_string()); |
| 664 | return true; |
| 665 | } |
| 666 | send( |
| 667 | connection, |
| 668 | format!( |
| 669 | "3:::{}", |
| 670 | json!({"id": request_id, "status": 200, "headers": {}, "body": ""}) |
| 671 | ), |
| 672 | ) |
| 673 | .await; |
| 674 | let body = serde_json::from_str::<Value>(&raw_body).ok(); |
| 675 | if self.config.forward_callbacks |
| 676 | && body |
| 677 | .as_ref() |
| 678 | .is_some_and(|body| body.get("evt").is_some_and(Value::is_number)) |
| 679 | { |
| 680 | let callback = json!({"channel": "callback", "requestId": request_id, "path": "", "contentEncoding": null, "body": raw_body}); |
| 681 | self.forward(&callback.to_string()); |
| 682 | return true; |
| 683 | } |
| 684 | if let Some(payload) = notification_payload(&path, body.as_ref(), now_ms()) { |
| 685 | self.forward(&payload.to_string()); |
| 686 | } |
| 687 | } |
| 688 | _ => {} |
| 689 | } |
| 690 | true |
| 691 | } |
| 692 | |
| 693 | async fn answer(&mut self, connection: &mut Connection, reply: CallbackReply) { |
| 694 | let Some(pending) = connection.pending.remove(&reply.request_id) else { |
| 695 | return; |
| 696 | }; |
| 697 | let frame = json!({"id": reply.request_id, "status": reply.status, "headers": pending.headers, "body": reply.body}); |
| 698 | send(connection, format!("3:::{frame}")).await; |
| 699 | } |
| 700 | |
| 701 | async fn send_event(&mut self, connection: &mut Connection, name: &str, args: Value) { |
| 702 | self.ack_counter += 1; |
| 703 | send( |
| 704 | connection, |
| 705 | format!( |
| 706 | "5:{}+::{}", |
| 707 | self.ack_counter, |
| 708 | json!({"name": name, "args": args}) |
| 709 | ), |
| 710 | ) |
| 711 | .await; |
| 712 | } |
| 713 | |
| 714 | async fn transmit_activity(&mut self, connection: &mut Connection, resend: bool) { |
| 715 | connection.activity_due = None; |
| 716 | connection.activity_resend_due = None; |
| 717 | if !connection.ready { |
| 718 | return; |
| 719 | } |
| 720 | let active = *self.activity.borrow(); |
| 721 | let label = if active { "active" } else { "inactive" }; |
| 722 | self.send_event( |
| 723 | connection, |
| 724 | "user.activity", |
| 725 | json!([{"state": label, "cv": uuid::Uuid::new_v4().to_string()}]), |
| 726 | ) |
| 727 | .await; |
| 728 | connection.sent_activity = Some(active); |
| 729 | connection.activity_ack_id = self.ack_counter; |
| 730 | if !resend { |
| 731 | connection.activity_resend_due = |
| 732 | Some(tokio::time::Instant::now() + ACTIVITY_ACK_TIMEOUT); |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | async fn register(&mut self, surl: &str) -> Result<(), String> { |
| 737 | if !surl.is_empty() { |
| 738 | self.surl = surl.to_owned(); |
| 739 | } |
| 740 | let mut request = Request::with_body( |
| 741 | Method::Post, |
| 742 | REGISTRAR, |
| 743 | registration_body(self.config.ringable, &self.endpoint_id, &self.surl), |
| 744 | ); |
| 745 | request.headers.extend([ |
| 746 | ("X-MS-Migration".to_owned(), "True".to_owned()), |
| 747 | ( |
| 748 | "Accept".to_owned(), |
| 749 | "application/json, text/javascript".to_owned(), |
| 750 | ), |
| 751 | ]); |
| 752 | match self.session.send(request, &ic3_scope()).await { |
| 753 | Ok(_) => { |
| 754 | self.registered_at = Some(Instant::now()); |
| 755 | Ok(()) |
| 756 | } |
| 757 | Err(session::Error::Api { status, .. }) => { |
| 758 | if matches!(status, 401 | 403) { |
| 759 | self.force_refresh = true; |
| 760 | } |
| 761 | Err(format!("registrar_http_{status}")) |
| 762 | } |
| 763 | Err(_) => Err("registrar_failed".to_owned()), |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | async fn unregister(&self) { |
| 768 | if self.registered_at.is_none() { |
| 769 | return; |
| 770 | } |
| 771 | let mut request = Request::get(format!("{REGISTRAR}/{}", self.endpoint_id)); |
| 772 | request.method = Method::Delete; |
| 773 | request |
| 774 | .headers |
| 775 | .push(("X-MS-Migration".to_owned(), "True".to_owned())); |
| 776 | let _ = timeout(STOP_STEP_TIMEOUT, self.session.send(request, &ic3_scope())).await; |
| 777 | } |
| 778 | |
| 779 | fn forward(&mut self, payload: &str) { |
| 780 | if let Some(callback) = decode_callback(payload) { |
| 781 | let _ = self.callbacks.output.send(callback); |
| 782 | return; |
| 783 | } |
| 784 | if let Ok(event) = decode_payload(payload) { |
| 785 | if let RealtimeEvent::Status(StatusEvent { |
| 786 | kind: StatusKind::Error, |
| 787 | detail, |
| 788 | }) = &event |
| 789 | && matches!(detail.as_str(), "registrar_http_401" | "registrar_http_403") |
| 790 | { |
| 791 | self.force_refresh = true; |
| 792 | } |
| 793 | let _ = self.output.send(event); |
| 794 | } |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | /// IPv4 first: on some networks the IPv6 address of the Trouter host takes longer than the whole connect budget to fail. |
| 799 | async fn open_socket( |
| 800 | host: &str, |
| 801 | url: &str, |
| 802 | ) -> Result<Socket, tokio_tungstenite::tungstenite::Error> { |
| 803 | let mut addresses: Vec<std::net::SocketAddr> = |
| 804 | tokio::net::lookup_host((host, 443)).await?.collect(); |
| 805 | addresses.sort_by_key(|address| address.is_ipv6()); |
| 806 | let mut last_error = std::io::Error::new(std::io::ErrorKind::NotFound, "no address"); |
| 807 | for address in addresses { |
| 808 | match timeout(ADDRESS_TIMEOUT, TcpStream::connect(address)).await { |
| 809 | Ok(Ok(stream)) => { |
| 810 | let (socket, _) = client_async_tls_with_config(url, stream, None, None).await?; |
| 811 | return Ok(socket); |
| 812 | } |
| 813 | Ok(Err(error)) => last_error = error, |
| 814 | Err(_) => { |
| 815 | last_error = std::io::Error::new( |
| 816 | std::io::ErrorKind::TimedOut, |
| 817 | format!( |
| 818 | "{} timed out", |
| 819 | if address.is_ipv6() { "IPv6" } else { "IPv4" } |
| 820 | ), |
| 821 | ) |
| 822 | } |
| 823 | } |
| 824 | } |
| 825 | Err(last_error.into()) |
| 826 | } |
| 827 | |
| 828 | async fn send(connection: &mut Connection, text: String) { |
| 829 | let _ = connection.socket.send(Message::Text(text.into())).await; |
| 830 | } |
| 831 | |
| 832 | fn short(text: &str) -> String { |
| 833 | text.chars().take(120).collect() |
| 834 | } |
| 835 | |
| 836 | #[cfg(test)] |
| 837 | mod tests { |
| 838 | use super::*; |
| 839 | |
| 840 | #[test] |
| 841 | fn frames_split_into_type_and_data() { |
| 842 | assert_eq!( |
| 843 | parse_frame("1::"), |
| 844 | Some(Frame { |
| 845 | kind: '1', |
| 846 | data: "" |
| 847 | }) |
| 848 | ); |
| 849 | assert_eq!( |
| 850 | parse_frame("5:3+::{\"a\":1}"), |
| 851 | Some(Frame { |
| 852 | kind: '5', |
| 853 | data: "{\"a\":1}" |
| 854 | }) |
| 855 | ); |
| 856 | assert_eq!( |
| 857 | parse_frame("3:::{\"x\":\"a:b\"}"), |
| 858 | Some(Frame { |
| 859 | kind: '3', |
| 860 | data: "{\"x\":\"a:b\"}" |
| 861 | }) |
| 862 | ); |
| 863 | assert_eq!(parse_frame("garbage"), None); |
| 864 | assert_eq!(parse_frame("12::"), None); |
| 865 | } |
| 866 | |
| 867 | #[test] |
| 868 | fn the_socket_url_carries_the_endpoint_and_encoded_client_info() { |
| 869 | let url = socket_url("go-eu.trouter.teams.microsoft.com", "ep-1", "cor-1", 42); |
| 870 | assert!( |
| 871 | url.starts_with("wss://go-eu.trouter.teams.microsoft.com/v4/c?tc=%7B%22cv%22"), |
| 872 | "{url}" |
| 873 | ); |
| 874 | assert!( |
| 875 | url.ends_with("&timeout=40&epid=ep-1&ccid=&cor_id=cor-1&con_num=42_0"), |
| 876 | "{url}" |
| 877 | ); |
| 878 | } |
| 879 | |
| 880 | #[test] |
| 881 | fn ringable_registration_uses_the_calling_app() { |
| 882 | let calling = registration_body(true, "ep", "https://surl/"); |
| 883 | assert_eq!(calling["clientDescription"]["appId"], "SkypeSpacesWeb"); |
| 884 | assert_eq!(calling["clientDescription"]["productContext"], ""); |
| 885 | let worker = registration_body(false, "ep", "https://surl/"); |
| 886 | assert_eq!( |
| 887 | worker["clientDescription"]["templateKey"], |
| 888 | "TeamsCDLWebWorker_2.6" |
| 889 | ); |
| 890 | assert!(worker["clientDescription"].get("productContext").is_none()); |
| 891 | assert_eq!(worker["transports"]["TROUTER"][0]["path"], "https://surl/"); |
| 892 | } |
| 893 | |
| 894 | #[test] |
| 895 | fn callback_replies_echo_chain_request_and_correlation() { |
| 896 | let echoed = echoed_headers( |
| 897 | &json!({"x-microsoft-skype-chain-id": "c", "Trouter-Request": "r", "ms-cv": "abc", "Other": "o"}), |
| 898 | ); |
| 899 | assert_eq!( |
| 900 | echoed, |
| 901 | json!({"X-Microsoft-Skype-Chain-ID": "c", "trouter-request": "r", "MS-CV": "abc.0"}) |
| 902 | ); |
| 903 | } |
| 904 | |
| 905 | #[test] |
| 906 | fn request_paths_drop_the_forwarding_prefix() { |
| 907 | assert_eq!(request_path("/v4/f/abc123/messaging"), "messaging"); |
| 908 | assert_eq!(request_path("/v4/f/abc/callAgent/x/y"), "callAgent/x/y"); |
| 909 | assert_eq!(request_path("messaging"), "messaging"); |
| 910 | } |
| 911 | |
| 912 | #[test] |
| 913 | fn a_message_notification_becomes_the_page_event() { |
| 914 | let body = json!({"resourceType": "NewMessage", "resource": {"messagetype": "RichText/Html", "id": "177", |
| 915 | "conversationLink": "https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2"}}); |
| 916 | let payload = notification_payload("messaging", Some(&body), 5).unwrap(); |
| 917 | assert_eq!(payload["eventKind"], "new_message"); |
| 918 | assert_eq!(payload["conversationId"], "19:abc@thread.v2"); |
| 919 | assert_eq!(payload["messageId"], "177"); |
| 920 | assert!(matches!( |
| 921 | decode_payload(&payload.to_string()), |
| 922 | Ok(RealtimeEvent::Message(_)) |
| 923 | )); |
| 924 | } |
| 925 | |
| 926 | #[test] |
| 927 | fn typing_names_the_sender() { |
| 928 | let body = json!({"resourceType": "NewMessage", "resource": {"messagetype": "Control/Typing", "imdisplayname": "Ada", |
| 929 | "from": "https://x/v1/users/ME/contacts/8:orgid:0a1b2c3d-0000-0000-0000-000000000000", "conversationLink": "conversations/19:t@thread.v2"}}); |
| 930 | let payload = notification_payload("messaging", Some(&body), 5).unwrap(); |
| 931 | assert_eq!(payload["eventKind"], "typing"); |
| 932 | assert_eq!(payload["typing"], "start"); |
| 933 | assert_eq!(payload["senderId"], "0a1b2c3d-0000-0000-0000-000000000000"); |
| 934 | assert_eq!(payload["senderName"], "Ada"); |
| 935 | assert!(payload["messageId"].is_null()); |
| 936 | } |
| 937 | |
| 938 | #[test] |
| 939 | fn presence_keeps_entries_with_an_availability() { |
| 940 | let body = json!({"presence": [{"mri": "8:orgid:a", "presence": {"availability": "Available", "activity": "Available"}}, {"mri": "8:orgid:b"}]}); |
| 941 | let payload = notification_payload("unifiedPresenceService", Some(&body), 5).unwrap(); |
| 942 | assert_eq!(payload["entries"].as_array().unwrap().len(), 1); |
| 943 | assert!( |
| 944 | notification_payload("unifiedPresenceService", Some(&json!({"presence": []})), 5) |
| 945 | .is_none() |
| 946 | ); |
| 947 | } |
| 948 | } |