git-box 0.2.0

git-box executable implementation
use {Args, to_hex};
use config::{Configure, GitBoxConfigResult};
use error::GitBoxError;
use filter::{Clean, Filter, GitBoxFilterResult, Smudge};
use git2::Config;
use sodium_sys::crypto::hash::generichash;
use std::io::{BufWriter, Read, Write};
use std::net::TcpStream;
use std::path::PathBuf;
use ssh2::Session;

#[derive(Default)]
/// ssh Binary Off-Repository eXternal Storage
pub struct Ssh2Box {
    // host
    host: String,
    // username
    user: String,
    // Path to the storage location.
    path: String,
}

impl Ssh2Box {
    /// Create a new Ssh2Box struct.
    pub fn new(host: String, user: String, path: String) -> Ssh2Box {
        Ssh2Box {
            host: host,
            user: user,
            path: path,
        }
    }
}

impl From<Config> for Ssh2Box {
    fn from(config: Config) -> Ssh2Box {
        Ssh2Box {
            host: match config.get_string("box.ssh.host") {
                Ok(u) => u.to_owned(),
                Err(_) => String::new(),
            },
            user: match config.get_string("box.ssh.user") {
                Ok(u) => u.to_owned(),
                Err(_) => String::new(),
            },
            path: match config.get_string("box.ssh.path") {
                Ok(u) => u.to_owned(),
                Err(_) => String::new(),
            },
        }
    }
}

impl From<Args> for Ssh2Box {
    fn from(args: Args) -> Ssh2Box {
        Ssh2Box {
            host: args.arg_host,
            user: args.arg_user,
            path: args.arg_path,
        }
    }
}

impl Configure for Ssh2Box {
    fn set_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.set_str("box.storagetype", "SSH2"));
        try!(config.set_str("box.ssh.user", &self.user[..]));
        try!(config.set_str("box.ssh.host", &self.host[..]));
        try!(config.set_str("box.ssh.path", &self.path[..]));

        if ::enabled() {
            debug!("Set git-box SSH2 config:");
            debug!("  box.storagetype: {}", "SSH2");
            debug!("  box.ssh.user:    {}", self.user);
            debug!("  box.ssh.host:    {}", self.host);
            debug!("  box.ssh.path:    {}", self.path);
        }

        Ok(0)
    }

    fn remove_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.remove("box.storagetype"));
        try!(config.remove("box.ssh.user"));
        try!(config.remove("box.ssh.host"));
        try!(config.remove("box.ssh.path"));

        if ::enabled() {
            debug!("Unset git-box SSH2 config");
        }

        Ok(0)
    }
}

impl Clean for Ssh2Box {
    fn clean(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
        // Check the buffer matches given hash and length.
        let chkhash = to_hex(try!(generichash::hash(&buf[..], None, None)));
        assert!(chkhash == hash);
        assert!(buf.len() == size);

        let hostport = format!("{}:{}", &self.host, 22);
        let tcp = try!(TcpStream::connect(&hostport[..]));
        let mut sess = try!(Session::new()
                                .ok_or(GitBoxError::Other("Unable to create ssh2 Session")));
        try!(sess.handshake(&tcp));
        try!(sess.userauth_agent(&self.user[..]));

        let mut path = PathBuf::from(&self.path[..]);
        path.push(hash);

        let sftp = try!(sess.sftp());
        let file = try!(sftp.create(path.as_path()));

        let mut bufw = BufWriter::new(file);
        try!(bufw.write_all(&buf[..]));
        try!(bufw.flush());
        Ok(size)
    }
}

impl Smudge for Ssh2Box {
    fn smudge(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
        let hostport = format!("{}:{}", &self.host, 22);
        let tcp = try!(TcpStream::connect(&hostport[..]));
        let mut sess = try!(Session::new()
                                .ok_or(GitBoxError::Other("Unable to create ssh2 Session")));
        try!(sess.handshake(&tcp));
        try!(sess.userauth_agent(&self.user[..]));

        let mut path = PathBuf::from(&self.path[..]);
        path.push(hash);

        let sftp = try!(sess.sftp());
        let mut remote_file = try!(sftp.open(path.as_path()));

        let actual_size = try!(remote_file.read_to_end(buf));
        assert!(size == actual_size);

        // Check the buffer matches given hash and length.
        let chkhash = to_hex(try!(generichash::hash(&buf[..], None, None)));
        assert!(chkhash == hash);
        assert!(buf.len() == size);

        Ok(size)
    }
}

impl Filter for Ssh2Box {}