5 use hyper
::client
::Client
;
6 use xdg
::BaseDirectories
;
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}
;
27 /// HTTP(S) API client
28 pub struct HttpClient
{
29 client
: Client
<hyper_tls
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
31 auth
: BroadcastFuture
<AuthInfo
>,
34 fn store_ticket_info(server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
36 let base
= BaseDirectories
::with_prefix("proxmox-backup")?
;
38 // usually /run/user/<uid>/...
39 let path
= base
.place_runtime_file("tickets")?
;
41 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
43 let mut data
= tools
::file_get_json(&path
, Some(json
!({}
)))?
;
45 let now
= Utc
::now().timestamp();
47 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
49 let mut new_data
= json
!({}
);
51 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
53 let empty
= serde_json
::map
::Map
::new();
54 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
55 for (_user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
56 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
57 let age
= now
- timestamp
;
58 if age
< ticket_lifetime
{
59 new_data
[server
][username
] = uinfo
.clone();
65 tools
::file_set_contents(path
, new_data
.to_string().as_bytes(), Some(mode
))?
;
70 fn load_ticket_info(server
: &str, username
: &str) -> Option
<(String
, String
)> {
71 let base
= match BaseDirectories
::with_prefix("proxmox-backup") {
76 // usually /run/user/<uid>/...
77 let path
= match base
.place_runtime_file("tickets") {
82 let data
= match tools
::file_get_json(&path
, None
) {
87 let now
= Utc
::now().timestamp();
89 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
91 if let Some(uinfo
) = data
[server
][username
].as_object() {
92 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
93 let age
= now
- timestamp
;
94 if age
< ticket_lifetime
{
95 let ticket
= match uinfo
["ticket"].as_str() {
99 let token
= match uinfo
["token"].as_str() {
103 return Some((ticket
.to_owned(), token
.to_owned()));
113 pub fn new(server
: &str, username
: &str) -> Result
<Self, Error
> {
114 let client
= Self::build_client();
116 let password
= if let Some((ticket
, _token
)) = load_ticket_info(server
, username
) {
119 Self::get_password(&username
)?
122 let login
= Self::credentials(client
.clone(), server
.to_owned(), username
.to_owned(), password
);
126 server
: String
::from(server
),
127 auth
: BroadcastFuture
::new(login
),
131 fn get_password(_username
: &str) -> Result
<String
, Error
> {
132 use std
::env
::VarError
::*;
133 match std
::env
::var("PBS_PASSWORD") {
134 Ok(p
) => return Ok(p
),
135 Err(NotUnicode(_
)) => bail
!("PBS_PASSWORD contains bad characters"),
137 // Try another method
141 // If we're on a TTY, query the user for a password
142 if tty
::stdin_isatty() {
143 return Ok(String
::from_utf8(tty
::read_password("Password: ")?
)?
);
146 bail
!("no password input mechanism available");
149 fn build_client() -> Client
<hyper_tls
::HttpsConnector
<hyper
::client
::HttpConnector
>> {
150 let mut builder
= native_tls
::TlsConnector
::builder();
151 // FIXME: We need a CLI option for this!
152 builder
.danger_accept_invalid_certs(true);
153 let tlsconnector
= builder
.build().unwrap();
154 let mut httpc
= hyper
::client
::HttpConnector
::new(1);
155 httpc
.enforce_http(false); // we want https...
156 let mut https
= hyper_tls
::HttpsConnector
::from((httpc
, tlsconnector
));
157 https
.https_only(true); // force it!
158 Client
::builder().build
::<_
, Body
>(https
)
161 pub fn request(&self, mut req
: Request
<Body
>) -> impl Future
<Item
=Value
, Error
=Error
> {
163 let login
= self.auth
.listen();
165 let client
= self.client
.clone();
167 login
.and_then(move |auth
| {
169 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
170 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
171 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
173 let request
= Self::api_request(client
, req
);
179 pub fn get(&self, path
: &str) -> impl Future
<Item
=Value
, Error
=Error
> {
181 let req
= Self::request_builder(&self.server
, "GET", path
, None
).unwrap();
185 pub fn delete(&mut self, path
: &str) -> impl Future
<Item
=Value
, Error
=Error
> {
187 let req
= Self::request_builder(&self.server
, "DELETE", path
, None
).unwrap();
191 pub fn post(&mut self, path
: &str, data
: Option
<Value
>) -> impl Future
<Item
=Value
, Error
=Error
> {
193 let req
= Self::request_builder(&self.server
, "POST", path
, data
).unwrap();
197 pub fn download(&mut self, path
: &str, mut output
: Box
<dyn std
::io
::Write
+ Send
>) -> impl Future
<Item
=(), Error
=Error
> {
199 let mut req
= Self::request_builder(&self.server
, "GET", path
, None
).unwrap();
201 let login
= self.auth
.listen();
203 let client
= self.client
.clone();
205 login
.and_then(move |auth
| {
207 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
208 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
211 .map_err(Error
::from
)
214 let _status
= resp
.status(); // fixme: ??
217 .map_err(Error
::from
)
218 .for_each(move |chunk
| {
219 output
.write_all(&chunk
)?
;
227 pub fn upload(&mut self, content_type
: &str, body
: Body
, path
: &str) -> impl Future
<Item
=Value
, Error
=Error
> {
229 let path
= path
.trim_matches('
/'
);
230 let url
: Uri
= format
!("https://{}:8007/{}", &self.server
, path
).parse().unwrap();
232 let req
= Request
::builder()
235 .header("User-Agent", "proxmox-backup-client/1.0")
236 .header("Content-Type", content_type
)
237 .body(body
).unwrap();
242 pub fn h2upgrade(&mut self, path
: &str) -> impl Future
<Item
=h2
::client
::SendRequest
<bytes
::Bytes
>, Error
=Error
> {
244 let mut req
= Self::request_builder(&self.server
, "GET", path
, None
).unwrap();
246 let login
= self.auth
.listen();
248 let client
= self.client
.clone();
250 login
.and_then(move |auth
| {
252 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
253 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
254 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str("proxmox-backup-protocol-h2").unwrap());
257 .map_err(Error
::from
)
260 let status
= resp
.status();
261 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
262 bail
!("h2upgrade failed with status {:?}", status
);
265 Ok(resp
.into_body().on_upgrade().map_err(Error
::from
))
268 .and_then(|upgraded
| {
269 println
!("upgraded");
271 h2
::client
::handshake(upgraded
).map_err(Error
::from
)
273 .and_then(|(h2
, connection
)| {
274 let connection
= connection
275 .map_err(|_
| panic
!("HTTP/2.0 connection failed"));
277 // Spawn a new task to drive the connection state
278 hyper
::rt
::spawn(connection
);
280 // Wait until the `SendRequest` handle has available capacity.
281 h2
.ready().map_err(Error
::from
)
287 client
: Client
<hyper_tls
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
291 ) -> Box
<Future
<Item
=AuthInfo
, Error
=Error
> + Send
> {
293 let server2
= server
.clone();
295 let create_request
= futures
::future
::lazy(move || {
296 let data
= json
!({ "username": username, "password": password }
);
297 let req
= Self::request_builder(&server
, "POST", "/api2/json/access/ticket", Some(data
)).unwrap();
298 Self::api_request(client
, req
)
301 let login_future
= create_request
302 .and_then(move |cred
| {
303 let auth
= AuthInfo
{
304 username
: cred
["data"]["username"].as_str().unwrap().to_owned(),
305 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
306 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
309 let _
= store_ticket_info(&server2
, &auth
.username
, &auth
.ticket
, &auth
.token
);
314 Box
::new(login_future
)
318 client
: Client
<hyper_tls
::HttpsConnector
<hyper
::client
::HttpConnector
>>,
320 ) -> impl Future
<Item
=Value
, Error
=Error
> {
323 .map_err(Error
::from
)
326 let status
= resp
.status();
331 .map_err(Error
::from
)
332 .and_then(move |data
| {
334 let text
= String
::from_utf8(data
.to_vec()).unwrap();
335 if status
.is_success() {
337 let value
: Value
= serde_json
::from_str(&text
)?
;
343 bail
!("HTTP Error {}: {}", status
, text
);
349 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
350 let path
= path
.trim_matches('
/'
);
351 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
353 if let Some(data
) = data
{
354 if method
== "POST" {
355 let request
= Request
::builder()
358 .header("User-Agent", "proxmox-backup-client/1.0")
359 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
360 .body(Body
::from(data
.to_string()))?
;
368 let request
= Request
::builder()
371 .header("User-Agent", "proxmox-backup-client/1.0")
372 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
373 .body(Body
::empty())?
;