rsmount 0.2.2

Safe Rust wrapper around the `util-linux/libmount` C library
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
// Copyright (c) 2023 Nick Piaddo
// SPDX-License-Identifier: Apache-2.0 OR MIT

// From dependency library

// From standard library
use std::ffi::CString;
use std::mem::MaybeUninit;
use std::path::{Path, PathBuf};

// From this library

use crate::ffi_utils;
use crate::mount::ExitCode;
use crate::mount::ExitStatus;
use crate::mount::MountSource;
use crate::mount::UMountIter;
use crate::mount::UMountNamespace;
use crate::mount::UmntBuilder;
use crate::mount::UnmountBuilder;
use crate::mount::UnmountError;

/// Object to unmount a device.
#[derive(Debug)]
#[repr(transparent)]
pub struct Unmount {
    pub(crate) inner: *mut libmount::libmnt_context,
}

impl Unmount {
    #[doc(hidden)]
    /// Wraps a raw `libmount::mnt_context` pointer with a safe `Unmount`.
    #[allow(dead_code)]
    pub(crate) fn from_ptr(ptr: *mut libmount::libmnt_context) -> Unmount {
        Self { inner: ptr }
    }

    #[doc(hidden)]
    /// Creates a new `Unmount`.
    pub(crate) fn new() -> Result<Unmount, UnmountError> {
        log::debug!("Unmount::new creating a new `Unmount` instance");

        let mut inner = MaybeUninit::<*mut libmount::libmnt_context>::zeroed();

        unsafe {
            inner.write(libmount::mnt_new_context());
        }

        match unsafe { inner.assume_init() } {
            inner if inner.is_null() => {
                let err_msg = "failed to create a new `Unmount` instance".to_owned();
                log::debug!(
                    "Unmount::new {}. libmount::mnt_new_contex returned a NULL pointer",
                    err_msg
                );

                Err(UnmountError::Creation(err_msg))
            }
            inner => {
                log::debug!("Unmount::new created a new `Unmount` instance");
                let mount = Self::from_ptr(inner);

                Ok(mount)
            }
        }
    }

    #[doc(hidden)]
    /// Converts a function's return code to unified `libmount` exit code.
    fn return_code_to_exit_status(&self, return_code: i32) -> Result<ExitStatus, UnmountError> {
        log::debug!(
            "Unmount::return_code_to_exit_status converting to exit status the return code: {:?}",
            return_code
        );

        const BUFFER_LENGTH: usize = 4097; // 4096 characters + `\0`
        let mut buffer: Vec<libc::c_char> = vec![0; BUFFER_LENGTH];

        let rc = unsafe {
            libmount::mnt_context_get_excode(
                self.inner,
                return_code,
                buffer.as_mut_ptr(),
                BUFFER_LENGTH,
            )
        };

        let exit_code = ExitCode::try_from(rc)?;
        let error_message = ffi_utils::c_char_array_to_string(buffer.as_ptr());
        let exit_status = ExitStatus::new(exit_code, error_message);

        log::debug!(
            "Unmount::return_code_to_exit_status converted return code: {:?} to exit status {:?}",
            return_code,
            exit_status
        );

        Ok(exit_status)
    }

    //---- BEGIN setters

    #[doc(hidden)]
    /// Enables/disables deleting loop devices after unmounting.
    fn enable_delete_loop_device(
        mount: *mut libmount::libmnt_context,
        enable: bool,
    ) -> Result<(), UnmountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_loopdel(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::enable_delete_loop_device {}d loop device deletion after unmount",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} loop device deletion after unmount", op_str);
                log::debug!("Unmount::enable_delete_loop_device {}. libmount::mnt_context_enable_loopdel returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Enables `Unmount` to delete loop devices after unmount.
    pub(crate) fn enable_detach_loop_device(&mut self) -> Result<(), UnmountError> {
        log::debug!(
            "Unmount::enable_detach_loop_device enabling loop device deletion after unmount"
        );

        Self::enable_delete_loop_device(self.inner, true)
    }

    #[doc(hidden)]
    /// Disables `Unmount` to delete loop devices after unmount.
    pub(crate) fn disable_detach_loop_device(&mut self) -> Result<(), UnmountError> {
        log::debug!(
            "Unmount::disable_detach_loop_device disabling loop device deletion after unmount"
        );

        Self::enable_delete_loop_device(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables path canonicalization.
    fn disable_canonicalize(
        mount: *mut libmount::libmnt_context,
        disable: bool,
    ) -> Result<(), UnmountError> {
        let op = if disable { 1 } else { 0 };
        let op_str = if disable {
            "disable".to_owned()
        } else {
            "enable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_disable_canonicalize(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::disable_canonicalize {}d path canonicalization",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} path canonicalization", op_str);
                log::debug!("Unmount::disable_canonicalize {}. libmount::mnt_context_disable_canonicalize returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Disables path canonicalization.
    pub(crate) fn disable_path_canonicalization(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::disable_path_canonicalization disabling path canonicalization");

        Self::disable_canonicalize(self.inner, true)
    }

    #[doc(hidden)]
    /// Enables path canonicalization.
    pub(crate) fn enable_path_canonicalization(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::enable_path_canonicalization enabling path canonicalization");

        Self::disable_canonicalize(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables mount helpers.
    fn disable_mnt_helpers(
        mount: *mut libmount::libmnt_context,
        disable: bool,
    ) -> Result<(), UnmountError> {
        let op = if disable { 1 } else { 0 };
        let op_str = if disable {
            "disable".to_owned()
        } else {
            "enable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_disable_helpers(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::disable_mnt_helpers {}d mount/umount helpers",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} mount/umount helpers", op_str);
                log::debug!("Unmount::disable_mnt_helpers {}. libmount::mnt_context_disable_helpers returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Prevents `Unmount` from calling `/sbin/umount.suffix` helper functions, where *suffix* is a file system type.
    pub(crate) fn disable_helpers(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::disable_helpers disabling mount/umount helpers");

        Self::disable_mnt_helpers(self.inner, true)
    }

    #[doc(hidden)]
    /// Allows `Unmount` to call `/sbin/umount.suffix` helper functions, where *suffix* is a file system type.
    pub(crate) fn enable_helpers(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::enable_helpers enabling mount/umount helpers");

        Self::disable_mnt_helpers(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables mount point lookup.
    fn disable_swap_match(
        mount: *mut libmount::libmnt_context,
        disable: bool,
    ) -> Result<(), UnmountError> {
        let op = if disable { 1 } else { 0 };
        let op_str = if disable {
            "disable".to_owned()
        } else {
            "enable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_disable_swapmatch(mount, op) };

        match result {
            0 => {
                log::debug!("Unmount::disable_swap_match {}d mount point lookup", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} mount point lookup", op_str);
                log::debug!("Unmount::disable_swap_match {}. libmount::mnt_context_disable_swapmatch returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Disables mount point lookup in `/etc/fstab` when either the mount `source` or `target` is
    /// not set.
    pub(crate) fn disable_mount_point_lookup(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::disable_mount_point_lookup disabling mount point lookup");

        Self::disable_swap_match(self.inner, true)
    }

    #[doc(hidden)]
    /// Enables mount point lookup in `/etc/fstab` when either the mount `source` or `target` is
    /// not set.
    pub(crate) fn enable_mount_point_lookup(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::enable_mount_point_lookup enabling mount point lookup");

        Self::disable_swap_match(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables userspace mount table updates.
    fn disable_mtab(
        mount: *mut libmount::libmnt_context,
        disable: bool,
    ) -> Result<(), UnmountError> {
        let op = if disable { 1 } else { 0 };
        let op_str = if disable {
            "disable".to_owned()
        } else {
            "enable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_disable_mtab(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::disable_mtab {}d userspace mount table updates",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} userspace mount table updates", op_str);
                log::debug!("Unmount::disable_mtab {}. libmount::mnt_context_disable_mtab returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Disables userspace mount table updates.
    pub(crate) fn do_not_update_utab(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::do_not_update_utab disabling userspace mount table updates");

        Self::disable_mtab(self.inner, true)
    }

    #[doc(hidden)]
    /// Enables userspace mount table updates.
    pub(crate) fn update_utab(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::update_utab enabling userspace mount table updates");

        Self::disable_mtab(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables skipping all mount source preparation, mount option analysis, and the actual mounting process.
    /// (see the [`mount` command](https://www.man7.org/linux/man-pages/man8/mount.8.html) man page, option `-f, --fake`)
    fn enable_fake(mount: *mut libmount::libmnt_context, enable: bool) -> Result<(), UnmountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_fake(mount, op) };

        match result {
            0 => {
                log::debug!("Unmount::enable_fake {}d dry run", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} dry run", op_str);
                log::debug!("Unmount::enable_fake {}. libmount::mnt_context_enable_fake returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Skips all mount source preparation, mount option analysis, and the actual mounting process.
    pub(crate) fn enable_dry_run(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::enable_dry_run enabling dry run");

        Self::enable_fake(self.inner, true)
    }

    #[doc(hidden)]
    pub(crate) fn disable_dry_run(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::disable_dry_run disabling dry run");

        Self::enable_fake(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables force device unmount.
    fn enable_force_device_unmount(
        mount: *mut libmount::libmnt_context,
        enable: bool,
    ) -> Result<(), UnmountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_force(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::enable_force_device_unmount {}d force device unmount",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} force device unmount", op_str);
                log::debug!("Unmount::enable_force_device_unmount {}. libmount::mnt_context_enable_force returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Forces a device umount.
    pub(crate) fn enable_force_unmount(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::enable_force_unmount enabling force device unmount");

        Self::enable_force_device_unmount(self.inner, true)
    }

    #[doc(hidden)]
    /// Prevents `Unmount` from forcing a device umount.
    pub(crate) fn disable_force_unmount(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::disable_force_unmount disabling force device unmount");

        Self::enable_force_device_unmount(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables lazy device unmount.
    fn enable_lazy_device_unmount(
        mount: *mut libmount::libmnt_context,
        enable: bool,
    ) -> Result<(), UnmountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_lazy(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::enable_lazy_device_unmount {}d lazy device unmount",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} lazy device unmount", op_str);
                log::debug!("Unmount::enable_lazy_device_unmount {}. libmount::mnt_context_enable_lazy returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Enables `Unmount` to lazily unmount devices.
    pub(crate) fn enable_lazy_unmount(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::enable_lazy_umount enabling lazy device unmount");

        Self::enable_lazy_device_unmount(self.inner, true)
    }

    #[doc(hidden)]
    /// Disables `Unmount` to lazily unmount devices.
    pub(crate) fn disable_lazy_unmount(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::disable_lazy_umount disabling lazy device unmount");

        Self::enable_lazy_device_unmount(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables verbose output.
    fn enable_verbose(
        mount: *mut libmount::libmnt_context,
        enable: bool,
    ) -> Result<(), UnmountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_verbose(mount, op) };

        match result {
            0 => {
                log::debug!("Unmount::enable_verbose {}d verbose output", op_str);

                Ok(())
            }
            code => {
                let err_msg = format!("failed to {} verbose output", op_str);
                log::debug!("Unmount::enable_verbose {}. libmount::mnt_context_enable_verbose returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Enables `Unmount` to check that a device is not already mounted before mounting it.
    pub(crate) fn enable_verbose_output(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::enable_verbose_output enabling verbose output");

        Self::enable_verbose(self.inner, true)
    }

    #[doc(hidden)]
    /// Disables `Unmount` to check that a device is not already mounted before mounting it.
    pub(crate) fn disable_verbose_output(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::disable_verbose_output disabling verbose output");

        Self::enable_verbose(self.inner, false)
    }

    #[doc(hidden)]
    /// Enables/disables `Unmount` functionality to remount a device in read-only mode after a failed unmount.
    fn enable_read_only_unmount(
        mount: *mut libmount::libmnt_context,
        enable: bool,
    ) -> Result<(), UnmountError> {
        let op = if enable { 1 } else { 0 };
        let op_str = if enable {
            "enable".to_owned()
        } else {
            "disable".to_owned()
        };

        let result = unsafe { libmount::mnt_context_enable_rdonly_umount(mount, op) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::enable_read_only_unmount {}d remount read-only after failed unmount",
                    op_str
                );

                Ok(())
            }
            code => {
                let err_msg = format!(
                    "failed to {} remount read-only after failed unmount",
                    op_str
                );
                log::debug!("Unmount::enable_read_only_unmount {}. libmount::mnt_context_enable_rdonly_umount returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Enables `Unmount` functionality to remount a device in read-only mode after a failed unmount.
    pub(crate) fn enable_on_fail_remount_read_only(&mut self) -> Result<(), UnmountError> {
        log::debug!(
            "Unmount::enable_on_fail_remount_read_only enabling read only remount after failed unmount"
        );

        Self::enable_read_only_unmount(self.inner, true)
    }

    #[doc(hidden)]
    /// Disables `Unmount` functionality to remount a device in read-only mode after a failed unmount.
    pub(crate) fn disable_on_fail_remount_read_only(&mut self) -> Result<(), UnmountError> {
        log::debug!(
            "Unmount::disable_on_fail_remount_read_only disabling read only remount after failed unmount"
        );

        Self::enable_read_only_unmount(self.inner, false)
    }

    #[doc(hidden)]
    /// Sets a list of file systems.
    pub(crate) fn set_file_systems_filter<T>(&mut self, fs_list: T) -> Result<(), UnmountError>
    where
        T: AsRef<str>,
    {
        let fs_list = fs_list.as_ref();
        let fs_list_cstr = ffi_utils::as_ref_str_to_c_string(fs_list)?;
        log::debug!(
            "Unmount::set_file_systems_filter setting the list of file systems: {:?}",
            fs_list
        );

        let result =
            unsafe { libmount::mnt_context_set_fstype_pattern(self.inner, fs_list_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::set_file_systems_filter set the list of file systems: {:?}",
                    fs_list
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set file systems list: {:?}", fs_list);
                log::debug!("Unmount::set_file_systems_filter {}. libmount::mnt_context_set_fstype_pattern returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets the pattern of mount options to use as filter when mounting devices.
    pub(crate) fn set_mount_options_filter<T>(
        &mut self,
        options_list: T,
    ) -> Result<(), UnmountError>
    where
        T: AsRef<str>,
    {
        let options_list = options_list.as_ref();
        let options_list_cstr = ffi_utils::as_ref_str_to_c_string(options_list)?;
        log::debug!(
            "Unmount::set_mount_options_filter setting mount options filter: {:?}",
            options_list
        );

        let result = unsafe {
            libmount::mnt_context_set_options_pattern(self.inner, options_list_cstr.as_ptr())
        };

        match result {
            0 => {
                log::debug!(
                    "Unmount::set_mount_options_filter set mount options filter: {:?}",
                    options_list
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount options filter: {:?}", options_list);
                log::debug!("Unmount::set_mount_options_filter {}. libmount::mnt_context_set_options_pattern returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Set the `Unmount`'s source.
    fn set_source(
        mount: *mut libmount::libmnt_context,
        source: CString,
    ) -> Result<(), UnmountError> {
        let result = unsafe { libmount::mnt_context_set_source(mount, source.as_ptr()) };

        match result {
            0 => {
                log::debug!("Unmount::set_source mount source set");

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount source: {:?}", source);
                log::debug!("Unmount::set_source {}. libmount::mnt_context_set_source returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets the location/ID of the device to mount.
    ///
    /// A source can take any of the following forms:
    /// - block device path (e.g. `/dev/sda1`),
    /// - network ID:
    ///     - Samba: `smb://ip-address-or-hostname/shared-dir`,
    ///     - NFS: `hostname:/shared-dir`  (e.g. knuth.cwi.nl:/dir)
    ///     - SSHFS: `[user@]ip-address-or-hostname:[/shared-dir]` elements in brackets are optional (e.g.
    ///     tux@192.168.0.1:/share)
    ///
    /// - label:
    ///     - `UUID=uuid`,
    ///     - `LABEL=label`,
    ///     - `PARTLABEL=label`,
    ///     - `PARTUUID=uuid`,
    ///     - `ID=id`.
    pub(crate) fn set_mount_source(&mut self, source: MountSource) -> Result<(), UnmountError> {
        let source = source.to_string();
        let source_cstr = ffi_utils::as_ref_path_to_c_string(&source)?;
        log::debug!(
            "Unmount::set_mount_source setting mount source: {:?}",
            source
        );

        Self::set_source(self.inner, source_cstr)
    }

    #[doc(hidden)]
    /// Sets this `Unmount`'s mount point.
    pub(crate) fn set_mount_target<T>(&mut self, target: T) -> Result<(), UnmountError>
    where
        T: AsRef<Path>,
    {
        let target = target.as_ref();
        let target_cstr = ffi_utils::as_ref_path_to_c_string(target)?;
        log::debug!(
            "Unmount::set_mount_target setting mount target to: {:?}",
            target
        );

        let result = unsafe { libmount::mnt_context_set_target(self.inner, target_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::set_mount_target set mount target to: {:?}",
                    target
                );

                Ok(())
            }
            code => {
                let err_msg = format!("failed to set mount target to: {:?}", target);
                log::debug!("Unmount::set_mount_target {}. libmount::mnt_context_set_target returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    #[doc(hidden)]
    /// Sets the namespace of this `Unmount`'s mount point.
    pub(crate) fn set_mount_target_namespace<T>(&mut self, path: T) -> Result<(), UnmountError>
    where
        T: AsRef<Path>,
    {
        let path = path.as_ref();
        let path_cstr = ffi_utils::as_ref_path_to_c_string(path)?;
        log::debug!(
            "Unmount::set_mount_target_namespace setting mount target namespace: {:?}",
            path
        );

        let result = unsafe { libmount::mnt_context_set_target_ns(self.inner, path_cstr.as_ptr()) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::set_mount_target_namespace set mount target namespace: {:?}",
                    path
                );

                Ok(())
            }
            code if code == -libc::ENOSYS => {
                let err_msg = "`libmount` was compiled without namespace support".to_owned();
                log::debug!("Unmount::set_mount_target_namespace {}. libmount::mnt_context_set_target returned error code: {:?}", err_msg, code);

                Err(UnmountError::NoNamespaceSupport(err_msg))
            }
            code => {
                let err_msg = format!("failed to set mount target namespace: {:?}", path);
                log::debug!("Unmount::set_mount_target_namespace {}. libmount::mnt_context_set_target_ns returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    //---- END setters

    /// Creates a [`UnmountBuilder`] to configure and construct a new `Unmount`
    /// instance.
    ///
    /// Call the `UnmountBuilder`'s [`build()`](UnmountBuilder::build) method to
    /// construct a new `Unmount` instance.
    pub fn builder() -> UnmountBuilder {
        log::debug!("Unmount::builder creating new `UnmountBuilder` instance");
        UmntBuilder::builder()
    }

    //---- BEGIN mutators

    /// Unmounts a device using the [`umount` syscall](https://www.man7.org/linux/man-pages/man2/umount.2.html) and/or
    /// [`umount` helpers](https://www.man7.org/linux/man-pages/man8/umount.8.html#EXTERNAL_HELPERS).
    ///
    /// Equivalent to running the following functions in succession:
    /// - [`Unmount::prepare_unmount`]
    /// - [`Unmount::call_umount_syscall`]
    /// - [`Unmount::finalize_umount`]
    pub fn unmount_device(&mut self) -> Result<ExitStatus, UnmountError> {
        log::debug!("Unmount::unmount_device unmounting device");

        let return_code = unsafe { libmount::mnt_context_umount(self.inner) };
        self.return_code_to_exit_status(return_code)
    }

    /// Validates this `Unmount`'s parameters before it tries to unmount a device.
    ///
    /// **Note:** you do not need to call this method if you are using [`Unmount::unmount_device`], it
    /// will take care of parameter validation.
    pub fn prepare_unmount(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::prepare_unmount preparing for unmount");

        let result = unsafe { libmount::mnt_context_prepare_umount(self.inner) };

        match result {
            0 => {
                log::debug!("Unmount::prepare_unmount preparation successful");

                Ok(())
            }
            code => {
                let err_msg = "failed to prepare for device unmount".to_owned();
                log::debug!("Unmount::prepare_unmount {}. libmount::mnt_context_prepare_umount returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    /// Runs the [`umount` syscall](https://www.man7.org/linux/man-pages/man2/umount.2.html) and/or
    /// [umount helpers](https://www.man7.org/linux/man-pages/man8/umount.8.html#EXTERNAL_HELPERS).
    ///
    /// **Note:** you do not need to call this method if you are using [`Unmount::unmount_device`], it
    /// will take care of everything for you.
    pub fn call_umount_syscall(&mut self) -> Result<ExitStatus, UnmountError> {
        log::debug!("Unmount::call_umount_syscall unmounting device");

        let return_code = unsafe { libmount::mnt_context_do_umount(self.inner) };
        self.return_code_to_exit_status(return_code)
    }

    /// Updates the system's mount tables to take the last modifications into account. You should
    /// call this function after invoking [`Unmount::call_umount_syscall`].
    ///
    /// **Note:** you do not need to call this method if you are using [`Unmount::unmount_device`], it
    /// will take care of finalizing the unmount.
    pub fn finalize_umount(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::finalize_umount finalizing unmount");

        let result = unsafe { libmount::mnt_context_finalize_umount(self.inner) };

        match result {
            0 => {
                log::debug!("Unmount::finalize_umount finalized unmount");

                Ok(())
            }
            code => {
                let err_msg = "failed to finalize device unmount".to_owned();
                log::debug!("Unmount::finalize_umount {}. libmount::mnt_context_finalize_umount returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    /// Sets `umount`'s syscall exit status if the function was called outside of `libmount`.
    ///
    /// The `exit_status` should be `0` on success, and a negative number on error (e.g. `-errno`).
    pub fn set_syscall_exit_status(&mut self, exit_status: i32) -> Result<(), UnmountError> {
        log::debug!(
            "Unmount::set_syscall_exit_status setting mount/umount syscall exit status to {:?}",
            exit_status
        );

        let result = unsafe { libmount::mnt_context_set_syscall_status(self.inner, exit_status) };

        match result {
            0 => {
                log::debug!(
                    "Unmount::set_syscall_exit_status set mount/umount syscall exit status to {:?}",
                    exit_status
                );

                Ok(())
            }
            code => {
                let err_msg = format!(
                    "ailed to set mount/umount syscall exit status to {:?}",
                    exit_status
                );
                log::debug!("Unmount::set_syscall_exit_status {}. libmount::mnt_context_set_syscall_status returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    /// Resets `umount` exit status so that `umount` methods can be called again.
    pub fn reset_syscall_exit_status(&mut self) -> Result<(), UnmountError> {
        log::debug!("Unmount::reset_syscall_exit_status resetting syscall exit status");

        let result = unsafe { libmount::mnt_context_reset_status(self.inner) };

        match result {
            0 => {
                log::debug!("Unmount::reset_syscall_exit_status reset syscall exit status");

                Ok(())
            }
            code => {
                let err_msg = "failed to reset syscall exit status".to_owned();
                log::debug!("Unmount::reset_syscall_exit_status {}. libmount::mnt_context_reset_status returned error code: {:?}", err_msg, code);

                Err(UnmountError::Config(err_msg))
            }
        }
    }

    /// Switches to the provided `namespace`, and returns the namespace used previously.
    pub fn switch_to_namespace(
        &mut self,
        namespace: UMountNamespace,
    ) -> Option<UMountNamespace<'_>> {
        log::debug!("Unmount::switch_to_namespace switching namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();
        unsafe {
            ptr.write(libmount::mnt_context_switch_ns(self.inner, namespace.ptr));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no prior namespace";
                log::debug!("Unmount::switch_to_namespace {}. libmount::mnt_context_switch_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Unmount::switch_to_namespace switched namespace");
                let namespace = UMountNamespace::from_raw_parts(ptr, self);

                Some(namespace)
            }
        }
    }

    /// Switches to the namespace at creation, and returns the replacement namespace used up to this point.
    pub fn switch_to_original_namespace(&mut self) -> Option<UMountNamespace<'_>> {
        log::debug!("Unmount::switch_to_original_namespace switching to original namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_switch_origin_ns(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no prior namespace";
                log::debug!("Unmount::switch_to_original_namespace {}. libmount::mnt_context_switch_origin_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Unmount::switch_to_original_namespace switched to original namespace");
                let namespace = UMountNamespace::from_raw_parts(ptr, self);

                Some(namespace)
            }
        }
    }

    /// Switches to the target's namespace, and returns the namespace used previously.
    pub fn switch_to_target_namespace(&mut self) -> Option<UMountNamespace<'_>> {
        log::debug!("Unmount::switch_to_target_namespace switching to target namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_switch_target_ns(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no prior namespace";
                log::debug!("Unmount::switch_to_target_namespace {}. libmount::mnt_context_switch_target_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Unmount::switch_to_target_namespace switched to target namespace");
                let namespace = UMountNamespace::from_raw_parts(ptr, self);

                Some(namespace)
            }
        }
    }

    //---- END mutators

    //---- BEGIN getters

    /// Returns the identifier of the device to mount, or `None` if it was not provided.
    pub fn source(&self) -> Option<String> {
        log::debug!("Unmount::source getting identifier of device to mount");

        let mut identifier = MaybeUninit::<*const libc::c_char>::zeroed();

        unsafe {
            identifier.write(libmount::mnt_context_get_source(self.inner));
        }

        match unsafe { identifier.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get identifier of device to mount";
                log::debug!(
                    "Unmount::source {}. libmount::mnt_context_get_source returned a NULL pointer",
                    err_msg
                );

                None
            }
            ptr => {
                log::debug!("Unmount::source got identifier of device to mount");
                let source = ffi_utils::c_char_array_to_string(ptr);

                Some(source)
            }
        }
    }

    /// Returns the configured device mount point, or `None` if it was not provided.
    pub fn target(&self) -> Option<PathBuf> {
        log::debug!("Unmount::target getting mount point");

        let mut mount_point = MaybeUninit::<*const libc::c_char>::zeroed();

        unsafe {
            mount_point.write(libmount::mnt_context_get_target(self.inner));
        }

        match unsafe { mount_point.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "failed to get mount point";
                log::debug!(
                    "Unmount::target {}. libmount::mnt_context_get_target returned a NULL pointer",
                    err_msg
                );

                None
            }
            ptr => {
                log::debug!("Unmount::target got mount point");
                let target = ffi_utils::const_c_char_array_to_path_buf(ptr);

                Some(target)
            }
        }
    }

    /// Returns the mount point's [`UMountNamespace`], or `None` if it is
    /// not set.
    pub fn target_namespace(&self) -> Option<UMountNamespace<'_>> {
        log::debug!("Unmount::target_namespace getting mount point's namespace");

        let mut ptr = MaybeUninit::<*mut libmount::libmnt_ns>::zeroed();

        unsafe {
            ptr.write(libmount::mnt_context_get_target_ns(self.inner));
        }

        match unsafe { ptr.assume_init() } {
            ptr if ptr.is_null() => {
                let err_msg = "found no mount point namespace";
                log::debug!("Unmount::target_namespace {}. libmount::mnt_context_get_target_ns returned a NULL pointer", err_msg);

                None
            }
            ptr => {
                log::debug!("Unmount::target_namespace got mount point's namespace");
                let ns = UMountNamespace::from_raw_parts(ptr, self);

                Some(ns)
            }
        }
    }

    /// Returns the exit status of a mount helper (mount.*filesytem*) called by the user. The
    /// resulting value is pertinent only when the method [`Unmount::has_run_umount_helper`] returns
    /// `true`.
    pub fn umount_helper_exit_status(&self) -> i32 {
        let status = unsafe { libmount::mnt_context_get_helper_status(self.inner) };
        log::debug!("Unmount::umount_helper_exit_status value: {:?}", status);

        status
    }

    /// Returns the number of the last error,
    /// [errno](https://www.man7.org/linux/man-pages/man3/errno.3.html), if invoking the
    /// [`mount` syscall](https://www.man7.org/linux/man-pages/man2/mount.2.html) syscall resulted in a
    /// failure.
    pub fn umount_syscall_errno(&self) -> Option<i32> {
        log::debug!("Unmount::umount_syscall_errno getting mount(2) syscall error number");

        let result = unsafe { libmount::mnt_context_get_syscall_errno(self.inner) };

        match result {
            0 => {
                let err_msg = "mount(2) syscall was never invoked, or ran successfully";
                log::debug!("Unmount::mount_syscall_errno {}. libmount::mnt_context_get_syscall_errno returned error code: 0", err_msg);

                None
            }
            errno => {
                log::debug!("Unmount::mount_syscall_errno got mount(2) syscall error number");

                Some(errno)
            }
        }
    }

    //---- END getters

    //---- BEGIN iterators

    /// Tries to sequentially umount entries in `/proc/self/mountinfo`.
    ///
    /// To filter devices to umount by file system type and/or mount options, use the
    /// methods [`UnmountBuilder::match_file_systems`] and/or [`UnmountBuilder::match_mount_options`]
    /// when instantiating a new `Mount` object.
    pub fn seq_unmount(&mut self) -> UMountIter<'_> {
        UMountIter::new(self).unwrap()
    }

    //---- END iterators

    //---- BEGIN predicates

    /// Returns `true` if this `Unmount` is configured to perform a dry run.
    pub fn is_dry_run(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_fake(self.inner) == 1 };
        log::debug!("Unmount::is_dry_run value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured to be verbose.
    pub fn is_verbose(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_verbose(self.inner) == 1 };
        log::debug!("Unmount::is_verbose value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured to delete loop devices after unmounting them.
    pub fn detaches_loop_device(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_loopdel(self.inner) == 1 };
        log::debug!("Unmount::detaches_loop_device value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured NOT to canonicalize paths.
    pub fn disabled_path_canonicalization(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_nocanonicalize(self.inner) == 1 };
        log::debug!("Unmount::disabled_path_canonicalization value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured NOT to lookup a device or mount point in
    /// `/etc/fstab` if one is not provided when setting this `Unmount`'s source or target.
    pub fn disabled_mount_point_lookup(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_swapmatch(self.inner) == 1 };
        log::debug!("Unmount::disabled_mount_point_lookup value: {:?}", state);

        state
    }

    /// Returns `true` if the [`umount` syscall](https://www.man7.org/linux/man-pages/man2/umount.2.html)
    /// was invoked.
    pub fn has_called_umount_syscall(&self) -> bool {
        let state = unsafe { libmount::mnt_context_syscall_called(self.inner) == 1 };
        log::debug!("Unmount::has_called_umount_syscall value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured NOT to use umount helpers.
    pub fn has_disabled_helpers(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_nohelpers(self.inner) == 1 };
        log::debug!("Unmount::has_disabled_helpers value: {:?}", state);

        state
    }

    /// Returns `true` if a umount helper was run.
    pub fn has_run_umount_helper(&self) -> bool {
        let state = unsafe { libmount::mnt_context_helper_executed(self.inner) == 1 };
        log::debug!("Unmount::has_run_umount_helper value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured to disable userpace mount table updates.
    pub fn does_not_update_utab(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_nohelpers(self.inner) == 1 };
        log::debug!("Unmount::does_not_update_utab value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured to unmount devices lazily.
    pub fn does_lazy_unmount(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_lazy(self.inner) == 1 };
        log::debug!("Unmount::does_lazy_unmount value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured to force device to unmount.
    pub fn forces_unmount(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_force(self.inner) == 1 };
        log::debug!("Unmount::forces_unmount value: {:?}", state);

        state
    }

    /// Returns `true` if this `Unmount` is configured to remount a device in read-only mode after a
    /// failed unmount.
    pub fn on_fail_remounts_read_only(&self) -> bool {
        let state = unsafe { libmount::mnt_context_is_rdonly_umount(self.inner) == 1 };
        log::debug!("Unmount::on_fail_remounts_read_only value: {:?}", state);

        state
    }

    //---- END predicates
}

impl AsRef<Unmount> for Unmount {
    fn as_ref(&self) -> &Unmount {
        self
    }
}

impl Drop for Unmount {
    fn drop(&mut self) {
        log::debug!("Unmount::drop deallocating `Unmount` instance");

        unsafe { libmount::mnt_free_context(self.inner) }
    }
}