pub mod bitcoind;
pub mod matrix;
pub mod netmaker;
pub mod deploy;
use bitcoin::util::bip32::ExtendedPrivKey;
use bitcoin::Network;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::net::TcpStream;
use std::path::Path;
use redgold_schema::util::mnemonic_words::MnemonicWords;
use ssh2::{Channel, Session};
use redgold_schema::ErrorInfoContext;
use redgold_schema::servers::Server;
use redgold_schema::structs::ErrorInfo;
pub struct SSH {
pub host: String,
pub user: Option<String>,
pub private_key_path: Option<String>,
pub session: Option<Session>
}
pub struct SSHResult {
pub stdout: String,
pub stderr: String,
pub exit_code: i32
}
impl SSH {
pub fn allow_tcp(&mut self, port: u16) -> SSHResult {
self.exec(format!("sudo ufw allow proto tcp from any to any port {:?}", port), true)
}
fn session(&mut self) -> Session {
if let Some(s) = &self.session {
return s.clone();
}
let tcp = TcpStream::connect(self.host.clone()).unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp);
sess.handshake().unwrap();
let home_dir = dirs::home_dir().expect("Cannot find home directory");
let buf = home_dir.join(".ssh");
let key_path = buf.join("id_rsa");
sess.userauth_pubkey_file(
&*self.user.clone().unwrap_or("root".to_string()),
None,
Path::new(&self.private_key_path.as_ref().unwrap_or(&key_path.to_str().expect("Cannot find key path").to_string())),
None,
)
.unwrap();
self.session = Some(sess.clone());
return sess;
}
pub fn verify(&mut self) -> Result<(), ErrorInfo> {
self.run("echo test").contains("test")
.then(|| Ok(()))
.unwrap_or(Err(ErrorInfo::error_info("Cannot verify ssh connection")))
}
pub fn run(&mut self, cmd: &str) -> String {
let sess = self.session();
let mut channel = sess.channel_session().unwrap();
channel.exec(cmd).unwrap();
let mut s = String::new();
channel.read_to_string(&mut s).unwrap();
println!("Stdout from SSH: {}", s);
channel.wait_close().expect("channel closed");
let mut stderr = String::new();
channel
.stderr()
.read_to_string(&mut stderr)
.expect("read failure on stderr");
println!("Stderr from SSH: {}", stderr);
println!("Exit code from SSH: {}", channel.exit_status().unwrap());
return s;
}
pub fn exec<S: Into<String>>(&mut self, cmd: S, print: bool) -> SSHResult {
let sess = self.session();
let mut channel = sess.channel_session().unwrap();
let string = cmd.into();
if print {
println!("Running command: {}", string.clone());
}
channel.exec(&*string).unwrap();
let mut stdout = String::new();
channel.read_to_string(&mut stdout).unwrap();
channel.wait_close().expect("channel closed");
let mut stderr = String::new();
channel
.stderr()
.read_to_string(&mut stderr)
.expect("read failure on stderr");
let exit = channel.exit_status().unwrap();
if print {
println!("Stdout from SSH: {}", stdout);
println!("Stderr from SSH: {}", stderr);
println!("Exit code from SSH: {}", exit);
}
return SSHResult{
stdout,
stderr,
exit_code: exit
};
}
pub fn read_channel(channel: &mut Channel) -> Result<String, ErrorInfo> {
let mut result = String::new();
loop {
let available = channel.read_window().available;
let mut zero_vec = vec![1u8; available as usize];
let buffer = &mut *zero_vec;
let bytes_read = channel.read(&mut buffer[..]).expect("works");
let s = String::from_utf8_lossy(&buffer[..bytes_read]);
let x = &s;
let partial_read = x.clone().to_string();
result.push_str(x);
println!("Finished partial: {partial_read}");
if channel.eof() { println!("Buffer is empty, SSH channel read terminated");
println!("Finished read: {result}");
break;
}
}
Ok(result)
}
pub async fn read_channel_partial(channel: &mut Channel, partial: fn(String) -> Result<(), ErrorInfo>) -> Result<String, ErrorInfo> {
let mut result = String::new();
loop {
let available = channel.read_window().available;
if available > 0 {
let mut zero_vec = vec![1u8; available as usize];
let buffer = &mut *zero_vec;
let bytes_read = channel.read(&mut buffer[..]).expect("works");
let s = String::from_utf8_lossy(&buffer[..bytes_read]);
let x = &s;
let partial_read = x.clone().to_string();
result.push_str(x);
partial(partial_read)?;
} else {
let mut stderr = channel.stderr();
let mut buffer = [0u8; 1024];
let bytes_read = stderr.read(&mut buffer[..]).expect("works");
let s = String::from_utf8_lossy(&buffer[..bytes_read]);
let x = &s;
let partial_read = x.clone().to_string();
result.push_str(x);
partial(partial_read)?;
}
if channel.eof() {
break;
}
}
Ok(result)
}
pub fn streaming_exec_channel<S: Into<String>>(&mut self, cmd: S, print: bool) -> Channel {
let sess = self.session();
let mut channel = sess.channel_session().unwrap();
let string = cmd.into();
if print {
println!("Running command: {}", string.clone());
}
channel.exec(&*string).unwrap();
channel
}
pub async fn stream_partial<S: Into<String>>(&mut self, cmd: S, print: bool, partial: fn(String)
-> Result<(), ErrorInfo>) -> Result<String, ErrorInfo> {
let sess = self.session();
let mut channel = sess.channel_session().unwrap();
let string = cmd.into();
let cmd_format: String = format!("Running command: {}", string.clone());
if print {
println!("{}", cmd_format.clone());
}
channel.exec(&*string).unwrap();
partial(cmd_format.clone())?;
let mut result = String::new();
result.push_str(&*cmd_format);
let exact_result = SSH::read_channel_partial(&mut channel, partial).await?;
result.push_str(&*exact_result);
Ok(result)
}
pub fn copy<S: Into<String>>(&mut self, contents: S, remote_path: String) {
println!("Copying to: {}", remote_path);
let contents = contents.into();
let path = "tmpfile";
fs::remove_file("tmpfile").ok();
let mut file = File::create(path).expect("create failed");
file.write_all(contents.as_bytes()).expect("write temp file");
self.scp("./tmpfile", &*remote_path);
fs::remove_file("tmpfile").unwrap();
}
pub fn scp(&mut self, file: &str, remote_path: &str) {
use std::io::prelude::*;
let sess = self.session();
let path1 = Path::new(file);
let path2 = Path::new(remote_path);
let x = fs::metadata(path1).unwrap().len();
let mut remote_file = sess.scp_send(path2, 0o644, x, None).unwrap();
let vec = fs::read(path1).unwrap();
for iter in vec.chunks(1024) {
remote_file.write(iter).unwrap();
}
remote_file.send_eof().unwrap();
remote_file.wait_eof().unwrap();
remote_file.close().unwrap();
remote_file.wait_close().unwrap();
}
pub fn new_ssh<S: Into<String>>(host: S, key_path: Option<S>) -> SSH {
let x = key_path
.map(|x| x.into());
SSH {
host: format!("{}:22", host.into()),
user: None,
private_key_path: x,
session: None
}
}
pub fn new_ssh2<S: Into<String>>(host: S, key_path: Option<S>, user: Option<S>) -> SSH {
let x = key_path
.map(|x| x.into());
let user = user
.map(|x| x.into());
SSH {
host: format!("{}:22", host.into()),
user,
private_key_path: x,
session: None
}
}
pub fn from_server(server: &Server) -> SSH {
SSH{
host: format!("{}:22", server.host.clone()),
user: server.username.clone(),
private_key_path: server.key_path.clone(),
session: None,
}
}
pub fn docker_logs(&mut self) {
self.exec("docker logs --tail 1000 redgold-predev", true);
}
}
#[test]
fn debug_ssh() {
}