git-box 0.2.0

git-box executable implementation
use {Args, to_hex};
use config::{Configure, GitBoxConfigResult};
use filter::{Clean, Filter, GitBoxFilterResult, Smudge};
use git2::Config;
use openssl::ssl::SslContext;
use openssl::ssl::SslMethod::Sslv23;
use postgres::{Connection, SslMode};
use postgres::types::ToSql;
use sodium_sys::crypto::hash::generichash;

#[derive(Default)]
/// Postgres Binary Off-Repository eXternal Storage
pub struct PostgresBox {
    // Username to connect with.
    user: String,
    // Password to connect with.
    password: Option<String>,
    // Host to connect to.
    host: Option<String>,
    // Port to connect to.
    port: Option<u16>,
    // Database name
    database: Option<String>,
    // Table name
    table: Option<String>,
    // Is SSL enabled?
    ssl: bool,
}

impl PostgresBox {
    fn url(&self) -> String {
        let mut url = String::from("postgresql://");
        url.push_str(&self.user);

        if let Some(ref p) = self.password {
            url.push(':');
            url.push_str(&p);
        }

        url.push('@');

        if let Some(ref h) = self.host {
            url.push_str(&h);

            if let Some(p) = self.port {
                url.push(':');
                url.push_str(&p.to_string());
            }
        }

        url.push('/');

        match self.database {
            Some(ref d) => url.push_str(&d),
            None => url.push_str(&self.user),
        }
        url
    }
}

impl From<Config> for PostgresBox {
    fn from(config: Config) -> PostgresBox {
        PostgresBox {
            user: match config.get_string("box.postgres.user") {
                Ok(u) => u.to_owned(),
                Err(_) => String::new(),
            },
            password: match config.get_string("box.postgres.password") {
                Ok(p) => Some(p.to_owned()),
                Err(_) => None,
            },
            host: match config.get_string("box.postgres.host") {
                Ok(h) => Some(h.to_owned()),
                Err(_) => None,
            },
            port: match config.get_i64("box.postgres.port") {
                Ok(p) => Some(p as u16),
                Err(_) => None,
            },
            database: match config.get_string("box.postgres.database") {
                Ok(d) => Some(d.to_owned()),
                Err(_) => None,
            },
            table: match config.get_string("box.postgres.table") {
                Ok(t) => Some(t.to_owned()),
                Err(_) => None,
            },
            ssl: match config.get_bool("box.posgtres.ssl") {
                Ok(b) => b,
                Err(_) => true,
            },
        }
    }
}

impl From<Args> for PostgresBox {
    fn from(args: Args) -> PostgresBox {
        PostgresBox {
            user: args.arg_user,
            password: args.flag_p,
            host: args.flag_h,
            port: args.flag_port,
            database: args.flag_d,
            table: args.flag_t,
            ssl: args.flag_ssl,
        }
    }
}

impl Configure for PostgresBox {
    fn set_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.set_str("box.storagetype", "POSTGRES"));
        try!(config.set_str("box.postgres.user", &self.user[..]));
        try!(config.set_bool("box.postgres.ssl", self.ssl));

        if let Some(ref p) = self.password {
            try!(config.set_str("box.postgres.password", &p[..]));
        }

        if let Some(ref h) = self.host {
            try!(config.set_str("box.postgres.host", &h[..]));
        }

        if let Some(p) = self.port {
            try!(config.set_i64("box.postgres.port", p as i64));
        }

        if let Some(ref d) = self.database {
            try!(config.set_str("box.postgres.database", &d[..]));
        }

        if let Some(ref t) = self.table {
            try!(config.set_str("box.postgres.table", &t[..]));
        }

        if ::enabled() {
            debug!("Set git-box POSTGRES config:");
            debug!("  box.storagetype:       {}", "POSTGRES");
            debug!("  box.postgres.user:     {}", self.user);
            debug!("  box.postgres.ssl:      {}", self.ssl);

            if let Some(ref p) = self.password {
                debug!("  box.postgres.password: {}", p);
            }

            if let Some(ref h) = self.host {
                debug!("  box.postgres.host:     {}", h);
            }

            if let Some(ref p) = self.port {
                debug!("  box.postgres.port:     {}", p);
            }

            if let Some(ref d) = self.database {
                debug!("  box.postgres.database: {}", d);
            }

            if let Some(ref t) = self.table {
                debug!("  box.postgres.table:    {}", t);
            }
        }

        Ok(0)
    }

    fn remove_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.remove("box.storagetype"));
        try!(config.remove("box.postgres.user"));
        try!(config.remove("box.postgres.password"));
        try!(config.remove("box.postgres.host"));
        try!(config.remove("box.postgres.database"));
        try!(config.remove("box.postgres.table"));
        try!(config.remove("box.postgres.ssl"));

        try!(config.remove("box.postgres.port"));

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

        Ok(0)
    }
}

impl Clean for PostgresBox {
    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 table = match self.table {
            Some(ref t) => t,
            None => &self.user,
        };

        let create_sql = format!("CREATE TABLE IF NOT EXISTS {} (id CHAR(65) PRIMARY KEY, image \
                                  bytea NOT NULL)",
                                 table);
        let insert_sql = format!("INSERT INTO {} (id, image) VALUES ($1,$2) ON CONFLICT DO \
                                  NOTHING",
                                 table);
        let ctx = try!(SslContext::new(Sslv23));
        let mode = if self.ssl {
            SslMode::Require(&ctx)
        } else {
            SslMode::None
        };
        let conn = try!(Connection::connect(&self.url()[..], mode));
        try!(conn.execute(&create_sql[..], &[]));
        let params: &[&ToSql] = &[&hash, buf];
        try!(conn.execute(&insert_sql[..], params));

        Ok(size)
    }
}

impl Smudge for PostgresBox {
    fn smudge(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
        let ctx = try!(SslContext::new(Sslv23));
        let mode = if self.ssl {
            SslMode::Require(&ctx)
        } else {
            SslMode::Prefer(&ctx)
        };
        let table = match self.table {
            Some(ref t) => t,
            None => &self.user,
        };

        let select_sql = format!("SELECT image FROM {} WHERE id = $1", table);
        let conn = try!(Connection::connect(&self.url()[..], mode));
        let params: &[&ToSql] = &[&hash];
        let res = try!(conn.query(&select_sql[..], params));

        for row in res.iter() {
            let b: Vec<u8> = row.get("image");
            buf.extend(&b);
        }

        // 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 PostgresBox {}