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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
extern crate chrono;
extern crate regex;

use self::chrono::{DateTime, Duration, Utc};
use self::regex::Regex;
use url::{ParseError as UrlParseError, Url};
use url_serde;

use crate::api::url::UrlBuilder;
use crate::config::SEND_DEFAULT_EXPIRE_TIME;
use crate::crypto::b64;

/// A pattern for share URL paths, capturing the file ID.
// TODO: match any sub-path?
// TODO: match URL-safe base64 chars for the file ID?
// TODO: constrain the ID length?
const SHARE_PATH_PATTERN: &str = r"^/?download/([[:alnum:]]{8,}={0,3})/?$";

/// A pattern for share URL fragments, capturing the file secret.
// TODO: constrain the secret length?
const SHARE_FRAGMENT_PATTERN: &str = r"^([a-zA-Z0-9-_+/]+)?\s*$";

/// A struct representing an uploaded file on a Send host.
///
/// The struct contains the file ID, the file URL, the key that is required
/// in combination with the file, and the owner key.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RemoteFile {
    /// The ID of the file on that server.
    id: String,

    /// The time the file was uploaded at, if known.
    upload_at: Option<DateTime<Utc>>,

    /// The time the file will expire at.
    expire_at: DateTime<Utc>,

    /// Define whether the expiry time is uncertain.
    expire_uncertain: bool,

    /// The host the file was uploaded to.
    #[serde(with = "url_serde")]
    host: Url,

    /// The file URL that was provided by the server.
    #[serde(with = "url_serde")]
    url: Url,

    /// The secret key that is required to download the file.
    secret: Vec<u8>,

    /// The owner key, that can be used to manage the file on the server.
    owner_token: Option<String>,
}

impl RemoteFile {
    /// Construct a new file.
    pub fn new(
        id: String,
        upload_at: Option<DateTime<Utc>>,
        expire_at: Option<DateTime<Utc>>,
        host: Url,
        url: Url,
        secret: Vec<u8>,
        owner_token: Option<String>,
    ) -> Self {
        // Assign the default expiry time if uncetain
        let expire_uncertain = expire_at.is_none();
        let expire_at =
            expire_at.unwrap_or(Utc::now() + Duration::seconds(SEND_DEFAULT_EXPIRE_TIME as i64));

        // Build the object
        Self {
            id,
            upload_at,
            expire_at,
            expire_uncertain,
            host,
            url,
            secret,
            owner_token,
        }
    }

    /// Construct a new file, that was created at this exact time.
    /// This will set the file expiration time
    pub fn new_now(
        id: String,
        host: Url,
        url: Url,
        secret: Vec<u8>,
        owner_token: Option<String>,
    ) -> Self {
        // Get the current time
        let now = Utc::now();
        let expire_at = now + Duration::seconds(SEND_DEFAULT_EXPIRE_TIME as i64);

        // Construct and return
        Self::new(
            id,
            Some(now),
            Some(expire_at),
            host,
            url,
            secret,
            owner_token,
        )
    }

    /// Try to parse the given share URL.
    ///
    /// The given URL is matched against a share URL pattern,
    /// this does not check whether the host is a valid and online host.
    ///
    /// If the URL fragmet contains a file secret, it is also parsed.
    /// If it does not, the secret is left empty and must be specified
    /// manually.
    ///
    /// An optional owner token may be given.
    pub fn parse_url(url: Url, owner_token: Option<String>) -> Result<RemoteFile, FileParseError> {
        // Build the host
        let mut host = url.clone();
        host.set_fragment(None);
        host.set_query(None);
        host.set_path("");

        // Validate the path, get the file ID
        let re_path = Regex::new(SHARE_PATH_PATTERN).unwrap();
        let id = re_path
            .captures(url.path())
            .ok_or(FileParseError::InvalidUrl)?[1]
            .trim()
            .to_owned();

        // Get the file secret
        let mut secret = Vec::new();
        if let Some(fragment) = url.fragment() {
            let re_fragment = Regex::new(SHARE_FRAGMENT_PATTERN).unwrap();
            if let Some(raw) = re_fragment
                .captures(fragment)
                .ok_or(FileParseError::InvalidSecret)?
                .get(1)
            {
                secret =
                    b64::decode(raw.as_str().trim()).map_err(|_| FileParseError::InvalidSecret)?
            }
        }

        // Construct the file
        Ok(Self::new(id, None, None, host, url, secret, owner_token))
    }

    /// Get the file ID.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get the time the file will expire after.
    /// Note that this time may not be correct as it may have been guessed,
    /// see `expire_uncertain()`.
    pub fn expire_at(&self) -> DateTime<Utc> {
        self.expire_at
    }

    /// Get the duration the file will expire after.
    /// Note that this time may not be correct as it may have been guessed,
    /// see `expire_uncertain()`.
    pub fn expire_duration(&self) -> Duration {
        // Get the current time
        let now = Utc::now();

        // Return the duration if not expired, otherwise return zero
        if self.expire_at > now {
            self.expire_at - now
        } else {
            Duration::zero()
        }
    }

    /// Set the time this file will expire at.
    /// None may be given to assign the default expiry time with the
    /// uncertainty flag set.
    pub fn set_expire_at(&mut self, expire_at: Option<DateTime<Utc>>) {
        if let Some(expire_at) = expire_at {
            self.expire_at = expire_at;
        } else {
            self.expire_at = Utc::now() + Duration::seconds(SEND_DEFAULT_EXPIRE_TIME as i64);
            self.expire_uncertain = true;
        }
    }

    /// Set the time this file will expire at,
    /// based on the given duration from now.
    pub fn set_expire_duration(&mut self, duration: Duration) {
        self.set_expire_at(Some(Utc::now() + duration));
    }

    /// Check whether this file has expired, based on it's expiry property.
    pub fn has_expired(&self) -> bool {
        self.expire_at < Utc::now()
    }

    /// Check whehter the set expiry time is uncertain.
    /// If the expiry time of a file is unknown,
    /// the default time is assigned from the first time
    /// the file was used. Such time will be uncertain as it probably isn't
    /// correct.
    /// This time may be used however to check for expiry.
    pub fn expire_uncertain(&self) -> bool {
        self.expire_uncertain
    }

    /// Get the file URL, provided by the server.
    pub fn url(&self) -> &Url {
        &self.url
    }

    /// Get the raw secret.
    // TODO: ensure whether the secret is set?
    pub fn secret_raw(&self) -> &Vec<u8> {
        &self.secret
    }

    /// Get the secret as base64 encoded string.
    pub fn secret(&self) -> String {
        b64::encode(self.secret_raw())
    }

    /// Set the secret for this file.
    pub fn set_secret(&mut self, secret: Vec<u8>) {
        self.secret = secret;
    }

    /// Check whether a file secret is set.
    /// This secret must be set to decrypt a downloaded Send file.
    pub fn has_secret(&self) -> bool {
        !self.secret.is_empty()
    }

    /// Get the owner token if set.
    pub fn owner_token(&self) -> Option<&String> {
        self.owner_token.as_ref()
    }

    /// Get the owner token if set.
    pub fn owner_token_mut(&mut self) -> &mut Option<String> {
        &mut self.owner_token
    }

    /// Set the owner token, wrapped in an option.
    /// If `None` is given, the owner token will be unset.
    pub fn set_owner_token(&mut self, token: Option<String>) {
        self.owner_token = token;
    }

    /// Check whether an owner token is set in this remote file.
    pub fn has_owner_token(&self) -> bool {
        self.owner_token
            .clone()
            .map(|t| !t.is_empty())
            .unwrap_or(false)
    }

    /// Get the host URL for this remote file.
    pub fn host(&self) -> Url {
        self.host.clone()
    }

    /// Build the download URL of the given file.
    /// This URL is identical to the share URL, a term used in this API.
    /// Set `secret` to `true`, to include it in the URL if known.
    pub fn download_url(&self, secret: bool) -> Url {
        UrlBuilder::download(&self, secret)
    }

    /// Merge properties non-existant into this file, from the given other file.
    /// This is ofcourse only done for properties that may be empty.
    ///
    /// The file IDs are not asserted for equality.
    #[allow(unknown_lints)]
    pub fn merge(&mut self, other: &RemoteFile, overwrite: bool) -> bool {
        // Remember whether anything has changed
        let mut changed = false;

        // Set the upload time
        if other.upload_at.is_some() && (self.upload_at.is_none() || overwrite) {
            self.upload_at = other.upload_at;
            changed = true;
        }

        // Set the expire time
        if !other.expire_uncertain() && (self.expire_uncertain() || overwrite) {
            self.expire_at = other.expire_at;
            self.expire_uncertain = other.expire_uncertain();
            changed = true;
        }

        // Set the secret
        if other.has_secret() && (!self.has_secret() || overwrite) {
            self.secret = other.secret_raw().clone();
            changed = true;
        }

        // Set the owner token
        if other.owner_token.is_some() && (self.owner_token.is_none() || overwrite) {
            self.owner_token = other.owner_token.clone();
            changed = true;
        }

        changed
    }
}

#[derive(Debug, Fail)]
pub enum FileParseError {
    /// An URL format error.
    #[fail(display = "failed to parse remote file, invalid URL format")]
    UrlFormatError(#[cause] UrlParseError),

    /// An error for an invalid share URL format.
    #[fail(display = "failed to parse remote file, invalid URL")]
    InvalidUrl,

    /// An error for an invalid secret format, if an URL fragmet exists.
    #[fail(display = "failed to parse remote file, invalid secret in URL")]
    InvalidSecret,
}