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