2021-08-26 21:11:13 +00:00
|
|
|
use crate::{database::Config, server_server::FedDest, utils, ConduitResult, Error, Result};
|
2021-01-15 02:32:22 +00:00
|
|
|
use ruma::{
|
2021-06-30 07:52:01 +00:00
|
|
|
api::{
|
|
|
|
client::r0::sync::sync_events,
|
|
|
|
federation::discovery::{ServerSigningKeys, VerifyKey},
|
|
|
|
},
|
2021-07-01 17:55:26 +00:00
|
|
|
DeviceId, EventId, MilliSecondsSinceUnixEpoch, RoomId, ServerName, ServerSigningKeyId, UserId,
|
2021-01-15 02:32:22 +00:00
|
|
|
};
|
2021-06-06 12:28:32 +00:00
|
|
|
use std::{
|
|
|
|
collections::{BTreeMap, HashMap},
|
2021-06-08 13:20:06 +00:00
|
|
|
fs,
|
2021-07-14 07:07:08 +00:00
|
|
|
future::Future,
|
2021-08-26 21:11:13 +00:00
|
|
|
net::IpAddr,
|
2021-06-06 12:28:32 +00:00
|
|
|
path::PathBuf,
|
2021-08-03 09:10:58 +00:00
|
|
|
sync::{Arc, Mutex, RwLock},
|
2021-06-06 12:28:32 +00:00
|
|
|
time::{Duration, Instant},
|
|
|
|
};
|
2021-08-02 08:13:34 +00:00
|
|
|
use tokio::sync::{broadcast, watch::Receiver, Mutex as TokioMutex, Semaphore};
|
2021-08-26 21:11:13 +00:00
|
|
|
use tracing::error;
|
2020-12-08 09:33:44 +00:00
|
|
|
use trust_dns_resolver::TokioAsyncResolver;
|
2020-07-24 03:03:24 +00:00
|
|
|
|
2021-06-08 16:10:00 +00:00
|
|
|
use super::abstraction::Tree;
|
|
|
|
|
|
|
|
pub const COUNTER: &[u8] = b"c";
|
2020-05-03 15:25:31 +00:00
|
|
|
|
2021-08-26 21:11:13 +00:00
|
|
|
type WellKnownMap = HashMap<Box<ServerName>, (FedDest, String)>;
|
|
|
|
type TlsNameMap = HashMap<String, (Vec<IpAddr>, u16)>;
|
2021-05-20 21:46:52 +00:00
|
|
|
type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries
|
2021-07-14 10:31:38 +00:00
|
|
|
type SyncHandle = (
|
|
|
|
Option<String>, // since
|
|
|
|
Receiver<Option<ConduitResult<sync_events::Response>>>, // rx
|
|
|
|
);
|
|
|
|
|
2020-05-03 15:25:31 +00:00
|
|
|
pub struct Globals {
|
2021-03-04 12:35:12 +00:00
|
|
|
pub actual_destination_cache: Arc<RwLock<WellKnownMap>>, // actual_destination, host
|
2021-04-16 01:07:27 +00:00
|
|
|
pub tls_name_override: Arc<RwLock<TlsNameMap>>,
|
2021-06-08 16:10:00 +00:00
|
|
|
pub(super) globals: Arc<dyn Tree>,
|
2020-12-06 10:05:51 +00:00
|
|
|
config: Config,
|
2020-09-15 14:13:54 +00:00
|
|
|
keypair: Arc<ruma::signatures::Ed25519KeyPair>,
|
2020-12-06 10:05:51 +00:00
|
|
|
dns_resolver: TokioAsyncResolver,
|
2021-02-07 16:38:45 +00:00
|
|
|
jwt_decoding_key: Option<jsonwebtoken::DecodingKey<'static>>,
|
2021-06-08 16:10:00 +00:00
|
|
|
pub(super) server_signingkeys: Arc<dyn Tree>,
|
2021-07-18 18:43:39 +00:00
|
|
|
pub bad_event_ratelimiter: Arc<RwLock<HashMap<EventId, RateLimitState>>>,
|
|
|
|
pub bad_signature_ratelimiter: Arc<RwLock<HashMap<Vec<String>, RateLimitState>>>,
|
|
|
|
pub servername_ratelimiter: Arc<RwLock<HashMap<Box<ServerName>, Arc<Semaphore>>>>,
|
|
|
|
pub sync_receivers: RwLock<HashMap<(UserId, Box<DeviceId>), SyncHandle>>,
|
2021-08-03 09:10:58 +00:00
|
|
|
pub roomid_mutex_insert: RwLock<HashMap<RoomId, Arc<Mutex<()>>>>,
|
|
|
|
pub roomid_mutex_state: RwLock<HashMap<RoomId, Arc<TokioMutex<()>>>>,
|
2021-08-02 08:13:34 +00:00
|
|
|
pub roomid_mutex_federation: RwLock<HashMap<RoomId, Arc<TokioMutex<()>>>>, // this lock will be held longer
|
2021-07-14 07:07:08 +00:00
|
|
|
pub rotate: RotationHandler,
|
2020-05-03 15:25:31 +00:00
|
|
|
}
|
|
|
|
|
2021-07-14 07:07:08 +00:00
|
|
|
/// Handles "rotation" of long-polling requests. "Rotation" in this context is similar to "rotation" of log files and the like.
|
|
|
|
///
|
|
|
|
/// This is utilized to have sync workers return early and release read locks on the database.
|
|
|
|
pub struct RotationHandler(broadcast::Sender<()>, broadcast::Receiver<()>);
|
|
|
|
|
|
|
|
impl RotationHandler {
|
|
|
|
pub fn new() -> Self {
|
|
|
|
let (s, r) = broadcast::channel::<()>(1);
|
|
|
|
|
|
|
|
Self(s, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn watch(&self) -> impl Future<Output = ()> {
|
|
|
|
let mut r = self.0.subscribe();
|
|
|
|
|
|
|
|
async move {
|
|
|
|
let _ = r.recv().await;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn fire(&self) {
|
|
|
|
let _ = self.0.send(());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-14 10:31:38 +00:00
|
|
|
impl Default for RotationHandler {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self::new()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-03 15:25:31 +00:00
|
|
|
impl Globals {
|
2021-02-04 01:00:01 +00:00
|
|
|
pub fn load(
|
2021-06-08 16:10:00 +00:00
|
|
|
globals: Arc<dyn Tree>,
|
|
|
|
server_signingkeys: Arc<dyn Tree>,
|
2021-02-04 01:00:01 +00:00
|
|
|
config: Config,
|
|
|
|
) -> Result<Self> {
|
2021-06-08 16:10:00 +00:00
|
|
|
let keypair_bytes = globals.get(b"keypair")?.map_or_else(
|
|
|
|
|| {
|
|
|
|
let keypair = utils::generate_keypair();
|
|
|
|
globals.insert(b"keypair", &keypair)?;
|
|
|
|
Ok::<_, Error>(keypair)
|
|
|
|
},
|
|
|
|
|s| Ok(s.to_vec()),
|
|
|
|
)?;
|
2020-09-15 19:46:10 +00:00
|
|
|
|
2021-06-08 16:10:00 +00:00
|
|
|
let mut parts = keypair_bytes.splitn(2, |&b| b == 0xff);
|
2020-09-15 19:46:10 +00:00
|
|
|
|
|
|
|
let keypair = utils::string_from_bytes(
|
|
|
|
// 1. version
|
|
|
|
parts
|
|
|
|
.next()
|
|
|
|
.expect("splitn always returns at least one element"),
|
|
|
|
)
|
|
|
|
.map_err(|_| Error::bad_database("Invalid version bytes in keypair."))
|
|
|
|
.and_then(|version| {
|
|
|
|
// 2. key
|
|
|
|
parts
|
|
|
|
.next()
|
|
|
|
.ok_or_else(|| Error::bad_database("Invalid keypair format in database."))
|
|
|
|
.map(|key| (version, key))
|
|
|
|
})
|
|
|
|
.and_then(|(version, key)| {
|
2021-05-28 11:44:40 +00:00
|
|
|
ruma::signatures::Ed25519KeyPair::from_der(&key, version)
|
2020-09-15 19:46:10 +00:00
|
|
|
.map_err(|_| Error::bad_database("Private or public keys are invalid."))
|
|
|
|
});
|
|
|
|
|
|
|
|
let keypair = match keypair {
|
|
|
|
Ok(k) => k,
|
|
|
|
Err(e) => {
|
|
|
|
error!("Keypair invalid. Deleting...");
|
2021-06-08 16:10:00 +00:00
|
|
|
globals.remove(b"keypair")?;
|
2020-09-15 19:46:10 +00:00
|
|
|
return Err(e);
|
|
|
|
}
|
|
|
|
};
|
2020-05-03 15:25:31 +00:00
|
|
|
|
2021-04-16 01:07:27 +00:00
|
|
|
let tls_name_override = Arc::new(RwLock::new(TlsNameMap::new()));
|
2020-12-19 15:00:11 +00:00
|
|
|
|
2021-02-07 16:38:45 +00:00
|
|
|
let jwt_decoding_key = config
|
|
|
|
.jwt_secret
|
|
|
|
.as_ref()
|
|
|
|
.map(|secret| jsonwebtoken::DecodingKey::from_secret(secret.as_bytes()).into_static());
|
|
|
|
|
2021-06-08 13:20:06 +00:00
|
|
|
let s = Self {
|
2020-05-03 15:25:31 +00:00
|
|
|
globals,
|
2020-12-06 10:05:51 +00:00
|
|
|
config,
|
2020-09-15 19:46:10 +00:00
|
|
|
keypair: Arc::new(keypair),
|
2021-01-29 16:20:33 +00:00
|
|
|
dns_resolver: TokioAsyncResolver::tokio_from_system_conf().map_err(|_| {
|
|
|
|
Error::bad_config("Failed to set up trust dns resolver with system config.")
|
|
|
|
})?,
|
2021-04-16 01:07:27 +00:00
|
|
|
actual_destination_cache: Arc::new(RwLock::new(WellKnownMap::new())),
|
|
|
|
tls_name_override,
|
2021-05-20 21:46:52 +00:00
|
|
|
server_signingkeys,
|
2021-03-15 08:48:19 +00:00
|
|
|
jwt_decoding_key,
|
2021-07-18 18:43:39 +00:00
|
|
|
bad_event_ratelimiter: Arc::new(RwLock::new(HashMap::new())),
|
|
|
|
bad_signature_ratelimiter: Arc::new(RwLock::new(HashMap::new())),
|
|
|
|
servername_ratelimiter: Arc::new(RwLock::new(HashMap::new())),
|
2021-08-03 09:10:58 +00:00
|
|
|
roomid_mutex_state: RwLock::new(HashMap::new()),
|
|
|
|
roomid_mutex_insert: RwLock::new(HashMap::new()),
|
2021-07-18 18:43:39 +00:00
|
|
|
roomid_mutex_federation: RwLock::new(HashMap::new()),
|
|
|
|
sync_receivers: RwLock::new(HashMap::new()),
|
2021-07-14 07:07:08 +00:00
|
|
|
rotate: RotationHandler::new(),
|
2021-06-08 13:20:06 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
fs::create_dir_all(s.get_media_folder())?;
|
|
|
|
|
|
|
|
Ok(s)
|
2020-05-03 15:25:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns this server's keypair.
|
2020-06-05 16:19:26 +00:00
|
|
|
pub fn keypair(&self) -> &ruma::signatures::Ed25519KeyPair {
|
2020-05-03 15:25:31 +00:00
|
|
|
&self.keypair
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a reqwest client which can be used to send requests.
|
2021-08-26 21:11:13 +00:00
|
|
|
pub fn reqwest_client(&self) -> Result<reqwest::ClientBuilder> {
|
|
|
|
let mut reqwest_client_builder = reqwest::Client::builder()
|
|
|
|
.connect_timeout(Duration::from_secs(30))
|
|
|
|
.timeout(Duration::from_secs(60 * 3))
|
|
|
|
.pool_max_idle_per_host(1);
|
|
|
|
if let Some(proxy) = self.config.proxy.to_proxy()? {
|
|
|
|
reqwest_client_builder = reqwest_client_builder.proxy(proxy);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(reqwest_client_builder)
|
2020-05-03 15:25:31 +00:00
|
|
|
}
|
|
|
|
|
2021-07-29 06:36:01 +00:00
|
|
|
#[tracing::instrument(skip(self))]
|
2020-05-03 15:25:31 +00:00
|
|
|
pub fn next_count(&self) -> Result<u64> {
|
2021-06-17 18:34:14 +00:00
|
|
|
utils::u64_from_bytes(&self.globals.increment(COUNTER)?)
|
|
|
|
.map_err(|_| Error::bad_database("Count has invalid bytes."))
|
2020-05-03 15:25:31 +00:00
|
|
|
}
|
|
|
|
|
2021-07-29 06:36:01 +00:00
|
|
|
#[tracing::instrument(skip(self))]
|
2020-05-03 15:25:31 +00:00
|
|
|
pub fn current_count(&self) -> Result<u64> {
|
2020-06-09 13:13:17 +00:00
|
|
|
self.globals.get(COUNTER)?.map_or(Ok(0_u64), |bytes| {
|
2021-06-17 18:34:14 +00:00
|
|
|
utils::u64_from_bytes(&bytes)
|
|
|
|
.map_err(|_| Error::bad_database("Count has invalid bytes."))
|
2020-06-09 13:13:17 +00:00
|
|
|
})
|
2020-05-03 15:25:31 +00:00
|
|
|
}
|
2020-06-06 17:02:31 +00:00
|
|
|
|
2020-07-17 20:00:39 +00:00
|
|
|
pub fn server_name(&self) -> &ServerName {
|
2020-12-05 20:03:43 +00:00
|
|
|
self.config.server_name.as_ref()
|
2020-06-06 17:02:31 +00:00
|
|
|
}
|
|
|
|
|
2020-07-24 03:03:24 +00:00
|
|
|
pub fn max_request_size(&self) -> u32 {
|
2020-12-05 20:03:43 +00:00
|
|
|
self.config.max_request_size
|
2020-07-24 03:03:24 +00:00
|
|
|
}
|
|
|
|
|
2021-01-01 12:47:53 +00:00
|
|
|
pub fn allow_registration(&self) -> bool {
|
|
|
|
self.config.allow_registration
|
2020-06-06 17:02:31 +00:00
|
|
|
}
|
2020-07-26 18:41:10 +00:00
|
|
|
|
2021-01-01 12:47:53 +00:00
|
|
|
pub fn allow_encryption(&self) -> bool {
|
|
|
|
self.config.allow_encryption
|
2020-07-26 18:41:10 +00:00
|
|
|
}
|
2020-10-06 19:04:51 +00:00
|
|
|
|
2021-01-01 12:47:53 +00:00
|
|
|
pub fn allow_federation(&self) -> bool {
|
|
|
|
self.config.allow_federation
|
2020-10-06 19:04:51 +00:00
|
|
|
}
|
2020-12-06 10:05:51 +00:00
|
|
|
|
2021-03-01 14:17:53 +00:00
|
|
|
pub fn trusted_servers(&self) -> &[Box<ServerName>] {
|
|
|
|
&self.config.trusted_servers
|
|
|
|
}
|
|
|
|
|
2020-12-06 10:05:51 +00:00
|
|
|
pub fn dns_resolver(&self) -> &TokioAsyncResolver {
|
|
|
|
&self.dns_resolver
|
|
|
|
}
|
2021-01-15 02:32:22 +00:00
|
|
|
|
2021-02-07 16:38:45 +00:00
|
|
|
pub fn jwt_decoding_key(&self) -> Option<&jsonwebtoken::DecodingKey<'_>> {
|
|
|
|
self.jwt_decoding_key.as_ref()
|
|
|
|
}
|
2021-01-15 02:32:22 +00:00
|
|
|
|
2021-01-15 02:32:22 +00:00
|
|
|
/// TODO: the key valid until timestamp is only honored in room version > 4
|
|
|
|
/// Remove the outdated keys and insert the new ones.
|
|
|
|
///
|
|
|
|
/// This doesn't actually check that the keys provided are newer than the old set.
|
2021-08-29 11:25:20 +00:00
|
|
|
pub fn add_signing_key(
|
|
|
|
&self,
|
|
|
|
origin: &ServerName,
|
|
|
|
new_keys: ServerSigningKeys,
|
|
|
|
) -> Result<BTreeMap<ServerSigningKeyId, VerifyKey>> {
|
2021-06-08 16:10:00 +00:00
|
|
|
// Not atomic, but this is not critical
|
|
|
|
let signingkeys = self.server_signingkeys.get(origin.as_bytes())?;
|
|
|
|
|
|
|
|
let mut keys = signingkeys
|
|
|
|
.and_then(|keys| serde_json::from_slice(&keys).ok())
|
|
|
|
.unwrap_or_else(|| {
|
|
|
|
// Just insert "now", it doesn't matter
|
|
|
|
ServerSigningKeys::new(origin.to_owned(), MilliSecondsSinceUnixEpoch::now())
|
|
|
|
});
|
|
|
|
|
|
|
|
let ServerSigningKeys {
|
|
|
|
verify_keys,
|
|
|
|
old_verify_keys,
|
|
|
|
..
|
|
|
|
} = new_keys;
|
|
|
|
|
|
|
|
keys.verify_keys.extend(verify_keys.into_iter());
|
|
|
|
keys.old_verify_keys.extend(old_verify_keys.into_iter());
|
|
|
|
|
|
|
|
self.server_signingkeys.insert(
|
|
|
|
origin.as_bytes(),
|
|
|
|
&serde_json::to_vec(&keys).expect("serversigningkeys can be serialized"),
|
|
|
|
)?;
|
2021-03-13 15:30:12 +00:00
|
|
|
|
2021-08-29 11:25:20 +00:00
|
|
|
let mut tree = keys.verify_keys;
|
|
|
|
tree.extend(
|
|
|
|
keys.old_verify_keys
|
|
|
|
.into_iter()
|
|
|
|
.map(|old| (old.0, VerifyKey::new(old.1.key))),
|
|
|
|
);
|
|
|
|
|
|
|
|
Ok(tree)
|
2021-01-15 02:32:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This returns an empty `Ok(BTreeMap<..>)` when there are no keys found for the server.
|
|
|
|
pub fn signing_keys_for(
|
|
|
|
&self,
|
|
|
|
origin: &ServerName,
|
|
|
|
) -> Result<BTreeMap<ServerSigningKeyId, VerifyKey>> {
|
2021-05-20 21:46:52 +00:00
|
|
|
let signingkeys = self
|
|
|
|
.server_signingkeys
|
|
|
|
.get(origin.as_bytes())?
|
|
|
|
.and_then(|bytes| serde_json::from_slice::<ServerSigningKeys>(&bytes).ok())
|
|
|
|
.map(|keys| {
|
|
|
|
let mut tree = keys.verify_keys;
|
|
|
|
tree.extend(
|
|
|
|
keys.old_verify_keys
|
|
|
|
.into_iter()
|
|
|
|
.map(|old| (old.0, VerifyKey::new(old.1.key))),
|
|
|
|
);
|
|
|
|
tree
|
|
|
|
})
|
|
|
|
.unwrap_or_else(BTreeMap::new);
|
|
|
|
|
|
|
|
Ok(signingkeys)
|
2021-01-15 02:32:22 +00:00
|
|
|
}
|
2021-05-17 08:25:27 +00:00
|
|
|
|
|
|
|
pub fn database_version(&self) -> Result<u64> {
|
2021-06-08 16:10:00 +00:00
|
|
|
self.globals.get(b"version")?.map_or(Ok(0), |version| {
|
2021-05-17 08:25:27 +00:00
|
|
|
utils::u64_from_bytes(&version)
|
|
|
|
.map_err(|_| Error::bad_database("Database version id is invalid."))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn bump_database_version(&self, new_version: u64) -> Result<()> {
|
2021-06-08 16:10:00 +00:00
|
|
|
self.globals
|
|
|
|
.insert(b"version", &new_version.to_be_bytes())?;
|
2021-05-17 08:25:27 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
2021-06-04 03:36:12 +00:00
|
|
|
|
|
|
|
pub fn get_media_folder(&self) -> PathBuf {
|
|
|
|
let mut r = PathBuf::new();
|
|
|
|
r.push(self.config.database_path.clone());
|
|
|
|
r.push("media");
|
|
|
|
r
|
|
|
|
}
|
|
|
|
|
2021-06-06 12:28:32 +00:00
|
|
|
pub fn get_media_file(&self, key: &[u8]) -> PathBuf {
|
2021-06-04 03:36:12 +00:00
|
|
|
let mut r = PathBuf::new();
|
|
|
|
r.push(self.config.database_path.clone());
|
|
|
|
r.push("media");
|
|
|
|
r.push(base64::encode_config(key, base64::URL_SAFE_NO_PAD));
|
|
|
|
r
|
|
|
|
}
|
2020-05-03 15:25:31 +00:00
|
|
|
}
|