summaryrefslogtreecommitdiff
path: root/util/nvmutil/lib/file.c
blob: 6546c2520819bdfadfb1b6103f43e9091d3e5f0a (plain)
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
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
/* SPDX-License-Identifier: MIT
 * Copyright (c) 2026 Leah Rowe <leah@libreboot.org>
 *
 * Pathless i/o, and some stuff you probably never saw.
 * Be nice to the demon.
 */

#if defined(__linux__) && !defined(_GNU_SOURCE)
/* for openat2 syscall on linux */
#define _GNU_SOURCE 1
#endif

#include <sys/types.h>
#include <sys/stat.h>

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/* for openat2: */
#ifdef __linux__
#include <linux/openat2.h>
#include <sys/syscall.h>
#endif

#include "../include/common.h"

/* check that a file changed
 */

int
same_file(int fd, struct stat *st_old,
    int check_size)
{
	struct stat st;
	int saved_errno = errno;

	/* TODO: null/-1 checks
	 *       like this can be
	 *       generalised
	 */
	if (st_old == NULL) {
		errno = EFAULT;
		goto err_same_file;
	}
	if (fd < 0) {
		errno = EBADF;
		goto err_same_file;
	}

	if (fstat(fd, &st) == -1)
		goto err_same_file;

	if (fd_verify_regular(fd, st_old, &st) < 0)
		goto err_same_file;

	if (check_size &&
	    st.st_size != st_old->st_size)
		goto err_same_file;

	errno = saved_errno;
	return 0;

err_same_file:

	if (errno == saved_errno)
		errno = ESTALE;

	return -1;
}

/* open() but with abort traps
 */
/* TODO: also support other things here than files.
	and then use, throughout the program.
	in particular, use of openat might help
	(split the path)
	(see: link attack mitigations throughout nvmutil)

	make it return, and handle the return value/errno

	(this could return e.g. EINTR)

  TODO: this function is not used by mkhtemp, nor will
       it probably be, it's currently used by nvmutil,
	for opening intel gbe nvm config files. i can
      probably remove it though and unify witth some
      of the verification code now used for mkhtemp

TODO: and don't abort. return -1. and handle in the caller.

minor obstacle: the mkhtemp code always requires absolute
paths, whereas the gbe editor takes relative paths.
 */
void
xopen(int *fd_ptr, const char *path, int flags, struct stat *st)
{
	if ((*fd_ptr = open(path, flags)) < 0)
		err(errno, "%s", path);

	if (fstat(*fd_ptr, st) < 0)
		err(errno, "%s: stat", path);

	if (!S_ISREG(st->st_mode))
		err(errno, "%s: not a regular file", path);

	if (lseek_on_eintr(*fd_ptr, 0, SEEK_CUR, 1, 1) == (off_t)-1)
		err(errno, "%s: file not seekable", path);
}

/* fsync() the directory of a file,
 * useful for atomic writes
 */

int
fsync_dir(const char *path)
{
	int saved_errno = errno;

	size_t pathlen = 0;
	size_t maxlen = 0;

	char *dirbuf = NULL;
	int dirfd = -1;

	char *slash = NULL;
	struct stat st = {0};

	int close_errno;

#if defined(PATH_LEN) && \
    (PATH_LEN) >= 256
	maxlen = PATH_LEN;
#else
	maxlen = 4096;
#endif

	if (path == NULL) {
		errno = EFAULT;
		goto err_fsync_dir;
	}

	if (slen(path, maxlen, &pathlen) < 0)
		goto err_fsync_dir;

	if (pathlen >= maxlen || pathlen < 0) {
		errno = EMSGSIZE;
		goto err_fsync_dir;
	}

	if (pathlen == 0)
	{
		errno = EINVAL;
		goto err_fsync_dir;
	}

	dirbuf = malloc(pathlen + 1);
	if (dirbuf == NULL) {

		errno = ENOMEM;
		goto err_fsync_dir;
	}

	memcpy(dirbuf, path, pathlen + 1);
	slash = strrchr(dirbuf, '/');

	if (slash != NULL) {
		*slash = '\0';
		if (*dirbuf == '\0') {
			dirbuf[0] = '/';
			dirbuf[1] = '\0';
		}
	} else {
		dirbuf[0] = '.';
		dirbuf[1] = '\0';
	}

	dirfd = fs_open(dirbuf,
	    O_RDONLY | O_CLOEXEC | O_NOCTTY
#ifdef O_DIRECTORY
	    | O_DIRECTORY
#endif
#ifdef O_NOFOLLOW
	    | O_NOFOLLOW
#endif
);
	if (dirfd < 0)
		goto err_fsync_dir;

	if (fstat(dirfd, &st) < 0)
		goto err_fsync_dir;

	if (!S_ISDIR(st.st_mode)) {

		errno = ENOTDIR;
		goto err_fsync_dir;
	}

	/* sync file on disk */
	if (fsync_on_eintr(dirfd) == -1)
		goto err_fsync_dir;

	if (close_on_eintr(dirfd) == -1) {

		dirfd = -1;
		goto err_fsync_dir;
	}

	if (dirbuf != NULL) {

		free(dirbuf);
		dirbuf = NULL;
	}

	dirbuf = NULL;

	errno = saved_errno;
	return 0;

err_fsync_dir:

	if (errno == saved_errno)
		errno = EIO;

	if (dirbuf != NULL) {

		free(dirbuf);
		dirbuf = NULL;
	}

	if (dirfd >= 0) {

		close_errno = errno;
		(void) close_on_eintr(dirfd);
		errno = close_errno;
		dirfd = -1;
	}

	return -1;
}

/* hardened tmpfile and tmpdir creation.
 * obsessively hardened, to the point that
 * you could even say it is unhinged.
 *
 * much stricter than mkstemp.
 *
 * userspace sandboxing. TOCTOU-aware,
 * much stricter than typical libc/mkstemp.
 * TODO: write docs! right now the documentation
 * is both tthe code and the specification.
 * this code will likely be hardened more, over
 * time, until a matured stable release can be
 * made. i intend for this to go in linux distros
 * and BSD source trees eventually, as a standalone
 * utility.
 *
 * NOTE TO LINUX DISTROS / BSDs: more testing
 * and auditing needed before putting this
 * in your project. this comment will be removed
 * after the code has matured for a while. this
 * is a rough implementation, already carefully
 * audited by one person: me
 *
 * expect bugs. one day, when this is ready,
 * i will make a lot more of the options configurable
 * at runtime, and add a special compatibility mode
 * so that it can also run like regular mktemp,
 * for compatibility; running mkhtemp with all the
 * hardening means you get very non-standard behaviour,
 * e.g. it's much stricter about ownership/permissions,
 * sticky bits, and regards as fault conditions, what
 * would be considered normal in mkstemp/mktemp.
 *
 * a full manual and specification will be written when
 * this code is fully matured, and then i will probably
 * start spamming your mailing lists myself ;)
 */

/* returns opened fd, sets fd and *path at pointers *fd and *path */
/* also sets external stat */

int
new_tmpfile(int *fd, char **path)
{
	return new_tmp_common(fd, path, MKHTEMP_FILE);
}

int
new_tmpdir(int *fd, char **path)
{
	return new_tmp_common(fd, path, MKHTEMP_DIR);
}

static int
new_tmp_common(int *fd, char **path, int type)
{
#if defined(PATH_LEN) && \
    (PATH_LEN) >= 256
	size_t maxlen = PATH_LEN;
#else
	size_t maxlen = 4096;
#endif
	struct stat st;

	char suffix[] =
	    "tmpXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
	char *tmpdir = NULL;

	int close_errno;
	size_t dirlen;
	size_t destlen;
	char *dest = NULL; /* final path (will be written into "path") */
	int saved_errno = errno;
	int dirfd = -1;
	const char *fname = NULL;

	struct stat st_dir_initial;

	if (path == NULL || fd == NULL) {
		errno = EFAULT;
		goto err;
	}

	/* don't mess with someone elses file */
	if (*fd >= 0) {
		errno = EEXIST;
		goto err;
	}

	/* regarding **path:
	* the pointer (to the pointer)
	* must nott be null, but we don't
	* care about the pointer it points
	* to. you should expect it to be
	* replaced upon successful return
	*
	* (on error, it will not be touched)
	*/


	*fd = -1;

#if defined(PERMIT_NON_STICKY_ALWAYS) && \
    ((PERMIT_NON_STICKY_ALWAYS) > 0)
	tmpdir = env_tmpdir(PERMIT_NON_STICKY_ALWAYS);
#else
	tmpdir = env_tmpdir(0);
#endif
	if (tmpdir == NULL)
		goto err;

	if (slen(tmpdir, maxlen, &dirlen) < 0)
		goto err;
	if (*tmpdir == '\0')
		goto err;
	if (*tmpdir != '/')
		goto err;

	/* sizeof adds an extra byte, useful
	 * because we also want '.' or '/'
	 */
	destlen = dirlen + sizeof(suffix);
	if (destlen > maxlen - 1) {
		errno = EOVERFLOW;
		goto err;
	}

	dest = malloc(destlen + 1);
	if (dest == NULL) {
		errno = ENOMEM;
		goto err;
	}

	memcpy(dest, tmpdir, dirlen);
	*(dest + dirlen) = '/';
	memcpy(dest + dirlen + 1, suffix, sizeof(suffix) - 1);
	*(dest + destlen) = '\0';

	fname = dest + dirlen + 1;

	dirfd = fs_open(tmpdir,
	    O_RDONLY | O_DIRECTORY);
	if (dirfd < 0)
		goto err;

	if (fstat(dirfd, &st_dir_initial) < 0)
		goto err;

	*fd = mkhtemp(fd, &st, dest, dirfd,
	    fname, &st_dir_initial, type);
	if (*fd < 0)
		goto err;

	if (dirfd >= 0) {
		close_errno = errno;
		(void) close_on_eintr(dirfd);
		errno = close_errno;
		dirfd = -1;
	}

	errno = saved_errno;
	*path = dest;

	return 0;

err:

	if (errno != saved_errno)
		saved_errno = errno;
	else
		saved_errno = errno = EIO;

	if (dest != NULL) {
		free(dest);
		dest = NULL;
	}

	if (dirfd >= 0) {
		close_errno = errno;
		(void) close_on_eintr(dirfd);
		errno = close_errno;
		dirfd = -1;
	}

	if (*fd >= 0) {
		close_errno = errno;
		(void) close_on_eintr(*fd);
		errno = close_errno;
		*fd = -1;
	}

	errno = saved_errno;
	return -1;
}


/* hardened TMPDIR parsing
 */

char *
env_tmpdir(int bypass_all_sticky_checks)
{
	char *t;
	int allow_noworld_unsticky;
	int saved_errno = errno;

	t = getenv("TMPDIR");

	if (t != NULL && *t != '\0') {

		if (tmpdir_policy(t,
		    &allow_noworld_unsticky) < 0) {
			errno = EPERM;
			return NULL; /* errno already set */
		}

		if (!world_writeable_and_sticky(t,
		    allow_noworld_unsticky,
		    bypass_all_sticky_checks)) {
			errno = EPERM;
			return NULL;
		}

		errno = saved_errno;
		return t;
	}

	allow_noworld_unsticky = 0;

	if (world_writeable_and_sticky("/tmp",
	    allow_noworld_unsticky,
	    bypass_all_sticky_checks)) {

		errno = saved_errno;
		return "/tmp";
	}

	if (world_writeable_and_sticky("/var/tmp",
	    allow_noworld_unsticky,
	    bypass_all_sticky_checks)) {

		errno = saved_errno;
		return "/var/tmp";
	}

	if (errno == saved_errno)
		errno = EPERM;

	return NULL;
}

int
tmpdir_policy(const char *path,
    int *allow_noworld_unsticky)
{
	int saved_errno = errno;
	int r;

	if (path == NULL ||
	    allow_noworld_unsticky == NULL) {

		errno = EFAULT;
		return -1;
	}

	*allow_noworld_unsticky = 1;

	r = same_dir(path, "/tmp");
	if (r < 0)
		goto err_tmpdir_policy;
	if (r > 0)
		*allow_noworld_unsticky = 0;

	r = same_dir(path, "/var/tmp");
	if (r < 0)
		goto err_tmpdir_policy;
	if (r > 0)
		*allow_noworld_unsticky = 0;

	errno = saved_errno;
	return 0;

err_tmpdir_policy:

	if (errno == saved_errno)
		errno = EIO;

	return -1;
}

int
same_dir(const char *a, const char *b)
{
	int fd_a = -1;
	int fd_b = -1;

	struct stat st_a;
	struct stat st_b;

	int saved_errno = errno;
	int rval_scmp;

#if defined(PATH_LEN) && \
    (PATH_LEN) >= 256
	size_t maxlen = (PATH_LEN);
#else
	size_t maxlen = 4096;
#endif

	/* optimisation: if both dirs
	   are the same, we don't need
	   to check anything. sehr schnell:
	 */
	if (scmp(a, b, maxlen, &rval_scmp) < 0)
		goto err_same_dir;
	/* bonus: scmp checks null for us */
	if (rval_scmp == 0)
		goto success_same_dir;

	fd_a = fs_open(a, O_RDONLY | O_DIRECTORY);
	if (fd_a < 0)
		goto err_same_dir;

	fd_b = fs_open(b, O_RDONLY | O_DIRECTORY);
	if (fd_b < 0)
		goto err_same_dir;

	if (fstat(fd_a, &st_a) < 0)
		goto err_same_dir;

	if (fstat(fd_b, &st_b) < 0)
		goto err_same_dir;

	if (st_a.st_dev == st_b.st_dev &&
	    st_a.st_ino == st_b.st_ino) {

		(void) close_on_eintr(fd_a);
		(void) close_on_eintr(fd_b);

success_same_dir:

		/* SUCCESS
		 */

		errno = saved_errno;
		return 1;
	}

	(void) close_on_eintr(fd_a);
	(void) close_on_eintr(fd_b);

	/* FAILURE (logical)
	 */

	errno = saved_errno;
	return 0;

err_same_dir:

	/* FAILURE (probably syscall)
	 */

	if (fd_a >= 0)
		(void) close_on_eintr(fd_a);
	if (fd_b >= 0)
		(void) close_on_eintr(fd_b);

	if (errno == saved_errno)
		errno = EIO;

	return -1;
}

/* bypass_all_sticky_checks: if set,
       disable stickiness checks (libc behaviour)
       (if not set: leah behaviour)

   allow_noworld_unsticky:
       allow non-sticky files if not world-writeable
       (still block non-sticky in standard TMPDIR)
*/
int
world_writeable_and_sticky(
    const char *s,
    int allow_noworld_unsticky,
    int bypass_all_sticky_checks)
{
	struct stat st;
	int dirfd = -1;

	int saved_errno = errno;

	if (s == NULL || *s == '\0') {
		errno = EINVAL;
		goto sticky_hell;
	}

	/* mitigate symlink attacks*
	 */
	dirfd = fs_open(s, O_RDONLY | O_DIRECTORY);
	if (dirfd < 0)
		goto sticky_hell;

	if (fstat(dirfd, &st) < 0)
		goto sticky_hell;

	if (!S_ISDIR(st.st_mode)) {
		errno = ENOTDIR;
		goto sticky_hell;
	}

	/* must be fully executable
	 * by everyone, or openat2
	 * becomes unreliable**
	 */
	if (!(st.st_mode & S_IXUSR) ||
	    !(st.st_mode & S_IXGRP) ||
	    !(st.st_mode & S_IXOTH)) {

		errno = EACCES;
		goto sticky_hell;
	}

	/* *normal-**ish mode (libc):
	 */

	if (bypass_all_sticky_checks)
		goto sticky_heaven; /* normal == no security */

	/* unhinged leah mode:
	 */

	if (st.st_mode & S_IWOTH) { /* world writeable */

		/* if world-writeable, only
		 * allow sticky files
		 */
		if (st.st_mode & S_ISVTX)
			goto sticky_heaven; /* sticky */

		errno = EPERM;
		goto sticky_hell; /* not sticky */
	}

	/* non-world-writeable, so
	 * stickiness is do-not-care
	 */
	if (allow_noworld_unsticky)
		goto sticky_heaven; /* sticky! */

	goto sticky_hell; /* heaven visa denied */

sticky_heaven:
/* i like the one in hamburg better */

	if (dirfd >= 0)
		(void) close_on_eintr(dirfd);

	errno = saved_errno;

	return 1;

sticky_hell:

	if (errno == saved_errno)
		errno = EPERM;

	saved_errno = errno;

	if (dirfd >= 0)
		(void) close_on_eintr(dirfd);

	errno = saved_errno;

	return 0;
}

/* mk(h)temp - hardened mktemp.
 * like mkstemp, but (MUCH) harder.
 *
 * designed to resist TOCTOU attacsk
 * e.g. directory race / symlink attack
 * 
 * extremely strict and even implements
 * some limited userspace-level sandboxing,
 * similar to openbsd unveil (which you
 * can also use with this in your program)
 *
 * supports both files and directories.
 * file: type = MKHTEMP_FILE (0)
 * dir: type = MKHTEMP_DIR (1)
 *
 * DESIGN NOTES:
 *
 * caller is expected to handle
 * cleanup e.g. free(), on *st,
 * *template, *fname (all of the
 * pointers). ditto fd cleanup.
 *
 * some limited cleanup is
 * performed here, e.g. directory/file
 * cleanup on error in mkhtemp_try_create
 *
 * we only check if these are not NULL,
 * and the caller is expected to take
 * care; without too many conditions,
 * these functions are more flexible,
 * but some precauttions are taken:
 *
 * when used via the function new_tmpfile
 * or new_tmpdir, thtis is extremely strict,
 * much stricter than previous mktemp
 * variants. for example, it is much
 * stricter about stickiness on world
 * writeable directories, and it enforces
 * file ownership under hardened mode
 * (only lets you touch your own files/dirs)
 */
int
mkhtemp(int *fd,
    struct stat *st,
    char *template,
    int dirfd,
    const char *fname,
    struct stat *st_dir_initial,
    int type)
{
	size_t len = 0;
	size_t xc = 0;
	size_t fname_len = 0;

	char *fname_copy = NULL;
	char *p;

	size_t retries;

	int close_errno;
	int saved_errno = errno;

#if defined(PATH_LEN) && \
    (PATH_LEN) >= 256
	size_t max_len = PATH_LEN;
#else
	size_t max_len = 4096;
#endif
	int r;
	char *end;

	if (fd == NULL ||
	    template == NULL ||
	    fname == NULL ||
	    st_dir_initial == NULL) {

		errno = EFAULT;
		return -1;
	}

	/* we do not mess with an
	   open descriptor.
	 */
	if (*fd >= 0) {
		errno = EEXIST; /* leave their file alone */
		return -1;
	}

	if (dirfd < 0) {
		errno = EBADF;
		return -1;
	}

	if (slen(template, max_len, &len) < 0)
		return -1;

	if (len >= max_len) {
		errno = EMSGSIZE;
		return -1;
	}

	if (slen(fname, max_len, &fname_len) < 0)
		return -1;

	if (fname_len == 0) {
		errno = EINVAL;
		return -1;
	}

	if (strrchr(fname, '/') != NULL) {
		errno = EINVAL;
		return -1;
	}

	/* count trailing X */
	end = template + len;
	while (end > template && *--end == 'X')
		xc++;

	if (xc < 12 || xc > len) {
		errno = EINVAL;
		return -1;
	}

	if (fname_len > len) {
		errno = EOVERFLOW;
		return -1;
	}

	if (memcmp(fname,
	    template + len - fname_len,
	    fname_len) != 0) {
		errno = EINVAL;
		return -1;
	}

	fname_copy = malloc(fname_len + 1);
	if (fname_copy == NULL) {
		errno = ENOMEM;
		goto err;
	}

	/* fname_copy = suffix region only; p points to trailing XXXXXX */
	memcpy(fname_copy,
	    template + len - fname_len,
	    fname_len + 1);
	p = fname_copy + fname_len - xc;

	for (retries = 0; retries < MKHTEMP_RETRY_MAX; retries++) {

		r = mkhtemp_try_create(
		    dirfd,
		    st_dir_initial,
		    fname_copy,
		    p,
		    xc,
		    fd,
		    st,
		    type);

		if (r == 0) {
			if (retries >= MKHTEMP_SPIN_THRESHOLD) {
				/* usleep can return EINTR */
				close_errno = errno;
				usleep((useconds_t)rlong() & 0x3FF);
				errno = close_errno;
			}
			continue;
		}
		if (r < 0)
			goto err;

		/* success: copy final name back */
		memcpy(template + len - fname_len,
		    fname_copy, fname_len);

		errno = saved_errno;
		goto success;
	}

	errno = EEXIST;

err:
	if (*fd >= 0) {
		close_errno = errno;
		(void)close_on_eintr(*fd);
		errno = close_errno;
		*fd = -1;
	}

success:

	if (fname_copy != NULL)
		free(fname_copy);

	return (*fd >= 0) ? *fd : -1;
}

static int
mkhtemp_try_create(int dirfd,
    struct stat *st_dir_initial,
    char *fname_copy,
    char *p,
    size_t xc,
    int *fd,
    struct stat *st,
    int type)
{
	struct stat st_open;
	int saved_errno = errno;
	int close_errno;
	int rval = -1;

	int file_created = 0;
	int dir_created = 0;

	if (fd == NULL || st == NULL || p == NULL || fname_copy == NULL ||
	    st_dir_initial == NULL) {
		errno = EFAULT;
		goto err;
	} else if (*fd >= 0) { /* do not mess with someone else's file */
		errno = EEXIST;
		goto err;
	}

	if (mkhtemp_fill_random(p, xc) < 0)
		goto err;

	if (fd_verify_dir_identity(dirfd, st_dir_initial) < 0)
		goto err;

	if (type == MKHTEMP_FILE) {
		*fd = openat2p(dirfd, fname_copy,
		    O_RDWR | O_CREAT | O_EXCL |
		    O_NOFOLLOW | O_CLOEXEC | O_NOCTTY,
		    0600);

		/* O_CREAT and O_EXCL guarantees
		 * creation upon success
		 */
		if (*fd >= 0)
			file_created = 1;

	} else { /* dir: MKHTEMP_DIR */

		if (mkdirat_on_eintr(dirfd, fname_copy, 0700) < 0)
			goto err;

		/* ^ NOTE: opening the directory here
			will never set errno=EEXIST,
			since we're not creating it */

		dir_created = 1;

		/* do it again (mitigate directory race) */
		if (fd_verify_dir_identity(dirfd, st_dir_initial) < 0)
			goto err;

		*fd = openat2p(dirfd, fname_copy,
		    O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0);
		if (*fd < 0)
			goto err;

		if (fstat(*fd, &st_open) < 0)
			goto err;

		if (!S_ISDIR(st_open.st_mode)) {
			errno = ENOTDIR;
			goto err;
		}

		/* NOTE: could check nlink count here,
		 *       but it's not very reliable here. skipped.
		 */

		if (fd_verify_dir_identity(dirfd, st_dir_initial) < 0)
			goto err;

	}

	/* NOTE: openat2p and mkdirat_on_eintr
	 * already handled EINTR/EAGAIN looping
	 */

	if (*fd < 0) {
		if (errno == EEXIST) {

			rval = 0;
			goto out;
		}
		goto err;
	}

	if (fstat(*fd, &st_open) < 0)
		goto err;

	if (type == MKHTEMP_FILE) {

		if (fd_verify_dir_identity(dirfd, st_dir_initial) < 0)
			goto err;

		if (secure_file(fd, st, &st_open,
		    O_APPEND, 1, 1, 0600) < 0) /* WARNING: only once */
			goto err;

	} else { /* dir: MKHTEMP_DIR */

		if (fd_verify_identity(*fd, &st_open, st_dir_initial) < 0)
			goto err;

		if (!S_ISDIR(st_open.st_mode)) {
			errno = ENOTDIR;
			goto err;
		}

		if (is_owner(&st_open) < 0)
			goto err;

		/* group/world writeable */
		if (st_open.st_mode & (S_IWGRP | S_IWOTH)) {
			errno = EPERM;
			goto err;
		}
	}

	errno = saved_errno;
	rval = 1;
	goto out;

err:
	close_errno = errno;

	if (fd != NULL && *fd >= 0) {
		(void) close_on_eintr(*fd);
		*fd = -1;
	}

	if (file_created)
		(void) unlinkat(dirfd, fname_copy, 0);

	if (dir_created)
		(void) unlinkat(dirfd, fname_copy, AT_REMOVEDIR);

	errno = close_errno;
	rval = -1;
out:
	return rval;
}

int
mkhtemp_fill_random(char *p, size_t xc)
{
	size_t chx = 0;
	int rand_failures = 0;

	size_t r;

	int saved_rand_error = 0;
	static char ch[] =
	    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

	/* clamp rand to prevent modulo bias
	 * (reduced risk of entropy leak)
	 */
	size_t limit = ((size_t)-1) - (((size_t)-1) % (sizeof(ch) - 1));

	int saved_errno = errno;

	if (p == NULL) {
		errno = EFAULT;
		goto err_mkhtemp_fill_random;
	}

	for (chx = 0; chx < xc; chx++) {

		do {
			saved_rand_error = errno;
			rand_failures = 0;
retry_rand:
			errno = 0;

			/* on bsd: uses arc4random
			   on linux: uses getrandom
			   on OLD linux: /dev/urandom
			   on old/other unix: /dev/urandom
			 */
			r = rlong();

			if (errno > 0) {
				if (++rand_failures <= 8)
					goto retry_rand;

				goto err_mkhtemp_fill_random;
			}

			rand_failures = 0;
			errno = saved_rand_error;

		} while (r >= limit);

		p[chx] = ch[r % (sizeof(ch) - 1)];
	}

	errno = saved_errno;
	return 0;

err_mkhtemp_fill_random:

	if (errno == saved_errno)
		errno = ECANCELED;

	return -1;
}

/* WARNING: **ONCE** per file.
 *
 *	!!! DO NOT RUN TWICE PER FILE. BEWARE OF THE DEMON !!!
 *	               watch out for spikes!
 */
int secure_file(int *fd,
    struct stat *st,
    struct stat *expected,
    int bad_flags,
    int check_seek,
    int do_lock,
    mode_t mode)
{
	int flags;
	struct stat st_now;
	int saved_errno = errno;
	/* you have been warned */
	if (fd == NULL) {
		errno = EFAULT;
		goto err_demons;
	}
	if (*fd < 0) {
		errno = EBADF;
		goto err_demons;
	}

	if (st == NULL) {
		errno = EFAULT;
		goto err_demons;
	}

	flags = fcntl(*fd, F_GETFL);

	if (flags == -1)
		goto err_demons;

	if (bad_flags > 0) {

		/* e.g. O_APPEND breaks pwrite/pread
		 * by allowing offsets to be ignored */
		if (flags & bad_flags) {
			errno = EPERM;
			goto err_demons;
		}
	}

	if (expected != NULL) {
		if (fd_verify_regular(*fd, expected, st) < 0)
			goto err_demons;
	} else {
		if (fstat(*fd, &st_now) == -1)
			goto err_demons;

		if (!S_ISREG(st_now.st_mode)) {
			errno = EBADF;
			goto err_demons;
		}

		*st = st_now;
	}

	if (check_seek) {

		/* check if it's seekable */
		if (lseek(*fd, 0, SEEK_CUR) == (off_t)-1)
			goto err_demons;
	}

	/* don't release the demon
	 */
	if (st->st_nlink != 1) { /***********/
		                 /* ( >:3 ) */
		errno = ELOOP;   /*  /| |\  */  /* don't let him out */
		goto err_demons; /*   / \   */
	                         /***********/
	}

	if (st->st_uid != geteuid() && /* someone else's file */
	    geteuid() != 0) { /* override for root */

		errno = EPERM;
		goto err_demons;
	}
	if (is_owner(st) < 0)
		goto err_demons;

	/* world-writeable or group-ownership.
	 * if these are set, then others could
	 * modify the file (not secure)
	 */
	if (st->st_mode & (S_IWGRP | S_IWOTH)) {
		errno = EPERM;
		goto err_demons;
	}

	if (do_lock) {
		if (lock_file(*fd, flags) == -1)
			goto err_demons;

		if (expected != NULL) {
			if (fd_verify_identity(*fd, expected, &st_now) < 0)
				goto err_demons;
		}
	}

	if (fchmod(*fd, mode) == -1)
		goto err_demons;

	errno = saved_errno;
	return 0;

err_demons:

	if (errno == saved_errno)
		errno = EIO;

	return -1;
}

int
fd_verify_regular(int fd,
    const struct stat *expected,
    struct stat *out)
{
	if (fd_verify_identity(fd, expected, out) < 0)
		return -1;

	if (!S_ISREG(out->st_mode)) {
		errno = EBADF;
		return -1;
	}

	return 0; /* regular file */
}

int
fd_verify_identity(int fd,
    const struct stat *expected,
    struct stat *out)
{
	struct stat st_now;
	int saved_errno = errno;

	if (fd < 0 || expected == NULL) {
		errno = EFAULT;
		return -1;
	}

	if (fstat(fd, &st_now) < 0)
		return -1;

	if (st_now.st_dev != expected->st_dev ||
	    st_now.st_ino != expected->st_ino) {
		errno = ESTALE;
		return -1;
	}

	if (out != NULL)
		*out = st_now;

	errno = saved_errno;
	return 0;
}

int
fd_verify_dir_identity(int fd,
    const struct stat *expected)
{
	struct stat st_now;
	int saved_errno = errno;

	if (fd < 0 || expected == NULL) {
		errno = EFAULT;
		return -1;
	}

	if (fstat(fd, &st_now) < 0)
		return -1;

	if (st_now.st_dev != expected->st_dev ||
	    st_now.st_ino != expected->st_ino) {
		errno = ESTALE;
		return -1;
	}

	if (!S_ISDIR(st_now.st_mode)) {
		errno = ENOTDIR;
		return -1;
	}

	errno = saved_errno;
	return 0;
}

int
is_owner(struct stat *st)
{
	if (st == NULL) {

		errno = EFAULT;
		return -1;
	}

#if ALLOW_ROOT_OVERRIDE
	if (st->st_uid != geteuid() && /* someone else's file */
	    geteuid() != 0) { /* override for root */
#else
	if (st->st_uid != geteuid()) { /* someone else's file */
#endif				       /* and no root override */
		errno = EPERM;
		return -1;
	}

	return 0;
}

int
lock_file(int fd, int flags)
{
	struct flock fl;
	int saved_errno = errno;

	if (fd < 0) {
		errno = EBADF;
		goto err_lock_file;
	}

	if (flags < 0) {
		errno = EINVAL;
		goto err_lock_file;
	}

	memset(&fl, 0, sizeof(fl));

	if ((flags & O_ACCMODE) == O_RDONLY)
		fl.l_type = F_RDLCK;
	else
		fl.l_type = F_WRLCK;

	fl.l_whence = SEEK_SET;

	if (fcntl(fd, F_SETLK, &fl) == -1)
		goto err_lock_file;

	saved_errno = errno;
	return 0;

err_lock_file:

	if (errno == saved_errno)
		errno = EIO;

	return -1;
}

/*
 * Safe I/O functions wrapping around
 * read(), write() and providing a portable
 * analog of both pread() and pwrite().
 * These functions are designed for maximum
 * robustness, checking NULL inputs, overflowed
 * outputs, and all kinds of errors that the
 * standard libc functions don't.
 *
 * Looping on EINTR and EAGAIN is supported.
 * EINTR/EAGAIN looping is done indefinitely.
 */

/* rw_file_exact() - Read perfectly or die
 *
 * Read/write, and absolutely insist on an
 * absolute read; e.g. if 100 bytes are
 * requested, this MUST return 100.
 *
 * This function will never return zero.
 * It will only return below (error),
 * or above (success). On error, -1 is
 * returned and errno is set accordingly.
 *
 * Zero-byte returns are not allowed.
 * It will re-spin a finite number of
 * times upon zero-return, to recover,
 * otherwise it will return an error.
 */

ssize_t
rw_file_exact(int fd, unsigned char *mem, size_t nrw,
    off_t off, int rw_type, int loop_eagain,
    int loop_eintr, size_t max_retries,
    int off_reset)
{
	ssize_t rval;
	ssize_t rc;

	size_t nrw_cur;

	off_t off_cur;
	void *mem_cur;

	size_t retries_on_zero;

	int saved_errno = errno;

	rval = 0;

	rc = 0;
	retries_on_zero = 0;

	if (io_args(fd, mem, nrw, off, rw_type) == -1)
		goto err_rw_file_exact;

	while (1) {
	
		/* Prevent theoretical overflow */
		if (rval >= 0 && (size_t)rval > (nrw - rc)) {
			errno = EOVERFLOW;
			goto err_rw_file_exact;
		}

		rc += rval;
		if ((size_t)rc >= nrw)
			break;

		mem_cur = (void *)(mem + (size_t)rc);
		nrw_cur = (size_t)(nrw - (size_t)rc);

		if (off < 0) {
			errno = EOVERFLOW;
			goto err_rw_file_exact;
		}

		off_cur = off + (off_t)rc;

		rval = prw(fd, mem_cur, nrw_cur, off_cur,
		    rw_type, loop_eagain, loop_eintr,
		    off_reset);

		if (rval < 0)
			goto err_rw_file_exact;

		if (rval == 0) {
			if (retries_on_zero++ < max_retries)
				continue;

			errno = EIO;
			goto err_rw_file_exact;
		}

		retries_on_zero = 0;
	}

	if ((size_t)rc != nrw) {

		errno = EIO;
		goto err_rw_file_exact;
	}

	rval = rw_over_nrw(rc, nrw);
	if (rval < 0)
		goto err_rw_file_exact;

	errno = saved_errno;

	return rval;

err_rw_file_exact:

	if (errno == saved_errno)
		errno = EIO;

	return -1;
}

/* prw() - portable read-write with more
 * safety checks than barebones libc
 *
 * portable pwrite/pread on request, or real
 * pwrite/pread libc functions can be used.
 * the portable (non-libc) pread/pwrite is not
 * thread-safe, because it does not prevent or
 * mitigate race conditions on file descriptors
 *
 * If you need real pwrite/pread, just compile
 * with flag: REAL_POS_IO=1
 *
 * A fallback is provided for regular read/write.
 * rw_type can be IO_READ (read), IO_WRITE (write),
 * IO_PREAD (pread) or IO_PWRITE
 *
 * loop_eagain does a retry loop on EAGAIN if set
 * loop_eintr does a retry loop on EINTR if set
 *
 * race conditions on non-libc pread/pwrite:
 * if a file offset changes, abort, to mitage.
 *
 * off_reset 1: reset the file offset *once* if
 *              a change was detected, assuming
 *              nothing else is touching it now
 * off_reset 0: never reset if changed
 */

ssize_t
prw(int fd, void *mem, size_t nrw,
    off_t off, int rw_type,
    int loop_eagain, int loop_eintr,
    int off_reset)
{
	ssize_t rval;
	ssize_t r;
	int positional_rw;
	struct stat st;
#if !defined(REAL_POS_IO) || \
    REAL_POS_IO < 1
	off_t verified;
	off_t off_orig;
	off_t off_last;
#endif
	int saved_errno = errno;

	if (io_args(fd, mem, nrw, off, rw_type)
	    == -1)
		goto err_prw;

	r = -1;

	/* do not use loop_eagain on
	 * normal files
	 */

	if (!loop_eagain) {
		/* check whether the file
		 * changed
		 */

		if (check_file(fd, &st) == -1)
			goto err_prw;
	}

	if (rw_type >= IO_PREAD)
		positional_rw = 1; /* pread/pwrite */
	else
		positional_rw = 0; /* read/write */

try_rw_again:

	if (!positional_rw) {
#if defined(REAL_POS_IO) && \
    REAL_POS_IO > 0
real_pread_pwrite:
#endif
		if (rw_type == IO_WRITE)
			r = write(fd, mem, nrw);
		else if (rw_type == IO_READ)
			r = read(fd, mem, nrw);
#if defined(REAL_POS_IO) && \
    REAL_POS_IO > 0
		else if (rw_type == IO_PWRITE)
			r = pwrite(fd, mem, nrw, off);
		else if (rw_type == IO_PREAD)
			r = pread(fd, mem, nrw, off);
#endif

		if (r == -1 && (errno == try_err(loop_eintr, EINTR)
		    || errno == try_err(loop_eagain, EAGAIN)))
			goto try_rw_again;

		rval = rw_over_nrw(r, nrw);
		if (rval < 0)
			goto err_prw;

		errno = saved_errno;

		return rval;
	}

#if defined(REAL_POS_IO) && \
    REAL_POS_IO > 0
	goto real_pread_pwrite;
#else
	if ((off_orig = lseek_on_eintr(fd, (off_t)0, SEEK_CUR,
	    loop_eagain, loop_eintr)) == (off_t)-1) {
		r = -1;
	} else if (lseek_on_eintr(fd, off, SEEK_SET,
	    loop_eagain, loop_eintr) == (off_t)-1) {
		r = -1;
	} else {
		verified = lseek_on_eintr(fd, (off_t)0, SEEK_CUR,
		    loop_eagain, loop_eintr);

		/* abort if the offset changed,
		 * indicating race condition. if
		 * off_reset enabled, reset *ONCE*
		 */

		if (off_reset && off != verified)
			lseek_on_eintr(fd, off, SEEK_SET,
			    loop_eagain, loop_eintr);

		do {
			/* check offset again, repeatedly.
			 * even if off_reset is set, this
			 * aborts if offsets change again
			 */

			verified = lseek_on_eintr(fd, (off_t)0, SEEK_CUR,
			    loop_eagain, loop_eintr);

			if (off != verified) {

				errno = EBUSY;
				goto err_prw;
			}

			if (rw_type == IO_PREAD)
				r = read(fd, mem, nrw);
			else if (rw_type == IO_PWRITE)
				r = write(fd, mem, nrw);

			if (rw_over_nrw(r, nrw) == -1)
				break;

		} while (r == -1 &&
		    (errno == try_err(loop_eintr, EINTR) ||
		     errno == try_err(loop_eagain, EAGAIN)));
	}

	saved_errno = errno;

	off_last = lseek_on_eintr(fd, off_orig, SEEK_SET,
	    loop_eagain, loop_eintr);

	if (off_last != off_orig) {
		errno = saved_errno;
		goto err_prw;
	}

	errno = saved_errno;

	rval = rw_over_nrw(r, nrw);
	if (rval < 0)
		goto err_prw;

	errno = saved_errno;

	return rval;

#endif

err_prw:

	if (errno == saved_errno)
		errno = EIO;

	return -1;
}

int
io_args(int fd, void *mem, size_t nrw,
    off_t off, int rw_type)
{
	int saved_errno = errno;

	/* obviously */
	if (mem == NULL) {

		errno = EFAULT;
		goto err_io_args;
	}

	/* uninitialised fd */
	if (fd < 0) {

		errno = EBADF;
		goto err_io_args;
	}

	/* negative offset */
	if (off < 0) {

		errno = ERANGE;
		goto err_io_args;
	}

	/* prevent zero-byte rw */
	if (!nrw)
		goto err_io_args;

	/* prevent overflow */
	if (nrw > (size_t)SSIZE_MAX) {

		errno = ERANGE;
		goto err_io_args;
	}

	/* prevent overflow */
	if (((size_t)off + nrw) < (size_t)off) {

		errno = ERANGE;
		goto err_io_args;
	}

	if (rw_type > IO_PWRITE) {

		errno = EINVAL;
		goto err_io_args;
	}

	errno = saved_errno;

	return 0;

err_io_args:

	if (errno == saved_errno)
		errno = EINVAL;

	return -1;
}

int
check_file(int fd, struct stat *st)
{
	int saved_errno = errno;

	if (fd < 0) {
		errno = EBADF;
		goto err_is_file;
	}

	if (st == NULL) {
		errno = EFAULT;
		goto err_is_file;
	}

	if (fstat(fd, st) == -1)	
		goto err_is_file;

	if (!S_ISREG(st->st_mode)) {

		errno = EBADF;
		goto err_is_file;
	}

	errno = saved_errno;

	return 0;

err_is_file:

	if (errno == saved_errno)
		errno = EINVAL;

	return -1;
}

/* POSIX can say whatever it wants.
 * specification != implementation
 */

ssize_t
rw_over_nrw(ssize_t r, size_t nrw)
{
	int saved_errno = errno;

	/* not a libc bug, but we
	 * don't like the number zero
	 */
	if (!nrw)
		goto err_rw_over_nrw;

	if (r == -1)
		return r;

	if ((size_t)
	    r > SSIZE_MAX) {

		/* Theoretical buggy libc
		 * check. Extremely academic.
		 *
		 * Specifications never
		 * allow this return value
		 * to exceed SSIZE_T, but
		 * spec != implementation
		 *
		 * Check this after using
		 * [p]read() or [p]write()
		 *
		 * NOTE: here, we assume
		 * ssize_t integers are the
		 * same size as SSIZE_T
		 */

		errno = ERANGE;
		goto err_rw_over_nrw;
	}

	/* Theoretical buggy libc:
	 * Should never return a number of
	 * bytes above the requested length.
	 */
	if ((size_t)r > nrw) {

		errno = ERANGE;
		goto err_rw_over_nrw;
	}

	errno = saved_errno;

	return r;

err_rw_over_nrw:

	if (errno == saved_errno)
		errno = EIO;

	return -1;
}

#if !defined(REAL_POS_IO) || \
    REAL_POS_IO < 1
off_t
lseek_on_eintr(int fd, off_t off, int whence,
    int loop_eagain, int loop_eintr)
{
	off_t old;

	old = -1;

	do {
		old = lseek(fd, off, whence);
	} while (old == (off_t)-1 && (
	    errno == try_err(loop_eintr, EINTR) ||
	    errno == try_err(loop_eintr, ETXTBSY) ||
	    errno == try_err(loop_eagain, EAGAIN) ||
	    errno == try_err(loop_eagain, EWOULDBLOCK)));

	return old;
}
#endif

int
try_err(int loop_err, int errval)
{
	if (loop_err)
		return errval;

	return -1;
}

int
close_on_eintr(int fd)
{
	int r;
	int saved_errno = errno;

	do {
		r = close(fd);
	} while (r == -1 && (
	    errno == EINTR || errno == EAGAIN ||
	    errno == EWOULDBLOCK || errno == ETXTBSY));

	if (r >= 0)
		errno = saved_errno;

	return r;
}

int
fsync_on_eintr(int fd)
{
	int r;
	int saved_errno = errno;

	do {
		r = fsync(fd);
	} while (r == -1 && (errno == EINTR || errno == EAGAIN ||
	    errno == ETXTBSY || errno == EWOULDBLOCK));

	if (r >= 0)
		errno = saved_errno;

	return r;
}

int
fs_rename_at(int olddirfd, const char *old,
    int newdirfd, const char *new)
{
	if (new == NULL || old == NULL) {

		errno = EFAULT;
		return -1;
	}

	if (olddirfd < 0 || newdirfd < 0) {

		errno = EBADF;
		return -1;
	}

	return renameat(olddirfd, old, newdirfd, new);
}

/* secure open, based on
 * relative path to root
 *
 * always a fixed fd for /
 * see: rootfs()
 */
int
fs_open(const char *path, int flags)
{
	struct filesystem *fs;
	const char *rel;

	if (path == NULL) {
		errno = EFAULT;
		return -1;
	}

	if (path[0] != '/') {
		errno = EINVAL;
		return -1;
	}

	fs = rootfs();
	if (fs == NULL)
		return -1;

	rel = path + 1;

	return fs_resolve_at(fs->rootfd, rel, flags);
}

/* singleton function
 * that returns a fixed
 * descriptor of /
 *
 * used throughout, for
 * repeated integrity checks
 */
struct filesystem *
rootfs(void)
{
	static struct filesystem global_fs;
	static int fs_initialised = 0;

	if (!fs_initialised) {

		global_fs.rootfd =
		    open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC);

		if (global_fs.rootfd < 0)
			return NULL;

		fs_initialised = 1;
	}

	return &global_fs;
}

/* filesystem sandboxing.
 * (in userspace)
 */
int
fs_resolve_at(int dirfd, const char *path, int flags)
{
	int nextfd = -1;
	int curfd;
	const char *p;
	char name[256];
	int saved_errno = errno;
	int r;
	int is_last;

	if (dirfd < 0 || path == NULL || *path == '\0') {
		errno = EINVAL;
		return -1;
	}

	p = path;
	curfd = dirfd; /* start here */

	for (;;) {
		r = fs_next_component(&p, name, sizeof(name));
		if (r < 0)
			goto err;
		if (r == 0)
			break;

		is_last = (*p == '\0');

		nextfd = fs_open_component(curfd, name, flags, is_last);
		if (nextfd < 0)
			goto err;

		/* close previous fd IF it is not the original input */
		if (curfd != dirfd) {
			(void) close_on_eintr(curfd);
		}

		curfd = nextfd;
		nextfd = -1;
	}

	errno = saved_errno;
	return curfd;

err:
	saved_errno = errno;

	if (nextfd >= 0)
		(void) close_on_eintr(nextfd);

	/* close curfd only if it's not the original */
	if (curfd != dirfd && curfd >= 0)
		(void) close_on_eintr(curfd);

	errno = saved_errno;
	return -1;
}

int
fs_next_component(const char **p,
    char *name, size_t namesz)
{
	const char *s = *p;
	size_t len = 0;
#if defined(PATH_LEN) && \
(PATH_LEN) >= 256
	size_t maxlen = PATH_LEN;
#else
	size_t maxlen = 4096;
#endif

	while (*s == '/')
		s++;

	if (*s == '\0') {
		*p = s;
		return 0;
	}

	while (s[len] != '/' && s[len] != '\0')
		len++;

	if (len == 0 || len >= namesz ||
	    len >= maxlen) {
		errno = ENAMETOOLONG;
		return -1;
	}

	memcpy(name, s, len);
	name[len] = '\0';

	/* reject . and .. */
	if ((name[0] == '.' && name[1] == '\0') ||
	    (name[0] == '.' && name[1] == '.' && name[2] == '\0')) {
		errno = EPERM;
		return -1;
	}

	*p = s + len;
	return 1;
}

int
fs_open_component(int dirfd, const char *name,
    int flags, int is_last)
{
	int fd;
	struct stat st;

	fd = openat2p(dirfd, name,
	    (is_last ? flags : (O_RDONLY | O_DIRECTORY)) |
	    O_NOFOLLOW | O_CLOEXEC, (flags & O_CREAT) ? 0600 : 0);

	/* the patient always lies
	 */
	if (!is_last) {

		if (fd < 0) {
			errno = EBADF;
			return -1;
		}

		if (fstat(fd, &st) < 0)
			return -1;

		if (!S_ISDIR(st.st_mode)) {

			(void) close_on_eintr(fd);
			errno = ENOTDIR;
			return -1;
		}
	}

	return fd;
}

int
fs_dirname_basename(const char *path,
    char **dir, char **base,
    int allow_relative)
{
	char *buf;
	char *slash;
	size_t len;
	int rval;
#if defined(PATH_LEN) && \
(PATH_LEN) >= 256
	size_t maxlen = PATH_LEN;
#else
	size_t maxlen = 4096;
#endif

	if (path == NULL || dir == NULL || base == NULL)
		return -1;

	if (slen(path, maxlen, &len) < 0)
		return -1;

	buf = malloc(len + 1);
	if (buf == NULL)
		return -1;

	memcpy(buf, path, len + 1);

	/* strip trailing slashes */
	while (len > 1 && buf[len - 1] == '/')
		buf[--len] = '\0';

	slash = strrchr(buf, '/');

	if (slash) {

		*slash = '\0';
		*dir = buf;
		*base = slash + 1;

		if (**dir == '\0') {
			(*dir)[0] = '/';
			(*dir)[1] = '\0';
		}
	} else if (allow_relative) {

		*dir = strdup(".");
		*base = buf;
	} else {
		errno = EINVAL;
		free(buf);
		return -1;
	}

	return 0;
}

/* portable wrapper for use of openat2 on linux,
 * with fallback for others e.g. openbsd
 *
 * BONUS: arg checks
 * TODO: consider EINTR/EAGAIN retry loop
 */
int
openat2p(int dirfd, const char *path,
    int flags, mode_t mode)
{
#ifdef __linux__
	struct open_how how = {
		.flags = flags,
		.mode = mode,
		.resolve =
		    RESOLVE_BENEATH |
		    RESOLVE_NO_SYMLINKS |
		    RESOLVE_NO_MAGICLINKS
	};
	int saved_errno = errno;
	int rval;
#endif

	if (dirfd < 0) {
		errno = EBADF;
		return -1;
	}

	if (path == NULL) {
		errno = EFAULT;
		return -1;
	}

retry:
	errno = 0;

#ifdef __linux__
	/* more secure than regular openat,
	 * but linux-only at the time of writing
	 */
	rval = syscall(SYS_openat2, dirfd, path, &how, sizeof(how));
#else
	/* less secure, but e.g. openbsd
	 * doesn't have openat2 yet
	 */
	rval = openat(dirfd, path, flags, mode);
#endif
	if (rval == -1 && (
	    errno == EINTR ||
	    errno == EAGAIN ||
	    errno == EWOULDBLOCK ||
	    errno == ETXTBSY))
		goto retry;

	if (rval >= 0)
		errno = saved_errno;

	return rval;
}

int
mkdirat_on_eintr( /* <-- say that 10 times to please the demon */
    int dirfd, 
    const char *path, mode_t mode)
{
	int saved_errno = errno;
	int rval;

	if (dirfd < 0) {
		errno = EBADF;
		return -1;
	}

	if (path == NULL) {
		errno = EFAULT;
		return -1;
	}

retry:
	errno = 0;
	rval = mkdirat(dirfd, path, mode);

	if (rval == -1 && (
	    errno == EINTR ||
	    errno == EAGAIN ||
	    errno == EWOULDBLOCK ||
	    errno == ETXTBSY))
		goto retry;

	if (rval >= 0)
		errno = saved_errno;

	return rval;
}