use std::env;
use std::fs::{File, OpenOptions};
use std::path::Path;
use std::io;
use std::io::Write;
use std::sync::Mutex;
pub trait KeyLog : Send + Sync {
fn log(&self, label: &str, client_random: &[u8], secret: &[u8]);
}
pub struct NoKeyLog;
impl KeyLog for NoKeyLog {
fn log(&self, _: &str, _: &[u8], _: &[u8]) {}
}
struct KeyLogFileInner {
file: Option<File>,
buf: Vec<u8>,
}
impl KeyLogFileInner {
fn new() -> Self {
let var = env::var("SSLKEYLOGFILE");
let path = match var {
Ok(ref s) => Path::new(s),
Err(env::VarError::NotUnicode(ref s)) => Path::new(s),
Err(env::VarError::NotPresent) => {
return KeyLogFileInner {
file: None,
buf: Vec::new(),
};
}
};
let file = match OpenOptions::new()
.append(true)
.create(true)
.open(path) {
Ok(f) => Some(f),
Err(e) => {
warn!("unable to create key log file '{:?}': {}", path, e);
None
}
};
KeyLogFileInner {
file,
buf: Vec::new(),
}
}
fn try_write(&mut self, label: &str, client_random: &[u8], secret: &[u8]) -> io::Result<()> {
let mut file = match self.file {
None => { return Ok(()); }
Some(ref f) => f,
};
self.buf.truncate(0);
write!(self.buf, "{} ", label)?;
for b in client_random.iter() {
write!(self.buf, "{:02x}", b)?;
}
write!(self.buf, " ")?;
for b in secret.iter() {
write!(self.buf, "{:02x}", b)?;
}
write!(self.buf, "\n")?;
file.write_all(&self.buf)
}
}
pub struct KeyLogFile(Mutex<KeyLogFileInner>);
impl KeyLogFile {
pub fn new() -> Self {
KeyLogFile(Mutex::new(KeyLogFileInner::new()))
}
}
impl KeyLog for KeyLogFile {
fn log(&self, label: &str, client_random: &[u8], secret: &[u8]) {
match self.0.lock()
.unwrap()
.try_write(label, client_random, secret) {
Ok(()) => {},
Err(e) => {
warn!("error writing to key log file: {}", e);
}
}
}
}