Skip to main content

libsignal_service/websocket/
mod.rs

1use std::collections::{HashMap, HashSet};
2use std::marker::PhantomData;
3use std::sync::{Arc, Mutex, MutexGuard};
4
5use std::future::Future;
6
7use bytes::Bytes;
8use futures::channel::oneshot::Canceled;
9use futures::channel::{mpsc, oneshot};
10use futures::future::BoxFuture;
11use futures::prelude::*;
12use futures::stream::FuturesUnordered;
13use reqwest::Method;
14use reqwest_websocket::WebSocket;
15use tokio::time::Instant;
16use tracing::debug;
17
18use crate::configuration::SignalServers;
19use crate::prelude::PushService;
20use crate::proto::{
21    web_socket_message, WebSocketMessage, WebSocketRequestMessage,
22    WebSocketResponseMessage,
23};
24use crate::push_service::{self, ServiceError, SignalServiceResponse};
25
26pub mod account;
27pub mod calling;
28#[cfg(feature = "cdsi")]
29pub mod directory;
30pub mod keys;
31pub mod linking;
32pub mod profile;
33pub mod registration;
34mod request;
35mod sender;
36pub mod stickers;
37mod usernames;
38
39pub use request::WebSocketRequestMessageBuilder;
40
41type RequestStreamItem = (
42    WebSocketRequestMessage,
43    oneshot::Sender<WebSocketResponseMessage>,
44);
45
46pub struct SignalRequestStream {
47    inner: mpsc::UnboundedReceiver<RequestStreamItem>,
48}
49
50impl Stream for SignalRequestStream {
51    type Item = RequestStreamItem;
52
53    fn poll_next(
54        mut self: std::pin::Pin<&mut Self>,
55        cx: &mut std::task::Context<'_>,
56    ) -> std::task::Poll<Option<Self::Item>> {
57        let inner = &mut self.inner;
58        futures::pin_mut!(inner);
59        Stream::poll_next(inner, cx)
60    }
61}
62
63#[derive(Debug, Clone)]
64pub struct Identified;
65
66#[derive(Debug, Clone)]
67pub struct Unidentified;
68
69pub trait WebSocketType: 'static {}
70
71impl WebSocketType for Identified {}
72
73impl WebSocketType for Unidentified {}
74
75/// A dispatching web socket client for the Signal web socket API.
76///
77/// This structure can be freely cloned, since this acts as a *facade* for multiple entry and exit
78/// points.
79#[derive(Clone)]
80pub struct SignalWebSocket<C: WebSocketType> {
81    _type: PhantomData<C>,
82    // XXX: at the end of the migration, this should be CDN operations only
83    pub(crate) unidentified_push_service: PushService,
84    inner: Arc<Mutex<SignalWebSocketInner>>,
85    request_sink: mpsc::Sender<(
86        WebSocketRequestMessage,
87        oneshot::Sender<Result<WebSocketResponseMessage, ServiceError>>,
88    )>,
89}
90
91struct SignalWebSocketInner {
92    stream: Option<SignalRequestStream>,
93}
94
95struct SignalWebSocketProcess {
96    /// Whether to enable keep-alive or not (and send a request to this path)
97    keep_alive_path: String,
98
99    /// Receives requests from the application, which we forward to Signal.
100    requests: mpsc::Receiver<(
101        WebSocketRequestMessage,
102        oneshot::Sender<Result<WebSocketResponseMessage, ServiceError>>,
103    )>,
104    /// Signal's requests should go in here, to be delivered to the application.
105    request_sink: mpsc::UnboundedSender<RequestStreamItem>,
106
107    outgoing_requests: HashMap<
108        u64,
109        oneshot::Sender<Result<WebSocketResponseMessage, ServiceError>>,
110    >,
111
112    outgoing_keep_alive_set: HashSet<u64>,
113
114    outgoing_responses: FuturesUnordered<
115        BoxFuture<'static, Result<WebSocketResponseMessage, Canceled>>,
116    >,
117
118    ws: WebSocket,
119}
120
121impl SignalWebSocketProcess {
122    async fn process_frame(
123        &mut self,
124        frame: Bytes,
125    ) -> Result<(), ServiceError> {
126        use prost::Message;
127        let msg = WebSocketMessage::decode(frame)?;
128        if let Some(request) = &msg.request {
129            tracing::trace!(
130                msg_type =? msg.r#type(),
131                request.id,
132                request.verb,
133                request.path,
134                request_body_size_bytes = request.body.as_ref().map(|x| x.len()).unwrap_or(0),
135                ?request.headers,
136                "decoded WebSocketMessage request"
137            );
138        } else if let Some(response) = &msg.response {
139            tracing::trace!(
140                msg_type =? msg.r#type(),
141                response.status,
142                response.message,
143                response_body_size_bytes = response.body.as_ref().map(|x| x.len()).unwrap_or(0),
144                ?response.headers,
145                response.id,
146                "decoded WebSocketMessage response"
147            );
148        } else {
149            tracing::debug!("decoded {msg:?}");
150        }
151
152        use web_socket_message::Type;
153        match (msg.r#type(), msg.request, msg.response) {
154            (Type::Unknown, _, _) => Err(ServiceError::InvalidFrame {
155                reason: "unknown frame type",
156            }),
157            (Type::Request, Some(request), _) => {
158                let (sink, recv) = oneshot::channel();
159                tracing::trace!("sending request with body");
160                self.request_sink.send((request, sink)).await.map_err(
161                    |_| ServiceError::WsClosing {
162                        reason: "request handler failed",
163                    },
164                )?;
165                self.outgoing_responses.push(Box::pin(recv));
166
167                Ok(())
168            },
169            (Type::Request, None, _) => Err(ServiceError::InvalidFrame {
170                reason: "type was request, but does not contain request",
171            }),
172            (Type::Response, _, Some(response)) => {
173                if let Some(id) = response.id {
174                    if let Some(responder) = self.outgoing_requests.remove(&id)
175                    {
176                        if let Err(e) = responder.send(Ok(response)) {
177                            tracing::warn!(
178                                "Could not deliver response for id {}: {:?}",
179                                id,
180                                e
181                            );
182                        }
183                    } else if let Some(_x) =
184                        self.outgoing_keep_alive_set.take(&id)
185                    {
186                        let status = reqwest::StatusCode::from_u16(
187                            response.status() as _,
188                        )
189                        .map_err(|e| {
190                            ServiceError::IO(std::io::Error::other(format!(
191                                "invalid http status code {} - {e}",
192                                response.status()
193                            )))
194                        })?;
195                        if !status.is_success() {
196                            tracing::warn!(
197                                %status,
198                                "response code for keep-alive not successful"
199                            );
200                            return Err(ServiceError::UnhandledResponseCode {
201                                status,
202                                body: String::from_utf8_lossy(response.body())
203                                    .into_owned(),
204                            });
205                        }
206                    } else {
207                        tracing::warn!(
208                            ?response,
209                            "response for non existing request"
210                        );
211                    }
212                }
213
214                Ok(())
215            },
216            (Type::Response, _, None) => Err(ServiceError::InvalidFrame {
217                reason: "type was response, but does not contain response",
218            }),
219        }
220    }
221
222    fn next_request_id(&self) -> u64 {
223        use rand::Rng;
224        let mut rng = rand::rng();
225        loop {
226            let id = rng.random();
227            if !self.outgoing_requests.contains_key(&id) {
228                return id;
229            }
230        }
231    }
232
233    async fn run(mut self) -> Result<(), ServiceError> {
234        // A keepalive sent before the server registers our presence makes it close the socket.
235        let mut ka_interval = tokio::time::interval_at(
236            Instant::now() + push_service::KEEPALIVE_TIMEOUT_SECONDS,
237            push_service::KEEPALIVE_TIMEOUT_SECONDS,
238        );
239
240        loop {
241            futures::select! {
242                _ = ka_interval.tick().fuse() => {
243                    use prost::Message;
244                    if !self.outgoing_keep_alive_set.is_empty() {
245                        tracing::warn!("Websocket will be closed due to failed keepalives.");
246                        if let Err(e) = self.ws.close(reqwest_websocket::CloseCode::Away, None).await {
247                            tracing::debug!("Could not close WebSocket: {:?}", e);
248                        }
249                        self.outgoing_keep_alive_set.clear();
250                        break;
251                    }
252                    tracing::debug!("sending keep-alive");
253                    let request = WebSocketRequestMessage::new(Method::GET)
254                        .id(self.next_request_id())
255                        .path(&self.keep_alive_path)
256                        .build();
257                    self.outgoing_keep_alive_set.insert(request.id.unwrap());
258                    let msg = WebSocketMessage {
259                        r#type: Some(web_socket_message::Type::Request.into()),
260                        request: Some(request),
261                        ..Default::default()
262                    };
263                    let buffer = msg.encode_to_vec();
264                    if let Err(e) = self.ws.send(reqwest_websocket::Message::Binary(buffer.into())).await {
265                        tracing::info!("Websocket sink has closed: {:?}.", e);
266                        break;
267                    };
268                },
269                // Process requests from the application, forward them to Signal
270                x = self.requests.next() => {
271                    match x {
272                        Some((mut request, responder)) => {
273                            use prost::Message;
274
275                            // Regenerate ID if already in the table
276                            request.id = Some(
277                                request
278                                    .id
279                                    .filter(|x| !self.outgoing_requests.contains_key(x))
280                                    .unwrap_or_else(|| self.next_request_id()),
281                            );
282                            tracing::trace!(
283                                request.id,
284                                request.verb,
285                                request.path,
286                                request_body_size_bytes = request.body.as_ref().map(|x| x.len()),
287                                ?request.headers,
288                                "sending WebSocketRequestMessage",
289                            );
290
291                            self.outgoing_requests.insert(request.id.unwrap(), responder);
292                            let msg = WebSocketMessage {
293                                r#type: Some(web_socket_message::Type::Request.into()),
294                                request: Some(request),
295                                ..Default::default()
296                            };
297                            let buffer = msg.encode_to_vec();
298                            self.ws.send(reqwest_websocket::Message::Binary(buffer.into())).await?
299                        }
300                        None => {
301                            debug!("end of application request stream; websocket closing");
302                            return Ok(());
303                        }
304                    }
305                }
306                // Incoming websocket message
307                web_socket_item = self.ws.next().fuse() => {
308                    use reqwest_websocket::Message;
309                    match web_socket_item {
310                        Some(Ok(Message::Close { code, reason })) => {
311                            tracing::warn!(%code, reason, "websocket closed");
312                            break;
313                        },
314                        Some(Ok(Message::Binary(frame))) => {
315                            self.process_frame(frame).await?;
316                        }
317                        Some(Ok(Message::Ping(_))) => {
318                            tracing::trace!("received ping");
319                        }
320                        Some(Ok(Message::Pong(_))) => {
321                            tracing::trace!("received pong");
322                        }
323                        Some(Ok(Message::Text(_))) => {
324                            tracing::trace!("received text (unsupported, skipping)");
325                        }
326                        Some(Err(e)) => return Err(e.into()),
327                        None => {
328                            return Err(ServiceError::WsClosing {
329                                reason: "end of web request stream; socket closing"
330                            });
331                        }
332                    }
333                }
334                response = self.outgoing_responses.next() => {
335                    use prost::Message;
336                    match response {
337                        Some(Ok(response)) => {
338                            tracing::trace!("sending response {:?}", response);
339
340                            let msg = WebSocketMessage {
341                                r#type: Some(web_socket_message::Type::Response.into()),
342                                response: Some(response),
343                                ..Default::default()
344                            };
345                            let buffer = msg.encode_to_vec();
346                            self.ws.send(buffer.into()).await?;
347                        }
348                        Some(Err(error)) => {
349                            tracing::error!(%error, "could not generate response to a Signal request; responder was canceled. continuing.");
350                        }
351                        None => {
352                            unreachable!("outgoing responses should never fuse")
353                        }
354                    }
355                }
356            }
357        }
358        Ok(())
359    }
360}
361
362impl<C: WebSocketType> SignalWebSocket<C> {
363    fn inner_locked(&self) -> MutexGuard<'_, SignalWebSocketInner> {
364        self.inner.lock().unwrap()
365    }
366
367    pub fn new(
368        ws: WebSocket,
369        keep_alive_path: String,
370        unidentified_push_service: PushService,
371    ) -> (Self, impl Future<Output = ()>) {
372        // Create process
373        let (incoming_request_sink, incoming_request_stream) =
374            mpsc::unbounded();
375        let (outgoing_request_sink, outgoing_requests) = mpsc::channel(1);
376
377        let process = SignalWebSocketProcess {
378            keep_alive_path,
379            requests: outgoing_requests,
380            request_sink: incoming_request_sink,
381            outgoing_requests: HashMap::default(),
382            outgoing_keep_alive_set: HashSet::new(),
383            // Initializing the FuturesUnordered with a `pending` future means it will never fuse
384            // itself, so an "empty" FuturesUnordered will still allow new futures to be added.
385            outgoing_responses: vec![
386                Box::pin(futures::future::pending()) as BoxFuture<_>
387            ]
388            .into_iter()
389            .collect(),
390            ws,
391        };
392        let process = process.run().map(|x| match x {
393            Ok(()) => (),
394            Err(e) => {
395                tracing::error!("SignalWebSocket: {}", e);
396            },
397        });
398
399        (
400            Self {
401                _type: PhantomData,
402                request_sink: outgoing_request_sink,
403                unidentified_push_service,
404                inner: Arc::new(Mutex::new(SignalWebSocketInner {
405                    stream: Some(SignalRequestStream {
406                        inner: incoming_request_stream,
407                    }),
408                })),
409            },
410            process,
411        )
412    }
413
414    pub fn servers(&self) -> SignalServers {
415        self.unidentified_push_service.servers
416    }
417
418    pub fn is_closed(&self) -> bool {
419        self.request_sink.is_closed()
420    }
421
422    pub fn is_used(&self) -> bool {
423        self.inner_locked().stream.is_none()
424    }
425
426    pub(crate) fn take_request_stream(
427        &mut self,
428    ) -> Option<SignalRequestStream> {
429        self.inner_locked().stream.take()
430    }
431
432    pub(crate) fn return_request_stream(&mut self, r: SignalRequestStream) {
433        self.inner_locked().stream.replace(r);
434    }
435
436    // XXX Ideally, this should take an *async* closure, then we could get rid of the
437    // `take_request_stream` and `return_request_stream`.
438    pub async fn with_request_stream<
439        R: 'static,
440        F: FnOnce(&mut SignalRequestStream) -> R,
441    >(
442        &mut self,
443        f: F,
444    ) -> R {
445        let mut s = self
446            .inner_locked()
447            .stream
448            .take()
449            .expect("request stream invariant");
450        let r = f(&mut s);
451        self.inner_locked().stream.replace(s);
452        r
453    }
454
455    pub fn request(
456        &mut self,
457        r: WebSocketRequestMessage,
458    ) -> impl Future<Output = Result<WebSocketResponseMessage, ServiceError>>
459    {
460        let (sink, recv): (
461            oneshot::Sender<Result<WebSocketResponseMessage, ServiceError>>,
462            _,
463        ) = oneshot::channel();
464
465        let mut request_sink = self.request_sink.clone();
466        async move {
467            if let Err(_e) = request_sink.send((r, sink)).await {
468                return Err(ServiceError::WsClosing {
469                    reason: "WebSocket closing while sending request",
470                });
471            }
472            // Handle the oneshot sender error for dropped senders.
473            match recv.await {
474                Ok(x) => x,
475                Err(_) => Err(ServiceError::WsClosing {
476                    reason: "WebSocket closing while waiting for a response",
477                }),
478            }
479        }
480    }
481
482    pub(crate) async fn request_json_with<T, F, Fut>(
483        &mut self,
484        r: WebSocketRequestMessage,
485        decode: F,
486    ) -> Result<T, ServiceError>
487    where
488        for<'de> T: serde::Deserialize<'de>,
489        F: FnOnce(WebSocketResponseMessage) -> Fut + Send,
490        Fut: Future<Output = Result<WebSocketResponseMessage, ServiceError>>
491            + Send,
492    {
493        self.request(r)
494            .await?
495            .service_error_for_status_with(decode)
496            .await?
497            .json()
498            .await
499    }
500}
501
502impl WebSocketResponseMessage {
503    pub async fn json<T: for<'a> serde::Deserialize<'a>>(
504        &self,
505    ) -> Result<T, ServiceError> {
506        self.body
507            .as_ref()
508            .ok_or(ServiceError::UnsupportedContent)
509            .and_then(|b| serde_json::from_slice(b).map_err(Into::into))
510    }
511}