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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// Copyright (C) 2020 O.S. Systems Sofware LTDA
//
// SPDX-License-Identifier: Apache-2.0

use crate::{api, Error, Result};
use async_std::{fs, io};
use slog_scope::{debug, error};
use std::{
    convert::{TryFrom, TryInto},
    path::Path,
};
use surf::{
    http::headers,
    middleware::{self, Middleware},
    Body, Request, Response, StatusCode,
};

struct Api;

#[surf::utils::async_trait]
impl Middleware for Api {
    async fn handle(
        &self,
        mut req: Request,
        client: surf::Client,
        next: middleware::Next<'_>,
    ) -> surf::Result<Response> {
        req.insert_header(headers::USER_AGENT, "updatehub/2.0 Linux");
        req.insert_header(headers::CONTENT_TYPE, "application/json");
        req.insert_header("api-content-type", "application/vnd.updatehub-v1+json");
        Ok(next.run(req, client).await?)
    }
}

pub struct Client<'a> {
    client: surf::Client,
    server: &'a str,
}

pub async fn get<W>(url: &str, handle: &mut W) -> Result<()>
where
    W: io::Write + Unpin,
{
    validate_url(url)?;
    save_body_to(surf::get(url), handle).await
}

async fn save_body_to<W>(req: surf::RequestBuilder, handle: &mut W) -> Result<()>
where
    W: io::Write + Unpin,
{
    use io::prelude::{ReadExt, WriteExt};
    use std::str::FromStr;

    let mut rep = req.await?;
    if !rep.status().is_success() {
        return Err(Error::InvalidStatusResponse(rep.status()));
    }

    let mut written: f32 = 0.;
    let mut threshold = 10;
    let length = match rep.header(headers::CONTENT_LENGTH) {
        Some(v) => usize::from_str(v.as_str())?,
        None => 0,
    };

    loop {
        let mut buf = [0; 4096];
        let read = rep.read(&mut buf).await?;
        if read == 0 {
            break;
        }
        handle.write_all(&buf[..read]).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));
            }
        }
    }
    debug!("100% of the file has been downloaded");

    Ok(())
}

impl<'a> Client<'a> {
    pub fn new(server: &'a str) -> Self {
        // Manually build inner clients since surf doesn't
        // yet support timout config for client
        // https://github.com/http-rs/surf/issues/274
        use isahc::config::Configurable;
        let duration = std::time::Duration::from_secs(10);
        let client = isahc::HttpClient::builder().connect_timeout(duration).build().unwrap();
        let client = http_client::isahc::IsahcClient::from_client(client);
        let client = surf::Client::with_http_client(client);

        Self { server, client: client.with(Api) }
    }

    pub async fn probe(
        &self,
        num_retries: usize,
        firmware: api::FirmwareMetadata<'_>,
    ) -> Result<api::ProbeResponse> {
        validate_url(self.server)?;

        let mut response = self
            .client
            .post(&format!("{}/upgrades", &self.server))
            .header("api-retries", num_retries.to_string())
            .body(Body::from_json(&firmware)?)
            .await?;

        match response.status() {
            StatusCode::NotFound => Ok(api::ProbeResponse::NoUpdate),
            StatusCode::Ok => {
                match response
                    .header("add-extra-poll")
                    .map(|extra_poll| extra_poll.as_str())
                    .and_then(|extra_poll| extra_poll.parse().ok())
                {
                    Some(extra_poll) => Ok(api::ProbeResponse::ExtraPoll(extra_poll)),
                    None => {
                        let signature =
                            response.header("UH-Signature").map(TryInto::try_into).transpose()?;
                        Ok(api::ProbeResponse::Update(
                            api::UpdatePackage::parse(&response.body_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)?;

        // FIXME: Discuss the need of packages inside the route
        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, &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))
            .body(Body::from_json(&payload)?)
            .await?;
        Ok(())
    }
}

impl TryFrom<&headers::HeaderValues> for api::Signature {
    type Error = Error;

    fn try_from(value: &headers::HeaderValues) -> Result<Self> {
        let value = value.as_str();

        // Workarround for https://github.com/sfackler/rust-openssl/issues/1325
        if value.is_empty() {
            return Self::from_base64_str("");
        }

        Self::from_base64_str(value)
    }
}

fn validate_url(url: &str) -> surf::Result<()> {
    surf::http::Url::parse(url)?;
    Ok(())
}