1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! ID and public key lookups.

use std::fmt;
use std::io::Read;
use std::str;

use reqwest::Client;

use crate::connection::map_response_code;
use crate::errors::ApiError;

/// Different ways to look up a Threema ID in the directory.
#[derive(Debug, PartialEq)]
pub enum LookupCriterion {
    /// The phone number must be passed in E.164 format, without the leading `+`.
    Phone(String),
    /// The phone number must be passed as an HMAC-SHA256 hash of the E.164
    /// number without the leading `+`. The HMAC key is
    /// `85adf8226953f3d96cfd5d09bf29555eb955fcd8aa5ec4f9fcd869e258370723`
    /// (in hexadecimal).
    PhoneHash(String),
    /// The email address.
    Email(String),
    /// The lowercased and whitespace-trimmed email address must be hashed with
    /// HMAC-SHA256. The HMAC key is
    /// `30a5500fed9701fa6defdb610841900febb8e430881f7ad816826264ec09bad7`
    /// (in hexadecimal).
    EmailHash(String),
}

impl fmt::Display for LookupCriterion {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            LookupCriterion::Phone(ref n) => write!(f, "phone {}", n),
            LookupCriterion::PhoneHash(ref nh) => write!(f, "phone hash {}", nh),
            LookupCriterion::Email(ref e) => write!(f, "email {}", e),
            LookupCriterion::EmailHash(ref eh) => write!(f, "email hash {}", eh),
        }
    }
}

/// A struct containing flags according to the capabilities of a Threema ID.
#[derive(Debug, PartialEq)]
pub struct Capabilities {
    /// Whether the ID can receive text messages.
    pub text: bool,
    /// Whether the ID can receive image messages.
    pub image: bool,
    /// Whether the ID can receive video messages.
    pub video: bool,
    /// Whether the ID can receive audio messages.
    pub audio: bool,
    /// Whether the ID can receive file messages.
    pub file: bool,
    /// List of other capabilities this ID has.
    pub other: Vec<String>,
}

impl Capabilities {
    fn new() -> Self {
        Capabilities {
            text: false,
            image: false,
            video: false,
            audio: false,
            file: false,
            other: Vec::new(),
        }
    }
}

impl str::FromStr for Capabilities {
    type Err = ApiError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut capabilities = Capabilities::new();
        for capability in s.split(',').map(str::trim).map(str::to_lowercase) {
            match capability.as_ref() {
                "text" => capabilities.text = true,
                "image" => capabilities.image = true,
                "video" => capabilities.video = true,
                "audio" => capabilities.audio = true,
                "file" => capabilities.file = true,
                _ if !capability.is_empty() => capabilities.other.push(capability),
                _ => { /* skip empty entries */ }
            };
        }
        Ok(capabilities)
    }
}

impl fmt::Display for Capabilities {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{{ text: {}, image: {}, video: {}, audio: {}, file: {}",
            self.text, self.image, self.video, self.audio, self.file
        )?;
        if !self.other.is_empty() {
            write!(f, ", other: {} }}", self.other.join(","))?;
        } else {
            write!(f, " }}")?;
        }
        Ok(())
    }
}

impl Capabilities {
    /// Return whether the specified capability is present.
    pub fn can(&self, capability: &str) -> bool {
        match capability {
            "text" => self.text,
            "image" => self.image,
            "video" => self.video,
            "audio" => self.audio,
            "file" => self.file,
            _ => self.other.contains(&capability.to_lowercase()),
        }
    }
}

/// Fetch the public key for the specified Threema ID.
pub(crate) fn lookup_pubkey(
    endpoint: &str,
    our_id: &str,
    their_id: &str,
    secret: &str,
) -> Result<String, ApiError> {
    // Build URL
    let url = format!(
        "{}/pubkeys/{}?from={}&secret={}",
        endpoint, their_id, our_id, secret
    );

    debug!("Looking up public key for {}", their_id);

    // Send request
    let mut res = Client::new().get(&url).send()?;
    map_response_code(res.status(), None)?;

    // Read and return response body
    let mut body = String::new();
    res.read_to_string(&mut body)?;
    Ok(body)
}

/// Look up an ID in the Threema directory.
pub(crate) fn lookup_id(
    endpoint: &str,
    criterion: &LookupCriterion,
    our_id: &str,
    secret: &str,
) -> Result<String, ApiError> {
    // Build URL
    let url_base = match criterion {
        LookupCriterion::Phone(ref val) => format!("{}/lookup/phone/{}", endpoint, val),
        LookupCriterion::PhoneHash(ref val) => format!("{}/lookup/phone_hash/{}", endpoint, val),
        LookupCriterion::Email(ref val) => format!("{}/lookup/email/{}", endpoint, val),
        LookupCriterion::EmailHash(ref val) => format!("{}/lookup/email_hash/{}", endpoint, val),
    };
    let url = format!("{}?from={}&secret={}", url_base, our_id, secret);

    debug!("Looking up id key for {}", criterion);

    // Send request
    let mut res = Client::new().get(&url).send()?;
    map_response_code(res.status(), Some(ApiError::BadHashLength))?;

    // Read and return response body
    let mut body = String::new();
    res.read_to_string(&mut body)?;
    Ok(body)
}

/// Look up remaining gateway credits.
pub(crate) fn lookup_credits(endpoint: &str, our_id: &str, secret: &str) -> Result<i64, ApiError> {
    let url = format!("{}/credits?from={}&secret={}", endpoint, our_id, secret);

    debug!("Looking up remaining credits");

    // Send request
    let mut res = Client::new().get(&url).send()?;
    map_response_code(res.status(), None)?;

    // Read, parse and return response body
    let mut body = String::new();
    res.read_to_string(&mut body)?;
    body.trim().parse::<i64>().map_err(|_| {
        ApiError::ParseError(format!(
            "Could not parse response body as i64: \"{}\"",
            body
        ))
    })
}

/// Look up ID capabilities.
pub(crate) fn lookup_capabilities(
    endpoint: &str,
    our_id: &str,
    their_id: &str,
    secret: &str,
) -> Result<Capabilities, ApiError> {
    // Build URL
    let url = format!(
        "{}/capabilities/{}?from={}&secret={}",
        endpoint, their_id, our_id, secret
    );

    debug!("Looking up capabilities for {}", their_id);

    // Send request
    let mut res = Client::new().get(&url).send()?;
    map_response_code(res.status(), Some(ApiError::BadHashLength))?;

    // Read response body
    let mut body = String::new();
    res.read_to_string(&mut body)?;

    // Parse response body
    body.parse()
}

#[cfg(test)]
mod tests {
    use super::{Capabilities, LookupCriterion};

    #[test]
    fn test_lookup_criterion_display() {
        let phone = LookupCriterion::Phone("1234".to_string());
        let phone_hash = LookupCriterion::PhoneHash("1234567890abcdef".to_string());
        let email = LookupCriterion::Email("user@example.com".to_string());
        let email_hash = LookupCriterion::EmailHash("1234567890abcdef".to_string());
        assert_eq!(&phone.to_string(), "phone 1234");
        assert_eq!(&phone_hash.to_string(), "phone hash 1234567890abcdef");
        assert_eq!(&email.to_string(), "email user@example.com");
        assert_eq!(&email_hash.to_string(), "email hash 1234567890abcdef");
    }

    #[test]
    fn test_parse_capabilities_empty() {
        assert_eq!(
            "".parse::<Capabilities>().unwrap(),
            Capabilities {
                text: false,
                image: false,
                video: false,
                audio: false,
                file: false,
                other: vec![],
            }
        );
    }

    #[test]
    fn test_parse_capabilities_simple() {
        assert_eq!(
            "image".parse::<Capabilities>().unwrap(),
            Capabilities {
                text: false,
                image: true,
                video: false,
                audio: false,
                file: false,
                other: vec![],
            }
        );
    }

    #[test]
    fn test_parse_capabilities_combined() {
        assert_eq!(
            "image,video,file".parse::<Capabilities>().unwrap(),
            Capabilities {
                text: false,
                image: true,
                video: true,
                audio: false,
                file: true,
                other: vec![],
            }
        );
    }

    #[test]
    fn test_parse_capabilities_unknown() {
        assert_eq!(
            "jetpack,text,lasersword".parse::<Capabilities>().unwrap(),
            Capabilities {
                text: true,
                image: false,
                video: false,
                audio: false,
                file: false,
                other: vec!["jetpack".into(), "lasersword".into()],
            }
        );
    }

    #[test]
    fn test_parse_capabilities_cleanup() {
        assert_eq!(
            "jetpack,Text ,LASERSWORD,,.,"
                .parse::<Capabilities>()
                .unwrap(),
            Capabilities {
                text: true,
                image: false,
                video: false,
                audio: false,
                file: false,
                other: vec!["jetpack".into(), "lasersword".into(), ".".into()],
            }
        );
    }

    #[test]
    fn test_parse_capabilities_can() {
        let cap = "jetpack,Text ,LASERSWORD,,.,"
            .parse::<Capabilities>()
            .unwrap();
        assert_eq!(
            cap,
            Capabilities {
                text: true,
                image: false,
                video: false,
                audio: false,
                file: false,
                other: vec!["jetpack".into(), "lasersword".into(), ".".into()],
            }
        );
        assert!(cap.can("jetpack"));
        assert!(cap.can("text"));
        assert!(cap.can("lasersword"));
        assert!(cap.can("."));
        assert!(!cap.can("image"));
    }
}