1use 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
28pub trait ToSql: rusqlite::ToSql + Send + Sync {}
31
32impl<T: rusqlite::ToSql + Send + Sync> ToSql for T {}
33
34#[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#[derive(Debug)]
53pub struct Sql {
54 pub(crate) dbfile: PathBuf,
56
57 pool: RwLock<Option<Pool>>,
59
60 is_encrypted: RwLock<Option<bool>>,
63
64 pub(crate) config_cache: RwLock<HashMap<String, Option<String>>>,
66}
67
68impl Sql {
69 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 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 let _lock = self.pool.write().await;
93
94 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 pub async fn is_open(&self) -> bool {
110 self.pool.read().await.is_some()
111 }
112
113 pub(crate) async fn is_encrypted(&self) -> Option<bool> {
117 *self.is_encrypted.read().await
118 }
119
120 pub(crate) async fn close(&self) {
122 let _ = self.pool.write().await.take();
123 }
125
126 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 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 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 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 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 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 }
208
209 Ok(())
210 }
211
212 pub async fn run_migrations(&self, context: &Context) -> Result<()> {
214 let (_update_icons, disable_server_delete, recode_avatar) = migrations::run(context, self)
220 .await
221 .context("failed to run migrations")?;
222
223 if disable_server_delete {
227 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 exists = true;
479 Ok(())
480 })?;
481
482 Ok(exists)
483 })
484 .await
485 }
486
487 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 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 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 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 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 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 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 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 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 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 pub async fn get_raw_config_bool(&self, key: &str) -> Result<bool> {
613 let res = self.get_raw_config_int(key).await?;
616 Ok(res.unwrap_or_default() > 0)
617 }
618
619 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 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 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 #[cfg(feature = "internals")]
639 pub fn config_cache(&self) -> &RwLock<HashMap<String, Option<String>>> {
640 &self.config_cache
641 }
642
643 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 return Ok(());
650 };
651
652 let query_only = true;
654 let conn = pool.get(query_only).await?;
655 tokio::task::block_in_place(|| {
656 conn.query_row("PRAGMA table_list", [], |_| Ok(()))?;
660 conn.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()))
661 })?;
662
663 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 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 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 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
715fn 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 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 conn.pragma_update(None, "auto_vacuum", "INCREMENTAL".to_string())?;
752
753 conn.pragma_update(None, "journal_mode", "WAL".to_string())?;
754 conn.pragma_update(None, "synchronous", "NORMAL".to_string())?;
756
757 Ok(conn)
758}
759
760async 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 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
790pub async fn housekeeping(context: &Context) -> Result<()> {
792 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 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_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
892pub 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
902pub 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 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 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 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
1108async fn prune_tombstones(sql: &Sql) -> Result<()> {
1111 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;