mirror of
https://github.com/dani-garcia/vaultwarden.git
synced 2025-09-11 03:05:58 +03:00
Implemented proper logging, with support for file logging, timestamp and syslog (this last one is untested)
This commit is contained in:
@@ -599,15 +599,15 @@ fn post_attachment(uuid: String, data: Data, content_type: &ContentType, headers
|
||||
.with_path(path) {
|
||||
SaveResult::Full(SavedData::File(_, size)) => size as i32,
|
||||
SaveResult::Full(other) => {
|
||||
println!("Attachment is not a file: {:?}", other);
|
||||
error!("Attachment is not a file: {:?}", other);
|
||||
return;
|
||||
},
|
||||
SaveResult::Partial(_, reason) => {
|
||||
println!("Partial result: {:?}", reason);
|
||||
error!("Partial result: {:?}", reason);
|
||||
return;
|
||||
},
|
||||
SaveResult::Error(e) => {
|
||||
println!("Error: {:?}", e);
|
||||
error!("Error: {:?}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -616,10 +616,10 @@ fn post_attachment(uuid: String, data: Data, content_type: &ContentType, headers
|
||||
attachment.key = attachment_key.clone();
|
||||
match attachment.save(&conn) {
|
||||
Ok(()) => (),
|
||||
Err(_) => println!("Error: failed to save attachment")
|
||||
Err(_) => error!("Failed to save attachment")
|
||||
};
|
||||
},
|
||||
_ => println!("Error: invalid multipart name")
|
||||
_ => error!("Invalid multipart name")
|
||||
}
|
||||
}).expect("Error processing multipart data");
|
||||
|
||||
@@ -751,7 +751,7 @@ fn move_cipher_selected(data: JsonUpcase<Value>, headers: Headers, conn: DbConn,
|
||||
}
|
||||
match cipher.save(&conn) {
|
||||
Ok(()) => (),
|
||||
Err(_) => println!("Error: Failed to save cipher")
|
||||
Err(_) => err!("Failed to save cipher")
|
||||
};
|
||||
ws.send_cipher_update(UpdateType::SyncCipherUpdate, &cipher, &cipher.update_users_revision(&conn));
|
||||
}
|
||||
|
@@ -243,7 +243,7 @@ fn _generate_recover_code(user: &mut User, conn: &DbConn) {
|
||||
let totp_recover = BASE32.encode(&crypto::get_random(vec![0u8; 20]));
|
||||
user.totp_recover = Some(totp_recover);
|
||||
if user.save(conn).is_err() {
|
||||
println!("Error: Failed to save the user's two factor recovery code")
|
||||
error!("Failed to save the user's two factor recovery code")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -400,7 +400,7 @@ fn activate_u2f(data: JsonUpcase<EnableU2FData>, headers: Headers, conn: DbConn)
|
||||
})))
|
||||
}
|
||||
Err(e) => {
|
||||
println!("Error: {:#?}", e);
|
||||
error!("{:#?}", e);
|
||||
err!("Error activating u2f")
|
||||
}
|
||||
}
|
||||
@@ -504,11 +504,11 @@ pub fn validate_u2f_login(user_uuid: &str, response: &str, conn: &DbConn) -> Api
|
||||
match response {
|
||||
Ok(new_counter) => {
|
||||
_counter = new_counter;
|
||||
println!("O {:#}", new_counter);
|
||||
info!("O {:#}", new_counter);
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => {
|
||||
println!("E {:#}", e);
|
||||
info!("E {:#}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@@ -43,7 +43,7 @@ fn get_icon (domain: &str) -> Vec<u8> {
|
||||
icon
|
||||
},
|
||||
Err(e) => {
|
||||
println!("Error downloading icon: {:?}", e);
|
||||
error!("Error downloading icon: {:?}", e);
|
||||
get_fallback_icon()
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ fn get_icon_url(domain: &str) -> String {
|
||||
}
|
||||
|
||||
fn download_icon(url: &str) -> Result<Vec<u8>, reqwest::Error> {
|
||||
println!("Downloading icon for {}...", url);
|
||||
info!("Downloading icon for {}...", url);
|
||||
let mut res = reqwest::get(url)?;
|
||||
|
||||
res = res.error_for_status()?;
|
||||
@@ -105,7 +105,7 @@ fn get_fallback_icon() -> Vec<u8> {
|
||||
icon
|
||||
},
|
||||
Err(e) => {
|
||||
println!("Error downloading fallback icon: {:?}", e);
|
||||
error!("Error downloading fallback icon: {:?}", e);
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
@@ -169,7 +169,7 @@ impl Handler for WSHandler {
|
||||
}
|
||||
|
||||
fn on_message(&mut self, msg: Message) -> ws::Result<()> {
|
||||
println!("Server got message '{}'. ", msg);
|
||||
info!("Server got message '{}'. ", msg);
|
||||
|
||||
if let Message::Text(text) = msg.clone() {
|
||||
let json = &text[..text.len() - 1]; // Remove last char
|
||||
|
@@ -51,7 +51,7 @@ pub fn decode_jwt(token: &str) -> Result<JWTClaims, String> {
|
||||
match jwt::decode(token, &PUBLIC_RSA_KEY, &validation) {
|
||||
Ok(decoded) => Ok(decoded.claims),
|
||||
Err(msg) => {
|
||||
println!("Error validating jwt - {:#?}", msg);
|
||||
error!("Error validating jwt - {:#?}", msg);
|
||||
Err(msg.to_string())
|
||||
}
|
||||
}
|
||||
|
@@ -78,11 +78,11 @@ impl Attachment {
|
||||
Ok(_) => break,
|
||||
Err(err) => {
|
||||
if retries < 1 {
|
||||
println!("ERROR: Failed with 10 retries");
|
||||
error!("Failed with 10 retries");
|
||||
return Err(err)
|
||||
} else {
|
||||
retries -= 1;
|
||||
println!("Had to retry! Retries left: {}", retries);
|
||||
info!("Had to retry! Retries left: {}", retries);
|
||||
thread::sleep(time::Duration::from_millis(500));
|
||||
continue
|
||||
}
|
||||
|
@@ -180,7 +180,7 @@ impl User {
|
||||
pub fn update_uuid_revision(uuid: &str, conn: &DbConn) {
|
||||
if let Some(mut user) = User::find_by_uuid(&uuid, conn) {
|
||||
if user.update_revision(conn).is_err(){
|
||||
println!("Warning: Failed to update revision for {}", user.email);
|
||||
warn!("Failed to update revision for {}", user.email);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
80
src/main.rs
80
src/main.rs
@@ -16,6 +16,11 @@ extern crate serde_derive;
|
||||
#[macro_use]
|
||||
extern crate serde_json;
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
extern crate fern;
|
||||
#[cfg(feature = "enable_syslog")]
|
||||
extern crate syslog;
|
||||
#[macro_use]
|
||||
extern crate diesel;
|
||||
#[macro_use]
|
||||
extern crate diesel_migrations;
|
||||
@@ -78,6 +83,10 @@ mod migrations {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if CONFIG.extended_logging {
|
||||
init_logging().ok();
|
||||
}
|
||||
|
||||
check_db();
|
||||
check_rsa_keys();
|
||||
check_web_vault();
|
||||
@@ -86,13 +95,60 @@ fn main() {
|
||||
init_rocket().launch();
|
||||
}
|
||||
|
||||
fn init_logging() -> Result<(), fern::InitError> {
|
||||
let mut logger = fern::Dispatch::new()
|
||||
.format(|out, message, record| {
|
||||
out.finish(format_args!(
|
||||
"{}[{}][{}] {}",
|
||||
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
|
||||
record.target(),
|
||||
record.level(),
|
||||
message
|
||||
))
|
||||
})
|
||||
.level(log::LevelFilter::Debug)
|
||||
.level_for("hyper", log::LevelFilter::Warn)
|
||||
.level_for("ws", log::LevelFilter::Info)
|
||||
.chain(std::io::stdout());
|
||||
|
||||
if let Some(log_file) = CONFIG.log_file.as_ref() {
|
||||
logger = logger.chain(fern::log_file(log_file)?);
|
||||
}
|
||||
|
||||
logger = chain_syslog(logger);
|
||||
logger.apply()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "enable_syslog"))]
|
||||
fn chain_syslog(logger: fern::Dispatch) -> fern::Dispatch { logger }
|
||||
|
||||
#[cfg(feature = "enable_syslog")]
|
||||
fn chain_syslog(logger: fern::Dispatch) -> fern::Dispatch {
|
||||
let syslog_fmt = syslog::Formatter3164 {
|
||||
facility: syslog::Facility::LOG_USER,
|
||||
hostname: None,
|
||||
process: "bitwarden_rs".into(),
|
||||
pid: 0,
|
||||
};
|
||||
|
||||
match syslog::unix(syslog_fmt) {
|
||||
Ok(sl) => logger.chain(sl),
|
||||
Err(e) => {
|
||||
error!("Unable to connect to syslog: {:?}", e);
|
||||
logger
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_db() {
|
||||
let path = Path::new(&CONFIG.database_url);
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
use std::fs;
|
||||
if fs::create_dir_all(parent).is_err() {
|
||||
println!("Error creating database directory");
|
||||
error!("Error creating database directory");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
@@ -107,16 +163,16 @@ fn check_rsa_keys() {
|
||||
// If the RSA keys don't exist, try to create them
|
||||
if !util::file_exists(&CONFIG.private_rsa_key)
|
||||
|| !util::file_exists(&CONFIG.public_rsa_key) {
|
||||
println!("JWT keys don't exist, checking if OpenSSL is available...");
|
||||
info!("JWT keys don't exist, checking if OpenSSL is available...");
|
||||
|
||||
Command::new("openssl")
|
||||
.arg("version")
|
||||
.output().unwrap_or_else(|_| {
|
||||
println!("Can't create keys because OpenSSL is not available, make sure it's installed and available on the PATH");
|
||||
info!("Can't create keys because OpenSSL is not available, make sure it's installed and available on the PATH");
|
||||
exit(1);
|
||||
});
|
||||
|
||||
println!("OpenSSL detected, creating keys...");
|
||||
info!("OpenSSL detected, creating keys...");
|
||||
|
||||
let mut success = Command::new("openssl").arg("genrsa")
|
||||
.arg("-out").arg(&CONFIG.private_rsa_key_pem)
|
||||
@@ -140,9 +196,9 @@ fn check_rsa_keys() {
|
||||
.status.success();
|
||||
|
||||
if success {
|
||||
println!("Keys created correctly.");
|
||||
info!("Keys created correctly.");
|
||||
} else {
|
||||
println!("Error creating keys, exiting...");
|
||||
error!("Error creating keys, exiting...");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
@@ -156,7 +212,7 @@ fn check_web_vault() {
|
||||
let index_path = Path::new(&CONFIG.web_vault_folder).join("index.html");
|
||||
|
||||
if !index_path.exists() {
|
||||
println!("Web vault is not found. Please follow the steps in the README to install it");
|
||||
error!("Web vault is not found. Please follow the steps in the README to install it");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
@@ -187,7 +243,7 @@ impl MailConfig {
|
||||
};
|
||||
|
||||
let smtp_from = get_env("SMTP_FROM").unwrap_or_else(|| {
|
||||
println!("Please specify SMTP_FROM to enable SMTP support.");
|
||||
error!("Please specify SMTP_FROM to enable SMTP support.");
|
||||
exit(1);
|
||||
});
|
||||
|
||||
@@ -203,7 +259,7 @@ impl MailConfig {
|
||||
let smtp_username = get_env("SMTP_USERNAME");
|
||||
let smtp_password = get_env("SMTP_PASSWORD").or_else(|| {
|
||||
if smtp_username.as_ref().is_some() {
|
||||
println!("SMTP_PASSWORD is mandatory when specifying SMTP_USERNAME.");
|
||||
error!("SMTP_PASSWORD is mandatory when specifying SMTP_USERNAME.");
|
||||
exit(1);
|
||||
} else {
|
||||
None
|
||||
@@ -237,6 +293,9 @@ pub struct Config {
|
||||
websocket_enabled: bool,
|
||||
websocket_url: String,
|
||||
|
||||
extended_logging: bool,
|
||||
log_file: Option<String>,
|
||||
|
||||
local_icon_extractor: bool,
|
||||
signups_allowed: bool,
|
||||
invitations_allowed: bool,
|
||||
@@ -282,6 +341,9 @@ impl Config {
|
||||
|
||||
websocket_enabled: get_env_or("WEBSOCKET_ENABLED", false),
|
||||
websocket_url: format!("{}:{}", get_env_or("WEBSOCKET_ADDRESS", "0.0.0.0".to_string()), get_env_or("WEBSOCKET_PORT", 3012)),
|
||||
|
||||
extended_logging: get_env_or("EXTENDED_LOGGING", true),
|
||||
log_file: get_env("LOG_FILE"),
|
||||
|
||||
local_icon_extractor: get_env_or("LOCAL_ICON_EXTRACTOR", false),
|
||||
signups_allowed: get_env_or("SIGNUPS_ALLOWED", true),
|
||||
|
@@ -4,7 +4,7 @@
|
||||
#[macro_export]
|
||||
macro_rules! err {
|
||||
($err:expr, $msg:expr) => {{
|
||||
println!("ERROR: {}", $msg);
|
||||
error!("{}", $msg);
|
||||
err_json!(json!({
|
||||
"error": $err,
|
||||
"error_description": $err,
|
||||
@@ -30,7 +30,7 @@ macro_rules! err_json {
|
||||
#[macro_export]
|
||||
macro_rules! err_handler {
|
||||
($expr:expr) => {{
|
||||
println!("ERROR: {}", $expr);
|
||||
error!("{}", $expr);
|
||||
return $crate::rocket::Outcome::Failure(($crate::rocket::http::Status::Unauthorized, $expr));
|
||||
}}
|
||||
}
|
||||
|
Reference in New Issue
Block a user