deltachat/
qr.rs

1//! # QR code module.
2
3mod dclogin_scheme;
4use std::collections::BTreeMap;
5use std::sync::LazyLock;
6
7use anyhow::{Context as _, Result, anyhow, bail, ensure};
8pub use dclogin_scheme::LoginOptions;
9pub(crate) use dclogin_scheme::login_param_from_login_qr;
10use deltachat_contact_tools::{ContactAddress, addr_normalize, may_be_valid_addr};
11use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, percent_encode};
12use rand::TryRngCore as _;
13use rand::distr::{Alphanumeric, SampleString};
14use serde::Deserialize;
15
16use crate::config::Config;
17use crate::contact::{Contact, ContactId, Origin};
18use crate::context::Context;
19use crate::key::Fingerprint;
20use crate::login_param::{EnteredCertificateChecks, EnteredLoginParam, EnteredServerLoginParam};
21use crate::net::http::post_empty;
22use crate::net::proxy::{DEFAULT_SOCKS_PORT, ProxyConfig};
23use crate::token;
24use crate::tools::{time, validate_id};
25
26const OPENPGP4FPR_SCHEME: &str = "OPENPGP4FPR:"; // yes: uppercase
27const IDELTACHAT_SCHEME: &str = "https://i.delta.chat/#";
28const IDELTACHAT_NOSLASH_SCHEME: &str = "https://i.delta.chat#";
29const DCACCOUNT_SCHEME: &str = "DCACCOUNT:";
30pub(super) const DCLOGIN_SCHEME: &str = "DCLOGIN:";
31const TG_SOCKS_SCHEME: &str = "https://t.me/socks";
32const MAILTO_SCHEME: &str = "mailto:";
33const MATMSG_SCHEME: &str = "MATMSG:";
34const VCARD_SCHEME: &str = "BEGIN:VCARD";
35const SMTP_SCHEME: &str = "SMTP:";
36const HTTPS_SCHEME: &str = "https://";
37const SHADOWSOCKS_SCHEME: &str = "ss://";
38
39/// Backup transfer based on iroh-net.
40pub(crate) const DCBACKUP_SCHEME_PREFIX: &str = "DCBACKUP";
41
42/// Version written to Backups and Backup-QR-Codes.
43/// Imports will fail when they have a larger version.
44pub(crate) const DCBACKUP_VERSION: i32 = 4;
45
46/// Scanned QR code.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum Qr {
49    /// Ask the user whether to verify the contact.
50    ///
51    /// If the user agrees, pass this QR code to [`crate::securejoin::join_securejoin`].
52    AskVerifyContact {
53        /// ID of the contact.
54        contact_id: ContactId,
55
56        /// Fingerprint of the contact key as scanned from the QR code.
57        fingerprint: Fingerprint,
58
59        /// Invite number.
60        invitenumber: String,
61
62        /// Authentication code.
63        authcode: String,
64    },
65
66    /// Ask the user whether to join the group.
67    AskVerifyGroup {
68        /// Group name.
69        grpname: String,
70
71        /// Group ID.
72        grpid: String,
73
74        /// ID of the contact.
75        contact_id: ContactId,
76
77        /// Fingerprint of the contact key as scanned from the QR code.
78        fingerprint: Fingerprint,
79
80        /// Invite number.
81        invitenumber: String,
82
83        /// Authentication code.
84        authcode: String,
85    },
86
87    /// Ask whether to join the broadcast channel.
88    AskJoinBroadcast {
89        /// The user-visible name of this broadcast channel
90        name: String,
91
92        /// A string of random characters,
93        /// uniquely identifying this broadcast channel across all databases/clients.
94        /// Called `grpid` for historic reasons:
95        /// The id of multi-user chats is always called `grpid` in the database
96        /// because groups were once the only multi-user chats.
97        grpid: String,
98
99        /// ID of the contact who owns the channel and created the QR code.
100        contact_id: ContactId,
101
102        /// Fingerprint of the contact's key as scanned from the QR code.
103        fingerprint: Fingerprint,
104
105        /// Invite number.
106        invitenumber: String,
107        /// Authentication code.
108        authcode: String,
109    },
110
111    /// Contact fingerprint is verified.
112    ///
113    /// Ask the user if they want to start chatting.
114    FprOk {
115        /// Contact ID.
116        contact_id: ContactId,
117    },
118
119    /// Scanned fingerprint does not match the last seen fingerprint.
120    FprMismatch {
121        /// Contact ID.
122        contact_id: Option<ContactId>,
123    },
124
125    /// The scanned QR code contains a fingerprint but no e-mail address.
126    FprWithoutAddr {
127        /// Key fingerprint.
128        fingerprint: String,
129    },
130
131    /// Ask the user if they want to create an account on the given domain.
132    Account {
133        /// Server domain name.
134        domain: String,
135    },
136
137    /// Provides a backup that can be retrieved using iroh-net based backup transfer protocol.
138    Backup2 {
139        /// Iroh node address.
140        node_addr: iroh::NodeAddr,
141
142        /// Authentication token.
143        auth_token: String,
144    },
145
146    /// The QR code is a backup, but it is too new. The user has to update its Delta Chat.
147    BackupTooNew {},
148
149    /// Ask the user if they want to use the given proxy.
150    ///
151    /// Note that HTTP(S) URLs without a path
152    /// and query parameters are treated as HTTP(S) proxy URL.
153    /// UI may want to still offer to open the URL
154    /// in the browser if QR code contents
155    /// starts with `http://` or `https://`
156    /// and the QR code was not scanned from
157    /// the proxy configuration screen.
158    Proxy {
159        /// Proxy URL.
160        ///
161        /// This is the URL that is going to be added.
162        url: String,
163
164        /// Host extracted from the URL to display in the UI.
165        host: String,
166
167        /// Port extracted from the URL to display in the UI.
168        port: u16,
169    },
170
171    /// Contact address is scanned.
172    ///
173    /// Optionally, a draft message could be provided.
174    /// Ask the user if they want to start chatting.
175    Addr {
176        /// Contact ID.
177        contact_id: ContactId,
178
179        /// Draft message.
180        draft: Option<String>,
181    },
182
183    /// URL scanned.
184    ///
185    /// Ask the user if they want to open a browser or copy the URL to clipboard.
186    Url {
187        /// URL.
188        url: String,
189    },
190
191    /// Text scanned.
192    ///
193    /// Ask the user if they want to copy the text to clipboard.
194    Text {
195        /// Scanned text.
196        text: String,
197    },
198
199    /// Ask the user if they want to withdraw their own QR code.
200    WithdrawVerifyContact {
201        /// Contact ID.
202        contact_id: ContactId,
203
204        /// Fingerprint of the contact key as scanned from the QR code.
205        fingerprint: Fingerprint,
206
207        /// Invite number.
208        invitenumber: String,
209
210        /// Authentication code.
211        authcode: String,
212    },
213
214    /// Ask the user if they want to withdraw their own group invite QR code.
215    WithdrawVerifyGroup {
216        /// Group name.
217        grpname: String,
218
219        /// Group ID.
220        grpid: String,
221
222        /// Contact ID.
223        contact_id: ContactId,
224
225        /// Fingerprint of the contact key as scanned from the QR code.
226        fingerprint: Fingerprint,
227
228        /// Invite number.
229        invitenumber: String,
230
231        /// Authentication code.
232        authcode: String,
233    },
234
235    /// Ask the user if they want to withdraw their own broadcast channel invite QR code.
236    WithdrawJoinBroadcast {
237        /// The user-visible name of this broadcast channel
238        name: String,
239
240        /// A string of random characters,
241        /// uniquely identifying this broadcast channel across all databases/clients.
242        /// Called `grpid` for historic reasons:
243        /// The id of multi-user chats is always called `grpid` in the database
244        /// because groups were once the only multi-user chats.
245        grpid: String,
246
247        /// Contact ID. Always `ContactId::SELF`.
248        contact_id: ContactId,
249
250        /// Fingerprint of the contact's key as scanned from the QR code.
251        fingerprint: Fingerprint,
252
253        /// Invite number.
254        invitenumber: String,
255
256        /// Authentication code.
257        authcode: String,
258    },
259
260    /// Ask the user if they want to revive their own QR code.
261    ReviveVerifyContact {
262        /// Contact ID.
263        contact_id: ContactId,
264
265        /// Fingerprint of the contact key as scanned from the QR code.
266        fingerprint: Fingerprint,
267
268        /// Invite number.
269        invitenumber: String,
270
271        /// Authentication code.
272        authcode: String,
273    },
274
275    /// Ask the user if they want to revive their own group invite QR code.
276    ReviveVerifyGroup {
277        /// Group name.
278        grpname: String,
279
280        /// Group ID.
281        grpid: String,
282
283        /// Contact ID.
284        contact_id: ContactId,
285
286        /// Fingerprint of the contact key as scanned from the QR code.
287        fingerprint: Fingerprint,
288
289        /// Invite number.
290        invitenumber: String,
291
292        /// Authentication code.
293        authcode: String,
294    },
295
296    /// Ask the user if they want to revive their own broadcast channel invite QR code.
297    ReviveJoinBroadcast {
298        /// The user-visible name of this broadcast channel
299        name: String,
300
301        /// A string of random characters,
302        /// uniquely identifying this broadcast channel across all databases/clients.
303        /// Called `grpid` for historic reasons:
304        /// The id of multi-user chats is always called `grpid` in the database
305        /// because groups were once the only multi-user chats.
306        grpid: String,
307
308        /// Contact ID. Always `ContactId::SELF`.
309        contact_id: ContactId,
310
311        /// Fingerprint of the contact's key as scanned from the QR code.
312        fingerprint: Fingerprint,
313
314        /// Invite number.
315        invitenumber: String,
316
317        /// Authentication code.
318        authcode: String,
319    },
320
321    /// `dclogin:` scheme parameters.
322    ///
323    /// Ask the user if they want to login with the email address.
324    Login {
325        /// Email address.
326        address: String,
327
328        /// Login parameters.
329        options: LoginOptions,
330    },
331}
332
333// hack around the changed JSON accidentally used by an iroh upgrade, see #6518 for more details and for code snippet.
334// this hack is mainly needed to give ppl time to upgrade and can be removed after some months (added 2025-02)
335fn fix_add_second_device_qr(qr: &str) -> String {
336    qr.replacen(r#","info":{"relay_url":"#, r#","relay_url":"#, 1)
337        .replacen(r#""]}}"#, r#""]}"#, 1)
338}
339
340fn starts_with_ignore_case(string: &str, pattern: &str) -> bool {
341    string.to_lowercase().starts_with(&pattern.to_lowercase())
342}
343
344/// Checks a scanned QR code.
345///
346/// The function should be called after a QR code is scanned.
347/// The function takes the raw text scanned and checks what can be done with it.
348pub async fn check_qr(context: &Context, qr: &str) -> Result<Qr> {
349    let qr = qr.trim();
350    let qrcode = if starts_with_ignore_case(qr, OPENPGP4FPR_SCHEME) {
351        decode_openpgp(context, qr)
352            .await
353            .context("failed to decode OPENPGP4FPR QR code")?
354    } else if qr.starts_with(IDELTACHAT_SCHEME) {
355        decode_ideltachat(context, IDELTACHAT_SCHEME, qr).await?
356    } else if qr.starts_with(IDELTACHAT_NOSLASH_SCHEME) {
357        decode_ideltachat(context, IDELTACHAT_NOSLASH_SCHEME, qr).await?
358    } else if starts_with_ignore_case(qr, DCACCOUNT_SCHEME) {
359        decode_account(qr)?
360    } else if starts_with_ignore_case(qr, DCLOGIN_SCHEME) {
361        dclogin_scheme::decode_login(qr)?
362    } else if starts_with_ignore_case(qr, TG_SOCKS_SCHEME) {
363        decode_tg_socks_proxy(context, qr)?
364    } else if qr.starts_with(SHADOWSOCKS_SCHEME) {
365        decode_shadowsocks_proxy(qr)?
366    } else if starts_with_ignore_case(qr, DCBACKUP_SCHEME_PREFIX) {
367        let qr_fixed = fix_add_second_device_qr(qr);
368        decode_backup2(&qr_fixed)?
369    } else if qr.starts_with(MAILTO_SCHEME) {
370        decode_mailto(context, qr).await?
371    } else if qr.starts_with(SMTP_SCHEME) {
372        decode_smtp(context, qr).await?
373    } else if qr.starts_with(MATMSG_SCHEME) {
374        decode_matmsg(context, qr).await?
375    } else if qr.starts_with(VCARD_SCHEME) {
376        decode_vcard(context, qr).await?
377    } else if let Ok(url) = url::Url::parse(qr) {
378        match url.scheme() {
379            "socks5" => Qr::Proxy {
380                url: qr.to_string(),
381                host: url.host_str().context("URL has no host")?.to_string(),
382                port: url.port().unwrap_or(DEFAULT_SOCKS_PORT),
383            },
384            "http" | "https" => {
385                // Parsing with a non-standard scheme
386                // is a hack to work around the `url` crate bug
387                // <https://github.com/servo/rust-url/issues/957>.
388                let url = if let Some(rest) = qr.strip_prefix("http://") {
389                    url::Url::parse(&format!("foobarbaz://{rest}"))?
390                } else if let Some(rest) = qr.strip_prefix("https://") {
391                    url::Url::parse(&format!("foobarbaz://{rest}"))?
392                } else {
393                    // Should not happen.
394                    url
395                };
396
397                if url.port().is_none() | (url.path() != "") | url.query().is_some() {
398                    // URL without a port, with a path or query cannot be a proxy URL.
399                    Qr::Url {
400                        url: qr.to_string(),
401                    }
402                } else {
403                    Qr::Proxy {
404                        url: qr.to_string(),
405                        host: url.host_str().context("URL has no host")?.to_string(),
406                        port: url
407                            .port_or_known_default()
408                            .context("HTTP(S) URLs are guaranteed to return Some port")?,
409                    }
410                }
411            }
412            _ => Qr::Url {
413                url: qr.to_string(),
414            },
415        }
416    } else {
417        Qr::Text {
418            text: qr.to_string(),
419        }
420    };
421    Ok(qrcode)
422}
423
424/// Formats the text of the [`Qr::Backup2`] variant.
425///
426/// This is the inverse of [`check_qr`] for that variant only.
427///
428/// TODO: Refactor this so all variants have a correct [`Display`] and transform `check_qr`
429/// into `FromStr`.
430pub fn format_backup(qr: &Qr) -> Result<String> {
431    match qr {
432        Qr::Backup2 {
433            node_addr,
434            auth_token,
435        } => {
436            let node_addr = serde_json::to_string(node_addr)?;
437            Ok(format!(
438                "{DCBACKUP_SCHEME_PREFIX}{DCBACKUP_VERSION}:{auth_token}&{node_addr}"
439            ))
440        }
441        _ => Err(anyhow!("Not a backup QR code")),
442    }
443}
444
445/// scheme: `OPENPGP4FPR:FINGERPRINT#a=ADDR&n=NAME&i=INVITENUMBER&s=AUTH`
446///     or: `OPENPGP4FPR:FINGERPRINT#a=ADDR&g=GROUPNAME&x=GROUPID&i=INVITENUMBER&s=AUTH`
447///     or: `OPENPGP4FPR:FINGERPRINT#a=ADDR&b=BROADCAST_NAME&x=BROADCAST_ID&j=INVITENUMBER&s=AUTH`
448///     or: `OPENPGP4FPR:FINGERPRINT#a=ADDR`
449async fn decode_openpgp(context: &Context, qr: &str) -> Result<Qr> {
450    let payload = qr
451        .get(OPENPGP4FPR_SCHEME.len()..)
452        .context("Invalid OPENPGP4FPR scheme")?;
453
454    // macOS and iOS sometimes replace the # with %23 (uri encode it), we should be able to parse this wrong format too.
455    // see issue https://github.com/deltachat/deltachat-core-rust/issues/1969 for more info
456    let (fingerprint, fragment) = match payload
457        .split_once('#')
458        .or_else(|| payload.split_once("%23"))
459    {
460        Some(pair) => pair,
461        None => (payload, ""),
462    };
463    let fingerprint: Fingerprint = fingerprint
464        .parse()
465        .context("Failed to parse fingerprint in the QR code")?;
466
467    let param: BTreeMap<&str, &str> = fragment
468        .split('&')
469        .filter_map(|s| {
470            if let [key, value] = s.splitn(2, '=').collect::<Vec<_>>()[..] {
471                Some((key, value))
472            } else {
473                None
474            }
475        })
476        .collect();
477
478    let addr = if let Some(addr) = param.get("a") {
479        Some(normalize_address(addr)?)
480    } else {
481        None
482    };
483
484    let name = decode_name(&param, "n")?.unwrap_or_default();
485
486    let invitenumber = param
487        .get("i")
488        // For historic reansons, broadcasts currently use j instead of i for the invitenumber:
489        .or_else(|| param.get("j"))
490        .filter(|&s| validate_id(s))
491        .map(|s| s.to_string());
492    let authcode = param
493        .get("s")
494        .filter(|&s| validate_id(s))
495        .map(|s| s.to_string());
496    let grpid = param
497        .get("x")
498        .filter(|&s| validate_id(s))
499        .map(|s| s.to_string());
500
501    let grpname = decode_name(&param, "g")?;
502    let broadcast_name = decode_name(&param, "b")?;
503
504    if let (Some(addr), Some(invitenumber), Some(authcode)) = (&addr, invitenumber, authcode) {
505        let addr = ContactAddress::new(addr)?;
506        let (contact_id, _) = Contact::add_or_lookup_ex(
507            context,
508            &name,
509            &addr,
510            &fingerprint.hex(),
511            Origin::UnhandledSecurejoinQrScan,
512        )
513        .await
514        .with_context(|| format!("failed to add or lookup contact for address {addr:?}"))?;
515
516        if let (Some(grpid), Some(grpname)) = (grpid.clone(), grpname) {
517            if context
518                .is_self_addr(&addr)
519                .await
520                .with_context(|| format!("can't check if address {addr:?} is our address"))?
521            {
522                if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await? {
523                    Ok(Qr::WithdrawVerifyGroup {
524                        grpname,
525                        grpid,
526                        contact_id,
527                        fingerprint,
528                        invitenumber,
529                        authcode,
530                    })
531                } else {
532                    Ok(Qr::ReviveVerifyGroup {
533                        grpname,
534                        grpid,
535                        contact_id,
536                        fingerprint,
537                        invitenumber,
538                        authcode,
539                    })
540                }
541            } else {
542                Ok(Qr::AskVerifyGroup {
543                    grpname,
544                    grpid,
545                    contact_id,
546                    fingerprint,
547                    invitenumber,
548                    authcode,
549                })
550            }
551        } else if let (Some(grpid), Some(name)) = (grpid, broadcast_name) {
552            if context
553                .is_self_addr(&addr)
554                .await
555                .with_context(|| format!("Can't check if {addr:?} is our address"))?
556            {
557                if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await? {
558                    Ok(Qr::WithdrawJoinBroadcast {
559                        name,
560                        grpid,
561                        contact_id,
562                        fingerprint,
563                        invitenumber,
564                        authcode,
565                    })
566                } else {
567                    Ok(Qr::ReviveJoinBroadcast {
568                        name,
569                        grpid,
570                        contact_id,
571                        fingerprint,
572                        invitenumber,
573                        authcode,
574                    })
575                }
576            } else {
577                Ok(Qr::AskJoinBroadcast {
578                    name,
579                    grpid,
580                    contact_id,
581                    fingerprint,
582                    invitenumber,
583                    authcode,
584                })
585            }
586        } else if context.is_self_addr(&addr).await? {
587            if token::exists(context, token::Namespace::InviteNumber, &invitenumber).await? {
588                Ok(Qr::WithdrawVerifyContact {
589                    contact_id,
590                    fingerprint,
591                    invitenumber,
592                    authcode,
593                })
594            } else {
595                Ok(Qr::ReviveVerifyContact {
596                    contact_id,
597                    fingerprint,
598                    invitenumber,
599                    authcode,
600                })
601            }
602        } else {
603            Ok(Qr::AskVerifyContact {
604                contact_id,
605                fingerprint,
606                invitenumber,
607                authcode,
608            })
609        }
610    } else if let Some(addr) = addr {
611        let fingerprint = fingerprint.hex();
612        let (contact_id, _) =
613            Contact::add_or_lookup_ex(context, "", &addr, &fingerprint, Origin::UnhandledQrScan)
614                .await?;
615        let contact = Contact::get_by_id(context, contact_id).await?;
616
617        if contact.public_key(context).await?.is_some() {
618            Ok(Qr::FprOk { contact_id })
619        } else {
620            Ok(Qr::FprMismatch {
621                contact_id: Some(contact_id),
622            })
623        }
624    } else {
625        Ok(Qr::FprWithoutAddr {
626            fingerprint: fingerprint.to_string(),
627        })
628    }
629}
630
631fn decode_name(param: &BTreeMap<&str, &str>, key: &str) -> Result<Option<String>> {
632    if let Some(encoded_name) = param.get(key) {
633        let encoded_name = encoded_name.replace('+', "%20"); // sometimes spaces are encoded as `+`
634        let mut name = match percent_decode_str(&encoded_name).decode_utf8() {
635            Ok(name) => name.to_string(),
636            Err(err) => bail!("Invalid QR param {key}: {err}"),
637        };
638        if let Some(n) = name.strip_suffix('_') {
639            name = format!("{n}…");
640        }
641        Ok(Some(name))
642    } else {
643        Ok(None)
644    }
645}
646
647/// scheme: `https://i.delta.chat[/]#FINGERPRINT&a=ADDR[&OPTIONAL_PARAMS]`
648async fn decode_ideltachat(context: &Context, prefix: &str, qr: &str) -> Result<Qr> {
649    let qr = qr.replacen(prefix, OPENPGP4FPR_SCHEME, 1);
650    let qr = qr.replacen('&', "#", 1);
651    decode_openpgp(context, &qr)
652        .await
653        .with_context(|| format!("failed to decode {prefix} QR code"))
654}
655
656/// scheme: `DCACCOUNT:example.org`
657/// or `DCACCOUNT:https://example.org/new`
658/// or `DCACCOUNT:https://example.org/new_email?t=1w_7wDjgjelxeX884x96v3`
659fn decode_account(qr: &str) -> Result<Qr> {
660    let payload = qr
661        .get(DCACCOUNT_SCHEME.len()..)
662        .context("Invalid DCACCOUNT payload")?;
663    if payload.starts_with("https://") {
664        let url = url::Url::parse(payload).context("Invalid account URL")?;
665        if url.scheme() == "https" {
666            Ok(Qr::Account {
667                domain: url
668                    .host_str()
669                    .context("can't extract account setup domain")?
670                    .to_string(),
671            })
672        } else {
673            bail!("Bad scheme for account URL: {:?}.", url.scheme());
674        }
675    } else {
676        Ok(Qr::Account {
677            domain: payload.to_string(),
678        })
679    }
680}
681
682/// scheme: `https://t.me/socks?server=foo&port=123` or `https://t.me/socks?server=1.2.3.4&port=123`
683fn decode_tg_socks_proxy(_context: &Context, qr: &str) -> Result<Qr> {
684    let url = url::Url::parse(qr).context("Invalid t.me/socks url")?;
685
686    let mut host: Option<String> = None;
687    let mut port: u16 = DEFAULT_SOCKS_PORT;
688    let mut user: Option<String> = None;
689    let mut pass: Option<String> = None;
690    for (key, value) in url.query_pairs() {
691        if key == "server" {
692            host = Some(value.to_string());
693        } else if key == "port" {
694            port = value.parse().unwrap_or(DEFAULT_SOCKS_PORT);
695        } else if key == "user" {
696            user = Some(value.to_string());
697        } else if key == "pass" {
698            pass = Some(value.to_string());
699        }
700    }
701
702    let Some(host) = host else {
703        bail!("Bad t.me/socks url: {url:?}");
704    };
705
706    let mut url = "socks5://".to_string();
707    if let Some(pass) = pass {
708        url += &percent_encode(user.unwrap_or_default().as_bytes(), NON_ALPHANUMERIC).to_string();
709        url += ":";
710        url += &percent_encode(pass.as_bytes(), NON_ALPHANUMERIC).to_string();
711        url += "@";
712    };
713    url += &host;
714    url += ":";
715    url += &port.to_string();
716
717    Ok(Qr::Proxy { url, host, port })
718}
719
720/// Decodes `ss://` URLs for Shadowsocks proxies.
721fn decode_shadowsocks_proxy(qr: &str) -> Result<Qr> {
722    let server_config = shadowsocks::config::ServerConfig::from_url(qr)?;
723    let addr = server_config.addr();
724    let host = addr.host().to_string();
725    let port = addr.port();
726    Ok(Qr::Proxy {
727        url: qr.to_string(),
728        host,
729        port,
730    })
731}
732
733/// Decodes a `DCBACKUP` QR code.
734fn decode_backup2(qr: &str) -> Result<Qr> {
735    let version_and_payload = qr
736        .strip_prefix(DCBACKUP_SCHEME_PREFIX)
737        .ok_or_else(|| anyhow!("Invalid DCBACKUP scheme"))?;
738    let (version, payload) = version_and_payload
739        .split_once(':')
740        .context("DCBACKUP scheme separator missing")?;
741    let version: i32 = version.parse().context("Not a valid number")?;
742    if version > DCBACKUP_VERSION {
743        return Ok(Qr::BackupTooNew {});
744    }
745
746    let (auth_token, node_addr) = payload
747        .split_once('&')
748        .context("Backup QR code has no separator")?;
749    let auth_token = auth_token.to_string();
750    let node_addr = serde_json::from_str::<iroh::NodeAddr>(node_addr)
751        .context("Invalid node addr in backup QR code")?;
752
753    Ok(Qr::Backup2 {
754        node_addr,
755        auth_token,
756    })
757}
758
759#[derive(Debug, Deserialize)]
760struct CreateAccountSuccessResponse {
761    /// Email address.
762    email: String,
763
764    /// Password.
765    password: String,
766}
767#[derive(Debug, Deserialize)]
768struct CreateAccountErrorResponse {
769    /// Reason for the failure to create account returned by the server.
770    reason: String,
771}
772
773/// Takes a QR with `DCACCOUNT:` scheme, parses its parameters,
774/// downloads additional information from the contained URL
775/// and returns the login parameters.
776pub(crate) async fn login_param_from_account_qr(
777    context: &Context,
778    qr: &str,
779) -> Result<EnteredLoginParam> {
780    let payload = qr
781        .get(DCACCOUNT_SCHEME.len()..)
782        .context("Invalid DCACCOUNT scheme")?;
783
784    if !payload.starts_with(HTTPS_SCHEME) {
785        let rng = &mut rand::rngs::OsRng.unwrap_err();
786        let username = Alphanumeric.sample_string(rng, 9);
787        let addr = username + "@" + payload;
788        let password = Alphanumeric.sample_string(rng, 50);
789
790        let param = EnteredLoginParam {
791            addr,
792            imap: EnteredServerLoginParam {
793                password,
794                ..Default::default()
795            },
796            smtp: Default::default(),
797            certificate_checks: EnteredCertificateChecks::Strict,
798            oauth2: false,
799        };
800        return Ok(param);
801    }
802
803    let (response_text, response_success) = post_empty(context, payload).await?;
804    if response_success {
805        let CreateAccountSuccessResponse { password, email } = serde_json::from_str(&response_text)
806            .with_context(|| {
807                format!("Cannot create account, response is malformed:\n{response_text:?}")
808            })?;
809
810        let param = EnteredLoginParam {
811            addr: email,
812            imap: EnteredServerLoginParam {
813                password,
814                ..Default::default()
815            },
816            smtp: Default::default(),
817            certificate_checks: EnteredCertificateChecks::Strict,
818            oauth2: false,
819        };
820
821        Ok(param)
822    } else {
823        match serde_json::from_str::<CreateAccountErrorResponse>(&response_text) {
824            Ok(error) => Err(anyhow!(error.reason)),
825            Err(parse_error) => {
826                error!(
827                    context,
828                    "Cannot create account, server response could not be parsed:\n{parse_error:#}\nraw response:\n{response_text}"
829                );
830                bail!("Cannot create account, unexpected server response:\n{response_text:?}")
831            }
832        }
833    }
834}
835
836/// Sets configuration values from a QR code.
837pub async fn set_config_from_qr(context: &Context, qr: &str) -> Result<()> {
838    match check_qr(context, qr).await? {
839        Qr::Account { .. } => {
840            let mut param = login_param_from_account_qr(context, qr).await?;
841            context.add_transport_inner(&mut param).await?
842        }
843        Qr::Proxy { url, .. } => {
844            let old_proxy_url_value = context
845                .get_config(Config::ProxyUrl)
846                .await?
847                .unwrap_or_default();
848
849            // Normalize the URL.
850            let url = ProxyConfig::from_url(&url)?.to_url();
851
852            let proxy_urls: Vec<&str> = std::iter::once(url.as_str())
853                .chain(
854                    old_proxy_url_value
855                        .split('\n')
856                        .filter(|s| !s.is_empty() && *s != url),
857                )
858                .collect();
859            context
860                .set_config(Config::ProxyUrl, Some(&proxy_urls.join("\n")))
861                .await?;
862            context.set_config_bool(Config::ProxyEnabled, true).await?;
863        }
864        Qr::WithdrawVerifyContact {
865            invitenumber,
866            authcode,
867            ..
868        } => {
869            token::delete(context, "").await?;
870            context
871                .sync_qr_code_token_deletion(invitenumber, authcode)
872                .await?;
873        }
874        Qr::WithdrawVerifyGroup {
875            grpid,
876            invitenumber,
877            authcode,
878            ..
879        }
880        | Qr::WithdrawJoinBroadcast {
881            grpid,
882            invitenumber,
883            authcode,
884            ..
885        } => {
886            token::delete(context, &grpid).await?;
887            context
888                .sync_qr_code_token_deletion(invitenumber, authcode)
889                .await?;
890        }
891        Qr::ReviveVerifyContact {
892            invitenumber,
893            authcode,
894            ..
895        } => {
896            let timestamp = time();
897            token::save(
898                context,
899                token::Namespace::InviteNumber,
900                None,
901                &invitenumber,
902                timestamp,
903            )
904            .await?;
905            token::save(context, token::Namespace::Auth, None, &authcode, timestamp).await?;
906            context.sync_qr_code_tokens(None).await?;
907            context.scheduler.interrupt_inbox().await;
908        }
909        Qr::ReviveVerifyGroup {
910            invitenumber,
911            authcode,
912            grpid,
913            ..
914        }
915        | Qr::ReviveJoinBroadcast {
916            invitenumber,
917            authcode,
918            grpid,
919            ..
920        } => {
921            let timestamp = time();
922            token::save(
923                context,
924                token::Namespace::InviteNumber,
925                Some(&grpid),
926                &invitenumber,
927                timestamp,
928            )
929            .await?;
930            token::save(
931                context,
932                token::Namespace::Auth,
933                Some(&grpid),
934                &authcode,
935                timestamp,
936            )
937            .await?;
938            context.sync_qr_code_tokens(Some(&grpid)).await?;
939            context.scheduler.interrupt_inbox().await;
940        }
941        Qr::Login { address, options } => {
942            let mut param = login_param_from_login_qr(&address, options)?;
943            context.add_transport_inner(&mut param).await?
944        }
945        _ => bail!("QR code does not contain config"),
946    }
947
948    Ok(())
949}
950
951/// Extract address for the mailto scheme.
952///
953/// Scheme: `mailto:addr...?subject=...&body=..`
954async fn decode_mailto(context: &Context, qr: &str) -> Result<Qr> {
955    let payload = qr
956        .get(MAILTO_SCHEME.len()..)
957        .context("Invalid mailto: scheme")?;
958
959    let (addr, query) = payload.split_once('?').unwrap_or((payload, ""));
960
961    let param: BTreeMap<&str, &str> = query
962        .split('&')
963        .filter_map(|s| {
964            if let [key, value] = s.splitn(2, '=').collect::<Vec<_>>()[..] {
965                Some((key, value))
966            } else {
967                None
968            }
969        })
970        .collect();
971
972    let subject = if let Some(subject) = param.get("subject") {
973        subject.to_string()
974    } else {
975        "".to_string()
976    };
977    let draft = if let Some(body) = param.get("body") {
978        if subject.is_empty() {
979            body.to_string()
980        } else {
981            subject + "\n" + body
982        }
983    } else {
984        subject
985    };
986    let draft = draft.replace('+', "%20"); // sometimes spaces are encoded as `+`
987    let draft = match percent_decode_str(&draft).decode_utf8() {
988        Ok(decoded_draft) => decoded_draft.to_string(),
989        Err(_err) => draft,
990    };
991
992    let addr = normalize_address(addr)?;
993    let name = "";
994    Qr::from_address(
995        context,
996        name,
997        &addr,
998        if draft.is_empty() { None } else { Some(draft) },
999    )
1000    .await
1001}
1002
1003/// Extract address for the smtp scheme.
1004///
1005/// Scheme: `SMTP:addr...:subject...:body...`
1006async fn decode_smtp(context: &Context, qr: &str) -> Result<Qr> {
1007    let payload = qr.get(SMTP_SCHEME.len()..).context("Invalid SMTP scheme")?;
1008
1009    let (addr, _rest) = payload
1010        .split_once(':')
1011        .context("Invalid SMTP scheme payload")?;
1012    let addr = normalize_address(addr)?;
1013    let name = "";
1014    Qr::from_address(context, name, &addr, None).await
1015}
1016
1017/// Extract address for the matmsg scheme.
1018///
1019/// Scheme: `MATMSG:TO:addr...;SUB:subject...;BODY:body...;`
1020///
1021/// There may or may not be linebreaks after the fields.
1022async fn decode_matmsg(context: &Context, qr: &str) -> Result<Qr> {
1023    // Does not work when the text `TO:` is used in subject/body _and_ TO: is not the first field.
1024    // we ignore this case.
1025    let addr = if let Some(to_index) = qr.find("TO:") {
1026        let addr = qr.get(to_index + 3..).unwrap_or_default().trim();
1027        if let Some(semi_index) = addr.find(';') {
1028            addr.get(..semi_index).unwrap_or_default().trim()
1029        } else {
1030            addr
1031        }
1032    } else {
1033        bail!("Invalid MATMSG found");
1034    };
1035
1036    let addr = normalize_address(addr)?;
1037    let name = "";
1038    Qr::from_address(context, name, &addr, None).await
1039}
1040
1041static VCARD_NAME_RE: LazyLock<regex::Regex> =
1042    LazyLock::new(|| regex::Regex::new(r"(?m)^N:([^;]*);([^;\n]*)").unwrap());
1043static VCARD_EMAIL_RE: LazyLock<regex::Regex> =
1044    LazyLock::new(|| regex::Regex::new(r"(?m)^EMAIL([^:\n]*):([^;\n]*)").unwrap());
1045
1046/// Extract address for the vcard scheme.
1047///
1048/// Scheme: `VCARD:BEGIN\nN:last name;first name;...;\nEMAIL;<type>:addr...;`
1049async fn decode_vcard(context: &Context, qr: &str) -> Result<Qr> {
1050    let name = VCARD_NAME_RE
1051        .captures(qr)
1052        .and_then(|caps| {
1053            let last_name = caps.get(1)?.as_str().trim();
1054            let first_name = caps.get(2)?.as_str().trim();
1055
1056            Some(format!("{first_name} {last_name}"))
1057        })
1058        .unwrap_or_default();
1059
1060    let addr = if let Some(cap) = VCARD_EMAIL_RE.captures(qr).and_then(|caps| caps.get(2)) {
1061        normalize_address(cap.as_str().trim())?
1062    } else {
1063        bail!("Bad e-mail address");
1064    };
1065
1066    Qr::from_address(context, &name, &addr, None).await
1067}
1068
1069impl Qr {
1070    /// Creates a new scanned QR code of a contact address.
1071    ///
1072    /// May contain a message draft.
1073    pub async fn from_address(
1074        context: &Context,
1075        name: &str,
1076        addr: &str,
1077        draft: Option<String>,
1078    ) -> Result<Self> {
1079        let addr = ContactAddress::new(addr)?;
1080        let (contact_id, _) =
1081            Contact::add_or_lookup(context, name, &addr, Origin::UnhandledQrScan).await?;
1082        Ok(Qr::Addr { contact_id, draft })
1083    }
1084}
1085
1086/// URL decodes a given address, does basic email validation on the result.
1087fn normalize_address(addr: &str) -> Result<String> {
1088    // urldecoding is needed at least for OPENPGP4FPR but should not hurt in the other cases
1089    let new_addr = percent_decode_str(addr).decode_utf8()?;
1090    let new_addr = addr_normalize(&new_addr);
1091
1092    ensure!(may_be_valid_addr(&new_addr), "Bad e-mail address");
1093
1094    Ok(new_addr.to_string())
1095}
1096
1097#[cfg(test)]
1098mod qr_tests;