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
// 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 http://mozilla.org/MPL/2.0/.

/// Wrap all libcryptsetup_rs_sys calls in the macro. It will expand to a
/// feature-flagged mutex lock call. If the `mutex` feature is not enabled, it is
/// a no-op.
macro_rules! mutex {
    ( $libcryptsetup_call:expr ) => {{
        #[cfg(feature = "mutex")]
        #[allow(unused_variables)]
        let lock = match $crate::MUTEX.lock() {
            Ok(l) => Some(l),
            Err(e) => {
                panic!(
                    "The synchronization mutex can no longer be locked. \
                    Locking failed with error: {}; see Rust's documentation \
                    on Mutex poisoning here to decide how to proceed: \
                    https://doc.rust-lang.org/std/sync/struct.Mutex.html#errors",
                    e,
                )
            }
        };

        #[cfg(not(feature = "mutex"))]
        if *$crate::THREAD_ID != std::thread::current().id() {
            panic!("Enable the mutex feature for this crate to allow calling libcryptsetup methods from multiple threads");
        }

        unsafe { $libcryptsetup_call }
    }};
}

/// Convert an errno-zero-success return pattern into a `Result<(), LibcryptErr>`
macro_rules! errno {
    ( $rc:expr ) => {
        match $rc {
            i if i < 0 => {
                return Err($crate::err::LibcryptErr::IOError(
                    std::io::Error::from_raw_os_error(-i),
                ))
            }
            i if i > 0 => panic!("Unexpected return value {}", i),
            _ => Result::<(), $crate::err::LibcryptErr>::Ok(()),
        }
    };
}

/// Convert an errno-positive-int-success return pattern into a `Result<std::os::raw::c_int, LibcryptErr>`
macro_rules! errno_int_success {
    ( $rc:expr ) => {
        match $rc {
            i if i < 0 => {
                return Err($crate::err::LibcryptErr::IOError(
                    std::io::Error::from_raw_os_error(-i),
                ))
            }
            i => Result::<_, $crate::err::LibcryptErr>::Ok(i),
        }
    };
}

/// Convert an integer return value into specified type
macro_rules! int_to_return {
    ( $rc:expr, $type:ty ) => {
        <$type>::from($rc)
    };
}

/// Try converting an integer return value into specified type
macro_rules! try_int_to_return {
    ( $rc:expr, $type:ty ) => {
        <$type>::try_from($rc)
    };
}

/// Convert a pointer to an `Option` containing a pointer
macro_rules! ptr_to_option {
    ( $ptr:expr ) => {{
        let p = $ptr;
        if p.is_null() {
            None
        } else {
            Some(p)
        }
    }};
}

/// Convert a pointer to a `Option` containing a reference
macro_rules! ptr_to_option_with_reference {
    ( $ptr:expr ) => {{
        let p = $ptr;
        unsafe { p.as_ref() }
    }};
}

/// Convert a pointer to an `Result` containing a pointer
macro_rules! ptr_to_result {
    ( $ptr:expr ) => {{
        ptr_to_option!($ptr).ok_or($crate::err::LibcryptErr::NullPtr)
    }};
}

/// Convert a pointer to a `Result` containing a reference
macro_rules! ptr_to_result_with_reference {
    ( $ptr:expr ) => {{
        let p = $ptr;
        unsafe { p.as_ref() }.ok_or($crate::err::LibcryptErr::NullPtr)
    }};
}

/// Convert a `Path` type into `CString`
macro_rules! path_to_cstring {
    ( $path:expr ) => {
        match $path
            .to_str()
            .ok_or_else(|| LibcryptErr::InvalidConversion)
            .and_then(|s| std::ffi::CString::new(s).map_err(LibcryptErr::NullError))
        {
            Ok(s) => Ok(s),
            Err(e) => Err(e),
        }
    };
}

/// Convert a string type into `CString`
macro_rules! to_cstring {
    ( $str:expr ) => {
        match std::ffi::CString::new($str.as_bytes()) {
            Ok(s) => Ok(s),
            Err(e) => Err($crate::err::LibcryptErr::NullError(e)),
        }
    };
}

/// Convert a byte slice into `*const c_char`
macro_rules! to_byte_ptr {
    ( $bytes:expr ) => {
        $bytes.as_ptr() as *const std::os::raw::c_char
    };
}

/// Convert a byte slice into `*mut c_char`
macro_rules! to_mut_byte_ptr {
    ( $bytes:expr ) => {
        $bytes.as_mut_ptr() as *mut std::os::raw::c_char
    };
}

/// Convert a `*const c_char` into a `&str` type
#[macro_export]
macro_rules! from_str_ptr {
    ( $str_ptr:expr ) => {
        unsafe { ::std::ffi::CStr::from_ptr($str_ptr) }
            .to_str()
            .map_err($crate::LibcryptErr::Utf8Error)
    };
}

/// Convert a `*const c_char` into a `String` type
macro_rules! from_str_ptr_to_owned {
    ( $str_ptr:expr ) => {
        unsafe { ::std::ffi::CStr::from_ptr($str_ptr) }
            .to_str()
            .map_err($crate::err::LibcryptErr::Utf8Error)
            .map(|s| s.to_string())
    };
}

/// Convert constants to and from a flag enum
macro_rules! consts_to_from_enum {
    ( #[$meta:meta] $flag_enum:ident, $flag_type:ty, $( $name:ident => $constant:expr ),* ) => {
        #[$meta]
        #[derive(Copy, Clone, Debug, PartialEq)]
        pub enum $flag_enum {
            $(
                #[allow(missing_docs)]
                $name,
            )*
        }

        #[allow(clippy::from_over_into)]
        impl std::convert::Into<$flag_type> for $flag_enum {
            fn into(self) -> $flag_type {
                match self {
                    $(
                        $flag_enum::$name => $constant,
                    )*
                }
            }
        }

        impl std::convert::TryFrom<$flag_type> for $flag_enum {
            type Error = $crate::err::LibcryptErr;

            fn try_from(v: $flag_type) -> Result<Self, Self::Error> {
                Ok(match v {
                    $(
                        i if i == $constant => $flag_enum::$name,
                    )*
                    _ => return Err($crate::err::LibcryptErr::InvalidConversion),
                })
            }
        }
    };
}

/// Convert bit flags to and from a struct
macro_rules! bitflags_to_from_struct {
    ( #[$meta:meta] $flags_type:ident, $flag_type:ty, $bitflags_type:ty ) => {
        #[$meta]
        pub struct $flags_type(Vec<$flag_type>);

        impl $flags_type {
            /// Create a new set of flags
            pub fn new(vec: Vec<$flag_type>) -> Self {
                $flags_type(vec)
            }

            /// Create an empty set of flags
            pub fn empty() -> Self {
                $flags_type(Vec::new())
            }
        }

        #[allow(clippy::from_over_into)]
        impl std::convert::Into<$bitflags_type> for $flags_type {
            fn into(self) -> $bitflags_type {
                self.0.into_iter().fold(0, |acc, flag| {
                    let flag: $bitflags_type = flag.into();
                    acc | flag
                })
            }
        }

        impl std::convert::TryFrom<$bitflags_type> for $flags_type {
            type Error = LibcryptErr;

            fn try_from(v: $bitflags_type) -> Result<Self, Self::Error> {
                let mut vec = vec![];
                for i in 0..std::mem::size_of::<$bitflags_type>() * 8 {
                    if (v & (1 << i)) == (1 << i) {
                        vec.push(<$flag_type>::try_from(1 << i)?);
                    }
                }
                Ok(<$flags_type>::new(vec))
            }
        }
    };
}

/// Convert bit a struct reference to bitflags
macro_rules! struct_ref_to_bitflags {
    ( $flags_type:ident, $flag_type:ty, $bitflags_type:ty ) => {
        #[allow(clippy::from_over_into)]
        impl<'a> std::convert::Into<$bitflags_type> for &'a $flags_type {
            fn into(self) -> $bitflags_type {
                self.0.iter().fold(0, |acc, flag| {
                    let flag: $bitflags_type = (*flag).into();
                    acc | flag
                })
            }
        }
    };
}

#[macro_export]
/// Create a C-compatible static string with a null byte
macro_rules! c_str {
    ( $str:tt ) => {
        concat!($str, "\0")
    };
}

#[macro_export]
/// Create a C-compatible callback to determine user confirmation which wraps safe Rust code
macro_rules! c_confirm_callback {
    ( $fn_name:ident, $type:ty, $safe_fn_name:ident ) => {
        extern "C" fn $fn_name(
            msg: *const std::os::raw::c_char,
            usrptr: *mut std::os::raw::c_void,
        ) -> std::os::raw::c_int {
            let msg_str =
                $crate::from_str_ptr!(msg).expect("Invalid message string passed to cryptsetup-rs");
            let generic_ptr = usrptr as *mut $type;
            let generic_ref = unsafe { generic_ptr.as_mut() };

            $safe_fn_name(msg_str, generic_ref) as std::os::raw::c_int
        }
    };
}

#[macro_export]
/// Create a C-compatible logging callback which wraps safe Rust code
macro_rules! c_logging_callback {
    ( $fn_name:ident, $type:ty, $safe_fn_name:ident ) => {
        extern "C" fn $fn_name(
            level: std::os::raw::c_int,
            msg: *const std::os::raw::c_char,
            usrptr: *mut std::os::raw::c_void,
        ) {
            let level =
                <$crate::CryptLogLevel as std::convert::TryFrom<std::os::raw::c_int>>::try_from(
                    level,
                )
                .expect("Invalid logging level passed to cryptsetup-rs");
            let msg_str =
                $crate::from_str_ptr!(msg).expect("Invalid message string passed to cryptsetup-rs");
            let generic_ptr = usrptr as *mut $type;
            let generic_ref = unsafe { generic_ptr.as_mut() };

            $safe_fn_name(level, msg_str, generic_ref);
        }
    };
}

#[macro_export]
/// Create a C-compatible progress callback for wiping a device which wraps safe Rust code
macro_rules! c_progress_callback {
    ( $fn_name:ident, $type:ty, $safe_fn_name:ident ) => {
        extern "C" fn $fn_name(
            size: u64,
            offset: u64,
            usrptr: *mut std::os::raw::c_void,
        ) -> std::os::raw::c_int {
            let generic_ptr = usrptr as *mut $type;
            let generic_ref = unsafe { generic_ptr.as_mut() };

            $safe_fn_name(size, offset, generic_ref) as std::os::raw::c_int
        }
    };
}

#[macro_export]
/// Create a C-compatible open callback compatible with `CryptTokenHandler`
macro_rules! c_token_handler_open {
    ( $fn_name:ident, $type:ty, $safe_fn_name:ident ) => {
        extern "C" fn $fn_name(
            cd: *mut libcryptsetup_rs_sys::crypt_device,
            token_id: std::os::raw::c_int,
            buffer: *mut *mut std::os::raw::c_char,
            buffer_len: *mut $crate::SizeT,
            usrptr: *mut std::os::raw::c_void,
        ) -> std::os::raw::c_int {
            let device = $crate::device::CryptDevice::from_ptr(cd);
            let generic_ptr = usrptr as *mut $type;
            let generic_ref = unsafe { generic_ptr.as_mut() };

            let buffer: Result<Box<[u8]>, $crate::LibcryptErr> =
                $safe_fn_name(device, token_id, generic_ref);
            match buffer {
                Ok(()) => {
                    *buffer = Box::into_raw(buffer) as *mut std::os::raw::c_char;
                    0
                }
                Err(_) => -1,
            }
        }
    };
}

#[macro_export]
/// Create a C-compatible callback for free compatible with `CryptTokenHandler`
macro_rules! c_token_handler_free {
    ( $fn_name:ident, $safe_fn_name:ident ) => {
        extern "C" fn $fn_name(buffer: *mut std::os::raw::c_void, buffer_len: $crate::SizeT) {
            let boxed_slice = unsafe {
                Box::from_raw(std::slice::from_raw_parts_mut(
                    buffer as *mut u8,
                    buffer_len as usize,
                ))
            };

            $safe_fn_name(boxed_slice)
        }
    };
}

#[macro_export]
/// Create a C-compatible callback for validate compatible with `CryptTokenHandler`
macro_rules! c_token_handler_validate {
    ( $fn_name:ident, $safe_fn_name:ident ) => {
        extern "C" fn $fn_name(
            cd: *mut libcryptsetup_rs_sys::crypt_device,
            json: *mut std::os::raw::c_char,
        ) -> std::os::raw::c_int {
            let device = $crate::device::CryptDevice::from_ptr(cd);
            let s = match $crate::from_str_ptr!(json) {
                Ok(s) => s,
                Err(_) => return -1,
            };
            let json_obj = match serde_json::from_str(s) {
                Ok(j) => j,
                Err(_) => return -1,
            };

            let rc: Result<(), $crate::LibcryptErr> = $safe_fn_name(device, json_obj);
            match rc {
                Ok(()) => 0,
                Err(_) => -1,
            }
        }
    };
}

#[macro_export]
/// Create a C-compatible callback for compatible with `CryptTokenHandler`
macro_rules! c_token_handler_dump {
    ( $fn_name:ident, $safe_fn_name:ident ) => {
        extern "C" fn $fn_name(
            cd: *mut libcryptsetup_rs_sys::crypt_device,
            json: *mut std::os::raw::c_char,
        ) {
            let device = $crate::device::CryptDevice::from_ptr(cd);
            let s = match $crate::from_str_ptr!(json) {
                Ok(s) => s,
                Err(_) => return,
            };
            let json_obj = match serde_json::from_str(s) {
                Ok(j) => j,
                Err(_) => return,
            };

            $safe_fn_name(device, json_obj)
        }
    };
}

#[cfg(test)]
mod test {
    use std::convert::TryFrom;

    use crate::{log::CryptLogLevel, Bool, Interrupt};

    fn safe_confirm_callback(_msg: &str, usrdata: Option<&mut u32>) -> Bool {
        Bool::from(*usrdata.unwrap() as i32)
    }

    c_confirm_callback!(confirm_callback, u32, safe_confirm_callback);

    fn safe_logging_callback(_level: CryptLogLevel, _msg: &str, _usrdata: Option<&mut u32>) {}

    c_logging_callback!(logging_callback, u32, safe_logging_callback);

    fn safe_progress_callback(_size: u64, _offset: u64, usrdata: Option<&mut u32>) -> Interrupt {
        Interrupt::from(*usrdata.unwrap() as i32)
    }

    c_progress_callback!(progress_callback, u32, safe_progress_callback);

    #[test]
    fn test_c_confirm_callback() {
        let ret = confirm_callback(
            "".as_ptr() as *const std::os::raw::c_char,
            &mut 1u32 as *mut _ as *mut std::os::raw::c_void,
        );
        assert_eq!(1, ret);
        assert_eq!(Bool::Yes, Bool::from(ret));

        let ret = confirm_callback(
            "".as_ptr() as *const std::os::raw::c_char,
            &mut 0u32 as *mut _ as *mut std::os::raw::c_void,
        );
        assert_eq!(0, ret);
        assert_eq!(Bool::No, Bool::from(ret));
    }

    #[test]
    fn test_c_logging_callback() {
        logging_callback(
            libcryptsetup_rs_sys::CRYPT_LOG_ERROR as i32,
            "".as_ptr() as *const std::os::raw::c_char,
            &mut 1u32 as *mut _ as *mut std::os::raw::c_void,
        );

        logging_callback(
            libcryptsetup_rs_sys::CRYPT_LOG_DEBUG as i32,
            "".as_ptr() as *const std::os::raw::c_char,
            &mut 0u32 as *mut _ as *mut std::os::raw::c_void,
        );
    }

    #[test]
    fn test_c_progress_callback() {
        let ret = progress_callback(0, 0, &mut 1u32 as *mut _ as *mut std::os::raw::c_void);
        assert_eq!(1, ret);
        assert_eq!(Interrupt::Yes, Interrupt::from(ret));

        let ret = progress_callback(0, 0, &mut 0u32 as *mut _ as *mut std::os::raw::c_void);
        assert_eq!(0, ret);
        assert_eq!(Interrupt::No, Interrupt::from(ret));
    }

    consts_to_from_enum!(
        /// An enum for testing `PartialEq`
        PETestEnum,
        u16,
        This => 0,
        Can => 1,
        Use => 2,
        PartialEq => 3
    );

    #[test]
    fn test_enum_partial_eq() {
        assert_eq!(PETestEnum::This, PETestEnum::try_from(0).unwrap());
        assert_eq!(PETestEnum::Can, PETestEnum::try_from(1).unwrap());
        assert_eq!(PETestEnum::Use, PETestEnum::try_from(2).unwrap());
        assert_eq!(PETestEnum::PartialEq, PETestEnum::try_from(3).unwrap());
    }

    #[cfg(feature = "mutex")]
    #[test]
    #[should_panic(expected = "The synchronization mutex can no longer be locked.")]
    fn test_mutex_poisoning_panic() {
        assert!(std::panic::catch_unwind(|| {
            let _lock = crate::MUTEX.lock().unwrap();
            panic!("Cause panic");
        })
        .is_err());

        crate::status::get_sector_size(None);
    }

    #[cfg(not(feature = "mutex"))]
    #[test]
    #[should_panic(expected = "Enable the mutex feature")]
    fn test_multiple_threads_no_mutex_feature() {
        std::thread::spawn(|| {
            crate::get_sector_size(None);
        })
        .join()
        .unwrap();
        crate::get_sector_size(None);
    }
}