1use super::*;
5
6#[derive(Clone, Debug, PartialEq)]
8pub struct ConnectedBody {
9 pub wsid: String,
10 pub timestamp: Option<f64>,
11}
12
13impl JsonCodable for ConnectedBody {
14 fn from_json(v: &Value) -> Result<Self> {
15 let r = Reader::new(v, "connected body")?;
16 Ok(ConnectedBody {
17 wsid: r.string("wsid")?,
18 timestamp: r.optional_number("timestamp")?,
19 })
20 }
21
22 fn to_json(&self) -> Value {
23 Builder::new()
24 .set("wsid", self.wsid.clone())
25 .opt("timestamp", self.timestamp)
26 .build()
27 }
28}
29
30#[derive(Clone, Debug, PartialEq, Default)]
33pub struct InitConnectionBody {
34 pub desired_queries_patch: UpQueriesPatch,
35 pub client_schema: Option<ClientSchema>,
38 pub deleted: Option<DeleteClientsBody>,
39 pub user_push_url: Option<String>,
41 pub user_push_headers: Option<Vec<(String, String)>>,
42 pub user_query_url: Option<String>,
44 pub user_query_headers: Option<Vec<(String, String)>>,
45 pub active_clients: Option<Vec<String>>,
48 pub traceparent: Option<String>,
50}
51
52impl JsonCodable for InitConnectionBody {
53 fn from_json(v: &Value) -> Result<Self> {
54 let r = Reader::new(v, "initConnection body")?;
55 Ok(InitConnectionBody {
56 desired_queries_patch: r.required("desiredQueriesPatch", up_queries_patch)?,
57 client_schema: r.optional("clientSchema", ClientSchema::from_json)?,
58 deleted: r.optional("deleted", DeleteClientsBody::from_json)?,
59 user_push_url: r.optional_string("userPushURL")?,
60 user_push_headers: r.optional("userPushHeaders", string_record)?,
61 user_query_url: r.optional_string("userQueryURL")?,
62 user_query_headers: r.optional("userQueryHeaders", string_record)?,
63 active_clients: r.optional("activeClients", decode::strings)?,
64 traceparent: r.optional_string("traceparent")?,
65 })
66 }
67
68 fn to_json(&self) -> Value {
69 Builder::new()
70 .set(
71 "desiredQueriesPatch",
72 array_json(&self.desired_queries_patch),
73 )
74 .opt(
75 "clientSchema",
76 self.client_schema.as_ref().map(ClientSchema::to_json),
77 )
78 .opt(
79 "deleted",
80 self.deleted.as_ref().map(DeleteClientsBody::to_json),
81 )
82 .opt("userPushURL", self.user_push_url.clone())
83 .opt(
84 "userPushHeaders",
85 self.user_push_headers.as_deref().map(string_record_json),
86 )
87 .opt("userQueryURL", self.user_query_url.clone())
88 .opt(
89 "userQueryHeaders",
90 self.user_query_headers.as_deref().map(string_record_json),
91 )
92 .opt(
93 "activeClients",
94 self.active_clients.as_deref().map(decode::strings_json),
95 )
96 .opt("traceparent", self.traceparent.clone())
97 .build()
98 }
99}
100
101#[derive(Clone, Debug, PartialEq, Default)]
105pub struct ConnectionUrl {
106 pub socket_origin: String,
108 pub client_id: String,
109 pub client_group_id: String,
110 pub user_id: Option<String>,
111 pub base_cookie: Option<String>,
113 pub timestamp: f64,
115 pub last_mutation_id: f64,
116 pub wsid: String,
117 pub profile_id: String,
118 pub debug_perf: bool,
119 pub additional_params: Vec<(String, String)>,
121}
122
123impl std::fmt::Display for ConnectionUrl {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 let mut params: Vec<(&str, String)> = vec![
126 ("clientID", self.client_id.clone()),
127 ("clientGroupID", self.client_group_id.clone()),
128 ];
129 if let Some(user_id) = &self.user_id {
130 params.push(("userID", user_id.clone()));
131 }
132 params.extend([
133 ("baseCookie", self.base_cookie.clone().unwrap_or_default()),
134 ("ts", json::number::format(self.timestamp)),
135 ("lmid", json::number::format(self.last_mutation_id)),
136 ("wsid", self.wsid.clone()),
137 ("profileID", self.profile_id.clone()),
138 ]);
139 if self.debug_perf {
140 params.push(("debugPerf", "true".to_owned()));
141 }
142 for (k, v) in &self.additional_params {
143 if !params.iter().any(|(p, _)| p == k) {
144 params.push((k, v.clone()));
145 }
146 }
147 let origin = self
148 .socket_origin
149 .strip_suffix('/')
150 .unwrap_or(&self.socket_origin);
151 write!(f, "{origin}/sync/v{PROTOCOL_VERSION}/connect?")?;
152 for (i, (k, v)) in params.iter().enumerate() {
153 let sep = if i == 0 { "" } else { "&" };
154 write!(f, "{sep}{}={}", form_encode(k), form_encode(v))?;
155 }
156 Ok(())
157 }
158}
159
160fn form_encode(s: &str) -> String {
162 let mut out = String::with_capacity(s.len());
163 for &b in s.as_bytes() {
164 match b {
165 b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'*' | b'-' | b'.' | b'_' => {
166 out.push(char::from(b))
167 }
168 b' ' => out.push('+'),
169 _ => out.push_str(&format!("%{b:02X}")),
170 }
171 }
172 out
173}
174
175const UTF8_BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
176
177pub mod sec_protocols {
183 use super::*;
184
185 pub fn encode(
186 init_connection: Option<&InitConnectionBody>,
187 auth_token: Option<&str>,
188 ) -> String {
189 let value = Builder::new()
190 .opt(
191 "initConnectionMessage",
192 init_connection.map(|b| message("initConnection", b.to_json())),
193 )
194 .opt("authToken", auth_token)
195 .build();
196 let base64 = base64_encode(json::stringify(&value).as_bytes());
197 base64
199 .replace('+', "%2B")
200 .replace('/', "%2F")
201 .replace('=', "%3D")
202 }
203
204 pub fn decode(sec_protocol: &str) -> Result<Value> {
207 let base64 = uri_component_decode(sec_protocol)?;
208 let bytes = forgiving_base64_decode(&base64)
209 .ok_or_else(|| DecodeError::new("The string to be decoded is not correctly encoded"))?;
210 let bytes = bytes.strip_prefix(UTF8_BOM).unwrap_or(&bytes);
212 parse_message(&String::from_utf8_lossy(bytes))
213 }
214}
215
216const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
217
218fn base64_encode(bytes: &[u8]) -> String {
220 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
221 for chunk in bytes.chunks(3) {
222 let n = chunk
223 .iter()
224 .enumerate()
225 .fold(0u32, |n, (i, &b)| n | u32::from(b) << (16 - 8 * i));
226 for i in 0..4 {
227 if i <= chunk.len() {
228 out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
229 } else {
230 out.push('=');
231 }
232 }
233 }
234 out
235}
236
237fn forgiving_base64_decode(s: &str) -> Option<Vec<u8>> {
239 let mut data = Vec::with_capacity(s.len());
240 for c in s.chars() {
241 match c {
242 '\t' | '\n' | '\u{c}' | '\r' | ' ' => {}
243 c if c.is_ascii() => data.push(c as u8),
244 _ => return None,
245 }
246 }
247 if data.len() % 4 == 0 {
248 for _ in 0..2 {
249 if data.last() == Some(&b'=') {
250 data.pop();
251 }
252 }
253 }
254 if data.len() % 4 == 1 {
255 return None;
256 }
257 let mut out = Vec::with_capacity(data.len() * 3 / 4);
258 let (mut buffer, mut bits) = (0u32, 0);
259 for c in data {
260 let v = ALPHABET.iter().position(|&a| a == c)? as u32;
261 buffer = buffer << 6 | v;
262 bits += 6;
263 if bits >= 8 {
264 bits -= 8;
265 out.push((buffer >> bits) as u8);
266 }
267 }
268 Some(out)
269}
270
271fn uri_component_decode(s: &str) -> Result<String> {
273 let malformed = || DecodeError::new("URI malformed");
274 let b = s.as_bytes();
275 let hex_byte = |i: usize| -> Option<u8> {
276 if i + 2 < b.len() && b[i] == b'%' {
277 let hi = (b[i + 1] as char).to_digit(16)?;
278 let lo = (b[i + 2] as char).to_digit(16)?;
279 Some((hi << 4 | lo) as u8)
280 } else {
281 None
282 }
283 };
284 let mut out = String::with_capacity(s.len());
285 let mut i = 0;
286 let mut copied = 0;
287 while i < b.len() {
288 if b[i] != b'%' {
289 i += 1;
290 continue;
291 }
292 out.push_str(&s[copied..i]);
293 let first = hex_byte(i).ok_or_else(malformed)?;
294 i += 3;
295 if first < 0x80 {
296 out.push(first as char);
298 copied = i;
299 continue;
300 }
301 let count = match first {
302 0xC0..=0xDF => 2,
303 0xE0..=0xEF => 3,
304 0xF0..=0xF7 => 4,
305 _ => return Err(malformed()),
306 };
307 let mut bytes = vec![first];
308 for _ in 1..count {
309 let byte = hex_byte(i)
310 .filter(|b| b & 0xC0 == 0x80)
311 .ok_or_else(malformed)?;
312 bytes.push(byte);
313 i += 3;
314 }
315 out.push_str(std::str::from_utf8(&bytes).map_err(|_| malformed())?);
316 copied = i;
317 }
318 out.push_str(&s[copied..]);
319 Ok(out)
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 #[test]
329 fn connection_url_is_form_encoded_in_js_order() {
330 let url = ConnectionUrl {
331 socket_origin: "ws://h:1/".to_owned(),
332 client_id: "a b*-._~é😀&=+/".to_owned(),
333 client_group_id: "g".to_owned(),
334 timestamp: 1.5,
335 wsid: "w".to_owned(),
336 profile_id: "p".to_owned(),
337 additional_params: vec![
338 ("wsid".to_owned(), "skipped".to_owned()),
339 ("extra".to_owned(), "1".to_owned()),
340 ],
341 ..ConnectionUrl::default()
342 };
343 assert_eq!(
344 url.to_string(),
345 "ws://h:1/sync/v57/connect?clientID=a+b*-._%7E%C3%A9%F0%9F%98%80%26%3D%2B%2F&clientGroupID=g&baseCookie=&ts=1.5&lmid=0&wsid=w&profileID=p&extra=1"
346 );
347 }
348}