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