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        g: G,
374    ) -> Result<H>
375    where
376        F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>,
377        G: Send + FnOnce(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    /// Prepares and executes the statement and maps a function over the resulting rows.
390    ///
391    /// Collects the resulting rows into a generic structure.
392    pub async fn query_map_collect<T, C, F>(
393        &self,
394        sql: &str,
395        params: impl rusqlite::Params + Send,
396        f: F,
397    ) -> Result<C>
398    where
399        T: Send + 'static,
400        C: Send + 'static + std::iter::FromIterator<T>,
401        F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>,
402    {
403        self.query_map(sql, params, f, |rows| {
404            rows.collect::<std::result::Result<C, _>>()
405                .map_err(Into::into)
406        })
407        .await
408    }
409
410    /// Prepares and executes the statement and maps a function over the resulting rows.
411    ///
412    /// Collects the resulting rows into a `Vec`.
413    pub async fn query_map_vec<T, F>(
414        &self,
415        sql: &str,
416        params: impl rusqlite::Params + Send,
417        f: F,
418    ) -> Result<Vec<T>>
419    where
420        T: Send + 'static,
421        F: Send + FnMut(&rusqlite::Row) -> rusqlite::Result<T>,
422    {
423        self.query_map_collect(sql, params, f).await
424    }
425
426    /// Used for executing `SELECT COUNT` statements only. Returns the resulting count.
427    pub async fn count(&self, query: &str, params: impl rusqlite::Params + Send) -> Result<usize> {
428        let count: isize = self.query_row(query, params, |row| row.get(0)).await?;
429        Ok(usize::try_from(count)?)
430    }
431
432    /// Used for executing `SELECT COUNT` statements only. Returns `true`, if the count is at least
433    /// one, `false` otherwise.
434    pub async fn exists(&self, sql: &str, params: impl rusqlite::Params + Send) -> Result<bool> {
435        let count = self.count(sql, params).await?;
436        Ok(count > 0)
437    }
438
439    /// Execute a query which is expected to return one row.
440    pub async fn query_row<T, F>(
441        &self,
442        query: &str,
443        params: impl rusqlite::Params + Send,
444        f: F,
445    ) -> Result<T>
446    where
447        F: FnOnce(&rusqlite::Row) -> rusqlite::Result<T> + Send,
448        T: Send + 'static,
449    {
450        let query_only = true;
451        self.call(query_only, move |conn| {
452            let res = conn.query_row(query, params, f)?;
453            Ok(res)
454        })
455        .await
456    }
457
458    /// Execute the function inside a transaction assuming that it does writes.
459    ///
460    /// If the function returns an error, the transaction will be rolled back. If it does not return an
461    /// error, the transaction will be committed.
462    pub async fn transaction<G, H>(&self, callback: G) -> Result<H>
463    where
464        H: Send + 'static,
465        G: Send + FnOnce(&mut rusqlite::Transaction<'_>) -> Result<H>,
466    {
467        let query_only = false;
468        self.transaction_ex(query_only, callback).await
469    }
470
471    /// Execute the function inside a transaction.
472    ///
473    /// * `query_only` - Whether the function only executes read statements (queries) and can be run
474    ///   in parallel with other transactions. NB: Creating and modifying temporary tables are also
475    ///   allowed with `query_only`, temporary tables aren't visible in other connections, but you
476    ///   need to pass `PRAGMA query_only=0;` to SQLite before that:
477    ///   ```text
478    ///   pragma_update(None, "query_only", "0")
479    ///   ```
480    ///   Also temporary tables need to be dropped because the connection is returned to the pool
481    ///   then.
482    ///
483    /// If the function returns an error, the transaction will be rolled back. If it does not return
484    /// an error, the transaction will be committed.
485    pub async fn transaction_ex<G, H>(&self, query_only: bool, callback: G) -> Result<H>
486    where
487        H: Send + 'static,
488        G: Send + FnOnce(&mut rusqlite::Transaction<'_>) -> Result<H>,
489    {
490        self.call(query_only, move |conn| {
491            let mut transaction = conn.transaction()?;
492            let ret = callback(&mut transaction);
493
494            match ret {
495                Ok(ret) => {
496                    transaction.commit()?;
497                    Ok(ret)
498                }
499                Err(err) => {
500                    transaction.rollback()?;
501                    Err(err)
502                }
503            }
504        })
505        .await
506    }
507
508    /// Query the database if the requested table already exists.
509    pub async fn table_exists(&self, name: &str) -> Result<bool> {
510        let query_only = true;
511        self.call(query_only, move |conn| {
512            let mut exists = false;
513            conn.pragma(None, "table_info", name.to_string(), |_row| {
514                // will only be executed if the info was found
515                exists = true;
516                Ok(())
517            })?;
518
519            Ok(exists)
520        })
521        .await
522    }
523
524    /// Check if a column exists in a given table.
525    pub async fn col_exists(&self, table_name: &str, col_name: &str) -> Result<bool> {
526        let query_only = true;
527        self.call(query_only, move |conn| {
528            let mut exists = false;
529            // `PRAGMA table_info` returns one row per column,
530            // each row containing 0=cid, 1=name, 2=type, 3=notnull, 4=dflt_value
531            conn.pragma(None, "table_info", table_name.to_string(), |row| {
532                let curr_name: String = row.get(1)?;
533                if col_name == curr_name {
534                    exists = true;
535                }
536                Ok(())
537            })?;
538
539            Ok(exists)
540        })
541        .await
542    }
543
544    /// Execute a query which is expected to return zero or one row.
545    pub async fn query_row_optional<T, F>(
546        &self,
547        sql: &str,
548        params: impl rusqlite::Params + Send,
549        f: F,
550    ) -> Result<Option<T>>
551    where
552        F: Send + FnOnce(&rusqlite::Row) -> rusqlite::Result<T>,
553        T: Send + 'static,
554    {
555        let query_only = true;
556        self.call(query_only, move |conn| {
557            match conn.query_row(sql.as_ref(), params, f) {
558                Ok(res) => Ok(Some(res)),
559                Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
560                Err(err) => Err(err.into()),
561            }
562        })
563        .await
564    }
565
566    /// Executes a query which is expected to return one row and one
567    /// column. If the query does not return any rows, returns `Ok(None)`.
568    pub async fn query_get_value<T>(
569        &self,
570        query: &str,
571        params: impl rusqlite::Params + Send,
572    ) -> Result<Option<T>>
573    where
574        T: rusqlite::types::FromSql + Send + 'static,
575    {
576        self.query_row_optional(query, params, |row| row.get::<_, T>(0))
577            .await
578    }
579
580    /// Set private configuration options.
581    ///
582    /// Setting `None` deletes the value.  On failure an error message
583    /// will already have been logged.
584    pub async fn set_raw_config(&self, key: &str, value: Option<&str>) -> Result<()> {
585        let mut lock = self.config_cache.write().await;
586        if let Some(value) = value {
587            self.execute(
588                "INSERT OR REPLACE INTO config (keyname, value) VALUES (?, ?)",
589                (key, value),
590            )
591            .await?;
592        } else {
593            self.execute("DELETE FROM config WHERE keyname=?", (key,))
594                .await?;
595        }
596        lock.insert(key.to_string(), value.map(|s| s.to_string()));
597        drop(lock);
598
599        Ok(())
600    }
601
602    /// Get configuration options from the database.
603    pub async fn get_raw_config(&self, key: &str) -> Result<Option<String>> {
604        let lock = self.config_cache.read().await;
605        let cached = lock.get(key).cloned();
606        drop(lock);
607
608        if let Some(c) = cached {
609            return Ok(c);
610        }
611
612        let mut lock = self.config_cache.write().await;
613        let value = self
614            .query_get_value("SELECT value FROM config WHERE keyname=?", (key,))
615            .await
616            .context(format!("failed to fetch raw config: {key}"))?;
617        lock.insert(key.to_string(), value.clone());
618        drop(lock);
619
620        Ok(value)
621    }
622
623    /// Removes the `key`'s value from the cache.
624    pub(crate) async fn uncache_raw_config(&self, key: &str) {
625        let mut lock = self.config_cache.write().await;
626        lock.remove(key);
627    }
628
629    /// Sets configuration for the given key to 32-bit signed integer value.
630    pub async fn set_raw_config_int(&self, key: &str, value: i32) -> Result<()> {
631        self.set_raw_config(key, Some(&format!("{value}"))).await
632    }
633
634    /// Returns 32-bit signed integer configuration value for the given key.
635    pub async fn get_raw_config_int(&self, key: &str) -> Result<Option<i32>> {
636        self.get_raw_config(key)
637            .await
638            .map(|s| s.and_then(|s| s.parse().ok()))
639    }
640
641    /// Returns 32-bit unsigned integer configuration value for the given key.
642    pub async fn get_raw_config_u32(&self, key: &str) -> Result<Option<u32>> {
643        self.get_raw_config(key)
644            .await
645            .map(|s| s.and_then(|s| s.parse().ok()))
646    }
647
648    /// Returns boolean configuration value for the given key.
649    pub async fn get_raw_config_bool(&self, key: &str) -> Result<bool> {
650        // Not the most obvious way to encode bool as string, but it is matter
651        // of backward compatibility.
652        let res = self.get_raw_config_int(key).await?;
653        Ok(res.unwrap_or_default() > 0)
654    }
655
656    /// Sets configuration for the given key to boolean value.
657    pub async fn set_raw_config_bool(&self, key: &str, value: bool) -> Result<()> {
658        let value = if value { Some("1") } else { None };
659        self.set_raw_config(key, value).await
660    }
661
662    /// Sets configuration for the given key to 64-bit signed integer value.
663    pub async fn set_raw_config_int64(&self, key: &str, value: i64) -> Result<()> {
664        self.set_raw_config(key, Some(&format!("{value}"))).await
665    }
666
667    /// Returns 64-bit signed integer configuration value for the given key.
668    pub async fn get_raw_config_int64(&self, key: &str) -> Result<Option<i64>> {
669        self.get_raw_config(key)
670            .await
671            .map(|s| s.and_then(|r| r.parse().ok()))
672    }
673
674    /// Returns configuration cache.
675    #[cfg(feature = "internals")]
676    pub fn config_cache(&self) -> &RwLock<HashMap<String, Option<String>>> {
677        &self.config_cache
678    }
679
680    /// Runs a checkpoint operation in TRUNCATE mode, so the WAL file is truncated to 0 bytes.
681    pub(crate) async fn wal_checkpoint(context: &Context) -> Result<()> {
682        let t_start = Time::now();
683        let lock = context.sql.pool.read().await;
684        let Some(pool) = lock.as_ref() else {
685            // No db connections, nothing to checkpoint.
686            return Ok(());
687        };
688
689        // Do as much work as possible without blocking anybody.
690        let query_only = true;
691        let conn = pool.get(query_only).await?;
692        tokio::task::block_in_place(|| {
693            // Execute some transaction causing the WAL file to be opened so that the
694            // `wal_checkpoint()` can proceed, otherwise it fails when called the first time,
695            // see https://sqlite.org/forum/forumpost/7512d76a05268fc8.
696            conn.query_row("PRAGMA table_list", [], |_| Ok(()))?;
697            conn.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()))
698        })?;
699
700        // Kick out writers.
701        const _: () = assert!(Sql::N_DB_CONNECTIONS > 1, "Deadlock possible");
702        let _write_lock = pool.write_lock().await;
703        let t_writers_blocked = Time::now();
704        // Ensure that all readers use the most recent database snapshot (are at the end of WAL) so
705        // that `wal_checkpoint(FULL)` isn't blocked. We could use `PASSIVE` as well, but it's
706        // documented poorly, https://www.sqlite.org/pragma.html#pragma_wal_checkpoint and
707        // https://www.sqlite.org/c3ref/wal_checkpoint_v2.html don't tell how it interacts with new
708        // readers.
709        let mut read_conns = Vec::with_capacity(Self::N_DB_CONNECTIONS - 1);
710        for _ in 0..(Self::N_DB_CONNECTIONS - 1) {
711            read_conns.push(pool.get(query_only).await?);
712        }
713        read_conns.clear();
714        // Checkpoint the remaining WAL pages without blocking readers.
715        let (pages_total, pages_checkpointed) = tokio::task::block_in_place(|| {
716            conn.query_row("PRAGMA wal_checkpoint(FULL)", [], |row| {
717                let pages_total: i64 = row.get(1)?;
718                let pages_checkpointed: i64 = row.get(2)?;
719                Ok((pages_total, pages_checkpointed))
720            })
721        })?;
722        if pages_checkpointed < pages_total {
723            warn!(
724                context,
725                "Cannot checkpoint whole WAL. Pages total: {pages_total}, checkpointed: {pages_checkpointed}. Make sure there are no external connections running transactions.",
726            );
727        }
728        // Kick out readers to avoid blocking/SQLITE_BUSY.
729        for _ in 0..(Self::N_DB_CONNECTIONS - 1) {
730            read_conns.push(pool.get(query_only).await?);
731        }
732        let t_readers_blocked = Time::now();
733        tokio::task::block_in_place(|| {
734            let blocked = conn.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
735                let blocked: i64 = row.get(0)?;
736                Ok(blocked)
737            })?;
738            ensure!(blocked == 0);
739            Ok(())
740        })?;
741        info!(
742            context,
743            "wal_checkpoint: Total time: {:?}. Writers blocked for: {:?}. Readers blocked for: {:?}.",
744            time_elapsed(&t_start),
745            time_elapsed(&t_writers_blocked),
746            time_elapsed(&t_readers_blocked),
747        );
748        Ok(())
749    }
750}
751
752/// Creates a new SQLite connection.
753///
754/// `path` is the database path.
755///
756/// `passphrase` is the SQLCipher database passphrase.
757/// Empty string if database is not encrypted.
758fn new_connection(path: &Path, passphrase: &str) -> Result<Connection> {
759    let flags = OpenFlags::SQLITE_OPEN_NO_MUTEX
760        | OpenFlags::SQLITE_OPEN_READ_WRITE
761        | OpenFlags::SQLITE_OPEN_CREATE;
762    let conn = Connection::open_with_flags(path, flags)?;
763    conn.execute_batch(
764        "PRAGMA cipher_memory_security = OFF; -- Too slow on Android
765         PRAGMA secure_delete=on;
766         PRAGMA busy_timeout = 0; -- fail immediately
767         PRAGMA soft_heap_limit = 8388608; -- 8 MiB limit, same as set in Android SQLiteDatabase.
768         PRAGMA foreign_keys=on;
769         ",
770    )?;
771
772    // Avoid SQLITE_IOERR_GETTEMPPATH errors on Android and maybe other systems.
773    // Downside is more RAM consumption esp. on VACUUM.
774    // Therefore, on systems known to have working default (using files), stay with that.
775    if cfg!(not(target_os = "ios")) {
776        conn.pragma_update(None, "temp_store", "memory")?;
777    }
778
779    if !passphrase.is_empty() {
780        conn.pragma_update(None, "key", passphrase)?;
781    }
782    // Try to enable auto_vacuum. This will only be
783    // applied if the database is new or after successful
784    // VACUUM, which usually happens before backup export.
785    // When auto_vacuum is INCREMENTAL, it is possible to
786    // use PRAGMA incremental_vacuum to return unused
787    // database pages to the filesystem.
788    conn.pragma_update(None, "auto_vacuum", "INCREMENTAL".to_string())?;
789
790    conn.pragma_update(None, "journal_mode", "WAL".to_string())?;
791    // Default synchronous=FULL is much slower. NORMAL is sufficient for WAL mode.
792    conn.pragma_update(None, "synchronous", "NORMAL".to_string())?;
793
794    Ok(conn)
795}
796
797// Tries to clear the freelist to free some space on the disk.
798//
799// This only works if auto_vacuum is enabled.
800async fn incremental_vacuum(context: &Context) -> Result<()> {
801    context
802        .sql
803        .call_write(move |conn| {
804            let mut stmt = conn
805                .prepare("PRAGMA incremental_vacuum")
806                .context("Failed to prepare incremental_vacuum statement")?;
807
808            // It is important to step the statement until it returns no more rows.
809            // Otherwise it will not free as many pages as it can:
810            // <https://stackoverflow.com/questions/53746807/sqlite-incremental-vacuum-removing-only-one-free-page>.
811            let mut rows = stmt
812                .query(())
813                .context("Failed to run incremental_vacuum statement")?;
814            let mut row_count = 0;
815            while let Some(_row) = rows
816                .next()
817                .context("Failed to step incremental_vacuum statement")?
818            {
819                row_count += 1;
820            }
821            info!(context, "Incremental vacuum freed {row_count} pages.");
822            Ok(())
823        })
824        .await
825}
826
827/// Cleanup the account to restore some storage and optimize the database.
828pub async fn housekeeping(context: &Context) -> Result<()> {
829    // Setting `Config::LastHousekeeping` at the beginning avoids endless loops when things do not
830    // work out for whatever reason or are interrupted by the OS.
831    if let Err(e) = context
832        .set_config_internal(Config::LastHousekeeping, Some(&time().to_string()))
833        .await
834    {
835        warn!(context, "Can't set config: {e:#}.");
836    }
837
838    http_cache_cleanup(context)
839        .await
840        .context("Failed to cleanup HTTP cache")
841        .log_err(context)
842        .ok();
843    migrations::msgs_to_key_contacts(context)
844        .await
845        .context("migrations::msgs_to_key_contacts")
846        .log_err(context)
847        .ok();
848
849    if let Err(err) = remove_unused_files(context).await {
850        warn!(
851            context,
852            "Housekeeping: cannot remove unused files: {:#}.", err
853        );
854    }
855
856    if let Err(err) = start_ephemeral_timers(context).await {
857        warn!(
858            context,
859            "Housekeeping: cannot start ephemeral timers: {:#}.", err
860        );
861    }
862
863    if let Err(err) = prune_tombstones(&context.sql).await {
864        warn!(
865            context,
866            "Housekeeping: Cannot prune message tombstones: {:#}.", err
867        );
868    }
869
870    if let Err(err) = incremental_vacuum(context).await {
871        warn!(context, "Failed to run incremental vacuum: {err:#}.");
872    }
873    // Work around possible checkpoint starvations (there were cases reported when a WAL file is
874    // bigger than 200M) and also make sure we truncate the WAL periodically. Auto-checkponting does
875    // not normally truncate the WAL (unless the `journal_size_limit` pragma is set), see
876    // https://www.sqlite.org/wal.html.
877    if let Err(err) = Sql::wal_checkpoint(context).await {
878        warn!(context, "wal_checkpoint() failed: {err:#}.");
879        debug_assert!(false);
880    }
881
882    context
883        .sql
884        .execute(
885            "DELETE FROM msgs_mdns WHERE msg_id NOT IN \
886            (SELECT id FROM msgs WHERE chat_id!=?)",
887            (DC_CHAT_ID_TRASH,),
888        )
889        .await
890        .context("failed to remove old MDNs")
891        .log_err(context)
892        .ok();
893
894    context
895        .sql
896        .execute(
897            "DELETE FROM msgs_status_updates WHERE msg_id NOT IN \
898            (SELECT id FROM msgs WHERE chat_id!=?)",
899            (DC_CHAT_ID_TRASH,),
900        )
901        .await
902        .context("failed to remove old webxdc status updates")
903        .log_err(context)
904        .ok();
905
906    prune_connection_history(context)
907        .await
908        .context("Failed to prune connection history")
909        .log_err(context)
910        .ok();
911    prune_dns_cache(context)
912        .await
913        .context("Failed to prune DNS cache")
914        .log_err(context)
915        .ok();
916
917    // Delete POI locations
918    // which don't have corresponding message.
919    delete_orphaned_poi_locations(context)
920        .await
921        .context("Failed to delete orphaned POI locations")
922        .log_err(context)
923        .ok();
924
925    info!(context, "Housekeeping done.");
926    Ok(())
927}
928
929/// Get the value of a column `idx` of the `row` as `Vec<u8>`.
930pub fn row_get_vec(row: &Row, idx: usize) -> rusqlite::Result<Vec<u8>> {
931    row.get(idx).or_else(|err| match row.get_ref(idx)? {
932        ValueRef::Null => Ok(Vec::new()),
933        ValueRef::Text(text) => Ok(text.to_vec()),
934        ValueRef::Blob(blob) => Ok(blob.to_vec()),
935        ValueRef::Integer(_) | ValueRef::Real(_) => Err(err),
936    })
937}
938
939/// Enumerates used files in the blobdir and removes unused ones.
940pub async fn remove_unused_files(context: &Context) -> Result<()> {
941    let mut files_in_use = HashSet::new();
942    let mut unreferenced_count = 0;
943
944    info!(context, "Start housekeeping...");
945    maybe_add_from_param(
946        &context.sql,
947        &mut files_in_use,
948        "SELECT param FROM msgs  WHERE chat_id!=3   AND type!=10;",
949        Param::File,
950    )
951    .await?;
952    maybe_add_from_param(
953        &context.sql,
954        &mut files_in_use,
955        "SELECT param FROM chats;",
956        Param::ProfileImage,
957    )
958    .await?;
959    maybe_add_from_param(
960        &context.sql,
961        &mut files_in_use,
962        "SELECT param FROM contacts;",
963        Param::ProfileImage,
964    )
965    .await?;
966
967    context
968        .sql
969        .query_map(
970            "SELECT value FROM config;",
971            (),
972            |row| row.get::<_, String>(0),
973            |rows| {
974                for row in rows {
975                    maybe_add_file(&mut files_in_use, &row?);
976                }
977                Ok(())
978            },
979        )
980        .await
981        .context("housekeeping: failed to SELECT value FROM config")?;
982
983    context
984        .sql
985        .query_map(
986            "SELECT blobname FROM http_cache",
987            (),
988            |row| row.get::<_, String>(0),
989            |rows| {
990                for row in rows {
991                    maybe_add_file(&mut files_in_use, &row?);
992                }
993                Ok(())
994            },
995        )
996        .await
997        .context("Failed to SELECT blobname FROM http_cache")?;
998
999    info!(context, "{} files in use.", files_in_use.len());
1000    /* go through directories and delete unused files */
1001    let blobdir = context.get_blobdir();
1002    for p in [&blobdir.join(BLOBS_BACKUP_NAME), blobdir] {
1003        match tokio::fs::read_dir(p).await {
1004            Ok(mut dir_handle) => {
1005                /* avoid deletion of files that are just created to build a message object */
1006                let diff = std::time::Duration::from_secs(60 * 60);
1007                let keep_files_newer_than = SystemTime::now()
1008                    .checked_sub(diff)
1009                    .unwrap_or(SystemTime::UNIX_EPOCH);
1010
1011                while let Ok(Some(entry)) = dir_handle.next_entry().await {
1012                    let name_f = entry.file_name();
1013                    let name_s = name_f.to_string_lossy();
1014
1015                    if p == blobdir
1016                        && (is_file_in_use(&files_in_use, None, &name_s)
1017                            || is_file_in_use(&files_in_use, Some(".waveform"), &name_s)
1018                            || is_file_in_use(&files_in_use, Some("-preview.jpg"), &name_s))
1019                    {
1020                        continue;
1021                    }
1022
1023                    let stats = match tokio::fs::metadata(entry.path()).await {
1024                        Err(err) => {
1025                            warn!(
1026                                context,
1027                                "Cannot get metadata for {}: {:#}.",
1028                                entry.path().display(),
1029                                err
1030                            );
1031                            continue;
1032                        }
1033                        Ok(stats) => stats,
1034                    };
1035
1036                    if stats.is_dir() {
1037                        if let Err(e) = tokio::fs::remove_dir(entry.path()).await {
1038                            // The dir could be created not by a user, but by a desktop
1039                            // environment f.e. So, no warning.
1040                            info!(
1041                                context,
1042                                "Housekeeping: Cannot rmdir {}: {:#}.",
1043                                entry.path().display(),
1044                                e
1045                            );
1046                        }
1047                        continue;
1048                    }
1049
1050                    unreferenced_count += 1;
1051                    let recently_created = stats.created().is_ok_and(|t| t > keep_files_newer_than);
1052                    let recently_modified =
1053                        stats.modified().is_ok_and(|t| t > keep_files_newer_than);
1054                    let recently_accessed =
1055                        stats.accessed().is_ok_and(|t| t > keep_files_newer_than);
1056
1057                    if p == blobdir && (recently_created || recently_modified || recently_accessed)
1058                    {
1059                        info!(
1060                            context,
1061                            "Housekeeping: Keeping new unreferenced file #{}: {:?}.",
1062                            unreferenced_count,
1063                            entry.file_name(),
1064                        );
1065                        continue;
1066                    }
1067
1068                    info!(
1069                        context,
1070                        "Housekeeping: Deleting unreferenced file #{}: {:?}.",
1071                        unreferenced_count,
1072                        entry.file_name()
1073                    );
1074                    let path = entry.path();
1075                    if let Err(err) = delete_file(context, &path).await {
1076                        error!(
1077                            context,
1078                            "Failed to delete unused file {}: {:#}.",
1079                            path.display(),
1080                            err
1081                        );
1082                    }
1083                }
1084            }
1085            Err(err) => {
1086                if !p.ends_with(BLOBS_BACKUP_NAME) {
1087                    warn!(
1088                        context,
1089                        "Housekeeping: Cannot read dir {}: {:#}.",
1090                        p.display(),
1091                        err
1092                    );
1093                }
1094            }
1095        }
1096    }
1097
1098    Ok(())
1099}
1100
1101fn is_file_in_use(files_in_use: &HashSet<String>, namespc_opt: Option<&str>, name: &str) -> bool {
1102    let name_to_check = if let Some(namespc) = namespc_opt {
1103        let Some(name) = name.strip_suffix(namespc) else {
1104            return false;
1105        };
1106        name
1107    } else {
1108        name
1109    };
1110    files_in_use.contains(name_to_check)
1111}
1112
1113fn maybe_add_file(files_in_use: &mut HashSet<String>, file: &str) {
1114    if let Some(file) = file.strip_prefix("$BLOBDIR/") {
1115        files_in_use.insert(file.to_string());
1116    }
1117}
1118
1119async fn maybe_add_from_param(
1120    sql: &Sql,
1121    files_in_use: &mut HashSet<String>,
1122    query: &str,
1123    param_id: Param,
1124) -> Result<()> {
1125    sql.query_map(
1126        query,
1127        (),
1128        |row| row.get::<_, String>(0),
1129        |rows| {
1130            for row in rows {
1131                let param: Params = row?.parse().unwrap_or_default();
1132                if let Some(file) = param.get(param_id) {
1133                    maybe_add_file(files_in_use, file);
1134                }
1135            }
1136            Ok(())
1137        },
1138    )
1139    .await
1140    .context(format!("housekeeping: failed to add_from_param {query}"))?;
1141
1142    Ok(())
1143}
1144
1145/// Removes from the database stale locally deleted messages that also don't
1146/// have a server UID.
1147async fn prune_tombstones(sql: &Sql) -> Result<()> {
1148    // Keep tombstones for the last two days to prevent redownloading locally deleted messages.
1149    let timestamp_max = time().saturating_sub(2 * 24 * 3600);
1150    sql.execute(
1151        "DELETE FROM msgs
1152         WHERE chat_id=?
1153         AND timestamp<=?
1154         AND NOT EXISTS (
1155         SELECT * FROM imap WHERE msgs.rfc724_mid=rfc724_mid AND target!=''
1156         )",
1157        (DC_CHAT_ID_TRASH, timestamp_max),
1158    )
1159    .await?;
1160    Ok(())
1161}
1162
1163#[cfg(test)]
1164mod sql_tests;