deltachat/
config.rs

1//! # Key-value configuration management.
2
3use std::env;
4use std::path::Path;
5use std::str::FromStr;
6
7use anyhow::{Context as _, Result, bail, ensure};
8use base64::Engine as _;
9use deltachat_contact_tools::{addr_cmp, sanitize_single_line};
10use serde::{Deserialize, Serialize};
11use strum::{EnumProperty, IntoEnumIterator};
12use strum_macros::{AsRefStr, Display, EnumIter, EnumString};
13use tokio::fs;
14
15use crate::blob::BlobObject;
16use crate::configure::EnteredLoginParam;
17use crate::constants;
18use crate::context::Context;
19use crate::events::EventType;
20use crate::log::{LogExt, info};
21use crate::login_param::ConfiguredLoginParam;
22use crate::mimefactory::RECOMMENDED_FILE_SIZE;
23use crate::provider::{Provider, get_provider_by_id};
24use crate::sync::{self, Sync::*, SyncData};
25use crate::tools::get_abs_path;
26
27/// The available configuration keys.
28#[derive(
29    Debug,
30    Clone,
31    Copy,
32    PartialEq,
33    Eq,
34    Display,
35    EnumString,
36    AsRefStr,
37    EnumIter,
38    EnumProperty,
39    PartialOrd,
40    Ord,
41    Serialize,
42    Deserialize,
43)]
44#[strum(serialize_all = "snake_case")]
45pub enum Config {
46    /// Email address, used in the `From:` field.
47    Addr,
48
49    /// IMAP server hostname.
50    MailServer,
51
52    /// IMAP server username.
53    MailUser,
54
55    /// IMAP server password.
56    MailPw,
57
58    /// IMAP server port.
59    MailPort,
60
61    /// IMAP server security (e.g. TLS, STARTTLS).
62    MailSecurity,
63
64    /// How to check TLS certificates.
65    ///
66    /// "IMAP" in the name is for compatibility,
67    /// this actually applies to both IMAP and SMTP connections.
68    ImapCertificateChecks,
69
70    /// SMTP server hostname.
71    SendServer,
72
73    /// SMTP server username.
74    SendUser,
75
76    /// SMTP server password.
77    SendPw,
78
79    /// SMTP server port.
80    SendPort,
81
82    /// SMTP server security (e.g. TLS, STARTTLS).
83    SendSecurity,
84
85    /// Deprecated option for backwards compatibility.
86    ///
87    /// Certificate checks for SMTP are actually controlled by `imap_certificate_checks` config.
88    SmtpCertificateChecks,
89
90    /// Whether to use OAuth 2.
91    ///
92    /// Historically contained other bitflags, which are now deprecated.
93    /// Should not be extended in the future, create new config keys instead.
94    ServerFlags,
95
96    /// True if proxy is enabled.
97    ///
98    /// Can be used to disable proxy without erasing known URLs.
99    ProxyEnabled,
100
101    /// Proxy URL.
102    ///
103    /// Supported URLs schemes are `http://` (HTTP), `https://` (HTTPS),
104    /// `socks5://` (SOCKS5) and `ss://` (Shadowsocks).
105    ///
106    /// May contain multiple URLs separated by newline, in which case the first one is used.
107    ProxyUrl,
108
109    /// True if SOCKS5 is enabled.
110    ///
111    /// Can be used to disable SOCKS5 without erasing SOCKS5 configuration.
112    ///
113    /// Deprecated in favor of `ProxyEnabled`.
114    Socks5Enabled,
115
116    /// SOCKS5 proxy server hostname or address.
117    ///
118    /// Deprecated in favor of `ProxyUrl`.
119    Socks5Host,
120
121    /// SOCKS5 proxy server port.
122    ///
123    /// Deprecated in favor of `ProxyUrl`.
124    Socks5Port,
125
126    /// SOCKS5 proxy server username.
127    ///
128    /// Deprecated in favor of `ProxyUrl`.
129    Socks5User,
130
131    /// SOCKS5 proxy server password.
132    ///
133    /// Deprecated in favor of `ProxyUrl`.
134    Socks5Password,
135
136    /// Own name to use in the `From:` field when sending messages.
137    Displayname,
138
139    /// Own status to display, sent in message footer.
140    Selfstatus,
141
142    /// Own avatar filename.
143    Selfavatar,
144
145    /// Send BCC copy to self.
146    ///
147    /// Should be enabled for multidevice setups.
148    /// Default is 0 for chatmail accounts, 1 otherwise.
149    ///
150    /// This is automatically enabled when importing/exporting a backup,
151    /// setting up a second device, or receiving a sync message.
152    BccSelf,
153
154    /// True if Message Delivery Notifications (read receipts) should
155    /// be sent and requested.
156    #[strum(props(default = "1"))]
157    MdnsEnabled,
158
159    /// True if "Sent" folder should be watched for changes.
160    #[strum(props(default = "0"))]
161    SentboxWatch,
162
163    /// True if chat messages should be moved to a separate folder. Auto-sent messages like sync
164    /// ones are moved there anyway.
165    #[strum(props(default = "1"))]
166    MvboxMove,
167
168    /// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only.
169    ///
170    /// This will not entirely disable other folders, e.g. the spam folder will also still
171    /// be watched for new messages.
172    #[strum(props(default = "0"))]
173    OnlyFetchMvbox,
174
175    /// Whether to show classic emails or only chat messages.
176    #[strum(props(default = "2"))] // also change ShowEmails.default() on changes
177    ShowEmails,
178
179    /// Quality of the media files to send.
180    #[strum(props(default = "0"))] // also change MediaQuality.default() on changes
181    MediaQuality,
182
183    /// If set to "1", then existing messages are considered to be already fetched.
184    /// This flag is reset after successful configuration.
185    #[strum(props(default = "1"))]
186    FetchedExistingMsgs,
187
188    /// Timer in seconds after which the message is deleted from the
189    /// server.
190    ///
191    /// 0 means messages are never deleted by Delta Chat.
192    ///
193    /// Value 1 is treated as "delete at once": messages are deleted
194    /// immediately, without moving to DeltaChat folder.
195    ///
196    /// Default is 1 for chatmail accounts without `BccSelf`, 0 otherwise.
197    DeleteServerAfter,
198
199    /// Timer in seconds after which the message is deleted from the
200    /// device.
201    ///
202    /// Equals to 0 by default, which means the message is never
203    /// deleted.
204    #[strum(props(default = "0"))]
205    DeleteDeviceAfter,
206
207    /// Move messages to the Trash folder instead of marking them "\Deleted". Overrides
208    /// `ProviderOptions::delete_to_trash`.
209    DeleteToTrash,
210
211    /// The primary email address. Also see `SecondaryAddrs`.
212    ConfiguredAddr,
213
214    /// List of configured IMAP servers as a JSON array.
215    ConfiguredImapServers,
216
217    /// Configured IMAP server hostname.
218    ///
219    /// This is replaced by `configured_imap_servers` for new configurations.
220    ConfiguredMailServer,
221
222    /// Configured IMAP server port.
223    ///
224    /// This is replaced by `configured_imap_servers` for new configurations.
225    ConfiguredMailPort,
226
227    /// Configured IMAP server security (e.g. TLS, STARTTLS).
228    ///
229    /// This is replaced by `configured_imap_servers` for new configurations.
230    ConfiguredMailSecurity,
231
232    /// Configured IMAP server username.
233    ///
234    /// This is set if user has configured username manually.
235    ConfiguredMailUser,
236
237    /// Configured IMAP server password.
238    ConfiguredMailPw,
239
240    /// Configured TLS certificate checks.
241    /// This option is saved on successful configuration
242    /// and should not be modified manually.
243    ///
244    /// This actually applies to both IMAP and SMTP connections,
245    /// but has "IMAP" in the name for backwards compatibility.
246    ConfiguredImapCertificateChecks,
247
248    /// List of configured SMTP servers as a JSON array.
249    ConfiguredSmtpServers,
250
251    /// Configured SMTP server hostname.
252    ///
253    /// This is replaced by `configured_smtp_servers` for new configurations.
254    ConfiguredSendServer,
255
256    /// Configured SMTP server port.
257    ///
258    /// This is replaced by `configured_smtp_servers` for new configurations.
259    ConfiguredSendPort,
260
261    /// Configured SMTP server security (e.g. TLS, STARTTLS).
262    ///
263    /// This is replaced by `configured_smtp_servers` for new configurations.
264    ConfiguredSendSecurity,
265
266    /// Configured SMTP server username.
267    ///
268    /// This is set if user has configured username manually.
269    ConfiguredSendUser,
270
271    /// Configured SMTP server password.
272    ConfiguredSendPw,
273
274    /// Deprecated, stored for backwards compatibility.
275    ///
276    /// ConfiguredImapCertificateChecks is actually used.
277    ConfiguredSmtpCertificateChecks,
278
279    /// Whether OAuth 2 is used with configured provider.
280    ConfiguredServerFlags,
281
282    /// Configured folder for incoming messages.
283    ConfiguredInboxFolder,
284
285    /// Configured folder for chat messages.
286    ConfiguredMvboxFolder,
287
288    /// Configured "Sent" folder.
289    ConfiguredSentboxFolder,
290
291    /// Configured "Trash" folder.
292    ConfiguredTrashFolder,
293
294    /// Unix timestamp of the last successful configuration.
295    ConfiguredTimestamp,
296
297    /// ID of the configured provider from the provider database.
298    ConfiguredProvider,
299
300    /// True if account is configured.
301    Configured,
302
303    /// True if account is a chatmail account.
304    IsChatmail,
305
306    /// True if `IsChatmail` mustn't be autoconfigured. For tests.
307    FixIsChatmail,
308
309    /// True if account is muted.
310    IsMuted,
311
312    /// Optional tag as "Work", "Family".
313    /// Meant to help profile owner to differ between profiles with similar names.
314    PrivateTag,
315
316    /// All secondary self addresses separated by spaces
317    /// (`addr1@example.org addr2@example.org addr3@example.org`)
318    SecondaryAddrs,
319
320    /// Read-only core version string.
321    #[strum(serialize = "sys.version")]
322    SysVersion,
323
324    /// Maximal recommended attachment size in bytes.
325    #[strum(serialize = "sys.msgsize_max_recommended")]
326    SysMsgsizeMaxRecommended,
327
328    /// Space separated list of all config keys available.
329    #[strum(serialize = "sys.config_keys")]
330    SysConfigKeys,
331
332    /// True if it is a bot account.
333    Bot,
334
335    /// True when to skip initial start messages in groups.
336    #[strum(props(default = "0"))]
337    SkipStartMessages,
338
339    /// Whether we send a warning if the password is wrong (set to false when we send a warning
340    /// because we do not want to send a second warning)
341    #[strum(props(default = "0"))]
342    NotifyAboutWrongPw,
343
344    /// If a warning about exceeding quota was shown recently,
345    /// this is the percentage of quota at the time the warning was given.
346    /// Unset, when quota falls below minimal warning threshold again.
347    QuotaExceeding,
348
349    /// Timestamp of the last time housekeeping was run
350    LastHousekeeping,
351
352    /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.
353    LastCantDecryptOutgoingMsgs,
354
355    /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.
356    #[strum(props(default = "60"))]
357    ScanAllFoldersDebounceSecs,
358
359    /// Whether to avoid using IMAP IDLE even if the server supports it.
360    ///
361    /// This is a developer option for testing "fake idle".
362    #[strum(props(default = "0"))]
363    DisableIdle,
364
365    /// Timestamp of the next check for donation request need.
366    DonationRequestNextCheck,
367
368    /// Defines the max. size (in bytes) of messages downloaded automatically.
369    /// 0 = no limit.
370    #[strum(props(default = "0"))]
371    DownloadLimit,
372
373    /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set
374    /// and `Bot` unset.
375    ///
376    /// On real devices, this is usually always enabled and `BccSelf` is the only setting
377    /// that controls whether sync messages are sent.
378    ///
379    /// In tests, this is usually disabled.
380    #[strum(props(default = "1"))]
381    SyncMsgs,
382
383    /// Space-separated list of all the authserv-ids which we believe
384    /// may be the one of our email server.
385    ///
386    /// See `crate::authres::update_authservid_candidates`.
387    AuthservIdCandidates,
388
389    /// Make all outgoing messages with Autocrypt header "multipart/signed".
390    SignUnencrypted,
391
392    /// Enable header protection for `Autocrypt` header.
393    ///
394    /// This is an experimental setting not compatible to other MUAs
395    /// and older Delta Chat versions (core version <= v1.149.0).
396    ProtectAutocrypt,
397
398    /// Let the core save all events to the database.
399    /// This value is used internally to remember the MsgId of the logging xdc
400    #[strum(props(default = "0"))]
401    DebugLogging,
402
403    /// Last message processed by the bot.
404    LastMsgId,
405
406    /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by
407    /// default.
408    ///
409    /// This is not supposed to be changed by UIs and only used for testing.
410    #[strum(props(default = "172800"))]
411    GossipPeriod,
412
413    /// Row ID of the key in the `keypairs` table
414    /// used for signatures, encryption to self and included in `Autocrypt` header.
415    KeyId,
416
417    /// This key is sent to the self_reporting bot so that the bot can recognize the user
418    /// without storing the email address
419    SelfReportingId,
420
421    /// MsgId of webxdc map integration.
422    WebxdcIntegration,
423
424    /// Enable webxdc realtime features.
425    #[strum(props(default = "1"))]
426    WebxdcRealtimeEnabled,
427
428    /// Last device token stored on the chatmail server.
429    ///
430    /// If it has not changed, we do not store
431    /// the device token again.
432    DeviceToken,
433
434    /// Device token encrypted with OpenPGP.
435    ///
436    /// We store encrypted token next to `device_token`
437    /// to avoid encrypting it differently and
438    /// storing the same token multiple times on the server.
439    EncryptedDeviceToken,
440
441    /// Return an error from `receive_imf_inner()` for a fully downloaded message. For tests.
442    FailOnReceivingFullMsg,
443}
444
445impl Config {
446    /// Whether the config option is synced across devices.
447    ///
448    /// This must be checked on both sides so that if there are different client versions, the
449    /// synchronisation of a particular option is either done or not done in both directions.
450    /// Moreover, receivers of a config value need to check if a key can be synced because if it is
451    /// a file path, it could otherwise lead to exfiltration of files from a receiver's
452    /// device if we assume an attacker to have control of a device in a multi-device setting or if
453    /// multiple users are sharing an account. Another example is `Self::SyncMsgs` itself which
454    /// mustn't be controlled by other devices.
455    pub(crate) fn is_synced(&self) -> bool {
456        matches!(
457            self,
458            Self::Displayname
459                | Self::MdnsEnabled
460                | Self::MvboxMove
461                | Self::ShowEmails
462                | Self::Selfavatar
463                | Self::Selfstatus,
464        )
465    }
466
467    /// Whether the config option needs an IO scheduler restart to take effect.
468    pub(crate) fn needs_io_restart(&self) -> bool {
469        matches!(
470            self,
471            Config::MvboxMove | Config::OnlyFetchMvbox | Config::SentboxWatch
472        )
473    }
474}
475
476impl Context {
477    /// Returns true if configuration value is set in the db for the given key.
478    ///
479    /// NB: Don't use this to check if the key is configured because this doesn't look into
480    /// environment. The proper use of this function is e.g. checking a key before setting it.
481    pub(crate) async fn config_exists(&self, key: Config) -> Result<bool> {
482        Ok(self.sql.get_raw_config(key.as_ref()).await?.is_some())
483    }
484
485    /// Get a config key value. Returns `None` if no value is set.
486    pub(crate) async fn get_config_opt(&self, key: Config) -> Result<Option<String>> {
487        let env_key = format!("DELTACHAT_{}", key.as_ref().to_uppercase());
488        if let Ok(value) = env::var(env_key) {
489            return Ok(Some(value));
490        }
491
492        let value = match key {
493            Config::Selfavatar => {
494                let rel_path = self.sql.get_raw_config(key.as_ref()).await?;
495                rel_path.map(|p| {
496                    get_abs_path(self, Path::new(&p))
497                        .to_string_lossy()
498                        .into_owned()
499                })
500            }
501            Config::SysVersion => Some((*constants::DC_VERSION_STR).clone()),
502            Config::SysMsgsizeMaxRecommended => Some(format!("{RECOMMENDED_FILE_SIZE}")),
503            Config::SysConfigKeys => Some(get_config_keys_string()),
504            _ => self.sql.get_raw_config(key.as_ref()).await?,
505        };
506        Ok(value)
507    }
508
509    /// Get a config key value if set, or a default value. Returns `None` if no value exists.
510    pub async fn get_config(&self, key: Config) -> Result<Option<String>> {
511        let value = self.get_config_opt(key).await?;
512        if value.is_some() {
513            return Ok(value);
514        }
515
516        // Default values
517        let val = match key {
518            Config::BccSelf => match Box::pin(self.is_chatmail()).await? {
519                false => Some("1".to_string()),
520                true => Some("0".to_string()),
521            },
522            Config::ConfiguredInboxFolder => Some("INBOX".to_string()),
523            Config::DeleteServerAfter => {
524                match !Box::pin(self.get_config_bool(Config::BccSelf)).await?
525                    && Box::pin(self.is_chatmail()).await?
526                {
527                    true => Some("1".to_string()),
528                    false => Some("0".to_string()),
529                }
530            }
531            Config::Addr => self.get_config_opt(Config::ConfiguredAddr).await?,
532            _ => key.get_str("default").map(|s| s.to_string()),
533        };
534        Ok(val)
535    }
536
537    /// Returns Some(T) if a value for the given key is set and was successfully parsed.
538    /// Returns None if could not parse.
539    pub(crate) async fn get_config_opt_parsed<T: FromStr>(&self, key: Config) -> Result<Option<T>> {
540        self.get_config_opt(key)
541            .await
542            .map(|s: Option<String>| s.and_then(|s| s.parse().ok()))
543    }
544
545    /// Returns Some(T) if a value for the given key exists (incl. default value) and was
546    /// successfully parsed.
547    /// Returns None if could not parse.
548    pub async fn get_config_parsed<T: FromStr>(&self, key: Config) -> Result<Option<T>> {
549        self.get_config(key)
550            .await
551            .map(|s: Option<String>| s.and_then(|s| s.parse().ok()))
552    }
553
554    /// Returns 32-bit signed integer configuration value for the given key.
555    pub async fn get_config_int(&self, key: Config) -> Result<i32> {
556        Ok(self.get_config_parsed(key).await?.unwrap_or_default())
557    }
558
559    /// Returns 32-bit unsigned integer configuration value for the given key.
560    pub async fn get_config_u32(&self, key: Config) -> Result<u32> {
561        Ok(self.get_config_parsed(key).await?.unwrap_or_default())
562    }
563
564    /// Returns 64-bit signed integer configuration value for the given key.
565    pub async fn get_config_i64(&self, key: Config) -> Result<i64> {
566        Ok(self.get_config_parsed(key).await?.unwrap_or_default())
567    }
568
569    /// Returns 64-bit unsigned integer configuration value for the given key.
570    pub async fn get_config_u64(&self, key: Config) -> Result<u64> {
571        Ok(self.get_config_parsed(key).await?.unwrap_or_default())
572    }
573
574    /// Returns boolean configuration value (if set) for the given key.
575    pub(crate) async fn get_config_bool_opt(&self, key: Config) -> Result<Option<bool>> {
576        Ok(self
577            .get_config_opt_parsed::<i32>(key)
578            .await?
579            .map(|x| x != 0))
580    }
581
582    /// Returns boolean configuration value for the given key.
583    pub async fn get_config_bool(&self, key: Config) -> Result<bool> {
584        Ok(self
585            .get_config_parsed::<i32>(key)
586            .await?
587            .map(|x| x != 0)
588            .unwrap_or_default())
589    }
590
591    /// Returns true if movebox ("DeltaChat" folder) should be watched.
592    pub(crate) async fn should_watch_mvbox(&self) -> Result<bool> {
593        Ok(self.get_config_bool(Config::MvboxMove).await?
594            || self.get_config_bool(Config::OnlyFetchMvbox).await?
595            || !self.get_config_bool(Config::IsChatmail).await?)
596    }
597
598    /// Returns true if sentbox ("Sent" folder) should be watched.
599    pub(crate) async fn should_watch_sentbox(&self) -> Result<bool> {
600        Ok(self.get_config_bool(Config::SentboxWatch).await?
601            && self
602                .get_config(Config::ConfiguredSentboxFolder)
603                .await?
604                .is_some())
605    }
606
607    /// Returns true if sync messages should be sent.
608    pub(crate) async fn should_send_sync_msgs(&self) -> Result<bool> {
609        Ok(self.get_config_bool(Config::SyncMsgs).await?
610            && self.get_config_bool(Config::BccSelf).await?
611            && !self.get_config_bool(Config::Bot).await?)
612    }
613
614    /// Returns whether sync messages should be uploaded to the mvbox.
615    pub(crate) async fn should_move_sync_msgs(&self) -> Result<bool> {
616        Ok(self.get_config_bool(Config::MvboxMove).await?
617            || !self.get_config_bool(Config::IsChatmail).await?)
618    }
619
620    /// Returns whether MDNs should be requested.
621    pub(crate) async fn should_request_mdns(&self) -> Result<bool> {
622        match self.get_config_bool_opt(Config::MdnsEnabled).await? {
623            Some(val) => Ok(val),
624            None => Ok(!self.get_config_bool(Config::Bot).await?),
625        }
626    }
627
628    /// Returns whether MDNs should be sent.
629    pub(crate) async fn should_send_mdns(&self) -> Result<bool> {
630        self.get_config_bool(Config::MdnsEnabled).await
631    }
632
633    /// Gets configured "delete_server_after" value.
634    ///
635    /// `None` means never delete the message, `Some(0)` means delete
636    /// at once, `Some(x)` means delete after `x` seconds.
637    pub async fn get_config_delete_server_after(&self) -> Result<Option<i64>> {
638        let val = match self
639            .get_config_parsed::<i64>(Config::DeleteServerAfter)
640            .await?
641            .unwrap_or(0)
642        {
643            0 => None,
644            1 => Some(0),
645            x => Some(x),
646        };
647        Ok(val)
648    }
649
650    /// Gets the configured provider, as saved in the `configured_provider` value.
651    ///
652    /// The provider is determined by `get_provider_info()` during configuration and then saved
653    /// to the db in `param.save_to_database()`, together with all the other `configured_*` values.
654    pub async fn get_configured_provider(&self) -> Result<Option<&'static Provider>> {
655        if let Some(cfg) = self.get_config(Config::ConfiguredProvider).await? {
656            return Ok(get_provider_by_id(&cfg));
657        }
658        Ok(None)
659    }
660
661    /// Gets configured "delete_device_after" value.
662    ///
663    /// `None` means never delete the message, `Some(x)` means delete
664    /// after `x` seconds.
665    pub async fn get_config_delete_device_after(&self) -> Result<Option<i64>> {
666        match self.get_config_int(Config::DeleteDeviceAfter).await? {
667            0 => Ok(None),
668            x => Ok(Some(i64::from(x))),
669        }
670    }
671
672    /// Executes [`SyncData::Config`] item sent by other device.
673    pub(crate) async fn sync_config(&self, key: &Config, value: &str) -> Result<()> {
674        let config_value;
675        let value = match key {
676            Config::Selfavatar if value.is_empty() => None,
677            Config::Selfavatar => {
678                config_value = BlobObject::store_from_base64(self, value)?;
679                Some(config_value.as_str())
680            }
681            _ => Some(value),
682        };
683        match key.is_synced() {
684            true => self.set_config_ex(Nosync, *key, value).await,
685            false => Ok(()),
686        }
687    }
688
689    fn check_config(key: Config, value: Option<&str>) -> Result<()> {
690        match key {
691            Config::Socks5Enabled
692            | Config::ProxyEnabled
693            | Config::BccSelf
694            | Config::MdnsEnabled
695            | Config::SentboxWatch
696            | Config::MvboxMove
697            | Config::OnlyFetchMvbox
698            | Config::DeleteToTrash
699            | Config::Configured
700            | Config::Bot
701            | Config::NotifyAboutWrongPw
702            | Config::SyncMsgs
703            | Config::SignUnencrypted
704            | Config::DisableIdle => {
705                ensure!(
706                    matches!(value, None | Some("0") | Some("1")),
707                    "Boolean value must be either 0 or 1"
708                );
709            }
710            _ => (),
711        }
712        Ok(())
713    }
714
715    /// Set the given config key and make it effective.
716    /// This may restart the IO scheduler. If `None` is passed as a value the value is cleared and
717    /// set to the default if there is one.
718    pub async fn set_config(&self, key: Config, value: Option<&str>) -> Result<()> {
719        Self::check_config(key, value)?;
720
721        let _pause = match key.needs_io_restart() {
722            true => self.scheduler.pause(self).await?,
723            _ => Default::default(),
724        };
725        self.set_config_internal(key, value).await?;
726        if key == Config::SentboxWatch {
727            self.last_full_folder_scan.lock().await.take();
728        }
729        Ok(())
730    }
731
732    pub(crate) async fn set_config_internal(&self, key: Config, value: Option<&str>) -> Result<()> {
733        self.set_config_ex(Sync, key, value).await
734    }
735
736    pub(crate) async fn set_config_ex(
737        &self,
738        sync: sync::Sync,
739        key: Config,
740        mut value: Option<&str>,
741    ) -> Result<()> {
742        Self::check_config(key, value)?;
743        let sync = sync == Sync && key.is_synced() && self.is_configured().await?;
744        let better_value;
745
746        match key {
747            Config::Selfavatar => {
748                self.sql
749                    .execute("UPDATE contacts SET selfavatar_sent=0;", ())
750                    .await?;
751                match value {
752                    Some(path) => {
753                        let path = get_abs_path(self, Path::new(path));
754                        let mut blob = BlobObject::create_and_deduplicate(self, &path, &path)?;
755                        blob.recode_to_avatar_size(self).await?;
756                        self.sql
757                            .set_raw_config(key.as_ref(), Some(blob.as_name()))
758                            .await?;
759                        if sync {
760                            let buf = fs::read(blob.to_abs_path()).await?;
761                            better_value = base64::engine::general_purpose::STANDARD.encode(buf);
762                            value = Some(&better_value);
763                        }
764                    }
765                    None => {
766                        self.sql.set_raw_config(key.as_ref(), None).await?;
767                        if sync {
768                            better_value = String::new();
769                            value = Some(&better_value);
770                        }
771                    }
772                }
773                self.emit_event(EventType::SelfavatarChanged);
774            }
775            Config::DeleteDeviceAfter => {
776                let ret = self.sql.set_raw_config(key.as_ref(), value).await;
777                // Interrupt ephemeral loop to delete old messages immediately.
778                self.scheduler.interrupt_ephemeral_task().await;
779                ret?
780            }
781            Config::Displayname => {
782                if let Some(v) = value {
783                    better_value = sanitize_single_line(v);
784                    value = Some(&better_value);
785                }
786                self.sql.set_raw_config(key.as_ref(), value).await?;
787            }
788            Config::Addr => {
789                self.sql
790                    .set_raw_config(key.as_ref(), value.map(|s| s.to_lowercase()).as_deref())
791                    .await?;
792            }
793            Config::MvboxMove => {
794                self.sql.set_raw_config(key.as_ref(), value).await?;
795                self.sql
796                    .set_raw_config(constants::DC_FOLDERS_CONFIGURED_KEY, None)
797                    .await?;
798            }
799            Config::ConfiguredAddr => {
800                if self.is_configured().await? {
801                    bail!("Cannot change ConfiguredAddr");
802                }
803                if let Some(addr) = value {
804                    info!(
805                        self,
806                        "Creating a pseudo configured account which will not be able to send or receive messages. Only meant for tests!"
807                    );
808                    ConfiguredLoginParam::from_json(&format!(
809                        r#"{{"addr":"{addr}","imap":[],"imap_user":"","imap_password":"","smtp":[],"smtp_user":"","smtp_password":"","certificate_checks":"Automatic","oauth2":false}}"#
810                    ))?
811                    .save_to_transports_table(self, &EnteredLoginParam::default())
812                    .await?;
813                }
814            }
815            _ => {
816                self.sql.set_raw_config(key.as_ref(), value).await?;
817            }
818        }
819        if matches!(
820            key,
821            Config::Displayname | Config::Selfavatar | Config::PrivateTag
822        ) {
823            self.emit_event(EventType::AccountsItemChanged);
824        }
825        if key.is_synced() {
826            self.emit_event(EventType::ConfigSynced { key });
827        }
828        if !sync {
829            return Ok(());
830        }
831        let Some(val) = value else {
832            return Ok(());
833        };
834        let val = val.to_string();
835        if self
836            .add_sync_item(SyncData::Config { key, val })
837            .await
838            .log_err(self)
839            .is_err()
840        {
841            return Ok(());
842        }
843        self.scheduler.interrupt_inbox().await;
844        Ok(())
845    }
846
847    /// Set the given config to an unsigned 32-bit integer value.
848    pub async fn set_config_u32(&self, key: Config, value: u32) -> Result<()> {
849        self.set_config(key, Some(&value.to_string())).await?;
850        Ok(())
851    }
852
853    /// Set the given config to a boolean value.
854    pub async fn set_config_bool(&self, key: Config, value: bool) -> Result<()> {
855        self.set_config(key, from_bool(value)).await?;
856        Ok(())
857    }
858
859    /// Sets an ui-specific key-value pair.
860    /// Keys must be prefixed by `ui.`
861    /// and should be followed by the name of the system and maybe subsystem,
862    /// eg. `ui.desktop.linux.foo`, `ui.desktop.macos.bar`, `ui.ios.foobar`.
863    pub async fn set_ui_config(&self, key: &str, value: Option<&str>) -> Result<()> {
864        ensure!(key.starts_with("ui."), "set_ui_config(): prefix missing.");
865        self.sql.set_raw_config(key, value).await
866    }
867
868    /// Gets an ui-specific value set by set_ui_config().
869    pub async fn get_ui_config(&self, key: &str) -> Result<Option<String>> {
870        ensure!(key.starts_with("ui."), "get_ui_config(): prefix missing.");
871        self.sql.get_raw_config(key).await
872    }
873}
874
875/// Returns a value for use in `Context::set_config_*()` for the given `bool`.
876pub(crate) fn from_bool(val: bool) -> Option<&'static str> {
877    Some(if val { "1" } else { "0" })
878}
879
880// Separate impl block for self address handling
881impl Context {
882    /// Determine whether the specified addr maps to the/a self addr.
883    /// Returns `false` if no addresses are configured.
884    pub(crate) async fn is_self_addr(&self, addr: &str) -> Result<bool> {
885        Ok(self
886            .get_config(Config::ConfiguredAddr)
887            .await?
888            .iter()
889            .any(|a| addr_cmp(addr, a))
890            || self
891                .get_secondary_self_addrs()
892                .await?
893                .iter()
894                .any(|a| addr_cmp(addr, a)))
895    }
896
897    /// Sets `primary_new` as the new primary self address and saves the old
898    /// primary address (if exists) as a secondary address.
899    ///
900    /// This should only be used by test code and during configure.
901    #[cfg(test)] // AEAP is disabled, but there are still tests for it
902    pub(crate) async fn set_primary_self_addr(&self, primary_new: &str) -> Result<()> {
903        self.quota.write().await.take();
904
905        // add old primary address (if exists) to secondary addresses
906        let mut secondary_addrs = self.get_all_self_addrs().await?;
907        // never store a primary address also as a secondary
908        secondary_addrs.retain(|a| !addr_cmp(a, primary_new));
909        self.set_config_internal(
910            Config::SecondaryAddrs,
911            Some(secondary_addrs.join(" ").as_str()),
912        )
913        .await?;
914
915        self.sql
916            .set_raw_config(Config::ConfiguredAddr.as_ref(), Some(primary_new))
917            .await?;
918        self.emit_event(EventType::ConnectivityChanged);
919        Ok(())
920    }
921
922    /// Returns all primary and secondary self addresses.
923    pub(crate) async fn get_all_self_addrs(&self) -> Result<Vec<String>> {
924        let primary_addrs = self.get_config(Config::ConfiguredAddr).await?.into_iter();
925        let secondary_addrs = self.get_secondary_self_addrs().await?.into_iter();
926
927        Ok(primary_addrs.chain(secondary_addrs).collect())
928    }
929
930    /// Returns all secondary self addresses.
931    pub(crate) async fn get_secondary_self_addrs(&self) -> Result<Vec<String>> {
932        let secondary_addrs = self
933            .get_config(Config::SecondaryAddrs)
934            .await?
935            .unwrap_or_default();
936        Ok(secondary_addrs
937            .split_ascii_whitespace()
938            .map(|s| s.to_string())
939            .collect())
940    }
941
942    /// Returns the primary self address.
943    /// Returns an error if no self addr is configured.
944    pub async fn get_primary_self_addr(&self) -> Result<String> {
945        self.get_config(Config::ConfiguredAddr)
946            .await?
947            .context("No self addr configured")
948    }
949}
950
951/// Returns all available configuration keys concated together.
952fn get_config_keys_string() -> String {
953    let keys = Config::iter().fold(String::new(), |mut acc, key| {
954        acc += key.as_ref();
955        acc += " ";
956        acc
957    });
958
959    format!(" {keys} ")
960}
961
962#[cfg(test)]
963mod config_tests;