deltachat/
sql.rs

1//! # SQLite wrapper.
2
3use std::collections::{HashMap, HashSet};
4use std::path::{Path, PathBuf};
5
6use anyhow::{Context as _, Result, bail, ensure};
7use rusqlite::{Connection, OpenFlags, Row, config::DbConfig, types::ValueRef};
8use tokio::sync::RwLock;
9
10use crate::blob::BlobObject;
11use crate::chat::add_device_msg;
12use crate::config::Config;
13use crate::constants::DC_CHAT_ID_TRASH;
14use crate::context::Context;
15use crate::debug_logging::set_debug_logging_xdc;
16use crate::ephemeral::start_ephemeral_timers;
17use crate::imex::BLOBS_BACKUP_NAME;
18use crate::location::delete_orphaned_poi_locations;
19use crate::log::{LogExt, error, info, warn};
20use crate::message::{Message, MsgId};
21use crate::net::dns::prune_dns_cache;
22use crate::net::http::http_cache_cleanup;
23use crate::net::prune_connection_history;
24use crate::param::{Param, Params};
25use crate::stock_str;
26use crate::tools::{SystemTime, Time, delete_file, time, time_elapsed};
27
28/// Extension to [`rusqlite::ToSql`] trait
29/// which also includes [`Send`] and [`Sync`].
30pub trait ToSql: rusqlite::ToSql + Send + Sync {}
31
32impl<T: rusqlite::ToSql + Send + Sync> ToSql for T {}
33
34/// Constructs a slice of trait object references `&dyn ToSql`.
35///
36/// One of the uses is passing more than 16 parameters
37/// to a query, because [`rusqlite::Params`] is only implemented
38/// for tuples of up to 16 elements.
39#[macro_export]
40macro_rules! params_slice {
41    ($($param:expr),+) => {
42        [$(&$param as &dyn $crate::sql::ToSql),+]
43    };
44}
45
46mod migrations;
47mod pool;
48
49use pool::Pool;
50
51/// A wrapper around the underlying Sqlite3 object.
52#[derive(Debug)]
53pub struct Sql {
54    /// Database file path
55    pub(crate) dbfile: PathBuf,
56
57    /// SQL connection pool.
58    pool: RwLock<Option<Pool>>,
59
60    /// None if the database is not open, true if it is open with passphrase and false if it is
61    /// open without a passphrase.
62    is_encrypted: RwLock<Option<bool>>,
63
64    /// Cache of `config` table.
65    pub(crate) config_cache: RwLock<HashMap<String, Option<String>>>,
66}
67
68impl Sql {
69    /// Creates new SQL database.
70    pub fn new(dbfile: PathBuf) -> Sql {
71        Self {
72            dbfile,
73            pool: Default::default(),
74            is_encrypted: Default::default(),
75            config_cache: Default::default(),
76        }
77    }
78
79    /// Tests SQLCipher passphrase.
80    ///
81    /// Returns true if passphrase is correct, i.e. the database is new or can be unlocked with
82    /// this passphrase, and false if the database is already encrypted with another passphrase or
83    /// corrupted.
84    ///
85    /// Fails if database is already open.
86    pub async fn check_passphrase(&self, passphrase: String) -> Result<bool> {
87        if self.is_open().await {
88            bail!("Database is already opened.");
89        }
90
91        // Hold the lock to prevent other thread from opening the database.
92        let _lock = self.pool.write().await;
93
94        // Test that the key is correct using a single connection.
95        let connection = Connection::open(&self.dbfile)?;
96        if !passphrase.is_empty() {
97            connection
98                .pragma_update(None, "key", &passphrase)
99                .context("Failed to set PRAGMA key")?;
100        }
101        let key_is_correct = connection
102            .query_row("SELECT count(*) FROM sqlite_master", [], |_row| Ok(()))
103            .is_ok();
104
105        Ok(key_is_correct)
106    }
107
108    /// Checks if there is currently a connection to the underlying Sqlite database.
109    pub async fn is_open(&self) -> bool {
110        self.pool.read().await.is_some()
111    }
112
113    /// Returns true if the database is encrypted.
114    ///
115    /// If database is not open, returns `None`.
116    pub(crate) async fn is_encrypted(&self) -> Option<bool> {
117        *self.is_encrypted.read().await
118    }
119
120    /// Closes all underlying Sqlite connections.
121    pub(crate) async fn close(&self) {
122        let _ = self.pool.write().await.take();
123        // drop closes the connection
124    }
125
126    /// Imports the database from a separate file with the given passphrase.
127    pub(crate) async fn import(&self, path: &Path, passphrase: String) -> Result<()> {
128        let path_str = path
129            .to_str()
130            .with_context(|| format!("path {path:?} is not valid unicode"))?
131            .to_string();
132
133        // Keep `config_cache` locked all the time the db is imported so that nobody can use invalid
134        // values from there. And clear it immediately so as not to forget in case of errors.
135        let mut config_cache = self.config_cache.write().await;
136        config_cache.clear();
137
138        let query_only = false;
139        self.call(query_only, move |conn| {
140            // Check that backup passphrase is correct before resetting our database.
141            conn.execute("ATTACH DATABASE ? AS backup KEY ?", (path_str, passphrase))
142                .context("failed to attach backup database")?;
143            let res = conn
144                .query_row("SELECT count(*) FROM sqlite_master", [], |_row| Ok(()))
145                .context("backup passphrase is not correct");
146
147            // Reset the database without reopening it. We don't want to reopen the database because we
148            // don't have main database passphrase at this point.
149            // See <https://sqlite.org/c3ref/c_dbconfig_enable_fkey.html> for documentation.
150            // Without resetting import may fail due to existing tables.
151            res.and_then(|_| {
152                conn.set_db_config(DbConfig::SQLITE_DBCONFIG_RESET_DATABASE, true)
153                    .context("failed to set SQLITE_DBCONFIG_RESET_DATABASE")
154            })
155            .and_then(|_| {
156                conn.execute("VACUUM", [])
157                    .context("failed to vacuum the database")
158            })
159            .and(
160                conn.set_db_config(DbConfig::SQLITE_DBCONFIG_RESET_DATABASE, false)
161                    .context("failed to unset SQLITE_DBCONFIG_RESET_DATABASE"),
162            )
163            .and_then(|_| {
164                conn.query_row("SELECT sqlcipher_export('main', 'backup')", [], |_row| {
165                    Ok(())
166                })
167                .context("failed to import from attached backup database")
168            })
169            .and(
170                conn.execute("DETACH DATABASE backup", [])
171                    .context("failed to detach backup database"),
172            )?;
173            Ok(())
174        })
175        .await
176    }
177
178    const N_DB_CONNECTIONS: usize = 3;
179
180    /// Creates a new connection pool.
181    fn new_pool(dbfile: &Path, passphrase: String) -> Result<Pool> {
182        let mut connections = Vec::with_capacity(Self::N_DB_CONNECTIONS);
183        for _ in 0..Self::N_DB_CONNECTIONS {
184            let connection = new_connection(dbfile, &passphrase)?;
185            connections.push(connection);
186        }
187
188        let pool = Pool::new(connections);
189        Ok(pool)
190    }
191
192    async fn try_open(&self, context: &Context, dbfile: &Path, passphrase: String) -> Result<()> {
193        *self.pool.write().await = Some(Self::new_pool(dbfile, passphrase.to_string())?);
194
195        if let Err(e) = self.run_migrations(context).await {
196            error!(context, "Running migrations failed: {e:#}");
197            // Emiting an error event probably doesn't work
198            // because we are in the process of opening the context,
199            // so there is no event emitter yet.
200            // So, try to report the error in other ways:
201            eprintln!("Running migrations failed: {e:#}");
202            context.set_migration_error(&format!("Updating Delta Chat failed. Please send this message to the Delta Chat developers, either at delta@merlinux.eu or at https://support.delta.chat.\n\n{e:#}"));
203            // We can't simply close the db for two reasons:
204            // a. backup export would fail
205            // b. The UI would think that the account is unconfigured (because `is_configured()` fails)
206            // and remove the account when the user presses "Back"
207        }
208
209        Ok(())
210    }
211
212    /// Updates SQL schema to the latest version.
213    pub async fn run_migrations(&self, context: &Context) -> Result<()> {
214        // (1) update low-level database structure.
215        // this should be done before updates that use high-level objects that
216        // rely themselves on the low-level structure.
217
218        // `update_icons` is not used anymore, since it's not necessary anymore to "update" icons:
219        let (_update_icons, disable_server_delete, recode_avatar) = migrations::run(context, self)
220            .await
221            .context("failed to run migrations")?;
222
223        // (2) updates that require high-level objects
224        // the structure is complete now and all objects are usable
225
226        if disable_server_delete {
227            // We now always watch all folders and delete messages there if delete_server is enabled.
228            // So, for people who have delete_server enabled, disable it and add a hint to the devicechat:
229            if context.get_config_delete_server_after().await?.is_some() {
230                let mut msg = Message::new_text(stock_str::delete_server_turned_off(context).await);
231                add_device_msg(context, None, Some(&mut msg)).await?;
232                context
233                    .set_config_internal(Config::DeleteServerAfter, Some("0"))
234                    .await?;
235            }
236        }
237
238        if recode_avatar {
239            if let Some(avatar) = context.get_config(Config::Selfavatar).await? {
240                let mut blob = BlobObject::from_path(context, Path::new(&avatar))?;
241                match blob.recode_to_avatar_size(context).await {
242                    Ok(()) => {
243                        if let Some(path) = blob.to_abs_path().to_str() {
244                            context
245                                .set_config_internal(Config::Selfavatar, Some(path))
246                                .await?;
247                        } else {
248                            warn!(context, "Setting selfavatar failed: non-UTF-8 filename");
249                        }
250                    }
251                    Err(e) => {
252                        warn!(context, "Migrations can't recode avatar, removing. {:#}", e);
253                        context
254                            .set_config_internal(Config::Selfavatar, None)
255                            .await?
256                    }
257                }
258            }
259        }
260
261        Ok(())
262    }
263
264    /// Opens the provided database and runs any necessary migrations.
265    /// If a database is already open, this will return an error.
266    pub async fn open(&self, context: &Context, passphrase: String) -> Result<()> {
267        if self.is_open().await {
268            error!(
269                context,
270                "Cannot open, database \"{:?}\" already opened.", self.dbfile,
271            );
272            bail!("SQL database is already opened.");
273        }
274
275        let passphrase_nonempty = !passphrase.is_empty();
276        self.try_open(context, &self.dbfile, passphrase).await?;
277        info!(context, "Opened database {:?}.", self.dbfile);
278        *self.is_encrypted.write().await = Some(passphrase_nonempty);
279
280        // setup debug logging if there is an entry containing its id
281        if let Some(xdc_id) = self
282            .get_raw_config_u32(Config::DebugLogging.as_ref())
283            .await?
284        {
285            set_debug_logging_xdc(context, Some(MsgId::new(xdc_id))).await?;
286        }
287        Ok(())
288    }
289
290    /// Changes the passphrase of encrypted database.
291    ///
292    /// The database must already be encrypted and the passphrase cannot be empty.
293    /// It is impossible to turn encrypted database into unencrypted
294    /// and vice versa this way, use import/export for this.
295    pub async fn change_passphrase(&self, passphrase: String) -> Result<()> {
296        let mut lock = self.pool.write().await;
297
298        let pool = lock.take().context("SQL connection pool is not open")?;
299        let query_only = false;
300        let conn = pool.get(query_only).await?;
301        if !passphrase.is_empty() {
302            conn.pragma_update(None, "rekey", passphrase.clone())
303                .context("Failed to set PRAGMA rekey")?;
304        }
305        drop(pool);
306
307        *lock = Some(Self::new_pool(&self.dbfile, passphrase.to_string())?);
308
309        Ok(())
310    }
311
312    /// Allocates a connection and calls `function` with the connection.
313    ///
314    /// If `query_only` is true, allocates read-only connection,
315    /// otherwise allocates write connection.
316    ///
317    /// Returns the result of the function.
318    async fn call<'a, F, R>(&'a self, query_only: bool, function: F) -> Result<R>
319    where
320        F: 'a + FnOnce(&mut Connection) -> Result<R> + Send,
321        R: Send + 'static,
322    {
323        let lock = self.pool.read().await;
324        let pool = lock.as_ref().context("no SQL connection")?;
325        let mut conn = pool.get(query_only).await?;
326        let res = tokio::task::block_in_place(move || function(&mut conn))?;
327        Ok(res)
328    }
329
330    /// Allocates a connection and calls given function, assuming it does write queries, with the
331    /// connection.
332    ///
333    /// Returns the result of the function.
334    pub async fn call_write<'a, F, R>(&'a self, function: F) -> Result<R>
335    where
336        F: 'a + FnOnce(&mut Connection) -> Result<R> + Send,
337        R: Send + 'static,
338    {
339        let query_only = false;
340        self.call(query_only, function).await
341    }
342
343    /// Execute `query` assuming it is a write query, returning the number of affected rows.
344    pub async fn execute(
345        &self,
346        query: &str,
347        params: impl rusqlite::Params + Send,
348    ) -> Result<usize> {
349        self.call_write(move |conn| {
350            let res = conn.execute(query, params)?;
351            Ok(res)
352        })
353        .await
354    }
355
356    /// Executes the given query, returning the last inserted row ID.
357    pub async fn insert(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<i64> {
358        self.call_write(move |conn| {
359            conn.execute(query, params)?;
360            Ok(conn.last_insert_rowid())
361        })
362        .await
363    }
364
365    /// Prepares and executes the statement and maps a function over the resulting rows.
366    /// Then executes the second function over the returned iterator and returns the
367    /// result of that function.
368    pub async fn query_map<T, F, G, H>(
369        &self,
370        sql: &str,
371        params: impl rusqlite::Params + Send,
372        f: F,
373        mut g: G,
374    ) -> Result<H>
375    where
376        F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>,
377        G: Send + FnMut(rusqlite::MappedRows<F>) -> Result<H>,
378        H: Send + 'static,
379    {
380        let query_only = true;
381        self.call(query_only, move |conn| {
382            let mut stmt = conn.prepare(sql)?;
383            let res = stmt.query_map(params, f)?;
384            g(res)
385        })
386        .await
387    }
388
389    /// Used for executing `SELECT COUNT` statements only. Returns the resulting count.
390    pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<usize> {
391        let count: isize = self.query_row(query, params, |row| row.get(0)).await?;
392        Ok(usize::try_from(count)?)
393    }
394
395    /// Used for executing `SELECT COUNT` statements only. Returns `true`, if the count is at least
396    /// one, `false` otherwise.
397    pub async fn exists(&self, sql: &str, params: impl rusqlite::Params + Send) -> Result<bool> {
398        let count = self.count(sql, params).await?;
399        Ok(count > 0)
400    }
401
402    /// Execute a query which is expected to return one row.
403    pub async fn query_row<T, F>(
404        &self,
405        query: &str,
406        params: impl rusqlite::Params + Send,
407        f: F,
408    ) -> Result<T>
409    where
410        F: FnOnce(&rusqlite::Row) -> rusqlite::Result<T> + Send,
411        T: Send + 'static,
412    {
413        let query_only = true;
414        self.call(query_only, move |conn| {
415            let res = conn.query_row(query, params, f)?;
416            Ok(res)
417        })
418        .await
419    }
420
421    /// Execute the function inside a transaction assuming that it does writes.
422    ///
423    /// If the function returns an error, the transaction will be rolled back. If it does not return an
424    /// error, the transaction will be committed.
425    pub async fn transaction<G, H>(&self, callback: G) -> Result<H>
426    where
427        H: Send + 'static,
428        G: Send + FnOnce(&mut rusqlite::Transaction<'_>) -> Result<H>,
429    {
430        let query_only = false;
431        self.transaction_ex(query_only, callback).await
432    }
433
434    /// Execute the function inside a transaction.
435    ///
436    /// * `query_only` - Whether the function only executes read statements (queries) and can be run
437    ///   in parallel with other transactions. NB: Creating and modifying temporary tables are also
438    ///   allowed with `query_only`, temporary tables aren't visible in other connections, but you
439    ///   need to pass `PRAGMA query_only=0;` to SQLite before that:
440    ///   ```text
441    ///   pragma_update(None, "query_only", "0")
442    ///   ```
443    ///   Also temporary tables need to be dropped because the connection is returned to the pool
444    ///   then.
445    ///
446    /// If the function returns an error, the transaction will be rolled back. If it does not return
447    /// an error, the transaction will be committed.
448    pub async fn transaction_ex<G, H>(&self, query_only: bool, callback: G) -> Result<H>
449    where
450        H: Send + 'static,
451        G: Send + FnOnce(&mut rusqlite::Transaction<'_>) -> Result<H>,
452    {
453        self.call(query_only, move |conn| {
454            let mut transaction = conn.transaction()?;
455            let ret = callback(&mut transaction);
456
457            match ret {
458                Ok(ret) => {
459                    transaction.commit()?;
460                    Ok(ret)
461                }
462                Err(err) => {
463                    transaction.rollback()?;
464                    Err(err)
465                }
466            }
467        })
468        .await
469    }
470
471    /// Query the database if the requested table already exists.
472    pub async fn table_exists(&self, name: &str) -> Result<bool> {
473        let query_only = true;
474        self.call(query_only, move |conn| {
475            let mut exists = false;
476            conn.pragma(None, "table_info", name.to_string(), |_row| {
477                // will only be executed if the info was found
478                exists = true;
479                Ok(())
480            })?;
481
482            Ok(exists)
483        })
484        .await
485    }
486
487    /// Check if a column exists in a given table.
488    pub async fn col_exists(&self, table_name: &str, col_name: &str) -> Result<bool> {
489        let query_only = true;
490        self.call(query_only, move |conn| {
491            let mut exists = false;
492            // `PRAGMA table_info` returns one row per column,
493            // each row containing 0=cid, 1=name, 2=type, 3=notnull, 4=dflt_value
494            conn.pragma(None, "table_info", table_name.to_string(), |row| {
495                let curr_name: String = row.get(1)?;
496                if col_name == curr_name {
497                    exists = true;
498                }
499                Ok(())
500            })?;
501
502            Ok(exists)
503        })
504        .await
505    }
506
507    /// Execute a query which is expected to return zero or one row.
508    pub async fn query_row_optional<T, F>(
509        &self,
510        sql: &str,
511        params: impl rusqlite::Params + Send,
512        f: F,
513    ) -> Result<Option<T>>
514    where
515        F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>,
516        T: Send + 'static,
517    {
518        let query_only = true;
519        self.call(query_only, move |conn| {
520            match conn.query_row(sql.as_ref(), params, f) {
521                Ok(res) => Ok(Some(res)),
522                Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
523                Err(err) => Err(err.into()),
524            }
525        })
526        .await
527    }
528
529    /// Executes a query which is expected to return one row and one
530    /// column. If the query does not return any rows, returns `Ok(None)`.
531    pub async fn query_get_value<T>(
532        &self,
533        query: &str,
534        params: impl rusqlite::Params + Send,
535    ) -> Result<Option<T>>
536    where
537        T: rusqlite::types::FromSql + Send + 'static,
538    {
539        self.query_row_optional(query, params, |row| row.get::<_, T>(0))
540            .await
541    }
542
543    /// Set private configuration options.
544    ///
545    /// Setting `None` deletes the value.  On failure an error message
546    /// will already have been logged.
547    pub async fn set_raw_config(&self, key: &str, value: Option<&str>) -> Result<()> {
548        let mut lock = self.config_cache.write().await;
549        if let Some(value) = value {
550            self.execute(
551                "INSERT OR REPLACE INTO config (keyname, value) VALUES (?, ?)",
552                (key, value),
553            )
554            .await?;
555        } else {
556            self.execute("DELETE FROM config WHERE keyname=?", (key,))
557                .await?;
558        }
559        lock.insert(key.to_string(), value.map(|s| s.to_string()));
560        drop(lock);
561
562        Ok(())
563    }
564
565    /// Get configuration options from the database.
566    pub async fn get_raw_config(&self, key: &str) -> Result<Option<String>> {
567        let lock = self.config_cache.read().await;
568        let cached = lock.get(key).cloned();
569        drop(lock);
570
571        if let Some(c) = cached {
572            return Ok(c);
573        }
574
575        let mut lock = self.config_cache.write().await;
576        let value = self
577            .query_get_value("SELECT value FROM config WHERE keyname=?", (key,))
578            .await
579            .context(format!("failed to fetch raw config: {key}"))?;
580        lock.insert(key.to_string(), value.clone());
581        drop(lock);
582
583        Ok(value)
584    }
585
586    /// Removes the `key`'s value from the cache.
587    pub(crate) async fn uncache_raw_config(&self, key: &str) {
588        let mut lock = self.config_cache.write().await;
589        lock.remove(key);
590    }
591
592    /// Sets configuration for the given key to 32-bit signed integer value.
593    pub async fn set_raw_config_int(&self, key: &str, value: i32) -> Result<()> {
594        self.set_raw_config(key, Some(&format!("{value}"))).await
595    }
596
597    /// Returns 32-bit signed integer configuration value for the given key.
598    pub async fn get_raw_config_int(&self, key: &str) -> Result<Option<i32>> {
599        self.get_raw_config(key)
600            .await
601            .map(|s| s.and_then(|s| s.parse().ok()))
602    }
603
604    /// Returns 32-bit unsigned integer configuration value for the given key.
605    pub async fn get_raw_config_u32(&self, key: &str) -> Result<Option<u32>> {
606        self.get_raw_config(key)
607            .await
608            .map(|s| s.and_then(|s| s.parse().ok()))
609    }
610
611    /// Returns boolean configuration value for the given key.
612    pub async fn get_raw_config_bool(&self, key: &str) -> Result<bool> {
613        // Not the most obvious way to encode bool as string, but it is matter
614        // of backward compatibility.
615        let res = self.get_raw_config_int(key).await?;
616        Ok(res.unwrap_or_default() > 0)
617    }
618
619    /// Sets configuration for the given key to boolean value.
620    pub async fn set_raw_config_bool(&self, key: &str, value: bool) -> Result<()> {
621        let value = if value { Some("1") } else { None };
622        self.set_raw_config(key, value).await
623    }
624
625    /// Sets configuration for the given key to 64-bit signed integer value.
626    pub async fn set_raw_config_int64(&self, key: &str, value: i64) -> Result<()> {
627        self.set_raw_config(key, Some(&format!("{value}"))).await
628    }
629
630    /// Returns 64-bit signed integer configuration value for the given key.
631    pub async fn get_raw_config_int64(&self, key: &str) -> Result<Option<i64>> {
632        self.get_raw_config(key)
633            .await
634            .map(|s| s.and_then(|r| r.parse().ok()))
635    }
636
637    /// Returns configuration cache.
638    #[cfg(feature = "internals")]
639    pub fn config_cache(&self) -> &RwLock<HashMap<String, Option<String>>> {
640        &self.config_cache
641    }
642
643    /// Runs a checkpoint operation in TRUNCATE mode, so the WAL file is truncated to 0 bytes.
644    pub(crate) async fn wal_checkpoint(context: &Context) -> Result<()> {
645        let t_start = Time::now();
646        let lock = context.sql.pool.read().await;
647        let Some(pool) = lock.as_ref() else {
648            // No db connections, nothing to checkpoint.
649            return Ok(());
650        };
651
652        // Do as much work as possible without blocking anybody.
653        let query_only = true;
654        let conn = pool.get(query_only).await?;
655        tokio::task::block_in_place(|| {
656            // Execute some transaction causing the WAL file to be opened so that the
657            // `wal_checkpoint()` can proceed, otherwise it fails when called the first time,
658            // see https://sqlite.org/forum/forumpost/7512d76a05268fc8.
659            conn.query_row("PRAGMA table_list", [], |_| Ok(()))?;
660            conn.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()))
661        })?;
662
663        // Kick out writers.
664        const _: () = assert!(Sql::N_DB_CONNECTIONS > 1, "Deadlock possible");
665        let _write_lock = pool.write_lock().await;
666        let t_writers_blocked = Time::now();
667        // Ensure that all readers use the most recent database snapshot (are at the end of WAL) so
668        // that `wal_checkpoint(FULL)` isn't blocked. We could use `PASSIVE` as well, but it's
669        // documented poorly, https://www.sqlite.org/pragma.html#pragma_wal_checkpoint and
670        // https://www.sqlite.org/c3ref/wal_checkpoint_v2.html don't tell how it interacts with new
671        // readers.
672        let mut read_conns = Vec::with_capacity(Self::N_DB_CONNECTIONS - 1);
673        for _ in 0..(Self::N_DB_CONNECTIONS - 1) {
674            read_conns.push(pool.get(query_only).await?);
675        }
676        read_conns.clear();
677        // Checkpoint the remaining WAL pages without blocking readers.
678        let (pages_total, pages_checkpointed) = tokio::task::block_in_place(|| {
679            conn.query_row("PRAGMA wal_checkpoint(FULL)", [], |row| {
680                let pages_total: i64 = row.get(1)?;
681                let pages_checkpointed: i64 = row.get(2)?;
682                Ok((pages_total, pages_checkpointed))
683            })
684        })?;
685        if pages_checkpointed < pages_total {
686            warn!(
687                context,
688                "Cannot checkpoint whole WAL. Pages total: {pages_total}, checkpointed: {pages_checkpointed}. Make sure there are no external connections running transactions.",
689            );
690        }
691        // Kick out readers to avoid blocking/SQLITE_BUSY.
692        for _ in 0..(Self::N_DB_CONNECTIONS - 1) {
693            read_conns.push(pool.get(query_only).await?);
694        }
695        let t_readers_blocked = Time::now();
696        tokio::task::block_in_place(|| {
697            let blocked = conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
698                let blocked: i64 = row.get(0)?;
699                Ok(blocked)
700            })?;
701            ensure!(blocked == 0);
702            Ok(())
703        })?;
704        info!(
705            context,
706            "wal_checkpoint: Total time: {:?}. Writers blocked for: {:?}. Readers blocked for: {:?}.",
707            time_elapsed(&t_start),
708            time_elapsed(&t_writers_blocked),
709            time_elapsed(&t_readers_blocked),
710        );
711        Ok(())
712    }
713}
714
715/// Creates a new SQLite connection.
716///
717/// `path` is the database path.
718///
719/// `passphrase` is the SQLCipher database passphrase.
720/// Empty string if database is not encrypted.
721fn new_connection(path: &Path, passphrase: &str) -> Result<Connection> {
722    let flags = OpenFlags::SQLITE_OPEN_NO_MUTEX
723        | OpenFlags::SQLITE_OPEN_READ_WRITE
724        | OpenFlags::SQLITE_OPEN_CREATE;
725    let conn = Connection::open_with_flags(path, flags)?;
726    conn.execute_batch(
727        "PRAGMA cipher_memory_security = OFF; -- Too slow on Android
728         PRAGMA secure_delete=on;
729         PRAGMA busy_timeout = 0; -- fail immediately
730         PRAGMA soft_heap_limit = 8388608; -- 8 MiB limit, same as set in Android SQLiteDatabase.
731         PRAGMA foreign_keys=on;
732         ",
733    )?;
734
735    // Avoid SQLITE_IOERR_GETTEMPPATH errors on Android and maybe other systems.
736    // Downside is more RAM consumption esp. on VACUUM.
737    // Therefore, on systems known to have working default (using files), stay with that.
738    if cfg!(not(target_os = "ios")) {
739        conn.pragma_update(None, "temp_store", "memory")?;
740    }
741
742    if !passphrase.is_empty() {
743        conn.pragma_update(None, "key", passphrase)?;
744    }
745    // Try to enable auto_vacuum. This will only be
746    // applied if the database is new or after successful
747    // VACUUM, which usually happens before backup export.
748    // When auto_vacuum is INCREMENTAL, it is possible to
749    // use PRAGMA incremental_vacuum to return unused
750    // database pages to the filesystem.
751    conn.pragma_update(None, "auto_vacuum", "INCREMENTAL".to_string())?;
752
753    conn.pragma_update(None, "journal_mode", "WAL".to_string())?;
754    // Default synchronous=FULL is much slower. NORMAL is sufficient for WAL mode.
755    conn.pragma_update(None, "synchronous", "NORMAL".to_string())?;
756
757    Ok(conn)
758}
759
760// Tries to clear the freelist to free some space on the disk.
761//
762// This only works if auto_vacuum is enabled.
763async fn incremental_vacuum(context: &Context) -> Result<()> {
764    context
765        .sql
766        .call_write(move |conn| {
767            let mut stmt = conn
768                .prepare("PRAGMA incremental_vacuum")
769                .context("Failed to prepare incremental_vacuum statement")?;
770
771            // It is important to step the statement until it returns no more rows.
772            // Otherwise it will not free as many pages as it can:
773            // <https://stackoverflow.com/questions/53746807/sqlite-incremental-vacuum-removing-only-one-free-page>.
774            let mut rows = stmt
775                .query(())
776                .context("Failed to run incremental_vacuum statement")?;
777            let mut row_count = 0;
778            while let Some(_row) = rows
779                .next()
780                .context("Failed to step incremental_vacuum statement")?
781            {
782                row_count += 1;
783            }
784            info!(context, "Incremental vacuum freed {row_count} pages.");
785            Ok(())
786        })
787        .await
788}
789
790/// Cleanup the account to restore some storage and optimize the database.
791pub async fn housekeeping(context: &Context) -> Result<()> {
792    // Setting `Config::LastHousekeeping` at the beginning avoids endless loops when things do not
793    // work out for whatever reason or are interrupted by the OS.
794    if let Err(e) = context
795        .set_config_internal(Config::LastHousekeeping, Some(&time().to_string()))
796        .await
797    {
798        warn!(context, "Can't set config: {e:#}.");
799    }
800
801    http_cache_cleanup(context)
802        .await
803        .context("Failed to cleanup HTTP cache")
804        .log_err(context)
805        .ok();
806    migrations::msgs_to_key_contacts(context)
807        .await
808        .context("migrations::msgs_to_key_contacts")
809        .log_err(context)
810        .ok();
811
812    if let Err(err) = remove_unused_files(context).await {
813        warn!(
814            context,
815            "Housekeeping: cannot remove unused files: {:#}.", err
816        );
817    }
818
819    if let Err(err) = start_ephemeral_timers(context).await {
820        warn!(
821            context,
822            "Housekeeping: cannot start ephemeral timers: {:#}.", err
823        );
824    }
825
826    if let Err(err) = prune_tombstones(&context.sql).await {
827        warn!(
828            context,
829            "Housekeeping: Cannot prune message tombstones: {:#}.", err
830        );
831    }
832
833    if let Err(err) = incremental_vacuum(context).await {
834        warn!(context, "Failed to run incremental vacuum: {err:#}.");
835    }
836    // Work around possible checkpoint starvations (there were cases reported when a WAL file is
837    // bigger than 200M) and also make sure we truncate the WAL periodically. Auto-checkponting does
838    // not normally truncate the WAL (unless the `journal_size_limit` pragma is set), see
839    // https://www.sqlite.org/wal.html.
840    if let Err(err) = Sql::wal_checkpoint(context).await {
841        warn!(context, "wal_checkpoint() failed: {err:#}.");
842        debug_assert!(false);
843    }
844
845    context
846        .sql
847        .execute(
848            "DELETE FROM msgs_mdns WHERE msg_id NOT IN \
849            (SELECT id FROM msgs WHERE chat_id!=?)",
850            (DC_CHAT_ID_TRASH,),
851        )
852        .await
853        .context("failed to remove old MDNs")
854        .log_err(context)
855        .ok();
856
857    context
858        .sql
859        .execute(
860            "DELETE FROM msgs_status_updates WHERE msg_id NOT IN \
861            (SELECT id FROM msgs WHERE chat_id!=?)",
862            (DC_CHAT_ID_TRASH,),
863        )
864        .await
865        .context("failed to remove old webxdc status updates")
866        .log_err(context)
867        .ok();
868
869    prune_connection_history(context)
870        .await
871        .context("Failed to prune connection history")
872        .log_err(context)
873        .ok();
874    prune_dns_cache(context)
875        .await
876        .context("Failed to prune DNS cache")
877        .log_err(context)
878        .ok();
879
880    // Delete POI locations
881    // which don't have corresponding message.
882    delete_orphaned_poi_locations(context)
883        .await
884        .context("Failed to delete orphaned POI locations")
885        .log_err(context)
886        .ok();
887
888    info!(context, "Housekeeping done.");
889    Ok(())
890}
891
892/// Get the value of a column `idx` of the `row` as `Vec<u8>`.
893pub fn row_get_vec(row: &Row, idx: usize) -> rusqlite::Result<Vec<u8>> {
894    row.get(idx).or_else(|err| match row.get_ref(idx)? {
895        ValueRef::Null => Ok(Vec::new()),
896        ValueRef::Text(text) => Ok(text.to_vec()),
897        ValueRef::Blob(blob) => Ok(blob.to_vec()),
898        ValueRef::Integer(_) | ValueRef::Real(_) => Err(err),
899    })
900}
901
902/// Enumerates used files in the blobdir and removes unused ones.
903pub async fn remove_unused_files(context: &Context) -> Result<()> {
904    let mut files_in_use = HashSet::new();
905    let mut unreferenced_count = 0;
906
907    info!(context, "Start housekeeping...");
908    maybe_add_from_param(
909        &context.sql,
910        &mut files_in_use,
911        "SELECT param FROM msgs  WHERE chat_id!=3   AND type!=10;",
912        Param::File,
913    )
914    .await?;
915    maybe_add_from_param(
916        &context.sql,
917        &mut files_in_use,
918        "SELECT param FROM chats;",
919        Param::ProfileImage,
920    )
921    .await?;
922    maybe_add_from_param(
923        &context.sql,
924        &mut files_in_use,
925        "SELECT param FROM contacts;",
926        Param::ProfileImage,
927    )
928    .await?;
929
930    context
931        .sql
932        .query_map(
933            "SELECT value FROM config;",
934            (),
935            |row| row.get::<_, String>(0),
936            |rows| {
937                for row in rows {
938                    maybe_add_file(&mut files_in_use, &row?);
939                }
940                Ok(())
941            },
942        )
943        .await
944        .context("housekeeping: failed to SELECT value FROM config")?;
945
946    context
947        .sql
948        .query_map(
949            "SELECT blobname FROM http_cache",
950            (),
951            |row| row.get::<_, String>(0),
952            |rows| {
953                for row in rows {
954                    maybe_add_file(&mut files_in_use, &row?);
955                }
956                Ok(())
957            },
958        )
959        .await
960        .context("Failed to SELECT blobname FROM http_cache")?;
961
962    info!(context, "{} files in use.", files_in_use.len());
963    /* go through directories and delete unused files */
964    let blobdir = context.get_blobdir();
965    for p in [&blobdir.join(BLOBS_BACKUP_NAME), blobdir] {
966        match tokio::fs::read_dir(p).await {
967            Ok(mut dir_handle) => {
968                /* avoid deletion of files that are just created to build a message object */
969                let diff = std::time::Duration::from_secs(60 * 60);
970                let keep_files_newer_than = SystemTime::now()
971                    .checked_sub(diff)
972                    .unwrap_or(SystemTime::UNIX_EPOCH);
973
974                while let Ok(Some(entry)) = dir_handle.next_entry().await {
975                    let name_f = entry.file_name();
976                    let name_s = name_f.to_string_lossy();
977
978                    if p == blobdir
979                        && (is_file_in_use(&files_in_use, None, &name_s)
980                            || is_file_in_use(&files_in_use, Some(".waveform"), &name_s)
981                            || is_file_in_use(&files_in_use, Some("-preview.jpg"), &name_s))
982                    {
983                        continue;
984                    }
985
986                    let stats = match tokio::fs::metadata(entry.path()).await {
987                        Err(err) => {
988                            warn!(
989                                context,
990                                "Cannot get metadata for {}: {:#}.",
991                                entry.path().display(),
992                                err
993                            );
994                            continue;
995                        }
996                        Ok(stats) => stats,
997                    };
998
999                    if stats.is_dir() {
1000                        if let Err(e) = tokio::fs::remove_dir(entry.path()).await {
1001                            // The dir could be created not by a user, but by a desktop
1002                            // environment f.e. So, no warning.
1003                            info!(
1004                                context,
1005                                "Housekeeping: Cannot rmdir {}: {:#}.",
1006                                entry.path().display(),
1007                                e
1008                            );
1009                        }
1010                        continue;
1011                    }
1012
1013                    unreferenced_count += 1;
1014                    let recently_created = stats.created().is_ok_and(|t| t > keep_files_newer_than);
1015                    let recently_modified =
1016                        stats.modified().is_ok_and(|t| t > keep_files_newer_than);
1017                    let recently_accessed =
1018                        stats.accessed().is_ok_and(|t| t > keep_files_newer_than);
1019
1020                    if p == blobdir && (recently_created || recently_modified || recently_accessed)
1021                    {
1022                        info!(
1023                            context,
1024                            "Housekeeping: Keeping new unreferenced file #{}: {:?}.",
1025                            unreferenced_count,
1026                            entry.file_name(),
1027                        );
1028                        continue;
1029                    }
1030
1031                    info!(
1032                        context,
1033                        "Housekeeping: Deleting unreferenced file #{}: {:?}.",
1034                        unreferenced_count,
1035                        entry.file_name()
1036                    );
1037                    let path = entry.path();
1038                    if let Err(err) = delete_file(context, &path).await {
1039                        error!(
1040                            context,
1041                            "Failed to delete unused file {}: {:#}.",
1042                            path.display(),
1043                            err
1044                        );
1045                    }
1046                }
1047            }
1048            Err(err) => {
1049                if !p.ends_with(BLOBS_BACKUP_NAME) {
1050                    warn!(
1051                        context,
1052                        "Housekeeping: Cannot read dir {}: {:#}.",
1053                        p.display(),
1054                        err
1055                    );
1056                }
1057            }
1058        }
1059    }
1060
1061    Ok(())
1062}
1063
1064fn is_file_in_use(files_in_use: &HashSet<String>, namespc_opt: Option<&str>, name: &str) -> bool {
1065    let name_to_check = if let Some(namespc) = namespc_opt {
1066        let Some(name) = name.strip_suffix(namespc) else {
1067            return false;
1068        };
1069        name
1070    } else {
1071        name
1072    };
1073    files_in_use.contains(name_to_check)
1074}
1075
1076fn maybe_add_file(files_in_use: &mut HashSet<String>, file: &str) {
1077    if let Some(file) = file.strip_prefix("$BLOBDIR/") {
1078        files_in_use.insert(file.to_string());
1079    }
1080}
1081
1082async fn maybe_add_from_param(
1083    sql: &Sql,
1084    files_in_use: &mut HashSet<String>,
1085    query: &str,
1086    param_id: Param,
1087) -> Result<()> {
1088    sql.query_map(
1089        query,
1090        (),
1091        |row| row.get::<_, String>(0),
1092        |rows| {
1093            for row in rows {
1094                let param: Params = row?.parse().unwrap_or_default();
1095                if let Some(file) = param.get(param_id) {
1096                    maybe_add_file(files_in_use, file);
1097                }
1098            }
1099            Ok(())
1100        },
1101    )
1102    .await
1103    .context(format!("housekeeping: failed to add_from_param {query}"))?;
1104
1105    Ok(())
1106}
1107
1108/// Removes from the database stale locally deleted messages that also don't
1109/// have a server UID.
1110async fn prune_tombstones(sql: &Sql) -> Result<()> {
1111    // Keep tombstones for the last two days to prevent redownloading locally deleted messages.
1112    let timestamp_max = time().saturating_sub(2 * 24 * 3600);
1113    sql.execute(
1114        "DELETE FROM msgs
1115         WHERE chat_id=?
1116         AND timestamp<=?
1117         AND NOT EXISTS (
1118         SELECT * FROM imap WHERE msgs.rfc724_mid=rfc724_mid AND target!=''
1119         )",
1120        (DC_CHAT_ID_TRASH, timestamp_max),
1121    )
1122    .await?;
1123    Ok(())
1124}
1125
1126#[cfg(test)]
1127mod sql_tests;