Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 1 | // Copyright 2020, The Android Open Source Project |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | //! Implements the android.security.vpnprofilestore interface. |
| 16 | |
| 17 | use android_security_vpnprofilestore::aidl::android::security::vpnprofilestore::{ |
| 18 | IVpnProfileStore::BnVpnProfileStore, IVpnProfileStore::IVpnProfileStore, |
| 19 | IVpnProfileStore::ERROR_PROFILE_NOT_FOUND, IVpnProfileStore::ERROR_SYSTEM_ERROR, |
| 20 | }; |
Andrew Walbran | de45c8b | 2021-04-13 14:42:38 +0000 | [diff] [blame] | 21 | use android_security_vpnprofilestore::binder::{ |
| 22 | BinderFeatures, ExceptionCode, Result as BinderResult, Status as BinderStatus, Strong, |
| 23 | ThreadState, |
| 24 | }; |
Seth Moore | fbe5cf5 | 2021-06-09 15:59:00 -0700 | [diff] [blame^] | 25 | use anyhow::{Context, Result}; |
Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 26 | use keystore2::{async_task::AsyncTask, legacy_blob::LegacyBlobLoader, utils::watchdog as wd}; |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 27 | use rusqlite::{ |
| 28 | params, Connection, OptionalExtension, Transaction, TransactionBehavior, NO_PARAMS, |
| 29 | }; |
Janis Danisevskis | 0689107 | 2021-02-11 10:28:17 -0800 | [diff] [blame] | 30 | use std::{ |
| 31 | collections::HashSet, |
| 32 | path::{Path, PathBuf}, |
| 33 | }; |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 34 | |
| 35 | struct DB { |
| 36 | conn: Connection, |
| 37 | } |
| 38 | |
| 39 | impl DB { |
| 40 | fn new(db_file: &Path) -> Result<Self> { |
| 41 | let mut db = Self { |
| 42 | conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?, |
| 43 | }; |
Janis Danisevskis | 1be7e18 | 2021-04-12 14:31:12 -0700 | [diff] [blame] | 44 | |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 45 | db.init_tables().context("Trying to initialize vpnstore db.")?; |
| 46 | Ok(db) |
| 47 | } |
| 48 | |
| 49 | fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T> |
| 50 | where |
| 51 | F: Fn(&Transaction) -> Result<T>, |
| 52 | { |
| 53 | loop { |
| 54 | match self |
| 55 | .conn |
| 56 | .transaction_with_behavior(behavior) |
| 57 | .context("In with_transaction.") |
| 58 | .and_then(|tx| f(&tx).map(|result| (result, tx))) |
| 59 | .and_then(|(result, tx)| { |
| 60 | tx.commit().context("In with_transaction: Failed to commit transaction.")?; |
| 61 | Ok(result) |
| 62 | }) { |
| 63 | Ok(result) => break Ok(result), |
| 64 | Err(e) => { |
| 65 | if Self::is_locked_error(&e) { |
| 66 | std::thread::sleep(std::time::Duration::from_micros(500)); |
| 67 | continue; |
| 68 | } else { |
| 69 | return Err(e).context("In with_transaction."); |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | fn is_locked_error(e: &anyhow::Error) -> bool { |
Janis Danisevskis | 13f0915 | 2021-04-19 09:55:15 -0700 | [diff] [blame] | 77 | matches!( |
| 78 | e.root_cause().downcast_ref::<rusqlite::ffi::Error>(), |
| 79 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) |
| 80 | | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. }) |
| 81 | ) |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 82 | } |
| 83 | |
| 84 | fn init_tables(&mut self) -> Result<()> { |
| 85 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 86 | tx.execute( |
| 87 | "CREATE TABLE IF NOT EXISTS profiles ( |
| 88 | owner INTEGER, |
| 89 | alias BLOB, |
| 90 | profile BLOB, |
| 91 | UNIQUE(owner, alias));", |
| 92 | NO_PARAMS, |
| 93 | ) |
| 94 | .context("Failed to initialize \"profiles\" table.")?; |
| 95 | Ok(()) |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> { |
| 100 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 101 | let mut stmt = tx |
| 102 | .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;") |
| 103 | .context("In list: Failed to prepare statement.")?; |
| 104 | |
| 105 | let aliases = stmt |
| 106 | .query_map(params![caller_uid], |row| row.get(0))? |
| 107 | .collect::<rusqlite::Result<Vec<String>>>() |
| 108 | .context("In list: query_map failed."); |
| 109 | aliases |
| 110 | }) |
| 111 | } |
| 112 | |
| 113 | fn put(&mut self, caller_uid: u32, alias: &str, profile: &[u8]) -> Result<()> { |
| 114 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 115 | tx.execute( |
| 116 | "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)", |
| 117 | params![caller_uid, alias, profile,], |
| 118 | ) |
| 119 | .context("In put: Failed to insert or replace.")?; |
| 120 | Ok(()) |
| 121 | }) |
| 122 | } |
| 123 | |
| 124 | fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> { |
| 125 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 126 | tx.query_row( |
| 127 | "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;", |
| 128 | params![caller_uid, alias], |
| 129 | |row| row.get(0), |
| 130 | ) |
| 131 | .optional() |
| 132 | .context("In get: failed loading profile.") |
| 133 | }) |
| 134 | } |
| 135 | |
| 136 | fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> { |
| 137 | let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 138 | tx.execute( |
| 139 | "DELETE FROM profiles WHERE owner = ? AND alias = ?;", |
| 140 | params![caller_uid, alias], |
| 141 | ) |
| 142 | .context("In remove: Failed to delete row.") |
| 143 | })?; |
| 144 | Ok(removed == 1) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | /// This is the main VpnProfileStore error type, it wraps binder exceptions and the |
| 149 | /// VnpStore errors. |
| 150 | #[derive(Debug, thiserror::Error, PartialEq)] |
| 151 | pub enum Error { |
| 152 | /// Wraps a VpnProfileStore error code. |
| 153 | #[error("Error::Error({0:?})")] |
| 154 | Error(i32), |
| 155 | /// Wraps a Binder exception code other than a service specific exception. |
| 156 | #[error("Binder exception code {0:?}, {1:?}")] |
| 157 | Binder(ExceptionCode, i32), |
| 158 | } |
| 159 | |
| 160 | impl Error { |
| 161 | /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)` |
| 162 | pub fn sys() -> Self { |
| 163 | Error::Error(ERROR_SYSTEM_ERROR) |
| 164 | } |
| 165 | |
| 166 | /// Short hand for `Error::Error(ERROR_PROFILE_NOT_FOUND)` |
| 167 | pub fn not_found() -> Self { |
| 168 | Error::Error(ERROR_PROFILE_NOT_FOUND) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// This function should be used by vpnprofilestore service calls to translate error conditions |
| 173 | /// into service specific exceptions. |
| 174 | /// |
Hasini Gunasinghe | e1d1bbd | 2021-04-20 18:13:25 +0000 | [diff] [blame] | 175 | /// All error conditions get logged by this function, except for ERROR_PROFILE_NOT_FOUND error. |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 176 | /// |
| 177 | /// `Error::Error(x)` variants get mapped onto a service specific error code of `x`. |
| 178 | /// |
| 179 | /// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`. |
| 180 | /// |
| 181 | /// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed |
| 182 | /// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it |
| 183 | /// typically returns Ok(value). |
| 184 | fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T> |
| 185 | where |
| 186 | F: FnOnce(U) -> BinderResult<T>, |
| 187 | { |
| 188 | result.map_or_else( |
| 189 | |e| { |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 190 | let root_cause = e.root_cause(); |
Hasini Gunasinghe | e1d1bbd | 2021-04-20 18:13:25 +0000 | [diff] [blame] | 191 | let (rc, log_error) = match root_cause.downcast_ref::<Error>() { |
| 192 | // Make the profile not found errors silent. |
| 193 | Some(Error::Error(ERROR_PROFILE_NOT_FOUND)) => (ERROR_PROFILE_NOT_FOUND, false), |
| 194 | Some(Error::Error(e)) => (*e, true), |
| 195 | Some(Error::Binder(_, _)) | None => (ERROR_SYSTEM_ERROR, true), |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 196 | }; |
Hasini Gunasinghe | e1d1bbd | 2021-04-20 18:13:25 +0000 | [diff] [blame] | 197 | if log_error { |
| 198 | log::error!("{:?}", e); |
| 199 | } |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 200 | Err(BinderStatus::new_service_specific_error(rc, None)) |
| 201 | }, |
| 202 | handle_ok, |
| 203 | ) |
| 204 | } |
| 205 | |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 206 | /// Implements IVpnProfileStore AIDL interface. |
| 207 | pub struct VpnProfileStore { |
| 208 | db_path: PathBuf, |
Janis Danisevskis | 0689107 | 2021-02-11 10:28:17 -0800 | [diff] [blame] | 209 | async_task: AsyncTask, |
| 210 | } |
| 211 | |
| 212 | struct AsyncState { |
| 213 | recently_imported: HashSet<(u32, String)>, |
| 214 | legacy_loader: LegacyBlobLoader, |
| 215 | db_path: PathBuf, |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 216 | } |
| 217 | |
| 218 | impl VpnProfileStore { |
| 219 | /// Creates a new VpnProfileStore instance. |
Janis Danisevskis | 0689107 | 2021-02-11 10:28:17 -0800 | [diff] [blame] | 220 | pub fn new_native_binder(path: &Path) -> Strong<dyn IVpnProfileStore> { |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 221 | let mut db_path = path.to_path_buf(); |
| 222 | db_path.push("vpnprofilestore.sqlite"); |
Janis Danisevskis | 0689107 | 2021-02-11 10:28:17 -0800 | [diff] [blame] | 223 | |
| 224 | let result = Self { db_path, async_task: Default::default() }; |
| 225 | result.init_shelf(path); |
Andrew Walbran | de45c8b | 2021-04-13 14:42:38 +0000 | [diff] [blame] | 226 | BnVpnProfileStore::new_binder(result, BinderFeatures::default()) |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 227 | } |
| 228 | |
| 229 | fn open_db(&self) -> Result<DB> { |
| 230 | DB::new(&self.db_path).context("In open_db: Failed to open db.") |
| 231 | } |
| 232 | |
| 233 | fn get(&self, alias: &str) -> Result<Vec<u8>> { |
| 234 | let mut db = self.open_db().context("In get.")?; |
| 235 | let calling_uid = ThreadState::get_calling_uid(); |
Janis Danisevskis | 0689107 | 2021-02-11 10:28:17 -0800 | [diff] [blame] | 236 | |
| 237 | if let Some(profile) = |
| 238 | db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")? |
| 239 | { |
| 240 | return Ok(profile); |
| 241 | } |
| 242 | if self.get_legacy(calling_uid, alias).context("In get: Trying to migrate legacy blob.")? { |
| 243 | // If we were able to migrate a legacy blob try again. |
| 244 | if let Some(profile) = |
| 245 | db.get(calling_uid, alias).context("In get: Trying to load profile from DB.")? |
| 246 | { |
| 247 | return Ok(profile); |
| 248 | } |
| 249 | } |
| 250 | Err(Error::not_found()).context("In get: No such profile.") |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 251 | } |
| 252 | |
| 253 | fn put(&self, alias: &str, profile: &[u8]) -> Result<()> { |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 254 | let calling_uid = ThreadState::get_calling_uid(); |
Janis Danisevskis | 0689107 | 2021-02-11 10:28:17 -0800 | [diff] [blame] | 255 | // In order to make sure that we don't have stale legacy profiles, make sure they are |
| 256 | // migrated before replacing them. |
| 257 | let _ = self.get_legacy(calling_uid, alias); |
| 258 | let mut db = self.open_db().context("In put.")?; |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 259 | db.put(calling_uid, alias, profile).context("In put: Trying to insert profile into DB.") |
| 260 | } |
| 261 | |
| 262 | fn remove(&self, alias: &str) -> Result<()> { |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 263 | let calling_uid = ThreadState::get_calling_uid(); |
Janis Danisevskis | 0689107 | 2021-02-11 10:28:17 -0800 | [diff] [blame] | 264 | let mut db = self.open_db().context("In remove.")?; |
| 265 | // In order to make sure that we don't have stale legacy profiles, make sure they are |
| 266 | // migrated before removing them. |
| 267 | let _ = self.get_legacy(calling_uid, alias); |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 268 | let removed = db |
| 269 | .remove(calling_uid, alias) |
| 270 | .context("In remove: Trying to remove profile from DB.")?; |
| 271 | if removed { |
| 272 | Ok(()) |
| 273 | } else { |
| 274 | Err(Error::not_found()).context("In remove: No such profile.") |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | fn list(&self, prefix: &str) -> Result<Vec<String>> { |
| 279 | let mut db = self.open_db().context("In list.")?; |
| 280 | let calling_uid = ThreadState::get_calling_uid(); |
Janis Danisevskis | 0689107 | 2021-02-11 10:28:17 -0800 | [diff] [blame] | 281 | let mut result = self.list_legacy(calling_uid).context("In list.")?; |
| 282 | result |
| 283 | .append(&mut db.list(calling_uid).context("In list: Trying to get list of profiles.")?); |
| 284 | result = result.into_iter().filter(|s| s.starts_with(prefix)).collect(); |
| 285 | result.sort_unstable(); |
| 286 | result.dedup(); |
| 287 | Ok(result) |
| 288 | } |
| 289 | |
| 290 | fn init_shelf(&self, path: &Path) { |
| 291 | let mut db_path = path.to_path_buf(); |
| 292 | self.async_task.queue_hi(move |shelf| { |
| 293 | let legacy_loader = LegacyBlobLoader::new(&db_path); |
| 294 | db_path.push("vpnprofilestore.sqlite"); |
| 295 | |
| 296 | shelf.put(AsyncState { legacy_loader, db_path, recently_imported: Default::default() }); |
| 297 | }) |
| 298 | } |
| 299 | |
| 300 | fn do_serialized<F, T: Send + 'static>(&self, f: F) -> Result<T> |
| 301 | where |
| 302 | F: FnOnce(&mut AsyncState) -> Result<T> + Send + 'static, |
| 303 | { |
| 304 | let (sender, receiver) = std::sync::mpsc::channel::<Result<T>>(); |
| 305 | self.async_task.queue_hi(move |shelf| { |
| 306 | let state = shelf.get_downcast_mut::<AsyncState>().expect("Failed to get shelf."); |
| 307 | sender.send(f(state)).expect("Failed to send result."); |
| 308 | }); |
| 309 | receiver.recv().context("In do_serialized: Failed to receive result.")? |
| 310 | } |
| 311 | |
| 312 | fn list_legacy(&self, uid: u32) -> Result<Vec<String>> { |
| 313 | self.do_serialized(move |state| { |
| 314 | state |
| 315 | .legacy_loader |
| 316 | .list_vpn_profiles(uid) |
| 317 | .context("Trying to list legacy vnp profiles.") |
| 318 | }) |
| 319 | .context("In list_legacy.") |
| 320 | } |
| 321 | |
| 322 | fn get_legacy(&self, uid: u32, alias: &str) -> Result<bool> { |
| 323 | let alias = alias.to_string(); |
| 324 | self.do_serialized(move |state| { |
| 325 | if state.recently_imported.contains(&(uid, alias.clone())) { |
| 326 | return Ok(true); |
| 327 | } |
| 328 | let mut db = DB::new(&state.db_path).context("In open_db: Failed to open db.")?; |
| 329 | let migrated = |
| 330 | Self::migrate_one_legacy_profile(uid, &alias, &state.legacy_loader, &mut db) |
| 331 | .context("Trying to migrate legacy vpn profile.")?; |
| 332 | if migrated { |
| 333 | state.recently_imported.insert((uid, alias)); |
| 334 | } |
| 335 | Ok(migrated) |
| 336 | }) |
| 337 | .context("In get_legacy.") |
| 338 | } |
| 339 | |
| 340 | fn migrate_one_legacy_profile( |
| 341 | uid: u32, |
| 342 | alias: &str, |
| 343 | legacy_loader: &LegacyBlobLoader, |
| 344 | db: &mut DB, |
| 345 | ) -> Result<bool> { |
| 346 | let blob = legacy_loader |
| 347 | .read_vpn_profile(uid, alias) |
| 348 | .context("In migrate_one_legacy_profile: Trying to read legacy vpn profile.")?; |
| 349 | if let Some(profile) = blob { |
| 350 | db.put(uid, alias, &profile) |
| 351 | .context("In migrate_one_legacy_profile: Trying to insert profile into DB.")?; |
| 352 | legacy_loader |
| 353 | .remove_vpn_profile(uid, alias) |
| 354 | .context("In migrate_one_legacy_profile: Trying to delete legacy profile.")?; |
| 355 | Ok(true) |
| 356 | } else { |
| 357 | Ok(false) |
| 358 | } |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 359 | } |
| 360 | } |
| 361 | |
| 362 | impl binder::Interface for VpnProfileStore {} |
| 363 | |
| 364 | impl IVpnProfileStore for VpnProfileStore { |
| 365 | fn get(&self, alias: &str) -> BinderResult<Vec<u8>> { |
Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 366 | let _wp = wd::watch_millis("IVpnProfileStore::get", 500); |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 367 | map_or_log_err(self.get(alias), Ok) |
| 368 | } |
| 369 | fn put(&self, alias: &str, profile: &[u8]) -> BinderResult<()> { |
Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 370 | let _wp = wd::watch_millis("IVpnProfileStore::put", 500); |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 371 | map_or_log_err(self.put(alias, profile), Ok) |
| 372 | } |
| 373 | fn remove(&self, alias: &str) -> BinderResult<()> { |
Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 374 | let _wp = wd::watch_millis("IVpnProfileStore::remove", 500); |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 375 | map_or_log_err(self.remove(alias), Ok) |
| 376 | } |
| 377 | fn list(&self, prefix: &str) -> BinderResult<Vec<String>> { |
Hasini Gunasinghe | 5a893e8 | 2021-05-05 14:32:32 +0000 | [diff] [blame] | 378 | let _wp = wd::watch_millis("IVpnProfileStore::list", 500); |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 379 | map_or_log_err(self.list(prefix), Ok) |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | #[cfg(test)] |
| 384 | mod db_test { |
| 385 | use super::*; |
| 386 | use keystore2_test_utils::TempDir; |
Janis Danisevskis | 1be7e18 | 2021-04-12 14:31:12 -0700 | [diff] [blame] | 387 | use std::sync::Arc; |
| 388 | use std::thread; |
| 389 | use std::time::Duration; |
| 390 | use std::time::Instant; |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 391 | |
Janis Danisevskis | 1be7e18 | 2021-04-12 14:31:12 -0700 | [diff] [blame] | 392 | static TEST_ALIAS: &str = &"test_alias"; |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 393 | static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; |
| 394 | static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0]; |
| 395 | static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0]; |
| 396 | static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0]; |
| 397 | |
| 398 | #[test] |
| 399 | fn test_profile_db() { |
| 400 | let test_dir = TempDir::new("profiledb_test_").expect("Failed to create temp dir."); |
| 401 | let mut db = |
| 402 | DB::new(&test_dir.build().push("vpnprofile.sqlite")).expect("Failed to open database."); |
| 403 | |
| 404 | // Insert three profiles for owner 2. |
| 405 | db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1."); |
| 406 | db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2."); |
| 407 | db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3."); |
| 408 | |
| 409 | // Check list returns all inserted aliases. |
| 410 | assert_eq!( |
| 411 | vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),], |
| 412 | db.list(2).expect("Failed to list profiles.") |
| 413 | ); |
| 414 | |
| 415 | // There should be no profiles for owner 1. |
| 416 | assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list profiles.")); |
| 417 | |
| 418 | // Check the content of the three entries. |
| 419 | assert_eq!( |
| 420 | Some(TEST_BLOB1), |
| 421 | db.get(2, "test1").expect("Failed to get profile.").as_deref() |
| 422 | ); |
| 423 | assert_eq!( |
| 424 | Some(TEST_BLOB2), |
| 425 | db.get(2, "test2").expect("Failed to get profile.").as_deref() |
| 426 | ); |
| 427 | assert_eq!( |
| 428 | Some(TEST_BLOB3), |
| 429 | db.get(2, "test3").expect("Failed to get profile.").as_deref() |
| 430 | ); |
| 431 | |
| 432 | // Remove test2 and check and check that it is no longer retrievable. |
| 433 | assert!(db.remove(2, "test2").expect("Failed to remove profile.")); |
| 434 | assert!(db.get(2, "test2").expect("Failed to get profile.").is_none()); |
| 435 | |
| 436 | // test2 should now no longer be in the list. |
| 437 | assert_eq!( |
| 438 | vec!["test1".to_string(), "test3".to_string(),], |
| 439 | db.list(2).expect("Failed to list profiles.") |
| 440 | ); |
| 441 | |
| 442 | // Put on existing alias replaces it. |
| 443 | // Verify test1 is TEST_BLOB1. |
| 444 | assert_eq!( |
| 445 | Some(TEST_BLOB1), |
| 446 | db.get(2, "test1").expect("Failed to get profile.").as_deref() |
| 447 | ); |
| 448 | db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1."); |
| 449 | // Verify test1 is TEST_BLOB4. |
| 450 | assert_eq!( |
| 451 | Some(TEST_BLOB4), |
| 452 | db.get(2, "test1").expect("Failed to get profile.").as_deref() |
| 453 | ); |
| 454 | } |
Janis Danisevskis | 1be7e18 | 2021-04-12 14:31:12 -0700 | [diff] [blame] | 455 | |
| 456 | #[test] |
| 457 | fn concurrent_vpn_profile_test() -> Result<()> { |
| 458 | let temp_dir = Arc::new( |
| 459 | TempDir::new("concurrent_vpn_profile_test_").expect("Failed to create temp dir."), |
| 460 | ); |
| 461 | |
| 462 | let db_path = temp_dir.build().push("vpnprofile.sqlite").to_owned(); |
| 463 | |
| 464 | let test_begin = Instant::now(); |
| 465 | |
| 466 | let mut db = DB::new(&db_path).expect("Failed to open database."); |
| 467 | const PROFILE_COUNT: u32 = 5000u32; |
| 468 | const PROFILE_DB_COUNT: u32 = 5000u32; |
| 469 | |
Seth Moore | 472fcbb | 2021-05-12 10:07:51 -0700 | [diff] [blame] | 470 | let mode: String = db.conn.pragma_query_value(None, "journal_mode", |row| row.get(0))?; |
| 471 | assert_eq!(mode, "wal"); |
| 472 | |
Janis Danisevskis | 1be7e18 | 2021-04-12 14:31:12 -0700 | [diff] [blame] | 473 | let mut actual_profile_count = PROFILE_COUNT; |
| 474 | // First insert PROFILE_COUNT profiles. |
| 475 | for count in 0..PROFILE_COUNT { |
| 476 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) { |
| 477 | actual_profile_count = count; |
| 478 | break; |
| 479 | } |
| 480 | let alias = format!("test_alias_{}", count); |
| 481 | db.put(1, &alias, TEST_BLOB1).expect("Failed to add profile (1)."); |
| 482 | } |
| 483 | |
| 484 | // Insert more keys from a different thread and into a different namespace. |
| 485 | let db_path1 = db_path.clone(); |
| 486 | let handle1 = thread::spawn(move || { |
| 487 | let mut db = DB::new(&db_path1).expect("Failed to open database."); |
| 488 | |
| 489 | for count in 0..actual_profile_count { |
| 490 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 491 | return; |
| 492 | } |
| 493 | let alias = format!("test_alias_{}", count); |
| 494 | db.put(2, &alias, TEST_BLOB2).expect("Failed to add profile (2)."); |
| 495 | } |
| 496 | |
| 497 | // Then delete them again. |
| 498 | for count in 0..actual_profile_count { |
| 499 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 500 | return; |
| 501 | } |
| 502 | let alias = format!("test_alias_{}", count); |
| 503 | db.remove(2, &alias).expect("Remove Failed (2)."); |
| 504 | } |
| 505 | }); |
| 506 | |
| 507 | // And start deleting the first set of profiles. |
| 508 | let db_path2 = db_path.clone(); |
| 509 | let handle2 = thread::spawn(move || { |
| 510 | let mut db = DB::new(&db_path2).expect("Failed to open database."); |
| 511 | |
| 512 | for count in 0..actual_profile_count { |
| 513 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 514 | return; |
| 515 | } |
| 516 | let alias = format!("test_alias_{}", count); |
| 517 | db.remove(1, &alias).expect("Remove Failed (1))."); |
| 518 | } |
| 519 | }); |
| 520 | |
| 521 | // While a lot of inserting and deleting is going on we have to open database connections |
| 522 | // successfully and then insert and delete a specific profile. |
| 523 | let db_path3 = db_path.clone(); |
| 524 | let handle3 = thread::spawn(move || { |
| 525 | for _count in 0..PROFILE_DB_COUNT { |
| 526 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 527 | return; |
| 528 | } |
| 529 | let mut db = DB::new(&db_path3).expect("Failed to open database."); |
| 530 | |
| 531 | db.put(3, &TEST_ALIAS, TEST_BLOB3).expect("Failed to add profile (3)."); |
| 532 | |
| 533 | db.remove(3, &TEST_ALIAS).expect("Remove failed (3)."); |
| 534 | } |
| 535 | }); |
| 536 | |
| 537 | // While thread 3 is inserting and deleting TEST_ALIAS, we try to get the alias. |
| 538 | // This may yield an entry or none, but it must not fail. |
| 539 | let handle4 = thread::spawn(move || { |
| 540 | for _count in 0..PROFILE_DB_COUNT { |
| 541 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 542 | return; |
| 543 | } |
| 544 | let mut db = DB::new(&db_path).expect("Failed to open database."); |
| 545 | |
| 546 | // This may return Some or None but it must not fail. |
| 547 | db.get(3, &TEST_ALIAS).expect("Failed to get profile (4)."); |
| 548 | } |
| 549 | }); |
| 550 | |
| 551 | handle1.join().expect("Thread 1 panicked."); |
| 552 | handle2.join().expect("Thread 2 panicked."); |
| 553 | handle3.join().expect("Thread 3 panicked."); |
| 554 | handle4.join().expect("Thread 4 panicked."); |
| 555 | |
| 556 | Ok(()) |
| 557 | } |
Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame] | 558 | } |