1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use crate::{api, Error, Result};
use reqwest::{header, StatusCode};
use slog_scope::{debug, error};
use std::{
convert::{TryFrom, TryInto},
path::Path,
};
use tokio::{fs, io};
pub struct Client<'a> {
client: reqwest::Client,
server: &'a str,
}
pub async fn get<W>(url: &str, handle: &mut W) -> Result<()>
where
W: io::AsyncWrite + Unpin,
{
let url = reqwest::Url::parse(url)?;
save_body_to(reqwest::get(url).await?, handle).await
}
async fn save_body_to<W>(mut resp: reqwest::Response, handle: &mut W) -> Result<()>
where
W: io::AsyncWrite + Unpin,
{
use io::AsyncWriteExt;
use std::str::FromStr;
if !resp.status().is_success() {
return Err(Error::InvalidStatusResponse(resp.status()));
}
let mut written: f32 = 0.;
let mut threshold = 10;
let length = match resp.headers().get(header::CONTENT_LENGTH) {
Some(v) => usize::from_str(v.to_str()?)?,
None => 0,
};
while let Some(chunk) = resp.chunk().await? {
let read = chunk.len();
handle.write_all(&chunk).await?;
if length > 0 {
written += read as f32 / (length as f32 / 100.);
if written as usize >= threshold {
threshold += 20;
debug!("{}% of the file has been downloaded", std::cmp::min(written as usize, 100));
}
}
}
Ok(())
}
impl<'a> Client<'a> {
pub fn new(server: &'a str) -> Self {
let mut headers = header::HeaderMap::new();
headers.insert(header::USER_AGENT, header::HeaderValue::from_static("updatehub/2.0 Linux"));
headers.insert(header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"));
headers.insert(
"api-content-type",
header::HeaderValue::from_static("application/vnd.updatehub-v1+json"),
);
let client = reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(10))
.default_headers(headers)
.build()
.unwrap();
Self { server, client }
}
pub async fn probe(
&self,
num_retries: usize,
firmware: api::FirmwareMetadata<'_>,
) -> Result<api::ProbeResponse> {
reqwest::Url::parse(self.server)?;
let response = self
.client
.post(&format!("{}/upgrades", &self.server))
.header("api-retries", num_retries.to_string())
.json(&firmware)
.send()
.await?;
match response.status() {
StatusCode::NOT_FOUND => Ok(api::ProbeResponse::NoUpdate),
StatusCode::OK => {
match response
.headers()
.get("add-extra-poll")
.and_then(|extra_poll| extra_poll.to_str().ok())
.and_then(|extra_poll| extra_poll.parse().ok())
{
Some(extra_poll) => Ok(api::ProbeResponse::ExtraPoll(extra_poll)),
None => {
let signature = response
.headers()
.get("UH-Signature")
.map(TryInto::try_into)
.transpose()?;
Ok(api::ProbeResponse::Update(
api::UpdatePackage::parse(&response.bytes().await?)?,
signature,
))
}
}
}
s => Err(Error::InvalidStatusResponse(s)),
}
}
pub async fn download_object(
&self,
product_uid: &str,
package_uid: &str,
download_dir: &Path,
object: &str,
) -> Result<()> {
validate_url(self.server)?;
let mut request = self.client.get(&format!(
"{}/products/{}/packages/{}/objects/{}",
&self.server, product_uid, package_uid, object
));
if !download_dir.exists() {
fs::create_dir_all(download_dir).await.map_err(|e| {
error!("fail to create {:?} directory, error: {}", download_dir, e);
e
})?;
}
let file = download_dir.join(object);
if file.exists() {
request = request
.header("RANGE", format!("bytes={}-", file.metadata()?.len().saturating_sub(1)));
}
let mut file = fs::OpenOptions::new().create(true).append(true).open(&file).await?;
save_body_to(request.send().await?, &mut file).await
}
pub async fn report(
&self,
state: &str,
firmware: api::FirmwareMetadata<'_>,
package_uid: &str,
previous_state: Option<&str>,
error_message: Option<String>,
current_log: Option<String>,
) -> Result<()> {
validate_url(self.server)?;
#[derive(serde::Serialize)]
#[serde(rename_all = "kebab-case")]
struct Payload<'a> {
#[serde(rename = "status")]
state: &'a str,
#[serde(flatten)]
firmware: api::FirmwareMetadata<'a>,
package_uid: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
previous_state: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
error_message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
current_log: Option<String>,
}
let payload =
Payload { state, firmware, package_uid, previous_state, error_message, current_log };
self.client.post(&format!("{}/report", &self.server)).json(&payload).send().await?;
Ok(())
}
}
impl TryFrom<&header::HeaderValue> for api::Signature {
type Error = Error;
fn try_from(value: &header::HeaderValue) -> Result<Self> {
let value = value.to_str()?;
if value.is_empty() {
return Self::from_base64_str("");
}
Self::from_base64_str(value)
}
}
fn validate_url(url: &str) -> Result<()> {
url::Url::parse(url)?;
Ok(())
}