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::context::Context;
18use crate::events::EventType;
19use crate::log::{LogExt, info};
20use crate::login_param::ConfiguredLoginParam;
21use crate::mimefactory::RECOMMENDED_FILE_SIZE;
22use crate::provider::{Provider, get_provider_by_id};
23use crate::sync::{self, Sync::*, SyncData};
24use crate::tools::get_abs_path;
25use crate::{constants, stats};
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 chat messages should be moved to a separate folder. Auto-sent messages like sync
160    /// ones are moved there anyway.
161    #[strum(props(default = "1"))]
162    MvboxMove,
163
164    /// Watch for new messages in the "Mvbox" (aka DeltaChat folder) only.
165    ///
166    /// This will not entirely disable other folders, e.g. the spam folder will also still
167    /// be watched for new messages.
168    #[strum(props(default = "0"))]
169    OnlyFetchMvbox,
170
171    /// Whether to show classic emails or only chat messages.
172    #[strum(props(default = "2"))] // also change ShowEmails.default() on changes
173    ShowEmails,
174
175    /// Quality of the media files to send.
176    #[strum(props(default = "0"))] // also change MediaQuality.default() on changes
177    MediaQuality,
178
179    /// If set to "1", then existing messages are considered to be already fetched.
180    /// This flag is reset after successful configuration.
181    #[strum(props(default = "1"))]
182    FetchedExistingMsgs,
183
184    /// Timer in seconds after which the message is deleted from the
185    /// server.
186    ///
187    /// 0 means messages are never deleted by Delta Chat.
188    ///
189    /// Value 1 is treated as "delete at once": messages are deleted
190    /// immediately, without moving to DeltaChat folder.
191    ///
192    /// Default is 1 for chatmail accounts without `BccSelf`, 0 otherwise.
193    DeleteServerAfter,
194
195    /// Timer in seconds after which the message is deleted from the
196    /// device.
197    ///
198    /// Equals to 0 by default, which means the message is never
199    /// deleted.
200    #[strum(props(default = "0"))]
201    DeleteDeviceAfter,
202
203    /// Move messages to the Trash folder instead of marking them "\Deleted". Overrides
204    /// `ProviderOptions::delete_to_trash`.
205    DeleteToTrash,
206
207    /// The primary email address. Also see `SecondaryAddrs`.
208    ConfiguredAddr,
209
210    /// List of configured IMAP servers as a JSON array.
211    ConfiguredImapServers,
212
213    /// Configured IMAP server hostname.
214    ///
215    /// This is replaced by `configured_imap_servers` for new configurations.
216    ConfiguredMailServer,
217
218    /// Configured IMAP server port.
219    ///
220    /// This is replaced by `configured_imap_servers` for new configurations.
221    ConfiguredMailPort,
222
223    /// Configured IMAP server security (e.g. TLS, STARTTLS).
224    ///
225    /// This is replaced by `configured_imap_servers` for new configurations.
226    ConfiguredMailSecurity,
227
228    /// Configured IMAP server username.
229    ///
230    /// This is set if user has configured username manually.
231    ConfiguredMailUser,
232
233    /// Configured IMAP server password.
234    ConfiguredMailPw,
235
236    /// Configured TLS certificate checks.
237    /// This option is saved on successful configuration
238    /// and should not be modified manually.
239    ///
240    /// This actually applies to both IMAP and SMTP connections,
241    /// but has "IMAP" in the name for backwards compatibility.
242    ConfiguredImapCertificateChecks,
243
244    /// List of configured SMTP servers as a JSON array.
245    ConfiguredSmtpServers,
246
247    /// Configured SMTP server hostname.
248    ///
249    /// This is replaced by `configured_smtp_servers` for new configurations.
250    ConfiguredSendServer,
251
252    /// Configured SMTP server port.
253    ///
254    /// This is replaced by `configured_smtp_servers` for new configurations.
255    ConfiguredSendPort,
256
257    /// Configured SMTP server security (e.g. TLS, STARTTLS).
258    ///
259    /// This is replaced by `configured_smtp_servers` for new configurations.
260    ConfiguredSendSecurity,
261
262    /// Configured SMTP server username.
263    ///
264    /// This is set if user has configured username manually.
265    ConfiguredSendUser,
266
267    /// Configured SMTP server password.
268    ConfiguredSendPw,
269
270    /// Deprecated, stored for backwards compatibility.
271    ///
272    /// ConfiguredImapCertificateChecks is actually used.
273    ConfiguredSmtpCertificateChecks,
274
275    /// Whether OAuth 2 is used with configured provider.
276    ConfiguredServerFlags,
277
278    /// Configured folder for incoming messages.
279    ConfiguredInboxFolder,
280
281    /// Configured folder for chat messages.
282    ConfiguredMvboxFolder,
283
284    /// Configured "Trash" folder.
285    ConfiguredTrashFolder,
286
287    /// Unix timestamp of the last successful configuration.
288    ConfiguredTimestamp,
289
290    /// ID of the configured provider from the provider database.
291    ConfiguredProvider,
292
293    /// True if account is configured.
294    Configured,
295
296    /// True if account is a chatmail account.
297    IsChatmail,
298
299    /// True if `IsChatmail` mustn't be autoconfigured. For tests.
300    FixIsChatmail,
301
302    /// True if account is muted.
303    IsMuted,
304
305    /// Optional tag as "Work", "Family".
306    /// Meant to help profile owner to differ between profiles with similar names.
307    PrivateTag,
308
309    /// All secondary self addresses separated by spaces
310    /// (`addr1@example.org addr2@example.org addr3@example.org`)
311    SecondaryAddrs,
312
313    /// Read-only core version string.
314    #[strum(serialize = "sys.version")]
315    SysVersion,
316
317    /// Maximal recommended attachment size in bytes.
318    #[strum(serialize = "sys.msgsize_max_recommended")]
319    SysMsgsizeMaxRecommended,
320
321    /// Space separated list of all config keys available.
322    #[strum(serialize = "sys.config_keys")]
323    SysConfigKeys,
324
325    /// True if it is a bot account.
326    Bot,
327
328    /// True when to skip initial start messages in groups.
329    #[strum(props(default = "0"))]
330    SkipStartMessages,
331
332    /// Whether we send a warning if the password is wrong (set to false when we send a warning
333    /// because we do not want to send a second warning)
334    #[strum(props(default = "0"))]
335    NotifyAboutWrongPw,
336
337    /// If a warning about exceeding quota was shown recently,
338    /// this is the percentage of quota at the time the warning was given.
339    /// Unset, when quota falls below minimal warning threshold again.
340    QuotaExceeding,
341
342    /// Timestamp of the last time housekeeping was run
343    LastHousekeeping,
344
345    /// Timestamp of the last `CantDecryptOutgoingMsgs` notification.
346    LastCantDecryptOutgoingMsgs,
347
348    /// To how many seconds to debounce scan_all_folders. Used mainly in tests, to disable debouncing completely.
349    #[strum(props(default = "60"))]
350    ScanAllFoldersDebounceSecs,
351
352    /// Whether to avoid using IMAP IDLE even if the server supports it.
353    ///
354    /// This is a developer option for testing "fake idle".
355    #[strum(props(default = "0"))]
356    DisableIdle,
357
358    /// Timestamp of the next check for donation request need.
359    DonationRequestNextCheck,
360
361    /// Defines the max. size (in bytes) of messages downloaded automatically.
362    /// 0 = no limit.
363    #[strum(props(default = "0"))]
364    DownloadLimit,
365
366    /// Enable sending and executing (applying) sync messages. Sending requires `BccSelf` to be set
367    /// and `Bot` unset.
368    ///
369    /// On real devices, this is usually always enabled and `BccSelf` is the only setting
370    /// that controls whether sync messages are sent.
371    ///
372    /// In tests, this is usually disabled.
373    #[strum(props(default = "1"))]
374    SyncMsgs,
375
376    /// Space-separated list of all the authserv-ids which we believe
377    /// may be the one of our email server.
378    ///
379    /// See `crate::authres::update_authservid_candidates`.
380    AuthservIdCandidates,
381
382    /// Make all outgoing messages with Autocrypt header "multipart/signed".
383    SignUnencrypted,
384
385    /// Let the core save all events to the database.
386    /// This value is used internally to remember the MsgId of the logging xdc
387    #[strum(props(default = "0"))]
388    DebugLogging,
389
390    /// Last message processed by the bot.
391    LastMsgId,
392
393    /// How often to gossip Autocrypt keys in chats with multiple recipients, in seconds. 2 days by
394    /// default.
395    ///
396    /// This is not supposed to be changed by UIs and only used for testing.
397    #[strum(props(default = "172800"))]
398    GossipPeriod,
399
400    /// Row ID of the key in the `keypairs` table
401    /// used for signatures, encryption to self and included in `Autocrypt` header.
402    KeyId,
403
404    /// Send statistics to Delta Chat's developers.
405    /// Can be exposed to the user as a setting.
406    StatsSending,
407
408    /// Last time statistics were sent to Delta Chat's developers
409    StatsLastSent,
410
411    /// Last time `update_message_stats()` was called
412    StatsLastUpdate,
413
414    /// This key is sent to the statistics bot so that the bot can recognize the user
415    /// without storing the email address
416    StatsId,
417
418    /// The last contact id that already existed when statistics-sending was enabled for the first time.
419    StatsLastOldContactId,
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!(self, Config::MvboxMove | Config::OnlyFetchMvbox)
470    }
471}
472
473impl Context {
474    /// Returns true if configuration value is set in the db for the given key.
475    ///
476    /// NB: Don't use this to check if the key is configured because this doesn't look into
477    /// environment. The proper use of this function is e.g. checking a key before setting it.
478    pub(crate) async fn config_exists(&self, key: Config) -> Result<bool> {
479        Ok(self.sql.get_raw_config(key.as_ref()).await?.is_some())
480    }
481
482    /// Get a config key value. Returns `None` if no value is set.
483    pub(crate) async fn get_config_opt(&self, key: Config) -> Result<Option<String>> {
484        let env_key = format!("DELTACHAT_{}", key.as_ref().to_uppercase());
485        if let Ok(value) = env::var(env_key) {
486            return Ok(Some(value));
487        }
488
489        let value = match key {
490            Config::Selfavatar => {
491                let rel_path = self.sql.get_raw_config(key.as_ref()).await?;
492                rel_path.map(|p| {
493                    get_abs_path(self, Path::new(&p))
494                        .to_string_lossy()
495                        .into_owned()
496                })
497            }
498            Config::SysVersion => Some((*constants::DC_VERSION_STR).clone()),
499            Config::SysMsgsizeMaxRecommended => Some(format!("{RECOMMENDED_FILE_SIZE}")),
500            Config::SysConfigKeys => Some(get_config_keys_string()),
501            _ => self.sql.get_raw_config(key.as_ref()).await?,
502        };
503        Ok(value)
504    }
505
506    /// Get a config key value if set, or a default value. Returns `None` if no value exists.
507    pub async fn get_config(&self, key: Config) -> Result<Option<String>> {
508        let value = self.get_config_opt(key).await?;
509        if value.is_some() {
510            return Ok(value);
511        }
512
513        // Default values
514        let val = match key {
515            Config::BccSelf => match Box::pin(self.is_chatmail()).await? {
516                false => Some("1".to_string()),
517                true => Some("0".to_string()),
518            },
519            Config::ConfiguredInboxFolder => Some("INBOX".to_string()),
520            Config::DeleteServerAfter => {
521                match !Box::pin(self.get_config_bool(Config::BccSelf)).await?
522                    && Box::pin(self.is_chatmail()).await?
523                {
524                    true => Some("1".to_string()),
525                    false => Some("0".to_string()),
526                }
527            }
528            Config::Addr => self.get_config_opt(Config::ConfiguredAddr).await?,
529            _ => key.get_str("default").map(|s| s.to_string()),
530        };
531        Ok(val)
532    }
533
534    /// Returns Some(T) if a value for the given key is set and was successfully parsed.
535    /// Returns None if could not parse.
536    pub(crate) async fn get_config_opt_parsed<T: FromStr>(&self, key: Config) -> Result<Option<T>> {
537        self.get_config_opt(key)
538            .await
539            .map(|s: Option<String>| s.and_then(|s| s.parse().ok()))
540    }
541
542    /// Returns Some(T) if a value for the given key exists (incl. default value) and was
543    /// successfully parsed.
544    /// Returns None if could not parse.
545    pub async fn get_config_parsed<T: FromStr>(&self, key: Config) -> Result<Option<T>> {
546        self.get_config(key)
547            .await
548            .map(|s: Option<String>| s.and_then(|s| s.parse().ok()))
549    }
550
551    /// Returns 32-bit signed integer configuration value for the given key.
552    pub async fn get_config_int(&self, key: Config) -> Result<i32> {
553        Ok(self.get_config_parsed(key).await?.unwrap_or_default())
554    }
555
556    /// Returns 32-bit unsigned integer configuration value for the given key.
557    pub async fn get_config_u32(&self, key: Config) -> Result<u32> {
558        Ok(self.get_config_parsed(key).await?.unwrap_or_default())
559    }
560
561    /// Returns 64-bit signed integer configuration value for the given key.
562    pub async fn get_config_i64(&self, key: Config) -> Result<i64> {
563        Ok(self.get_config_parsed(key).await?.unwrap_or_default())
564    }
565
566    /// Returns 64-bit unsigned integer configuration value for the given key.
567    pub async fn get_config_u64(&self, key: Config) -> Result<u64> {
568        Ok(self.get_config_parsed(key).await?.unwrap_or_default())
569    }
570
571    /// Returns boolean configuration value (if set) for the given key.
572    pub(crate) async fn get_config_bool_opt(&self, key: Config) -> Result<Option<bool>> {
573        Ok(self
574            .get_config_opt_parsed::<i32>(key)
575            .await?
576            .map(|x| x != 0))
577    }
578
579    /// Returns boolean configuration value for the given key.
580    pub async fn get_config_bool(&self, key: Config) -> Result<bool> {
581        Ok(self
582            .get_config(key)
583            .await?
584            .and_then(|s| s.parse::<i32>().ok())
585            .map(|x| x != 0)
586            .unwrap_or_default())
587    }
588
589    /// Returns true if movebox ("DeltaChat" folder) should be watched.
590    pub(crate) async fn should_watch_mvbox(&self) -> Result<bool> {
591        Ok(self.get_config_bool(Config::MvboxMove).await?
592            || self.get_config_bool(Config::OnlyFetchMvbox).await?
593            || !self.get_config_bool(Config::IsChatmail).await?)
594    }
595
596    /// Returns true if sync messages should be sent.
597    pub(crate) async fn should_send_sync_msgs(&self) -> Result<bool> {
598        Ok(self.get_config_bool(Config::SyncMsgs).await?
599            && self.get_config_bool(Config::BccSelf).await?
600            && !self.get_config_bool(Config::Bot).await?)
601    }
602
603    /// Returns whether sync messages should be uploaded to the mvbox.
604    pub(crate) async fn should_move_sync_msgs(&self) -> Result<bool> {
605        Ok(self.get_config_bool(Config::MvboxMove).await?
606            || !self.get_config_bool(Config::IsChatmail).await?)
607    }
608
609    /// Returns whether MDNs should be requested.
610    pub(crate) async fn should_request_mdns(&self) -> Result<bool> {
611        match self.get_config_bool_opt(Config::MdnsEnabled).await? {
612            Some(val) => Ok(val),
613            None => Ok(!self.get_config_bool(Config::Bot).await?),
614        }
615    }
616
617    /// Returns whether MDNs should be sent.
618    pub(crate) async fn should_send_mdns(&self) -> Result<bool> {
619        self.get_config_bool(Config::MdnsEnabled).await
620    }
621
622    /// Gets configured "delete_server_after" value.
623    ///
624    /// `None` means never delete the message, `Some(0)` means delete
625    /// at once, `Some(x)` means delete after `x` seconds.
626    pub async fn get_config_delete_server_after(&self) -> Result<Option<i64>> {
627        let val = match self
628            .get_config_parsed::<i64>(Config::DeleteServerAfter)
629            .await?
630            .unwrap_or(0)
631        {
632            0 => None,
633            1 => Some(0),
634            x => Some(x),
635        };
636        Ok(val)
637    }
638
639    /// Gets the configured provider, as saved in the `configured_provider` value.
640    ///
641    /// The provider is determined by `get_provider_info()` during configuration and then saved
642    /// to the db in `param.save_to_database()`, together with all the other `configured_*` values.
643    pub async fn get_configured_provider(&self) -> Result<Option<&'static Provider>> {
644        if let Some(cfg) = self.get_config(Config::ConfiguredProvider).await? {
645            return Ok(get_provider_by_id(&cfg));
646        }
647        Ok(None)
648    }
649
650    /// Gets configured "delete_device_after" value.
651    ///
652    /// `None` means never delete the message, `Some(x)` means delete
653    /// after `x` seconds.
654    pub async fn get_config_delete_device_after(&self) -> Result<Option<i64>> {
655        match self.get_config_int(Config::DeleteDeviceAfter).await? {
656            0 => Ok(None),
657            x => Ok(Some(i64::from(x))),
658        }
659    }
660
661    /// Executes [`SyncData::Config`] item sent by other device.
662    pub(crate) async fn sync_config(&self, key: &Config, value: &str) -> Result<()> {
663        let config_value;
664        let value = match key {
665            Config::Selfavatar if value.is_empty() => None,
666            Config::Selfavatar => {
667                config_value = BlobObject::store_from_base64(self, value)?;
668                Some(config_value.as_str())
669            }
670            _ => Some(value),
671        };
672        match key.is_synced() {
673            true => self.set_config_ex(Nosync, *key, value).await,
674            false => Ok(()),
675        }
676    }
677
678    fn check_config(key: Config, value: Option<&str>) -> Result<()> {
679        match key {
680            Config::Socks5Enabled
681            | Config::ProxyEnabled
682            | Config::BccSelf
683            | Config::MdnsEnabled
684            | Config::MvboxMove
685            | Config::OnlyFetchMvbox
686            | Config::DeleteToTrash
687            | Config::Configured
688            | Config::Bot
689            | Config::NotifyAboutWrongPw
690            | Config::SyncMsgs
691            | Config::SignUnencrypted
692            | Config::DisableIdle => {
693                ensure!(
694                    matches!(value, None | Some("0") | Some("1")),
695                    "Boolean value must be either 0 or 1"
696                );
697            }
698            _ => (),
699        }
700        Ok(())
701    }
702
703    /// Set the given config key and make it effective.
704    /// This may restart the IO scheduler. If `None` is passed as a value the value is cleared and
705    /// set to the default if there is one.
706    pub async fn set_config(&self, key: Config, value: Option<&str>) -> Result<()> {
707        Self::check_config(key, value)?;
708
709        let _pause = match key.needs_io_restart() {
710            true => self.scheduler.pause(self).await?,
711            _ => Default::default(),
712        };
713        if key == Config::StatsSending {
714            let old_value = self.get_config(key).await?;
715            let old_value = bool_from_config(old_value.as_deref());
716            let new_value = bool_from_config(value);
717            stats::pre_sending_config_change(self, old_value, new_value).await?;
718        }
719        self.set_config_internal(key, value).await?;
720        if key == Config::StatsSending {
721            stats::maybe_send_stats(self).await?;
722        }
723        Ok(())
724    }
725
726    pub(crate) async fn set_config_internal(&self, key: Config, value: Option<&str>) -> Result<()> {
727        self.set_config_ex(Sync, key, value).await
728    }
729
730    pub(crate) async fn set_config_ex(
731        &self,
732        sync: sync::Sync,
733        key: Config,
734        mut value: Option<&str>,
735    ) -> Result<()> {
736        Self::check_config(key, value)?;
737        let sync = sync == Sync && key.is_synced() && self.is_configured().await?;
738        let better_value;
739
740        match key {
741            Config::Selfavatar => {
742                self.sql
743                    .execute("UPDATE contacts SET selfavatar_sent=0;", ())
744                    .await?;
745                match value {
746                    Some(path) => {
747                        let path = get_abs_path(self, Path::new(path));
748                        let mut blob = BlobObject::create_and_deduplicate(self, &path, &path)?;
749                        blob.recode_to_avatar_size(self).await?;
750                        self.sql
751                            .set_raw_config(key.as_ref(), Some(blob.as_name()))
752                            .await?;
753                        if sync {
754                            let buf = fs::read(blob.to_abs_path()).await?;
755                            better_value = base64::engine::general_purpose::STANDARD.encode(buf);
756                            value = Some(&better_value);
757                        }
758                    }
759                    None => {
760                        self.sql.set_raw_config(key.as_ref(), None).await?;
761                        if sync {
762                            better_value = String::new();
763                            value = Some(&better_value);
764                        }
765                    }
766                }
767                self.emit_event(EventType::SelfavatarChanged);
768            }
769            Config::DeleteDeviceAfter => {
770                let ret = self.sql.set_raw_config(key.as_ref(), value).await;
771                // Interrupt ephemeral loop to delete old messages immediately.
772                self.scheduler.interrupt_ephemeral_task().await;
773                ret?
774            }
775            Config::Displayname => {
776                if let Some(v) = value {
777                    better_value = sanitize_single_line(v);
778                    value = Some(&better_value);
779                }
780                self.sql.set_raw_config(key.as_ref(), value).await?;
781            }
782            Config::Addr => {
783                self.sql
784                    .set_raw_config(key.as_ref(), value.map(|s| s.to_lowercase()).as_deref())
785                    .await?;
786            }
787            Config::MvboxMove => {
788                self.sql.set_raw_config(key.as_ref(), value).await?;
789                self.sql
790                    .set_raw_config(constants::DC_FOLDERS_CONFIGURED_KEY, None)
791                    .await?;
792            }
793            Config::ConfiguredAddr => {
794                if self.is_configured().await? {
795                    bail!("Cannot change ConfiguredAddr");
796                }
797                if let Some(addr) = value {
798                    info!(
799                        self,
800                        "Creating a pseudo configured account which will not be able to send or receive messages. Only meant for tests!"
801                    );
802                    ConfiguredLoginParam::from_json(&format!(
803                        r#"{{"addr":"{addr}","imap":[],"imap_user":"","imap_password":"","smtp":[],"smtp_user":"","smtp_password":"","certificate_checks":"Automatic","oauth2":false}}"#
804                    ))?
805                    .save_to_transports_table(self, &EnteredLoginParam::default())
806                    .await?;
807                }
808            }
809            _ => {
810                self.sql.set_raw_config(key.as_ref(), value).await?;
811            }
812        }
813        if matches!(
814            key,
815            Config::Displayname | Config::Selfavatar | Config::PrivateTag
816        ) {
817            self.emit_event(EventType::AccountsItemChanged);
818        }
819        if key.is_synced() {
820            self.emit_event(EventType::ConfigSynced { key });
821        }
822        if !sync {
823            return Ok(());
824        }
825        let Some(val) = value else {
826            return Ok(());
827        };
828        let val = val.to_string();
829        if self
830            .add_sync_item(SyncData::Config { key, val })
831            .await
832            .log_err(self)
833            .is_err()
834        {
835            return Ok(());
836        }
837        self.scheduler.interrupt_inbox().await;
838        Ok(())
839    }
840
841    /// Set the given config to an unsigned 32-bit integer value.
842    pub async fn set_config_u32(&self, key: Config, value: u32) -> Result<()> {
843        self.set_config(key, Some(&value.to_string())).await?;
844        Ok(())
845    }
846
847    /// Set the given config to a boolean value.
848    pub async fn set_config_bool(&self, key: Config, value: bool) -> Result<()> {
849        self.set_config(key, from_bool(value)).await?;
850        Ok(())
851    }
852
853    /// Sets an ui-specific key-value pair.
854    /// Keys must be prefixed by `ui.`
855    /// and should be followed by the name of the system and maybe subsystem,
856    /// eg. `ui.desktop.linux.foo`, `ui.desktop.macos.bar`, `ui.ios.foobar`.
857    pub async fn set_ui_config(&self, key: &str, value: Option<&str>) -> Result<()> {
858        ensure!(key.starts_with("ui."), "set_ui_config(): prefix missing.");
859        self.sql.set_raw_config(key, value).await
860    }
861
862    /// Gets an ui-specific value set by set_ui_config().
863    pub async fn get_ui_config(&self, key: &str) -> Result<Option<String>> {
864        ensure!(key.starts_with("ui."), "get_ui_config(): prefix missing.");
865        self.sql.get_raw_config(key).await
866    }
867}
868
869/// Returns a value for use in `Context::set_config_*()` for the given `bool`.
870pub(crate) fn from_bool(val: bool) -> Option<&'static str> {
871    Some(if val { "1" } else { "0" })
872}
873
874pub(crate) fn bool_from_config(config: Option<&str>) -> bool {
875    config.is_some_and(|v| v.parse::<i32>().unwrap_or_default() != 0)
876}
877
878// Separate impl block for self address handling
879impl Context {
880    /// Determine whether the specified addr maps to the/a self addr.
881    /// Returns `false` if no addresses are configured.
882    pub(crate) async fn is_self_addr(&self, addr: &str) -> Result<bool> {
883        Ok(self
884            .get_config(Config::ConfiguredAddr)
885            .await?
886            .iter()
887            .any(|a| addr_cmp(addr, a))
888            || self
889                .get_secondary_self_addrs()
890                .await?
891                .iter()
892                .any(|a| addr_cmp(addr, a)))
893    }
894
895    /// Sets `primary_new` as the new primary self address and saves the old
896    /// primary address (if exists) as a secondary address.
897    ///
898    /// This should only be used by test code and during configure.
899    #[cfg(test)] // AEAP is disabled, but there are still tests for it
900    pub(crate) async fn set_primary_self_addr(&self, primary_new: &str) -> Result<()> {
901        self.quota.write().await.take();
902
903        // add old primary address (if exists) to secondary addresses
904        let mut secondary_addrs = self.get_all_self_addrs().await?;
905        // never store a primary address also as a secondary
906        secondary_addrs.retain(|a| !addr_cmp(a, primary_new));
907        self.set_config_internal(
908            Config::SecondaryAddrs,
909            Some(secondary_addrs.join(" ").as_str()),
910        )
911        .await?;
912
913        self.sql
914            .set_raw_config(Config::ConfiguredAddr.as_ref(), Some(primary_new))
915            .await?;
916        self.emit_event(EventType::ConnectivityChanged);
917        Ok(())
918    }
919
920    /// Returns all primary and secondary self addresses.
921    pub(crate) async fn get_all_self_addrs(&self) -> Result<Vec<String>> {
922        let primary_addrs = self.get_config(Config::ConfiguredAddr).await?.into_iter();
923        let secondary_addrs = self.get_secondary_self_addrs().await?.into_iter();
924
925        Ok(primary_addrs.chain(secondary_addrs).collect())
926    }
927
928    /// Returns all secondary self addresses.
929    pub(crate) async fn get_secondary_self_addrs(&self) -> Result<Vec<String>> {
930        let secondary_addrs = self
931            .get_config(Config::SecondaryAddrs)
932            .await?
933            .unwrap_or_default();
934        Ok(secondary_addrs
935            .split_ascii_whitespace()
936            .map(|s| s.to_string())
937            .collect())
938    }
939
940    /// Returns the primary self address.
941    /// Returns an error if no self addr is configured.
942    pub async fn get_primary_self_addr(&self) -> Result<String> {
943        self.get_config(Config::ConfiguredAddr)
944            .await?
945            .context("No self addr configured")
946    }
947}
948
949/// Returns all available configuration keys concated together.
950fn get_config_keys_string() -> String {
951    let keys = Config::iter().fold(String::new(), |mut acc, key| {
952        acc += key.as_ref();
953        acc += " ";
954        acc
955    });
956
957    format!(" {keys} ")
958}
959
960#[cfg(test)]
961mod config_tests;