Save key to a file

This commit is contained in:
arkpar
2016-02-15 18:36:34 +01:00
parent 30968925ee
commit 0e1e80477a
3 changed files with 67 additions and 2 deletions

View File

@@ -21,6 +21,9 @@ use std::str::{FromStr};
use std::sync::*;
use std::ops::*;
use std::cmp::min;
use std::path::{Path, PathBuf};
use std::io::{Read, Write};
use std::fs;
use mio::*;
use mio::tcp::*;
use target_info::Target;
@@ -340,7 +343,19 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
let addr = config.listen_address;
// Setup the server socket
let tcp_listener = TcpListener::bind(&addr).unwrap();
let keys = if let Some(ref secret) = config.use_secret { KeyPair::from_secret(secret.clone()).unwrap() } else { KeyPair::create().unwrap() };
let keys = if let Some(ref secret) = config.use_secret {
KeyPair::from_secret(secret.clone()).unwrap()
} else {
config.config_path.clone().and_then(|ref p| load_key(&Path::new(&p)))
.map_or_else(|| {
let key = KeyPair::create().unwrap();
if let Some(path) = config.config_path.clone() {
save_key(&Path::new(&path), &key.secret());
}
key
},
|s| KeyPair::from_secret(s).expect("Error creating node secret key"))
};
let endpoint = NodeEndpoint { address: addr.clone(), udp_port: addr.port() };
let discovery = Discovery::new(&keys, endpoint, DISCOVERY);
let path = config.config_path.clone();
@@ -914,3 +929,49 @@ impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Messa
}
}
}
fn save_key(path: &Path, key: &Secret) {
let mut path_buf = PathBuf::from(path);
if let Err(e) = fs::create_dir_all(path_buf.as_path()) {
warn!("Error creating key directory: {:?}", e);
return;
};
path_buf.push("key");
let mut file = match fs::File::create(path_buf.as_path()) {
Ok(file) => file,
Err(e) => {
warn!("Error creating key file: {:?}", e);
return;
}
};
if let Err(e) = file.write(&key.hex().into_bytes()) {
warn!("Error writing key file: {:?}", e);
}
}
fn load_key(path: &Path) -> Option<Secret> {
let mut path_buf = PathBuf::from(path);
path_buf.push("key");
let mut file = match fs::File::open(path_buf.as_path()) {
Ok(file) => file,
Err(e) => {
debug!("Error opening key file: {:?}", e);
return None;
}
};
let mut buf = String::new();
match file.read_to_string(&mut buf) {
Ok(_) => {},
Err(e) => {
warn!("Error reading key file: {:?}", e);
return None;
}
}
match Secret::from_str(&buf) {
Ok(key) => Some(key),
Err(e) => {
warn!("Error parsing key file: {:?}", e);
None
}
}
}

View File

@@ -273,7 +273,7 @@ impl NodeTable {
let mut file = match fs::File::open(path_buf.as_path()) {
Ok(file) => file,
Err(e) => {
warn!("Error opening node table file: {:?}", e);
debug!("Error opening node table file: {:?}", e);
return nodes;
}
};