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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

/*! Debian source control files. */

use {
    crate::{
        control::{ControlParagraph, ControlParagraphReader},
        dependency::{DependencyList, PackageDependencyFields},
        error::{DebianError, Result},
        io::ContentDigest,
        package_version::PackageVersion,
        repository::release::ChecksumType,
    },
    std::{
        io::BufRead,
        ops::{Deref, DerefMut},
        str::FromStr,
    },
};

/// A single file as described by a `Files` or `Checksums-*` field in a [DebianSourceControlFile].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DebianSourceControlFileEntry<'a> {
    /// The filename/path.
    pub filename: &'a str,

    /// The content digest of this file.
    pub digest: ContentDigest,

    /// The size in bytes of the file.
    pub size: u64,
}

impl<'a> DebianSourceControlFileEntry<'a> {
    /// Convert this instance to a [DebianSourceControlFileFetch].
    ///
    /// The path in the fetch is prefixed with the given `directory` value. It usually
    /// comes from the `Directory` field of the control paragraph from which the entry was
    /// derived.
    pub fn as_fetch(&self, directory: &str) -> DebianSourceControlFileFetch {
        DebianSourceControlFileFetch {
            path: format!("{}/{}", directory, self.filename),
            digest: self.digest.clone(),
            size: self.size,
        }
    }
}

/// Describes a single binary package entry in a `Package-List` field in a [DebianSourceControlFile].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DebianSourceControlFilePackage<'a> {
    /// The name of the binary package.
    pub name: &'a str,
    /// The package type.
    pub package_type: &'a str,
    /// The section it appears in.
    pub section: &'a str,
    /// The package priority.
    pub priority: &'a str,
    /// Extra fields.
    pub extra: Vec<&'a str>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DebianSourceControlFileFetch {
    /// The path relative to the repository root to fetch.
    pub path: String,

    /// The digest of the file.
    pub digest: ContentDigest,

    /// The size of the file in bytes.
    pub size: u64,
}

/// A Debian source control file/paragraph.
///
/// This control file consists of a single paragraph and defines a source package.
/// This paragraph is typically found in `.dsc` files and in `Sources` files in repositories.
///
/// The fields are defined at
/// <https://www.debian.org/doc/debian-policy/ch-controlfields.html#debian-source-control-files-dsc>.
#[derive(Default)]
pub struct DebianSourceControlFile<'a> {
    paragraph: ControlParagraph<'a>,
    /// Parsed PGP signatures for this file.
    signatures: Option<pgp_cleartext::CleartextSignatures>,
}

impl<'a> Deref for DebianSourceControlFile<'a> {
    type Target = ControlParagraph<'a>;

    fn deref(&self) -> &Self::Target {
        &self.paragraph
    }
}

impl<'a> DerefMut for DebianSourceControlFile<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.paragraph
    }
}

impl<'a> From<ControlParagraph<'a>> for DebianSourceControlFile<'a> {
    fn from(paragraph: ControlParagraph<'a>) -> Self {
        Self {
            paragraph,
            signatures: None,
        }
    }
}

impl<'a> From<DebianSourceControlFile<'a>> for ControlParagraph<'a> {
    fn from(cf: DebianSourceControlFile<'a>) -> Self {
        cf.paragraph
    }
}

impl<'a> DebianSourceControlFile<'a> {
    /// Construct an instance by reading data from a reader.
    ///
    /// The source must be a Debian source control file with exactly 1 paragraph.
    ///
    /// The source must not be PGP armored (e.g. beginning with
    /// `-----BEGIN PGP SIGNED MESSAGE-----`). For PGP armored data, use
    /// [Self::from_armored_reader()].
    pub fn from_reader<R: BufRead>(reader: R) -> Result<Self> {
        let paragraphs = ControlParagraphReader::new(reader).collect::<Result<Vec<_>>>()?;

        if paragraphs.len() != 1 {
            return Err(DebianError::DebianSourceControlFileParagraphMismatch(
                paragraphs.len(),
            ));
        }

        let paragraph = paragraphs
            .into_iter()
            .next()
            .expect("validated paragraph count above");

        Ok(Self {
            paragraph,
            signatures: None,
        })
    }

    /// Construct an instance by reading data from a reader containing a PGP cleartext signature.
    ///
    /// This can be used to parse content from a `.dsc` file which begins
    /// with `-----BEGIN PGP SIGNED MESSAGE-----`.
    ///
    /// An error occurs if the PGP cleartext file is not well-formed or if a PGP parsing
    /// error occurs.
    ///
    /// The PGP signature is NOT validated. The file will be parsed despite lack of
    /// signature verification. This is conceptually insecure. But since Rust has memory
    /// safety, some risk is prevented.
    pub fn from_armored_reader<R: BufRead>(reader: R) -> Result<Self> {
        let reader = pgp_cleartext::CleartextSignatureReader::new(reader);
        let mut reader = std::io::BufReader::new(reader);

        let mut slf = Self::from_reader(&mut reader)?;
        slf.signatures = Some(reader.into_inner().finalize());

        Ok(slf)
    }

    /// Clone without preserving signatures data.
    pub fn clone_no_signatures(&self) -> Self {
        Self {
            paragraph: self.paragraph.clone(),
            signatures: None,
        }
    }

    /// Obtain PGP signatures from this possibly signed file.
    pub fn signatures(&self) -> Option<&pgp_cleartext::CleartextSignatures> {
        self.signatures.as_ref()
    }

    /// The format of the source package.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-format>.
    pub fn format(&self) -> Result<&str> {
        self.required_field_str("Format")
    }

    /// The name of the source package.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-source>.
    pub fn source(&self) -> Result<&str> {
        self.required_field_str("Source")
    }

    /// The binary packages this source package produces.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-binary>.
    pub fn binary(&self) -> Option<Box<(dyn Iterator<Item = &str> + '_)>> {
        self.iter_field_comma_delimited("Binary")
    }

    /// The architectures this source package will build for.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-architecture>.
    pub fn architecture(&self) -> Option<Box<(dyn Iterator<Item = &str> + '_)>> {
        self.iter_field_words("Architecture")
    }

    /// The version number of the package as a string.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-version>.
    pub fn version_str(&self) -> Result<&str> {
        self.required_field_str("Version")
    }

    /// The parsed version of the source package.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-version>.
    pub fn version(&self) -> Result<PackageVersion> {
        PackageVersion::parse(self.version_str()?)
    }

    /// The package maintainer.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-maintainer>.
    pub fn maintainer(&self) -> Result<&str> {
        self.required_field_str("Maintainer")
    }

    /// The list of uploaders and co-maintainers.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-uploaders>.
    pub fn uploaders(&self) -> Option<Box<(dyn Iterator<Item = &str> + '_)>> {
        self.iter_field_comma_delimited("Uploaders")
    }

    /// The URL from which the source of this package can be obtained.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-homepage>.
    pub fn homepage(&self) -> Option<&str> {
        self.field_str("Homepage")
    }

    /// Test suites.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-testsuite>.
    pub fn testsuite(&self) -> Option<Box<(dyn Iterator<Item = &str> + '_)>> {
        self.iter_field_comma_delimited("Testsuite")
    }

    /// Describes the Git source from which this package came.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-dgit>.
    pub fn dgit(&self) -> Option<&str> {
        self.field_str("Dgit")
    }

    /// The most recent version of the standards this package conforms to.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-standards-version>.
    pub fn standards_version(&self) -> Result<&str> {
        self.required_field_str("Standards-Version")
    }

    /// The `Depends` field, parsed to a [DependencyList].
    pub fn depends(&self) -> Option<Result<DependencyList>> {
        self.field_dependency_list("Depends")
    }

    /// The `Recommends` field, parsed to a [DependencyList].
    pub fn recommends(&self) -> Option<Result<DependencyList>> {
        self.field_dependency_list("Recommends")
    }

    /// The `Suggests` field, parsed to a [DependencyList].
    pub fn suggests(&self) -> Option<Result<DependencyList>> {
        self.field_dependency_list("Suggests")
    }

    /// The `Enhances` field, parsed to a [DependencyList].
    pub fn enhances(&self) -> Option<Result<DependencyList>> {
        self.field_dependency_list("Enhances")
    }

    /// The `Pre-Depends` field, parsed to a [DependencyList].
    pub fn pre_depends(&self) -> Option<Result<DependencyList>> {
        self.field_dependency_list("Pre-Depends")
    }

    /// Obtain parsed values of all fields defining dependencies.
    pub fn package_dependency_fields(&self) -> Result<PackageDependencyFields> {
        PackageDependencyFields::from_paragraph(self)
    }

    /// Packages that can be built from this source package.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-package-list>.
    pub fn package_list(
        &self,
    ) -> Option<Box<(dyn Iterator<Item = Result<DebianSourceControlFilePackage<'_>>> + '_)>> {
        if let Some(iter) = self.iter_field_lines("Package-List") {
            Some(Box::new(iter.map(move |v| {
                let mut words = v.split_ascii_whitespace();

                let name = words
                    .next()
                    .ok_or(DebianError::ControlPackageListMissingField("name"))?;
                let package_type = words
                    .next()
                    .ok_or(DebianError::ControlPackageListMissingField("type"))?;
                let section = words
                    .next()
                    .ok_or(DebianError::ControlPackageListMissingField("section"))?;
                let priority = words
                    .next()
                    .ok_or(DebianError::ControlPackageListMissingField("priority"))?;
                let extra = words.collect::<Vec<_>>();

                Ok(DebianSourceControlFilePackage {
                    name,
                    package_type,
                    section,
                    priority,
                    extra,
                })
            })))
        } else {
            None
        }
    }

    /// List of associated files with SHA-1 checksums.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-checksums>.
    pub fn checksums_sha1(
        &self,
    ) -> Option<Box<(dyn Iterator<Item = Result<DebianSourceControlFileEntry<'_>>> + '_)>> {
        self.iter_files("Checksums-Sha1", ChecksumType::Sha1)
    }

    /// List of associated files with SHA-256 checksums.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-checksums>.
    pub fn checksums_sha256(
        &self,
    ) -> Option<Box<(dyn Iterator<Item = Result<DebianSourceControlFileEntry<'_>>> + '_)>> {
        self.iter_files("Checksums-Sha256", ChecksumType::Sha256)
    }

    /// List of associated files with MD5 checksums.
    ///
    /// See <https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-files>.
    pub fn files(
        &self,
    ) -> Result<Box<(dyn Iterator<Item = Result<DebianSourceControlFileEntry<'_>>> + '_)>> {
        self.iter_files("Files", ChecksumType::Md5)
            .ok_or_else(|| DebianError::ControlRequiredFieldMissing("Files".to_string()))
    }

    fn iter_files(
        &self,
        field: &str,
        checksum: ChecksumType,
    ) -> Option<Box<(dyn Iterator<Item = Result<DebianSourceControlFileEntry<'_>>> + '_)>> {
        if let Some(iter) = self.iter_field_lines(field) {
            Some(Box::new(iter.map(move |v| {
                // Values are of form: <digest> <size> <path>

                let mut parts = v.split_ascii_whitespace();

                let digest = parts.next().ok_or(DebianError::ReleaseMissingDigest)?;
                let size = parts.next().ok_or(DebianError::ReleaseMissingSize)?;
                let filename = parts.next().ok_or(DebianError::ReleaseMissingPath)?;

                // Are paths with spaces allowed?
                if parts.next().is_some() {
                    return Err(DebianError::ReleasePathWithSpaces(v.to_string()));
                }

                let digest = ContentDigest::from_hex_digest(checksum, digest)?;
                let size = u64::from_str(size)?;

                Ok(DebianSourceControlFileEntry {
                    filename,
                    digest,
                    size,
                })
            })))
        } else {
            None
        }
    }

    /// Obtain [DebianSourceControlFileFetch] for a given digest variant.
    ///
    /// This obtains records that instruct how to fetch the files that compose this
    /// source package.
    pub fn file_fetches(
        &self,
        checksum: ChecksumType,
    ) -> Result<Box<(dyn Iterator<Item = Result<DebianSourceControlFileFetch>> + '_)>> {
        let entries = match checksum {
            ChecksumType::Md5 => self.files()?,
            ChecksumType::Sha1 => self.checksums_sha1().ok_or_else(|| {
                DebianError::ControlRequiredFieldMissing("Checksums-Sha1".to_string())
            })?,
            ChecksumType::Sha256 => self.checksums_sha256().ok_or_else(|| {
                DebianError::ControlRequiredFieldMissing("Checksums-Sha256".to_string())
            })?,
        };

        Ok(Box::new(entries.map(move |entry| {
            let entry = entry?;
            let directory = self.required_field_str("Directory")?;

            Ok(entry.as_fetch(directory))
        })))
    }
}

#[cfg(test)]
mod test {
    use super::*;

    const ZSTD_DSC: &[u8] = include_bytes!("testdata/libzstd_1.4.8+dfsg-3.dsc");

    #[test]
    fn parse_cleartext_armored() -> Result<()> {
        let cf = DebianSourceControlFile::from_armored_reader(std::io::Cursor::new(ZSTD_DSC))?;

        cf.signatures()
            .expect("PGP signatures should have been parsed");

        assert_eq!(cf.format()?, "3.0 (quilt)");
        assert_eq!(cf.source()?, "libzstd");
        assert_eq!(
            cf.binary().unwrap().collect::<Vec<_>>(),
            vec!["libzstd-dev", "libzstd1", "zstd", "libzstd1-udeb"]
        );
        assert_eq!(cf.architecture().unwrap().collect::<Vec<_>>(), vec!["any"]);
        assert_eq!(cf.version_str()?, "1.4.8+dfsg-3");
        assert_eq!(
            cf.maintainer()?,
            "Debian Med Packaging Team <debian-med-packaging@lists.alioth.debian.org>"
        );
        assert_eq!(
            cf.uploaders().unwrap().collect::<Vec<_>>(),
            vec![
                "Kevin Murray <kdmfoss@gmail.com>",
                "Olivier Sallou <osallou@debian.org>",
                "Alexandre Mestiashvili <mestia@debian.org>",
            ]
        );
        assert_eq!(cf.homepage(), Some("https://github.com/facebook/zstd"));
        assert_eq!(cf.standards_version()?, "4.6.0");
        assert_eq!(
            cf.testsuite().unwrap().collect::<Vec<_>>(),
            vec!["autopkgtest"]
        );
        assert_eq!(
            cf.package_list().unwrap().collect::<Result<Vec<_>>>()?,
            vec![
                DebianSourceControlFilePackage {
                    name: "libzstd-dev",
                    package_type: "deb",
                    section: "libdevel",
                    priority: "optional",
                    extra: vec!["arch=any"]
                },
                DebianSourceControlFilePackage {
                    name: "libzstd1",
                    package_type: "deb",
                    section: "libs",
                    priority: "optional",
                    extra: vec!["arch=any"]
                },
                DebianSourceControlFilePackage {
                    name: "libzstd1-udeb",
                    package_type: "udeb",
                    section: "debian-installer",
                    priority: "optional",
                    extra: vec!["arch=any"]
                },
                DebianSourceControlFilePackage {
                    name: "zstd",
                    package_type: "deb",
                    section: "utils",
                    priority: "optional",
                    extra: vec!["arch=any"]
                }
            ]
        );
        assert_eq!(
            cf.checksums_sha1().unwrap().collect::<Result<Vec<_>>>()?,
            vec![
                DebianSourceControlFileEntry {
                    filename: "libzstd_1.4.8+dfsg.orig.tar.xz",
                    digest: ContentDigest::sha1_hex("a24e4ccf9fc356aeaaa0783316a26bd65817c354")?,
                    size: 1331996,
                },
                DebianSourceControlFileEntry {
                    filename: "libzstd_1.4.8+dfsg-3.debian.tar.xz",
                    digest: ContentDigest::sha1_hex("896a47a2934d0fcf9faa8397d05a12b932697d1f")?,
                    size: 12184,
                }
            ]
        );
        assert_eq!(
            cf.checksums_sha256().unwrap().collect::<Result<Vec<_>>>()?,
            vec![
                DebianSourceControlFileEntry {
                    filename: "libzstd_1.4.8+dfsg.orig.tar.xz",
                    digest: ContentDigest::sha256_hex(
                        "1e8ce5c4880a6d5bd8d3186e4186607dd19b64fc98a3877fc13aeefd566d67c5"
                    )?,
                    size: 1331996,
                },
                DebianSourceControlFileEntry {
                    filename: "libzstd_1.4.8+dfsg-3.debian.tar.xz",
                    digest: ContentDigest::sha256_hex(
                        "fecd87a469d5a07b6deeeef53ed24b2f1a74ee097ce11528fe3b58540f05c147"
                    )?,
                    size: 12184,
                }
            ]
        );
        assert_eq!(
            cf.files().unwrap().collect::<Result<Vec<_>>>()?,
            vec![
                DebianSourceControlFileEntry {
                    filename: "libzstd_1.4.8+dfsg.orig.tar.xz",
                    digest: ContentDigest::md5_hex("943bed8b8d98a50c8d8a101b12693bb4")?,
                    size: 1331996,
                },
                DebianSourceControlFileEntry {
                    filename: "libzstd_1.4.8+dfsg-3.debian.tar.xz",
                    digest: ContentDigest::md5_hex("4d2692830e1f481ce769e2dd24cbc9db")?,
                    size: 12184,
                }
            ]
        );

        Ok(())
    }
}