5 use hyper
::client
::Client
;
6 use xdg
::BaseDirectories
;
9 use http
::{Request, Response}
;
10 use http
::header
::HeaderValue
;
13 use futures
::stream
::Stream
;
15 use serde_json
::{json, Value}
;
16 use url
::percent_encoding
::{percent_encode, DEFAULT_ENCODE_SET}
;
18 use crate::tools
::{self, BroadcastFuture, tty}
;
19 use super::pipe_to_stream
::*;
28 /// HTTP(S) API client
29 pub struct HttpClient
{
30 client
: Client
<hyper_tls
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
32 auth
: BroadcastFuture
<AuthInfo
>,
35 fn store_ticket_info(server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
37 let base
= BaseDirectories
::with_prefix("proxmox-backup")?
;
39 // usually /run/user/<uid>/...
40 let path
= base
.place_runtime_file("tickets")?
;
42 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
44 let mut data
= tools
::file_get_json(&path
, Some(json
!({}
)))?
;
46 let now
= Utc
::now().timestamp();
48 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
50 let mut new_data
= json
!({}
);
52 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
54 let empty
= serde_json
::map
::Map
::new();
55 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
56 for (_user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
57 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
58 let age
= now
- timestamp
;
59 if age
< ticket_lifetime
{
60 new_data
[server
][username
] = uinfo
.clone();
66 tools
::file_set_contents(path
, new_data
.to_string().as_bytes(), Some(mode
))?
;
71 fn load_ticket_info(server
: &str, username
: &str) -> Option
<(String
, String
)> {
72 let base
= match BaseDirectories
::with_prefix("proxmox-backup") {
77 // usually /run/user/<uid>/...
78 let path
= match base
.place_runtime_file("tickets") {
83 let data
= match tools
::file_get_json(&path
, None
) {
88 let now
= Utc
::now().timestamp();
90 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
92 if let Some(uinfo
) = data
[server
][username
].as_object() {
93 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
94 let age
= now
- timestamp
;
95 if age
< ticket_lifetime
{
96 let ticket
= match uinfo
["ticket"].as_str() {
100 let token
= match uinfo
["token"].as_str() {
104 return Some((ticket
.to_owned(), token
.to_owned()));
114 pub fn new(server
: &str, username
: &str) -> Result
<Self, Error
> {
115 let client
= Self::build_client();
117 let password
= if let Some((ticket
, _token
)) = load_ticket_info(server
, username
) {
120 Self::get_password(&username
)?
123 let login
= Self::credentials(client
.clone(), server
.to_owned(), username
.to_owned(), password
);
127 server
: String
::from(server
),
128 auth
: BroadcastFuture
::new(login
),
132 fn get_password(_username
: &str) -> Result
<String
, Error
> {
133 use std
::env
::VarError
::*;
134 match std
::env
::var("PBS_PASSWORD") {
135 Ok(p
) => return Ok(p
),
136 Err(NotUnicode(_
)) => bail
!("PBS_PASSWORD contains bad characters"),
138 // Try another method
142 // If we're on a TTY, query the user for a password
143 if tty
::stdin_isatty() {
144 return Ok(String
::from_utf8(tty
::read_password("Password: ")?
)?
);
147 bail
!("no password input mechanism available");
150 fn build_client() -> Client
<hyper_tls
::HttpsConnector
<hyper
::client
::HttpConnector
>> {
151 let mut builder
= native_tls
::TlsConnector
::builder();
152 // FIXME: We need a CLI option for this!
153 builder
.danger_accept_invalid_certs(true);
154 let tlsconnector
= builder
.build().unwrap();
155 let mut httpc
= hyper
::client
::HttpConnector
::new(1);
156 httpc
.enforce_http(false); // we want https...
157 let mut https
= hyper_tls
::HttpsConnector
::from((httpc
, tlsconnector
));
158 https
.https_only(true); // force it!
159 Client
::builder().build
::<_
, Body
>(https
)
162 pub fn request(&self, mut req
: Request
<Body
>) -> impl Future
<Item
=Value
, Error
=Error
> {
164 let login
= self.auth
.listen();
166 let client
= self.client
.clone();
168 login
.and_then(move |auth
| {
170 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
171 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
172 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
174 let request
= Self::api_request(client
, req
);
180 pub fn get(&self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
182 let req
= Self::request_builder(&self.server
, "GET", path
, data
).unwrap();
186 pub fn delete(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
188 let req
= Self::request_builder(&self.server
, "DELETE", path
, data
).unwrap();
192 pub fn post(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
194 let req
= Self::request_builder(&self.server
, "POST", path
, data
).unwrap();
198 pub fn download(&mut self, path
: &str, mut output
: Box
<dyn std
::io
::Write
+ Send
>) -> impl Future
<Item
=(), Error
=Error
> {
200 let mut req
= Self::request_builder(&self.server
, "GET", path
, None
).unwrap();
202 let login
= self.auth
.listen();
204 let client
= self.client
.clone();
206 login
.and_then(move |auth
| {
208 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
209 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
212 .map_err(Error
::from
)
215 let _status
= resp
.status(); // fixme: ??
218 .map_err(Error
::from
)
219 .for_each(move |chunk
| {
220 output
.write_all(&chunk
)?
;
228 pub fn upload(&mut self, content_type
: &str, body
: Body
, path
: &str) -> impl Future
<Item
=Value
, Error
=Error
> {
230 let path
= path
.trim_matches('
/'
);
231 let url
: Uri
= format
!("https://{}:8007/{}", &self.server
, path
).parse().unwrap();
233 let req
= Request
::builder()
236 .header("User-Agent", "proxmox-backup-client/1.0")
237 .header("Content-Type", content_type
)
238 .body(body
).unwrap();
245 &str, param
: Option
<Value
>
246 ) -> impl Future
<Item
=H2Client
, Error
=Error
> {
248 let mut req
= Self::request_builder(&self.server
, "GET", path
, param
).unwrap();
250 let login
= self.auth
.listen();
252 let client
= self.client
.clone();
254 login
.and_then(move |auth
| {
256 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
257 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
258 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str("proxmox-backup-protocol-h2").unwrap());
261 .map_err(Error
::from
)
264 let status
= resp
.status();
265 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
266 bail
!("h2upgrade failed with status {:?}", status
);
269 Ok(resp
.into_body().on_upgrade().map_err(Error
::from
))
272 .and_then(|upgraded
| {
273 h2
::client
::handshake(upgraded
).map_err(Error
::from
)
275 .and_then(|(h2
, connection
)| {
276 let connection
= connection
277 .map_err(|_
| panic
!("HTTP/2.0 connection failed"));
279 // Spawn a new task to drive the connection state
280 hyper
::rt
::spawn(connection
);
282 // Wait until the `SendRequest` handle has available capacity.
285 .map_err(Error
::from
)
291 client
: Client
<hyper_tls
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
295 ) -> Box
<Future
<Item
=AuthInfo
, Error
=Error
> + Send
> {
297 let server2
= server
.clone();
299 let create_request
= futures
::future
::lazy(move || {
300 let data
= json
!({ "username": username, "password": password }
);
301 let req
= Self::request_builder(&server
, "POST", "/api2/json/access/ticket", Some(data
)).unwrap();
302 Self::api_request(client
, req
)
305 let login_future
= create_request
306 .and_then(move |cred
| {
307 let auth
= AuthInfo
{
308 username
: cred
["data"]["username"].as_str().unwrap().to_owned(),
309 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
310 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
313 let _
= store_ticket_info(&server2
, &auth
.username
, &auth
.ticket
, &auth
.token
);
318 Box
::new(login_future
)
322 client
: Client
<hyper_tls
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
324 ) -> impl Future
<Item
=Value
, Error
=Error
> {
327 .map_err(Error
::from
)
330 let status
= resp
.status();
335 .map_err(Error
::from
)
336 .and_then(move |data
| {
338 let text
= String
::from_utf8(data
.to_vec()).unwrap();
339 if status
.is_success() {
341 let value
: Value
= serde_json
::from_str(&text
)?
;
347 bail
!("HTTP Error {}: {}", status
, text
);
353 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
354 let path
= path
.trim_matches('
/'
);
355 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
357 if let Some(data
) = data
{
358 if method
== "POST" {
359 let request
= Request
::builder()
362 .header("User-Agent", "proxmox-backup-client/1.0")
363 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
364 .body(Body
::from(data
.to_string()))?
;
367 let query
= tools
::json_object_to_query(data
)?
;
368 let url
: Uri
= format
!("https://{}:8007/{}?{}", server
, path
, query
).parse()?
;
369 let request
= Request
::builder()
372 .header("User-Agent", "proxmox-backup-client/1.0")
373 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
374 .body(Body
::empty())?
;
379 let request
= Request
::builder()
382 .header("User-Agent", "proxmox-backup-client/1.0")
383 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
384 .body(Body
::empty())?
;
391 pub struct H2Client
{
392 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
397 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
401 pub fn get(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
402 let req
= Self::request_builder("localhost", "GET", path
, param
).unwrap();
406 pub fn post(&self, path
: &str, param
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
407 let req
= Self::request_builder("localhost", "POST", path
, param
).unwrap();
411 pub fn upload(&self, path
: &str, param
: Option
<Value
>, data
: Vec
<u8>) -> impl Future
<Item
=Value
, Error
=Error
> {
412 let request
= Self::request_builder("localhost", "POST", path
, param
).unwrap();
416 .map_err(Error
::from
)
417 .and_then(move |mut send_request
| {
418 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
419 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
)
422 .map_err(Error
::from
)
423 .and_then(Self::h2api_response
)
430 request
: Request
<()>,
431 ) -> impl Future
<Item
=Value
, Error
=Error
> {
435 .map_err(Error
::from
)
436 .and_then(move |mut send_request
| {
437 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
439 .map_err(Error
::from
)
440 .and_then(Self::h2api_response
)
444 fn h2api_response(response
: Response
<h2
::RecvStream
>) -> impl Future
<Item
=Value
, Error
=Error
> {
446 let status
= response
.status();
448 let (_head
, mut body
) = response
.into_parts();
450 // The `release_capacity` handle allows the caller to manage
453 // Whenever data is received, the caller is responsible for
454 // releasing capacity back to the server once it has freed
455 // the data from memory.
456 let mut release_capacity
= body
.release_capacity().clone();
460 // Let the server send more data.
461 let _
= release_capacity
.release_capacity(chunk
.len());
465 .map_err(Error
::from
)
466 .and_then(move |data
| {
467 let text
= String
::from_utf8(data
.to_vec()).unwrap();
468 if status
.is_success() {
470 let mut value
: Value
= serde_json
::from_str(&text
)?
;
471 if let Some(map
) = value
.as_object_mut() {
472 if let Some(data
) = map
.remove("data") {
476 bail
!("got result without data property");
481 bail
!("HTTP Error {}: {}", status
, text
);
486 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<()>, Error
> {
487 let path
= path
.trim_matches('
/'
);
488 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
490 if let Some(data
) = data
{
491 let query
= tools
::json_object_to_query(data
)?
;
492 let url
: Uri
= format
!("https://{}:8007/{}?{}", server
, path
, query
).parse()?
;
493 let request
= Request
::builder()
496 .header("User-Agent", "proxmox-backup-client/1.0")
497 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
502 let request
= Request
::builder()
505 .header("User-Agent", "proxmox-backup-client/1.0")
506 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")