conduit/src/database.rs

370 lines
14 KiB
Rust
Raw Normal View History

pub mod account_data;
2020-11-09 11:21:04 +00:00
pub mod admin;
pub mod appservice;
pub mod globals;
pub mod key_backups;
pub mod media;
pub mod pusher;
pub mod rooms;
2020-09-15 14:13:54 +00:00
pub mod sending;
2020-08-25 11:24:38 +00:00
pub mod transaction_ids;
pub mod uiaa;
pub mod users;
use crate::{utils, Error, Result};
use directories::ProjectDirs;
use futures::StreamExt;
use log::{error, info};
use rocket::futures::{self, channel::mpsc};
use ruma::{DeviceId, ServerName, UserId};
use serde::Deserialize;
use std::{
collections::HashMap,
fs::remove_dir_all,
sync::{Arc, RwLock},
};
2020-12-19 15:00:11 +00:00
use tokio::sync::Semaphore;
#[derive(Clone, Debug, Deserialize)]
pub struct Config {
server_name: Box<ServerName>,
database_path: String,
#[serde(default = "default_cache_capacity")]
cache_capacity: u32,
#[serde(default = "default_max_request_size")]
max_request_size: u32,
2020-12-19 15:00:11 +00:00
#[serde(default = "default_max_concurrent_requests")]
max_concurrent_requests: u16,
2021-02-07 12:20:00 +00:00
#[serde(default = "true_fn")]
2021-01-01 12:47:53 +00:00
allow_registration: bool,
#[serde(default = "true_fn")]
allow_encryption: bool,
#[serde(default = "false_fn")]
allow_federation: bool,
2021-02-28 11:41:03 +00:00
#[serde(default = "false_fn")]
pub allow_jaeger: bool,
2021-02-07 16:38:45 +00:00
jwt_secret: Option<String>,
#[serde(default = "Vec::new")]
trusted_servers: Vec<Box<ServerName>>,
#[serde(default = "default_log")]
pub log: String,
2021-01-01 12:47:53 +00:00
}
fn false_fn() -> bool {
false
}
fn true_fn() -> bool {
true
}
fn default_cache_capacity() -> u32 {
1024 * 1024 * 1024
}
fn default_max_request_size() -> u32 {
20 * 1024 * 1024 // Default to 20 MB
}
2020-05-06 13:36:44 +00:00
2020-12-19 15:00:11 +00:00
fn default_max_concurrent_requests() -> u16 {
100
2020-12-19 15:00:11 +00:00
}
fn default_log() -> String {
2021-03-26 10:10:45 +00:00
"info,state_res=warn,rocket=off,_=off,sled=off".to_owned()
}
2020-11-09 11:21:04 +00:00
#[derive(Clone)]
pub struct Database {
pub globals: globals::Globals,
pub users: users::Users,
2020-06-06 16:44:50 +00:00
pub uiaa: uiaa::Uiaa,
pub rooms: rooms::Rooms,
pub account_data: account_data::AccountData,
2020-05-18 15:53:34 +00:00
pub media: media::Media,
2020-06-16 10:11:38 +00:00
pub key_backups: key_backups::KeyBackups,
2020-08-25 11:24:38 +00:00
pub transaction_ids: transaction_ids::TransactionIds,
2020-09-15 14:13:54 +00:00
pub sending: sending::Sending,
2020-11-09 11:21:04 +00:00
pub admin: admin::Admin,
pub appservice: appservice::Appservice,
pub pusher: pusher::PushData,
pub _db: sled::Db,
}
impl Database {
/// Tries to remove the old database but ignores all errors.
2020-06-09 13:13:17 +00:00
pub fn try_remove(server_name: &str) -> Result<()> {
2020-04-11 18:03:22 +00:00
let mut path = ProjectDirs::from("xyz", "koesters", "conduit")
2020-11-15 11:17:21 +00:00
.ok_or_else(|| Error::bad_config("The OS didn't return a valid home directory path."))?
.data_dir()
.to_path_buf();
2020-05-06 13:36:44 +00:00
path.push(server_name);
let _ = remove_dir_all(path);
2020-06-09 13:13:17 +00:00
Ok(())
}
/// Load an existing database or create a new one.
2020-12-06 10:05:51 +00:00
pub async fn load_or_create(config: Config) -> Result<Self> {
2020-10-21 19:43:59 +00:00
let db = sled::Config::default()
.path(&config.database_path)
2021-04-11 08:12:05 +00:00
.cache_capacity(config.cache_capacity as u64)
2021-03-18 12:13:08 +00:00
.use_compression(true)
2020-10-21 19:43:59 +00:00
.open()?;
if config.max_request_size < 1024 {
eprintln!("ERROR: Max request size is less than 1KB. Please increase it.");
}
2020-11-09 11:21:04 +00:00
let (admin_sender, admin_receiver) = mpsc::unbounded();
let db = Self {
users: users::Users {
2020-06-09 13:13:17 +00:00
userid_password: db.open_tree("userid_password")?,
userid_displayname: db.open_tree("userid_displayname")?,
userid_avatarurl: db.open_tree("userid_avatarurl")?,
userdeviceid_token: db.open_tree("userdeviceid_token")?,
userdeviceid_metadata: db.open_tree("userdeviceid_metadata")?,
2021-04-21 08:51:34 +00:00
userid_devicelistversion: db.open_tree("userid_devicelistversion")?,
2020-06-09 13:13:17 +00:00
token_userdeviceid: db.open_tree("token_userdeviceid")?,
onetimekeyid_onetimekeys: db.open_tree("onetimekeyid_onetimekeys")?,
userid_lastonetimekeyupdate: db.open_tree("userid_lastonetimekeyupdate")?,
2021-03-23 11:59:27 +00:00
keychangeid_userid: db.open_tree("keychangeid_userid")?,
2020-06-16 10:11:38 +00:00
keyid_key: db.open_tree("keyid_key")?,
userid_masterkeyid: db.open_tree("userid_masterkeyid")?,
userid_selfsigningkeyid: db.open_tree("userid_selfsigningkeyid")?,
userid_usersigningkeyid: db.open_tree("userid_usersigningkeyid")?,
2020-06-09 13:13:17 +00:00
todeviceid_events: db.open_tree("todeviceid_events")?,
},
2020-06-06 16:44:50 +00:00
uiaa: uiaa::Uiaa {
userdevicesessionid_uiaainfo: db.open_tree("userdevicesessionid_uiaainfo")?,
userdevicesessionid_uiaarequest: db.open_tree("userdevicesessionid_uiaarequest")?,
2020-06-06 16:44:50 +00:00
},
rooms: rooms::Rooms {
edus: rooms::RoomEdus {
readreceiptid_readreceipt: db.open_tree("readreceiptid_readreceipt")?,
roomuserid_privateread: db.open_tree("roomuserid_privateread")?, // "Private" read receipt
2020-08-25 11:24:38 +00:00
roomuserid_lastprivatereadupdate: db
2021-03-23 11:59:27 +00:00
.open_tree("roomuserid_lastprivatereadupdate")?,
typingid_userid: db.open_tree("typingid_userid")?,
roomid_lasttypingupdate: db.open_tree("roomid_lasttypingupdate")?,
2020-07-28 13:58:50 +00:00
presenceid_presence: db.open_tree("presenceid_presence")?,
userid_lastpresenceupdate: db.open_tree("userid_lastpresenceupdate")?,
},
2020-06-09 13:13:17 +00:00
pduid_pdu: db.open_tree("pduid_pdu")?,
eventid_pduid: db.open_tree("eventid_pduid")?,
roomid_pduleaves: db.open_tree("roomid_pduleaves")?,
2020-06-09 13:13:17 +00:00
alias_roomid: db.open_tree("alias_roomid")?,
2021-03-23 11:59:27 +00:00
aliasid_alias: db.open_tree("aliasid_alias")?,
2020-06-09 13:13:17 +00:00
publicroomids: db.open_tree("publicroomids")?,
2020-05-25 21:24:13 +00:00
2020-08-18 10:15:27 +00:00
tokenids: db.open_tree("tokenids")?,
2020-09-14 18:23:19 +00:00
roomserverids: db.open_tree("roomserverids")?,
serverroomids: db.open_tree("serverroomids")?,
2020-06-09 13:13:17 +00:00
userroomid_joined: db.open_tree("userroomid_joined")?,
roomuserid_joined: db.open_tree("roomuserid_joined")?,
2020-08-06 11:21:53 +00:00
roomuseroncejoinedids: db.open_tree("roomuseroncejoinedids")?,
2021-04-11 19:01:27 +00:00
userroomid_invitestate: db.open_tree("userroomid_invitestate")?,
roomuserid_invitecount: db.open_tree("roomuserid_invitecount")?,
2021-04-13 13:00:45 +00:00
userroomid_leftstate: db.open_tree("userroomid_leftstate")?,
roomuserid_leftcount: db.open_tree("roomuserid_leftcount")?,
userroomid_notificationcount: db.open_tree("userroomid_notificationcount")?,
userroomid_highlightcount: db.open_tree("userroomid_highlightcount")?,
2021-03-17 21:30:25 +00:00
statekey_shortstatekey: db.open_tree("statekey_shortstatekey")?,
stateid_shorteventid: db.open_tree("stateid_shorteventid")?,
eventid_shorteventid: db.open_tree("eventid_shorteventid")?,
shorteventid_eventid: db.open_tree("shorteventid_eventid")?,
2021-03-23 11:59:27 +00:00
shorteventid_shortstatehash: db.open_tree("shorteventid_shortstatehash")?,
2021-03-17 21:30:25 +00:00
roomid_shortstatehash: db.open_tree("roomid_shortstatehash")?,
statehash_shortstatehash: db.open_tree("statehash_shortstatehash")?,
2021-03-23 11:59:27 +00:00
eventid_outlierpdu: db.open_tree("eventid_outlierpdu")?,
prevevent_parent: db.open_tree("prevevent_parent")?,
},
account_data: account_data::AccountData {
2020-06-09 13:13:17 +00:00
roomuserdataid_accountdata: db.open_tree("roomuserdataid_accountdata")?,
},
2020-05-18 15:53:34 +00:00
media: media::Media {
2020-06-09 13:13:17 +00:00
mediaid_file: db.open_tree("mediaid_file")?,
2020-05-18 15:53:34 +00:00
},
2020-06-16 10:11:38 +00:00
key_backups: key_backups::KeyBackups {
backupid_algorithm: db.open_tree("backupid_algorithm")?,
backupid_etag: db.open_tree("backupid_etag")?,
2021-03-23 11:59:27 +00:00
backupkeyid_backup: db.open_tree("backupkeyid_backup")?,
2020-06-16 10:11:38 +00:00
},
2020-08-25 11:24:38 +00:00
transaction_ids: transaction_ids::TransactionIds {
userdevicetxnid_response: db.open_tree("userdevicetxnid_response")?,
},
2020-09-15 14:13:54 +00:00
sending: sending::Sending {
servername_educount: db.open_tree("servername_educount")?,
servernamepduids: db.open_tree("servernamepduids")?,
servercurrentevents: db.open_tree("servercurrentevents")?,
maximum_requests: Arc::new(Semaphore::new(config.max_concurrent_requests as usize)),
2020-09-15 14:13:54 +00:00
},
2020-11-09 11:21:04 +00:00
admin: admin::Admin {
sender: admin_sender,
},
appservice: appservice::Appservice {
cached_registrations: Arc::new(RwLock::new(HashMap::new())),
id_appserviceregistrations: db.open_tree("id_appserviceregistrations")?,
},
pusher: pusher::PushData::new(&db)?,
globals: globals::Globals::load(
db.open_tree("global")?,
db.open_tree("server_signingkeys")?,
config,
)?,
_db: db,
2020-11-09 11:21:04 +00:00
};
// MIGRATIONS
if db.globals.database_version()? < 1 {
for roomserverid in db.rooms.roomserverids.iter().keys() {
let roomserverid = roomserverid?;
let mut parts = roomserverid.split(|&b| b == 0xff);
let room_id = parts.next().expect("split always returns one element");
let servername = match parts.next() {
Some(s) => s,
None => {
error!("Migration: Invalid roomserverid in db.");
continue;
}
};
let mut serverroomid = servername.to_vec();
serverroomid.push(0xff);
serverroomid.extend_from_slice(room_id);
db.rooms.serverroomids.insert(serverroomid, &[])?;
}
db.globals.bump_database_version(1)?;
info!("Migration: 0 -> 1 finished");
}
if db.globals.database_version()? < 2 {
// We accidentally inserted hashed versions of "" into the db instead of just ""
for userid_password in db.users.userid_password.iter() {
let (userid, password) = userid_password?;
let password = utils::string_from_bytes(&password);
if password.map_or(false, |password| {
argon2::verify_encoded(&password, b"").unwrap_or(false)
}) {
db.users.userid_password.insert(userid, b"")?;
}
}
db.globals.bump_database_version(2)?;
info!("Migration: 1 -> 2 finished");
}
// This data is probably outdated
db.rooms.edus.presenceid_presence.clear()?;
2020-11-09 11:21:04 +00:00
db.admin.start_handler(db.clone(), admin_receiver);
Ok(db)
}
pub async fn watch(&self, user_id: &UserId, device_id: &DeviceId) {
let userid_bytes = user_id.as_bytes().to_vec();
let mut userid_prefix = userid_bytes.clone();
userid_prefix.push(0xff);
let mut userdeviceid_prefix = userid_prefix.clone();
userdeviceid_prefix.extend_from_slice(device_id.as_bytes());
userdeviceid_prefix.push(0xff);
let mut futures = futures::stream::FuturesUnordered::new();
// Return when *any* user changed his key
// TODO: only send for user they share a room with
futures.push(
self.users
.todeviceid_events
.watch_prefix(&userdeviceid_prefix),
);
futures.push(self.rooms.userroomid_joined.watch_prefix(&userid_prefix));
2021-04-11 19:01:27 +00:00
futures.push(
self.rooms
.userroomid_invitestate
.watch_prefix(&userid_prefix),
);
2021-04-13 13:00:45 +00:00
futures.push(self.rooms.userroomid_leftstate.watch_prefix(&userid_prefix));
// Events for rooms we are in
for room_id in self.rooms.rooms_joined(user_id).filter_map(|r| r.ok()) {
let roomid_bytes = room_id.as_bytes().to_vec();
2020-08-22 20:02:32 +00:00
let mut roomid_prefix = roomid_bytes.clone();
roomid_prefix.push(0xff);
// PDUs
futures.push(self.rooms.pduid_pdu.watch_prefix(&roomid_prefix));
// EDUs
futures.push(
self.rooms
.edus
.roomid_lasttypingupdate
2020-08-22 20:02:32 +00:00
.watch_prefix(&roomid_bytes),
);
futures.push(
self.rooms
.edus
.readreceiptid_readreceipt
.watch_prefix(&roomid_prefix),
);
// Key changes
futures.push(self.users.keychangeid_userid.watch_prefix(&roomid_prefix));
// Room account data
let mut roomuser_prefix = roomid_prefix.clone();
roomuser_prefix.extend_from_slice(&userid_prefix);
futures.push(
self.account_data
.roomuserdataid_accountdata
.watch_prefix(&roomuser_prefix),
);
}
let mut globaluserdata_prefix = vec![0xff];
globaluserdata_prefix.extend_from_slice(&userid_prefix);
futures.push(
self.account_data
.roomuserdataid_accountdata
.watch_prefix(&globaluserdata_prefix),
);
// More key changes (used when user is not joined to any rooms)
futures.push(self.users.keychangeid_userid.watch_prefix(&userid_prefix));
// One time keys
futures.push(
self.users
.userid_lastonetimekeyupdate
.watch_prefix(&userid_bytes),
);
// Wait until one of them finds something
futures.next().await;
}
pub async fn flush(&self) -> Result<()> {
2021-04-11 08:12:05 +00:00
// noop while we don't use sled 1.0
//self._db.flush_async().await?;
Ok(())
}
}