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 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 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 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 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 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 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 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 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 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 exists = true;
516 Ok(())
517 })?;
518
519 Ok(exists)
520 })
521 .await
522 }
523
524 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 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 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 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 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 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 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 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 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 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 pub async fn get_raw_config_bool(&self, key: &str) -> Result<bool> {
650 let res = self.get_raw_config_int(key).await?;
653 Ok(res.unwrap_or_default() > 0)
654 }
655
656 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 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 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 #[cfg(feature = "internals")]
676 pub fn config_cache(&self) -> &RwLock<HashMap<String, Option<String>>> {
677 &self.config_cache
678 }
679
680 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 return Ok(());
687 };
688
689 let query_only = true;
691 let conn = pool.get(query_only).await?;
692 tokio::task::block_in_place(|| {
693 conn.query_row("PRAGMA table_list", [], |_| Ok(()))?;
697 conn.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()))
698 })?;
699
700 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 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 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 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
752fn 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 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 conn.pragma_update(None, "auto_vacuum", "INCREMENTAL".to_string())?;
789
790 conn.pragma_update(None, "journal_mode", "WAL".to_string())?;
791 conn.pragma_update(None, "synchronous", "NORMAL".to_string())?;
793
794 Ok(conn)
795}
796
797async 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 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
827pub async fn housekeeping(context: &Context) -> Result<()> {
829 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 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_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
929pub 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
939pub 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 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 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 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
1145async fn prune_tombstones(sql: &Sql) -> Result<()> {
1148 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;