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
|
/*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2022 Gothel Software e.K.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <jau/debug.hpp>
#include <jau/file_util.hpp>
#include <cstdint>
#include <cstdlib>
#include <cinttypes>
#include <limits>
#include <cstring>
#include <cstdio>
#include <random>
extern "C" {
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mount.h>
#ifdef __linux__
#include <sys/sendfile.h>
#include <linux/loop.h>
#endif
}
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_NONBLOCK
#define O_NONBLOCK 0
#endif
inline constexpr const int _open_dir_flags = O_RDONLY|O_BINARY|O_NOCTTY|O_DIRECTORY;
using namespace jau;
using namespace jau::fs;
#if defined(__linux__)
#define _USE_STATX_ 1
#define _USE_SENDFILE_ 1
#endif
#if defined(__FreeBSD__)
typedef struct ::stat struct_stat64;
typedef off_t off64_t;
#define __posix_fstatat64 ::fstatat
#define __posix_openat64 ::openat
#else
typedef struct ::stat64 struct_stat64;
#define __posix_fstatat64 ::fstatat64
#define __posix_openat64 ::openat64
#endif
std::string jau::fs::get_cwd() noexcept {
char path[PATH_MAX];
char* res = ::getcwd(path, PATH_MAX);
if( res == path ) {
return std::string(path);
} else {
return std::string();
}
}
static const std::string _slash("/");
static const std::string _slash_dot_slash("/./");
static const std::string _slash_dot("/.");
static const std::string _dot_slash("./");
static const std::string _dot(".");
static const std::string _slash_dotdot_slash("/../");
static const std::string _slash_dotdot("/..");
static const std::string _dotdot("..");
std::string jau::fs::dirname(const std::string_view& path) noexcept {
if( 0 == path.size() ) {
return _dot;
}
size_t end_pos;
if( '/' == path[path.size()-1] ) {
if( 1 == path.size() ) { // maintain a single '/'
return std::string(path);
}
end_pos = path.size()-2;
} else {
end_pos = path.size()-1;
}
size_t idx = path.find_last_of('/', end_pos);
if( idx == std::string_view::npos ) {
return _dot;
} else {
// ensure `/lala` -> '/', i.e. don't cut off single '/'
return std::string( path.substr(0, std::max<size_t>(1, idx)) );
}
}
std::string jau::fs::basename(const std::string_view& path) noexcept {
if( 0 == path.size() ) {
return _dot;
}
size_t end_pos;
if( '/' == path[path.size()-1] ) {
if( 1 == path.size() ) { // maintain a single '/'
return std::string(path);
}
end_pos = path.size()-2;
} else {
end_pos = path.size()-1;
}
size_t idx = path.find_last_of('/', end_pos);
if( idx == std::string_view::npos ) {
return std::string( path.substr(0, end_pos+1));
} else {
return std::string( path.substr(idx+1, end_pos-idx) );
}
}
std::unique_ptr<dir_item::backed_string_view> dir_item::reduce(const std::string_view& path_) noexcept {
constexpr const bool _debug = false;
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.0: path '%s'\n", std::string(path_).c_str());
}
std::unique_ptr<dir_item::backed_string_view> path2 = std::make_unique<dir_item::backed_string_view>(path_);
if( _dot == path_ || _slash == path_ ) {
return path2;
}
// remove initial './'
while( 0 == path2->view.find(_dot_slash) ) {
path2->view = path2->view.substr(2, path2->view.size()-2);
}
// remove trailing slash if not ending with '/./' or '/../'
if( '/' == path2->view[path2->view.size()-1] &&
( path2->view.size() < 3 || std::string_view::npos == path2->view.find(_slash_dot_slash, path2->view.size()-3) ) &&
( path2->view.size() < 4 || std::string_view::npos == path2->view.find(_slash_dotdot_slash, path2->view.size()-4) )
)
{
path2->view = path2->view.substr(0, path2->view.size()-1);
}
// append final '/' to complete '/../' or '/./' sequence
if( ( path2->view.size() >= 3 && std::string_view::npos != path2->view.find(_slash_dotdot, path2->view.size()-3) ) ||
( path2->view.size() >= 2 && std::string_view::npos != path2->view.find(_slash_dot, path2->view.size()-2) ) ) {
path2->backup();
path2->view = path2->backing.append(_slash);
}
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.1: path2 '%s'\n", path2->to_string(true).c_str());
}
// resolve '/./'
size_t spos=0;
size_t idx;
do {
idx = path2->view.find(_slash_dot_slash, spos);
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.2.1: path2: spos %zu, idx %zu, '%s'\n", spos, idx, path2->to_string(true).c_str());
}
if( std::string_view::npos == idx ) {
break;
}
std::string_view pre = path2->view.substr(0, idx);
if( 0 == pre.size() ) {
// case '/./bbb' -> '/bbb'
path2->view = path2->view.substr(idx+2);
spos = 0;
} else {
// case '/zzz/aaa/./bbb' -> '/zzz/aaa/bbb'
const std::string post( path2->view.substr(idx+2) );
path2->backup_and_append( pre, post );
spos = pre.size();
}
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.2.2: path2: spos %zu, '%s'\n", spos, path2->to_string(true).c_str());
}
} while( spos <= path2->view.size()-3 );
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.2.X: path2: '%s'\n", path2->to_string(true).c_str());
}
// resolve '/../'
spos=0;
do {
idx = path2->view.find(_slash_dotdot_slash, spos);
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.3.1: path2: spos %zu, idx %zu, '%s'\n", spos, idx, path2->to_string(true).c_str());
}
if( std::string_view::npos == idx ) {
break;
}
if( 0 == idx ) {
// case '/../bbb' -> Error, End
WARN_PRINT("dir_item::resolve: '..' resolution error: '%s' -> '%s'", std::string(path_).c_str(), path2->to_string().c_str());
return path2;
}
std::string_view pre = path2->view.substr(0, idx);
if( 2 == idx && _dotdot == pre ) {
// case '../../bbb' -> '../../bbb' unchanged
spos = idx+4;
} else if( 3 <= idx && _slash_dotdot == path2->view.substr(idx-3, 3) ) {
// case '../../../bbb' -> '../../../bbb' unchanged
spos = idx+4;
} else {
std::string pre_str = jau::fs::dirname( pre );
if( _slash == pre_str ) {
// case '/aaa/../bbb' -> '/bbb'
path2->view = path2->view.substr(idx+3);
spos = 0;
} else if( _dot == pre_str ) {
// case 'aaa/../bbb' -> 'bbb'
path2->view = path2->view.substr(idx+4);
spos = 0;
} else {
// case '/zzz/aaa/../bbb' -> '/zzz/bbb'
const std::string post( path2->view.substr(idx+3) );
path2->backup_and_append( pre_str, post );
spos = pre_str.size();
}
}
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.3.2: path2: spos %zu, '%s'\n", spos, path2->to_string(true).c_str());
}
} while( spos <= path2->view.size()-4 );
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.3.X: path2: '%s'\n", path2->to_string(true).c_str());
}
// remove trailing slash in path2
if( '/' == path2->view[path2->view.size()-1] ) {
path2->view = path2->view.substr(0, path2->view.size()-1);
}
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "X.X: path2: '%s'\n", path2->to_string(true).c_str());
}
return path2;
}
dir_item::dir_item(std::unique_ptr<backed_string_view> cleanpath) noexcept
: dirname_(jau::fs::dirname(cleanpath->view)), basename_(jau::fs::basename(cleanpath->view)) {
if( _slash == dirname_ && _slash == basename_ ) { // remove duplicate '/' in basename
basename_ = _dot;
}
}
dir_item::dir_item(const std::string& dirname__, const std::string& basename__) noexcept
: dirname_(dirname__), basename_(basename__) {
}
dir_item::dir_item() noexcept
: dirname_(_dot), basename_(_dot) {}
dir_item::dir_item(const std::string_view& path_) noexcept
: dir_item( reduce(path_) )
{ }
std::string dir_item::path() const noexcept {
if( _dot == dirname_ ) {
return basename_;
}
if( _dot == basename_ ) {
return dirname_;
}
if( _slash == dirname_ ) {
return dirname_ + basename_;
}
return dirname_ + _slash + basename_;
}
std::string dir_item::to_string() const noexcept {
return "['"+dirname()+"', '"+basename()+"']";
}
template<typename T>
static void append_bitstr(std::string& out, T mask, T bit, const std::string& bitstr, bool& comma) {
if( is_set( mask, bit )) {
if( comma ) { out.append(", "); }
out.append(bitstr); comma = true;
}
}
#define APPEND_BITSTR(U,V,M) append_bitstr(out, M, U::V, #V, comma);
#define FMODEBITS_ENUM(X,M) \
X(fmode_t,fd,M) \
X(fmode_t,dir,M) \
X(fmode_t,file,M) \
X(fmode_t,link,M) \
X(fmode_t,no_access,M) \
X(fmode_t,not_existing,M)
static void append_bitstr(std::string& out, fmode_t mask, fmode_t bit, const std::string& bitstr) {
if( is_set( mask, bit )) {
out.append(bitstr);
} else {
out.append("-");
}
}
std::string jau::fs::to_string(const fmode_t mask, const bool show_rwx) noexcept {
std::string out;
bool comma = false;
FMODEBITS_ENUM(APPEND_BITSTR,mask)
out.append(", ");
if( show_rwx ) {
if( fmode_t::none != ( mask & fmode_t::ugs_set ) ) {
append_bitstr(out, mask, fmode_t::set_uid, "u");
append_bitstr(out, mask, fmode_t::set_gid, "g");
append_bitstr(out, mask, fmode_t::sticky, "s");
}
const std::string r("r");
const std::string w("w");
const std::string x("x");
append_bitstr(out, mask, fmode_t::read_usr, r);
append_bitstr(out, mask, fmode_t::write_usr, w);
append_bitstr(out, mask, fmode_t::exec_usr, x);
append_bitstr(out, mask, fmode_t::read_grp, r);
append_bitstr(out, mask, fmode_t::write_grp, w);
append_bitstr(out, mask, fmode_t::exec_grp, x);
append_bitstr(out, mask, fmode_t::read_oth, r);
append_bitstr(out, mask, fmode_t::write_oth, w);
append_bitstr(out, mask, fmode_t::exec_oth, x);
} else {
char buf[8];
int len = snprintf(buf, sizeof(buf), "0%o", (unsigned int)(mask & fmode_t::protection_mask));
out.append(std::string(buf, len));
}
return out;
}
std::unique_ptr<std::string> jau::fs::to_named_fd(const int fd) noexcept {
if( 0 > fd ) {
return nullptr;
}
std::unique_ptr<std::string> res = std::make_unique<std::string>("/dev/fd/");
res->append(std::to_string(fd));
return res;
}
int jau::fs::from_named_fd(const std::string& named_fd) noexcept {
int scan_value = -1;
if( 1 == sscanf(named_fd.c_str(), "/dev/fd/%d", &scan_value) ) {
// GNU/Linux, FreeBSD, ... ?
return scan_value;
} else if( 1 == sscanf(named_fd.c_str(), "/proc/self/fd/%d", &scan_value) ) {
// GNU/Linux only?
return scan_value;
}
return -1;
}
#define FILESTATS_FIELD_ENUM(X,M) \
X(file_stats::field_t,type,M) \
X(file_stats::field_t,mode,M) \
X(file_stats::field_t,nlink,M) \
X(file_stats::field_t,uid,M) \
X(file_stats::field_t,gid,M) \
X(file_stats::field_t,atime,M) \
X(file_stats::field_t,mtime,M) \
X(file_stats::field_t,ctime,M) \
X(file_stats::field_t,ino,M) \
X(file_stats::field_t,size,M) \
X(file_stats::field_t,blocks,M) \
X(file_stats::field_t,btime,M)
std::string jau::fs::to_string(const file_stats::field_t mask) noexcept {
std::string out("[");
bool comma = false;
FILESTATS_FIELD_ENUM(APPEND_BITSTR,mask)
out.append("]");
return out;
}
file_stats::file_stats() noexcept
: has_fields_(field_t::none), item_(), link_target_path_(), link_target_(), mode_(fmode_t::not_existing), fd_(-1),
uid_(0), gid_(0), size_(0), btime_(), atime_(), ctime_(), mtime_(),
errno_res_(0)
{}
#if _USE_STATX_
static constexpr bool jau_has_stat(const uint32_t mask, const uint32_t bit) { return bit == ( mask & bit ); }
#endif
file_stats::file_stats(const ctor_cookie& cc, const int dirfd, const dir_item& item, const bool dirfd_is_item_dirname) noexcept
: has_fields_(field_t::none), item_(item), link_target_path_(), link_target_(), mode_(fmode_t::none), fd_(-1),
uid_(0), gid_(0), size_(0), btime_(), atime_(), ctime_(), mtime_(),
errno_res_(0)
{
constexpr const bool _debug = false;
(void)cc;
const std::string full_path( item_.path() );
const std::string& dirfd_path = dirfd_is_item_dirname ? item.basename() : full_path;
{
int scan_value = jau::fs::from_named_fd(full_path);
if( 0 <= scan_value ) {
mode_ = fmode_t::fd;
has_fields_ |= field_t::fd;
fd_ = scan_value;
}
}
#if _USE_STATX_
struct ::statx s;
::bzero(&s, sizeof(s));
int stat_res = ::statx(dirfd, dirfd_path.c_str(),
( AT_NO_AUTOMOUNT | AT_SYMLINK_NOFOLLOW ),
( STATX_BASIC_STATS | STATX_BTIME ), &s);
if( 0 != stat_res ) {
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "file_stats(%d): Test ERROR: '%s', %d, errno %d (%s)\n", (int)cc.rec_level, full_path.c_str(), stat_res, errno, ::strerror(errno));
}
switch( errno ) {
case EACCES:
mode_ |= fmode_t::no_access;
break;
case ENOENT:
mode_ |= fmode_t::not_existing;
break;
default:
break;
}
if( has_access() && exists() ) {
errno_res_ = errno;
}
} else {
if( jau_has_stat( s.stx_mask, STATX_TYPE ) ) {
has_fields_ |= field_t::type;
}
if( has( field_t::type ) ) {
if( S_ISLNK( s.stx_mode ) && !is_fd() ) {
mode_ |= fmode_t::link;
}
if( S_ISREG( s.stx_mode ) ) {
mode_ |= fmode_t::file;
} else if( S_ISDIR( s.stx_mode ) ) {
mode_ |= fmode_t::dir;
}
}
if( jau_has_stat( s.stx_mask, STATX_MODE ) ) {
has_fields_ |= field_t::mode;
// Append POSIX protection bits
mode_ |= static_cast<fmode_t>( s.stx_mode & ( S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX ) );
}
if( jau_has_stat( s.stx_mask, STATX_NLINK ) ) {
has_fields_ |= field_t::nlink;
}
if( jau_has_stat( s.stx_mask, STATX_UID ) ) {
has_fields_ |= field_t::uid;
uid_ = s.stx_uid;
}
if( jau_has_stat( s.stx_mask, STATX_GID ) ) {
has_fields_ |= field_t::gid;
gid_ = s.stx_gid;
}
if( jau_has_stat( s.stx_mask, STATX_ATIME ) || 0 != s.stx_atime.tv_sec || 0 != s.stx_atime.tv_nsec ) { // if STATX_ATIME is not reported but has its value (duh?)
has_fields_ |= field_t::atime;
atime_ = jau::fraction_timespec( s.stx_atime.tv_sec, s.stx_atime.tv_nsec );
}
if( jau_has_stat( s.stx_mask, STATX_MTIME ) ) {
has_fields_ |= field_t::mtime;
mtime_ = jau::fraction_timespec( s.stx_mtime.tv_sec, s.stx_mtime.tv_nsec );
}
if( jau_has_stat( s.stx_mask, STATX_CTIME ) ) {
has_fields_ |= field_t::ctime;
ctime_ = jau::fraction_timespec( s.stx_ctime.tv_sec, s.stx_ctime.tv_nsec );
}
if( jau_has_stat( s.stx_mask, STATX_INO ) ) {
has_fields_ |= field_t::ino;
}
if( jau_has_stat( s.stx_mask, STATX_SIZE ) ) {
if( is_file() && !is_link() ) {
has_fields_ |= field_t::size;
size_ = s.stx_size;
}
}
if( jau_has_stat( s.stx_mask, STATX_BLOCKS ) ) {
has_fields_ |= field_t::blocks;
}
if( jau_has_stat( s.stx_mask, STATX_BTIME ) ) {
has_fields_ |= field_t::btime;
btime_ = jau::fraction_timespec( s.stx_btime.tv_sec, s.stx_btime.tv_nsec );
}
if( is_link() ) {
// follow symbolic link recursively until !exists(), is_file() or is_dir()
std::string link_path;
{
const ssize_t path_link_max_len = 0 < s.stx_size ? s.stx_size + 1 : PATH_MAX;
char* buffer = (char*) ::malloc(path_link_max_len);
ssize_t path_link_len = 0;;
if( nullptr == buffer ) {
errno_res_ = errno;
link_target_ = std::make_shared<file_stats>();
goto errorout;
}
path_link_len = ::readlinkat(dirfd, dirfd_path.c_str(), buffer, path_link_max_len);
if( 0 > path_link_len ) {
errno_res_ = errno;
::free(buffer);
link_target_ = std::make_shared<file_stats>();
goto errorout;
}
// Note: if( path_link_len == path_link_max_len ) then buffer may have been truncated
link_path = std::string(buffer, path_link_len);
}
link_target_path_ = std::make_shared<std::string>(link_path);
if( 0 == cc.rec_level ) {
// Initial symbolic followed: Test recursive loop-error
::bzero(&s, sizeof(s));
stat_res = ::statx(dirfd, dirfd_path.c_str(), AT_NO_AUTOMOUNT, STATX_BASIC_STATS, &s);
if( 0 != stat_res ) {
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "file_stats(%d): Test link ERROR: '%s', %d, errno %d (%s)\n", (int)cc.rec_level, full_path.c_str(), stat_res, errno, ::strerror(errno));
}
switch( errno ) {
case EACCES:
mode_ |= fmode_t::no_access;
break;
case ELOOP:
// Too many symbolic links encountered while traversing the pathname
[[fallthrough]];
case ENOENT:
// A component of pathname does not exist
[[fallthrough]];
default:
// Anything else ..
mode_ |= fmode_t::not_existing;
break;
}
goto errorout;
}
}
if( 0 < link_path.size() && '/' == link_path[0] ) {
link_target_ = std::make_shared<file_stats>(ctor_cookie(cc.rec_level+1), dirfd, dir_item( link_path ), false /* dirfd_is_item_dirname */); // absolute link_path
} else {
link_target_ = std::make_shared<file_stats>(ctor_cookie(cc.rec_level+1), dirfd, dir_item( jau::fs::dirname(full_path), link_path ), dirfd_is_item_dirname );
}
if( link_target_->is_fd() ) {
mode_ |= fmode_t::fd;
has_fields_ |= field_t::fd;
fd_ = link_target_->fd();
} else if( link_target_->is_file() ) {
mode_ |= fmode_t::file;
has_fields_ |= field_t::size;
size_ = link_target_->size();
} else if( link_target_->is_dir() ) {
mode_ |= fmode_t::dir;
} else if( !link_target_->exists() ) {
mode_ |= fmode_t::not_existing;
} else if( !link_target_->has_access() ) {
mode_ |= fmode_t::no_access;
}
}
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "file_stats(%d): '%s', %d, errno %d (%s)\n", (int)cc.rec_level, to_string().c_str(), stat_res, errno, ::strerror(errno));
}
}
#else /* _USE_STATX_ */
struct_stat64 s;
::bzero(&s, sizeof(s));
int stat_res = __posix_fstatat64(dirfd, dirfd_path.c_str(), &s, AT_SYMLINK_NOFOLLOW); // lstat64 compatible
if( 0 != stat_res ) {
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "file_stats(%d): Test ERROR: '%s', %d, errno %d (%s)\n", (int)cc.rec_level, full_path.c_str(), stat_res, errno, ::strerror(errno));
}
switch( errno ) {
case EACCES:
mode_ |= fmode_t::no_access;
break;
case ENOENT:
mode_ |= fmode_t::not_existing;
break;
default:
break;
}
if( has_access() && exists() ) {
errno_res_ = errno;
}
} else {
has_fields_ = field_t::type | field_t::mode | field_t::uid | field_t::gid |
field_t::atime | field_t::ctime | field_t::mtime;
if( S_ISLNK( s.st_mode ) && !is_fd() ) {
mode_ |= fmode_t::link;
}
if( S_ISREG( s.st_mode ) ) {
mode_ |= fmode_t::file;
if( !is_link() ) {
has_fields_ |= field_t::size;
}
} else if( S_ISDIR( s.st_mode ) ) {
mode_ |= fmode_t::dir;
}
// Append POSIX protection bits
mode_ |= static_cast<fmode_t>( s.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX ) );
uid_ = s.st_uid;
gid_ = s.st_gid;
size_ = is_file() ? s.st_size : 0;
atime_ = jau::fraction_timespec( s.st_atim.tv_sec, s.st_atim.tv_nsec );
ctime_ = jau::fraction_timespec( s.st_ctim.tv_sec, s.st_ctim.tv_nsec );
mtime_ = jau::fraction_timespec( s.st_mtim.tv_sec, s.st_mtim.tv_nsec );
if( is_link() ) {
// follow symbolic link recursively until !exists(), is_file() or is_dir()
std::string link_path;
{
const ssize_t path_link_max_len = 0 < s.st_size ? s.st_size + 1 : PATH_MAX;
char* buffer = (char*) ::malloc(path_link_max_len);
ssize_t path_link_len = 0;;
if( nullptr == buffer ) {
errno_res_ = errno;
link_target_ = std::make_shared<file_stats>();
goto errorout;
}
path_link_len = ::readlinkat(dirfd, dirfd_path.c_str(), buffer, path_link_max_len);
if( 0 > path_link_len ) {
errno_res_ = errno;
::free(buffer);
link_target_ = std::make_shared<file_stats>();
goto errorout;
}
// Note: if( path_link_len == path_link_max_len ) then buffer may have been truncated
link_path = std::string(buffer, path_link_len);
}
link_target_path_ = std::make_shared<std::string>(link_path);
if( 0 == cc.rec_level ) {
// Initial symbolic followed: Test recursive loop-error
::bzero(&s, sizeof(s));
stat_res = __posix_fstatat64(dirfd, dirfd_path.c_str(), &s, 0); // stat64 compatible
if( 0 != stat_res ) {
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "file_stats(%d): Test link ERROR: '%s', %d, errno %d (%s)\n", (int)cc.rec_level, full_path.c_str(), stat_res, errno, ::strerror(errno));
}
switch( errno ) {
case EACCES:
mode_ |= fmode_t::no_access;
break;
case ELOOP:
// Too many symbolic links encountered while traversing the pathname
[[fallthrough]];
case ENOENT:
// A component of pathname does not exist
[[fallthrough]];
default:
// Anything else ..
mode_ |= fmode_t::not_existing;
break;
}
goto errorout;
}
}
if( 0 < link_path.size() && '/' == link_path[0] ) {
link_target_ = std::make_shared<file_stats>(ctor_cookie(cc.rec_level+1), dirfd, dir_item( link_path ), false /* dirfd_is_item_dirname */); // absolute link_path
} else {
link_target_ = std::make_shared<file_stats>(ctor_cookie(cc.rec_level+1), dirfd, dir_item( jau::fs::dirname(full_path), link_path ), dirfd_is_item_dirname );
}
if( link_target_->is_fd() ) {
mode_ |= fmode_t::fd;
has_fields_ |= field_t::fd;
fd_ = link_target_->fd();
} else if( link_target_->is_file() ) {
mode_ |= fmode_t::file;
has_fields_ |= field_t::size;
size_ = link_target_->size();
} else if( link_target_->is_dir() ) {
mode_ |= fmode_t::dir;
} else if( !link_target_->exists() ) {
mode_ |= fmode_t::not_existing;
} else if( !link_target_->has_access() ) {
mode_ |= fmode_t::no_access;
}
}
if constexpr ( _debug ) {
jau::fprintf_td(stderr, "file_stats(%d): '%s', %d, errno %d (%s)\n", (int)cc.rec_level, to_string().c_str(), stat_res, errno, ::strerror(errno));
}
}
#endif /* _USE_STATX_ */
errorout: ;
}
file_stats::file_stats(const dir_item& item) noexcept
: file_stats(ctor_cookie(0), AT_FDCWD, item, false /* dirfd_is_item_dirname */)
{}
file_stats::file_stats(const int dirfd, const dir_item& item, const bool dirfd_is_item_dirname) noexcept
: file_stats(ctor_cookie(0), dirfd, item, dirfd_is_item_dirname)
{}
file_stats::file_stats(const std::string& _path) noexcept
: file_stats(ctor_cookie(0), AT_FDCWD, dir_item(_path), false /* dirfd_is_item_dirname */)
{}
file_stats::file_stats(const int dirfd, const std::string& _path) noexcept
: file_stats(ctor_cookie(0), dirfd, dir_item(_path), false /* dirfd_is_item_dirname */)
{}
const file_stats* file_stats::final_target(size_t* link_count) const noexcept {
size_t count = 0;
const file_stats* fs0 = this;
const file_stats* fs1 = fs0->link_target().get();
while( nullptr != fs1 ) {
++count;
fs0 = fs1;
fs1 = fs0->link_target().get();
}
if( nullptr != link_count ) {
*link_count = count;
}
return fs0;
}
bool file_stats::has(const field_t fields) const noexcept {
return fields == ( has_fields_ & fields );
}
bool file_stats::operator ==(const file_stats& rhs) const noexcept {
if( this == &rhs ) {
return true;
}
return item_ == rhs.item_ &&
has_fields_ == rhs.has_fields_ &&
mode_ == rhs.mode_ &&
uid_ == rhs.uid_ && gid_ == rhs.gid_ &&
errno_res_ == rhs.errno_res_ &&
size_ == rhs.size_ &&
btime_ == rhs.btime_ &&
atime_ == rhs.atime_ &&
ctime_ == rhs.ctime_ &&
mtime_ == rhs.mtime_ &&
( !is_link() ||
( link_target_path_ == rhs.link_target_path_&&
link_target_ == rhs.link_target_
)
);
}
std::string file_stats::to_string() const noexcept {
std::string stored_path, link_detail;
{
if( nullptr != link_target_path_ ) {
stored_path = " [-> "+*link_target_path_+"]";
}
size_t link_count;
const file_stats* final_target_ = final_target(&link_count);
if( 0 < link_count ) {
link_detail = " -(" + std::to_string(link_count) + ")-> '" + final_target_->path() + "'";
}
}
std::string res( "file_stats[");
res.append(jau::fs::to_string(mode_))
.append(", '"+item_.path()+"'"+stored_path+link_detail );
if( 0 == errno_res_ ) {
if( has( field_t::fd ) ) {
res.append( ", fd " ).append( std::to_string(fd_) );
}
if( has( field_t::uid ) ) {
res.append( ", uid " ).append( std::to_string(uid_) );
}
if( has( field_t::gid ) ) {
res.append( ", gid " ).append( std::to_string(gid_) );
}
if( has( field_t::size ) ) {
res.append( ", size " ).append( jau::to_decstring( size_ ) );
}
if( has( field_t::btime ) ) {
res.append( ", btime " ).append( btime_.to_iso8601_string() );
}
if( has( field_t::atime ) ) {
res.append( ", atime " ).append( atime_.to_iso8601_string() );
}
if( has( field_t::ctime ) ) {
res.append( ", ctime " ).append( ctime_.to_iso8601_string() );
}
if( has( field_t::mtime ) ) {
res.append( ", mtime " ).append( mtime_.to_iso8601_string() );
}
// res.append( ", fields ").append( jau::fs::to_string( has_fields_ ) );
} else {
res.append( ", errno " ).append( std::to_string(errno_res_) ).append( ", " ).append( std::string(::strerror(errno_res_)) );
}
res.append("]");
return res;
}
bool jau::fs::mkdir(const std::string& path, const fmode_t mode, const bool verbose) noexcept {
file_stats stats(path);
if( stats.is_dir() ) {
if( verbose ) {
jau::fprintf_td(stderr, "mkdir: dir already exists: %s\n", stats.to_string().c_str());
}
return true;
} else if( !stats.exists() ) {
const int dir_err = ::mkdir(path.c_str(), posix_protection_bits(mode));
if ( 0 != dir_err ) {
ERR_PRINT("%s, failure", stats.to_string().c_str());
return false;
} else {
return true;
}
} else {
ERR_PRINT("%s, exists but is no dir", stats.to_string().c_str());
return false;
}
}
bool jau::fs::touch(const std::string& path, const jau::fraction_timespec& atime, const jau::fraction_timespec& mtime, const fmode_t mode) noexcept {
int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, posix_protection_bits(mode));
if( 0 > fd ) {
ERR_PRINT("Couldn't open/create file '%s'", path.c_str());
return false;
}
struct timespec ts2[2] = { atime.to_timespec(), mtime.to_timespec() };
bool res;
if( 0 != ::futimens(fd, ts2) ) {
ERR_PRINT("Couldn't update time of file '%s'", path.c_str());
res = false;
} else {
res = true;
}
::close(fd);
return res;
}
bool jau::fs::touch(const std::string& path, const fmode_t mode) noexcept {
int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, posix_protection_bits(mode));
if( 0 > fd ) {
ERR_PRINT("Couldn't open/create file '%s'", path.c_str());
return false;
}
bool res;
if( 0 != ::futimens(fd, NULL /* current time */) ) {
ERR_PRINT("Couldn't update time of file '%s'", path.c_str());
res = false;
} else {
res = true;
}
::close(fd);
return res;
}
bool jau::fs::get_dir_content(const std::string& path, const consume_dir_item& digest) noexcept {
DIR *dir;
struct dirent *ent;
if( ( dir = ::opendir( path.c_str() ) ) != nullptr ) {
while ( ( ent = ::readdir( dir ) ) != NULL ) {
std::string fname( ent->d_name );
if( _dot != fname && _dotdot != fname ) { // avoid '.' and '..'
digest( dir_item( path, fname ) );
}
}
::closedir (dir);
return true;
} else {
return false;
}
}
bool jau::fs::get_dir_content(const int dirfd, const std::string& path, const consume_dir_item& digest) noexcept {
DIR *dir;
struct dirent *ent;
int dirfd2 = ::dup(dirfd);
if( 0 > dirfd2 ) {
ERR_PRINT("Couldn't duplicate given dirfd %d for path '%s'", dirfd, path.c_str());
return false;
}
if( ( dir = ::fdopendir( dirfd2 ) ) != nullptr ) {
while ( ( ent = ::readdir( dir ) ) != NULL ) {
std::string fname( ent->d_name );
if( _dot != fname && _dotdot != fname ) { // avoid '.' and '..'
digest( dir_item( path, fname ) );
}
}
::closedir (dir);
return true;
} else {
return false;
}
}
#define TRAVERSEEVENT_ENUM(X,M) \
X(traverse_event,symlink,M) \
X(traverse_event,file,M) \
X(traverse_event,dir_entry,M) \
X(traverse_event,dir_exit,M) \
X(traverse_event,dir_symlink,M)
std::string jau::fs::to_string(const traverse_event mask) noexcept {
std::string out("[");
bool comma = false;
TRAVERSEEVENT_ENUM(APPEND_BITSTR,mask)
out.append("]");
return out;
}
#define TRAVERSEOPTIONS_ENUM(X,M) \
X(traverse_options,recursive,M) \
X(traverse_options,follow_symlinks,M) \
X(traverse_options,dir_entry,M) \
X(traverse_options,dir_exit,M)
std::string jau::fs::to_string(const traverse_options mask) noexcept {
std::string out("[");
bool comma = false;
TRAVERSEOPTIONS_ENUM(APPEND_BITSTR,mask)
out.append("]");
return out;
}
static bool _visit(const file_stats& item_stats, const traverse_options topts, const path_visitor& visitor, std::vector<int>& dirfds) noexcept {
if( item_stats.is_dir() ) {
if( item_stats.is_link() && !is_set(topts, traverse_options::follow_symlinks) ) {
return visitor( traverse_event::dir_symlink, item_stats );
}
if( !is_set(topts, traverse_options::recursive) ) {
return visitor( traverse_event::dir_non_recursive, item_stats );
}
if( dirfds.size() < 1 ) {
ERR_PRINT("dirfd stack error: count %zu] @ %s", dirfds.size(), item_stats.to_string().c_str());
return false;
}
const int parent_dirfd = dirfds.back();
const int this_dirfd = __posix_openat64(parent_dirfd, item_stats.item().basename().c_str(), _open_dir_flags);
if ( 0 > this_dirfd ) {
ERR_PRINT("entered path dir couldn't be opened, source %s", item_stats.to_string().c_str());
return false;
}
dirfds.push_back(this_dirfd);
if( is_set(topts, traverse_options::dir_entry) ) {
if( !visitor( traverse_event::dir_entry, item_stats ) ) {
return false;
}
}
std::vector<dir_item> content;
const consume_dir_item cs = jau::bindCaptureRefFunc<void, std::vector<dir_item>, const dir_item&>(&content,
( void(*)(std::vector<dir_item>*, const dir_item&) ) /* help template type deduction of function-ptr */
( [](std::vector<dir_item>* receiver, const dir_item& item) -> void { receiver->push_back( item ); } )
);
if( get_dir_content(this_dirfd, item_stats.path(), cs) && content.size() > 0 ) {
for (const dir_item& element : content) {
const file_stats element_stats( this_dirfd, element, true /* dirfd_is_item_dirname */ );
if( element_stats.is_dir() ) { // an OK dir
if( element_stats.is_link() && !is_set(topts, traverse_options::follow_symlinks) ) {
if( !visitor( traverse_event::dir_symlink, element_stats ) ) {
return false;
}
} else if( !_visit(element_stats, topts, visitor, dirfds) ) { // recursive
return false;
}
} else if( !visitor( ( element_stats.is_file() ? traverse_event::file : traverse_event::none ) |
( element_stats.is_link() ? traverse_event::symlink : traverse_event::none),
element_stats ) )
{
return false;
}
}
}
if( dirfds.size() < 2 ) {
ERR_PRINT("dirfd stack error: count %zu] @ %s", dirfds.size(), item_stats.to_string().c_str());
return false;
}
bool res = true;
if( is_set(topts, traverse_options::dir_exit) ) {
res = visitor( traverse_event::dir_exit, item_stats );
}
::close(this_dirfd);
dirfds.pop_back();
return res;
} // endif item_stats.is_dir()
else if( item_stats.is_file() || !item_stats.ok() ) { // file or error-alike
return visitor( ( item_stats.is_file() ? traverse_event::file : traverse_event::none ) |
( item_stats.is_link() ? traverse_event::symlink : traverse_event::none),
item_stats );
}
return true;
}
bool jau::fs::visit(const file_stats& item_stats, const traverse_options topts, const path_visitor& visitor, std::vector<int>* dirfds) noexcept {
const bool user_dirfds = nullptr != dirfds;
if( !user_dirfds ) {
dirfds = new std::vector<int>();
}
if( 0 != dirfds->size() ) {
ERR_PRINT("dirfd stack error: count %zu] @ %s", dirfds->size(), item_stats.to_string().c_str());
return false;
}
// initial parent directory dirfd of initial item_stats (a directory)
const int dirfd = __posix_openat64(AT_FDCWD, item_stats.item().dirname().c_str(), _open_dir_flags);
if ( 0 > dirfd ) {
ERR_PRINT("path dirname couldn't be opened, source %s", item_stats.to_string().c_str());
return false;
}
dirfds->push_back(dirfd);
bool res = _visit(item_stats, topts, visitor, *dirfds);
if( dirfds->size() != 1 && res ) {
ERR_PRINT("dirfd stack error: count %zu", dirfds->size());
res = false;
}
while( !dirfds->empty() ) {
::close(dirfds->back());
dirfds->pop_back();
}
if( !user_dirfds ) {
delete dirfds;
}
return res;
}
bool jau::fs::visit(const std::string& path, const traverse_options topts, const path_visitor& visitor, std::vector<int>* dirfds) noexcept {
return jau::fs::visit(file_stats(path), topts, visitor, dirfds);
}
bool jau::fs::remove(const std::string& path, const traverse_options topts) noexcept {
file_stats path_stats(path);
if( path_stats.is_file() ||
( path_stats.is_dir() && path_stats.is_link() && !is_set(topts, traverse_options::follow_symlinks) )
)
{
int res = ::unlink( path_stats.path().c_str() );
if( 0 != res ) {
ERR_PRINT("remove failed: %s, res %d", path_stats.to_string().c_str(), res);
return false;
}
return true;
}
if( path_stats.is_dir() && !is_set(topts, traverse_options::recursive) ) {
if( is_set(topts, traverse_options::verbose) ) {
jau::fprintf_td(stderr, "remove: Error: path is dir but !recursive, %s\n", path_stats.to_string().c_str());
}
return false;
}
if( path_stats.is_fd() ) {
ERR_PRINT("remove: failed: path is fd: %s", path_stats.to_string().c_str());
return false;
}
struct remove_context_t {
traverse_options topts;
std::vector<int> dirfds;
};
remove_context_t ctx = { topts | jau::fs::traverse_options::dir_exit, std::vector<int>() };
const path_visitor pv = jau::bindCaptureRefFunc<bool, remove_context_t, traverse_event, const file_stats&>(&ctx,
( bool(*)(remove_context_t*, traverse_event, const file_stats&) ) /* help template type deduction of function-ptr */
( [](remove_context_t* ctx_ptr, traverse_event tevt, const file_stats& element_stats) -> bool {
(void)tevt;
if( !element_stats.has_access() ) {
if( is_set(ctx_ptr->topts, traverse_options::verbose) ) {
jau::fprintf_td(stderr, "remove: Error: remove failed: no access, %s\n", element_stats.to_string().c_str());
}
return false;
}
const int dirfd = ctx_ptr->dirfds.back();
const std::string& basename_ = element_stats.item().basename();
if( is_set(tevt, traverse_event::dir_entry) ) {
// NOP
} else if( is_set(tevt, traverse_event::dir_exit) ) {
const int dirfd2 = *( ctx_ptr->dirfds.end() - 2 );
const int res = ::unlinkat( dirfd2, basename_.c_str(), AT_REMOVEDIR );
if( 0 != res ) {
ERR_PRINT("remove failed: %s, res %d", element_stats.to_string().c_str(), res);
return false;
}
if( is_set(ctx_ptr->topts, traverse_options::verbose) ) {
jau::fprintf_td(stderr, "remove: %s removed\n", element_stats.to_string().c_str());
}
} else if( is_set(tevt, traverse_event::file) || is_set(tevt, traverse_event::symlink) || is_set(tevt, traverse_event::dir_symlink) ) {
const int res = ::unlinkat( dirfd, basename_.c_str(), 0 );
if( 0 != res ) {
ERR_PRINT("remove failed: %s, res %d", element_stats.to_string().c_str(), res);
return false;
}
if( is_set(ctx_ptr->topts, traverse_options::verbose) ) {
jau::fprintf_td(stderr, "remove: %s removed\n", element_stats.to_string().c_str());
}
}
return true;
} ) );
return jau::fs::visit(path_stats, ctx.topts, pv, &ctx.dirfds);
}
bool jau::fs::compare(const std::string& source1, const std::string& source2, const bool verbose) noexcept {
const file_stats s1(source1);
const file_stats s2(source2);
return compare(s1, s2, verbose);
}
bool jau::fs::compare(const file_stats& source1, const file_stats& source2, const bool verbose) noexcept {
if( !source1.is_file() ) {
ERR_PRINT("source1_stats is not a file: %s", source1.to_string().c_str());
return false;
}
if( !source2.is_file() ) {
ERR_PRINT("source2_stats is not a file: %s", source2.to_string().c_str());
return false;
}
if( source1.size() != source2.size() ) {
if( verbose ) {
jau::fprintf_td(stderr, "compare: Source files size mismatch, %s != %s\n",
source1.to_string().c_str(), source2.to_string().c_str());
}
return false;
}
int src1=-1, src2=-1;
int src_flags = O_RDONLY|O_BINARY|O_NOCTTY;
uint64_t offset = 0;
bool res = false;
src1 = __posix_openat64(AT_FDCWD, source1.path().c_str(), src_flags);
if ( 0 > src1 ) {
ERR_PRINT("Failed to open source1 %s, errno %d, %s", source1.to_string().c_str());
goto errout;
}
src2 = __posix_openat64(AT_FDCWD, source2.path().c_str(), src_flags);
if ( 0 > src2 ) {
ERR_PRINT("Failed to open source2 %s, errno %d, %s", source2.to_string().c_str());
goto errout;
}
while ( offset < source1.size()) {
ssize_t rc1, rc2=0;
char buffer1[BUFSIZ];
char buffer2[BUFSIZ];
if( ( rc1 = ::read(src1, buffer1, sizeof(buffer1)) ) > 0 ) {
ssize_t bytes_to_write = rc1;
size_t buffer_offset = 0;
while( 0 < bytes_to_write ) { // src2-read required src1 size in chunks, allowing potential multiple read-ops to match src1 size
if( ( rc2 = ::read(src2, buffer2+buffer_offset, bytes_to_write) ) < 0 ) {
break;
}
buffer_offset += rc2;
bytes_to_write -= rc2;
offset += (uint64_t)rc2;
}
}
if ( 0 > rc1 || 0 > rc2 ) {
if ( 0 > rc1 ) {
ERR_PRINT("Failed to read source1 bytes @ %s / %s, %s",
jau::to_decstring(offset).c_str(), jau::to_decstring(source1.size()).c_str(),
source1.to_string().c_str());
} else if ( 0 > rc2 ) {
ERR_PRINT("Failed to read source2 bytes @ %s / %s, %s",
jau::to_decstring(offset).c_str(), jau::to_decstring(source2.size()).c_str(),
source2.to_string().c_str());
}
goto errout;
}
if( 0 != ::memcmp(buffer1, buffer2, rc1) ) {
if( verbose ) {
jau::fprintf_td(stderr, "compare: Difference within %s bytes @ %s / %s, %s != %s\n",
jau::to_decstring(rc1).c_str(), jau::to_decstring(offset-rc1).c_str(), jau::to_decstring(source1.size()).c_str(),
source1.to_string().c_str(), source2.to_string().c_str());
}
goto errout;
}
if ( 0 == rc1 ) {
break;
}
}
if( offset < source1.size() ) {
ERR_PRINT("Incomplete transfer %s / %s, %s != %s\n",
jau::to_decstring(offset).c_str(), jau::to_decstring(source1.size()).c_str(),
source1.to_string().c_str(), source2.to_string().c_str());
goto errout;
}
res = true;
errout:
if( 0 <= src1 ) {
::close(src1);
}
if( 0 <= src2 ) {
::close(src2);
}
return res;
}
#define COPYOPTIONS_BIT_ENUM(X,M) \
X(copy_options,recursive,M) \
X(copy_options,follow_symlinks,M) \
X(copy_options,into_existing_dir,M) \
X(copy_options,ignore_symlink_errors,M) \
X(copy_options,overwrite,M) \
X(copy_options,preserve_all,M) \
X(copy_options,sync,M)
std::string jau::fs::to_string(const copy_options mask) noexcept {
std::string out("[");
bool comma = false;
COPYOPTIONS_BIT_ENUM(APPEND_BITSTR,mask)
out.append("]");
return out;
}
struct copy_context_t {
copy_options copts;
int skip_dst_dir_mkdir;
std::vector<int> src_dirfds;
std::vector<int> dst_dirfds;
};
static bool copy_file(const int src_dirfd, const file_stats& src_stats,
const int dst_dirfd, const std::string& dst_basename, const copy_options copts) noexcept {
file_stats dst_stats(dst_dirfd, dst_basename);
// overwrite: remove pre-existing file, if copy_options::overwrite set
if( dst_stats.is_file() ) {
if( !is_set(copts, copy_options::overwrite) ) {
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Error: dest_path exists but copy_options::overwrite not set: source %s, dest '%s', copts %s\n",
src_stats.to_string().c_str(), dst_stats.to_string().c_str(), to_string( copts ).c_str());
}
return false;
}
const int res = ::unlinkat(dst_dirfd, dst_basename.c_str(), 0);
if( 0 != res ) {
ERR_PRINT("remove existing dest_path for symbolic-link failed: source %s, dest '%s'",
src_stats.to_string().c_str(), dst_stats.to_string().c_str());
return false;
}
}
// copy as symbolic link
if( src_stats.is_link() && !is_set(copts, copy_options::follow_symlinks) ) {
const std::shared_ptr<std::string> link_target_path = src_stats.link_target_path();
if( nullptr == link_target_path || 0 == link_target_path->size() ) {
ERR_PRINT("Symbolic link-path is empty %s", src_stats.to_string().c_str());
return false;
}
// symlink
const int res = ::symlinkat(link_target_path->c_str(), dst_dirfd, dst_basename.c_str());
if( 0 > res ) {
if( EPERM == errno && is_set(copts, copy_options::ignore_symlink_errors ) ) {
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Ignored: Failed to create symink %s -> %s, %s, errno %d, %s\n",
dst_basename.c_str(), link_target_path->c_str(), src_stats.to_string().c_str(), errno, ::strerror(errno));
}
return true;
}
ERR_PRINT("Creating symlink failed %s -> %s, %s", dst_basename.c_str(), link_target_path->c_str(), src_stats.to_string().c_str());
return false;
}
if( is_set(copts, copy_options::preserve_all) ) {
// preserve time
struct timespec ts2[2] = { src_stats.atime().to_timespec(), src_stats.mtime().to_timespec() };
if( 0 != ::utimensat(dst_dirfd, dst_basename.c_str(), ts2, AT_SYMLINK_NOFOLLOW) ) {
ERR_PRINT("Couldn't preserve time of symlink, source %s, dest '%s'", src_stats.to_string().c_str(), dst_basename.c_str());
return false;
}
// preserve ownership
const uid_t caller_uid = ::geteuid();
const ::uid_t source_uid = 0 == caller_uid ? src_stats.uid() : -1;
if( 0 != ::fchownat(dst_dirfd, dst_basename.c_str(), source_uid, src_stats.gid(), AT_SYMLINK_NOFOLLOW) ) {
if( errno != EPERM && errno != EINVAL ) {
ERR_PRINT("Couldn't preserve ownership of symlink, source %s, dest '%s'", src_stats.to_string().c_str(), dst_basename.c_str());
return false;
}
// OK to fail due to permissions
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Warn: Couldn't preserve ownership of symlink, source %s, dest '%s', errno %d (%s)\n",
src_stats.to_string().c_str(), dst_basename.c_str(), errno, ::strerror(errno));
}
}
}
return true;
}
// copy actual file bytes
const file_stats* target_stats = src_stats.final_target(); // follows symlinks up to definite item
const fmode_t dest_mode = target_stats->prot_mode();
const fmode_t omitted_permissions = dest_mode & ( fmode_t::rwx_grp | fmode_t::rwx_oth );
const uid_t caller_uid = ::geteuid();
int src=-1, dst=-1;
int src_flags = O_RDONLY|O_BINARY|O_NOCTTY;
uint64_t offset = 0;
bool res = false;
#if defined(__linux__)
if( caller_uid == target_stats->uid() ) {
src_flags |= O_NOATIME;
} // else we are not allowed to not use O_NOATIME
#endif /* defined(__linux__) */
src = __posix_openat64(src_dirfd, src_stats.item().basename().c_str(), src_flags);
if ( 0 > src ) {
if( src_stats.is_link() ) {
res = is_set(copts, copy_options::ignore_symlink_errors);
}
if( !res ) {
ERR_PRINT("Failed to open source %s", src_stats.to_string().c_str());
} else if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Ignored: Failed to open source %s, errno %d, %s\n", src_stats.to_string().c_str(), errno, ::strerror(errno));
}
goto errout;
}
dst = __posix_openat64 (dst_dirfd, dst_basename.c_str(), O_CREAT|O_WRONLY|O_BINARY|O_EXCL|O_NOCTTY, jau::fs::posix_protection_bits( dest_mode & ~omitted_permissions ) );
if ( 0 > dst ) {
ERR_PRINT("Failed to open target_path '%s'", dst_basename.c_str());
goto errout;
}
while ( offset < src_stats.size()) {
ssize_t rc1, rc2=0;
#ifdef _USE_SENDFILE_
off64_t offset_i = (off64_t)offset; // we drop 1 bit of value-range as off64_t is int64_t
const uint64_t count = std::max<uint64_t>(std::numeric_limits<ssize_t>::max(), src_stats.size() - offset);
if( ( rc1 = ::sendfile64(dst, src, &offset_i, (size_t)count) ) >= 0 ) {
offset = (uint64_t)offset_i;
}
#else /* _USE_SENDFILE_ */
char buffer[BUFSIZ];
if( ( rc1 = ::read(src, buffer, sizeof(buffer)) ) > 0 ) {
ssize_t bytes_to_write = rc1;
size_t buffer_offset = 0;
while( 0 < bytes_to_write ) { // write the read chunk, allowing potential multiple write-ops
if( ( rc2 = ::write(dst, buffer+buffer_offset, bytes_to_write) ) < 0 ) {
break;
}
buffer_offset += rc2;
bytes_to_write -= rc2;
offset += rc2;
}
}
#endif/* _USE_SENDFILE_ */
if ( 0 > rc1 || 0 > rc2 ) {
#ifdef _USE_SENDFILE_
ERR_PRINT("Failed to copy bytes @ %s / %s, %s -> '%s'",
jau::to_decstring(offset).c_str(), jau::to_decstring(src_stats.size()).c_str(),
src_stats.to_string().c_str(), dst_basename.c_str());
#else /* _USE_SENDFILE_ */
if ( 0 > rc1 ) {
ERR_PRINT("Failed to read bytes @ %s / %s, %s",
jau::to_decstring(offset).c_str(), jau::to_decstring(src_stats.size()).c_str(),
src_stats.to_string().c_str());
} else if ( 0 > rc2 ) {
ERR_PRINT("Failed to write bytes @ %s / %s, %s",
jau::to_decstring(offset).c_str(), jau::to_decstring(src_stats.size()).c_str(),
dst_basename.c_str());
}
#endif/* _USE_SENDFILE_ */
goto errout;
}
if ( 0 == rc1 ) {
break;
}
}
if( offset < src_stats.size() ) {
ERR_PRINT("Incomplete transfer %s / %s, %s -> '%s'",
jau::to_decstring(offset).c_str(), jau::to_decstring(src_stats.size()).c_str(),
src_stats.to_string().c_str(), dst_basename.c_str());
goto errout;
}
res = true;
if( omitted_permissions != fmode_t::none ) {
// restore omitted permissions
if( 0 != ::fchmod(dst, jau::fs::posix_protection_bits( dest_mode )) ) {
ERR_PRINT("Couldn't restore omitted permissions, source %s, dest '%s'",
src_stats.to_string().c_str(), dst_basename.c_str());
res = false;
}
}
if( is_set(copts, copy_options::preserve_all) ) {
// preserve time
struct timespec ts2[2] = { target_stats->atime().to_timespec(), target_stats->mtime().to_timespec() };
if( 0 != ::futimens(dst, ts2) ) {
ERR_PRINT("Couldn't preserve time of file, source %s, dest '%s'",
src_stats.to_string().c_str(), dst_basename.c_str());
res = false;
}
// preserve ownership
::uid_t source_uid = 0 == caller_uid ? target_stats->uid() : -1;
if( 0 != ::fchown(dst, source_uid, target_stats->gid()) ) {
if( errno != EPERM && errno != EINVAL ) {
ERR_PRINT("Couldn't preserve ownership of file, uid(caller %" PRIu32 ", chown %" PRIu32 "), source %s, dest '%s'",
caller_uid, source_uid, src_stats.to_string().c_str(), dst_basename.c_str());
res = false;
} else {
// OK to fail due to permissions
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Ignored: Preserve ownership of file failed, uid(caller %" PRIu32 ", chown %" PRIu32 "), source %s, dest '%s', errno %d (%s)\n",
caller_uid, source_uid, src_stats.to_string().c_str(), dst_stats.to_string().c_str(), errno, ::strerror(errno));
}
}
}
}
if( is_set(copts, copy_options::sync) ) {
if( 0 != ::fsync(dst) ) {
ERR_PRINT("Couldn't synchronize destination file, source %s, dest '%s'",
src_stats.to_string().c_str(), dst_basename.c_str());
res = false;
}
}
errout:
if( 0 <= src ) {
::close(src);
}
if( 0 <= dst ) {
::close(dst);
}
return res;
}
static bool copy_push_mkdir(const file_stats& dst_stats, copy_context_t& ctx) noexcept
{
// atomically, using unpredictable '.'+rand temp dir (if target dir non-existent)
// and drops read-permissions for user and all of group and others after fetching its dirfd.
bool new_dir = false;
std::string basename_;
const int dest_dirfd = ctx.dst_dirfds.back();
if( dst_stats.is_dir() ) {
if( is_set(ctx.copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: mkdir directory already exist: %s\n", dst_stats.to_string().c_str());
}
basename_ = dst_stats.item().basename();
} else if( !dst_stats.exists() ) {
new_dir = true;
constexpr const uint64_t val_min = 888;
constexpr const uint64_t val_max = 999999999999999; // 15 digits
uint64_t mkdir_cntr = 0;
std::mt19937_64 prng;
std::uniform_int_distribution<uint64_t> prng_dist(val_min, val_max);
bool mkdir_ok = false;
do {
++mkdir_cntr;
const uint64_t val = prng_dist(prng);
basename_ = "."+std::to_string(val);
if( 0 == ::mkdirat(dest_dirfd, basename_.c_str(), jau::fs::posix_protection_bits(fmode_t::rwx_usr)) ) {
mkdir_ok = true;
} else if (errno != EINTR && errno != EEXIST) {
ERR_PRINT("mkdir failed: %s, temp '%s'", dst_stats.to_string().c_str(), basename_.c_str());
return false;
} // else continue on EINTR or EEXIST
} while( !mkdir_ok && mkdir_cntr < val_max );
if( !mkdir_ok ) {
ERR_PRINT("mkdir failed: %s", dst_stats.to_string().c_str());
return false;
}
} else {
ERR_PRINT("mkdir failed: %s, exists but is no dir", dst_stats.to_string().c_str());
return false;
}
// open dirfd
const int new_dirfd = __posix_openat64(dest_dirfd, basename_.c_str(), _open_dir_flags);
if ( 0 > new_dirfd ) {
if( new_dir ) {
ERR_PRINT("Couldn't open new dir %s, temp '%s'", dst_stats.to_string().c_str(), basename_.c_str());
} else {
ERR_PRINT("Couldn't open new dir %s", dst_stats.to_string().c_str());
}
if( new_dir ) {
::unlinkat(dest_dirfd, basename_.c_str(), AT_REMOVEDIR);
}
return false;
}
// drop read permissions to render destination directory transaction safe until copy is done
if( 0 != ::fchmod(new_dirfd, jau::fs::posix_protection_bits(fmode_t::write_usr | fmode_t::exec_usr)) ) {
if( new_dir ) {
::unlinkat(dest_dirfd, basename_.c_str(), AT_REMOVEDIR);
ERR_PRINT("zero permissions on dest %s, temp '%s'", dst_stats.to_string().c_str(), basename_.c_str());
} else {
ERR_PRINT("zero permissions on dest %s", dst_stats.to_string().c_str());
}
::close(new_dirfd);
return false;
}
if( new_dir ) {
#if defined(__linux__)
const int rename_flags = 0; // Not supported on all fs: RENAME_NOREPLACE
const int rename_res = ::renameat2(dest_dirfd, basename_.c_str(), dest_dirfd, dst_stats.item().basename().c_str(), rename_flags);
#else /* defined(__linux__) */
const int rename_res = ::renameat(dest_dirfd, basename_.c_str(), dest_dirfd, dst_stats.item().basename().c_str());
#endif /* defined(__linux__) */
if( 0 != rename_res ) {
ERR_PRINT("rename temp to dest, temp '%s', dest %s", basename_.c_str(), dst_stats.to_string().c_str());
::unlinkat(dest_dirfd, basename_.c_str(), AT_REMOVEDIR);
::close(new_dirfd);
return false;
}
}
ctx.dst_dirfds.push_back(new_dirfd);
return true;
}
static bool copy_dir_preserve(const file_stats& src_stats, const int dst_dirfd, const std::string& dst_basename, const copy_options copts) noexcept {
const file_stats* target_stats = src_stats.is_link() ? src_stats.link_target().get() : &src_stats;
// restore permissions
const fmode_t dest_mode = target_stats->prot_mode();
if( 0 != ::fchmod(dst_dirfd, jau::fs::posix_protection_bits( dest_mode )) ) {
ERR_PRINT("restore permissions, source %s, dest '%s'", src_stats.to_string().c_str(), dst_basename.c_str());
return false;
}
if( is_set(copts, copy_options::preserve_all) ) {
// preserve time
struct timespec ts2[2] = { target_stats->atime().to_timespec(), target_stats->mtime().to_timespec() };
if( 0 != ::futimens(dst_dirfd, ts2) ) {
ERR_PRINT("preserve time of file failed, source %s, dest '%s'", src_stats.to_string().c_str(), dst_basename.c_str());
return false;
}
// preserve ownership
const uid_t caller_uid = ::geteuid();
const ::uid_t source_uid = 0 == caller_uid ? target_stats->uid() : -1;
if( 0 != ::fchown(dst_dirfd, source_uid, target_stats->gid()) ) {
if( errno != EPERM && errno != EINVAL ) {
ERR_PRINT("dir_preserve ownership of file failed, uid(caller %" PRIu32 ", chown %" PRIu32 "), source %s, dest '%s'",
caller_uid, source_uid, src_stats.to_string().c_str(), dst_basename.c_str());
return false;
}
// OK to fail due to permissions
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Ignored: dir_preserve ownership of file failed, uid(caller %" PRIu32 ", chown %" PRIu32 "), source %s, dest '%s', errno %d (%s)\n",
caller_uid, source_uid, src_stats.to_string().c_str(), dst_basename.c_str(), errno, ::strerror(errno));
}
}
}
if( is_set(copts, copy_options::sync) ) {
if( 0 != ::fsync(dst_dirfd) ) {
ERR_PRINT("Couldn't synchronize destination file '%s'", dst_basename.c_str());
return false;
}
}
return true;
}
bool jau::fs::copy(const std::string& source_path, const std::string& target_path, const copy_options copts) noexcept {
traverse_options topts = traverse_options::dir_entry | traverse_options::dir_exit;
if( is_set(copts, copy_options::recursive) ) {
topts |= traverse_options::recursive;
}
if( is_set(copts, copy_options::follow_symlinks) ) {
topts |= traverse_options::follow_symlinks;
}
if( is_set(copts, copy_options::verbose) ) {
topts |= traverse_options::verbose;
}
file_stats source_stats(source_path);
file_stats target_stats(target_path);
if( source_stats.is_file() ) {
//
// single file copy
//
if( target_stats.exists() ) {
if( target_stats.is_file() ) {
if( !is_set(copts, copy_options::overwrite)) {
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Error: source_path is file, target_path existing file w/o overwrite, source %s, target %s\n",
source_stats.to_string().c_str(), target_stats.to_string().c_str());
}
return false;
}
} // else file2file to directory
} // else file2file to explicit new file
const int src_dirfd = __posix_openat64(AT_FDCWD, source_stats.item().dirname().c_str(), _open_dir_flags);
if ( 0 > src_dirfd ) {
ERR_PRINT("source_path dir couldn't be opened, source %s", source_stats.to_string().c_str());
return false;
}
std::string dst_basename;
int dst_dirfd = -1;
if( target_stats.is_dir() ) {
// file2file to directory
dst_dirfd = __posix_openat64(AT_FDCWD, target_stats.path().c_str(), _open_dir_flags);
if ( 0 > dst_dirfd ) {
ERR_PRINT("target dir couldn't be opened, target %s", target_stats.to_string().c_str());
::close(src_dirfd);
return false;
}
dst_basename = source_stats.item().basename();
} else {
// file2file to file
file_stats target_parent_stats(target_stats.item().dirname());
if( !target_parent_stats.is_dir() ) {
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Error: target parent is not an existing directory, target %s, target_parent %s\n",
target_stats.to_string().c_str(), target_parent_stats.to_string().c_str());
}
::close(src_dirfd);
return false;
}
dst_dirfd = __posix_openat64(AT_FDCWD, target_parent_stats.path().c_str(), _open_dir_flags);
if ( 0 > dst_dirfd ) {
ERR_PRINT("target_parent dir couldn't be opened, target %s, target_parent %s",
target_stats.to_string().c_str(), target_parent_stats.to_string().c_str());
::close(src_dirfd);
return false;
}
dst_basename = target_stats.item().basename();
}
if( !copy_file(src_dirfd, source_stats, dst_dirfd, dst_basename, copts) ) {
return false;
}
::close(src_dirfd);
::close(dst_dirfd);
return true;
}
if( !source_stats.is_dir() ) {
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Error: source_path is neither file nor dir, source %s, target %s\n",
source_stats.to_string().c_str(), target_stats.to_string().c_str());
}
return false;
}
//
// directory copy
//
copy_context_t ctx { copts, 0, std::vector<int>(), std::vector<int>() };
if( !is_set(copts, copy_options::recursive) ) {
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Error: source_path is dir but !recursive, %s\n", source_stats.to_string().c_str());
}
return false;
}
if( target_stats.exists() && !target_stats.is_dir() ) {
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Error: source_path is dir but target_path exist and is no dir, source %s, target %s\n",
source_stats.to_string().c_str(), target_stats.to_string().c_str());
}
return false;
}
// src_dirfd of 'source_stats.item().dirname().c_str()' will be pushed by visit() itself
if( target_stats.is_dir() && !is_set(copts, copy_options::into_existing_dir) ) {
// Case: If dest_path exists as a directory, source_path dir will be copied below the dest_path directory
// _if_ copy_options::into_existing_dir is not set. Otherwise its content is copied into the existing dest_path.
const int dst_dirfd = __posix_openat64(AT_FDCWD, target_stats.path().c_str(), _open_dir_flags);
if ( 0 > dst_dirfd ) {
ERR_PRINT("target dir couldn't be opened, target %s", target_stats.to_string().c_str());
return false;
}
ctx.dst_dirfds.push_back(dst_dirfd);
} else {
// Case: If dest_path doesn't exist, source_path dir content is copied into the newly created dest_path.
// - OR - dest_path does exist and copy_options::into_existing_dir is set
file_stats target_parent_stats(target_stats.item().dirname());
if( !target_parent_stats.is_dir() ) {
if( is_set(copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Error: target parent is not an existing directory, target %s, target_parent %s\n",
target_stats.to_string().c_str(), target_parent_stats.to_string().c_str());
}
return false;
}
const int dst_parent_dirfd = __posix_openat64(AT_FDCWD, target_parent_stats.path().c_str(), _open_dir_flags);
if ( 0 > dst_parent_dirfd ) {
ERR_PRINT("target dirname couldn't be opened, target %s, target_parent %s",
target_stats.to_string().c_str(), target_parent_stats.to_string().c_str());
return false;
}
ctx.dst_dirfds.push_back(dst_parent_dirfd);
if( target_stats.is_dir() ) {
// Case: copy_options::into_existing_dir
const int dst_dirfd = __posix_openat64(AT_FDCWD, target_stats.path().c_str(), _open_dir_flags);
if ( 0 > dst_dirfd ) {
ERR_PRINT("target dir couldn't be opened, target %s", target_stats.to_string().c_str());
return false;
}
ctx.dst_dirfds.push_back(dst_dirfd);
} else {
if( !copy_push_mkdir(target_stats, ctx) ) {
return false;
}
}
ctx.skip_dst_dir_mkdir = 1;
}
const path_visitor pv = jau::bindCaptureRefFunc<bool, copy_context_t, traverse_event, const file_stats&>(&ctx,
( bool(*)(copy_context_t*, traverse_event, const file_stats&) ) /* help template type deduction of function-ptr */
( [](copy_context_t* ctx_ptr, traverse_event tevt, const file_stats& element_stats) -> bool {
if( !element_stats.has_access() ) {
if( is_set(ctx_ptr->copts, copy_options::verbose) ) {
jau::fprintf_td(stderr, "copy: Error: remove failed: no access, %s\n", element_stats.to_string().c_str());
}
return false;
}
if( ctx_ptr->dst_dirfds.size() < 1 ) {
ERR_PRINT("dirfd stack error: count[src %zu, dst %zu, dst_skip %d] @ %s",
ctx_ptr->src_dirfds.size(), ctx_ptr->dst_dirfds.size(), ctx_ptr->skip_dst_dir_mkdir, element_stats.to_string().c_str());
return false;
}
const int src_dirfd = ctx_ptr->src_dirfds.back();
const int dst_dirfd = ctx_ptr->dst_dirfds.back();
const std::string& basename_ = element_stats.item().basename();
if( is_set(tevt, traverse_event::dir_entry) ) {
if( 0 < ctx_ptr->skip_dst_dir_mkdir ) {
--ctx_ptr->skip_dst_dir_mkdir;
} else {
const file_stats target_stats_(dst_dirfd, basename_);
if( !copy_push_mkdir(target_stats_, *ctx_ptr) ) {
return false;
}
}
} else if( is_set(tevt, traverse_event::dir_exit) ) {
if( ctx_ptr->dst_dirfds.size() < 2 ) {
ERR_PRINT("dirfd stack error: count[src %zu, dst %zu] @ %s",
ctx_ptr->src_dirfds.size(), ctx_ptr->dst_dirfds.size(), element_stats.to_string().c_str());
return false;
}
if( !copy_dir_preserve( element_stats, dst_dirfd, basename_, ctx_ptr->copts ) ) {
return false;
}
::close(dst_dirfd);
ctx_ptr->dst_dirfds.pop_back();
} else if( is_set(tevt, traverse_event::file) || is_set(tevt, traverse_event::symlink) || is_set(tevt, traverse_event::dir_symlink) ) {
if( !copy_file(src_dirfd, element_stats, dst_dirfd, basename_, ctx_ptr->copts) ) {
return false;
}
}
return true;
} ) );
bool res = jau::fs::visit(source_stats, topts, pv, &ctx.src_dirfds);
while( !ctx.dst_dirfds.empty() ) {
::close(ctx.dst_dirfds.back());
ctx.dst_dirfds.pop_back();
}
return res;
}
bool jau::fs::rename(const std::string& oldpath, const std::string& newpath) noexcept {
file_stats oldpath_stats(oldpath);
file_stats newpath_stats(newpath);
if( !oldpath_stats.exists() ) {
ERR_PRINT("oldpath doesn't exist, oldpath %s, newpath %s\n",
oldpath_stats.to_string().c_str(), newpath_stats.to_string().c_str());
return false;
}
if( 0 != ::rename(oldpath_stats.path().c_str(), newpath_stats.path().c_str()) ) {
ERR_PRINT("raname failed, oldpath %s, newpath %s\n",
oldpath_stats.to_string().c_str(), newpath_stats.to_string().c_str());
return false;
}
return true;
}
void jau::fs::sync() noexcept {
::sync();
}
static bool set_effective_uid(::uid_t user_id) {
if( 0 != ::seteuid(user_id) ) {
ERR_PRINT("seteuid(%" PRIu32 ") failed", user_id);
return false;
}
return true;
}
jau::fs::mount_ctx jau::fs::mount_image(const std::string& image_path, const std::string& mount_point, const std::string& fs_type,
const unsigned long mountflags, const std::string fs_options)
{
file_stats image_stats(image_path);
if( !image_stats.is_file()) {
return mount_ctx();
}
file_stats target_stats(mount_point);
if( !target_stats.is_dir()) {
return mount_ctx();
}
int backingfile = __posix_openat64(AT_FDCWD, image_stats.path().c_str(), O_RDWR);
if( 0 > backingfile ) {
ERR_PRINT("Couldn't open image-file '%s': res %d", image_stats.to_string().c_str(), backingfile);
return mount_ctx();
}
#ifdef __linux__
const ::uid_t caller_uid = ::geteuid();
int loop_device_id = -1;
::pid_t pid = ::fork();
if( 0 == pid ) {
int loop_ctl_fd = -1, loop_device_fd = -1;
char loopname[4096];
int mount_res = -1;
void* fs_options_cstr = nullptr;
if( 0 != caller_uid ) {
if( !set_effective_uid(0) ) {
goto errout_child;
}
}
loop_ctl_fd = __posix_openat64(AT_FDCWD, "/dev/loop-control", O_RDWR);
if( 0 > loop_ctl_fd ) {
ERR_PRINT("Couldn't open loop-control: res %d", loop_ctl_fd);
goto errout_child;
}
loop_device_id = (int) ::ioctl(loop_ctl_fd, LOOP_CTL_GET_FREE);
if( 0 > loop_device_id ) {
ERR_PRINT("Couldn't get free loop-device: res %d", loop_device_id);
goto errout_child;
}
if( 254 < loop_device_id ) { // _exit() encoding
ERR_PRINT("loop-device %d out of valid range [0..254]", loop_device_id);
goto errout_child;
}
::close(loop_ctl_fd);
loop_ctl_fd = -1;
snprintf(loopname, sizeof(loopname), "/dev/loop%d", loop_device_id);
jau::INFO_PRINT("mount: Info: Using loop-device '%s'", loopname);
loop_device_fd = __posix_openat64(AT_FDCWD, loopname, O_RDWR);
if( 0 > loop_device_fd ) {
ERR_PRINT("Couldn't open loop-device '%s': res %d", loopname, loop_device_fd);
goto errout_child;
}
if( 0 > ::ioctl(loop_device_fd, LOOP_SET_FD, backingfile) ) {
ERR_PRINT("Couldn't attach image-file '%s' to loop-device '%s'", image_stats.to_string().c_str(), loopname);
goto errout_child;
}
if( fs_options.size() > 0 ) {
fs_options_cstr = (void*) fs_options.data();
}
mount_res = ::mount(loopname, target_stats.path().c_str(), fs_type.c_str(), mountflags, fs_options_cstr);
if( 0 != mount_res ) {
ERR_PRINT("source_path %s, target_path %s, fs_type %s, res %d", image_path.c_str(), mount_point.c_str(), fs_type.c_str(), mount_res);
::ioctl(loop_device_fd, LOOP_CLR_FD, 0);
goto errout_child;
}
::close(loop_device_fd);
loop_device_fd = -1;
::_exit(loop_device_id+1);
errout_child:
if( 0 <= loop_ctl_fd ) {
::close(loop_ctl_fd);
}
if( 0 <= loop_device_fd ) {
::close(loop_device_fd);
}
::_exit(0);
} else if( 0 < pid ) {
int pid_status = 0;
::pid_t child_pid = ::waitpid(pid, &pid_status, 0);
if( 0 > child_pid ) {
ERR_PRINT("wait(%d) failed: child_pid %d", pid, child_pid);
} else {
if( child_pid != pid ) {
WARN_PRINT("wait(%d) terminated child_pid %d", pid, child_pid);
}
if( !WIFEXITED(pid_status) ) {
WARN_PRINT("wait(%d) terminated abnormally child_pid %d, pid_status %d", pid, child_pid, pid_status);
goto errout;
}
loop_device_id = WEXITSTATUS(pid_status);
if( 0 >= loop_device_id ) {
goto errout;
}
--loop_device_id;
}
} else {
ERR_PRINT("Couldn't fork() process: res %d", pid);
goto errout;
}
if( 0 <= backingfile ) {
::close(backingfile);
backingfile = -1;
}
return mount_ctx(mount_point, loop_device_id);
errout:
#else
(void)fs_type;
(void)mountflags;
(void)fs_options;
#endif
if( 0 <= backingfile ) {
::close(backingfile);
}
return mount_ctx();
}
bool jau::fs::umount(const mount_ctx& context)
{
if( !context.mounted) {
return false;
}
file_stats target_stats(context.mount_point);
if( !target_stats.is_dir()) {
return false;
}
const ::uid_t caller_uid = ::geteuid();
::pid_t pid = ::fork();
if( 0 == pid ) {
if( 0 != caller_uid ) {
if( !set_effective_uid(0) ) {
::_exit(EXIT_FAILURE);
}
}
#if defined(__linux__)
const int umount_res = ::umount(target_stats.path().c_str());
#elif defined(__FreeBSD__)
const int umount_res = ::unmount(target_stats.path().c_str(), 0);
#else
#warning Add OS support
const int umount_res = -1;
#endif
if( 0 != umount_res ) {
ERR_PRINT("Couldn't umount '%s': res %d\n", target_stats.to_string().c_str(), umount_res);
}
if( 0 > context.loop_device_id ) {
// mounted w/o loop-device, done
::_exit(0 == umount_res ? EXIT_SUCCESS : EXIT_FAILURE);
}
#if defined(__linux__)
int loop_device_fd = -1;
char loopname[4096];
snprintf(loopname, sizeof(loopname), "/dev/loop%d", context.loop_device_id);
jau::INFO_PRINT("umount: Info: Using loop-device '%s'", loopname);
loop_device_fd = __posix_openat64(AT_FDCWD, loopname, O_RDWR);
if( 0 > loop_device_fd ) {
ERR_PRINT("Couldn't open loop-device '%s': res %d", loopname, loop_device_fd);
goto errout_child;
}
if( 0 > ::ioctl(loop_device_fd, LOOP_CLR_FD, 0) ) {
ERR_PRINT("Couldn't detach loop-device '%s'", loopname);
goto errout_child;
}
::close(loop_device_fd);
loop_device_fd = -1;
::_exit(0 == umount_res ? EXIT_SUCCESS : EXIT_FAILURE);
#endif
// No loop-device handling for OS
::_exit(EXIT_FAILURE);
#ifdef __linux__
errout_child:
if( 0 <= loop_device_fd ) {
::close(loop_device_fd);
}
::_exit(EXIT_FAILURE);
#endif
} else if( 0 < pid ) {
int pid_status = 0;
::pid_t child_pid = ::waitpid(pid, &pid_status, 0);
if( 0 > child_pid ) {
ERR_PRINT("wait(%d) failed: child_pid %d", pid, child_pid);
} else {
if( child_pid != pid ) {
WARN_PRINT("wait(%d) terminated child_pid %d", pid, child_pid);
}
if( WIFEXITED(pid_status) && EXIT_SUCCESS == WEXITSTATUS(pid_status) ) {
return true;
}
WARN_PRINT("wait(%d) terminated abnormally child_pid %d, pid_status %d", pid, child_pid, pid_status);
}
} else {
ERR_PRINT("Couldn't fork() process: res %d", pid);
}
return false;
}
|