rustypaste 0.16.1

A minimal file upload/pastebin service
Documentation
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
use crate::config::Config;
use crate::file::Directory;
use crate::header::ContentDisposition;
use crate::util;
use actix_web::{error, Error};
use awc::Client;
use std::fs::{self, File};
use std::io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult, Write};
use std::path::{Path, PathBuf};
use std::str;
use std::sync::RwLock;
use std::{
    convert::{TryFrom, TryInto},
    ops::Add,
};
use url::Url;

/// Type of the data to store.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PasteType {
    /// Any type of file.
    File,
    /// A file that is on a remote URL.
    RemoteFile,
    /// A file that allowed to be accessed once.
    Oneshot,
    /// A file that only contains an URL.
    Url,
    /// A oneshot url.
    OneshotUrl,
}

impl<'a> TryFrom<&'a ContentDisposition> for PasteType {
    type Error = ();
    fn try_from(content_disposition: &'a ContentDisposition) -> Result<Self, Self::Error> {
        if content_disposition.has_form_field("file") {
            Ok(Self::File)
        } else if content_disposition.has_form_field("remote") {
            Ok(Self::RemoteFile)
        } else if content_disposition.has_form_field("oneshot") {
            Ok(Self::Oneshot)
        } else if content_disposition.has_form_field("oneshot_url") {
            Ok(Self::OneshotUrl)
        } else if content_disposition.has_form_field("url") {
            Ok(Self::Url)
        } else {
            Err(())
        }
    }
}

impl PasteType {
    /// Returns the corresponding directory of the paste type.
    pub fn get_dir(&self) -> String {
        match self {
            Self::File | Self::RemoteFile => String::new(),
            Self::Oneshot => String::from("oneshot"),
            Self::Url => String::from("url"),
            Self::OneshotUrl => String::from("oneshot_url"),
        }
    }

    /// Returns the given path with [`directory`](Self::get_dir) adjoined.
    pub fn get_path(&self, path: &Path) -> IoResult<PathBuf> {
        let dir = self.get_dir();
        if dir.is_empty() {
            Ok(path.to_path_buf())
        } else {
            util::safe_path_join(path, Path::new(&dir))
        }
    }

    /// Returns `true` if the variant is [`Oneshot`](Self::Oneshot).
    pub fn is_oneshot(&self) -> bool {
        self == &Self::Oneshot
    }
}

/// Representation of a single paste.
#[derive(Debug)]
pub struct Paste {
    /// Data to store.
    pub data: Vec<u8>,
    /// Type of the data.
    pub type_: PasteType,
}

impl Paste {
    /// Writes the bytes to a file in upload directory.
    ///
    /// - If `file_name` does not have an extension, it is replaced with [`default_extension`].
    /// - If `file_name` is "-", it is replaced with "stdin".
    /// - If [`random_url.enabled`] is `true`, `file_name` is replaced with a pet name or random string.
    /// - If `header_filename` is set, it will override the filename.
    ///
    /// [`default_extension`]: crate::config::PasteConfig::default_extension
    /// [`random_url.enabled`]: crate::random::RandomURLConfig::enabled
    pub fn store_file(
        &self,
        file_name: &str,
        expiry_date: Option<u128>,
        header_filename: Option<String>,
        config: &Config,
    ) -> Result<String, Error> {
        let file_type = infer::get(&self.data);
        if let Some(file_type) = file_type {
            for mime_type in &config.paste.mime_blacklist {
                if mime_type == file_type.mime_type() {
                    return Err(error::ErrorUnsupportedMediaType(
                        "this file type is not permitted",
                    ));
                }
            }
        }

        if let Some(max_dir_size) = config.server.max_upload_dir_size {
            let file_size = u64::try_from(self.data.len()).unwrap_or_default();
            let upload_dir = self.type_.get_path(&config.server.upload_path)?;
            let current_size_of_upload_dir = util::get_dir_size(&upload_dir).map_err(|e| {
                error::ErrorInternalServerError(format!("could not get directory size: {e}"))
            })?;
            let expected_size_of_upload_dir = current_size_of_upload_dir.add(file_size);
            if expected_size_of_upload_dir > max_dir_size {
                return Err(error::ErrorInsufficientStorage(
                    "upload directory size limit exceeded",
                ));
            }
        }

        let mut file_name = match PathBuf::from(file_name)
            .file_name()
            .and_then(|v| v.to_str())
        {
            Some("-") => String::from("stdin"),
            Some(".") => String::from("file"),
            Some(v) => v.to_string(),
            None => String::from("file"),
        };
        if let Some(handle_spaces_config) = config.server.handle_spaces {
            file_name = handle_spaces_config.process_filename(&file_name);
        }

        let mut path =
            util::safe_path_join(self.type_.get_path(&config.server.upload_path)?, &file_name)?;
        let mut parts: Vec<&str> = file_name.split('.').collect();
        let mut dotfile = false;
        let mut lower_bound = 1;
        let mut file_name = match parts[0] {
            "" => {
                // Index shifts one to the right in the array for the rest of the string (the extension)
                dotfile = true;
                lower_bound = 2;
                // If the first array element is empty, it means the file started with a dot (e.g.: .foo)
                format!(".{}", parts[1])
            }
            _ => parts[0].to_string(),
        };
        let mut extension = if parts.len() > lower_bound {
            // To get the rest (the extension), we have to remove the first element of the array, which is the filename
            parts.remove(0);
            if dotfile {
                // If the filename starts with a dot, we have to remove another element, because the first element was empty
                parts.remove(0);
            }
            parts.join(".")
        } else {
            file_type
                .map(|t| t.extension())
                .unwrap_or(&config.paste.default_extension)
                .to_string()
        };
        if let Some(random_url) = &config.paste.random_url {
            if let Some(random_text) = random_url.generate() {
                if let Some(suffix_mode) = random_url.suffix_mode {
                    if suffix_mode {
                        extension = format!("{}.{}", random_text, extension);
                    } else {
                        file_name = random_text;
                    }
                } else {
                    file_name = random_text;
                }
            }
        }
        path.set_file_name(file_name);
        path.set_extension(extension);
        if let Some(header_filename) = header_filename {
            file_name = header_filename;
            path.set_file_name(file_name);
        }
        let file_name = path
            .file_name()
            .map(|v| v.to_string_lossy())
            .unwrap_or_default()
            .to_string();
        let file_path = util::glob_match_file(path.clone())
            .map_err(|_| IoError::new(IoErrorKind::Other, String::from("path is not valid")))?;
        if file_path.is_file() && file_path.exists() {
            return Err(error::ErrorConflict("file already exists\n"));
        }
        if let Some(timestamp) = expiry_date {
            path.set_file_name(format!("{file_name}.{timestamp}"));
        }
        let mut buffer = File::create(&path)?;
        buffer.write_all(&self.data)?;
        Ok(file_name)
    }

    /// Downloads a file from URL and stores it with [`store_file`].
    ///
    /// - File name is inferred from URL if the last URL segment is a file.
    /// - Same content length configuration is applied for download limit.
    /// - Checks SHA256 digest of the downloaded file for preventing duplication.
    /// - Assumes `self.data` contains a valid URL, otherwise returns an error.
    ///
    /// [`store_file`]: Self::store_file
    pub async fn store_remote_file(
        &mut self,
        expiry_date: Option<u128>,
        client: &Client,
        config: &RwLock<Config>,
    ) -> Result<String, Error> {
        let data = str::from_utf8(&self.data).map_err(error::ErrorBadRequest)?;
        let url = Url::parse(data).map_err(error::ErrorBadRequest)?;
        let file_name = url
            .path_segments()
            .and_then(|segments| segments.last())
            .and_then(|name| if name.is_empty() { None } else { Some(name) })
            .unwrap_or("file");
        let mut response = client
            .get(url.as_str())
            .send()
            .await
            .map_err(error::ErrorInternalServerError)?;
        let payload_limit = config
            .read()
            .map_err(|_| error::ErrorInternalServerError("cannot acquire config"))?
            .server
            .max_content_length
            .try_into()
            .map_err(error::ErrorInternalServerError)?;
        let bytes = response
            .body()
            .limit(payload_limit)
            .await
            .map_err(error::ErrorInternalServerError)?
            .to_vec();
        let config = config
            .read()
            .map_err(|_| error::ErrorInternalServerError("cannot acquire config"))?;
        let bytes_checksum = util::sha256_digest(&*bytes)?;
        self.data = bytes;
        if !config.paste.duplicate_files.unwrap_or(true) && expiry_date.is_none() {
            if let Some(file) =
                Directory::try_from(config.server.upload_path.as_path())?.get_file(bytes_checksum)
            {
                return Ok(file
                    .path
                    .file_name()
                    .map(|v| v.to_string_lossy())
                    .unwrap_or_default()
                    .to_string());
            }
        }
        self.store_file(file_name, expiry_date, None, &config)
    }

    /// Writes an URL to a file in upload directory.
    ///
    /// - Checks if the data is a valid URL.
    /// - If [`random_url.enabled`] is `true`, file name is set to a pet name or random string.
    ///
    /// [`random_url.enabled`]: crate::random::RandomURLConfig::enabled
    #[allow(deprecated)]
    pub fn store_url(
        &self,
        expiry_date: Option<u128>,
        header_filename: Option<String>,
        config: &Config,
    ) -> IoResult<String> {
        let data = str::from_utf8(&self.data)
            .map_err(|e| IoError::new(IoErrorKind::Other, e.to_string()))?;
        let url = Url::parse(data).map_err(|e| IoError::new(IoErrorKind::Other, e.to_string()))?;
        let mut file_name = self.type_.get_dir();
        if let Some(random_url) = &config.paste.random_url {
            if let Some(random_text) = random_url.generate() {
                file_name = random_text;
            }
        }
        if let Some(header_filename) = header_filename {
            file_name = header_filename;
        }
        let mut path =
            util::safe_path_join(self.type_.get_path(&config.server.upload_path)?, &file_name)?;
        if let Some(timestamp) = expiry_date {
            path.set_file_name(format!("{file_name}.{timestamp}"));
        }
        fs::write(&path, url.to_string())?;
        Ok(file_name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::random::{RandomURLConfig, RandomURLType};
    use crate::util;
    use actix_web::web::Data;
    use awc::ClientBuilder;
    use byte_unit::Byte;
    use std::env;
    use std::str::FromStr;
    use std::time::Duration;

    #[actix_rt::test]
    #[allow(deprecated)]
    async fn test_paste_data() -> Result<(), Error> {
        let mut config = Config::default();
        config.server.upload_path = env::current_dir()?;
        config.paste.random_url = Some(RandomURLConfig {
            enabled: Some(true),
            words: Some(3),
            separator: Some(String::from("_")),
            type_: RandomURLType::PetName,
            ..RandomURLConfig::default()
        });
        let paste = Paste {
            data: vec![65, 66, 67],
            type_: PasteType::File,
        };
        let file_name = paste.store_file("test.txt", None, None, &config)?;
        assert_eq!("ABC", fs::read_to_string(&file_name)?);
        assert_eq!(
            Some("txt"),
            PathBuf::from(&file_name)
                .extension()
                .and_then(|v| v.to_str())
        );
        fs::remove_file(file_name)?;

        config.paste.random_url = Some(RandomURLConfig {
            length: Some(4),
            type_: RandomURLType::Alphanumeric,
            suffix_mode: Some(true),
            ..RandomURLConfig::default()
        });
        let paste = Paste {
            data: vec![116, 101, 115, 115, 117, 115],
            type_: PasteType::File,
        };
        let file_name = paste.store_file("foo.tar.gz", None, None, &config)?;
        assert_eq!("tessus", fs::read_to_string(&file_name)?);
        assert!(file_name.ends_with(".tar.gz"));
        assert!(file_name.starts_with("foo."));
        fs::remove_file(file_name)?;

        config.paste.random_url = Some(RandomURLConfig {
            length: Some(4),
            type_: RandomURLType::Alphanumeric,
            suffix_mode: Some(true),
            ..RandomURLConfig::default()
        });
        let paste = Paste {
            data: vec![116, 101, 115, 115, 117, 115],
            type_: PasteType::File,
        };
        let file_name = paste.store_file(".foo.tar.gz", None, None, &config)?;
        assert_eq!("tessus", fs::read_to_string(&file_name)?);
        assert!(file_name.ends_with(".tar.gz"));
        assert!(file_name.starts_with(".foo."));
        fs::remove_file(file_name)?;

        config.paste.random_url = Some(RandomURLConfig {
            length: Some(4),
            type_: RandomURLType::Alphanumeric,
            suffix_mode: Some(false),
            ..RandomURLConfig::default()
        });
        let paste = Paste {
            data: vec![116, 101, 115, 115, 117, 115],
            type_: PasteType::File,
        };
        let file_name = paste.store_file("foo.tar.gz", None, None, &config)?;
        assert_eq!("tessus", fs::read_to_string(&file_name)?);
        assert!(file_name.ends_with(".tar.gz"));
        fs::remove_file(file_name)?;

        config.paste.default_extension = String::from("txt");
        config.paste.random_url = None;
        let paste = Paste {
            data: vec![120, 121, 122],
            type_: PasteType::File,
        };
        let file_name = paste.store_file(".foo", None, None, &config)?;
        assert_eq!("xyz", fs::read_to_string(&file_name)?);
        assert_eq!(".foo.txt", file_name);
        fs::remove_file(file_name)?;

        config.paste.default_extension = String::from("bin");
        config.paste.random_url = Some(RandomURLConfig {
            length: Some(10),
            type_: RandomURLType::Alphanumeric,
            ..RandomURLConfig::default()
        });
        let paste = Paste {
            data: vec![120, 121, 122],
            type_: PasteType::File,
        };
        let file_name = paste.store_file("random", None, None, &config)?;
        assert_eq!("xyz", fs::read_to_string(&file_name)?);
        assert_eq!(
            Some("bin"),
            PathBuf::from(&file_name)
                .extension()
                .and_then(|v| v.to_str())
        );
        fs::remove_file(file_name)?;

        config.paste.random_url = Some(RandomURLConfig {
            length: Some(4),
            type_: RandomURLType::Alphanumeric,
            suffix_mode: Some(true),
            ..RandomURLConfig::default()
        });
        let paste = Paste {
            data: vec![116, 101, 115, 115, 117, 115],
            type_: PasteType::File,
        };
        let file_name = paste.store_file(
            "filename.txt",
            None,
            Some("fn_from_header.txt".to_string()),
            &config,
        )?;
        assert_eq!("tessus", fs::read_to_string(&file_name)?);
        assert_eq!("fn_from_header.txt", file_name);
        fs::remove_file(file_name)?;

        config.paste.random_url = Some(RandomURLConfig {
            length: Some(4),
            type_: RandomURLType::Alphanumeric,
            suffix_mode: Some(true),
            ..RandomURLConfig::default()
        });
        let paste = Paste {
            data: vec![116, 101, 115, 115, 117, 115],
            type_: PasteType::File,
        };
        let file_name = paste.store_file(
            "filename.txt",
            None,
            Some("fn_from_header".to_string()),
            &config,
        )?;
        assert_eq!("tessus", fs::read_to_string(&file_name)?);
        assert_eq!("fn_from_header", file_name);
        fs::remove_file(file_name)?;

        for paste_type in &[PasteType::Url, PasteType::Oneshot] {
            fs::create_dir_all(
                paste_type
                    .get_path(&config.server.upload_path)
                    .expect("Bad upload path"),
            )?;
        }

        config.paste.random_url = None;
        let paste = Paste {
            data: vec![116, 101, 115, 116],
            type_: PasteType::Oneshot,
        };
        let expiry_date = util::get_system_time()?.as_millis() + 100;
        let file_name = paste.store_file("test.file", Some(expiry_date), None, &config)?;
        let file_path = PasteType::Oneshot
            .get_path(&config.server.upload_path)
            .expect("Bad upload path")
            .join(format!("{file_name}.{expiry_date}"));
        assert_eq!("test", fs::read_to_string(&file_path)?);
        fs::remove_file(file_path)?;

        config.paste.random_url = Some(RandomURLConfig {
            enabled: Some(true),
            ..RandomURLConfig::default()
        });
        let url = String::from("https://orhun.dev/");
        let paste = Paste {
            data: url.as_bytes().to_vec(),
            type_: PasteType::Url,
        };
        let file_name = paste.store_url(None, None, &config)?;
        let file_path = PasteType::Url
            .get_path(&config.server.upload_path)
            .expect("Bad upload path")
            .join(&file_name);
        assert_eq!(url, fs::read_to_string(&file_path)?);
        fs::remove_file(file_path)?;

        let url = String::from("testurl.com");
        let paste = Paste {
            data: url.as_bytes().to_vec(),
            type_: PasteType::Url,
        };
        assert!(paste.store_url(None, None, &config).is_err());

        let url = String::from("https://orhun.dev/");
        let paste = Paste {
            data: url.as_bytes().to_vec(),
            type_: PasteType::Url,
        };
        let prepared_result = paste.store_url(None, Some("prepared-name".to_string()), &config)?;
        let file_path = PasteType::Url
            .get_path(&config.server.upload_path)
            .expect("Bad upload path")
            .join(&prepared_result);
        assert_eq!(prepared_result, "prepared-name");
        assert_eq!(url, fs::read_to_string(&file_path)?);
        fs::remove_file(file_path)?;

        config.server.max_content_length = Byte::from_str("30k").expect("cannot parse byte");
        let url = String::from("https://raw.githubusercontent.com/orhun/rustypaste/refs/heads/master/img/rp_test_3b5eeeee7a7326cd6141f54820e6356a0e9d1dd4021407cb1d5e9de9f034ed2f.png");
        let mut paste = Paste {
            data: url.as_bytes().to_vec(),
            type_: PasteType::RemoteFile,
        };
        let client_data = Data::new(
            ClientBuilder::new()
                .timeout(Duration::from_secs(30))
                .finish(),
        );
        let file_name = paste
            .store_remote_file(None, &client_data, &RwLock::new(config.clone()))
            .await?;
        let file_path = PasteType::RemoteFile
            .get_path(&config.server.upload_path)
            .expect("Bad upload path")
            .join(file_name);
        assert_eq!(
            "3b5eeeee7a7326cd6141f54820e6356a0e9d1dd4021407cb1d5e9de9f034ed2f",
            util::sha256_digest(&*paste.data)?
        );
        fs::remove_file(file_path)?;

        for paste_type in &[PasteType::Url, PasteType::Oneshot] {
            fs::remove_dir(
                paste_type
                    .get_path(&config.server.upload_path)
                    .expect("Bad upload path"),
            )?;
        }

        Ok(())
    }
}