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
//! A collection of types used in various header records.
use crate::{constants::*, errors};

/// Describes a file present in the rpm file.
pub struct RPMFileEntry {
    pub(crate) size: i32,
    pub(crate) mode: FileMode,
    pub(crate) modified_at: i32,
    pub(crate) sha_checksum: String,
    pub(crate) link: String,
    pub(crate) flag: i32,
    pub(crate) user: String,
    pub(crate) group: String,
    pub(crate) base_name: String,
    pub(crate) dir: String,
    pub(crate) content: Option<Vec<u8>>,
}

#[non_exhaustive]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum FileMode {
    // It does not really matter if we use u16 or i16 since all we care about
    // is the bit representation which is the same for both.
    Dir { permissions: u16 },
    Regular { permissions: u16 },
    // For "Invalid" we use a larger integer since it is possible to create an invalid
    // FileMode by providing an overflowing integer.
    Invalid { raw_mode: i32, reason: &'static str },
}

// there are more file types but in the context of RPM, only regular and directory should be relevant.
// See https://man7.org/linux/man-pages/man7/inode.7.html section "The file type and mode"
const FILE_TYPE_BIT_MASK: u16 = 0o170000; // bit representation = "1111000000000000"
const PERMISSIONS_BIT_MASK: u16 = 0o7777; // bit representation = "0000111111111111"
const REGULAR_FILE_TYPE: u16 = 0o100000; //  bit representation = "1000000000000000"
const DIR_FILE_TYPE: u16 = 0o040000; //      bit representation = "0100000000000000"

impl From<u16> for FileMode {
    fn from(raw_mode: u16) -> Self {
        // example
        //  1111000000000000  (0o170000)  <- file type bit mask
        // &1000000111101101  (0o100755)  <- regular executable file
        // -----------------------------
        //  1000000000000000  (0o100000)  <- type for regular files
        //
        // we effectively extract the file type bits with an AND operation.
        // Here are two links for a quick refresh:
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND
        // https://en.wikipedia.org/wiki/Bitwise_operation#AND
        let file_type = raw_mode & FILE_TYPE_BIT_MASK;
        let permissions = raw_mode & PERMISSIONS_BIT_MASK;
        match file_type {
            DIR_FILE_TYPE => FileMode::Dir { permissions },
            REGULAR_FILE_TYPE => FileMode::Regular { permissions },
            _ => FileMode::Invalid {
                raw_mode: raw_mode as i32,
                reason: "unknown file type",
            },
        }
    }
}

impl From<i16> for FileMode {
    fn from(raw: i16) -> Self {
        Self::from(raw as u16)
    }
}

impl From<i32> for FileMode {
    fn from(raw_mode: i32) -> Self {
        // since we ultimatively only deal with 16bit integers
        // we need to check if a safe convertion to 16bit is doable.
        if raw_mode > u16::MAX.into() || raw_mode < i16::MIN.into() {
            FileMode::Invalid {
                raw_mode,
                reason: "provided integer is out of 16bit bounds",
            }
        } else {
            FileMode::from(raw_mode as u16)
        }
    }
}

impl FileMode {
    /// Create a new Regular instance. `permissions` can be between 0 and 0o7777. Values greater will be set to 0o7777.
    pub fn regular(permissions: u16) -> Self {
        FileMode::Regular {
            permissions: permissions & PERMISSIONS_BIT_MASK,
        }
    }

    /// Create a new Dir instance. `permissions` can be between 0 and 0o7777. Values greater will be set to 0o7777.
    pub fn dir(permissions: u16) -> Self {
        FileMode::Dir {
            permissions: permissions & PERMISSIONS_BIT_MASK,
        }
    }

    /// Usually this should be done with TryFrom, but since we already have a `From` implementation,
    /// we run into this issue: https://github.com/rust-lang/rust/issues/50133
    pub fn try_from_raw(raw: i32) -> Result<Self, errors::RPMError> {
        let mode: FileMode = raw.into();
        mode.to_result()
    }

    /// Turns this FileMode into a result. If the mode is Invalid, it will be converted into
    /// RPMError::InvalidFileMode. Otherwise it is Ok(self).
    pub fn to_result(self) -> Result<Self, errors::RPMError> {
        match self {
            Self::Invalid { raw_mode, reason } => {
                Err(errors::RPMError::InvalidFileMode { raw_mode, reason })
            }
            _ => Ok(self),
        }
    }

    /// Returns the complete file mode (type and permissions)
    pub fn raw_mode(&self) -> u16 {
        match self {
            Self::Dir { permissions } | Self::Regular { permissions } => {
                *permissions | self.file_type()
            }
            Self::Invalid {
                raw_mode,
                reason: _,
            } => *raw_mode as u16,
        }
    }

    pub fn file_type(&self) -> u16 {
        match self {
            Self::Dir { permissions: _ } => DIR_FILE_TYPE,
            Self::Regular { permissions: _ } => REGULAR_FILE_TYPE,
            Self::Invalid {
                raw_mode,
                reason: _,
            } => *raw_mode as u16 & FILE_TYPE_BIT_MASK,
        }
    }

    pub fn permissions(&self) -> u16 {
        match self {
            Self::Dir { permissions } | Self::Regular { permissions } => *permissions,
            Self::Invalid {
                raw_mode,
                reason: _,
            } => *raw_mode as u16 & PERMISSIONS_BIT_MASK,
        }
    }
}

impl Into<u32> for FileMode {
    fn into(self) -> u32 {
        self.raw_mode() as u32
    }
}

impl Into<i32> for FileMode {
    fn into(self) -> i32 {
        self.raw_mode() as i32
    }
}

impl Into<i16> for FileMode {
    fn into(self) -> i16 {
        self.raw_mode() as i16
    }
}

impl Into<u16> for FileMode {
    fn into(self) -> u16 {
        self.raw_mode()
    }
}

/// Description of file modes.
///
/// A subset
pub struct RPMFileOptions {
    pub(crate) destination: String,
    pub(crate) user: String,
    pub(crate) group: String,
    pub(crate) symlink: String,
    pub(crate) mode: FileMode,
    pub(crate) flag: i32,
    pub(crate) inherit_permissions: bool,
}

impl RPMFileOptions {
    pub fn new<T: Into<String>>(dest: T) -> RPMFileOptionsBuilder {
        RPMFileOptionsBuilder {
            inner: RPMFileOptions {
                destination: dest.into(),
                user: "root".to_string(),
                group: "root".to_string(),
                symlink: "".to_string(),
                mode: FileMode::regular(0o664),
                flag: 0,
                inherit_permissions: true,
            },
        }
    }
}

pub struct RPMFileOptionsBuilder {
    inner: RPMFileOptions,
}

impl RPMFileOptionsBuilder {
    pub fn user<T: Into<String>>(mut self, user: T) -> Self {
        self.inner.user = user.into();
        self
    }

    pub fn group<T: Into<String>>(mut self, group: T) -> Self {
        self.inner.group = group.into();
        self
    }

    pub fn symlink<T: Into<String>>(mut self, symlink: T) -> Self {
        self.inner.symlink = symlink.into();
        self
    }

    pub fn mode<T: Into<FileMode>>(mut self, mode: T) -> Self {
        self.inner.mode = mode.into();
        self.inner.inherit_permissions = false;
        self
    }

    pub fn is_doc(mut self) -> Self {
        self.inner.flag = RPMFILE_DOC;
        self
    }

    pub fn is_config(mut self) -> Self {
        self.inner.flag = RPMFILE_CONFIG;
        self
    }
}

impl Into<RPMFileOptions> for RPMFileOptionsBuilder {
    fn into(self) -> RPMFileOptions {
        self.inner
    }
}

/// Description of a dependency as present in a RPM header record.
pub struct Dependency {
    pub(crate) dep_name: String,
    pub(crate) sense: u32,
    pub(crate) version: String,
}

impl Dependency {
    pub fn less<E, T>(dep_name: T, version: E) -> Self
    where
        T: Into<String>,
        E: Into<String>,
    {
        Self::new(dep_name.into(), RPMSENSE_LESS, version.into())
    }

    pub fn less_eq<E, T>(dep_name: T, version: E) -> Self
    where
        T: Into<String>,
        E: Into<String>,
    {
        Self::new(
            dep_name.into(),
            RPMSENSE_LESS | RPMSENSE_EQUAL,
            version.into(),
        )
    }

    pub fn eq<E, T>(dep_name: T, version: E) -> Self
    where
        T: Into<String>,
        E: Into<String>,
    {
        Self::new(dep_name.into(), RPMSENSE_EQUAL, version.into())
    }

    pub fn greater<E, T>(dep_name: T, version: E) -> Self
    where
        T: Into<String>,
        E: Into<String>,
    {
        Self::new(dep_name.into(), RPMSENSE_GREATER, version.into())
    }

    pub fn greater_eq<E, T>(dep_name: T, version: E) -> Self
    where
        T: Into<String>,
        E: Into<String>,
    {
        Self::new(
            dep_name.into(),
            RPMSENSE_GREATER | RPMSENSE_EQUAL,
            version.into(),
        )
    }

    pub fn any<T>(dep_name: T) -> Self
    where
        T: Into<String>,
    {
        Self::new(dep_name.into(), RPMSENSE_ANY, "".to_string())
    }

    fn new(dep_name: String, sense: u32, version: String) -> Self {
        Dependency {
            dep_name,
            sense,
            version,
        }
    }
}

mod test {

    #[test]
    fn test_file_mode() -> Result<(), Box<dyn std::error::Error>> {
        use super::*;

        // test constructor functions
        let test_table = vec![(0, 0), (0o7777, 0o7777), (0o17777, 0o7777)];
        for (permissions, expected) in test_table {
            let result = FileMode::dir(permissions);
            assert_eq!(expected, result.permissions());
            let result = FileMode::regular(permissions);
            assert_eq!(expected, result.permissions());
        }

        let test_table = vec![
            (0o10_0664, Ok(FileMode::regular(0o664))),
            (0o04_0665, Ok(FileMode::dir(0o665))),
            // test sticky bit
            (0o10_1664, Ok(FileMode::regular(0o1664))),
            (
                0o664,
                Err(errors::RPMError::InvalidFileMode {
                    raw_mode: 0o664,
                    reason: "unknown file type",
                }),
            ),
            (
                0o27_1664,
                Err(errors::RPMError::InvalidFileMode {
                    raw_mode: 0o27_1664,
                    reason: "provided integer is out of 16bit bounds",
                }),
            ),
        ];

        // test try_from_raw
        for (testant, expected) in test_table {
            let result = FileMode::try_from_raw(testant);
            match (&expected, &result) {
                (Ok(expected), Ok(actual)) => {
                    assert_eq!(expected, actual);
                }
                (Err(expected), Err(actual)) => {
                    if let errors::RPMError::InvalidFileMode {
                        raw_mode: actual_raw_mode,
                        reason: actual_reason,
                    } = actual
                    {
                        if let errors::RPMError::InvalidFileMode {
                            raw_mode: expected_raw_mode,
                            reason: expected_reason,
                        } = expected
                        {
                            assert_eq!(expected_raw_mode, actual_raw_mode);
                            assert_eq!(expected_reason, actual_reason);
                        } else {
                            unreachable!();
                        }
                    } else {
                        panic!("invalid error type");
                    }
                }
                _ => panic!("a and b not equal,{:?} vs {:?}", expected, result),
            }
        }

        // test into methods
        let test_table = vec![
            (0o10_0755, FileMode::regular(0o0755), REGULAR_FILE_TYPE),
            (0o10_1755, FileMode::regular(0o1755), REGULAR_FILE_TYPE),
            (0o04_0755, FileMode::dir(0o0755), DIR_FILE_TYPE),
            (
                0o20_0755,
                FileMode::Invalid {
                    raw_mode: 0o20_0755,
                    reason: "provided integer is out of 16bit bounds",
                },
                0,
            ),
            (
                0o0755,
                FileMode::Invalid {
                    raw_mode: 0o0755,
                    reason: "unknown file type",
                },
                0,
            ),
        ];
        for (raw_mode, expected_mode, expected_type) in test_table {
            let mode = FileMode::from(raw_mode);
            assert_eq!(expected_mode, mode);
            assert_eq!(raw_mode as u16, mode.raw_mode());
            assert_eq!(expected_type, mode.file_type());
        }
        Ok(())
    }
}