git-box 0.2.0

git-box executable implementation
use {Args, to_hex};
use chrono::UTC;
use config::{Configure, GitBoxConfigResult};
use error::GitBoxError;
use filter::{Clean, Filter, GitBoxFilterResult, Smudge, repo};
use git2::Config;
use sodium_sys::crypto::hash::generichash;
use regex::Regex;
use std::collections::HashSet;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::str::FromStr;
use urlparse::urlparse;
use warheadhateus::{AWSAuth, HttpRequestMethod, Region, Service, hashed_data};

const DATE_TIME_FMT: &'static str = "%Y%m%dT%H%M%SZ";

#[derive(Default)]
/// Amazon AWS S3 Binary Off-Repository eXternal Storage
pub struct S3Box {
    /// AWS Base URL
    url: String,
    /// AWS Region
    region: String,
}

impl From<Config> for S3Box {
    fn from(config: Config) -> S3Box {
        S3Box {
            url: match config.get_string("box.s3.url") {
                Ok(u) => u,
                Err(_) => "s3.amazonaws.com".to_owned(),
            },
            region: match config.get_string("box.s3.region") {
                Ok(u) => u,
                Err(_) => "us-east-1".to_owned(),
            },
        }
    }
}

impl From<Args> for S3Box {
    fn from(args: Args) -> S3Box {
        S3Box {
            url: args.arg_url,
            region: args.arg_region,
        }
    }
}

impl Configure for S3Box {
    fn set_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.set_str("box.storagetype", "S3"));
        try!(config.set_str("box.s3.url", &self.url[..]));
        try!(config.set_str("box.s3.region", &self.region[..]));

        if ::enabled() {
            debug!("Set git-box S3 config:");
            debug!("  box.storagetype: {}", "S3");
            debug!("  box.s3.url:      {}", self.url);
            debug!("  box.s3.region:   {}", self.region);
        }

        Ok(0)
    }

    fn remove_config(&self, config: &mut Config) -> GitBoxConfigResult {
        try!(config.remove("box.storagetype"));
        try!(config.remove("box.s3.url"));
        try!(config.remove("box.s3.region"));

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

        Ok(0)
    }
}

fn credentials() -> Result<(String, String), io::Error> {
    let mut ak = String::new();
    let mut sk = String::new();

    if let Some(hd) = env::home_dir() {
        let akre = Regex::new(r"^aws_access_key_id = (.*)").expect("Failed to compile regex!");
        let skre = Regex::new(r"^aws_secret_access_key = (.*)").expect("Failed to compile regex!");
        let creds = try!(File::open(hd.join(".aws").join("credentials")));
        let f = BufReader::new(creds);

        for line in f.lines() {
            if let Ok(l) = line {
                if let Some(caps) = akre.captures(&l) {
                    ak.push_str(caps.at(1).expect("Unable to capture!"));
                }

                if let Some(scaps) = skre.captures(&l) {
                    sk.push_str(scaps.at(1).expect("Unable to capture!"));
                }
            }
        }
    }

    Ok((ak, sk))
}

impl S3Box {
    fn head(&self, url: &str, content_length: usize) -> GitBoxFilterResult {
        // Calculate the payload hash.
        let payload_hash = try!(hashed_data(None));

        // Setup the Authorization header
        let now = UTC::now();
        let nowfmt = now.format(DATE_TIME_FMT).to_string();
        let host = urlparse(url).hostname.unwrap_or("".to_owned());
        let mut auth = try!(AWSAuth::new(&url));
        let region = try!(Region::from_str(&self.region));
        let (ak, sk) = try!(credentials());
        auth.set_service(Service::S3)
            .set_request_type(HttpRequestMethod::HEAD)
            .set_date(now)
            .set_region(region)
            .set_payload_hash(&payload_hash)
            .set_access_key_id(&ak)
            .set_secret_access_key(&sk)
            .add_header("X-Amz-Date", &nowfmt)
            .add_header("x-amz-content-sha256", &payload_hash);

        if !host.is_empty() {
            auth.add_header("Host", &host);
        }

        let auth_header = try!(auth.auth_header());

        // Setup the request headers
        let mut headers = HashSet::new();

        headers.insert(("X-Amz-Date", &nowfmt[..]));
        headers.insert(("x-amz-content-sha256", &payload_hash[..]));
        headers.insert(("Authorization", &auth_header[..]));

        if !host.is_empty() {
            headers.insert(("Host", &host[..]));
        }

        // Request metadata via HEAD request for the file.
        let resp = try!(repo::head(&url, headers, None));

        match resp.get_code() {
            200 => {
                debug!("Headers: {:?}", resp.get_headers());
                let clh = resp.get_header("content-length");

                if clh.len() > 0 {
                    let cl = try!(clh[0].parse::<usize>());
                    debug!("CLH: {}, CL: {}", cl, content_length);
                    if cl == content_length {
                        return Ok(content_length);
                    } else {
                        return Err(GitBoxError::Other("Content-Length differs!"));
                    }
                } else {
                    return Err(GitBoxError::Other("Unable to read Content-Length header!"));
                }
            }
            _ => {
                try!(repo::stderr_resp(resp));
                return Err(GitBoxError::Other("Error getting metadata!"));
            }
        }
    }
}

impl Clean for S3Box {
    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);

        // Setup the full url
        let mut url = self.url.clone();
        url.push('/');
        url.push_str(&chkhash);

        self.head(&url, buf.len()).or_else(|_| {
            // Calculate the payload hash.
            let payload_hash = try!(hashed_data(Some(&buf)));

            // Setup the Authorization header
            let now = UTC::now();
            let nowfmt = now.format(DATE_TIME_FMT).to_string();
            let host = urlparse(&url).hostname.unwrap_or("".to_owned());
            let content_length = buf.len().to_string();
            let mut auth = try!(AWSAuth::new(&url));
            let region = try!(Region::from_str(&self.region));
            let (ak, sk) = try!(credentials());
            auth.set_service(Service::S3)
                .set_request_type(HttpRequestMethod::PUT)
                .set_date(now)
                .set_region(region)
                .set_payload_hash(&payload_hash)
                .set_access_key_id(&ak)
                .set_secret_access_key(&sk)
                .add_header("Content-Length", &content_length)
                .add_header("X-Amz-Date", &nowfmt)
                .add_header("x-amz-content-sha256", &payload_hash);

            if !host.is_empty() {
                auth.add_header("Host", &host);
            }

            let auth_header = try!(auth.auth_header());

            // Setup the request headers
            let mut headers = HashSet::new();

            headers.insert(("Content-Length", &content_length[..]));
            headers.insert(("X-Amz-Date", &nowfmt[..]));
            headers.insert(("x-amz-content-sha256", &payload_hash[..]));
            headers.insert(("Authorization", &auth_header[..]));

            if !host.is_empty() {
                headers.insert(("Host", &host[..]));
            }

            // Put the file.
            let resp = try!(repo::put(&url, buf, headers, Some(3600000), true));

            match resp.get_code() {
                200 => {}
                _ => {
                    try!(repo::stderr_resp(resp));
                    return Err(GitBoxError::Other("Error putting file in S3 bucket!"));
                }
            }

            Ok(size)
        })
    }
}

impl Smudge for S3Box {
    fn smudge(&self, buf: &mut Vec<u8>, hash: &str, size: usize) -> GitBoxFilterResult {
        // Setup the full url
        let mut url = self.url.clone();
        url.push('/');
        url.push_str(&hash);

        self.head(&url, buf.len()).or_else(|_| {
            // Calculate the payload hash.
            let payload_hash = try!(hashed_data(None));

            // Setup the Authorization header
            let now = UTC::now();
            let nowfmt = now.format(DATE_TIME_FMT).to_string();
            let host = urlparse(&url).hostname.unwrap_or("".to_owned());
            let mut auth = try!(AWSAuth::new(&url));
            let region = try!(Region::from_str(&self.region));
            let (ak, sk) = try!(credentials());
            auth.set_service(Service::S3)
                .set_request_type(HttpRequestMethod::GET)
                .set_date(now)
                .set_region(region)
                .set_payload_hash(&payload_hash)
                .set_access_key_id(&ak)
                .set_secret_access_key(&sk)
                .add_header("X-Amz-Date", &nowfmt)
                .add_header("x-amz-content-sha256", &payload_hash);

            if !host.is_empty() {
                auth.add_header("Host", &host);
            }

            let auth_header = try!(auth.auth_header());

            // Setup the request headers
            let mut headers = HashSet::new();

            headers.insert(("X-Amz-Date", &nowfmt[..]));
            headers.insert(("x-amz-content-sha256", &payload_hash[..]));
            headers.insert(("Authorization", &auth_header[..]));

            if !host.is_empty() {
                headers.insert(("Host", &host[..]));
            }

            // Get the file.
            let resp = try!(repo::get(&url, headers, Some(3600000)));

            match resp.get_code() {
                200 => {}
                _ => {
                    try!(repo::stderr_resp(resp));
                    return Err(GitBoxError::Other("Error putting file in S3 bucket!"));
                }
            }

            buf.extend(resp.get_body());
            assert!(size == buf.len());

            Ok(size)
        })
    }
}

impl Filter for S3Box {}