summaryrefslogtreecommitdiffhomepage
path: root/lib/fs.c
blob: 0f03ad4c55213ebb20d58844d27257654da7fdb7 (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
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
/*
 * Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/**
 * # Filesystem Access
 *
 * The `fs` module provides functions for interacting with the file system.
 *
 * Functions can be individually imported and directly accessed using the
 * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#named_import named import}
 * syntax:
 *
 *   ```
 *   import { readlink, popen } from 'fs';
 *
 *   let dest = readlink('/sys/class/net/eth0');
 *   let proc = popen('ps ww');
 *   ```
 *
 * Alternatively, the module namespace can be imported
 * using a wildcard import statement:
 *
 *   ```
 *   import * as fs from 'fs';
 *
 *   let dest = fs.readlink('/sys/class/net/eth0');
 *   let proc = fs.popen('ps ww');
 *   ```
 *
 * Additionally, the filesystem module namespace may also be imported by invoking
 * the `ucode` interpreter with the `-lfs` switch.
 *
 * @module fs
 */

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
#include <glob.h>
#include <fnmatch.h>
#include <limits.h>
#include <fcntl.h>

#include "ucode/module.h"
#include "ucode/platform.h"

#define err_return(err) do { last_error = err; return NULL; } while(0)

//static const uc_ops *ops;
static uc_resource_type_t *file_type, *proc_type, *dir_type;

static int last_error = 0;

/**
 * Query error information.
 *
 * Returns a string containing a description of the last occurred error or
 * `null` if there is no error information.
 *
 * @function module:fs#error
 *
 *
 * @returns {string|null}
 *
 * @example
 * // Trigger file system error
 * unlink('/path/does/not/exist');
 *
 * // Print error (should yield "No such file or directory")
 * print(error(), "\n");
 */
static uc_value_t *
uc_fs_error(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *errmsg;

	if (last_error == 0)
		return NULL;

	errmsg = ucv_string_new(strerror(last_error));
	last_error = 0;

	return errmsg;
}

static uc_value_t *
uc_fs_read_common(uc_vm_t *vm, size_t nargs, const char *type)
{
	uc_value_t *limit = uc_fn_arg(0);
	uc_value_t *rv = NULL;
	char buf[128], *p = NULL, *tmp;
	size_t rlen, len = 0;
	const char *lstr;
	int64_t lsize;
	ssize_t llen;

	FILE **fp = uc_fn_this(type);

	if (!fp || !*fp)
		err_return(EBADF);

	if (ucv_type(limit) == UC_STRING) {
		lstr = ucv_string_get(limit);
		llen = ucv_string_length(limit);

		if (llen == 4 && !strcmp(lstr, "line")) {
			llen = getline(&p, &rlen, *fp);

			if (llen == -1)
				err_return(errno);

			len = (size_t)llen;
		}
		else if (llen == 3 && !strcmp(lstr, "all")) {
			while (true) {
				rlen = fread(buf, 1, sizeof(buf), *fp);

				tmp = realloc(p, len + rlen);

				if (!tmp) {
					free(p);
					err_return(ENOMEM);
				}

				memcpy(tmp + len, buf, rlen);

				p = tmp;
				len += rlen;

				if (rlen == 0)
					break;
			}
		}
		else if (llen == 1) {
			llen = getdelim(&p, &rlen, *lstr, *fp);

			if (llen == -1)
				err_return(errno);

			len = (size_t)llen;
		}
		else {
			return NULL;
		}
	}
	else if (ucv_type(limit) == UC_INTEGER) {
		lsize = ucv_int64_get(limit);

		if (lsize <= 0)
			return NULL;

		p = calloc(1, lsize);

		if (!p)
			err_return(ENOMEM);

		len = fread(p, 1, lsize, *fp);

		if (ferror(*fp)) {
			free(p);
			err_return(errno);
		}
	}
	else {
		err_return(EINVAL);
	}

	rv = ucv_string_new_length(p, len);
	free(p);

	return rv;
}

static uc_value_t *
uc_fs_write_common(uc_vm_t *vm, size_t nargs, const char *type)
{
	uc_value_t *data = uc_fn_arg(0);
	size_t len, wsize;
	char *str;

	FILE **fp = uc_fn_this(type);

	if (!fp || !*fp)
		err_return(EBADF);

	if (ucv_type(data) == UC_STRING) {
		len = ucv_string_length(data);
		wsize = fwrite(ucv_string_get(data), 1, len, *fp);
	}
	else {
		str = ucv_to_jsonstring(vm, data);
		len = str ? strlen(str) : 0;
		wsize = fwrite(str, 1, len, *fp);
		free(str);
	}

	if (wsize < len && ferror(*fp))
		err_return(errno);

	return ucv_int64_new(wsize);
}

static uc_value_t *
uc_fs_flush_common(uc_vm_t *vm, size_t nargs, const char *type)
{
	FILE **fp = uc_fn_this(type);

	if (!fp || !*fp)
		err_return(EBADF);

	if (fflush(*fp) != EOF)
		err_return(errno);

	return ucv_boolean_new(true);
}

static uc_value_t *
uc_fs_fileno_common(uc_vm_t *vm, size_t nargs, const char *type)
{
	int fd;

	FILE **fp = uc_fn_this(type);

	if (!fp || !*fp)
		err_return(EBADF);

	fd = fileno(*fp);

	if (fd == -1)
		err_return(errno);

	return ucv_int64_new(fd);
}


/**
 * Represents a handle for interacting with a program launched by `popen()`.
 *
 * @class module:fs.proc
 * @hideconstructor
 *
 * @see {@link module:fs#popen|popen()}
 *
 * @example
 *
 * const handle = popen(…);
 *
 * handle.read(…);
 * handle.write(…);
 * handle.flush();
 *
 * handle.fileno();
 *
 * handle.close();
 *
 * handle.error();
 */

/**
 * Query error information.
 *
 * Returns a string containing a description of the last occurred error or
 * `null` if there is no error information.
 *
 * @function module:fs.proc#error
 *
 * @returns {string|null}
 *
 * @example
 * // Trigger error
 * const fp = popen("command");
 * fp.close();
 * fp.close(); // already closed
 *
 * // Print error (should yield "Bad file descriptor")
 * print(fp.error(), "\n");
 */

/**
 * Closes the program handle and awaits program termination.
 *
 * Upon calling `close()` on the handle, the program's input or output stream
 * (depending on the open mode) is closed. Afterwards, the function awaits the
 * termination of the underlying program and returns its exit code.
 *
 * - When the program was terminated by a signal, the return value will be the
 *   negative signal number, e.g. `-9` for SIGKILL.
 *
 * - When the program terminated normally, the return value will be the positive
 *   exit code of the program.
 *
 * Returns a negative signal number if the program was terminated by a signal.
 *
 * Returns a positive exit code if the program terminated normally.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs.proc#close
 *
 * @returns {number|null}
 */
static uc_value_t *
uc_fs_pclose(uc_vm_t *vm, size_t nargs)
{
	FILE **fp = uc_fn_this("fs.proc");
	int rc;

	if (!fp || !*fp)
		err_return(EBADF);

	rc = pclose(*fp);
	*fp = NULL;

	if (rc == -1)
		err_return(errno);

	if (WIFEXITED(rc))
		return ucv_int64_new(WEXITSTATUS(rc));

	if (WIFSIGNALED(rc))
		return ucv_int64_new(-WTERMSIG(rc));

	return ucv_int64_new(0);
}

/**
 * Reads a chunk of data from the program handle.
 *
 * The length argument may be either a positive number of bytes to read, in
 * which case the read call returns up to that many bytes, or a string to
 * specify a dynamic read size.
 *
 *  - If length is a number, the method will read the specified number of bytes
 *    from the handle. Reading stops after the given amount of bytes or after
 *    encountering EOF, whatever comes first.
 *
 *  - If length is the string "line", the method will read an entire line,
 *    terminated by "\n" (a newline), from the handle. Reading stops at the next
 *    newline or when encountering EOF. The returned data will contain the
 *    terminating newline character if one was read.
 *
 *  - If length is the string "all", the method will read from the handle until
 *    encountering EOF and return the complete contents.
 *
 *  - If length is a single character string, the method will read from the
 *    handle until encountering the specified character or upon encountering
 *    EOF. The returned data will contain the terminating character if one was
 *    read.
 *
 * Returns a string containing the read data.
 *
 * Returns an empty string on EOF.
 *
 * Returns `null` if a read error occurred.
 *
 * @function module:fs.proc#read
 *
 * @param {number|string} length
 * The length of data to read. Can be a number, the string "line", the string
 * "all", or a single character string.
 *
 * @returns {string|null}
 *
 * @example
 * const fp = popen("command", "r");
 *
 * // Example 1: Read 10 bytes from the handle
 * const chunk = fp.read(10);
 *
 * // Example 2: Read the handle line by line
 * for (let line = fp.read("line"); length(line); line = fp.read("line"))
 *   print(line);
 *
 * // Example 3: Read the complete contents from the handle
 * const content = fp.read("all");
 *
 * // Example 4: Read until encountering the character ':'
 * const field = fp.read(":");
 */
static uc_value_t *
uc_fs_pread(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_read_common(vm, nargs, "fs.proc");
}

/**
 * Writes a chunk of data to the program handle.
 *
 * In case the given data is not a string, it is converted to a string before
 * being written to the program's stdin. String values are written as-is,
 * integer and double values are written in decimal notation, boolean values are
 * written as `true` or `false` while arrays and objects are converted to their
 * JSON representation before being written. The `null` value is represented by
 * an empty string so `proc.write(null)` would be a no-op. Resource values are
 * written in the form `<type address>`, e.g. `<fs.file 0x7f60f0981760>`.
 *
 * If resource, array or object values contain a `tostring()` function in their
 * prototypes, then this function is invoked to obtain an alternative string
 * representation of the value.
 *
 * Returns the number of bytes written.
 *
 * Returns `null` if a write error occurred.
 *
 * @function module:fs.proc#write
 *
 * @param {*} data
 * The data to be written.
 *
 * @returns {number|null}
 *
 * @example
 * const fp = popen("command", "w");
 *
 * fp.write("Hello world!\n");
 */
static uc_value_t *
uc_fs_pwrite(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_write_common(vm, nargs, "fs.proc");
}

/**
 * Forces a write of all buffered data to the underlying handle.
 *
 * Returns `true` if the data was successfully flushed.
 *
 * Returns `null` on error.
 *
 * @function module:fs.proc#flush
 *
 * @returns {boolean|null}
 *
 */
static uc_value_t *
uc_fs_pflush(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_flush_common(vm, nargs, "fs.proc");
}

/**
 * Obtains the number of the handle's underlying file descriptor.
 *
 * Returns the descriptor number.
 *
 * Returns `null` on error.
 *
 * @function module:fs.proc#fileno
 *
 * @returns {number|null}
 */
static uc_value_t *
uc_fs_pfileno(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_fileno_common(vm, nargs, "fs.proc");
}

/**
 * Starts a process and returns a handle representing the executed process.
 *
 * The handle will be connected to the process stdin or stdout, depending on the
 * value of the mode argument.
 *
 * The mode argument may be either "r" to open the process for reading (connect
 * to its stdin) or "w" to open the process for writing (connect to its stdout).
 *
 * The mode character "r" or "w" may be optionally followed by "e" to apply the
 * FD_CLOEXEC flag onto the open descriptor.
 *
 * Returns a process handle referring to the executed process.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs#popen
 *
 * @param {string} command
 * The command to be executed.
 *
 * @param {string} [mode="r"]
 * The open mode of the process handle.
 *
 * @returns {module:fs.proc|null}
 *
 * @example
 * // Open a process
 * const process = popen('command', 'r');
 */
static uc_value_t *
uc_fs_popen(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *comm = uc_fn_arg(0);
	uc_value_t *mode = uc_fn_arg(1);
	FILE *fp;

	if (ucv_type(comm) != UC_STRING)
		err_return(EINVAL);

	fp = popen(ucv_string_get(comm),
		ucv_type(mode) == UC_STRING ? ucv_string_get(mode) : "r");

	if (!fp)
		err_return(errno);

	return uc_resource_new(proc_type, fp);
}


/**
 * Represents a handle for interacting with a file opened by one of the file
 * open functions.
 *
 * @class module:fs.file
 * @hideconstructor
 *
 * @see {@link module:fs#open|open()}
 * @see {@link module:fs#fdopen|fdopen()}
 * @see {@link module:fs#mkstemp|mkstemp()}
 * @see {@link module:fs#pipe|pipe()}
 *
 * @example
 *
 * const handle = open(…);
 *
 * handle.read(…);
 * handle.write(…);
 * handle.flush();
 *
 * handle.seek(…);
 * handle.tell();
 *
 * handle.isatty();
 * handle.fileno();
 *
 * handle.close();
 *
 * handle.error();
 */

/**
 * Query error information.
 *
 * Returns a string containing a description of the last occurred error or
 * `null` if there is no error information.
 *
 * @function module:fs.file#error
 *
 * @returns {string|null}
 *
 * @example
 * // Trigger error
 * const fp = open("file.txt");
 * fp.close();
 * fp.close(); // already closed
 *
 * // Print error (should yield "Bad file descriptor")
 * print(fp.error(), "\n");
 */

/**
 * Closes the file handle.
 *
 * Upon calling `close()` on the handle, buffered data is flushed and the
 * underlying file descriptor is closed.
 *
 * Returns `true` if the handle was properly closed.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs.file#close
 *
 * @returns {boolean|null}
 */
static uc_value_t *
uc_fs_close(uc_vm_t *vm, size_t nargs)
{
	FILE **fp = uc_fn_this("fs.file");

	if (!fp || !*fp)
		err_return(EBADF);

	fclose(*fp);
	*fp = NULL;

	return ucv_boolean_new(true);
}

/**
 * Reads a chunk of data from the file handle.
 *
 * The length argument may be either a positive number of bytes to read, in
 * which case the read call returns up to that many bytes, or a string to
 * specify a dynamic read size.
 *
 *  - If length is a number, the method will read the specified number of bytes
 *    from the handle. Reading stops after the given amount of bytes or after
 *    encountering EOF, whatever comes first.
 *
 *  - If length is the string "line", the method will read an entire line,
 *    terminated by "\n" (a newline), from the handle. Reading stops at the next
 *    newline or when encountering EOF. The returned data will contain the
 *    terminating newline character if one was read.
 *
 *  - If length is the string "all", the method will read from the handle until
 *    encountering EOF and return the complete contents.
 *
 *  - If length is a single character string, the method will read from the
 *    handle until encountering the specified character or upon encountering
 *    EOF. The returned data will contain the terminating character if one was
 *    read.
 *
 * Returns a string containing the read data.
 *
 * Returns an empty string on EOF.
 *
 * Returns `null` if a read error occurred.
 *
 * @function module:fs.file#read
 *
 * @param {number|string} length
 * The length of data to read. Can be a number, the string "line", the string
 * "all", or a single character string.
 *
 * @returns {string|null}
 *
 * @example
 * const fp = open("file.txt", "r");
 *
 * // Example 1: Read 10 bytes from the handle
 * const chunk = fp.read(10);
 *
 * // Example 2: Read the handle line by line
 * for (let line = fp.read("line"); length(line); line = fp.read("line"))
 *   print(line);
 *
 * // Example 3: Read the complete contents from the handle
 * const content = fp.read("all");
 *
 * // Example 4: Read until encountering the character ':'
 * const field = fp.read(":");
 */
static uc_value_t *
uc_fs_read(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_read_common(vm, nargs, "fs.file");
}

/**
 * Writes a chunk of data to the file handle.
 *
 * In case the given data is not a string, it is converted to a string before
 * being written into the file. String values are written as-is, integer and
 * double values are written in decimal notation, boolean values are written as
 * `true` or `false` while arrays and objects are converted to their JSON
 * representation before being written. The `null` value is represented by an
 * empty string so `file.write(null)` would be a no-op. Resource values are
 * written in the form `<type address>`, e.g. `<fs.file 0x7f60f0981760>`.
 *
 * If resource, array or object values contain a `tostring()` function in their
 * prototypes, then this function is invoked to obtain an alternative string
 * representation of the value.
 *
 * Returns the number of bytes written.
 *
 * Returns `null` if a write error occurred.
 *
 * @function module:fs.file#write
 *
 * @param {*} data
 * The data to be written.
 *
 * @returns {number|null}
 *
 * @example
 * const fp = open("file.txt", "w");
 *
 * fp.write("Hello world!\n");
 */
static uc_value_t *
uc_fs_write(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_write_common(vm, nargs, "fs.file");
}

/**
 * Set file read position.
 *
 * Set the read position of the open file handle to the given offset and
 * position.
 *
 * Returns `true` if the read position was set.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs.file#seek
 *
 * @param {number} [offset=0]
 * The offset in bytes.
 *
 * @param {number} [position=0]
 * The position of the offset.
 *
 * | Position | Description                                                                                  |
 * |----------|----------------------------------------------------------------------------------------------|
 * | `0`      | The given offset is relative to the start of the file. This is the default value if omitted. |
 * | `1`      | The given offset is relative to the current read position.                                   |
 * | `2`      | The given offset is relative to the end of the file.                                         |
 *
 * @returns {boolean|null}
 *
 * @example
 * const fp = open("file.txt", "r");
 *
 * print(fp.read(100), "\n");  // read 100 bytes...
 * fp.seek(0, 0);              // ... and reset position to start of file
 * print(fp.read(100), "\n");  // ... read same 100 bytes again
 *
 * fp.seek(10, 1);  // skip 10 bytes forward, relative to current offset ...
 * fp.tell();       // ... position is at 110 now
 *
 * fp.seek(-10, 2);            // set position to ten bytes before EOF ...
 * print(fp.read(100), "\n");  // ... reads 10 bytes at most
 */
static uc_value_t *
uc_fs_seek(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *ofs = uc_fn_arg(0);
	uc_value_t *how = uc_fn_arg(1);
	int whence, res;
	off_t offset;

	FILE **fp = uc_fn_this("fs.file");

	if (!fp || !*fp)
		err_return(EBADF);

	if (!ofs)
		offset = 0;
	else if (ucv_type(ofs) != UC_INTEGER)
		err_return(EINVAL);
	else
		offset = (off_t)ucv_int64_get(ofs);

	if (!how)
		whence = 0;
	else if (ucv_type(how) != UC_INTEGER)
		err_return(EINVAL);
	else
		whence = (int)ucv_int64_get(how);

	res = fseeko(*fp, offset, whence);

	if (res < 0)
		err_return(errno);

	return ucv_boolean_new(true);
}

/**
 * Obtain current read position.
 *
 * Obtains the current, absolute read position of the open file.
 *
 * Returns an integer containing the current read offset in bytes.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs.file#tell
 *
 * @returns {number|null}
 */
static uc_value_t *
uc_fs_tell(uc_vm_t *vm, size_t nargs)
{
	off_t offset;

	FILE **fp = uc_fn_this("fs.file");

	if (!fp || !*fp)
		err_return(EBADF);

	offset = ftello(*fp);

	if (offset < 0)
		err_return(errno);

	return ucv_int64_new(offset);
}

/**
 * Check for TTY.
 *
 * Checks whether the open file handle refers to a TTY (terminal) device.
 *
 * Returns `true` if the handle refers to a terminal.
 *
 * Returns `false` if the handle refers to another kind of file.
 *
 * Returns `null` on error.
 *
 * @function module:fs.file#isatty
 *
 * @returns {boolean|null}
 *
 */
static uc_value_t *
uc_fs_isatty(uc_vm_t *vm, size_t nargs)
{
	FILE **fp = uc_fn_this("fs.file");
	int fd;

	if (!fp || !*fp)
		err_return(EBADF);

	fd = fileno(*fp);

	if (fd == -1)
		err_return(errno);

	return ucv_boolean_new(isatty(fd) == 1);
}

/**
 * Forces a write of all buffered data to the underlying handle.
 *
 * Returns `true` if the data was successfully flushed.
 *
 * Returns `null` on error.
 *
 * @function module:fs.file#flush
 *
 * @returns {boolean|null}
 *
 */
static uc_value_t *
uc_fs_flush(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_flush_common(vm, nargs, "fs.file");
}

/**
 * Obtains the number of the handle's underlying file descriptor.
 *
 * Returns the descriptor number.
 *
 * Returns `null` on error.
 *
 * @function module:fs.file#fileno
 *
 * @returns {number|null}
 */
static uc_value_t *
uc_fs_fileno(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_fileno_common(vm, nargs, "fs.file");
}

/**
 * Opens a file.
 *
 * The mode argument specifies the way the file is opened, it may
 * start with one of the following values:
 *
 * | Mode    | Description                                                                                                   |
 * |---------|---------------------------------------------------------------------------------------------------------------|
 * | "r"     | Opens a file for reading. The file must exist.                                                                 |
 * | "w"     | Opens a file for writing. If the file exists, it is truncated. If the file does not exist, it is created.     |
 * | "a"     | Opens a file for appending. Data is written at the end of the file. If the file does not exist, it is created. |
 * | "r+"    | Opens a file for both reading and writing. The file must exist.                                              |
 * | "w+"    | Opens a file for both reading and writing. If the file exists, it is truncated. If the file does not exist, it is created. |
 * | "a+"    | Opens a file for both reading and appending. Data can be read and written at the end of the file. If the file does not exist, it is created. |
 *
 * Additionally, the following flag characters may be appended to
 * the mode value:
 *
 * | Flag    | Description                                                                                                   |
 * |---------|---------------------------------------------------------------------------------------------------------------|
 * | "x"     | Opens a file for exclusive creation. If the file exists, the `open` call fails.                             |
 * | "e"     | Opens a file with the `O_CLOEXEC` flag set, ensuring that the file descriptor is closed on `exec` calls.      |
 *
 * If the mode is one of `"w…"` or `"a…"`, the permission argument
 * controls the filesystem permissions bits used when creating
 * the file.
 *
 * Returns a file handle object associated with the opened file.
 *
 * @function module:fs#open
 *
 * @param {string} path
 * The path to the file.
 *
 * @param {string} [mode="r"]
 * The file opening mode.
 *
 * @param {number} [perm=0o666]
 * The file creation permissions (for modes `w…` and `a…`)
 *
 * @returns {module:fs.file|null}
 *
 * @example
 * // Open a file in read-only mode
 * const fileHandle = open('file.txt', 'r');
 */
static uc_value_t *
uc_fs_open(uc_vm_t *vm, size_t nargs)
{
	int open_mode, open_flags, fd, i;
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *mode = uc_fn_arg(1);
	uc_value_t *perm = uc_fn_arg(2);
	mode_t open_perm = 0666;
	FILE *fp;
	char *m;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	m = (ucv_type(mode) == UC_STRING) ? ucv_string_get(mode) : "r";

	switch (*m) {
	case 'r':
		open_mode = O_RDONLY;
		open_flags = 0;
		break;

	case 'w':
		open_mode = O_WRONLY;
		open_flags = O_CREAT | O_TRUNC;
		break;

	case 'a':
		open_mode = O_WRONLY;
		open_flags = O_CREAT | O_APPEND;
		break;

	default:
		err_return(EINVAL);
	}

	for (i = 1; m[i]; i++) {
		switch (m[i]) {
		case '+': open_mode = O_RDWR;      break;
		case 'x': open_flags |= O_EXCL;    break;
		case 'e': open_flags |= O_CLOEXEC; break;
		}
	}

	if (perm) {
		if (ucv_type(perm) != UC_INTEGER)
			err_return(EINVAL);

		open_perm = ucv_int64_get(perm);
	}

#ifdef O_LARGEFILE
	open_flags |= open_mode | O_LARGEFILE;
#else
	open_flags |= open_mode;
#endif

	fd = open(ucv_string_get(path), open_flags, open_perm);

	if (fd < 0)
		return NULL;

	fp = fdopen(fd, m);

	if (!fp) {
		i = errno;
		close(fd);
		err_return(i);
	}

	return uc_resource_new(file_type, fp);
}

/**
 * Associates a file descriptor number with a file handle object.
 *
 * The mode argument controls how the file handle object is opened
 * and must match the open mode of the underlying descriptor.
 *
 * It may be set to one of the following values:
 *
 * | Mode    | Description                                                                                                  |
 * |---------|--------------------------------------------------------------------------------------------------------------|
 * | "r"     | Opens a file stream for reading. The file descriptor must be valid and opened in read mode.                  |
 * | "w"     | Opens a file stream for writing. The file descriptor must be valid and opened in write mode.                 |
 * | "a"     | Opens a file stream for appending. The file descriptor must be valid and opened in write mode.               |
 * | "r+"    | Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode. |
 * | "w+"    | Opens a file stream for both reading and writing. The file descriptor must be valid and opened in read/write mode. |
 * | "a+"    | Opens a file stream for both reading and appending. The file descriptor must be valid and opened in read/write mode. |
 *
 * Returns the file handle object associated with the file descriptor.
 *
 * @function module:fs#fdopen
 *
 * @param {number} fd
 * The file descriptor.
 *
 * @param {string} [mode="r"]
 * The open mode.
 *
 * @returns {Object}
 *
 * @example
 * // Associate file descriptors of stdin and stdout with handles
 * const stdinHandle = fdopen(0, 'r');
 * const stdoutHandle = fdopen(1, 'w');
 */
static uc_value_t *
uc_fs_fdopen(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *fdno = uc_fn_arg(0);
	uc_value_t *mode = uc_fn_arg(1);
	int64_t n;
	FILE *fp;

	if (ucv_type(fdno) != UC_INTEGER)
		err_return(EINVAL);

	n = ucv_int64_get(fdno);

	if (n < 0 || n > INT_MAX)
		err_return(EBADF);

	fp = fdopen((int)n,
		ucv_type(mode) == UC_STRING ? ucv_string_get(mode) : "r");

	if (!fp)
		err_return(errno);

	return uc_resource_new(file_type, fp);
}


/**
 * Represents a handle for interacting with a directory opened by `opendir()`.
 *
 * @class module:fs.dir
 * @hideconstructor
 *
 * @see {@link module:fs#opendir|opendir()}
 *
 * @example
 *
 * const handle = opendir(…);
 *
 * handle.read();
 *
 * handle.tell();
 * handle.seek(…);
 *
 * handle.close();
 *
 * handle.error();
 */

/**
 * Query error information.
 *
 * Returns a string containing a description of the last occurred error or
 * `null` if there is no error information.
 *
 * @function module:fs.dir#error
 *
 * @returns {string|null}
 *
 * @example
 * // Trigger error
 * const fp = opendir("/tmp");
 * fp.close();
 * fp.close(); // already closed
 *
 * // Print error (should yield "Bad file descriptor")
 * print(fp.error(), "\n");
 */

/**
 * Read the next entry from the open directory.
 *
 * Returns a string containing the entry name.
 *
 * Returns `null` if there are no more entries to read.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs.dir#read
 *
 * @returns {string|null}
 */
static uc_value_t *
uc_fs_readdir(uc_vm_t *vm, size_t nargs)
{
	DIR **dp = uc_fn_this("fs.dir");
	struct dirent *e;

	if (!dp || !*dp)
		err_return(EINVAL);

	errno = 0;
	e = readdir(*dp);

	if (!e)
		err_return(errno);

	return ucv_string_new(e->d_name);
}

/**
 * Obtain current read position.
 *
 * Returns the current read position in the open directory handle which can be
 * passed back to the `seek()` function to return to this position. This is
 * mainly useful to read an open directory handle (or specific items) multiple
 * times.
 *
 * Returns an integer referring to the current position.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs.dir#tell
 *
 * @returns {number|null}
 */
static uc_value_t *
uc_fs_telldir(uc_vm_t *vm, size_t nargs)
{
	DIR **dp = uc_fn_this("fs.dir");
	long position;

	if (!dp || !*dp)
		err_return(EBADF);

	position = telldir(*dp);

	if (position == -1)
		err_return(errno);

	return ucv_int64_new((int64_t)position);
}

/**
 * Set read position.
 *
 * Sets the read position within the open directory handle to the given offset
 * value. The offset value should be obtained by a previous call to `tell()` as
 * the specific integer values are implementation defined.
 *
 * Returns `true` if the read position was set.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs.dir#seek
 *
 * @param {number} offset
 * Position value obtained by `tell()`.
 *
 * @returns {boolean|null}
 *
 * @example
 *
 * const handle = opendir("/tmp");
 * const begin = handle.tell();
 *
 * print(handle.read(), "\n");
 *
 * handle.seek(begin);
 *
 * print(handle.read(), "\n");  // prints the first entry again
 */
static uc_value_t *
uc_fs_seekdir(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *ofs = uc_fn_arg(0);
	DIR **dp = uc_fn_this("fs.dir");
	long position;

	if (ucv_type(ofs) != UC_INTEGER)
		err_return(EINVAL);

	if (!dp || !*dp)
		err_return(EBADF);

	position = (long)ucv_int64_get(ofs);

	seekdir(*dp, position);

	return ucv_boolean_new(true);
}

/**
 * Closes the directory handle.
 *
 * Closes the underlying file descriptor referring to the opened directory.
 *
 * Returns `true` if the handle was properly closed.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs.dir#close
 *
 * @returns {boolean|null}
 */
static uc_value_t *
uc_fs_closedir(uc_vm_t *vm, size_t nargs)
{
	DIR **dp = uc_fn_this("fs.dir");

	if (!dp || !*dp)
		err_return(EBADF);

	closedir(*dp);
	*dp = NULL;

	return ucv_boolean_new(true);
}

/**
 * Opens a directory and returns a directory handle associated with the open
 * directory descriptor.
 *
 * Returns a director handle referring to the open directory.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs#opendir
 *
 * @param {string} path
 * The path to the directory.
 *
 * @returns {module:fs.dir|null}
 *
 * @example
 * // Open a directory
 * const directory = opendir('path/to/directory');
 */
static uc_value_t *
uc_fs_opendir(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	DIR *dp;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	dp = opendir(ucv_string_get(path));

	if (!dp)
		err_return(errno);

	return uc_resource_new(dir_type, dp);
}

/**
 * Reads the target path of a symbolic link.
 *
 * Returns a string containing the target path.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs#readlink
 *
 * @param {string} path
 * The path to the symbolic link.
 *
 * @returns {string|null}
 *
 * @example
 * // Read the value of a symbolic link
 * const targetPath = readlink('symbolicLink');
 */
static uc_value_t *
uc_fs_readlink(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *res;
	ssize_t buflen = 0, rv;
	char *buf = NULL, *tmp;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	do {
		buflen += 128;
		tmp = realloc(buf, buflen);

		if (!tmp) {
			free(buf);
			err_return(ENOMEM);
		}

		buf = tmp;
		rv = readlink(ucv_string_get(path), buf, buflen);

		if (rv == -1) {
			free(buf);
			err_return(errno);
		}

		if (rv < buflen)
			break;
	}
	while (true);

	res = ucv_string_new_length(buf, rv);

	free(buf);

	return res;
}

/**
 * @typedef {Object} module:fs.FileStatResult
 * @property {Object} dev - The device information.
 * @property {number} dev.major - The major device number.
 * @property {number} dev.minor - The minor device number.
 * @property {Object} perm - The file permissions.
 * @property {boolean} perm.setuid - Whether the setuid bit is set.
 * @property {boolean} perm.setgid - Whether the setgid bit is set.
 * @property {boolean} perm.sticky - Whether the sticky bit is set.
 * @property {boolean} perm.user_read - Whether the file is readable by the owner.
 * @property {boolean} perm.user_write - Whether the file is writable by the owner.
 * @property {boolean} perm.user_exec - Whether the file is executable by the owner.
 * @property {boolean} perm.group_read - Whether the file is readable by the group.
 * @property {boolean} perm.group_write - Whether the file is writable by the group.
 * @property {boolean} perm.group_exec - Whether the file is executable by the group.
 * @property {boolean} perm.other_read - Whether the file is readable by others.
 * @property {boolean} perm.other_write - Whether the file is writable by others.
 * @property {boolean} perm.other_exec - Whether the file is executable by others.
 * @property {number} inode - The inode number.
 * @property {number} mode - The file mode.
 * @property {number} nlink - The number of hard links.
 * @property {number} uid - The user ID of the owner.
 * @property {number} gid - The group ID of the owner.
 * @property {number} size - The file size in bytes.
 * @property {number} blksize - The block size for file system I/O.
 * @property {number} blocks - The number of 512-byte blocks allocated for the file.
 * @property {number} atime - The timestamp when the file was last accessed.
 * @property {number} mtime - The timestamp when the file was last modified.
 * @property {number} ctime - The timestamp when the file status was last changed.
 * @property {string} type - The type of the file ("directory", "file", etc.).
 */

static uc_value_t *
uc_fs_stat_common(uc_vm_t *vm, size_t nargs, bool use_lstat)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *res, *o;
	struct stat st;
	int rv;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	rv = (use_lstat ? lstat : stat)(ucv_string_get(path), &st);

	if (rv == -1)
		err_return(errno);

	res = ucv_object_new(vm);

	if (!res)
		err_return(ENOMEM);

	o = ucv_object_new(vm);

	if (o) {
		ucv_object_add(o, "major", ucv_int64_new(major(st.st_dev)));
		ucv_object_add(o, "minor", ucv_int64_new(minor(st.st_dev)));

		ucv_object_add(res, "dev", o);
	}

	o = ucv_object_new(vm);

	if (o) {
		ucv_object_add(o, "setuid", ucv_boolean_new(st.st_mode & S_ISUID));
		ucv_object_add(o, "setgid", ucv_boolean_new(st.st_mode & S_ISGID));
		ucv_object_add(o, "sticky", ucv_boolean_new(st.st_mode & S_ISVTX));

		ucv_object_add(o, "user_read", ucv_boolean_new(st.st_mode & S_IRUSR));
		ucv_object_add(o, "user_write", ucv_boolean_new(st.st_mode & S_IWUSR));
		ucv_object_add(o, "user_exec", ucv_boolean_new(st.st_mode & S_IXUSR));

		ucv_object_add(o, "group_read", ucv_boolean_new(st.st_mode & S_IRGRP));
		ucv_object_add(o, "group_write", ucv_boolean_new(st.st_mode & S_IWGRP));
		ucv_object_add(o, "group_exec", ucv_boolean_new(st.st_mode & S_IXGRP));

		ucv_object_add(o, "other_read", ucv_boolean_new(st.st_mode & S_IROTH));
		ucv_object_add(o, "other_write", ucv_boolean_new(st.st_mode & S_IWOTH));
		ucv_object_add(o, "other_exec", ucv_boolean_new(st.st_mode & S_IXOTH));

		ucv_object_add(res, "perm", o);
	}

	ucv_object_add(res, "inode", ucv_int64_new((int64_t)st.st_ino));
	ucv_object_add(res, "mode", ucv_int64_new((int64_t)st.st_mode & ~S_IFMT));
	ucv_object_add(res, "nlink", ucv_int64_new((int64_t)st.st_nlink));
	ucv_object_add(res, "uid", ucv_int64_new((int64_t)st.st_uid));
	ucv_object_add(res, "gid", ucv_int64_new((int64_t)st.st_gid));
	ucv_object_add(res, "size", ucv_int64_new((int64_t)st.st_size));
	ucv_object_add(res, "blksize", ucv_int64_new((int64_t)st.st_blksize));
	ucv_object_add(res, "blocks", ucv_int64_new((int64_t)st.st_blocks));
	ucv_object_add(res, "atime", ucv_int64_new((int64_t)st.st_atime));
	ucv_object_add(res, "mtime", ucv_int64_new((int64_t)st.st_mtime));
	ucv_object_add(res, "ctime", ucv_int64_new((int64_t)st.st_ctime));

	if (S_ISREG(st.st_mode))
		ucv_object_add(res, "type", ucv_string_new("file"));
	else if (S_ISDIR(st.st_mode))
		ucv_object_add(res, "type", ucv_string_new("directory"));
	else if (S_ISCHR(st.st_mode))
		ucv_object_add(res, "type", ucv_string_new("char"));
	else if (S_ISBLK(st.st_mode))
		ucv_object_add(res, "type", ucv_string_new("block"));
	else if (S_ISFIFO(st.st_mode))
		ucv_object_add(res, "type", ucv_string_new("fifo"));
	else if (S_ISLNK(st.st_mode))
		ucv_object_add(res, "type", ucv_string_new("link"));
	else if (S_ISSOCK(st.st_mode))
		ucv_object_add(res, "type", ucv_string_new("socket"));
	else
		ucv_object_add(res, "type", ucv_string_new("unknown"));

	return res;
}

/**
 * Retrieves information about a file or directory.
 *
 * Returns an object containing information about the file or directory.
 *
 * Returns `null` if an error occurred, e.g. due to insufficient permissions.
 *
 * @function module:fs#stat
 *
 * @param {string} path
 * The path to the file or directory.
 *
 * @returns {module:fs.FileStatResult|null}
 *
 * @example
 * // Get information about a file
 * const fileInfo = stat('path/to/file');
 */
static uc_value_t *
uc_fs_stat(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_stat_common(vm, nargs, false);
}

/**
 * Retrieves information about a file or directory, without following symbolic
 * links.
 *
 * Returns an object containing information about the file or directory.
 *
 * Returns `null` if an error occurred, e.g. due to insufficient permissions.
 *
 * @function module:fs#lstat
 *
 * @param {string} path
 * The path to the file or directory.
 *
 * @returns {module:fs.FileStatResult|null}
 *
 * @example
 * // Get information about a directory
 * const dirInfo = lstat('path/to/directory');
 */
static uc_value_t *
uc_fs_lstat(uc_vm_t *vm, size_t nargs)
{
	return uc_fs_stat_common(vm, nargs, true);
}

/**
 * Creates a new directory.
 *
 * Returns `true` if the directory was successfully created.
 *
 * Returns `null` if an error occurred, e.g. due to inexistent path.
 *
 * @function module:fs#mkdir
 *
 * @param {string} path
 * The path to the new directory.
 *
 * @returns {boolean|null}
 *
 * @example
 * // Create a directory
 * mkdir('path/to/new-directory');
 */
static uc_value_t *
uc_fs_mkdir(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *mode = uc_fn_arg(1);

	if (ucv_type(path) != UC_STRING ||
	    (mode && ucv_type(mode) != UC_INTEGER))
		err_return(EINVAL);

	if (mkdir(ucv_string_get(path), (mode_t)(mode ? ucv_int64_get(mode) : 0777)) == -1)
		err_return(errno);

	return ucv_boolean_new(true);
}

/**
 * Removes the specified directory.
 *
 * Returns `true` if the directory was successfully removed.
 *
 * Returns `null` if an error occurred, e.g. due to inexistent path.
 *
 * @function module:fs#rmdir
 *
 * @param {string} path
 * The path to the directory to be removed.
 *
 * @returns {boolean|null}
 *
 * @example
 * // Remove a directory
 * rmdir('path/to/directory');
 */
static uc_value_t *
uc_fs_rmdir(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	if (rmdir(ucv_string_get(path)) == -1)
		err_return(errno);

	return ucv_boolean_new(true);
}

/**
 * Creates a new symbolic link.
 *
 * Returns `true` if the symlink was successfully created.
 *
 * Returns `null` if an error occurred, e.g. due to inexistent path.
 *
 * @function module:fs#symlink
 *
 * @param {string} target
 * The target of the symbolic link.
 *
 * @param {string} path
 * The path of the symbolic link.
 *
 * @returns {boolean|null}
 *
 * @example
 * // Create a symbolic link
 * symlink('target', 'path/to/symlink');
 */
static uc_value_t *
uc_fs_symlink(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *dest = uc_fn_arg(0);
	uc_value_t *path = uc_fn_arg(1);

	if (ucv_type(dest) != UC_STRING ||
	    ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	if (symlink(ucv_string_get(dest), ucv_string_get(path)) == -1)
		err_return(errno);

	return ucv_boolean_new(true);
}

/**
 * Removes the specified file or symbolic link.
 *
 * Returns `true` if the unlink operation was successful.
 *
 * Returns `null` if an error occurred, e.g. due to inexistent path.
 *
 * @function module:fs#unlink
 *
 * @param {string} path
 * The path to the file or symbolic link.
 *
 * @returns {boolean|null}
 *
 * @example
 * // Remove a file
 * unlink('path/to/file');
 */
static uc_value_t *
uc_fs_unlink(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	if (unlink(ucv_string_get(path)) == -1)
		err_return(errno);

	return ucv_boolean_new(true);
}

/**
 * Retrieves the current working directory.
 *
 * Returns a string containing the current working directory path.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs#getcwd
 *
 * @returns {string|null}
 *
 * @example
 * // Get the current working directory
 * const cwd = getcwd();
 */
static uc_value_t *
uc_fs_getcwd(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *res;
	char *buf = NULL, *tmp;
	size_t buflen = 0;

	do {
		buflen += 128;
		tmp = realloc(buf, buflen);

		if (!tmp) {
			free(buf);
			err_return(ENOMEM);
		}

		buf = tmp;

		if (getcwd(buf, buflen) != NULL)
			break;

		if (errno == ERANGE)
			continue;

		free(buf);
		err_return(errno);
	}
	while (true);

	res = ucv_string_new(buf);

	free(buf);

	return res;
}

/**
 * Changes the current working directory to the specified path.
 *
 * Returns `true` if the permission change was successful.
 *
 * Returns `null` if an error occurred, e.g. due to insufficient permissions or
 * invalid arguments.
 *
 * @function module:fs#chdir
 *
 * @param {string} path
 * The path to the new working directory.
 *
 * @returns {boolean|null}
 *
 * @example
 * // Change the current working directory
 * chdir('new-directory');
 */
static uc_value_t *
uc_fs_chdir(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	if (chdir(ucv_string_get(path)) == -1)
		err_return(errno);

	return ucv_boolean_new(true);
}

/**
 * Changes the permission mode bits of a file or directory.
 *
 * Returns `true` if the permission change was successful.
 *
 * Returns `null` if an error occurred, e.g. due to insufficient permissions or
 * invalid arguments.
 *
 * @function module:fs#chmod
 *
 * @param {string} path
 * The path to the file or directory.
 *
 * @param {number} mode
 * The new mode (permissions).
 *
 * @returns {boolean|null}
 *
 * @example
 * // Change the mode of a file
 * chmod('path/to/file', 0o644);
 */
static uc_value_t *
uc_fs_chmod(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *mode = uc_fn_arg(1);

	if (ucv_type(path) != UC_STRING ||
	    ucv_type(mode) != UC_INTEGER)
		err_return(EINVAL);

	if (chmod(ucv_string_get(path), (mode_t)ucv_int64_get(mode)) == -1)
		err_return(errno);

	return ucv_boolean_new(true);
}

static bool
uc_fs_resolve_user(uc_value_t *v, uid_t *uid)
{
	struct passwd *pw = NULL;
	int64_t n;
	char *s;

	*uid = (uid_t)-1;

	switch (ucv_type(v)) {
	case UC_INTEGER:
		n = ucv_int64_get(v);

		if (n < -1) {
			errno = ERANGE;

			return false;
		}

		*uid = (uid_t)n;

		return true;

	case UC_STRING:
		s = ucv_string_get(v);
		pw = getpwnam(s);

		if (!pw) {
			errno = ENOENT;

			return false;
		}

		*uid = pw->pw_uid;

		return true;

	case UC_NULL:
		return true;

	default:
		errno = EINVAL;

		return false;
	}
}

static bool
uc_fs_resolve_group(uc_value_t *v, gid_t *gid)
{
	struct group *gr = NULL;
	int64_t n;
	char *s;

	*gid = (gid_t)-1;

	switch (ucv_type(v)) {
	case UC_INTEGER:
		n = ucv_int64_get(v);

		if (n < -1) {
			errno = ERANGE;

			return false;
		}

		*gid = (gid_t)n;

		return true;

	case UC_STRING:
		s = ucv_string_get(v);
		gr = getgrnam(s);

		if (!gr) {
			errno = ENOENT;

			return false;
		}

		*gid = gr->gr_gid;

		return true;

	case UC_NULL:
		return true;

	default:
		errno = EINVAL;

		return false;
	}
}

/**
 * Changes the owner and group of a file or directory.
 *
 * The user and group may be specified either as uid or gid number respectively,
 * or as a string containing the user or group name, in which case it is
 * resolved to the proper uid/gid first.
 *
 * If either the user or group parameter is omitted or given as `-1`,
 * it is not changed.
 *
 * Returns `true` if the ownership change was successful.
 *
 * Returns `null` if an error occurred or if a user/group name cannot be
 * resolved to a uid/gid value.
 *
 * @function module:fs#chown
 *
 * @param {string} path
 * The path to the file or directory.
 *
 * @param {number|string} [uid=-1]
 * The new owner's user ID. When given as number, it is used as-is, when given
 * as string, the user name is resolved to the corresponding uid first.
 *
 * @param {number|string} [gid=-1]
 * The new group's ID. When given as number, it is used as-is, when given as
 * string, the group name is resolved to the corresponding gid first.
 *
 * @returns {boolean|null}
 *
 * @example
 * // Change the owner of a file
 * chown('path/to/file', 1000);
 *
 * // Change the group of a directory
 * chown('/htdocs/', null, 'www-data');
 */
static uc_value_t *
uc_fs_chown(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *user = uc_fn_arg(1);
	uc_value_t *group = uc_fn_arg(2);
	uid_t uid;
	gid_t gid;

	if (ucv_type(path) != UC_STRING)
	    err_return(EINVAL);

	if (!uc_fs_resolve_user(user, &uid) ||
	    !uc_fs_resolve_group(group, &gid))
		err_return(errno);

	if (chown(ucv_string_get(path), uid, gid) == -1)
		err_return(errno);

	return ucv_boolean_new(true);
}

/**
 * Renames or moves a file or directory.
 *
 * Returns `true` if the rename operation was successful.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs#rename
 *
 * @param {string} oldPath
 * The current path of the file or directory.
 *
 * @param {string} newPath
 * The new path of the file or directory.
 *
 * @returns {boolean|null}
 *
 * @example
 * // Rename a file
 * rename('old-name.txt', 'new-name.txt');
 */
static uc_value_t *
uc_fs_rename(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *oldpath = uc_fn_arg(0);
	uc_value_t *newpath = uc_fn_arg(1);

	if (ucv_type(oldpath) != UC_STRING ||
	    ucv_type(newpath) != UC_STRING)
		err_return(EINVAL);

	if (rename(ucv_string_get(oldpath), ucv_string_get(newpath)))
		err_return(errno);

	return ucv_boolean_new(true);
}

static uc_value_t *
uc_fs_glob(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *pat, *arr;
	glob_t gl = { 0 };
	size_t i;

	for (i = 0; i < nargs; i++) {
		pat = uc_fn_arg(i);

		if (ucv_type(pat) != UC_STRING) {
			globfree(&gl);
			err_return(EINVAL);
		}

		glob(ucv_string_get(pat), i ? GLOB_APPEND : 0, NULL, &gl);
	}

	arr = ucv_array_new(vm);

	for (i = 0; i < gl.gl_pathc; i++)
		ucv_array_push(arr, ucv_string_new(gl.gl_pathv[i]));

	globfree(&gl);

	return arr;
}

/**
 * Retrieves the directory name of a path.
 *
 * Returns the directory name component of the specified path.
 *
 * Returns `null` if the path argument is not a string.
 *
 * @function module:fs#dirname
 *
 * @param {string} path
 * The path to extract the directory name from.
 *
 * @returns {string|null}
 *
 * @example
 * // Get the directory name of a path
 * const directoryName = dirname('/path/to/file.txt');
 */
static uc_value_t *
uc_fs_dirname(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	size_t i;
	char *s;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	i = ucv_string_length(path);
	s = ucv_string_get(path);

	if (i == 0)
		return ucv_string_new(".");

	for (i--; s[i] == '/'; i--)
		if (i == 0)
			return ucv_string_new("/");

	for (; s[i] != '/'; i--)
		if (i == 0)
			return ucv_string_new(".");

	for (; s[i] == '/'; i--)
		if (i == 0)
			return ucv_string_new("/");

	return ucv_string_new_length(s, i + 1);
}

/**
 * Retrieves the base name of a path.
 *
 * Returns the base name component of the specified path.
 *
 * Returns `null` if the path argument is not a string.
 *
 * @function module:fs#basename
 *
 * @param {string} path
 * The path to extract the base name from.
 *
 * @returns {string|null}
 *
 * @example
 * // Get the base name of a path
 * const baseName = basename('/path/to/file.txt');
 */
static uc_value_t *
uc_fs_basename(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	size_t i, len, skip;
	char *s;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	len = ucv_string_length(path);
	s = ucv_string_get(path);

	if (len == 0)
		return ucv_string_new(".");

	for (i = len - 1, skip = 0; i > 0 && s[i] == '/'; i--, skip++)
		;

	for (; i > 0 && s[i - 1] != '/'; i--)
		;

	return ucv_string_new_length(s + i, len - i - skip);
}

static int
uc_fs_lsdir_sort_fn(const void *k1, const void *k2)
{
	uc_value_t * const *v1 = k1;
	uc_value_t * const *v2 = k2;

	return strcmp(ucv_string_get(*v1), ucv_string_get(*v2));
}

/**
 * Lists the content of a directory.
 *
 * Returns a sorted array of the names of files and directories in the specified
 * directory.
 *
 * Returns `null` if an error occurred, e.g. if the specified directory cannot
 * be opened.
 *
 * @function module:fs#lsdir
 *
 * @param {string} path
 * The path to the directory.
 *
 * @returns {string[]|null}
 *
 * @example
 * // List the content of a directory
 * const fileList = lsdir('/path/to/directory');
 */
static uc_value_t *
uc_fs_lsdir(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *pat = uc_fn_arg(1);
	uc_value_t *res = NULL;
	uc_regexp_t *reg;
	struct dirent *e;
	DIR *d;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	switch (ucv_type(pat)) {
	case UC_NULL:
	case UC_STRING:
	case UC_REGEXP:
		break;

	default:
		err_return(EINVAL);
	}

	d = opendir(ucv_string_get(path));

	if (!d)
		err_return(errno);

	res = ucv_array_new(vm);

	while ((e = readdir(d)) != NULL) {
		if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
			continue;

		if (ucv_type(pat) == UC_REGEXP) {
			reg = (uc_regexp_t *)pat;

			if (regexec(&reg->regexp, e->d_name, 0, NULL, 0) == REG_NOMATCH)
				continue;
		}
		else if (ucv_type(pat) == UC_STRING) {
			if (fnmatch(ucv_string_get(pat), e->d_name, 0) == FNM_NOMATCH)
				continue;
		}

		ucv_array_push(res, ucv_string_new(e->d_name));
	}

	closedir(d);

	ucv_array_sort(res, uc_fs_lsdir_sort_fn);

	return res;
}

/**
 * Creates a unique, ephemeral temporary file.
 *
 * Creates a new temporary file, opens it in read and write mode, unlinks it and
 * returns a file handle object referring to the yet open but deleted file.
 *
 * Upon closing the handle, the associated file will automatically vanish from
 * the system.
 *
 * The optional path template argument may be used to override the path and name
 * chosen for the temporary file. If the path template contains no path element,
 * `/tmp/` is prepended, if it does not end with `XXXXXX`, then  * `.XXXXXX` is
 * appended to it. The `XXXXXX` sequence is replaced with a random value
 * ensuring uniqueness of the temporary file name.
 *
 * Returns a file handle object referring to the ephemeral file on success.
 *
 * Returns `null` if an error occurred, e.g. on insufficient permissions or
 * inaccessible directory.
 *
 * @function module:fs#mkstemp
 *
 * @param {string} [template="/tmp/XXXXXX"]
 * The path template to use when forming the temporary file name.
 *
 * @returns {module:fs.file|null}
 *
 * @example
 * // Create a unique temporary file in the current working directory
 * const tempFile = mkstemp('./data-XXXXXX');
 */
static uc_value_t *
uc_fs_mkstemp(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *template = uc_fn_arg(0);
	bool ends_with_template = false;
	char *path, *t;
	FILE *fp;
	size_t l;
	int fd;

	if (template && ucv_type(template) != UC_STRING)
		err_return(EINVAL);

	t = ucv_string_get(template);
	l = ucv_string_length(template);

	ends_with_template = (l >= 6 && strcmp(&t[l - 6], "XXXXXX") == 0);

	if (t && strchr(t, '/')) {
		if (ends_with_template)
			xasprintf(&path, "%s", t);
		else
			xasprintf(&path, "%s.XXXXXX", t);
	}
	else if (t) {
		if (ends_with_template)
			xasprintf(&path, "/tmp/%s", t);
		else
			xasprintf(&path, "/tmp/%s.XXXXXX", t);
	}
	else {
		xasprintf(&path, "/tmp/XXXXXX");
	}

	do {
		fd = mkstemp(path);
	}
	while (fd == -1 && errno == EINTR);

	if (fd == -1) {
		free(path);
		err_return(errno);
	}

	unlink(path);
	free(path);

	fp = fdopen(fd, "r+");

	if (!fp) {
		close(fd);
		err_return(errno);
	}

	return uc_resource_new(file_type, fp);
}

/**
 * Checks the accessibility of a file or directory.
 *
 * The optional modes argument specifies the access modes which should be
 * checked. A file is only considered accessible if all access modes specified
 * in the modes argument are possible.
 *
 * The following modes are recognized:
 *
 * | Mode | Description                           |
 * |------|---------------------------------------|
 * | "r"  | Tests whether the file is readable.   |
 * | "w"  | Tests whether the file is writable.   |
 * | "x"  | Tests whether the file is executable. |
 * | "f"  | Tests whether the file exists.        |
 *
 * Returns `true` if the given path is accessible or `false` when it is not.
 *
 * Returns `null` if an error occurred, e.g. due to inaccessible intermediate
 * path components, invalid path arguments etc.
 *
 * @function module:fs#access
 *
 * @param {string} path
 * The path to the file or directory.
 *
 * @param {number} [mode="f"]
 * Optional access mode.
 *
 * @returns {boolean|null}
 *
 * @example
 * // Check file read and write accessibility
 * const isAccessible = access('path/to/file', 'rw');
 *
 * // Check execute permissions
 * const mayExecute = access('/usr/bin/example', 'x');
 */
static uc_value_t *
uc_fs_access(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *test = uc_fn_arg(1);
	int mode = F_OK;
	char *p;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	if (test && ucv_type(test) != UC_STRING)
		err_return(EINVAL);

	for (p = ucv_string_get(test); p && *p; p++) {
		switch (*p) {
		case 'r':
			mode |= R_OK;
			break;

		case 'w':
			mode |= W_OK;
			break;

		case 'x':
			mode |= X_OK;
			break;

		case 'f':
			mode |= F_OK;
			break;

		default:
			err_return(EINVAL);
		}
	}

	if (access(ucv_string_get(path), mode) == -1)
		err_return(errno);

	return ucv_boolean_new(true);
}

/**
 * Reads the content of a file, optionally limited to the given amount of bytes.
 *
 * Returns a string containing the file contents.
 *
 * Returns `null` if an error occurred, e.g. due to insufficient permissions.
 *
 * @function module:fs#readfile
 *
 * @param {string} path
 * The path to the file.
 *
 * @param {number} [limit]
 * Number of bytes to limit the result to. When omitted, the entire content is
 * returned.
 *
 * @returns {string|null}
 *
 * @example
 * // Read first 100 bytes of content
 * const content = readfile('path/to/file', 100);
 *
 * // Read entire file content
 * const content = readfile('path/to/file');
 */
static uc_value_t *
uc_fs_readfile(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *size = uc_fn_arg(1);
	uc_value_t *res = NULL;
	uc_stringbuf_t *buf;
	ssize_t limit = -1;
	size_t rlen, blen;
	FILE *fp;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	if (size) {
		if (ucv_type(size) != UC_INTEGER)
			err_return(EINVAL);

		limit = ucv_int64_get(size);
	}

	fp = fopen(ucv_string_get(path), "r");

	if (!fp)
		err_return(errno);

	buf = ucv_stringbuf_new();

	if (limit > -1 && limit < BUFSIZ)
		setvbuf(fp, NULL, _IONBF, 0);

	while (limit != 0) {
		blen = 1024;

		if (limit > 0 && blen > (size_t)limit)
			blen = (size_t)limit;

		printbuf_memset(buf, printbuf_length(buf) + blen - 1, 0, 1);

		buf->bpos -= blen;
		rlen = fread(buf->buf + buf->bpos, 1, blen, fp);
		buf->bpos += rlen;

		if (rlen < blen)
			break;

		if (limit > 0)
			limit -= rlen;
	}

	if (ferror(fp)) {
		fclose(fp);
		printbuf_free(buf);
		err_return(errno);
	}

	fclose(fp);

	/* add sentinel null byte but don't count it towards the string length */
	printbuf_memappend_fast(buf, "\0", 1);
	res = ucv_stringbuf_finish(buf);
	((uc_string_t *)res)->length--;

	return res;
}

/**
 * Writes the given data to a file, optionally truncated to the given amount
 * of bytes.
 *
 * In case the given data is not a string, it is converted to a string before
 * being written into the file. String values are written as-is, integer and
 * double values are written in decimal notation, boolean values are written as
 * `true` or `false` while arrays and objects are converted to their JSON
 * representation before being written into the file. The `null` value is
 * represented by an empty string so `writefile(…, null)` would write an empty
 * file. Resource values are written in the form `<type address>`, e.g.
 * `<fs.file 0x7f60f0981760>`.
 *
 * If resource, array or object values contain a `tostring()` function in their
 * prototypes, then this function is invoked to obtain an alternative string
 * representation of the value.
 *
 * If a file already exists at the given path, it is truncated. If no file
 * exists, it is created with default permissions 0o666 masked by the currently
 * effective umask.
 *
 * Returns the number of bytes written.
 *
 * Returns `null` if an error occurred, e.g. due to insufficient permissions.
 *
 * @function module:fs#writefile
 *
 * @param {string} path
 * The path to the file.
 *
 * @param {*} data
 * The data to be written.
 *
 * @param {number} [limit]
 * Truncates the amount of data to be written to the specified amount of bytes.
 * When omitted, the entire content is written.
 *
 * @returns {number|null}
 *
 * @example
 * // Write string to a file
 * const bytesWritten = writefile('path/to/file', 'Hello, World!');
 *
 * // Write object as JSON to a file and limit to 1024 bytes at most
 * const obj = { foo: "Hello world", bar: true, baz: 123 };
 * const bytesWritten = writefile('debug.txt', obj, 1024);
 */
static uc_value_t *
uc_fs_writefile(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0);
	uc_value_t *data = uc_fn_arg(1);
	uc_value_t *size = uc_fn_arg(2);
	uc_stringbuf_t *buf = NULL;
	ssize_t limit = -1;
	size_t wlen = 0;
	int err = 0;
	FILE *fp;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	if (size) {
		if (ucv_type(size) != UC_INTEGER)
			err_return(EINVAL);

		limit = ucv_int64_get(size);
	}

	fp = fopen(ucv_string_get(path), "w");

	if (!fp)
		err_return(errno);

	if (data && ucv_type(data) != UC_STRING) {
		buf = xprintbuf_new();
		ucv_to_stringbuf_formatted(vm, buf, data, 0, '\0', 0);

		if (limit < 0 || limit > printbuf_length(buf))
			limit = printbuf_length(buf);

		wlen = fwrite(buf->buf, 1, limit, fp);

		if (wlen < (size_t)limit)
			err = errno;

		printbuf_free(buf);
	}
	else if (data) {
		if (limit < 0 || (size_t)limit > ucv_string_length(data))
			limit = ucv_string_length(data);

		wlen = fwrite(ucv_string_get(data), 1, limit, fp);

		if (wlen < (size_t)limit)
			err = errno;
	}

	fclose(fp);

	if (err)
		err_return(err);

	return ucv_uint64_new(wlen);
}

/**
 * Resolves the absolute path of a file or directory.
 *
 * Returns a string containing the resolved path.
 *
 * Returns `null` if an error occurred, e.g. due to insufficient permissions.
 *
 * @function module:fs#realpath
 *
 * @param {string} path
 * The path to the file or directory.
 *
 * @returns {string|null}
 *
 * @example
 * // Resolve the absolute path of a file
 * const absolutePath = realpath('path/to/file', 'utf8');
 */
static uc_value_t *
uc_fs_realpath(uc_vm_t *vm, size_t nargs)
{
	uc_value_t *path = uc_fn_arg(0), *rv;
	char *resolved;

	if (ucv_type(path) != UC_STRING)
		err_return(EINVAL);

	resolved = realpath(ucv_string_get(path), NULL);

	if (!resolved)
		err_return(errno);

	rv = ucv_string_new(resolved);

	free(resolved);

	return rv;
}

/**
 * Creates a pipe and returns file handle objects associated with the read- and
 * write end of the pipe respectively.
 *
 * Returns a two element array containing both a file handle object open in read
 * mode referring to the read end of the pipe and a file handle object open in
 * write mode referring to the write end of the pipe.
 *
 * Returns `null` if an error occurred.
 *
 * @function module:fs#pipe
 *
 * @returns {module:fs.file[]|null}
 *
 * @example
 * // Create a pipe
 * const pipeHandles = pipe();
 * pipeHandles[1].write("Hello world\n");
 * print(pipeHandles[0].read("line"));
 */
static uc_value_t *
uc_fs_pipe(uc_vm_t *vm, size_t nargs)
{
	int pfds[2], err;
	FILE *rfp, *wfp;
	uc_value_t *rv;

	if (pipe(pfds) == -1)
		err_return(errno);

	rfp = fdopen(pfds[0], "r");

	if (!rfp) {
		err = errno;
		close(pfds[0]);
		close(pfds[1]);
		err_return(err);
	}

	wfp = fdopen(pfds[1], "w");

	if (!wfp) {
		err = errno;
		fclose(rfp);
		close(pfds[1]);
		err_return(err);
	}

	rv = ucv_array_new_length(vm, 2);

	ucv_array_push(rv, uc_resource_new(file_type, rfp));
	ucv_array_push(rv, uc_resource_new(file_type, wfp));

	return rv;
}


static const uc_function_list_t proc_fns[] = {
	{ "read",		uc_fs_pread },
	{ "write",		uc_fs_pwrite },
	{ "close",		uc_fs_pclose },
	{ "flush",		uc_fs_pflush },
	{ "fileno",		uc_fs_pfileno },
	{ "error",		uc_fs_error },
};

static const uc_function_list_t file_fns[] = {
	{ "read",		uc_fs_read },
	{ "write",		uc_fs_write },
	{ "seek",		uc_fs_seek },
	{ "tell",		uc_fs_tell },
	{ "close",		uc_fs_close },
	{ "flush",		uc_fs_flush },
	{ "fileno",		uc_fs_fileno },
	{ "error",		uc_fs_error },
	{ "isatty",		uc_fs_isatty },
};

static const uc_function_list_t dir_fns[] = {
	{ "read",		uc_fs_readdir },
	{ "seek",		uc_fs_seekdir },
	{ "tell",		uc_fs_telldir },
	{ "close",		uc_fs_closedir },
	{ "error",		uc_fs_error },
};

static const uc_function_list_t global_fns[] = {
	{ "error",		uc_fs_error },
	{ "open",		uc_fs_open },
	{ "fdopen",		uc_fs_fdopen },
	{ "opendir",	uc_fs_opendir },
	{ "popen",		uc_fs_popen },
	{ "readlink",	uc_fs_readlink },
	{ "stat",		uc_fs_stat },
	{ "lstat",		uc_fs_lstat },
	{ "mkdir",		uc_fs_mkdir },
	{ "rmdir",		uc_fs_rmdir },
	{ "symlink",	uc_fs_symlink },
	{ "unlink",		uc_fs_unlink },
	{ "getcwd",		uc_fs_getcwd },
	{ "chdir",		uc_fs_chdir },
	{ "chmod",		uc_fs_chmod },
	{ "chown",		uc_fs_chown },
	{ "rename",		uc_fs_rename },
	{ "glob",		uc_fs_glob },
	{ "dirname",	uc_fs_dirname },
	{ "basename",	uc_fs_basename },
	{ "lsdir",		uc_fs_lsdir },
	{ "mkstemp",	uc_fs_mkstemp },
	{ "access",		uc_fs_access },
	{ "readfile",	uc_fs_readfile },
	{ "writefile",	uc_fs_writefile },
	{ "realpath",	uc_fs_realpath },
	{ "pipe",		uc_fs_pipe },
};


static void close_proc(void *ud)
{
	FILE *fp = ud;

	if (fp)
		pclose(fp);
}

static void close_file(void *ud)
{
	FILE *fp = ud;
	int n;

	n = fp ? fileno(fp) : -1;

	if (n > 2)
		fclose(fp);
}

static void close_dir(void *ud)
{
	DIR *dp = ud;

	if (dp)
		closedir(dp);
}

void uc_module_init(uc_vm_t *vm, uc_value_t *scope)
{
	uc_function_list_register(scope, global_fns);

	proc_type = uc_type_declare(vm, "fs.proc", proc_fns, close_proc);
	file_type = uc_type_declare(vm, "fs.file", file_fns, close_file);
	dir_type = uc_type_declare(vm, "fs.dir", dir_fns, close_dir);

	ucv_object_add(scope, "stdin", uc_resource_new(file_type, stdin));
	ucv_object_add(scope, "stdout", uc_resource_new(file_type, stdout));
	ucv_object_add(scope, "stderr", uc_resource_new(file_type, stderr));
}