2019-01-17 10:29:38 +00:00
|
|
|
use failure::*;
|
|
|
|
|
|
|
|
use http::Uri;
|
|
|
|
use hyper::Body;
|
|
|
|
use hyper::client::Client;
|
2019-03-05 11:54:44 +00:00
|
|
|
use xdg::BaseDirectories;
|
|
|
|
use chrono::Utc;
|
2019-01-17 10:29:38 +00:00
|
|
|
|
2019-05-13 08:27:22 +00:00
|
|
|
use http::{Request, Response};
|
2019-04-28 08:55:03 +00:00
|
|
|
use http::header::HeaderValue;
|
|
|
|
|
|
|
|
use futures::Future;
|
2019-01-21 17:56:48 +00:00
|
|
|
use futures::stream::Stream;
|
|
|
|
|
2019-03-05 11:54:44 +00:00
|
|
|
use serde_json::{json, Value};
|
2019-02-13 13:31:43 +00:00
|
|
|
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
|
2019-01-21 17:56:48 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
use crate::tools::{self, BroadcastFuture, tty};
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct AuthInfo {
|
|
|
|
username: String,
|
|
|
|
ticket: String,
|
|
|
|
token: String,
|
|
|
|
}
|
2019-02-20 13:18:27 +00:00
|
|
|
|
2019-02-14 10:11:39 +00:00
|
|
|
/// HTTP(S) API client
|
2019-01-17 10:29:38 +00:00
|
|
|
pub struct HttpClient {
|
2019-04-28 08:55:03 +00:00
|
|
|
client: Client<hyper_tls::HttpsConnector<hyper::client::HttpConnector>>,
|
2019-01-17 10:29:38 +00:00
|
|
|
server: String,
|
2019-04-28 08:55:03 +00:00
|
|
|
auth: BroadcastFuture<AuthInfo>,
|
2019-01-17 10:29:38 +00:00
|
|
|
}
|
|
|
|
|
2019-03-05 11:54:44 +00:00
|
|
|
fn store_ticket_info(server: &str, username: &str, ticket: &str, token: &str) -> Result<(), Error> {
|
|
|
|
|
|
|
|
let base = BaseDirectories::with_prefix("proxmox-backup")?;
|
|
|
|
|
|
|
|
// usually /run/user/<uid>/...
|
|
|
|
let path = base.place_runtime_file("tickets")?;
|
|
|
|
|
|
|
|
let mode = nix::sys::stat::Mode::from_bits_truncate(0o0600);
|
|
|
|
|
2019-04-04 10:24:18 +00:00
|
|
|
let mut data = tools::file_get_json(&path, Some(json!({})))?;
|
2019-03-05 11:54:44 +00:00
|
|
|
|
|
|
|
let now = Utc::now().timestamp();
|
|
|
|
|
|
|
|
data[server][username] = json!({ "timestamp": now, "ticket": ticket, "token": token});
|
|
|
|
|
|
|
|
let mut new_data = json!({});
|
|
|
|
|
|
|
|
let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60;
|
|
|
|
|
|
|
|
let empty = serde_json::map::Map::new();
|
|
|
|
for (server, info) in data.as_object().unwrap_or(&empty) {
|
|
|
|
for (_user, uinfo) in info.as_object().unwrap_or(&empty) {
|
|
|
|
if let Some(timestamp) = uinfo["timestamp"].as_i64() {
|
|
|
|
let age = now - timestamp;
|
|
|
|
if age < ticket_lifetime {
|
|
|
|
new_data[server][username] = uinfo.clone();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
tools::file_set_contents(path, new_data.to_string().as_bytes(), Some(mode))?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load_ticket_info(server: &str, username: &str) -> Option<(String, String)> {
|
|
|
|
let base = match BaseDirectories::with_prefix("proxmox-backup") {
|
|
|
|
Ok(b) => b,
|
|
|
|
_ => return None,
|
|
|
|
};
|
|
|
|
|
|
|
|
// usually /run/user/<uid>/...
|
|
|
|
let path = match base.place_runtime_file("tickets") {
|
|
|
|
Ok(p) => p,
|
|
|
|
_ => return None,
|
|
|
|
};
|
|
|
|
|
2019-04-04 10:24:18 +00:00
|
|
|
let data = match tools::file_get_json(&path, None) {
|
|
|
|
Ok(v) => v,
|
|
|
|
_ => return None,
|
|
|
|
};
|
2019-03-05 11:54:44 +00:00
|
|
|
|
|
|
|
let now = Utc::now().timestamp();
|
|
|
|
|
|
|
|
let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60;
|
|
|
|
|
|
|
|
if let Some(uinfo) = data[server][username].as_object() {
|
|
|
|
if let Some(timestamp) = uinfo["timestamp"].as_i64() {
|
|
|
|
let age = now - timestamp;
|
|
|
|
if age < ticket_lifetime {
|
|
|
|
let ticket = match uinfo["ticket"].as_str() {
|
|
|
|
Some(t) => t,
|
|
|
|
None => return None,
|
|
|
|
};
|
|
|
|
let token = match uinfo["token"].as_str() {
|
|
|
|
Some(t) => t,
|
|
|
|
None => return None,
|
2019-03-06 05:45:51 +00:00
|
|
|
};
|
2019-03-05 11:54:44 +00:00
|
|
|
return Some((ticket.to_owned(), token.to_owned()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
2019-01-17 10:29:38 +00:00
|
|
|
impl HttpClient {
|
|
|
|
|
2019-04-30 09:44:35 +00:00
|
|
|
pub fn new(server: &str, username: &str) -> Result<Self, Error> {
|
2019-04-28 08:55:03 +00:00
|
|
|
let client = Self::build_client();
|
|
|
|
|
2019-04-30 09:44:35 +00:00
|
|
|
let password = if let Some((ticket, _token)) = load_ticket_info(server, username) {
|
|
|
|
ticket
|
|
|
|
} else {
|
|
|
|
Self::get_password(&username)?
|
|
|
|
};
|
|
|
|
|
|
|
|
let login = Self::credentials(client.clone(), server.to_owned(), username.to_owned(), password);
|
|
|
|
|
|
|
|
Ok(Self {
|
2019-04-28 08:55:03 +00:00
|
|
|
client,
|
2019-01-17 10:29:38 +00:00
|
|
|
server: String::from(server),
|
2019-04-28 08:55:03 +00:00
|
|
|
auth: BroadcastFuture::new(login),
|
2019-04-30 09:44:35 +00:00
|
|
|
})
|
2019-01-17 10:29:38 +00:00
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
fn get_password(_username: &str) -> Result<String, Error> {
|
2019-02-20 13:18:27 +00:00
|
|
|
use std::env::VarError::*;
|
|
|
|
match std::env::var("PBS_PASSWORD") {
|
|
|
|
Ok(p) => return Ok(p),
|
|
|
|
Err(NotUnicode(_)) => bail!("PBS_PASSWORD contains bad characters"),
|
|
|
|
Err(NotPresent) => {
|
|
|
|
// Try another method
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we're on a TTY, query the user for a password
|
|
|
|
if tty::stdin_isatty() {
|
|
|
|
return Ok(String::from_utf8(tty::read_password("Password: ")?)?);
|
|
|
|
}
|
|
|
|
|
|
|
|
bail!("no password input mechanism available");
|
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
fn build_client() -> Client<hyper_tls::HttpsConnector<hyper::client::HttpConnector>> {
|
2019-02-13 10:03:02 +00:00
|
|
|
let mut builder = native_tls::TlsConnector::builder();
|
|
|
|
// FIXME: We need a CLI option for this!
|
|
|
|
builder.danger_accept_invalid_certs(true);
|
2019-04-28 08:55:03 +00:00
|
|
|
let tlsconnector = builder.build().unwrap();
|
2019-02-13 10:03:02 +00:00
|
|
|
let mut httpc = hyper::client::HttpConnector::new(1);
|
|
|
|
httpc.enforce_http(false); // we want https...
|
|
|
|
let mut https = hyper_tls::HttpsConnector::from((httpc, tlsconnector));
|
|
|
|
https.https_only(true); // force it!
|
2019-04-28 08:55:03 +00:00
|
|
|
Client::builder().build::<_, Body>(https)
|
2019-03-06 09:45:38 +00:00
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
pub fn request(&self, mut req: Request<Body>) -> impl Future<Item=Value, Error=Error> {
|
2019-01-17 10:29:38 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let login = self.auth.listen();
|
2019-01-17 10:29:38 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let client = self.client.clone();
|
2019-01-17 10:29:38 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
login.and_then(move |auth| {
|
2019-01-17 10:29:38 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
|
|
|
|
req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
|
|
|
|
req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap());
|
2019-01-17 10:29:38 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let request = Self::api_request(client, req);
|
2019-01-17 10:29:38 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
request
|
|
|
|
})
|
2019-01-21 17:56:48 +00:00
|
|
|
}
|
|
|
|
|
2019-05-13 07:12:03 +00:00
|
|
|
pub fn get(&self, path: &str, data: Option<Value>) -> impl Future<Item=Value, Error=Error> {
|
2019-03-06 09:45:38 +00:00
|
|
|
|
2019-05-13 07:12:03 +00:00
|
|
|
let req = Self::request_builder(&self.server, "GET", path, data).unwrap();
|
2019-04-28 08:55:03 +00:00
|
|
|
self.request(req)
|
2019-03-06 09:45:38 +00:00
|
|
|
}
|
|
|
|
|
2019-05-13 07:12:03 +00:00
|
|
|
pub fn delete(&mut self, path: &str, data: Option<Value>) -> impl Future<Item=Value, Error=Error> {
|
2019-03-06 09:45:38 +00:00
|
|
|
|
2019-05-13 07:12:03 +00:00
|
|
|
let req = Self::request_builder(&self.server, "DELETE", path, data).unwrap();
|
2019-04-28 08:55:03 +00:00
|
|
|
self.request(req)
|
2019-03-06 09:45:38 +00:00
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
pub fn post(&mut self, path: &str, data: Option<Value>) -> impl Future<Item=Value, Error=Error> {
|
2019-03-13 10:56:37 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let req = Self::request_builder(&self.server, "POST", path, data).unwrap();
|
|
|
|
self.request(req)
|
2019-03-13 10:56:37 +00:00
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
pub fn download(&mut self, path: &str, mut output: Box<dyn std::io::Write + Send>) -> impl Future<Item=(), Error=Error> {
|
2019-03-13 10:56:37 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let mut req = Self::request_builder(&self.server, "GET", path, None).unwrap();
|
2019-03-13 10:56:37 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let login = self.auth.listen();
|
2019-03-13 10:56:37 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let client = self.client.clone();
|
2019-01-21 17:56:48 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
login.and_then(move |auth| {
|
2019-02-20 13:09:55 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
|
|
|
|
req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
|
2019-03-03 10:29:00 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
client.request(req)
|
|
|
|
.map_err(Error::from)
|
|
|
|
.and_then(|resp| {
|
2019-03-03 10:29:00 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let _status = resp.status(); // fixme: ??
|
2019-03-03 10:29:00 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
resp.into_body()
|
|
|
|
.map_err(Error::from)
|
|
|
|
.for_each(move |chunk| {
|
|
|
|
output.write_all(&chunk)?;
|
|
|
|
Ok(())
|
|
|
|
})
|
2019-03-03 10:29:00 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
})
|
|
|
|
})
|
2019-03-03 10:29:00 +00:00
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
pub fn upload(&mut self, content_type: &str, body: Body, path: &str) -> impl Future<Item=Value, Error=Error> {
|
2019-02-20 13:09:55 +00:00
|
|
|
|
|
|
|
let path = path.trim_matches('/');
|
2019-04-28 08:55:03 +00:00
|
|
|
let url: Uri = format!("https://{}:8007/{}", &self.server, path).parse().unwrap();
|
2019-02-20 13:09:55 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let req = Request::builder()
|
2019-02-20 13:09:55 +00:00
|
|
|
.method("POST")
|
|
|
|
.uri(url)
|
|
|
|
.header("User-Agent", "proxmox-backup-client/1.0")
|
2019-04-28 08:55:03 +00:00
|
|
|
.header("Content-Type", content_type)
|
|
|
|
.body(body).unwrap();
|
2019-02-20 13:09:55 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
self.request(req)
|
2019-01-21 17:56:48 +00:00
|
|
|
}
|
|
|
|
|
2019-05-13 07:12:03 +00:00
|
|
|
pub fn h2upgrade(
|
|
|
|
&mut self, path:
|
|
|
|
&str, param: Option<Value>
|
2019-05-13 14:44:59 +00:00
|
|
|
) -> impl Future<Item=H2Client, Error=Error> {
|
2019-04-29 09:57:58 +00:00
|
|
|
|
2019-05-13 07:12:03 +00:00
|
|
|
let mut req = Self::request_builder(&self.server, "GET", path, param).unwrap();
|
2019-04-29 09:57:58 +00:00
|
|
|
|
|
|
|
let login = self.auth.listen();
|
|
|
|
|
|
|
|
let client = self.client.clone();
|
|
|
|
|
|
|
|
login.and_then(move |auth| {
|
|
|
|
|
|
|
|
let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
|
|
|
|
req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
|
|
|
|
req.headers_mut().insert("UPGRADE", HeaderValue::from_str("proxmox-backup-protocol-h2").unwrap());
|
|
|
|
|
|
|
|
client.request(req)
|
|
|
|
.map_err(Error::from)
|
|
|
|
.and_then(|resp| {
|
|
|
|
|
|
|
|
let status = resp.status();
|
|
|
|
if status != http::StatusCode::SWITCHING_PROTOCOLS {
|
|
|
|
bail!("h2upgrade failed with status {:?}", status);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(resp.into_body().on_upgrade().map_err(Error::from))
|
|
|
|
})
|
|
|
|
.flatten()
|
|
|
|
.and_then(|upgraded| {
|
|
|
|
h2::client::handshake(upgraded).map_err(Error::from)
|
|
|
|
})
|
|
|
|
.and_then(|(h2, connection)| {
|
|
|
|
let connection = connection
|
|
|
|
.map_err(|_| panic!("HTTP/2.0 connection failed"));
|
|
|
|
|
|
|
|
// Spawn a new task to drive the connection state
|
|
|
|
hyper::rt::spawn(connection);
|
|
|
|
|
|
|
|
// Wait until the `SendRequest` handle has available capacity.
|
2019-05-13 14:44:59 +00:00
|
|
|
h2.ready()
|
|
|
|
.map(H2Client::new)
|
|
|
|
.map_err(Error::from)
|
2019-04-29 09:57:58 +00:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
fn credentials(
|
|
|
|
client: Client<hyper_tls::HttpsConnector<hyper::client::HttpConnector>>,
|
2019-04-30 09:44:35 +00:00
|
|
|
server: String,
|
|
|
|
username: String,
|
|
|
|
password: String,
|
2019-04-28 08:55:03 +00:00
|
|
|
) -> Box<Future<Item=AuthInfo, Error=Error> + Send> {
|
2019-02-27 11:12:00 +00:00
|
|
|
|
2019-04-30 09:44:35 +00:00
|
|
|
let server2 = server.clone();
|
2019-02-27 11:12:00 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let create_request = futures::future::lazy(move || {
|
2019-04-30 09:44:35 +00:00
|
|
|
let data = json!({ "username": username, "password": password });
|
2019-04-28 08:55:03 +00:00
|
|
|
let req = Self::request_builder(&server, "POST", "/api2/json/access/ticket", Some(data)).unwrap();
|
2019-04-30 09:44:35 +00:00
|
|
|
Self::api_request(client, req)
|
2019-04-28 08:55:03 +00:00
|
|
|
});
|
2019-02-13 13:31:43 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let login_future = create_request
|
|
|
|
.and_then(move |cred| {
|
|
|
|
let auth = AuthInfo {
|
|
|
|
username: cred["data"]["username"].as_str().unwrap().to_owned(),
|
|
|
|
ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(),
|
|
|
|
token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
|
|
|
|
};
|
2019-02-13 13:31:43 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let _ = store_ticket_info(&server2, &auth.username, &auth.ticket, &auth.token);
|
2019-02-13 13:31:43 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
Ok(auth)
|
|
|
|
});
|
2019-02-13 13:31:43 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
Box::new(login_future)
|
2019-03-05 11:54:44 +00:00
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
fn api_request(
|
|
|
|
client: Client<hyper_tls::HttpsConnector<hyper::client::HttpConnector>>,
|
|
|
|
req: Request<Body>
|
|
|
|
) -> impl Future<Item=Value, Error=Error> {
|
2019-03-05 11:54:44 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
client.request(req)
|
|
|
|
.map_err(Error::from)
|
|
|
|
.and_then(|resp| {
|
2019-03-05 11:54:44 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let status = resp.status();
|
2019-03-05 11:54:44 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
resp
|
|
|
|
.into_body()
|
|
|
|
.concat2()
|
|
|
|
.map_err(Error::from)
|
|
|
|
.and_then(move |data| {
|
2019-02-26 10:59:10 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
let text = String::from_utf8(data.to_vec()).unwrap();
|
|
|
|
if status.is_success() {
|
|
|
|
if text.len() > 0 {
|
|
|
|
let value: Value = serde_json::from_str(&text)?;
|
|
|
|
Ok(value)
|
|
|
|
} else {
|
|
|
|
Ok(Value::Null)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
bail!("HTTP Error {}: {}", status, text);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
2019-02-13 13:31:43 +00:00
|
|
|
}
|
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> {
|
2019-02-18 05:24:28 +00:00
|
|
|
let path = path.trim_matches('/');
|
2019-04-28 08:55:03 +00:00
|
|
|
let url: Uri = format!("https://{}:8007/{}", server, path).parse()?;
|
|
|
|
|
|
|
|
if let Some(data) = data {
|
|
|
|
if method == "POST" {
|
|
|
|
let request = Request::builder()
|
|
|
|
.method(method)
|
|
|
|
.uri(url)
|
|
|
|
.header("User-Agent", "proxmox-backup-client/1.0")
|
|
|
|
.header(hyper::header::CONTENT_TYPE, "application/json")
|
|
|
|
.body(Body::from(data.to_string()))?;
|
|
|
|
return Ok(request);
|
|
|
|
} else {
|
2019-05-13 07:12:03 +00:00
|
|
|
let query = tools::json_object_to_query(data)?;
|
|
|
|
let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?;
|
|
|
|
let request = Request::builder()
|
|
|
|
.method(method)
|
|
|
|
.uri(url)
|
|
|
|
.header("User-Agent", "proxmox-backup-client/1.0")
|
|
|
|
.header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
|
|
|
.body(Body::empty())?;
|
|
|
|
return Ok(request);
|
2019-04-28 08:55:03 +00:00
|
|
|
}
|
|
|
|
}
|
2019-02-13 13:31:43 +00:00
|
|
|
|
2019-01-21 17:56:48 +00:00
|
|
|
let request = Request::builder()
|
2019-04-28 08:55:03 +00:00
|
|
|
.method(method)
|
2019-01-21 17:56:48 +00:00
|
|
|
.uri(url)
|
|
|
|
.header("User-Agent", "proxmox-backup-client/1.0")
|
2019-04-28 08:55:03 +00:00
|
|
|
.header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
|
|
|
.body(Body::empty())?;
|
2019-01-21 17:56:48 +00:00
|
|
|
|
2019-04-28 08:55:03 +00:00
|
|
|
Ok(request)
|
2019-01-17 10:29:38 +00:00
|
|
|
}
|
|
|
|
}
|
2019-05-13 08:27:22 +00:00
|
|
|
|
2019-05-14 07:00:24 +00:00
|
|
|
#[derive(Clone)]
|
2019-05-13 08:27:22 +00:00
|
|
|
pub struct H2Client {
|
|
|
|
h2: h2::client::SendRequest<bytes::Bytes>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl H2Client {
|
|
|
|
|
|
|
|
pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self {
|
|
|
|
Self { h2 }
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> {
|
|
|
|
let req = Self::request_builder("localhost", "GET", path, param).unwrap();
|
|
|
|
self.request(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn post(&self, path: &str, param: Option<Value>) -> impl Future<Item=Value, Error=Error> {
|
|
|
|
let req = Self::request_builder("localhost", "POST", path, param).unwrap();
|
|
|
|
self.request(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn request(
|
|
|
|
&self,
|
|
|
|
request: Request<()>,
|
|
|
|
) -> impl Future<Item=Value, Error=Error> {
|
|
|
|
|
2019-05-13 10:11:18 +00:00
|
|
|
self.h2.clone()
|
|
|
|
.ready()
|
|
|
|
.map_err(Error::from)
|
|
|
|
.and_then(move |mut send_request| {
|
2019-05-13 08:27:22 +00:00
|
|
|
// fixme: what about stream/upload?
|
|
|
|
let (response, _stream) = send_request.send_request(request, true).unwrap();
|
|
|
|
response
|
|
|
|
.map_err(Error::from)
|
|
|
|
.and_then(Self::h2api_response)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn h2api_response(response: Response<h2::RecvStream>) -> impl Future<Item=Value, Error=Error> {
|
|
|
|
|
|
|
|
let status = response.status();
|
|
|
|
|
|
|
|
let (_head, mut body) = response.into_parts();
|
|
|
|
|
|
|
|
// The `release_capacity` handle allows the caller to manage
|
|
|
|
// flow control.
|
|
|
|
//
|
|
|
|
// Whenever data is received, the caller is responsible for
|
|
|
|
// releasing capacity back to the server once it has freed
|
|
|
|
// the data from memory.
|
|
|
|
let mut release_capacity = body.release_capacity().clone();
|
|
|
|
|
|
|
|
body
|
|
|
|
.map(move |chunk| {
|
|
|
|
// Let the server send more data.
|
|
|
|
let _ = release_capacity.release_capacity(chunk.len());
|
|
|
|
chunk
|
|
|
|
})
|
|
|
|
.concat2()
|
|
|
|
.map_err(Error::from)
|
|
|
|
.and_then(move |data| {
|
|
|
|
let text = String::from_utf8(data.to_vec()).unwrap();
|
|
|
|
if status.is_success() {
|
|
|
|
if text.len() > 0 {
|
|
|
|
let mut value: Value = serde_json::from_str(&text)?;
|
|
|
|
if let Some(map) = value.as_object_mut() {
|
|
|
|
if let Some(data) = map.remove("data") {
|
|
|
|
return Ok(data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
bail!("got result without data property");
|
|
|
|
} else {
|
|
|
|
Ok(Value::Null)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
bail!("HTTP Error {}: {}", status, text);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn request_builder(server: &str, method: &str, path: &str, data: Option<Value>) -> Result<Request<()>, Error> {
|
|
|
|
let path = path.trim_matches('/');
|
|
|
|
let url: Uri = format!("https://{}:8007/{}", server, path).parse()?;
|
|
|
|
|
|
|
|
if let Some(data) = data {
|
|
|
|
let query = tools::json_object_to_query(data)?;
|
|
|
|
let url: Uri = format!("https://{}:8007/{}?{}", server, path, query).parse()?;
|
|
|
|
let request = Request::builder()
|
|
|
|
.method(method)
|
|
|
|
.uri(url)
|
|
|
|
.header("User-Agent", "proxmox-backup-client/1.0")
|
|
|
|
.header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
|
|
|
.body(())?;
|
|
|
|
return Ok(request);
|
|
|
|
}
|
|
|
|
|
|
|
|
let request = Request::builder()
|
|
|
|
.method(method)
|
|
|
|
.uri(url)
|
|
|
|
.header("User-Agent", "proxmox-backup-client/1.0")
|
|
|
|
.header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
|
|
|
.body(())?;
|
|
|
|
|
|
|
|
Ok(request)
|
|
|
|
}
|
|
|
|
}
|