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
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
// Copyright (c) 2023 Nick Piaddo
// SPDX-License-Identifier: Apache-2.0 OR MIT
// From dependency library
use enum_iterator::All;
// From standard library
use std::fs::{File, OpenOptions};
use std::mem::MaybeUninit;
use std::os::fd::AsRawFd;
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
// From this library
use crate::core::device::Tag;
use crate::core::device::TagName;
use crate::core::device::Usage;
use crate::core::errors::ConversionError;
use crate::core::partition::FileSystem;
use crate::core::partition::PartitionTableType;
use crate::probe::Filter;
use crate::probe::FsProperty;
use crate::probe::IoHint;
use crate::probe::PartitionIter;
use crate::probe::PartitionScanningOption;
use crate::probe::PrbBuilder;
use crate::probe::ProbeBuilder;
use crate::probe::ProbeError;
use crate::probe::ScanResult;
use crate::probe::TagIter;
use crate::probe::Topology;
use crate::probe::TopologyError;
use crate::ffi_utils;
/// Low-level device probe.
#[derive(Debug)]
pub struct Probe {
pub(crate) inner: libblkid::blkid_probe,
file: File,
is_read_only: bool,
}
impl Probe {
/// Creates a [`ProbeBuilder`] to configure and construct a new`Probe` instance.
///
/// Call the `ProbeBuilder`'s [`build()`](ProbeBuilder::build) method to construct a new `Probe`
/// instance.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::probe::Probe;
///
/// fn main() -> rsblkid::Result<()> {
/// let probe_builder = Probe::builder();
///
/// let probe = probe_builder
/// .scan_device("/dev/vda")
/// .build();
///
/// assert!(probe.is_ok());
///
/// Ok(())
/// }
/// ```
pub fn builder() -> ProbeBuilder {
log::debug!("Probe::builder creating new `ProbeBuilder` instance");
PrbBuilder::builder()
}
#[doc(hidden)]
/// Associate a device to a new blkid_probe C struct.
/// FIXME
/// libblkid::blkid_probe_set_device does not deallocate the file by default if the
/// BLKID_FL_PRIVATE_FD flag is not set in the blkid_probe struct
/// see util-linux/libblkid/src/probe.c:889
/// unless FDGETFDCSTAT is defined
/// see util-linux/libblkid/src/probe.c:977 -> 1006
/// POTENTIAL DOUBLE FREE RISK??
/// Assign a device file descriptor to the probe, reset its internal buffers,
/// state, and close the previously associated device.
///
/// # Arguments
///
/// - ptr -- pointer to a libblkid probe structure.
/// - file -- `File` object associated to the device to probe.
/// - location -- location of the region to probe (offset from the start of the device).
/// - size -- size of the region to probe (a value of `0` <=> probe the whole device/file).
///
fn set_device(
ptr: libblkid::blkid_probe,
file: &mut File,
location: u64,
size: u64,
) -> Result<(), ProbeError> {
log::debug!("Probe::set_device setting device to scan");
let result = unsafe {
libblkid::blkid_probe_set_device(ptr, file.as_raw_fd(), location as i64, size as i64)
};
match result {
0 | 1 => {
log::debug!("Probe::set_device set device to scan");
Ok(())
}
code => {
let err_msg = "failed to set device to scan".to_owned();
log::debug!(
"Probe::set_device {}. libblkid::blkid_probe_set_device returned error code {:?}",
err_msg,
code
);
Err(ProbeError::Config(err_msg))
}
}
}
#[doc(hidden)]
/// Returns a new read only `Probe` on a device.
pub(crate) fn new_read_only<T>(
file_name: T,
scan_segment: (u64, u64),
) -> Result<Probe, ProbeError>
where
T: AsRef<Path>,
{
let file_name = file_name.as_ref();
let (location, size) = &scan_segment;
log::debug!(
"Probe::new_read_only creating a new Probe in read only mode associated with {:?} scanning the {}",
file_name,
if scan_segment == (0, 0) {
"whole device".to_owned()
} else {
format!("region (location: {}, size: {} bytes)", location, size)
}
);
// Custom flags taken from util-linux/libblkid/src/probe.c:215
let status_flags = libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NONBLOCK;
let file = OpenOptions::new()
.read(true)
.custom_flags(status_flags)
.open(file_name)
.map_err(|e| {
let err_msg = format!("failed to open file {:?} {}", file_name, e);
ProbeError::IoOpen(err_msg)
})?;
Self::new(file, scan_segment, false)
}
#[doc(hidden)]
/// Returns a new read-write `Probe` on a device.
pub(crate) fn new_read_write<T>(
file_name: T,
scan_segment: (u64, u64),
) -> Result<Probe, ProbeError>
where
T: AsRef<Path>,
{
let file_name = file_name.as_ref();
let (location, size) = &scan_segment;
log::debug!(
"Probe::new_read_write creating a new Probe in read/write mode associated with {:?} scanning the {}",
file_name,
if scan_segment == (0, 0) {
"whole device".to_owned()
} else {
format!("region (location: {}, size: {} bytes)", location, size)
}
);
// Custom flags taken from util-linux/libblkid/src/probe.c:215
let status_flags = libc::O_RDWR | libc::O_CLOEXEC;
let file = OpenOptions::new()
.read(true)
.custom_flags(status_flags)
.open(file_name)
.map_err(|e| {
let err_msg = format!("failed to open file {:?} {}", file_name, e);
ProbeError::IoOpen(err_msg)
})?;
let mut probe = Self::new(file, scan_segment, false)?;
// Required if we want to erase device properties on device or in memory
let flags = [FsProperty::Magic];
probe.collect_fs_properties(&flags)?;
let option = [PartitionScanningOption::Magic];
probe.set_partitions_scanning_options(&option)?;
Ok(probe)
}
#[doc(hidden)]
/// Returns a new `Probe` instance from a `File` object.
pub(crate) fn new_from_file(file: File, scan_segment: (u64, u64)) -> Result<Probe, ProbeError> {
log::debug!("Probe::new_from_file creating new `Probe` instance from `File`");
Self::new(file, scan_segment, true)
}
#[doc(hidden)]
/// Returns a new `Probe` instance from a `File` object.
pub(crate) fn new_from_file_read_write(
file: File,
scan_segment: (u64, u64),
) -> Result<Probe, ProbeError> {
log::debug!("Probe::new_from_file_read_write creating new `Probe` instance from `File`");
let status = ffi_utils::is_open_read_write(&file).map_err(|e| {
let err_msg = format!("failed to get file status {}", e);
ProbeError::IoError(err_msg)
})?;
if status {
let mut probe = Self::new(file, scan_segment, false)?;
let flags = [FsProperty::Magic];
// Required if we want to erase device properties on device or in memory
probe.collect_fs_properties(&flags)?;
Ok(probe)
} else {
let err_msg =
"failed to create a `Probe` in read/write mode from a read-only `File`".to_owned();
Err(ProbeError::Creation(err_msg))
}
}
#[doc(hidden)]
/// Returns a new `Probe` linked to a device.
pub(crate) fn new(
mut file: File,
scan_segment: (u64, u64),
is_read_only: bool,
) -> Result<Probe, ProbeError> {
let (location, size) = scan_segment;
let mut probe = MaybeUninit::<libblkid::blkid_probe>::zeroed();
// Allocate a new blkid_probe C struct.
unsafe {
probe.write(libblkid::blkid_new_probe());
}
match unsafe { probe.assume_init() } {
ptr if ptr.is_null() => {
let err_msg = "failed to create a new `Probe` instance".to_owned();
log::debug!(
"Probe::new {}. libblkid::blkid_new_probe returned a NULL pointer",
err_msg
);
Err(ProbeError::Creation(err_msg))
}
inner => {
Self::set_device(inner, &mut file, location, size)?;
log::debug!("Probe::new created a new `Probe` instance");
Ok(Self {
inner,
file,
is_read_only,
})
}
}
}
/// Returns the associated block device's identification number (`0` for a regular file).
pub fn device_number(&self) -> u64 {
let dev_num = unsafe { libblkid::blkid_probe_get_devno(self.inner) };
log::debug!("Probe::device_number device has ID number: {:?}", dev_num);
dev_num
}
/// Returns a reference to the [`File`] object associated with the device being scanned.
pub fn device_file(&self) -> &File {
log::debug!("Probe::device_file return `File` object reference");
&self.file
}
/// Returns the size of the associated block device in 512-byte sectors.
pub fn device_size_in_sectors(&self) -> u64 {
log::debug!("Probe::device_size_in_sectors getting block device size (sectors)");
let size = unsafe { libblkid::blkid_probe_get_sectors(self.inner) };
log::debug!(
"Probe::device_size_in_sectors device size (sectors): {:?}",
size
);
size as u64
}
/// Returns the size in bytes of the associated block device.
pub fn device_size(&self) -> u64 {
log::debug!("Probe::device_size getting block device size (bytes)");
let size = self.device_size_in_sectors() * 512;
log::debug!("Probe::device_size block device size (bytes): {:?}", size);
size
}
/// Returns the size in bytes of a logical sector on the associated block device.
pub fn device_logical_sector_size(&self) -> usize {
let size = unsafe { libblkid::blkid_probe_get_sectorsize(self.inner) };
log::debug!(
"Probe::device_logical_sector_size logical sector size (bytes): {:?}",
size
);
size as usize
}
/// Returns the identification number assigned to the whole disk containing the associated block device.
///
/// Returns `0` for a regular file.
pub fn device_whole_disk_number(&self) -> u64 {
let disk_num = unsafe { libblkid::blkid_probe_get_wholedisk_devno(self.inner) };
log::debug!(
"Probe::device_whole_disk_number disk identification number: {:?}",
disk_num
);
disk_num
}
/// Defines a segment of bytes to skip while scanning the associated block device. Data in
/// memory buffers matching the given range are filled with zeros.
///
/// - **Warning:** configuration about segments to skip is discarded when the function
/// [`Probe::empty_buffers`] is called.
///
/// # Arguments
///
/// - `from` -- location (in bytes) of the segment to skip (i.e. offset).
/// - `length` -- length of the segment to skip.
pub fn device_skip_bytes(&mut self, from: u64, length: u64) -> Result<(), ProbeError> {
log::debug!(
"Probe::device_skip_bytes skipping segment (from: {:?}, length: {:?})",
from,
length
);
let result = unsafe { libblkid::blkid_probe_hide_range(self.inner, from, length) };
match result {
0 => {
log::debug!(
"Probe::device_skip_bytes skipped segment (from: {:?}, length: {:?})",
from,
length
);
Ok(())
}
code => {
let err_msg = format!(
"failed to skip segment (from: {}, length: {})",
from, length
);
log::debug!("Probe::device_skip_bytes {}. libblkid::blkid_probe_hide_range returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Returns `true` when the device associated to the `Probe` is a whole disk instead of a partition.
pub fn is_device_whole_disk(&self) -> bool {
let res = unsafe { libblkid::blkid_probe_is_wholedisk(self.inner) == 1 };
log::debug!("Probe::is_device_whole_disk {}", res);
res
}
/// Returns `true` if the device associated to the `Probe` is a partition.
pub fn is_device_partition(&self) -> bool {
let res = unsafe { libblkid::blkid_probe_is_wholedisk(self.inner) == 0 };
log::debug!("Probe::is_device_partition {}", res);
res
}
/// Returns the location of the segment being scanned with respect to the device's first byte.
pub fn scanned_device_segment_location(&self) -> u64 {
log::debug!(
"Probe::scanned_device_segment_location getting scanned segment location (bytes)"
);
let location = unsafe { libblkid::blkid_probe_get_offset(self.inner) };
log::debug!(
"Probe::scanned_device_segment_location scanned segment location (bytes): {:?}",
location
);
location as u64
}
/// Returns the size in bytes of the segment being scanned.
///
/// Returns the size of the whole block device when no limits were defined for the region to scan.
pub fn scanned_device_segment_size(&self) -> u64 {
log::debug!("Probe::scanned_device_segment_size getting scanned segment size (bytes)");
let size = unsafe { libblkid::blkid_probe_get_size(self.inner) };
log::debug!(
"Probe::scanned_device_segment_size scanned segment size (bytes): {}",
size
);
size as u64
}
/// Resets and frees all cached buffers.
///
/// For performance, `Probe` maintains an in-memory cache of the characteristics of its
/// associated device. Calling this function will invalidate the cache's buffers.
///
/// The next call to [`Probe::run_scan`] will read data directly from the `Probe`'s associated
/// block device.
pub fn empty_buffers(&mut self) -> Result<(), ProbeError> {
log::debug!("Probe::empty_buffers emptying buffers");
let result = unsafe { libblkid::blkid_probe_reset_buffers(self.inner) };
match result {
0 => {
log::debug!("Probe::empty_buffers emptied buffers");
Ok(())
}
code => {
let err_msg = "failed to empty buffers".to_owned();
log::debug!(
"Probe::empty_buffers {}. libblkid::blkid_probe_reset_buffers returned error code {:?}",
err_msg,
code
);
Err(ProbeError::Config(err_msg))
}
}
}
/// Sets I/O hints about a device.
///
/// Some legacy devices do not provide I/O hints, this function allows you to define the
/// missing values for optimal performance.
///
/// Currently, the only I/O hint supported by the library is `"session_offset"` for designating
/// the location (in bytes) of a session on a multi-session device in Universal Disk Format (UDF).
pub fn set_hint(&mut self, hint: &IoHint) -> Result<(), ProbeError> {
let hint_cstr = hint.name_to_c_string().map_err(|e| {
let err_msg = format!("failed to convert {:?} to a `CString`. {}", hint.name(), e);
ConversionError::CString(err_msg)
})?;
let value = hint.value();
log::debug!(
"Probe::set_hint setting hint {:?} with value {:?}",
hint,
value
);
let result =
unsafe { libblkid::blkid_probe_set_hint(self.inner, hint_cstr.as_ptr(), value) };
match result {
0 => {
log::debug!("Probe::set_hint set hint {:?} with value {:?}", hint, value);
Ok(())
}
code => {
let err_msg = format!("failed to set hint {:?} with velue {:?}", hint, value);
log::debug!(
"Probe::set_hint {}. libblkid::blkid_probe_set_hint returned error code {:?}",
err_msg,
code
);
Err(ProbeError::Config(err_msg))
}
}
}
/// Discards all hints set by [`Probe::set_hint`].
pub fn discard_hints(&mut self) {
log::debug!("Probe::discard_hints discarding hints");
unsafe { libblkid::blkid_probe_reset_hints(self.inner) }
}
#[doc(hidden)]
/// Sets how many consecutive bytes amount to a sector.
/// Note that blkid_probe_set_device() resets this setting. Use it after
/// blkid_probe_set_device() and before any probing call.
pub(crate) fn set_bytes_per_sector(&self, size: u32) -> Result<(), ProbeError> {
log::debug!("Probe::set_bytes_per_sector setting sector size");
let result = unsafe { libblkid::blkid_probe_set_sectorsize(self.inner, size) };
match result {
0 => {
log::debug!(
"Probe::set_bytes_per_sector set bytes per sector to {:?}",
size
);
Ok(())
}
code => {
let err_msg = format!("failed to set bytes per sector to: {:?}", size);
log::debug!("Probe::set_bytes_per_sector {}. libblkid::blkid_probe_set_sectorsize returned error code {}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Reverts the `Probe` to its state at creation.
pub fn reset(&mut self) {
log::debug!("Probe::reset resetting probe");
unsafe { libblkid::blkid_reset_probe(self.inner) }
}
#[doc(hidden)]
/// Convert a return code to a `ScanResult`.
///
/// # Arguments
///
/// - `returned_code` -- code returned by any of the `libblkid::blkid_do_*` functions.
/// - `libblkid_fn_name` -- fully-qualified libblkid function name (e.g. `libblkid::do_fullprobe`).
/// - `fn_name` -- equivalent rsblkid fully-qualified function name (e.g. `Probe::find_device_properties`).
fn to_scan_result(returned_code: i32, libblkid_fn_name: &str, fn_name: &str) -> ScanResult {
match returned_code {
libblkid::BLKID_PROBE_AMBIGUOUS => {
let res = ScanResult::ConflictingValues;
log::debug!("{} returned {:?}", fn_name, res);
res
}
libblkid::BLKID_PROBE_ERROR => {
let res = ScanResult::Error;
log::debug!("{} returned {:?}", fn_name, res);
res
}
libblkid::BLKID_PROBE_OK => {
let res = ScanResult::FoundProperties;
log::debug!("{} returned {:?}", fn_name, res);
res
}
libblkid::BLKID_PROBE_NONE => {
let res = ScanResult::NoProperties;
log::debug!("{} returned {:?}", fn_name, res);
res
}
code => {
log::debug!(
"{} reached an unexpected state. {} returned error code {:?}",
fn_name,
libblkid_fn_name,
code
);
ScanResult::Exception(code)
}
}
}
/// Runs search functions for device properties, collects data from the first match in a
/// requested category, then moves onto the next (as described in the
/// [overview](crate::probe#overview) of the `probe` module).
///
/// # Returns
///
/// - [`ScanResult::FoundProperties`] -- when any of the search functions, in any category, has found device properties.
/// - [`ScanResult::NoProperties`] -- when no search function has found a match in any category.
/// - [`ScanResult::Error`] -- when an error occurred during the scan.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::partition::PartitionTableType;
/// use rsblkid::probe::{Filter, Probe, ScanResult};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// // Assuming `/dev/vda` has an ext4 file system on a partition,
/// // in a GPT partition table
/// .scan_device("/dev/vda")
/// // Search device for the following types of file system.
/// .scan_superblocks_for_file_systems(Filter::In,
/// vec![
/// FileSystem::APFS,
/// FileSystem::NTFS,
/// FileSystem::Ext4,
/// FileSystem::VFAT,
/// FileSystem::ZFS,
/// ])
/// // Activate partition search functions.
/// .scan_device_partitions(true)
/// // Search for partition in the following partition tables
/// .scan_partitions_for_partition_tables(Filter::In,
/// vec![
/// PartitionTableType::AIX,
/// PartitionTableType::BSD,
/// PartitionTableType::GPT,
/// PartitionTableType::SGI,
/// ])
/// .build()?;
///
/// // Probe state
/// // Legend: [*] has run [ ] did not run [#] has matched
/// //
/// // Before
/// //
/// // category: superblocks
/// // search function: APFS [ ]
/// // search function: NTFS [ ]
/// // search function: Ext4 [ ]
/// // search function: VFAT [ ]
/// // search function: ZFS [ ]
/// // category: partitions
/// // search function: AIX [ ]
/// // search function: BSD [ ]
/// // search function: GPT [ ]
/// // search function: SGI [ ]
/// match probe.find_device_properties() {
/// // After
/// //
/// // category: superblocks
/// // search function: APFS [*]
/// // search function: NTFS [*]
/// // search function: Ext4 [#]
/// // search function: VFAT [ ]
/// // search function: ZFS [ ]
/// // category: partitions
/// // search function: AIX [*]
/// // search function: BSD [*]
/// // search function: GPT [#]
/// // search function: SGI [ ]
/// ScanResult::FoundProperties => {
/// // Print collected file system properties
/// for property in probe.iter_device_properties() {
/// println!("{property}")
/// }
///
/// // Print metadata about partition table entries
/// // Header
/// println!("Partition table");
/// println!("{} {:>10} {:>10} {:>10}\n----", "number", "start", "size", "part_type");
///
/// for partition in probe.iter_partitions() {
/// let number = partition.number();
/// let start = partition.location_in_sectors();
/// let size = partition.size_in_sectors();
/// let part_type = partition.partition_type();
///
/// // Row
/// println!("#{}: {:>10} {:>10} 0x{:x}", number, start, size, part_type)
/// }
/// }
/// _ => eprintln!("could not find any supported file system properties"),
/// }
///
/// Ok(())
/// }
/// ```
pub fn find_device_properties(&mut self) -> ScanResult {
log::debug!("Probe::find_device_properties collecting all device properties");
let rc = unsafe { libblkid::blkid_do_fullprobe(self.inner) };
Self::to_scan_result(
rc,
"libblkid::blkid_do_fullprobe",
"Probe::find_device_properties",
)
}
/// Follows the same process as [`Probe::find_device_properties`]. However, instead of moving
/// onto the next category after finding a match, this method continues to run the remaining
/// non-executed search functions in each category, telling the caller about any data collision
/// it detects.
///
/// # Returns
///
/// - [`ScanResult::FoundProperties`] -- when any of the search functions, in any category, has found device properties.
/// - [`ScanResult::ConflictingValues`] -- when several search functions in the same category
/// have found identical device properties with different values.
/// - [`ScanResult::NoProperties`] -- when no search function has found a match in any category.
/// - [`ScanResult::Error`] -- when an error occurred during the scan.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::partition::PartitionTableType;
/// use rsblkid::probe::{Filter, Probe, ScanResult};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// // Assuming `/dev/vda` has an ext4 file system on a partition,
/// // in a GPT partition table
/// .scan_device("/dev/vda")
/// // Search device for the following types of file system.
/// .scan_superblocks_for_file_systems(Filter::In,
/// vec![
/// FileSystem::APFS,
/// FileSystem::NTFS,
/// FileSystem::Ext4,
/// FileSystem::VFAT,
/// FileSystem::ZFS,
/// ])
/// // Activate partition search functions.
/// .scan_device_partitions(true)
/// // Search for partition in the following partition tables
/// .scan_partitions_for_partition_tables(Filter::In,
/// vec![
/// PartitionTableType::AIX,
/// PartitionTableType::BSD,
/// PartitionTableType::GPT,
/// PartitionTableType::SGI,
/// ])
/// .build()?;
///
/// // Probe state
/// // Legend: [*] has run [ ] did not run [#] has matched
/// //
/// // Before
/// //
/// // category: superblocks
/// // search function: APFS [ ]
/// // search function: NTFS [ ]
/// // search function: Ext4 [ ]
/// // search function: VFAT [ ]
/// // search function: ZFS [ ]
/// // category: partitions
/// // search function: AIX [ ]
/// // search function: BSD [ ]
/// // search function: GPT [ ]
/// // search function: SGI [ ]
/// match probe.find_all_device_properties() {
/// // After
/// //
/// // category: superblocks
/// // search function: APFS [*]
/// // search function: NTFS [*]
/// // search function: Ext4 [#]
/// // search function: VFAT [*]
/// // search function: ZFS [*]
/// // category: partitions
/// // search function: AIX [*]
/// // search function: BSD [*]
/// // search function: GPT [#]
/// // search function: SGI [*]
/// ScanResult::FoundProperties => {
/// // Print collected file system properties
/// for property in probe.iter_device_properties() {
/// println!("{property}")
/// }
///
/// // Print metadata about partition table entries
/// // Header
/// println!("Partition table");
/// println!("{} {:>10} {:>10} {:>10}\n----", "number", "start", "size", "part_type");
///
/// for partition in probe.iter_partitions() {
/// let number = partition.number();
/// let start = partition.location_in_sectors();
/// let size = partition.size_in_sectors();
/// let part_type = partition.partition_type();
///
/// // Row
/// println!("#{}: {:>10} {:>10} 0x{:x}", number, start, size, part_type)
/// }
/// }
/// _ => eprintln!("could not find any supported file system properties"),
/// }
///
/// Ok(())
/// }
/// ```
pub fn find_all_device_properties(&mut self) -> ScanResult {
log::debug!("Probe::find_all_device_properties collecting all device properties and checking value consistencies");
let rc = unsafe { libblkid::blkid_do_safeprobe(self.inner) };
Self::to_scan_result(
rc,
"libblkid::blkid_do_safeprobe",
"Probe::find_all_device_properties",
)
}
/// Runs sequentially each search function for device properties in the current category, until
/// one matches. It then collects the device properties found, and saves its last position in
/// the sequence resuming the search process on the next function call.
///
/// When all search functions have run for a given category, `run_scan` moves onto the next,
/// and applies the same process again.
///
/// # Returns
///
/// - [`ScanResult::FoundProperties`] -- when a search function has found device properties.
/// - [`ScanResult::NoProperties`] -- when no search function has found a match.
/// - [`ScanResult::Error`] -- when an error occurred during the scan.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::partition::PartitionTableType;
/// use rsblkid::probe::{Filter, Probe, ScanResult};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// // Assuming `/dev/vda` has an ext4 file system on a partition,
/// // in a GPT partition table
/// .scan_device("/dev/vda")
/// // Search device for the following types of file system.
/// .scan_superblocks_for_file_systems(Filter::In,
/// vec![
/// FileSystem::APFS,
/// FileSystem::NTFS,
/// FileSystem::Ext4,
/// FileSystem::VFAT,
/// FileSystem::ZFS,
/// ])
/// // Activate partition search functions.
/// .scan_device_partitions(true)
/// // Search for partition in the following partition tables
/// .scan_partitions_for_partition_tables(Filter::In,
/// vec![
/// PartitionTableType::AIX,
/// PartitionTableType::BSD,
/// PartitionTableType::GPT,
/// PartitionTableType::SGI,
/// ])
/// .build()?;
///
/// // Probe state
/// // Legend: [*] has run [ ] did not run [#] has matched
/// //
/// // Before
/// //
/// // category: superblocks
/// // search function: APFS [ ]
/// // search function: NTFS [ ]
/// // search function: Ext4 [ ]
/// // search function: VFAT [ ]
/// // search function: ZFS [ ]
/// // category: partitions
/// // search function: AIX [ ]
/// // search function: BSD [ ]
/// // search function: GPT [ ]
/// // search function: SGI [ ]
/// match probe.run_scan() {
/// // After
/// //
/// // category: superblocks
/// // search function: APFS [*]
/// // search function: NTFS [*]
/// // search function: Ext4 [#] ◁─── last position
/// // search function: VFAT [ ]
/// // search function: Zfs [ ]
/// // category: partitions
/// // search function: AIX [ ]
/// // search function: BSD [ ]
/// // search function: GPT [ ]
/// // search function: SGI [ ]
/// ScanResult::FoundProperties => {
/// // Print collected file system properties
/// for property in probe.iter_device_properties() {
/// println!("{property}")
/// }
/// }
/// _ => eprintln!("could not find any supported file system properties"),
/// }
///
/// // Second function call
/// match probe.run_scan() {
/// // category: superblocks
/// // search function: Apfs [*]
/// // search function: Ntfs [*]
/// // search function: Ext4 [#]
/// // search function: VFAT [ ]
/// // search function: Zfs [ ]
/// // category: partitions
/// // search function: AIX [*] ◁─── resumes here
/// // search function: BSD [*]
/// // search function: GPT [#] ◁─── last position
/// // search function: SGI [ ]
/// ScanResult::FoundProperties => {
/// // Print metadata about partition table entries
/// // Header
/// println!("Partition table");
/// println!("{} {:>10} {:>10} {:>10}\n----", "number", "start", "size", "part_type");
///
/// for partition in probe.iter_partitions() {
/// let number = partition.number();
/// let start = partition.location_in_sectors();
/// let size = partition.size_in_sectors();
/// let part_type = partition.partition_type();
///
/// // Row
/// println!("#{}: {:>10} {:>10} 0x{:x}", number, start, size, part_type)
/// }
/// }
/// _ => panic!("could not find any supported partition metadata"),
/// }
///
/// Ok(())
/// }
/// ```
pub fn run_scan(&mut self) -> ScanResult {
log::debug!("Probe::run_scan searching for next device properties");
let rc = unsafe { libblkid::blkid_do_probe(self.inner) };
Self::to_scan_result(rc, "libblkid::blkid_do_probe", "Probe::run_scan")
}
/// Sets the current position in the sequence of search functions to that of the one executed before last.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::probe::{Filter, FsProperty, Probe, ScanResult};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// // Assuming `/dev/vda` has an ext4 file system
/// .scan_device("/dev/vda")
/// // Search device for the following types of file system.
/// .scan_superblocks_for_file_systems(Filter::In,
/// vec![
/// FileSystem::APFS,
/// FileSystem::NTFS,
/// FileSystem::Ext4,
/// FileSystem::VFAT,
/// FileSystem::ZFS,
/// ])
/// .build()?;
///
/// // Probe state
/// // Legend: [*] has run [ ] did not run [#] has matched
/// //
/// // Before
/// //
/// // category: superblocks
/// // search function: APFS [ ]
/// // search function: NTFS [ ]
/// // search function: Ext4 [ ]
/// // search function: VFAT [ ]
/// // search function: ZFS [ ]
/// match probe.run_scan() {
/// // After
/// //
/// // category: superblocks
/// // search function: APFS [*]
/// // search function: NTFS [*]
/// // search function: Ext4 [#] ◁─── last position
/// // search function: VFAT [ ]
/// // search function: ZFS [ ]
/// ScanResult::FoundProperties => {
/// // Print collected file system properties
/// for property in probe.iter_device_properties() {
/// println!("{property}")
/// }
/// }
/// _ => eprintln!("could not find any supported file system properties"),
/// }
///
/// // Probe state
/// // Legend: [*] has run [ ] did not run [#] has matched
/// //
/// // Before
/// //
/// // category: superblocks
/// // search function: APFS [*]
/// // search function: NTFS [*]
/// // search function: Ext4 [#] ◁─── last position
/// // search function: VFAT [ ]
/// // search function: ZFS [ ]
/// probe.backtrack()?;
/// // After
/// //
/// // category: superblocks
/// // search function: APFS [*]
/// // search function: NTFS [*] ◁─── moved last position one step up
/// // search function: Ext4 [ ]
/// // search function: VFAT [ ]
/// // search function: ZFS [ ]
///
/// Ok(())
/// }
/// ```
pub fn backtrack(&mut self) -> Result<(), ProbeError> {
log::debug!("Probe::backtrack backtracking to previous search function");
let result = unsafe { libblkid::blkid_probe_step_back(self.inner) };
match result {
0 => {
log::debug!("Probe::backtrack backtracked to previous search function");
Ok(())
}
code => {
let err_msg = "failed to backtrack to previous search function".to_owned();
log::debug!(
"Probe::backtrack {}. libblkid::blkid_probe_step_back returned error code: {}",
err_msg,
code
);
Err(ProbeError::Search(err_msg))
}
}
}
/// Marks the last device properties detected for deletion from memory buffers. It also
/// backtracks on the last position in the sequence of search functions, so that the next call
/// to [`Probe::run_scan`] will run the last executed search function again, and effectively
/// overwrite the data.
///
/// **Note:** If you want to delete superblocks with broken checksums, add
/// [`FsProperty::BadChecksum`](crate::probe::FsProperty::BadChecksum) to the list of
/// properties to collect (see [`Probe::collect_fs_properties`]).
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::probe::{Filter, FsProperty, Probe, ScanResult};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// // Assuming `/dev/vda` has an ext4 file system
/// .scan_device("/dev/vda")
/// // Open device in read/write mode.
/// .allow_writes()
/// // Collect the following file system properties.
/// .collect_fs_properties(
/// vec![
/// FsProperty::Label,
/// FsProperty::Version,
/// ]
/// )
/// .build()?;
///
/// // Before metadata deletion
/// let res = probe.run_scan();
/// assert_eq!(res, ScanResult::FoundProperties);
///
/// let properties_before: Vec<_> = probe
/// .iter_device_properties()
/// .collect();
///
/// assert_eq!(properties_before.is_empty(), false);
///
/// // Mark collected file system metadata for deletion from buffers in memory.
/// probe.delete_properties_from_memory()?;
///
/// // Rerun last search function
/// let res = probe.run_scan();
/// assert_eq!(res, ScanResult::NoProperties);
///
/// let properties_after: Vec<_> = probe
/// .iter_device_properties()
/// .collect();
///
/// assert_eq!(properties_after.is_empty(), true);
///
/// Ok(())
/// }
/// ```
pub fn delete_properties_from_memory(&mut self) -> Result<(), ProbeError> {
log::debug!(
"Probe::delete_properties_from_buffer deleting last device properties found from buffer"
);
Self::delete_properties(self.inner, "buffer", true, self.is_read_only)
}
/// Marks the last device properties detected for deletion from the device. It also
/// backtracks on the last position in the sequence of search functions, so that the next call
/// to [`Probe::run_scan`] will run the last executed search function again, and
/// **permanently** overwrite the data.
///
/// **Note:** If you want to delete superblocks with broken checksums, add
/// [`FsProperty::BadChecksum`](crate::probe::FsProperty::BadChecksum) to the list of
/// properties to collect (see [`Probe::collect_fs_properties`]).
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::probe::{Filter, FsProperty, Probe, ScanResult};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// // Assuming `/dev/vda` has an ext4 file system
/// .scan_device("/dev/vda")
/// // Open device in read/write mode.
/// .allow_writes()
/// // Collect the following file system properties.
/// .collect_fs_properties(
/// vec![
/// FsProperty::Label,
/// FsProperty::Version,
/// ]
/// )
/// .build()?;
///
/// // Before metadata deletion
/// let res = probe.run_scan();
/// assert_eq!(res, ScanResult::FoundProperties);
///
/// let properties_before: Vec<_> = probe
/// .iter_device_properties()
/// .collect();
///
/// assert_eq!(properties_before.is_empty(), false);
///
/// // Mark collected file system metadata for deletion from `/dev/vda`.
/// probe.delete_properties_from_device()?;
///
/// // Rerun last search function
/// let res = probe.run_scan();
/// assert_eq!(res, ScanResult::NoProperties);
///
/// let properties_after: Vec<_> = probe
/// .iter_device_properties()
/// .collect();
///
/// assert_eq!(properties_after.is_empty(), true);
///
/// Ok(())
/// }
/// ```
pub fn delete_properties_from_device(&mut self) -> Result<(), ProbeError> {
log::debug!(
"Probe::delete_properties_from_device deleting last property found from device"
);
Self::delete_properties(self.inner, "device", false, self.is_read_only)
}
fn delete_properties(
ptr: libblkid::blkid_probe,
target: &str,
is_dry_run: bool,
is_read_only: bool,
) -> Result<(), ProbeError> {
log::debug!("Probe::delete_properties deleting property");
if !is_read_only {
let dry_run = if is_dry_run { 1 } else { 0 };
let result = unsafe { libblkid::blkid_do_wipe(ptr, dry_run) };
match result {
0 => {
log::debug!(
"Probe::delete_properties deleted device properties from {}",
target
);
Ok(())
}
code => {
log::debug!("Probe::delete_properties failed to delete device properties. libblkid::blkid_do_wipe returned error code {:?}", code);
Err(ProbeError::DeleteProperty(
"failed to delete device properties".to_owned(),
))
}
}
} else {
Err(ProbeError::IoWrite(
"can not delete device properties. `Probe` is in read-only mode".to_owned(),
))
}
}
/// Returns an iterator over the properties gathered during a block device scan as [`Tag`](crate::core::device::Tag)s.
pub fn iter_device_properties(&self) -> TagIter {
log::debug!("Probe::iter_device_properties creating a new `TagIter` instance");
TagIter::new(self)
}
/// Returns the `nth` property gathered during a device scan as a [`Tag`](crate::core::device::Tag).
pub fn nth_device_property(&self, n: usize) -> Option<Tag> {
log::debug!(
"Probe::nth_device_property accessing device property number: {:?}",
n
);
self.iter_device_properties().nth(n)
}
/// Returns `true` if the property of a device associated with a `Probe` has a value.
pub fn device_property_has_value<T>(&self, property: T) -> bool
where
T: AsRef<TagName>,
{
let property = property.as_ref();
let property_cstr = property.to_c_string();
let res =
unsafe { libblkid::blkid_probe_has_value(self.inner, property_cstr.as_ptr()) == 1 };
log::debug!(
"Probe::device_property_has_value does property {:?} have a value? answer: {:?} ",
property,
res
);
res
}
/// Returns the value of a device property.
pub fn lookup_device_property_value<T>(&mut self, property: T) -> Option<Tag>
where
T: AsRef<TagName>,
{
let property = property.as_ref();
let property_cstr = property.to_c_string();
let mut data_ptr = MaybeUninit::<*const libc::c_char>::zeroed();
let mut len: libc::size_t = 0;
log::debug!(
"Probe::lookup_device_property_value looking up value of device property {:?}",
property
);
let result = unsafe {
libblkid::blkid_probe_lookup_value(
self.inner,
property_cstr.as_ptr(),
data_ptr.as_mut_ptr(),
&mut len,
)
};
match result {
0 => {
let data_cstr = unsafe { data_ptr.assume_init() };
let value = ffi_utils::const_c_char_array_to_bytes(data_cstr);
Tag::try_from((property, value)).map(|tag| {
log::debug!(
"Probe::lookup_device_property_value device property {:?} has value {:?}",
property,
tag
);
tag
})
.map_err(|e| {
log::debug!(
"Probe::lookup_device_property_value error while converting value of property {:?} {:?}",
property,
e
);
e
}).ok()
}
code => {
log::debug!("Probe::lookup_device_property_value failed to find a value for device property {:?}. libblkid::blkid_probe_lookup_value returned error code {:?}", property, code);
None
}
}
}
/// Returns the total number of properties gathered by the `Probe`.
///
/// **Warning:** The underlying function [`blkid_probe_numof_values`](https://mirrors.edge.kernel.org/pub/linux/utils/util-linux/v2.39/libblkid-docs/libblkid-Low-level-tags.html#blkid-probe-numof-values)
/// returns `-1` in case of error. However, we assume that an error occurring while counting the number of values is the same as having no value at all and return `0` instead.
///
/// This might explain any discrepancy between values returned by
/// [`Probe::count_device_properties`], and the counting function from the device properties
/// iterator [`TagIter::count`].
pub fn count_device_properties(&self) -> usize {
log::debug!("Probe::count_device_properties counting device properties");
let result = unsafe { libblkid::blkid_probe_numof_values(self.inner) };
match result {
count if count < 0 => {
log::debug!("Probe::count_device_properties failed to count device properties. libblkid::blkid_probe_numof_values returned error code {:?}", count);
0
}
count => {
log::debug!(
"Probe::count_device_properties device properties total: {:?}",
count
);
count as usize
}
}
}
#[doc(hidden)]
/// Activates/Deactivates file system superblock scanning.
fn configure_chain_superblocks(
ptr: libblkid::blkid_probe,
enable: bool,
) -> Result<(), ProbeError> {
log::debug!("Probe::configure_chain_superblocks enable: {}", enable);
let operation = if enable { "enable" } else { "disable" };
let enable = if enable { 1 } else { 0 };
let result = unsafe { libblkid::blkid_probe_enable_superblocks(ptr, enable) };
match result {
0 => {
log::debug!(
"Probe::configure_chain_superblocks {}d superblocks chain",
operation
);
Ok(())
}
code => {
let err_msg = format!("failed to {} superblocks scanning", operation);
log::debug!("Probe::configure_chain_superblocks {}. libblkid::blkid_probe_enable_superblocks returned error code {}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
#[doc(hidden)]
/// Activate file system search functions.
pub(super) fn enable_chain_superblocks(&mut self) -> Result<(), ProbeError> {
log::debug!("Probe::enable_chain_superblocks enabling superblocks chain");
Self::configure_chain_superblocks(self.inner, true)
}
#[doc(hidden)]
/// Deactivate file system search functions.
pub(super) fn disable_chain_superblocks(&mut self) -> Result<(), ProbeError> {
log::debug!("Probe::disable_chain_superblocks disabling superblocks chain");
Self::configure_chain_superblocks(self.inner, false)
}
/// Returns an iterator over all file systems supported by `rsblkid`.
pub fn iter_supported_file_systems() -> All<FileSystem> {
log::debug!("Probe::iter_supported_file_systems iterating all supported file systems");
enum_iterator::all::<FileSystem>()
}
/// Specifies which file systems to search for/exclude when scanning a device. By default,
/// a `Probe` will try to identify any of the supported [`FileSystem`]s.
///
/// **Warning:** Each time this method is called, [`Probe`] discards the last saved position in
/// the sequence of search functions. So, when [`Probe::run_scan`] is called, the search
/// sequence starts over instead of resuming from where it left off.
///
/// Therefore, it is **strongly advised NOT to call** this function while **in a loop**.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::probe::{Filter, Probe};
///
/// fn main() -> rsblkid::Result<()> {
/// let probe = Probe::builder()
/// .scan_device("/dev/vda")
/// .scan_device_superblocks(true)
/// // Specify which file systems to search for when scanning the device, by default all
/// // supported search functions are tried.
/// .scan_superblocks_for_file_systems(Filter::In,
/// vec![
/// FileSystem::APFS,
/// FileSystem::Ext4,
/// FileSystem::VFAT,
/// ])
/// .build()?;
///
/// // Do some work...
///
/// Ok(())
/// }
/// ```
pub fn scan_superblocks_for_file_systems(
&mut self,
filter: Filter,
fs_types: &[FileSystem],
) -> Result<(), ProbeError> {
log::debug!(
"Probe::scan_superblocks_for_file_systems scanning for superblocks with file systems {:?} [{:?}]",
filter,
fs_types
);
// Convert each FileSystem element to CString
let fs_filters: Vec<_> = fs_types.iter().map(|fs| fs.to_c_string()).collect();
// Convert each CString to a C char array
let mut filters: Vec<_> = fs_filters
.iter()
.map(|str| str.as_ptr() as *mut _)
.collect();
// Add a terminal NULL pointer to the array of char arrays
filters.push(std::ptr::null_mut());
let result = unsafe {
libblkid::blkid_probe_filter_superblocks_type(
self.inner,
filter.into(),
filters.as_mut_ptr(),
)
};
match result {
0 => {
log::debug!("Probe::scan_superblocks_for_file_systems scan successful");
Ok(())
}
code => {
let err_msg = format!(
"failed to find superblocks matching the list of file systems: {:?}",
fs_types
);
log::debug!("Probe::scan_superblocks_for_file_systems {}. libblkid::blkid_probe_filter_superblocks_type returned error code {}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Specifies which file systems to search for/exclude when scanning a device based on their
/// [`Usage`]. By default, a `Probe` will try to identify any of the supported [`FileSystem`]s.
///
/// **Warning:** Each time this method is called, [`Probe`] discards the last saved position in
/// the sequence of search functions. So, when [`Probe::run_scan`] is called, the search
/// sequence starts over instead of resuming from where it left off.
///
/// Therefore, it is **strongly advised NOT to call** this function while **in a loop**.
///
/// # Arguments
///
/// - `filter` -- [`Filter`](crate::probe::Filter) for including/excluding .
/// - `usage_flags` -- [`Usage`](crate::core::device::Usage) flags to search for/exclude during a scan.
pub fn scan_superblocks_with_usage_flags(
&mut self,
filter: Filter,
usage_flags: &[Usage],
) -> Result<(), ProbeError> {
let flags_str = usage_flags
.iter()
.map(|u| u.to_string())
.collect::<Vec<_>>()
.join(", ");
log::debug!("Probe::scan_superblocks_with_usage_flags searching for superblocks with usage flags {} [{}]", filter, flags_str);
let flags = usage_flags
.iter()
.fold(0i32, |acc, &item| acc | item as i32);
let result = unsafe {
libblkid::blkid_probe_filter_superblocks_usage(self.inner, filter.into(), flags)
};
match result {
0 => {
log::debug!("Probe::scan_superblocks_with_usage_flags found superblocks with usage flags {} [{}]", filter, flags_str);
Ok(())
}
code => {
let err_msg = format!(
"failed to find superblocks with usage flags {} [{}]",
filter, flags_str
);
log::debug!("Probe::scan_superblocks_with_usage_flags {}. libblkid::blkid_probe_filter_superblocks_usage returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Inverts the scanning [`Filter`](crate::probe::Filter) defined during the [`Probe`]'s creation.
///
/// **Warning:** Each time this method is called, [`Probe`] discards the last saved position in
/// the sequence of search functions. So, when [`Probe::run_scan`] is called, the search
/// sequence starts over instead of resuming from where it left off.
///
/// Therefore, it is **strongly advised NOT to call** this function while **in a loop**.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::probe::{Filter, Probe};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// .scan_device_superblocks(true)
/// .scan_device("/dev/vda")
/// // Search ONLY for the presence of an ext4 file system
/// .scan_superblocks_for_file_systems(Filter::In,
/// vec![
/// FileSystem::Ext4,
/// ])
/// .build()?;
///
/// // Do some work...
///
/// // From now on, the Probe will search for ALL supported file systems EXCEPT ext4...
/// probe.invert_superblocks_scanning_filter()?;
///
/// // ...
///
/// Ok(())
/// }
/// ```
pub fn invert_superblocks_scanning_filter(&mut self) -> Result<(), ProbeError> {
log::debug!(
"Probe::invert_superblocks_scanning_filter inverting superblocks scanning filter"
);
let result = unsafe { libblkid::blkid_probe_invert_superblocks_filter(self.inner) };
match result {
0 => {
log::debug!("Probe::invert_superblocks_scanning_filter inverted superblocks scanning filter");
Ok(())
}
code => {
let err_msg = "failed to invert superblocks scanning filter".to_owned();
log::debug!("Probe::invert_superblocks_scanning_filter {}. libblkid::blkid_probe_invert_superblocks_filter returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Resets the scanning [`Filter`](crate::probe::Filter) of a [`Probe`] to its value
/// at creation.
///
/// **Warning:** Each time this method is called, [`Probe`] discards the last saved position in
/// the sequence of search functions. So, when [`Probe::run_scan`] is called, the search
/// sequence starts over instead of resuming from where it left off.
///
/// Therefore, it is **strongly advised NOT to call** this function while **in a loop**.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::FileSystem;
/// use rsblkid::probe::{Filter, Probe};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// .scan_device("/dev/vda")
/// .scan_device_superblocks(true)
/// // Search ONLY for the presence of an ext4 file system
/// .scan_superblocks_for_file_systems(Filter::In,
/// vec![
/// FileSystem::Ext4,
/// ])
/// .build()?;
///
/// // Do some work...
///
/// // Now, the Probe will search for ALL supported file systems EXCEPT ext4.
/// // This is equivalent to calling the method `scan_superblocks_for_file_systems` above
/// // with the `filter` parameter set to `Filter::Out`.
/// probe.invert_superblocks_scanning_filter()?;
///
/// // ...
///
/// // From this point on, we are BACK to searching ONLY for an ext4 file system...
/// probe.reset_superblocks_scanning_filter()?;
///
/// // ...
///
///
/// Ok(())
/// }
/// ```
pub fn reset_superblocks_scanning_filter(&mut self) -> Result<(), ProbeError> {
log::debug!(
"Probe::reset_superblocks_scanning_filter resetting superblocks scanning filter to initial value"
);
let result = unsafe { libblkid::blkid_probe_reset_superblocks_filter(self.inner) };
match result {
0 => {
log::debug!("Probe::reset_superblocks_scanning_filter superblocks scanning filter reset to initial value");
Ok(())
}
code => {
let err_msg =
"failed to reset superblocks scanning filter to initial value".to_owned();
log::debug!("Probe::reset_superblocks_scanning_filter {}. libblkid::blkid_probe_reset_superblocks_filter returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Collects [`Tag`](crate::core::device::Tag)s matching the given list of file system properties during a
/// device scan.
///
/// To access the data gathered, use the [`Probe::iter_device_properties`] method.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::probe::{FsProperty, Probe};
///
/// fn main() -> rsblkid::Result<()> {
/// let probe = Probe::builder()
/// .scan_device("/dev/vda")
/// .scan_device_superblocks(true)
/// // Collect `Tag`s matching the given list of file system properties
/// // during the device scan.
/// .collect_fs_properties(
/// vec![
/// FsProperty::Label,
/// FsProperty::Uuid,
/// FsProperty::FsInfo,
/// FsProperty::Version,
/// ]
/// )
/// .build()?;
///
/// // Do some work...
///
/// Ok(())
/// }
/// ```
pub fn collect_fs_properties(
&mut self,
fs_properties: &[FsProperty],
) -> Result<(), ProbeError> {
let fs_properties_str = fs_properties
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ");
log::debug!(
"Probe::collect_fs_properties selecting superblocks properties [{}]",
fs_properties_str
);
let fs_properties = fs_properties
.iter()
.fold(0i32, |acc, &item| acc | item as i32);
let result =
unsafe { libblkid::blkid_probe_set_superblocks_flags(self.inner, fs_properties) };
match result {
0 => {
log::debug!("Probe::collect_fs_properties selected superblocks properties");
Ok(())
}
code => {
let err_msg = format!(
"failed to select superblocks properties [{}]",
fs_properties_str
);
log::debug!("Probe::collect_fs_properties {}. libblkid::blkid_probe_set_superblocks_flags returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
//---------- partitions search functions
#[doc(hidden)]
/// Enables/Disables partitions search functions.
fn configure_chain_partitions(
ptr: libblkid::blkid_probe,
enable: bool,
) -> Result<(), ProbeError> {
log::debug!("Probe::configure_chain_partitions enable: {:?}", enable);
let operation = if enable { "enable" } else { "disable" };
let enable = if enable { 1 } else { 0 };
let result = unsafe { libblkid::blkid_probe_enable_partitions(ptr, enable) };
match result {
0 => {
log::debug!(
"Probe::configure_chain_partitions {}d partitions chain",
operation
);
Ok(())
}
code => {
let err_msg = format!("failed to {} partitions scanning", operation);
log::debug!("Probe::configure_chain_partitions {}. libblkid::blkid_probe_enable_partitions returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
#[doc(hidden)]
/// Activate partition search functions.
pub(super) fn enable_chain_partitions(&mut self) -> Result<(), ProbeError> {
log::debug!("Probe::enable_chain_partitions enabling partitions chain");
Self::configure_chain_partitions(self.inner, true)
}
#[doc(hidden)]
/// Deactivate partition search functions.
pub(super) fn disable_chain_partitions(&mut self) -> Result<(), ProbeError> {
log::debug!("Probe::disable_chain_partitions disabling partitions chain");
Self::configure_chain_partitions(self.inner, false)
}
/// Returns an iterator over all supported partition table types.
pub fn iter_supported_partition_tables() -> All<PartitionTableType> {
log::debug!("Probe::iter_supported_partition_tables iterating over list of supported partition tables");
enum_iterator::all::<PartitionTableType>()
}
/// Specifies which kind of partition table to search for/exclude when scanning a device. By default,
/// a `Probe` will try to identify any of the supported [`PartitionTableType`]s.
///
/// **Warning:** Each time this method is called, [`Probe`] discards the last saved position in
/// the sequence of search functions. So, when [`Probe::run_scan`] is called, the search
/// sequence starts over instead of resuming from where it left off.
///
/// Therefore, it is **strongly advised NOT to call** this function while **in a loop**.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::PartitionTableType;
/// use rsblkid::probe::{Filter, Probe};
///
/// fn main() -> rsblkid::Result<()> {
/// let probe = Probe::builder()
/// .scan_device("/dev/vda")
/// .scan_device_partitions(true)
/// // Specify which partition tables to search for when scanning the device, by
/// // default all supported partition table identification functions are tried.
/// .scan_partitions_for_partition_tables(Filter::In,
/// vec![
/// PartitionTableType::AIX,
/// PartitionTableType::BSD,
/// PartitionTableType::GPT,
/// PartitionTableType::DOS,
/// ])
/// .build()?;
///
/// // Do some work...
///
/// Ok(())
/// }
/// ```
pub fn scan_partitions_for_partition_tables(
&mut self,
filter: Filter,
pt_types: &[PartitionTableType],
) -> Result<(), ProbeError> {
log::debug!(
"Probe::scan_partitions_for_partition_tables scanning partitions for partition tables {} [{:?}]",
filter,
pt_types
);
// convert PartitionTableType to CString
let filters_cstring: Vec<_> = pt_types.iter().map(|ptt| ptt.to_c_string()).collect();
// convert to char array
let mut filters: Vec<_> = filters_cstring
.iter()
.map(|cstr| cstr.as_ptr() as *mut _)
.collect();
// Add a terminal NULL pointer to the array of char arrays
filters.push(std::ptr::null_mut());
let result = unsafe {
libblkid::blkid_probe_filter_partitions_type(
self.inner,
filter.into(),
filters.as_mut_ptr(),
)
};
match result {
0 => {
log::debug!("Probe::scan_partitions_for_partition_tables scan successful");
Ok(())
}
code => {
let err_msg = format!(
"failed to find partitions matching the criteria: [{:?}]",
pt_types
);
log::debug!("Probe::scan_partitions_for_partition_tables {}. libblkid::blkid_probe_filter_partitions_type returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Inverts the scanning [`Filter`](crate::probe::Filter) defined during the [`Probe`]'s creation.
///
/// **Warning:** Each time this method is called, [`Probe`] discards the last saved position in
/// the sequence of search functions. So, when [`Probe::run_scan`] is called, the search
/// sequence starts over instead of resuming from where it left off.
///
/// Therefore, it is **strongly advised NOT to call** this function while **in a loop**.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::PartitionTableType;
/// use rsblkid::probe::{Filter, Probe};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// .scan_device("/dev/vda")
/// .scan_device_partitions(true)
/// // Search ONLY for the presence of a GPT partition table
/// .scan_partitions_for_partition_tables(Filter::In,
/// vec![
/// PartitionTableType::GPT,
/// ])
/// .build()?;
///
/// // Do some work...
///
/// // From now on, the Probe will search for ALL supported partition tables EXCEPT GPT...
/// probe.invert_partitions_scanning_filter()?;
///
/// // ...
///
/// Ok(())
/// }
/// ```
pub fn invert_partitions_scanning_filter(&mut self) -> Result<(), ProbeError> {
log::debug!(
"Probe::invert_partitions_scanning_filter inverting partitions scanning filter"
);
let result = unsafe { libblkid::blkid_probe_invert_partitions_filter(self.inner) };
match result {
0 => {
log::debug!(
"Probe::invert_partitions_scanning_filter inverted partitions scanning filter"
);
Ok(())
}
code => {
let err_msg = "failed to invert partitions scanning filter".to_owned();
log::debug!("Probe::invert_partitions_scanning_filter {}. libblkid::blkid_probe_invert_partitions_filter returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Resets the scanning [`Filter`](crate::probe::Filter) of a [`Probe`] to its value
/// at creation.
///
/// **Warning:** Each time this method is called, [`Probe`] discards the last saved position in
/// the sequence of search functions. So, when [`Probe::run_scan`] is called, the search
/// sequence starts over instead of resuming from where it left off.
///
/// Therefore, it is **strongly advised NOT to call** this function while **in a loop**.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::partition::PartitionTableType;
/// use rsblkid::probe::{Filter, Probe};
///
/// fn main() -> rsblkid::Result<()> {
/// let mut probe = Probe::builder()
/// .scan_device("/dev/vda")
/// .scan_device_partitions(true)
/// // Search ONLY for the presence of partition entries in a GPT partition table
/// .scan_partitions_for_partition_tables(Filter::In,
/// vec![
/// PartitionTableType::GPT,
/// ])
/// .build()?;
///
/// // Do some work...
///
/// // From now on, the Probe will search in ALL supported partition tables EXCEPT GPT...
/// probe.invert_partitions_scanning_filter()?;
///
/// // ...
///
/// // From this point on, we are BACK to searching ONLY in a GPT partition table...
/// probe.reset_partitions_scanning_filter()?;
///
/// // ...
///
/// Ok(())
/// }
/// ```
pub fn reset_partitions_scanning_filter(&mut self) -> Result<(), ProbeError> {
log::debug!(
"Probe::reset_partitions_scanning_filter resetting partitions scanning filter to initial value"
);
let result = unsafe { libblkid::blkid_probe_reset_partitions_filter(self.inner) };
match result {
0 => {
log::debug!(
"Probe::reset_partitions_scanning_filter partitions scanning filter reset to initial value"
);
Ok(())
}
code => {
let err_msg =
"failed to reset partitions scanning filter to initial value".to_owned();
log::debug!("Probe::reset_partitions_scanning_filter {}. libblkid::blkid_probe_reset_partitions_filter returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Sets optional properties to collect, or methods to use during a scan.
///
/// # Examples
///
/// ```ignore
/// use rsblkid::probe::{PartitionScanningOption, Probe};
///
/// fn main() -> rsblkid::Result<()> {
/// let probe = Probe::builder()
/// .scan_device("/dev/vda")
/// .scan_device_partitions(true)
/// // Set additional data to collect on partitions, and collection methods to use
/// .partitions_scanning_options(
/// vec![
/// PartitionScanningOption::EntryDetails,
/// PartitionScanningOption::ForceGPT,
/// ])
/// .build()?;
///
/// // Do some work...
///
/// Ok(())
/// }
/// ```
pub fn set_partitions_scanning_options(
&mut self,
options: &[PartitionScanningOption],
) -> Result<(), ProbeError> {
let options_str = options
.iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(", ");
log::debug!(
"Probe::set_partitions_scanning_options setting partition scanning options [{}]",
options_str
);
let flag = options.iter().fold(0i32, |acc, &item| {
let item: i32 = item.into();
acc | item
});
let result = unsafe { libblkid::blkid_probe_set_partitions_flags(self.inner, flag) };
match result {
0 => {
log::debug!(
"Probe::set_partitions_scanning_options set partition scanning options"
);
Ok(())
}
code => {
let err_msg = format!("failed to set partitions scanning options: {}", options_str);
log::debug!("Probe::set_partitions_scanning_options {}. libblkid::blkid_probe_set_partitions_flags returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
/// Returns an iterator over all [`Partition`](crate::probe::Partition)s found after a device scan.
pub fn iter_partitions(&self) -> PartitionIter {
log::debug!("Probe::iter_partitions iterating over list of device partitions");
PartitionIter::new(self)
}
//---------- device topology search functions
#[doc(hidden)]
/// Activates/Deactivates topology search functions.
fn configure_chain_topology(
ptr: libblkid::blkid_probe,
enable: bool,
) -> Result<(), ProbeError> {
log::debug!("Probe::configure_chain_topology enable: {:?}", enable);
let operation = if enable { "enable" } else { "disable" };
let enable = if enable { 1 } else { 0 };
let result = unsafe { libblkid::blkid_probe_enable_topology(ptr, enable) };
match result {
0 => {
log::debug!(
"Probe::configure_chain_topology {}d topology chain",
operation
);
Ok(())
}
code => {
let err_msg = format!(
"Probe::configure_chain_topology failed to {} topology chain",
operation
);
log::debug!("Probe::configure_chain_topology {}. libblkid::blkid_probe_enable_topology returned error code {:?}", err_msg, code);
Err(ProbeError::Config(err_msg))
}
}
}
#[doc(hidden)]
/// Activate topology search functions.
pub(super) fn enable_chain_topology(&mut self) -> Result<(), ProbeError> {
log::debug!("Probe::enable_chain_topology enabling topology chain");
Self::configure_chain_topology(self.inner, true)
}
#[doc(hidden)]
/// Deactivate topology search functions.
pub(super) fn disable_chain_topology(&mut self) -> Result<(), ProbeError> {
log::debug!("Probe::disable_chain_topology disabling topology chain");
Self::configure_chain_topology(self.inner, false)
}
/// Returns metadata about a device's topology.
pub fn topology(&self) -> Result<Topology, ProbeError> {
log::debug!("Probe::topology getting device topology");
let mut ptr = MaybeUninit::<libblkid::blkid_topology>::zeroed();
unsafe {
ptr.write(libblkid::blkid_probe_get_topology(self.inner));
}
match unsafe { ptr.assume_init() } {
topology if topology.is_null() => {
let err_msg = "failed to get device topology".to_owned();
log::debug!("Probe::topology {}. libblkid::blkid_probe_get_topology returned a NULL pointer", err_msg);
Err(ProbeError::from(TopologyError::Creation(err_msg)))
}
topology => {
log::debug!("Probe::topology got device topology");
Ok(Topology::new(self, topology))
}
}
}
}
impl Drop for Probe {
fn drop(&mut self) {
log::debug!("Probe:: deallocating probe instance");
unsafe { libblkid::blkid_free_probe(self.inner) }
}
}
#[cfg(test)]
#[allow(unused_imports)]
mod tests {
use super::*;
use pretty_assertions::{assert_eq, assert_ne};
#[test]
#[should_panic(expected = "one of the options `scan_device` or `scan_file` must be set")]
fn probe_one_of_scan_device_or_scan_file_must_be_set() {
let _ = Probe::builder().build().unwrap();
}
#[test]
#[should_panic(expected = "can not set `scan_device` and `scan_file` simultaneously")]
fn probe_scan_device_and_scan_file_are_mutually_exclusive() {
let tmp_file = tempfile::tempfile().unwrap();
let _ = Probe::builder()
.scan_device("/dev/vda")
.scan_file(tmp_file)
.build()
.unwrap();
}
}