#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
extern crate colored;
extern crate url;
use http::StatusCode;
use std::convert::From;
use std::fs::{metadata, write, File};
use std::io::prelude::*;
use std::path::Path;
use std::str::FromStr;
use crate::aws::AWS4Client;
use crate::error::Error;
use quick_xml::events::Event;
use quick_xml::Reader;
use regex::Regex;
use reqwest::Response;
use serde_json;
use url::Url;
mod aws;
mod error;
static RESPONSE_CONTENT_FORMAT: &'static str =
r#""Contents":\["([^"]+?)","([^"]+?)","\\"([^"]+?)\\"",([^"]+?),"([^"]+?)"(.*?)\]"#;
static RESPONSE_MARKER_FORMAT: &'static str = r#""NextMarker":"([^"]+?)","#;
#[derive(Debug, Clone, Deserialize)]
pub struct CredentialConfig {
pub host: String,
pub user: Option<String>,
pub access_key: String,
pub secret_key: String,
pub region: Option<String>,
pub s3_type: Option<String>,
pub secure: Option<bool>,
}
pub enum AuthType {
AWS4,
AWS2,
}
#[derive(Clone)]
pub enum Format {
JSON,
XML,
}
pub enum UrlStyle {
PATH,
HOST,
}
pub(crate) trait S3Client {
fn request(
&self,
method: &str,
host: &str,
uri: &str,
query_strings: &mut Vec<(&str, &str)>,
headers: &mut Vec<(&str, &str)>,
payload: &Vec<u8>,
) -> Result<(StatusCode, Vec<u8>, reqwest::header::HeaderMap), Error>;
fn redirect_parser(&self, body: Vec<u8>, format: Format) -> Result<String, Error>;
fn update(&mut self, region: String, secure: bool);
fn current_region(&self) -> Option<String>;
}
pub struct Handler<'a> {
pub access_key: &'a str,
pub secret_key: &'a str,
pub host: &'a str,
s3_client: Box<dyn S3Client + 'a>,
pub auth_type: AuthType,
pub format: Format,
pub url_style: UrlStyle,
pub region: Option<String>,
domain_name: String,
secure: bool,
}
#[derive(Debug, Clone)]
pub struct S3Object {
pub bucket: Option<String>,
pub key: Option<String>,
pub mtime: Option<String>,
pub etag: Option<String>,
pub storage_class: Option<String>,
}
impl From<String> for S3Object {
fn from(s3_path: String) -> Self {
if s3_path.starts_with("s3://") || s3_path.starts_with("S3://") {
let url_parser = Url::parse(&s3_path).unwrap();
let bucket = match url_parser.host_str() {
Some(h) if h != "" => Some(h.to_string()),
_ => None,
};
match url_parser.path() {
"/" | "" => S3Object {
bucket: bucket,
key: None,
mtime: None,
etag: None,
storage_class: None,
},
_ => S3Object {
bucket: bucket,
key: Some(url_parser.path().to_string()),
mtime: None,
etag: None,
storage_class: None,
},
}
} else {
S3Convert::new_from_uri(s3_path)
}
}
}
impl From<S3Object> for String {
fn from(s3_object: S3Object) -> Self {
match s3_object.bucket {
Some(b) => match s3_object.key {
Some(k) => format!("s3://{}{}", b, k),
None => format!("s3://{}", b),
},
None => format!("s3://"),
}
}
}
pub trait S3Convert {
fn virtural_host_style_links(&self, host: String) -> (String, String);
fn path_style_links(&self, host: String) -> (String, String);
fn new_from_uri(path: String) -> Self;
fn new(
bucket: Option<String>,
key: Option<String>,
mtime: Option<String>,
etag: Option<String>,
storage_class: Option<String>,
) -> Self;
}
impl S3Convert for S3Object {
fn virtural_host_style_links(&self, host: String) -> (String, String) {
match self.bucket.clone() {
Some(b) => (
format!("{}.{}", b, host),
self.key.clone().unwrap_or("/".to_string()),
),
None => (host, "/".to_string()),
}
}
fn path_style_links(&self, host: String) -> (String, String) {
match self.bucket.clone() {
Some(b) => (
host,
format!("/{}{}", b, self.key.clone().unwrap_or("/".to_string())),
),
None => (host, "/".to_string()),
}
}
fn new_from_uri(uri: String) -> S3Object {
let re = Regex::new(r#"/?(?P<bucket>[A-Za-z0-9\-\._]+)(?P<object>[A-Za-z0-9\-\._/]*)\s*"#)
.unwrap();
let caps = re.captures(&uri).expect("S3 object uri format error.");
if &caps["object"] == "" || &caps["object"] == "/" {
S3Object {
bucket: Some(caps["bucket"].to_string()),
key: None,
mtime: None,
etag: None,
storage_class: None,
}
} else {
S3Object {
bucket: Some(caps["bucket"].to_string()),
key: Some(caps["object"].to_string()),
mtime: None,
etag: None,
storage_class: None,
}
}
}
fn new(
bucket: Option<String>,
object: Option<String>,
mtime: Option<String>,
etag: Option<String>,
storage_class: Option<String>,
) -> S3Object {
let key = match object {
None => None,
Some(b) => {
if b.starts_with("/") {
Some(b)
} else {
Some(format!("/{}", b))
}
}
};
S3Object {
bucket: bucket,
key: key,
mtime: mtime,
etag: etag,
storage_class: storage_class,
}
}
}
trait ResponseHandler {
fn handle_response(&mut self) -> (StatusCode, Vec<u8>, reqwest::header::HeaderMap);
}
impl ResponseHandler for Response {
fn handle_response(&mut self) -> (StatusCode, Vec<u8>, reqwest::header::HeaderMap) {
let mut body = Vec::new();
let _ = self.read_to_end(&mut body);
if self.status().is_success() || self.status().is_redirection() {
info!("Status: {}", self.status());
info!("Headers:\n{:?}", self.headers());
info!(
"Body:\n{}\n\n",
std::str::from_utf8(&body).expect("Body can not decode as UTF8")
);
} else {
error!("Status: {}", self.status());
error!("Headers:\n{:?}", self.headers());
error!(
"Body:\n{}\n\n",
std::str::from_utf8(&body).expect("Body can not decode as UTF8")
);
}
(self.status(), body, self.headers().clone())
}
}
impl Handler<'_> {
fn request(
&mut self,
method: &str,
s3_object: &S3Object,
qs: &Vec<(&str, &str)>,
headers: &mut Vec<(&str, &str)>,
payload: &Vec<u8>,
) -> Result<(Vec<u8>, reqwest::header::HeaderMap), Error> {
let mut query_strings = vec![];
match self.format {
Format::JSON => query_strings.push(("format", "json")),
_ => {}
}
query_strings.extend(qs.iter().cloned());
let (request_host, uri) = match self.url_style {
UrlStyle::HOST => s3_object.virtural_host_style_links(self.domain_name.to_string()),
UrlStyle::PATH => s3_object.path_style_links(self.domain_name.to_string()),
};
debug!("method: {}", method);
debug!("request_host: {}", request_host);
debug!("uri: {}", uri);
let (status_code, body, response_headers) = self.s3_client.request(
method,
&request_host,
&uri,
&mut query_strings,
headers,
&payload,
)?;
match status_code.is_redirection() {
true => {
self.region = Some(
response_headers["x-amz-bucket-region"]
.to_str()
.unwrap_or("")
.to_string(),
);
let origin_region = self.s3_client.current_region();
self.s3_client
.update(self.region.clone().unwrap(), self.secure);
let (_status_code, body, response_headers) = self.s3_client.request(
method,
&self.s3_client.redirect_parser(body, self.format.clone())?,
&uri,
&mut query_strings,
headers,
&payload,
)?;
self.s3_client.update(origin_region.unwrap(), self.secure);
Ok((body, response_headers))
}
false => Ok((body, response_headers)),
}
}
fn next_marker_xml_parser(&self, body: &str) -> Option<String> {
let mut reader = Reader::from_str(body);
let mut in_tag = false;
let mut buf = Vec::new();
let mut output = "".to_string();
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => match e.name() {
b"NextMarker" => in_tag = true,
_ => {}
},
Ok(Event::End(ref e)) => match e.name() {
_ => {}
},
Ok(Event::Text(e)) => {
if in_tag {
output = e.unescape_and_decode(&reader).unwrap();
break;
}
}
Ok(Event::Eof) => break,
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
if output.is_empty() {
None
} else {
Some(output)
}
}
fn object_list_xml_parser(&self, body: &str) -> Result<Vec<S3Object>, Error> {
let mut reader = Reader::from_str(body);
let mut output = Vec::new();
let mut in_name_tag = false;
let mut in_key_tag = false;
let mut in_mtime_tag = false;
let mut in_etag_tag = false;
let mut in_storage_class_tag = false;
let mut bucket = String::new();
let mut key = String::new();
let mut mtime = String::new();
let mut etag = String::new();
let mut storage_class = String::new();
let mut buf = Vec::new();
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => match e.name() {
b"Name" => in_name_tag = true,
b"Key" => in_key_tag = true,
b"LastModified" => in_mtime_tag = true,
b"ETag" => in_etag_tag = true,
b"StorageClass" => in_storage_class_tag = true,
_ => {}
},
Ok(Event::End(ref e)) => match e.name() {
b"Name" => {
output.push(S3Convert::new(Some(bucket.clone()), None, None, None, None))
}
b"Contents" => output.push(S3Convert::new(
Some(bucket.clone()),
Some(key.clone()),
Some(mtime.clone()),
Some(etag[1..etag.len() - 1].to_string()),
Some(storage_class.clone()),
)),
_ => {}
},
Ok(Event::Text(e)) => {
if in_key_tag {
key = e.unescape_and_decode(&reader).unwrap();
in_key_tag = false;
}
if in_mtime_tag {
mtime = e.unescape_and_decode(&reader).unwrap();
in_mtime_tag = false;
}
if in_etag_tag {
etag = e.unescape_and_decode(&reader).unwrap();
in_etag_tag = false;
}
if in_storage_class_tag {
storage_class = e.unescape_and_decode(&reader).unwrap();
in_storage_class_tag = false;
}
if in_name_tag {
bucket = e.unescape_and_decode(&reader).unwrap();
in_name_tag = false;
}
}
Ok(Event::Eof) => break,
Err(e) => return Err(Error::XMLParseError(e)),
_ => (),
}
buf.clear();
}
Ok(output)
}
pub fn la(&mut self) -> Result<Vec<S3Object>, Error> {
let mut output = Vec::new();
let content_re = Regex::new(RESPONSE_CONTENT_FORMAT).unwrap();
let next_marker_re = Regex::new(RESPONSE_MARKER_FORMAT).unwrap();
let s3_object = S3Object::from("s3://".to_string());
let res = &self
.request("GET", &s3_object, &Vec::new(), &mut Vec::new(), &Vec::new())?
.0;
let mut buckets = Vec::new();
match self.format {
Format::JSON => {
let result: serde_json::Value = serde_json::from_slice(&res).unwrap();
result[1].as_array().map(|bucket_list| {
buckets.extend(
bucket_list
.iter()
.map(|b| b["Name"].as_str().unwrap().to_string()),
)
});
}
Format::XML => {
buckets.extend(
self.object_list_xml_parser(std::str::from_utf8(res).unwrap_or(""))?
.iter()
.map(|o| o.bucket.clone().unwrap()),
);
}
}
for bucket in buckets {
let s3_object = S3Object::from(format!("s3://{}", bucket));
let mut next_marker = Some("".to_string());
while next_marker.is_some() {
let body = &self
.request(
"GET",
&s3_object,
&vec![("marker", &next_marker.clone().unwrap())],
&mut Vec::new(),
&Vec::new(),
)?
.0;
match self.format {
Format::JSON => {
next_marker = match next_marker_re
.captures_iter(std::str::from_utf8(body).unwrap_or(""))
.nth(0)
{
Some(c) => Some(c[1].to_string()),
None => None,
};
output.extend(
content_re
.captures_iter(std::str::from_utf8(body).unwrap_or(""))
.map(|cap| {
S3Convert::new(
Some(bucket.clone()),
Some(cap[1].to_string()),
Some(cap[2].to_string()),
Some(cap[3].to_string()),
Some(cap[5].to_string()),
)
}),
);
}
Format::XML => {
next_marker =
self.next_marker_xml_parser(std::str::from_utf8(body).unwrap_or(""));
output.extend(
self.object_list_xml_parser(std::str::from_utf8(body).unwrap_or(""))?,
);
}
}
}
}
Ok(output)
}
pub fn ls(&mut self, prefix: Option<&str>) -> Result<Vec<S3Object>, Error> {
let mut output = Vec::new();
let mut res: String;
let s3_object = S3Object::from(prefix.unwrap_or("s3://").to_string());
let s3_bucket = S3Object::new(s3_object.bucket, None, None, None, None);
match s3_bucket.bucket.clone() {
Some(b) => {
let re = Regex::new(RESPONSE_CONTENT_FORMAT).unwrap();
let next_marker_re = Regex::new(RESPONSE_MARKER_FORMAT).unwrap();
let mut next_marker = Some("".to_string());
while next_marker.is_some() {
res = std::str::from_utf8(
&self
.request(
"GET",
&s3_bucket,
&vec![
(
"prefix",
&s3_object.key.clone().unwrap_or("/".to_string())[1..],
),
("marker", &next_marker.clone().unwrap()),
],
&mut Vec::new(),
&Vec::new(),
)?
.0,
)
.unwrap_or("")
.to_string();
match self.format {
Format::JSON => {
next_marker = match next_marker_re.captures_iter(&res).nth(0) {
Some(c) => Some(c[1].to_string()),
None => None,
};
output.extend(re.captures_iter(&res).map(|cap| {
S3Convert::new(
Some(b.to_string()),
Some(cap[1].to_string()),
Some(cap[2].to_string()),
Some(cap[3].to_string()),
Some(cap[5].to_string()),
)
}));
}
Format::XML => {
next_marker = self.next_marker_xml_parser(&res);
output.extend(self.object_list_xml_parser(&res)?);
}
}
}
}
None => {
let s3_object = S3Object::from("s3://".to_string());
let body = &self
.request("GET", &s3_object, &Vec::new(), &mut Vec::new(), &Vec::new())?
.0;
match self.format {
Format::JSON => {
let result: serde_json::Value =
serde_json::from_str(std::str::from_utf8(body).unwrap_or("")).unwrap();
result[1].as_array().map(|bucket_list| {
output.extend(bucket_list.iter().map(|b| {
S3Convert::new(
Some(b["Name"].as_str().unwrap().to_string()),
None,
None,
None,
None,
)
}))
});
}
Format::XML => {
output.extend(
self.object_list_xml_parser(std::str::from_utf8(body).unwrap_or(""))?,
);
}
}
}
};
Ok(output)
}
pub fn put(&mut self, file: &str, dest: &str) -> Result<(), Error> {
if file == "" || dest == "" {
return Err(Error::UserError("please specify the file and the destiney"));
}
let mut s3_object = S3Object::from(dest.to_string());
let mut content: Vec<u8>;
if s3_object.key.is_none() {
let file_name = Path::new(file).file_name().unwrap().to_string_lossy();
s3_object.key = Some(format!("/{}", file_name));
}
if !Path::new(file).exists() && file == "test" {
content = vec![83, 51, 82, 83, 32, 116, 101, 115, 116, 10];
let _ = self.request("PUT", &s3_object, &Vec::new(), &mut Vec::new(), &content);
} else {
let file_size = match metadata(Path::new(file)) {
Ok(m) => m.len(),
Err(e) => {
error!("file meta error: {}", e);
0
}
};
debug!("upload file size: {}", file_size);
if file_size > 5242880 {
let total_part_number = file_size / 5242880 + 1;
debug!("upload file in {} parts", total_part_number);
let res = std::str::from_utf8(
&self
.request(
"POST",
&s3_object,
&vec![("uploads", "")],
&mut Vec::new(),
&Vec::new(),
)?
.0,
)
.unwrap_or("")
.to_string();
let mut upload_id = "".to_string();
match self.format {
Format::JSON => {
let re = Regex::new(r#""UploadId":"(?P<upload_id>[^"]+)""#).unwrap();
let caps = re.captures(&res).expect("Upload ID missing");
upload_id = caps["upload_id"].to_string();
}
Format::XML => {
let mut reader = Reader::from_str(&res);
let mut in_tag = false;
let mut buf = Vec::new();
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => {
if e.name() == b"UploadId" {
in_tag = true;
}
}
Ok(Event::End(ref e)) => {
if e.name() == b"UploadId" {
in_tag = false;
}
}
Ok(Event::Text(e)) => {
if in_tag {
upload_id = e.unescape_and_decode(&reader).unwrap();
}
}
Ok(Event::Eof) => break,
Err(e) => return Err(Error::XMLParseError(e)),
_ => (),
}
buf.clear();
}
}
}
info!("upload id: {}", upload_id);
let mut etags = Vec::new();
let mut part = 0u64;
let mut fin = File::open(file)?;
loop {
part += 1;
let mut buffer = [0; 5242880];
let mut tail_buffer = Vec::new();
if part == total_part_number {
fin.read_to_end(&mut tail_buffer)?;
} else {
fin.read_exact(&mut buffer)?
}
let headers = if part == total_part_number {
self.request(
"PUT",
&s3_object,
&vec![
("uploadId", upload_id.as_str()),
("partNumber", part.to_string().as_str()),
],
&mut Vec::new(),
&tail_buffer,
)?
.1
} else {
self.request(
"PUT",
&s3_object,
&vec![
("uploadId", upload_id.as_str()),
("partNumber", part.to_string().as_str()),
],
&mut Vec::new(),
&buffer.to_vec(),
)?
.1
};
let etag = headers[reqwest::header::ETAG]
.to_str()
.expect("unexpected etag from server");
etags.push((part.clone(), etag.to_string()));
info!("part: {} uploaded, etag: {}", part, etag);
if part * 5242880 >= file_size {
let mut content = format!("<CompleteMultipartUpload>");
for etag in etags {
content.push_str(&format!(
"<Part><PartNumber>{}</PartNumber><ETag>{}</ETag></Part>",
etag.0, etag.1
));
}
content.push_str(&format!("</CompleteMultipartUpload>"));
let _ = self.request(
"POST",
&s3_object,
&vec![("uploadId", upload_id.as_str())],
&mut Vec::new(),
&content.into_bytes(),
)?;
info!("complete multipart");
break;
}
}
} else {
content = Vec::new();
let mut fin = File::open(file)?;
let _ = fin.read_to_end(&mut content);
let _ = self.request("PUT", &s3_object, &Vec::new(), &mut Vec::new(), &content)?;
};
}
Ok(())
}
pub fn get(&mut self, src: &str, file: Option<&str>) -> Result<(), Error> {
let s3_object = S3Object::from(src.to_string());
if s3_object.key.is_none() {
return Err(Error::UserError("Please specific the object"));
}
let fout = match file {
Some(fname) => fname,
None => Path::new(src)
.file_name()
.unwrap()
.to_str()
.unwrap_or("s3download"),
};
write(
fout,
self.request("GET", &s3_object, &Vec::new(), &mut Vec::new(), &Vec::new())?
.0,
)?;
Ok(())
}
pub fn cat(&mut self, src: &str) -> Result<(), Error> {
let s3_object = S3Object::from(src.to_string());
if s3_object.key.is_none() {
return Err(Error::UserError("Please specific the object"));
}
self.request("GET", &s3_object, &Vec::new(), &mut Vec::new(), &Vec::new())
.map(|r| println!("{}", std::str::from_utf8(&r.0).unwrap_or("")))?;
Ok(())
}
pub fn del_with_flag(
&mut self,
src: &str,
headers: &mut Vec<(&str, &str)>,
) -> Result<(), Error> {
debug!("headers: {:?}", headers);
let s3_object = S3Object::from(src.to_string());
if s3_object.key.is_none() {
return Err(Error::UserError("Please specific the object"));
}
self.request("DELETE", &s3_object, &Vec::new(), headers, &Vec::new())?;
Ok(())
}
pub fn del(&mut self, src: &str) -> Result<(), Error> {
self.del_with_flag(src, &mut Vec::new())
}
pub fn mb(&mut self, bucket: &str) -> Result<(), Error> {
let s3_object = S3Object::from(bucket.to_string());
if s3_object.bucket.is_none() {
return Err(Error::UserError("please specific the bucket name"));
}
self.request("PUT", &s3_object, &Vec::new(), &mut Vec::new(), &Vec::new())?;
Ok(())
}
pub fn rb(&mut self, bucket: &str) -> Result<(), Error> {
let s3_object = S3Object::from(bucket.to_string());
if s3_object.bucket.is_none() {
return Err(Error::UserError("please specific the bucket name"));
}
self.request(
"DELETE",
&s3_object,
&Vec::new(),
&mut Vec::new(),
&Vec::new(),
)?;
Ok(())
}
pub fn list_tag(&mut self, target: &str) -> Result<(), Error> {
let res: String;
debug!("target: {:?}", target);
let s3_object = S3Object::from(target.to_string());
if s3_object.key.is_none() {
return Err(Error::UserError("Please specific the object"));
}
let query_string = vec![("tagging", "")];
res = std::str::from_utf8(
&self
.request(
"GET",
&s3_object,
&query_string,
&mut Vec::new(),
&Vec::new(),
)?
.0,
)
.unwrap_or("")
.to_string();
println!("{}", res);
Ok(())
}
pub fn add_tag(&mut self, target: &str, tags: &Vec<(&str, &str)>) -> Result<(), Error> {
debug!("target: {:?}", target);
debug!("tags: {:?}", tags);
let s3_object = S3Object::from(target.to_string());
if s3_object.key.is_none() {
return Err(Error::UserError("Please specific the object"));
}
let mut content = format!("<Tagging><TagSet>");
for tag in tags {
content.push_str(&format!(
"<Tag><Key>{}</Key><Value>{}</Value></Tag>",
tag.0, tag.1
));
}
content.push_str(&format!("</TagSet></Tagging>"));
debug!("payload: {:?}", content);
let query_string = vec![("tagging", "")];
self.request(
"PUT",
&s3_object,
&query_string,
&mut Vec::new(),
&content.into_bytes(),
)?;
Ok(())
}
pub fn del_tag(&mut self, target: &str) -> Result<(), Error> {
debug!("target: {:?}", target);
let s3_object = S3Object::from(target.to_string());
if s3_object.key.is_none() {
return Err(Error::UserError("Please specific the object"));
}
let query_string = vec![("tagging", "")];
self.request(
"DELETE",
&s3_object,
&query_string,
&mut Vec::new(),
&Vec::new(),
)?;
Ok(())
}
pub fn usage(&mut self, target: &str, options: &Vec<(&str, &str)>) -> Result<(), Error> {
let s3_admin_bucket_object = S3Convert::new_from_uri("/admin/buckets".to_string());
let s3_object = S3Object::from(target.to_string());
let mut query_strings = options.clone();
if s3_object.bucket.is_none() {
return Err(Error::UserError("S3 format not correct."));
};
let bucket = s3_object.bucket.unwrap();
query_strings.push(("bucket", &bucket));
let result = self.request(
"GET",
&s3_admin_bucket_object,
&query_strings,
&mut Vec::new(),
&Vec::new(),
)?;
match self.format {
Format::JSON => {
let json: serde_json::Value;
json = serde_json::from_str(std::str::from_utf8(&result.0).unwrap_or("")).unwrap();
println!(
"{}",
serde_json::to_string_pretty(&json["usage"]).unwrap_or("".to_string())
);
}
Format::XML => {
unimplemented!();
}
};
Ok(())
}
pub fn url_command(&mut self, url: &str) -> Result<(), Error> {
let s3_object;
let mut raw_qs = String::new();
let mut query_strings = Vec::new();
match url.find('?') {
Some(idx) => {
s3_object = S3Object::from(url[..idx].to_string());
raw_qs.push_str(&String::from_str(&url[idx + 1..]).unwrap());
for q_pair in raw_qs.split('&') {
match q_pair.find('=') {
Some(_) => query_strings.push((
q_pair.split('=').nth(0).unwrap(),
q_pair.split('=').nth(1).unwrap(),
)),
None => query_strings.push((&q_pair, "")),
}
}
}
None => {
s3_object = S3Object::from(url.to_string());
}
}
let result = self.request(
"GET",
&s3_object,
&query_strings,
&mut Vec::new(),
&Vec::new(),
)?;
println!("{}", std::str::from_utf8(&result.0).unwrap_or(""));
Ok(())
}
pub fn change_s3_type(&mut self, command: &str) {
println!("set up s3 type as {}", command);
if command.ends_with("aws") {
self.auth_type = AuthType::AWS4;
self.format = Format::XML;
self.url_style = UrlStyle::HOST;
println!("using aws verion 4 signature, xml format, and host style url");
} else if command.ends_with("ceph") {
self.auth_type = AuthType::AWS4;
self.format = Format::JSON;
self.url_style = UrlStyle::PATH;
println!("using aws verion 4 signature, json format, and path style url");
} else {
println!("usage: s3_type [aws/ceph]");
}
}
pub fn change_auth_type(&mut self, command: &str) {
if command.ends_with("aws2") {
self.auth_type = AuthType::AWS2;
println!("using aws version 2 signature");
} else if command.ends_with("aws4") || command.ends_with("aws") {
self.auth_type = AuthType::AWS4;
println!("using aws verion 4 signature");
} else {
println!("usage: auth_type [aws4/aws2]");
}
}
pub fn change_format_type(&mut self, command: &str) {
if command.ends_with("xml") {
self.format = Format::XML;
println!("using xml format");
} else if command.ends_with("json") {
self.format = Format::JSON;
println!("using json format");
} else {
println!("usage: format_type [xml/json]");
}
}
pub fn change_url_style(&mut self, command: &str) {
if command.ends_with("path") {
self.url_style = UrlStyle::PATH;
println!("using path style url");
} else if command.ends_with("host") {
self.url_style = UrlStyle::HOST;
println!("using host style url");
} else {
println!("usage: url_style [path/host]");
}
}
}
impl<'a> From<&'a CredentialConfig> for Handler<'a> {
fn from(credential: &'a CredentialConfig) -> Self {
debug!("host: {}", credential.host);
debug!("access key: {}", credential.access_key);
debug!("secret key: {}", credential.secret_key);
match credential
.clone()
.s3_type
.unwrap_or("".to_string())
.as_str()
{
"aws" => Handler {
access_key: &credential.access_key,
secret_key: &credential.secret_key,
host: &credential.host,
s3_client: Box::new(AWS4Client {
tls: credential.secure.unwrap_or(false),
access_key: &credential.access_key,
secret_key: &credential.secret_key,
host: &credential.host,
region: credential.region.clone().unwrap(),
}),
auth_type: AuthType::AWS4,
format: Format::XML,
url_style: UrlStyle::HOST,
region: credential.region.clone(),
secure: credential.secure.unwrap_or(false),
domain_name: credential.host.to_string(),
},
"ceph" => Handler {
access_key: &credential.access_key,
secret_key: &credential.secret_key,
host: &credential.host,
s3_client: Box::new(AWS4Client {
tls: credential.secure.unwrap_or(false),
access_key: &credential.access_key,
secret_key: &credential.secret_key,
host: &credential.host,
region: credential.region.clone().unwrap(),
}),
auth_type: AuthType::AWS4,
format: Format::JSON,
url_style: UrlStyle::PATH,
region: credential.region.clone(),
secure: credential.secure.unwrap_or(false),
domain_name: credential.host.to_string(),
},
_ => Handler {
access_key: &credential.access_key,
secret_key: &credential.secret_key,
host: &credential.host,
auth_type: AuthType::AWS4,
format: Format::XML,
url_style: UrlStyle::PATH,
region: credential.region.clone(),
secure: credential.secure.unwrap_or(false),
domain_name: credential.host.to_string(),
s3_client: Box::new(AWS4Client {
tls: credential.secure.unwrap_or(false),
access_key: &credential.access_key,
secret_key: &credential.secret_key,
host: &credential.host,
region: credential.region.clone().unwrap_or("us-east-1".to_string()),
}),
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_s3object_for_dummy_folder() {
let s3_object = S3Object::from("s3://bucket/dummy_folder/".to_string());
assert_eq!(s3_object.bucket, Some("bucket".to_string()));
assert_eq!(s3_object.key, Some("/dummy_folder/".to_string()));
assert_eq!(
"s3://bucket/dummy_folder/".to_string(),
String::from(s3_object)
);
}
#[test]
fn test_s3object_for_bucket() {
let s3_object = S3Object::from("s3://bucket".to_string());
assert_eq!(s3_object.bucket, Some("bucket".to_string()));
assert_eq!(s3_object.key, None);
assert_eq!("s3://bucket".to_string(), String::from(s3_object));
}
#[test]
fn test_s3object_for_dummy_folder_from_uri() {
let s3_object: S3Object = S3Convert::new_from_uri("/bucket/dummy_folder/".to_string());
assert_eq!(
"s3://bucket/dummy_folder/".to_string(),
String::from(s3_object)
);
}
#[test]
fn test_s3object_for_root() {
let s3_object = S3Object::from("s3://".to_string());
assert_eq!(s3_object.bucket, None);
assert_eq!(s3_object.key, None);
}
#[test]
fn test_s3object_for_bucket_from_uri() {
let s3_object: S3Object = S3Convert::new_from_uri("/bucket".to_string());
assert_eq!("s3://bucket".to_string(), String::from(s3_object));
}
#[test]
fn test_s3object_for_slash_end_bucket_from_uri() {
let s3_object: S3Object = S3Convert::new_from_uri("/bucket/".to_string());
assert_eq!("s3://bucket".to_string(), String::from(s3_object));
}
#[test]
fn test_s3object_for_bucket_from_bucket_name() {
let s3_object: S3Object = S3Convert::new_from_uri("bucket".to_string());
assert_eq!("s3://bucket".to_string(), String::from(s3_object));
}
}