Skip to main content

wechat_protocol/
openim.rs

1//! Read one exact OpenIM contact through the supported native contact operation.
2use crate::{protobuf as p, AccountState, NativeClient};
3use anyhow::{ensure, Result};
4use serde::{Deserialize, Serialize};
5
6const CGI: u16 = 881;
7const PATH: &str = "/cgi-bin/micromsg-bin/getopenimcontact";
8const MAX_ID_BYTES: usize = 256;
9const MAX_LABEL_BYTES: usize = 4096;
10const MAX_URL_BYTES: usize = 16384;
11const MAX_TICKET_BYTES: usize = 16384;
12
13/// Supplied contact fields for one accepted OpenIM identity.
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
15pub struct OpenImContact {
16    /// Exact OpenIM username returned for the requested identity.
17    pub username: String,
18    /// Contact's nickname, preserving absent and present-empty values.
19    pub nickname: Option<String>,
20    /// Saved remark supplied by the service, when present.
21    pub remark: Option<String>,
22    /// Server-advertised large-avatar source. Validate it before any download.
23    pub large_avatar_url: Option<String>,
24    /// Server-advertised small-avatar source. Validate it before any download.
25    pub small_avatar_url: Option<String>,
26}
27
28/// A service rejection retaining the signed OpenIM response code.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct OpenImServiceError {
31    /// Signed `ret` returned by the OpenIM service.
32    pub service_code: i32,
33}
34
35impl std::fmt::Display for OpenImServiceError {
36    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        write!(formatter, "OpenIM service returned {}", self.service_code)
38    }
39}
40
41impl std::error::Error for OpenImServiceError {}
42
43fn identity(value: &str, suffix: &str) -> bool {
44    value.len() <= MAX_ID_BYTES
45        && value
46            .strip_suffix(suffix)
47            .is_some_and(|prefix| !prefix.is_empty() && !prefix.contains('@'))
48        && !value
49            .chars()
50            .any(|character| character.is_control() || character.is_whitespace())
51}
52
53/// Encode an exact OpenIM lookup with optional ordinary/OpenIM group context and ticket.
54pub fn request(username: &str, room: Option<&str>, ticket: Option<&str>) -> Result<Vec<u8>> {
55    ensure!(identity(username, "@openim"), "Invalid OpenIM identity");
56    if let Some(room) = room {
57        ensure!(
58            identity(room, "@chatroom") || identity(room, "@im.chatroom"),
59            "Invalid OpenIM room context"
60        );
61    }
62    if let Some(ticket) = ticket {
63        ensure!(
64            ticket.len() <= MAX_TICKET_BYTES && !ticket.contains('\0'),
65            "Invalid OpenIM lookup ticket"
66        );
67    }
68    let mut fields = vec![p::bytes(1, username.as_bytes())];
69    if let Some(room) = room {
70        fields.push(p::bytes(2, room.as_bytes()));
71    }
72    if let Some(ticket) = ticket {
73        fields.push(p::bytes(3, ticket.as_bytes()));
74    }
75    p::message(&fields)
76}
77
78fn optional_text(fields: &[p::Field], number: u32, max: usize) -> Result<Option<String>> {
79    p::optional_data(fields, number)?
80        .map(|bytes| {
81            ensure!(bytes.len() <= max, "OpenIM field exceeds limit");
82            let text = std::str::from_utf8(bytes)?;
83            ensure!(!text.contains('\0'), "Invalid OpenIM text");
84            Ok(text.to_owned())
85        })
86        .transpose()
87}
88
89/// Decode an authenticated OpenIM response and require the exact requested contact identity.
90pub fn decode_response(bytes: &[u8], requested_username: &str) -> Result<OpenImContact> {
91    ensure!(
92        identity(requested_username, "@openim"),
93        "Invalid OpenIM identity"
94    );
95    let fields = p::decode(bytes)?;
96    let raw_code = p::scalar(&fields, 1)?;
97    let service_code = raw_code as u32 as i32;
98    ensure!(
99        raw_code <= u64::from(u32::MAX)
100            || (service_code < 0 && raw_code == service_code as i64 as u64),
101        "Invalid OpenIM service code"
102    );
103    let raw_contact = p::optional_data(&fields, 2)?;
104    if service_code != 0 {
105        return Err(OpenImServiceError { service_code }.into());
106    }
107    let contact = p::decode(raw_contact.ok_or_else(|| anyhow::anyhow!("Missing OpenIM contact"))?)?;
108    let username = optional_text(&contact, 1, MAX_ID_BYTES)?
109        .ok_or_else(|| anyhow::anyhow!("Missing OpenIM contact identity"))?;
110    ensure!(
111        username == requested_username,
112        "OpenIM contact identity mismatch"
113    );
114    Ok(OpenImContact {
115        username,
116        nickname: optional_text(&contact, 2, MAX_LABEL_BYTES)?,
117        remark: optional_text(&contact, 4, MAX_LABEL_BYTES)?,
118        large_avatar_url: optional_text(&contact, 5, MAX_URL_BYTES)?,
119        small_avatar_url: optional_text(&contact, 6, MAX_URL_BYTES)?,
120    })
121}
122
123impl NativeClient {
124    pub(crate) fn openim_contact_raw_snapshot(
125        &self,
126        state: &mut AccountState,
127        username: &str,
128        room: Option<&str>,
129        ticket: Option<&str>,
130    ) -> Result<Vec<u8>> {
131        let request = zeroize::Zeroizing::new(request(username, room, ticket)?);
132        self.authenticated_rpc(state, CGI, PATH, &request)
133    }
134
135    pub(crate) fn openim_contact_snapshot(
136        &self,
137        state: &mut AccountState,
138        username: &str,
139        room: Option<&str>,
140        ticket: Option<&str>,
141    ) -> Result<OpenImContact> {
142        let reply = self.openim_contact_raw_snapshot(state, username, room, ticket)?;
143        decode_response(&reply, username)
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    const USER: &str = "123@openim";
152
153    fn response(fields: &[Vec<u8>]) -> Vec<u8> {
154        p::message(&[p::int32(1, 0), p::bytes(2, &p::message(fields).unwrap())]).unwrap()
155    }
156
157    #[test]
158    fn request_matches_the_direct_string_wire_layout() {
159        // Three direct string fields, in field-number order. Optional context
160        // and ticket presence is controlled separately from the required identity.
161        let expected =
162            hex::decode("0a0a313233406f70656e696d120a374063686174726f6f6d1a0174").unwrap();
163        assert_eq!(
164            request(USER, Some("7@chatroom"), Some("t")).unwrap(),
165            expected
166        );
167        assert_eq!(
168            request(USER, None, None).unwrap(),
169            hex::decode("0a0a313233406f70656e696d").unwrap()
170        );
171        assert!(request(USER, Some("7@im.chatroom"), None).is_ok());
172        assert_eq!(
173            request(USER, None, Some("")).unwrap(),
174            hex::decode("0a0a313233406f70656e696d1a00").unwrap()
175        );
176    }
177
178    #[test]
179    fn request_rejects_invalid_identities_contexts_and_oversized_tickets() {
180        for user in [
181            "",
182            "@openim",
183            "person",
184            "person@kefu.openim",
185            "two words@openim",
186            "x@y@openim",
187        ] {
188            assert!(request(user, None, None).is_err());
189        }
190        assert!(request(&format!("{}@openim", "x".repeat(MAX_ID_BYTES)), None, None).is_err());
191        for room in [
192            "",
193            "@chatroom",
194            "person",
195            "person@openim",
196            "two words@chatroom",
197        ] {
198            assert!(request(USER, Some(room), None).is_err());
199        }
200        assert!(request(USER, None, Some(&"x".repeat(MAX_TICKET_BYTES + 1))).is_err());
201        assert!(request(USER, None, Some("bad\0ticket")).is_err());
202    }
203
204    #[test]
205    fn response_reads_supplied_fields_and_preserves_empty_values() {
206        let bytes = response(&[
207            p::bytes(1, USER.as_bytes()),
208            p::bytes(2, "Example member".as_bytes()),
209            p::bytes(4, b""),
210            p::bytes(5, b"https://wework.qpic.cn/synthetic-large"),
211            p::bytes(6, b"https://wework.qpic.cn/synthetic-small"),
212            p::uint(99, 1),
213            p::uint(99, 2),
214        ]);
215        let contact = decode_response(&bytes, USER).unwrap();
216        assert_eq!(contact.username, USER);
217        assert_eq!(contact.nickname.as_deref(), Some("Example member"));
218        assert_eq!(contact.remark.as_deref(), Some(""));
219        assert_eq!(
220            contact.large_avatar_url.as_deref(),
221            Some("https://wework.qpic.cn/synthetic-large")
222        );
223        assert_eq!(
224            contact.small_avatar_url.as_deref(),
225            Some("https://wework.qpic.cn/synthetic-small")
226        );
227        let minimal = decode_response(&response(&[p::bytes(1, USER.as_bytes())]), USER).unwrap();
228        assert!(
229            minimal.nickname.is_none()
230                && minimal.remark.is_none()
231                && minimal.small_avatar_url.is_none()
232        );
233    }
234
235    #[test]
236    fn response_preserves_signed_service_rejections() {
237        for code in [-1, -13, i32::MIN, 1, i32::MAX] {
238            let bytes = p::message(&[p::int32(1, code)]).unwrap();
239            let error = decode_response(&bytes, USER).unwrap_err();
240            assert_eq!(
241                error
242                    .downcast_ref::<OpenImServiceError>()
243                    .unwrap()
244                    .service_code,
245                code
246            );
247        }
248    }
249
250    #[test]
251    fn response_rejects_cross_identity_ambiguous_or_malformed_fields() {
252        for bytes in [
253            Vec::new(),
254            p::bytes(2, &p::bytes(1, USER.as_bytes())),
255            p::int32(1, 0),
256            response(&[]),
257            p::message(&[
258                p::int32(1, 0),
259                p::int32(1, 0),
260                p::bytes(2, &p::bytes(1, USER.as_bytes())),
261            ])
262            .unwrap(),
263            p::message(&[p::int32(1, 0), p::bytes(2, b""), p::bytes(2, b"")]).unwrap(),
264            p::message(&[p::uint(1, 1u64 << 32), p::bytes(2, b"")]).unwrap(),
265            response(&[p::bytes(1, b"456@openim")]),
266            response(&[p::bytes(1, USER.as_bytes()), p::bytes(1, USER.as_bytes())]),
267            response(&[p::bytes(1, USER.as_bytes()), p::uint(2, 1)]),
268            response(&[p::bytes(1, USER.as_bytes()), p::bytes(2, &[0xff])]),
269            response(&[
270                p::bytes(1, USER.as_bytes()),
271                p::bytes(2, &vec![b'x'; MAX_LABEL_BYTES + 1]),
272            ]),
273            response(&[
274                p::bytes(1, USER.as_bytes()),
275                p::bytes(4, b"one"),
276                p::bytes(4, b"two"),
277            ]),
278            response(&[
279                p::bytes(1, USER.as_bytes()),
280                p::bytes(5, &vec![b'x'; MAX_URL_BYTES + 1]),
281            ]),
282            response(&[
283                p::bytes(1, USER.as_bytes()),
284                p::bytes(6, b"one"),
285                p::bytes(6, b"two"),
286            ]),
287        ] {
288            assert!(decode_response(&bytes, USER).is_err());
289        }
290    }
291}