summaryrefslogtreecommitdiff
path: root/luxio.c
blob: e5b370c445156a2837759496ce66ef4656f9d7ad (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
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
/* Light Unix I/O for Lua
 * Copyright 2012 Rob Kendrick <rjek+luxio@rjek.com>
 *
 * Copyright 2012 Daniel Silverstone <dsilvers@digital-scurf.org>
 *
 * Distributed under the same terms as Lua itself (MIT).
 */

/***
Low-level bindings to POSIX functionality.

Luxio provides a very light-weight binding to many of the standard POSIX
and common Unix library calls.  Where possible, calls are very raw.  In
cases such as the `dirent` family, BSD sockets, the `getaddrinfo` family,
and some other cases, they interfaces are somewhat "cooked" either to make
them more efficient or even possible.

For the simple raw uncooked functions, all we present here is an example
of the C prototype, and possible styles for use in Lua.  You'll have to
go looking in man pages for actual information on their use.

Not all systems will provide all the functions described here.

@module luxio
*/
 
#define LUXIO_RELEASE 13 /* clients use to check for features/bug fixes */
#define LUXIO_ABI 0 /* clients use to check the ABI of calls is same */
#define LUXIO_COPYRIGHT "Copyright 2013 Rob Kendrick <rjek+luxio@rjek.com>\n" \
	"Copyright 2014 Daniel Silverstone <dsilvers@digital-scurf.org>"

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <lua.h>
#include <lauxlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <sys/utsname.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <net/if.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/select.h>
#include <unistd.h>
#include <dirent.h>
#include <time.h>
#include <limits.h>
#include <signal.h>
#include <syslog.h>
#include <iconv.h>

#if (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 24)
/* readdir is deprecated as of glibc 2.24, use readdir instead */
#define LUXIO_USE_READDIR
#endif

#ifdef HAVE_SENDFILE
# include <sys/sendfile.h>
#endif

#if (LUA_VERSION_NUM == 501)
# define lua_rawlen(L, idx) lua_objlen((L), (idx))

/* Lua 5.1 doesn't have this :<
 * so we steal it from lua 5.3, thanks #lua :>
 */
void *luaL_testudata (lua_State *L, int i, const char *tname) {
  void *p = lua_touserdata(L, i);
  luaL_checkstack(L, 2, "not enough stack slots");
  if (p == NULL || !lua_getmetatable(L, i))
    return NULL;
  else {
    int res = 0;
    luaL_getmetatable(L, tname);
    res = lua_rawequal(L, -1, -2);
    lua_pop(L, 2);
    if (!res)
      p = NULL;
  }
  return p;
}
#endif

#define INVALID_MODE ((mode_t) -1)

/* Internal helper functions *************************************************/

#define LUXIO_MIN_PATHSIZE 4096

static int safe_pathconf(const char *path, int conf)
{
	int pc = pathconf(path, conf);

	return (pc < LUXIO_MIN_PATHSIZE) ? LUXIO_MIN_PATHSIZE : pc;
}

static int safe_fpathconf(int fd, int conf)
{
	int pc = fpathconf(fd, conf);

	return (pc < LUXIO_MIN_PATHSIZE) ? LUXIO_MIN_PATHSIZE : pc;
}

#undef LUXIO_MIN_PATHSIZE

/* External interface to Lua *************************************************/

int luaopen_luxio(lua_State *L);

/*** Process creation and execution.
Functions to do with the creation of new processes and the execution of other
programs.
@section process
*/

/*** Fork a child process. Return 0 in the child and the child's process id
in the parent.

@treturn number return value
@treturn errno errno
@function fork
*/
static int
luxio_fork(lua_State *L) /* 3.1.1 */
{
	lua_pushinteger(L, fork());
	lua_pushinteger(L, errno);

	return 2;
}

static int
luxio__exec(lua_State *L, bool usep)
{
	const char *path = luaL_checkstring(L, 1);
	int params = lua_gettop(L) - 1;
	char **args;
	int c, ret;

	/* we probably at least need them to fill in arg[0] ... */
	luaL_checkstring(L, 2);

	args = calloc(params + 1, sizeof(*args));

	for (c = 0; c < params; c++) {
		/* gah!  constness */
		args[c] = (char *)luaL_checkstring(L, c + 2);
	}

	args[c] = NULL;

	if (usep) {
		ret = execvp(path, args);
	} else {
		ret = execv(path, args);
	}

	/* if we got here, there's an error. */
	free(args);
	lua_pushinteger(L, ret);
	lua_pushinteger(L, errno);

	return 2;
}

/*** Execute a new program, replacing the current process.
This function will not return when it succeeds, because
the calling program is replaced by the new program.
This function will only return if an error has occurred,
the return value will be -1 and errno will be set to indicate the error.

This function is implemented with execv().

@tparam string path absolute path to executable
@tparam string ... parameters to pass to executatable
@treturn number return value
@treturn errno errno
@function exec
*/
static int
luxio_exec(lua_State *L) /* 3.1.2 */
{
	return luxio__exec(L, false);
}

/*** Execute a new program, replacing the current process.
This function will not return when it succeeds, because
the calling program is replaced by the new program.
This function will only return if an error has occurred,
the return value will be -1 and errno will be set to indicate the error.

The difference between this function and exec, is that
this function will search for the name of the executable
in the colon-separated list of directories specified
in the PATH environment variable.

This function is implemented with execp()

@tparam string path name of executable
@tparam string ... parameters to pass to executatable
@treturn number return value
@treturn number errno
@function execp
*/
static int
luxio_execp(lua_State *L) /* 3.1.2 */
{
	return luxio__exec(L, true);
}

/* TODO: pthread_atfork() 3.1.3 */

/*** Process termination.
Functions to do with the termination of processes.
@section termination
*/

/*** Wait for a process to change state.

This function obtains status information for one of the caller's
child processes. `waitpid()` will suspend execution of the calling thread
until status information becomes available
(unless `luxio.WNOHANG` is specified). If status information is available
prior to the call to `waitpid()` then the function shall return immediately.

The pid argument specifies a set of child processes for which the status
is requested. The `waitpid()` function shall only return the status of
a child process from the following set:

- If `pid` is -1, status is requested for any child process.
- If `pid` is greater than 0, it specifies the process of a single
  process for which status is requested.
- If `pid` is 0, status is requested for any child process whose process
  group ID is equal to that of the calling process.
- If `pid` is less than -1, status is requested for any child process
  whose process group ID is equal to absolute value of `pid`.

The options argument is constructed from the bitwise OR of zero
or more of the following flags:

- `luxio.WCONTINUED`: report the status of any child process whose status
  has not been reported since it continued from a job control stop
- `luxio.WNOHANG`: return immediately, do not wait for status to become available
- `luxio.WUNTRACED`: return the status of any child process whose status
  has not been reported since it was stopped

@tparam number pid process id to wait on
@tparam number options options for call
@treturn number return value
@treturn number|errno status code or errno if error
@function waitpid

*/
static int
luxio_waitpid(lua_State *L) /* 3.2.1 */
{
	pid_t pid = luaL_checkinteger(L, 1);
	int options = luaL_checkinteger(L, 2);
	int status;
	pid_t proc;

	proc = waitpid(pid, &status, options);
	lua_pushinteger(L, proc);
	if (proc == -1) {
		lua_pushinteger(L, errno);
	} else {
		lua_pushinteger(L, status);
	}

	return 2;
}

#define WAITPID_STATUS(x) static int luxio_##x(lua_State *L) { \
		int status = luaL_checkinteger(L, 1);	      \
		lua_pushinteger(L, x(status));		      \
		return 1;				      \
	}

/*** Check status macro for WIFEXITED.

Returns true for status of a child process that terminated normally.

@tparam number status code from `waitpid`()
@treturn number true or false
@function WIFEXITED
*/
WAITPID_STATUS(WIFEXITED)

/**% WEXITSTATUS
 *  retval = WEXITSTATUS(status);
 *  retval = WIFEXITED(status)
 */
/*** Obtain exit status code from child.

If the value of `WIFEXITED(status)` is true, return the exit code
of the child process.

@tparam number status code from `waitpid`()
@treturn number exit status code
@function WEXITSTATUS
*/
WAITPID_STATUS(WEXITSTATUS)

/*** Check status macro for WIFSIGNALED.

Returns true for status of a child process that was terminated
by an uncaught signal.

@tparam number status code from `waitpid`()
@treturn number true or false
@function WIFSIGNALLED
*/
WAITPID_STATUS(WIFSIGNALED)

/*** Obtain signal used to kill child.

If the value of `WIFSIGNALED(status)` is true, return the number
of the signal that terminated the child process.

@tparam number status code from `waitpid`()
@treturn number signal number
@function WTERMSIG
*/
WAITPID_STATUS(WTERMSIG)


/**% WCOREDUMP
 *  retval = WCOREDUMP(status);
 *  retval = WCOREDUMP(status)
 */
/*** Check for core dump.

  Returns true if the child process produced a core dump.
  This should only be used if `WIFSIGNALED(status)` returns true.

__WCOREDUMP is not specified in POSIX.1-2001 and is not available
  on some platforms, e.g. AIX and Solaris.__

@tparam number status code from `waitpid`()
@treturn number true or false
@function WCOREDUMP
*/
#ifdef WCOREDUMP
WAITPID_STATUS(WCOREDUMP)
#endif

/*** Check whether process was stopped by delivery of a signal.

Returns true if the child process was stopped by delivery of a signal.
This can only return true if `waitpid()` was called with the `luxio.WUNTRACED`
option.

@tparam number status code from `waitpid`()
@treturn number true or false
@function WIFSTOPPED
*/
WAITPID_STATUS(WIFSTOPPED)

/*** Obtain signal number used to stop child.

If the value of `WIFSTOPPED(status)` is true, return the number of the signal
that caused the child to stop.

@tparam number status code from `waitpid`()
@treturn number signal number
@function WSTOPSIG
*/
WAITPID_STATUS(WSTOPSIG)

#ifdef WIFCONTINUED
/*** Check status for WIFCONTINUED.

Returns true if child process was resumed by SIGCONT.

_(since Linux 2.6.10)._

@tparam number status code from `waitpid`()
@treturn number true or false
@function WIFCONTINUED
*/
WAITPID_STATUS(WIFCONTINUED)
#endif

#undef WAITPID_STATUS

/*** Terminate calling process.  Does not return.

Terminates calling process "immediately", this differs from `exit(3)`
in that any functions registered via `atexit(3)` or `on_exit(3)` are
__not__ called when the process exits.

Any open file descriptors are closed, any children of the process are
inherited by pid 1 (init), and the process's parent is sent a `SIGCHLD` signal.

@tparam[opt=0] number exit status code.
@function _exit
*/
static int
luxio__exit(lua_State *L) /* 3.2.2 */
{
	int ret = luaL_optinteger(L, 1, 0);

	_exit(ret);

	return 0;
}

/*** Signals.  Functions related to sending signals.

All signals are defined
symbolically: `luxio.SIGKILL`, `luxio.SIGINT` etc,
for a complete list of signals consult `signal(2)` or `signal(7)`
man pages.

@section signals
*/

/**% kill
 *  retval = kill(pid, sig);
 *  retval, errno = kill(pid, sig)
 */
/*** Send signal to a process or a group of processes.

This function sends a signal to a process or a group of processes
based on the value of the `pid` parameter. The signal sent is specified
by the `signal` parameter.

If `pid` is positive, then `signal` is sent to the process with the ID
specified by `pid`.

If `pid` equals 0, then `signal` is sent to all processes
whose process group ID is equal to the process group ID of the caller,
and for which the caller has permission to send a signal
(excluding an unspecified set of system processes).

If `pid` equals -1, then `signal` is sent to every process for which the calling
process has permission to send signals (excluding an unspecified set of
system processes).

If `pid` is less than -1, then `signal` is sent to every process
(excluding an unspecified set of system processes) whose process
group ID is equal to the absolute value of `pid`.

If `signal` is 0 then no signal is sent, but error checking is still performed.
This may be used to check for the existence of a process ID or process group ID.

Return 0 on success (at least one signal was sent).
On error -1 is returned and errno will be set.

@tparam number pid signal destination
@tparam number signal signal to send
@treturn number return value
@treturn errno errno
@function kill
*/
static int
luxio_kill(lua_State *L) /* 3.3.2 */
{
	pid_t pid = luaL_checkinteger(L, 1);
	int sig = luaL_checkinteger(L, 2);

	lua_pushinteger(L, kill(pid, sig));
	lua_pushinteger(L, errno);

	return 2;
}

/* Signals are going to be almost impossible to do nicely and safely. */

#define LUXIO_SIGNALSET_METATABLE "luxio.signalset"

typedef struct {
	sigset_t set;
} luxio_signalset;

static int
luxio_signalset_tostring(lua_State *L)
{
	luxio_signalset *s = luaL_checkudata(L, 1, LUXIO_SIGNALSET_METATABLE);
	char buf[1024];

	snprintf(buf, sizeof(buf), "sigset: %p", &s->set);
	lua_pushstring(L, buf);

	return 1;
}

static void
luxio__bless_signalset(lua_State *L)
{
	int create = luaL_newmetatable(L, LUXIO_SIGNALSET_METATABLE);

	if (create != 0) {
		lua_pushcfunction(L, luxio_signalset_tostring);
		lua_setfield(L, -2, "__tostring");
	}

	lua_setmetatable(L, -2);
}

/*** Create a new signal set
@treturn A new signal set
*/
static int
luxio_newsigset(lua_State *L)
{
	luxio_signalset *s = lua_newuserdata(L, sizeof(*s));

	luxio__bless_signalset(L);

	return 1;
}

/*** Initialise a signal set to be empty.

Return 0 on success, or -1 on error with errno set appropriately.

@tparam sigset sigset signal set
@tparam number signo signal
@treturn number return value
@treturn errno errno
@function sigemptyset
*/
static int
luxio_sigemptyset(lua_State *L)
{
	luxio_signalset *s = luaL_checkudata(L, 1, LUXIO_SIGNALSET_METATABLE);
	lua_pushinteger(L, sigemptyset(&s->set));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Initialise a signal set to contain all signals.

Return 0 on success, or -1 on error with errno set appropriately.

@tparam sigset sigset signal set
@tparam number signo signal
@treturn number return value
@treturn errno errno
@function sigfillset
*/
static int
luxio_sigfillset(lua_State *L)
{
	luxio_signalset *s = luaL_checkudata(L, 1, LUXIO_SIGNALSET_METATABLE);
	lua_pushinteger(L, sigfillset(&s->set));
	lua_pushinteger(L, errno);

	return 2;
}

#define LUXIO__SIGSET_OPERATION(L, op) do { \
	luxio_signalset *s = luaL_checkudata(L, 1, LUXIO_SIGNALSET_METATABLE); \
	int signo = luaL_checkinteger(L, 2); \
	lua_pushinteger(L, op(&s->set, signo)); \
	lua_pushinteger(L, errno); \
	return 2; \
} while (0)

/*** Add a signal to a signal set.

Return 0 on success, or -1 on error with errno set appropriately.

@tparam sigset sigset signal set
@tparam number signo signal
@treturn number return value
@treturn errno errno
@function sigaddset
*/
static int
luxio_sigaddset(lua_State *L)
{
	LUXIO__SIGSET_OPERATION(L, sigaddset);
}

/*** Remove a signal from a signal set.

Return 0 on success, or -1 on error with errno set appropriately.

@tparam sigset sigset signal set
@tparam number signo signal
@treturn number return value
@treturn errno errno
@function sigdelset
*/
static int
luxio_sigdelset(lua_State *L)
{
	LUXIO__SIGSET_OPERATION(L, sigdelset);
}

/*** Check whether a signal set contains a given signal.

Return 1 if signal is a member of the set, or 0 if the signal is
not a member of the set. A return value of -1 indicates that an error
occurred and errno will be set accordingly.

@tparam sigset set
@tparam number signal
@treturn number return value
@treturn errno errno
@function sigismember
*/
static int luxio_sigismember(lua_State *L)
{
	LUXIO__SIGSET_OPERATION(L, sigismember);
}

/* NSIG is not in POSIX, it's 64 on Linux and 33 on OpenBSD
 * we define a value much larger than either to be on the safe side */
#define LUXIO_NSIG 512

struct luxio_signal_handler {
    lua_State *state;
    int handler_fn;
};

static struct {
	lua_Hook orighook;
	int orighookmask;
	int orighookcount;
	sigset_t origset;
	int signo;
	bool isinfo;
	siginfo_t info;
	struct luxio_signal_handler handlers[LUXIO_NSIG];
	bool sigaction;
} luxio__signal_ctx;

static void luxio__push_siginfo_table(lua_State *L, const siginfo_t *info)
{
	lua_newtable(L);

	lua_pushinteger(L, info->si_signo);
	lua_setfield(L, -2, "si_signo");

	lua_pushinteger(L, info->si_code);
	lua_setfield(L, -2, "si_code");

	lua_pushinteger(L, info->si_errno);
	lua_setfield(L, -2, "si_errno");

	lua_pushinteger(L, info->si_pid);
	lua_setfield(L, -2, "si_pid");

	lua_pushinteger(L, info->si_uid);
	lua_setfield(L, -2, "si_uid");

	lua_pushinteger(L, info->si_utime);
	lua_setfield(L, -2, "si_utime");

	lua_pushinteger(L, info->si_stime);
	lua_setfield(L, -2, "si_stime");

	lua_pushinteger(L, (lua_Integer) info->si_addr);
	lua_setfield(L, -2, "si_addr");

	lua_pushinteger(L, info->si_status);
	lua_setfield(L, -2, "si_status");

#ifndef __FreeBSD__
	lua_pushinteger(L, info->si_utime);
	lua_setfield(L, -2, "si_utime");

	lua_pushinteger(L, info->si_stime);
	lua_setfield(L, -2, "si_stime");
#endif

#ifdef __linux__
	lua_pushinteger(L, info->si_band);
	lua_setfield(L, -2, "si_band");
#endif
}

static void luxio__sigaction_hook(lua_State *L, lua_Debug *ar)
{
	int nargs = 1;

	/* Push the callback onto the stack using the Lua reference we */
	/* stored in the registry */
	lua_rawgeti(L, LUA_REGISTRYINDEX,
		luxio__signal_ctx.handlers[luxio__signal_ctx.signo].handler_fn);
	lua_pushinteger(L, luxio__signal_ctx.signo);

	if (luxio__signal_ctx.sigaction) {
		nargs++;

		if (luxio__signal_ctx.isinfo) {
			luxio__push_siginfo_table(L, &luxio__signal_ctx.info);
		} else {
			lua_pushnil(L);
		}
	}

	lua_pcall(L, nargs, 0, 0);

	/* Restore original hook */
	lua_sethook(L, luxio__signal_ctx.orighook,
		luxio__signal_ctx.orighookmask,
		luxio__signal_ctx.orighookcount);

	/* The signal we're currently handling was blocked during signal delivery,
	 * but we also blocked everything manually in the handler,
	 * so we must now unblock this signal ourselves as well.
	 */
	sigdelset(&luxio__signal_ctx.origset, luxio__signal_ctx.signo);

	/* Restore the original signal mask */
	sigprocmask(SIG_SETMASK, &luxio__signal_ctx.origset, NULL);
}

static void luxio__sigaction_common_handler(int signo, siginfo_t *info)
{
	sigset_t set;
	lua_State *L = luxio__signal_ctx.handlers[signo].state;

	/* Block everything till we're done handling the signal on the lua side */
	sigfillset(&set);
	sigprocmask(SIG_SETMASK, &set, &luxio__signal_ctx.origset);

	luxio__signal_ctx.orighook = lua_gethook(L);
	luxio__signal_ctx.orighookmask = lua_gethookmask(L);
	luxio__signal_ctx.orighookcount = lua_gethookcount(L);
	luxio__signal_ctx.signo = signo;
	if (info != NULL) {
		luxio__signal_ctx.isinfo = true;
		luxio__signal_ctx.info = *info;
	} else {
		luxio__signal_ctx.isinfo = false;
	}

	lua_sethook(L, luxio__sigaction_hook,
		LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
}

static void luxio__sigaction_sa_handler(int signo)
{
	luxio__signal_ctx.sigaction = false;
	luxio__sigaction_common_handler(signo, NULL);
}

static void luxio__sigaction_sigaction_handler(int signo, siginfo_t *info, void *context)
{
	luxio__signal_ctx.sigaction = true;
	luxio__sigaction_common_handler(signo, info);
}

/**% sigaction
 *  retval = sigaction(sig, sa_params)
 *  retval, errno = sigaction(sig, sa_params)
 */
/*** Examine and change a signal action.

sigaction can be used to install a signal handler function. When this handler
is installed the default action for the signal, which is usually program
termination, is overriden. When a signal, such as SIGINT, is received,
the associated handler is called.

A signal handler can be deregistered by setting sa_handler to nil or SIG_DFL.

A signal can be ignored by setting sa_handler to SIG_IGN.

There may only be one handler registered per signal at any given time,
if one Lua VM attempts to register a signal that is already registered by another
VM then sigaction shall return -1 and errno shall be set to ENOSPC.

Return 0 on success, on error -1 is returned and errno will be set.
On success a table containing the currently installed signal mask and flags
is returned.

Example usage: @{sigaction.lua}

@tparam number sig signal to examine/change
@tparam sigaction-table sa_params sigaction parameters
@treturn number return value
@treturn sigaction-table|errno result table, or errno
@function sigaction
*/

/*** sigaction() table
@table sigaction-table
@field sa_handler function that will be the handler, may also be SIG_DFL or nil.
@field sa_sigaction function that will be a sa_sigaction handler, may also be SIG_DFL or nil.
@field sa_flags flags
*/
static int
luxio_sigaction(lua_State *L)
{
	int signo;
	struct sigaction sa = {.sa_handler = SIG_DFL}, old_sa;

	signo = luaL_checkinteger(L, 1);

	if (signo >= LUXIO_NSIG) {
		goto einval;
	}

	luaL_checktype(L, 2, LUA_TTABLE);
	lua_pushnil(L);

	while (lua_next(L, 2)) {
		const char *key;
		/* push a copy of the key onto the stack
		 * so we can convert it into a string and
		 * leave the original untouched for lua_next
		 */
		lua_pushvalue(L, -2);

		key = luaL_checkstring(L, -1);
		lua_pop(L, 1);

		if (strcmp(key, "sa_handler") == 0 || strcmp(key, "sa_sigaction") == 0) {
			if (lua_isfunction(L, -1)) {
				lua_State *sigstate = luxio__signal_ctx.handlers[signo].state;

				if (sigstate != NULL && sigstate != L) {
					goto enospc;
				}

				luxio__signal_ctx.handlers[signo].handler_fn = luaL_ref(L, LUA_REGISTRYINDEX);
				luxio__signal_ctx.handlers[signo].state = L;

				if (strcmp(key, "sa_handler") == 0) {
					sa.sa_handler = luxio__sigaction_sa_handler;
				} else {
					sa.sa_sigaction = luxio__sigaction_sigaction_handler;
				}
			} else if (lua_type(L, -1) == LUA_TNUMBER) {
				int disposition = luaL_checkinteger(L, -1);
				lua_pop(L, 1);

				if (disposition == (int) SIG_DFL) {
					sa.sa_handler = SIG_DFL;
				} else if (disposition == (int) SIG_IGN) {
					sa.sa_handler = SIG_IGN;
				} else {
					goto einval;
				}
			} else {
				goto einval;
			}
		} else if (strcmp(key, "sa_mask") == 0) {
			luxio_signalset *s = luaL_checkudata(L, -1, LUXIO_SIGNALSET_METATABLE);
			sa.sa_mask = s->set;
			lua_pop(L, 1);
		} else if (strcmp(key, "sa_flags") == 0) {
			sa.sa_flags = luaL_checkint(L, -1);
			lua_pop(L, 1);
		} else {
			goto einval;
		}
	}

	lua_pushinteger(L, sigaction(signo, &sa, &old_sa));
	if (errno != 0) {
		lua_pushinteger(L, errno);
	} else {
		lua_newtable(L);

		lua_pushinteger(L, old_sa.sa_flags);
		lua_setfield(L, -2, "sa_flags");
	}

	if (sa.sa_handler == SIG_DFL) {
		luxio__signal_ctx.handlers[signo].state = NULL;
	}

	return 2;

einval:
	lua_pushinteger(L, -1);
	lua_pushinteger(L, EINVAL);
	return 2;
enospc:
	lua_pushinteger(L, -1);
	lua_pushinteger(L, ENOSPC);
	return 2;
}

/* TODO: pthread_sigmask(), sigprocmask() 3.3.5 */

/*** Manipulate the current signal mask.

sigprocmask examines and/or changes the current process signal mask.
Signals are blocked if they are members of the current signal mask set.

The action performed by sigprocmask depends on the value of `how`,
which can be one of:

- `luxio.SIG_BLOCK` - The new mask is the existing mask plus all of the
signals in the specified set.

- `luxio.SIG_UNBLOCK` - The new mask is the existing mask minus the signals
contained within the specified set.

- `luxio.SIG_SETMASK` - The current mask is replaced with the specified set.

On success the previous signal mask will be returned, otherwise on error
nil will be returned and errno will be set appropriately.

If the `set` parameter is set to nil then the current signal mask will
be returned without performing any modification to the current signal mask,
and the `how` parameter will be ignored.

@tparam number how Action to perform on signal mask
@tparam sigset set signal set
@treturn return number return value
@treturn errno
@function sigprocmask
*/
static int
luxio_sigprocmask(lua_State *L)
{
	int how = luaL_checkinteger(L, 1);
	void *p = lua_touserdata(L, 2);
	sigset_t orig, *set = NULL;

	if (p != NULL) {
		luxio_signalset *s = luaL_checkudata(L, 2, LUXIO_SIGNALSET_METATABLE);
		set = &s->set;
	}

	if (sigprocmask(how, set, &orig) == -1) {
		lua_pushnil(L);
	} else {
		luxio_signalset *o = lua_newuserdata(L, sizeof(*o));
		o->set = orig;
		luxio__bless_signalset(L);
	}

	lua_pushinteger(L, errno);

	return 2;
}

/*** Send a signal to the calling process.

@tparam sig signal The signal to send
@treturn number return value
@treturn errno
@function raise
*/
static int
luxio_raise(lua_State *L)
{
	int sig = luaL_checkinteger(L, 1);

	lua_pushinteger(L, raise(sig));
	lua_pushinteger(L, errno);
	return 2;
}

/*** Return set of signals pending for the calling process.

@treturn sigset|nil set of pending signals, or nil on error
@treturn errno
@function sigpending
*/
static int
luxio_sigpending(lua_State *L)
{
	sigset_t s;
	luxio_signalset *pending;

	if (sigpending(&s) == -1) {
		lua_pushinteger(L, -1);
	} else {
		pending = lua_newuserdata(L, sizeof(*pending));
		pending->set = s;
		luxio__bless_signalset(L);
	}

	lua_pushinteger(L, errno);
	return 2;
}

/*** Suspend execution of calling process until signal is delivered.

sigsuspend temporarily replaces the signal mask of the calling
process with another mask until delivery of a signal that is not
masked occurs. sigsuspend always returns -1, with errno set to
indicate the error (which is generally EINTR). Upon returning
sigsuspend will restore the original signal mask that was replaced.

@tparam set mask
@treturn number return value
@treturn errno
@function sigsuspend
*/
static int
luxio_sigsuspend(lua_State *L)
{
	luxio_signalset *s = luaL_checkudata(L, 1, LUXIO_SIGNALSET_METATABLE);

	lua_pushinteger(L, sigsuspend(&s->set));
	lua_pushinteger(L, errno);
	return 2;
}

/*** Suspend execution of calling process until signal becomes pending.

sigwait temporarily waits for any one of the signals provided in
the set parameter to become pending. The signal that becomes
pending will be removed from the set. On success the pending signal
will be returned, otherwise nil is returned and errno is set accordingly.

@tparam set set of signals to wait on
@treturn number|nil signal, or nil on error
@treturn errno
@function sigwait
*/
static int
luxio_sigwait(lua_State *L)
{
	luxio_signalset *s = luaL_checkudata(L, 1, LUXIO_SIGNALSET_METATABLE);
	int sig;

	if (sigwait(&s->set, &sig) == -1) {
		lua_pushnil(L);
	} else {
		lua_pushinteger(L, sig);
	}

	lua_pushinteger(L, errno);
	return 2;
}

#ifdef __linux__
/*** Suspend execution of calling process until signal becomes pending.

Linux only.

sigwaitinfo suspends execution of the calling process until one of
the signals provided in the set parameter is pending. If one of
the signals is already pending then sigwaitinfo will return without
suspending execution.

sigwaitinfo returns the info table for the signal that was received
and removes that signal from the set argument.

If multiple signals are pending then the signal returned by sigwaitinfo is
determined using the usual rules detailed in signal(7).

@tparam set set of signals to wait on
@treturn sigwaitinfo-table|nil signal info table, or nil on error
@treturn errno
@function sigwaitinfo
*/

/*** sigwaitinfo() table
@table sigwaitinfo-table
@field si_signo Signal number
@field si_code Signal code
@field si_errno An errno value
@field si_pid Sending process ID
@field si_uid Real user ID of sending process
@field si_utime User time consumed
@field si_stime System time consumed
@field si_addr Memory location which caused fault
@field si_status Exit value or signal
@field si_band Band event (Linux only)
*/

static int
luxio_sigwaitinfo(lua_State *L)
{
	luxio_signalset *s = luaL_checkudata(L, 1, LUXIO_SIGNALSET_METATABLE);
	siginfo_t info;

	if (sigwaitinfo(&s->set, &info) == -1) {
		lua_pushnil(L);
	} else {
		luxio__push_siginfo_table(L, &info);
	}

	lua_pushinteger(L, errno);
	return 2;
}

/*** Suspend execution of process for a given time period
or until signal is delivered.

Linux only.

sigtimedwait behaves exactly as sigwaitinfo but will suspend execution
for a given time period specified by the (seconds, nanoseconds) arguments.
If both of the (seconds, nanoseconds) arguments are 0 then the function
polls for pending signals rather than suspending execution until a signal
becomes pending. On success a signal info table for the pending signal
is returned, otherwise nil is returned and errno is set accordingly.

@tparam set set of signals to wait on
@tparam number seconds
@tparam number nanoseconds
@treturn sigwaitinfo-table|nil signal info table, or nil on error
@treturn errno
@function sigtimedwait
*/

static int
luxio_sigtimedwait(lua_State *L)
{
	luxio_signalset *s = luaL_checkudata(L, 1, LUXIO_SIGNALSET_METATABLE);
	siginfo_t info;
	time_t tv_secs = luaL_checkinteger(L, 2);
	long tv_nsec = luaL_checkinteger(L, 3);
	struct timespec timeout = { tv_secs, tv_nsec };

	if (sigtimedwait(&s->set, &info, &timeout) == -1) {
		lua_pushnil(L);
	} else {
		luxio__push_siginfo_table(L, &info);
	}

	lua_pushinteger(L, errno);
	return 2;
}
#endif

/* TODO: sigqueue() 3.3.9 */
/* TODO: pthread_kill() 3.3.10 */

/*** Timer operations.
@section timer
*/

/*** Arranges for a SIGALRM signal to be delivered to the calling process in
`seconds` seconds.

@tparam number seconds How long to wait before signal delivery
@treturn number return value
@function alarm
*/
static int
luxio_alarm(lua_State *L) /* 3.4.1 */
{
	unsigned int seconds = luaL_checkinteger(L, 1);
	lua_pushinteger(L, alarm(seconds));

	return 1;
}

/*** Wait for a signal.

`pause()` causes the caller to suspend execution until either
a signal is caught or a signal is received which terminates the process.

`pause()` returns only when a signal is caught and the signal catching
function returns. In which case `pause()` will return -1 and errno will
be set to EINTR.

@treturn number return value
@function pause
*/
static int
luxio_pause(lua_State *L) /* 3.4.2 */
{
	lua_pushinteger(L, pause());
	lua_pushinteger(L, errno);

	return 2;
}

/*** Sleep for the specified number of seconds.
@tparam number seconds number of seconds to sleep
@treturn number return value
@function sleep
*/
static int
luxio_sleep(lua_State *L) /* 3.4.3 */
{
	unsigned int seconds = luaL_checkinteger(L, 1);

	lua_pushinteger(L, sleep(seconds));

	return 1;
}

/*** Process identification
@section procident
*/

/*** Get process identification.

Returns the process ID of the calling process.

@treturn number pid
@function getpid
*/
static int
luxio_getpid(lua_State *L) /* 4.1.1 */
{
	lua_pushinteger(L, getpid());

	return 1;
}

/*** Get process's parent's identification.

Returns the process ID of the parent of calling process

@treturn number pid
@function getppid
*/
static int
luxio_getppid(lua_State *L) /* 4.1.1 */
{
	lua_pushinteger(L, getppid());

	return 1;
}

/*** User identification.
@section userident
*/

/*** Get user identity.

Returns the real user ID of the calling process.

@treturn number uid
@function getuid
*/
static int
luxio_getuid(lua_State *L) /* 4.2.1 */
{
	lua_pushinteger(L, getuid());

	return 1;
}

/*** Get effective user identity.

Returns the effective user ID of the calling process.

@treturn number uid
@function geteuid
*/
static int
luxio_geteuid(lua_State *L) /* 4.2.1 */
{
	lua_pushinteger(L, geteuid());

	return 1;
}

/*** Get group identity.

Returns the real group ID of the calling process.

@treturn number gid
@function getgid
*/
static int
luxio_getgid(lua_State *L) /* 4.2.1 */
{
	lua_pushinteger(L, getgid());

	return 1;
}

/*** Get effective group identity.

Returns the effective group ID of the calling process

@treturn number gid
@function getegid
*/
static int
luxio_getegid(lua_State *L) /* 4.2.1 */
{
	lua_pushinteger(L, getegid());

	return 1;
}

/*** Set user identity.

Set the effective user ID of the calling process.
If the effective UID of the caller is root the real UID and
saved set-user-ID are also set.

Returns zero on success. Returns -1 on failure, with errno set appropriately.

__`setuid()` can fail even when the caller is UID 0,
   it is a grave security error to fail to check return value of `setuid().`__

@tparam number uid
@treturn number return value
@treturn errno errno
@function setuid
*/
static int
luxio_setuid(lua_State *L) /* 4.2.2 */
{
	uid_t uid = luaL_checkinteger(L, 1);

	lua_pushinteger(L, setuid(uid));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Set group identity.

Set the effective group ID of the calling process.
If the caller is the superuser, the real GID and saved set-group-ID
are also set.

Returns zero on success. Returns -1 on failure, with errno set appropriately.

@tparam number gid
@treturn number return value
@treturn errno errno
@function setgid
*/
static int
luxio_setgid(lua_State *L) /* 4.2.2 */
{
	gid_t gid = luaL_checkinteger(L, 1);

	lua_pushinteger(L, setgid(gid));
	lua_pushinteger(L, errno);

	return 2;
}

/* TODO: getgroups() 4.2.3 */

/*** Get username.

Returns 0 on success and non-zero on failure.

On success the second return value contains the name of the user logged in on
the process's controlling terminal. On failure the second return value
contains errno.

@treturn number return value
@treturn string|errno username or errno
@function getlogin
*/
static int
luxio_getlogin(lua_State *L) /* 4.2.4 */
{
	char buf[LOGIN_NAME_MAX];
	int r = getlogin_r(buf, sizeof(buf));

	if (r != 0) {
		lua_pushinteger(L, r);
		lua_pushinteger(L, errno);

		return 2;
	}

	lua_pushinteger(L, r);
	lua_pushstring(L, buf);

	return 2;
}

/*** Process groups.
@section procgroup
*/

static int
luxio_getpgrp(lua_State *L)
{
	pid_t pgid;

	pgid = getpgrp();

	lua_pushinteger(L, pgid);

	return 1;
}

static int
luxio_setsid(lua_State *L)
{
	pid_t sid;

	sid = setsid();

	lua_pushinteger(L, sid);

	if (sid < 0) {
		lua_pushinteger(L, errno);
		return 2;
	}

	return 1;
}


static int
luxio_setpgid(lua_State *L)
{
	pid_t pid, pgid;
	int r;

	pid = luaL_checkinteger(L, 1);
	pgid = luaL_checkinteger(L, 2);

	r = setpgid(pid, pgid);

	lua_pushinteger(L, r);

	if (r < 0) {
		lua_pushinteger(L, errno);
		return 2;
	}

	return 1;
}

/*** System identification.
@section sysident
*/

/*** uname() information table.
Returned by @{uname}.  Some fields are OS-specific.
@field sysname Operating system name, such as Linux or NetBSD.
@field nodename System's name
@field release Operating systems's release version
@field machine Hardware identifier
@field domainname NIS or YP domain name _Note: GNU extension_
@table uname-table
*/

/*** Get name and information about current kernel.
@treturn number return value
@treturn uname-table|errno result table, or errno.
@function uname
*/
static int
luxio_uname(lua_State *L) /* 4.4.1 */
{
	struct utsname buf;
	int r = uname(&buf);

	lua_pushinteger(L, r);

	if (r < 0) {
		lua_pushinteger(L, errno);

		return 2;
	}

	lua_createtable(L, 0, 6);

#define UNAME_FIELD(n) do { lua_pushstring(L, #n); \
	lua_pushstring(L, buf.n); \
	lua_settable(L, 2); } while (0)

	UNAME_FIELD(sysname);
	UNAME_FIELD(nodename);
	UNAME_FIELD(release);
	UNAME_FIELD(version);
	UNAME_FIELD(machine);
#ifdef _GNU_SOURCE
	UNAME_FIELD(domainname);
#endif

#undef UNAME_FIELD

	return 2;
}

/*** Time.
@section time
*/

/*** Get time in seconds.

On success, returns the time as the number of seconds since the Epoch,
1970-01-01 00:00:00 +0000 (UTC). On failure, returns -1 with errno
set appropriately.

@treturn number seconds since epoch.
@treturn number errno
@function time
*/
static int
luxio_time(lua_State *L) /* 4.5.1 */
{
	lua_pushinteger(L, time(NULL));
	lua_pushinteger(L, errno);

	return 2;
}

/*** times() information table.
Returned by @{times}.
@field utime user time
@field stime system time
@field cutime user time of children
@field cstime system time of children
@table times-table
*/

/*** Get process times.
@treturn number return value
@treturn times-table|errno Time data, or errno.
@function times
*/
static int
luxio_times(lua_State *L) /* 4.5.2 */
{
	struct tms buf;
	clock_t r = times(&buf);

	if (r == (clock_t)-1) {
		lua_pushinteger(L, r);
		lua_pushinteger(L, errno);
		return 2;
	}

	lua_pushinteger(L, r);
	lua_createtable(L, 0, 4);

#define TIMES_FIELD(n) do { lua_pushstring(L, #n); \
	lua_pushinteger(L, buf.tms_##n); \
	lua_settable(L, 2); } while (0)

	TIMES_FIELD(utime);
	TIMES_FIELD(stime);
	TIMES_FIELD(cutime);
	TIMES_FIELD(cstime);

#undef TIMES_FIELD
	return 2;
}

/*** Environment variables.
@section envvar
*/

/*** Get an environment variable.

Returns the value of the environment variable, or nil if the environment
variable does not exist.

@tparam string name
@treturn string|nil return value
@function getenv
*/
static int
luxio_getenv(lua_State *L) /* 4.6.1 */
{
	const char *envvar = luaL_checkstring(L, 1);

	char *envval = getenv(envvar);

	if (envval == NULL)
		return 0;

	lua_pushstring(L, envval);

	return 1;
}

/*** Set an environment variable.

Returns zero on success, or -1 on error, with errno set appropriately.

Add the variable with name `name` to the environment if it
doesn't already exist. If it does already exist then overwrite
it if `overwrite` is non-zero, otherwise do nothing.
_Note: `setenv()` still returns successfully if the variable
is found and `overwrite` is zero._

@tparam string name
@tparam string value
@tparam[opt=0] number overwrite
@treturn number return value
@treturn errno
@function setenv
*/
static int
luxio_setenv(lua_State *L) /* POSIX.1-2001 */
{
	const char *envvar = luaL_checkstring(L, 1);
	const char *envval = luaL_checkstring(L, 2);
	int overwrite = luaL_optint(L, 3, 1);

	lua_pushinteger(L, setenv(envvar, envval, overwrite));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Unsets an environment variable.

Returns zero on success, or -1 on error, with errno set appropriately.

@tparam string name
@treturn number return value
@treturn errno
@function unsetenv
*/
static int
luxio_unsetenv(lua_State *L) /* POSIX.1-2001 */
{
	const char *envvar = luaL_checkstring(L, 1);

	lua_pushinteger(L, unsetenv(envvar));
	lua_pushinteger(L, errno);

	return 2;
}

/* 4.7 Terminal identification ***********************************************/

static int
luxio_ctermid(lua_State *L)
{
	lua_pushstring(L, ctermid(NULL));
	return 1;
}

static int
luxio_ttyname(lua_State *L)
{
	int fd = luaL_checkinteger(L, 1);

	lua_pushstring(L, ttyname(fd));
	lua_pushinteger(L, errno);

	return 2;
}

static int
luxio_isatty(lua_State *L)
{
	int fd = luaL_checkinteger(L, 1);

	lua_pushboolean(L, isatty(fd));
	lua_pushinteger(L, errno);

	return 2;
}

/* 4.8 Configurable system variables *****************************************/

static int
luxio_sysconf(lua_State *L)
{
	int name = luaL_checkinteger(L, 1);
	long result = sysconf(name);

	lua_pushinteger(L, result);
	lua_pushinteger(L, result == -1 ? errno : 0);

	return 2;
}

/*** Directories.
@section dir
*/

#define LUXIO_READDIR_METATABLE "luxio.readdir"

typedef struct {
	DIR *dirp;
	struct dirent *buf, *ent;
} luxio_readdir_state;

static int
luxio_readdir_gc(lua_State *L)
{
	luxio_readdir_state *s = luaL_checkudata(L, 1, LUXIO_READDIR_METATABLE);

	closedir(s->dirp);
	free(s->buf);

	return 0;
}

static int
luxio_readdir_tostring(lua_State *L)
{
	luxio_readdir_state *s = luaL_checkudata(L, 1, LUXIO_READDIR_METATABLE);
	char buf[sizeof("dirent: 0xffffffffffffffff")];

	/* we can't use lua_pushfstring here, because our pointer might
	 * be 64 bits.
	 */
	snprintf(buf, sizeof(buf), "dirent: %p", s);
	lua_pushstring(L, buf);

	return 1;
}

static void
luxio__bless_readdir(lua_State *L)
{
	int create = luaL_newmetatable(L, LUXIO_READDIR_METATABLE);

	if (create != 0) {
		lua_pushcfunction(L, luxio_readdir_gc);
		lua_setfield(L, -2, "__gc");
		lua_pushcfunction(L, luxio_readdir_tostring);
		lua_setfield(L, -2, "__tostring");
	}

	lua_setmetatable(L, -2);
}

/*** Open a directory for enumeration.
@tparam string dir directory to enumerate
@treturn DIR|nil DIR object, or nil on error
@treturn errno errno
@function opendir
*/
static int
luxio_opendir(lua_State *L) /* 5.1.2 */
{
	const char *path = luaL_checkstring(L, 1);
	DIR *d = opendir(path);
	size_t bufz;
	luxio_readdir_state *s;

	if (d == NULL) {
		lua_pushnil(L);
		lua_pushinteger(L, errno);
		return 2;
	}

	s = lua_newuserdata(L, sizeof(*s));

	s->dirp = d;
	/* + 256 because it'd always be +1 if it weren't for the horrors
	 * of Solaris.  If we were using autoconf, we could use Ben
	 * Hutchings' function mentioned in his article "readdir_r considered
	 * harmful".
	 */
	bufz = sizeof(struct dirent) + safe_pathconf(path, _PC_NAME_MAX) + 256;
	s->buf = malloc(bufz);

	luxio__bless_readdir(L);

	return 1;
}

/*** Open a directory for enumeration by open fd.
@tparam number fd file descriptor
@treturn DIR|nil DIR object, or nil on error
@treturn errno errno
@function fdopendir
*/
static int
luxio_fdopendir(lua_State *L) /* POSIX.1-2008 */
{
	int fd = luaL_checkinteger(L, 1);
	DIR *d = fdopendir(fd);
	size_t bufz;
	luxio_readdir_state *s;

	if (d == NULL) {
		lua_pushnil(L);
		lua_pushinteger(L, errno);
		return 2;
	}

	s = lua_newuserdata(L, sizeof(*s));

	s->dirp = d;
	/* + 256 because it'd always be +1 if it weren't for the horrors
	 * of Solaris.  If we were using autoconf, we could use Ben
	 * Hutchings' function mentioned in his article "readdir_r considered
	 * harmful".
	 */
	bufz = sizeof(struct dirent) + safe_fpathconf(fd, _PC_NAME_MAX) + 256;
	s->buf = malloc(bufz);

	luxio__bless_readdir(L);

	return 1;
}

/*** Close a previously open directory.
@tparam DIR handle DIR object to close
@function closedir
*/
static int
luxio_closedir(lua_State *L) /* 5.1.2 */
{
	luxio_readdir_state *s = luaL_checkudata(L, 1, LUXIO_READDIR_METATABLE);

	if (s->dirp != NULL) {
		closedir(s->dirp);
		s->dirp = NULL;
	}

	free(s->buf);
	s->buf = NULL;

	return 0;
}

/*** readdir() information table.
Returned by @{readdir}.  Some fields are OS-specific.
@field d_ino inode number
@field d_name file name
@field d_type file type _Note: `d_type` is not supported by all filesystems._
@table dirent
*/

/*** Read a directory entry
@tparam DIR handle directory handle
@treturn dirent|nil directory entry table, or nil on error
@treturn errno errno
@function readdir
*/
static int
luxio_readdir(lua_State *L) /* 5.1.2 */
{
	luxio_readdir_state *s = luaL_checkudata(L, 1, LUXIO_READDIR_METATABLE);

	errno = 0;
#ifdef LUXIO_USE_READDIR
	struct dirent *ent = readdir(s->dirp);
#else
	errno = readdir_r(s->dirp, s->buf, &s->ent);
	struct dirent *ent = errno == 0 ? s->ent : NULL;
#endif

	if (ent == NULL) {
		if (errno != 0) {
			lua_pushinteger(L, errno);
		} else {
			/* end of directory */
			lua_pushnil(L);
		}

		return 1;
	}

	lua_pushinteger(L, 0);
	lua_createtable(L, 0, 3);
	lua_pushinteger(L, ent->d_ino);
	lua_setfield(L, -2, "d_ino");
	lua_pushstring(L, ent->d_name);
	lua_setfield(L, -2, "d_name");
#ifdef HAVE_D_TYPE
	lua_pushinteger(L, ent->d_type);
	lua_setfield(L, -2, "d_type");
#endif
	return 2;
}

/*** Reset directory stream
@tparam DIR handle
@function rewinddir
*/
static int
luxio_rewinddir(lua_State *L) /* 5.1.2 */
{
	luxio_readdir_state *s = luaL_checkudata(L, 1, LUXIO_READDIR_METATABLE);

	rewinddir(s->dirp);

	return 0;
}

/*** Working directory.
@section workdir
*/

/*** Change working directory.

Returns zero on success, or -1 on error with errno set appropriately.

@tparam string path
@treturn number return value
@treturn errno errno
@function chdir
*/
static int
luxio_chdir(lua_State *L) /* 5.2.1 */
{
	const char *path = luaL_checkstring(L, 1);

	lua_pushinteger(L, chdir(path));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Get the current working directory.

@treturn string|nil path or nil on error
@treturn errno
@function getcwd
*/
static int
luxio_getcwd(lua_State *L) /* 5.2.2 */
{
	size_t buflen = safe_pathconf("/", _PC_PATH_MAX) + 256;
	char buf[buflen];

	if (getcwd(buf, buflen) == NULL) {
		lua_pushnil(L);
	} else {
		lua_pushstring(L, buf);
	}

	lua_pushinteger(L, errno);

	return 2;
}

/*** General file creation.
@section genfile
*/

/*** Open and possibly create a file or device.

Returns file descriptor on success. On error returns -1 with errno set
appropriately.

`mode` is an optional parameter that may be a bitwise OR of the following
constants:

- _Read, write and executable_
	- `luxio.S_IRWXU` - User read, write and executable
	- `luxio.S_IRWXG` - Group read, write and executable
	- `luxio.S_IRWXO` - World read, write and executable

- _Readable_
	- `luxio.S_IRUSR` - User readable
	- `luxio.S_IRGRP` - Group readable
	- `luxio.S_IROTH` - World readable

- _Writeable_
	- `luxio.S_IWUSR` - User writeable
	- `luxio.S_IWGRP` - Group writeable
	- `luxio.S_IWOTH` - World writeable

- _Executable_
	- `luxio.S_IXUSR` - User executable
	- `luxio.S_IXGRP` - Group executable
	- `luxio.S_IXOTH` - World executable

`flags` is a parameter that may be a bitwise OR of the following
constants:

- `luxio.O_RDONLY`
- `luxio.O_WRONLY`
- `luxio.O_RDWR`
- `luxio.O_APPEND`
- `luxio.O_ASYNC`
- `luxio.O_CLOEXEC`
- `luxio.O_CREAT`
- `luxio.O_EXCL`
- `luxio.O_NOCTTY`
- `luxio.O_NONBLOCK`
- `luxio.O_SYNC`
- `luxio.O_TRUNC`
- `luxio.O_DIRECT`
- `luxio.O_NOFOLLOW`
- `luxio.O_NOATIME`
- `luxio.O_LARGEFILE`

_Note: Not all of these constants are available on all platforms.
Consult the `open(2)` man pages for details._

@tparam string path
@tparam number flags
@tparam[opt] number mode, must be specified if creating.
@treturn result File descriptor
@treturn errno
@function open
*/
static int
luxio_open(lua_State *L) /* 5.3.1 */
{
	const char *pathname = luaL_checkstring(L, 1);
	int flags = luaL_checkint(L, 2);
	mode_t mode = luaL_optinteger(L, 3, INVALID_MODE);
	int result;

	if ((flags & O_CREAT) && mode == INVALID_MODE) {
		lua_pushstring(L, "open with O_CREAT called with no mode");
		lua_error(L);
	}

	if (mode == INVALID_MODE)
		result = open(pathname, flags);
	else
		result = open(pathname, flags, mode);

	lua_pushinteger(L, result);
	lua_pushinteger(L, errno);

	return 2;
}

/*** Create a file or device.

Returns file descriptor on success. On error returns -1 with errno set
appropriately.

@tparam string path
@tparam[opt] number mode, must be specified if creating.
@treturn result File descriptor
@treturn errno
@function creat
*/
static int
luxio_creat(lua_State *L)
{
	const char *pathname = luaL_checkstring(L, 1);
	mode_t mode = luaL_optinteger(L, 2, 0);

	lua_pushinteger(L, creat(pathname, mode));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Set file mode creation mask.
@tparam number mask
@function umask
*/
static int
luxio_umask(lua_State *L) /* 5.3.3 */
{
	mode_t mask = luaL_checkinteger(L, 1);

	lua_pushinteger(L, umask(mask));

	return 1;
}

/*** Make a new name for a file.
@tparam string existing existing file name
@tparam string new new file name
@treturn number return value
@treturn errno
@function link
*/
static int
luxio_link(lua_State *L) /* 5.3.4 */
{
	const char *existing = luaL_checkstring(L, 1);
	const char *new = luaL_checkstring(L, 2);

	lua_pushinteger(L, link(existing, new));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Make a new (symbolic) name for a file.
@tparam string existing existing file name
@tparam string new new file name
@treturn number return value
@treturn errno
@function symlink
*/
static int
luxio_symlink(lua_State *L) /* POSIX.1-2001, Unknown location */
{
	const char *oldpath = luaL_checkstring(L, 1);
	const char *newpath = luaL_checkstring(L, 2);

	lua_pushinteger(L, symlink(oldpath, newpath));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Read value of symlink.
@tparam string path
@treturn number return value
@treturn string|errno value, or errno on error
@function readlink
*/
static int
luxio_readlink(lua_State *L) /* POSIX.1-2001, Unknown location */
{
	size_t buflen = safe_pathconf("/", _PC_PATH_MAX) + 256;
	char buffer[buflen];
	ssize_t ret;
	const char *path = luaL_checkstring(L, 1);

	lua_pushinteger(L, (ret = readlink(path, buffer, buflen)));
	if (ret > 0) {
		lua_pushinteger(L, errno);
	} else {
		lua_pushstring(L, buffer);
	}

	return 2;
}

/*** Create a unique temporary file.

@tparam string|nil pattern Pattern to use, or nil for default pattern.
@treturn number FD of temporary file (-1 on error)
@treturn string|errno Filename of temporary file or errno on error
@function mkstemp
*/
static int
luxio_mkstemp(lua_State *L)
{
	size_t infname_len;
	const char *infname = luaL_optlstring(L, 1, "lux_XXXXXX", &infname_len);
	size_t buflen = safe_pathconf(infname, _PC_PATH_MAX) + 256;
	char fnamebuf[buflen];
	int fd, saved_errno;

	if (infname_len > (buflen - 1)) {
		lua_pushinteger(L, -1);
		lua_pushinteger(L, EINVAL);
		return 2;
	}

	strcpy(fnamebuf, infname); /* Safe because of above test */

	fd = mkstemp(fnamebuf);
	if (fd == -1) {
		saved_errno = errno;
		lua_pushnumber(L, -1);
		lua_pushnumber(L, saved_errno);
		return 2;
	}

	lua_pushnumber(L, fd);
	lua_pushstring(L, fnamebuf);
	return 2;
}

/*** Special file creation
@section specfile
*/

/*** Create a directory.
@tparam string path
@tparam number mode
@treturn number return value
@treturn errno
@function mkdir
*/
static int
luxio_mkdir(lua_State *L) /* 5.4.1 */
{
	const char *pathname = luaL_checkstring(L, 1);
	mode_t mode = luaL_checkinteger(L, 2);

	lua_pushinteger(L, mkdir(pathname, mode));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Make a FIFO special file (a named pipe)
@tparam string path
@tparam number mode
@treturn number return value
@treturn errno
@function mkfifo
*/
static int
luxio_mkfifo(lua_State *L) /* 5.4.2 */
{
	const char *pathname = luaL_checkstring(L, 1);
	mode_t mode = luaL_checkinteger(L, 2);

	lua_pushinteger(L, mkfifo(pathname, mode));
	lua_pushinteger(L, errno);

	return 2;
}

/*** File removal
@section filerem
*/

/*** Delete a name and possibly the file it points to.
@tparam string path
@treturn number return value
@treturn errno
@function unlink
*/
static int
luxio_unlink(lua_State *L) /* 5.5.1 */
{
	const char *s = luaL_checkstring(L, 1);

	lua_pushinteger(L, unlink(s));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Delete a directory.
@tparam string path
@treturn number return value
@treturn errno
@function rmdir
*/
static int
luxio_rmdir(lua_State *L) /* 5.5.2 */
{
	const char *pathname = luaL_checkstring(L, 1);

	lua_pushinteger(L, rmdir(pathname));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Change the name or location of a file.
@tparam string oldpath
@tparam string newpath
@treturn number return value
@treturn errno
@function rename
*/
static int
luxio_rename(lua_State *L) /* 5.5.3 */
{
	const char *old = luaL_checkstring(L, 1);
	const char *new = luaL_checkstring(L, 2);

	lua_pushinteger(L, rename(old, new));
	lua_pushinteger(L, errno);

	return 2;
}

/*** File characteristics
@section filechar
*/

/*** stat() information table
Returned by @{stat} and family.
@field dev id of device containing file
@field ino inode of file
@field mode protection mode
@field nlink number of links
@field uid user id of owner
@field gid group id of owner
@field rdev device id (if special file)
@field size total size, in bytes
@field blksize blocksize for file system I/O
@field blocks number of blocks allocated
@field atime time of last access
@field mtime time of last modification
@field ctime time of last status change
@table stat-table
*/

static void
luxio_push_stat_table(lua_State *L, struct stat *s)
{
	lua_createtable(L, 0, 13);

#define PUSH_ENTRY(e) do { lua_pushstring(L, #e);	\
	lua_pushinteger(L, s->st_##e);			\
	lua_settable(L, 3); } while (0)

	PUSH_ENTRY(dev);
	PUSH_ENTRY(ino);
	PUSH_ENTRY(mode);
	PUSH_ENTRY(nlink);
	PUSH_ENTRY(uid);
	PUSH_ENTRY(gid);
	PUSH_ENTRY(rdev);
	PUSH_ENTRY(size);
	PUSH_ENTRY(blksize);
	PUSH_ENTRY(blocks);
	PUSH_ENTRY(atime);
	PUSH_ENTRY(mtime);
	PUSH_ENTRY(ctime);

#undef PUSH_ENTRY
}

/*** Get file status by path.
@tparam string path
@treturn number return value
@treturn errno|stat-table
@function stat
*/
static int
luxio_stat(lua_State *L) /* 5.6.2 */
{
	const char *pathname = luaL_checkstring(L, 1);
	struct stat s;
	int r = stat(pathname, &s);

	lua_pushinteger(L, r);

	if (r < 0) {
		lua_pushinteger(L, errno);
	} else {
		luxio_push_stat_table(L, &s);
	}

	return 2;
}

/*** Get file status by fd.
@tparam number fd
@treturn number return value
@treturn errno|stat-table
@function fstat
*/
static int
luxio_fstat(lua_State *L) /* 5.6.2 */
{
	int fd = luaL_checkinteger(L, 1);
	struct stat s;
	int r = fstat(fd, &s);

	lua_pushinteger(L, r);

	if (r < 0) {
		lua_pushinteger(L, errno);
	} else {
		luxio_push_stat_table(L, &s);
	}

	return 2;
}

/*** Get symlink status by path.
@tparam string path to symlink
@treturn number return value
@treturn errno|stat-table
@function lstat
*/
static int
luxio_lstat(lua_State *L) /* POSIX.1-2001 */
{
	const char *pathname = luaL_checkstring(L, 1);
	struct stat s;
	int r = lstat(pathname, &s);

	lua_pushinteger(L, r);

	if (r < 0) {
		lua_pushinteger(L, errno);
	} else {
		luxio_push_stat_table(L, &s);
	}

	return 2;
}

#define STAT_IS(x) static int luxio_S_IS##x(lua_State *L) { \
	int mode = luaL_checkinteger(L, 1);               \
	lua_pushinteger(L, S_IS##x(mode));                 \
	return 1;                                         \
	}

/*** Check status macro S_ISREG for stat mode field.
@function S_ISREG
@tparam number mode field from a stat call
@treturn number
*/
STAT_IS(REG)

/*** Check status macro S_ISDIR for stat mode field.
@function S_ISDIR
@tparam number mode field from a stat call
@treturn number
*/
 STAT_IS(DIR)

/*** Check status macro S_ISCHR for stat mode field.
@function S_ISCHR
@tparam number mode field from a stat call
@treturn number
*/
STAT_IS(CHR)

/*** Check status macro S_ISBLK for stat mode field.
@function S_ISBLK
@tparam number mode field from a stat call
@treturn number
*/
STAT_IS(BLK)

/*** Check status macro S_ISFIFO for stat mode field.
@function S_ISFIFO
@tparam number mode field from a stat call
@treturn number
*/
STAT_IS(FIFO)

#ifdef S_ISLNK
/*** Check status macro S_ISLNK for stat mode field.
Not always available.
@function S_ISLNK
@tparam number mode field from a stat call
@treturn number
*/
STAT_IS(LNK)
#endif

#ifdef S_ISSOCK
/*** Check status macro S_ISSOCK for stat mode field.
Not always available.
@function S_ISSOCK
@tparam number mode field from a stat call
@treturn number
*/

STAT_IS(SOCK)
#endif

#undef STAT_IS

static int
luxio_access(lua_State *L)
{
	const char *path = luaL_checkstring(L, 1);
	mode_t mode = luaL_checkinteger(L, 2);

	lua_pushinteger(L, access(path, mode));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Change permissions of a file.
@tparam string path
@tparam number mode
@treturn number return value
@treturn errno
@function chmod
*/
static int
luxio_chmod(lua_State *L) /* 5.6.4 */
{
	const char *path = luaL_checkstring(L, 1);
	mode_t mode = luaL_checkinteger(L, 2);

	lua_pushinteger(L, chmod(path, mode));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Change permissions of a file by fd.
@tparam number fd
@tparam number mode
@treturn number return value
@treturn errno
@function chmod
*/
static int
luxio_fchmod(lua_State *L) /* 5.6.4 */
{
	int fd = luaL_checkinteger(L, 1);
	mode_t mode = luaL_checkinteger(L, 2);

	lua_pushinteger(L, fchmod(fd, mode));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Change ownership of a file.
@tparam string path
@tparam number owner
@tparam number group
@treturn number return value
@treturn errno
@function chmod
*/
static int
luxio_chown(lua_State *L) /* 5.6.5 */
{
	const char *path = luaL_checkstring(L, 1);
	uid_t owner = luaL_checkinteger(L, 2);
	gid_t group = luaL_checkinteger(L, 3);

	lua_pushinteger(L, chown(path, owner, group));
	lua_pushinteger(L, errno);

	return 2;
}

/* TODO: utime() 5.6.6 */

/*** Truncate a file to a specified length.
@tparam number fd
@tparam number lenght
@treturn number return value
@treturn errno
@function ftruncate
*/
static int
luxio_ftruncate(lua_State *L) /* 5.6.7 */
{
	int fildes = luaL_checkinteger(L, 1);
        off_t length = luaL_checkinteger(L, 2);

	lua_pushinteger(L, ftruncate(fildes, length));
	lua_pushinteger(L, errno);

	return 2;
}

/* 5.7 Configurable pathname variables ***************************************/

/* TODO: pathconf(), fpathconf() 5.7.1 */

/*** Pipes
@section pipes
*/

/*** Create pipe.
@tparam table pipe A table for which this function will fill in the keys 1 and 2
@treturn number return value
@treturn errno
@function pipe
*/
static int
luxio_pipe(lua_State *L) /* 6.1.1 */
{
	int res, pipefd[2];
	luaL_checktype(L, 1, LUA_TTABLE);

	res = pipe(pipefd);
	if (res == 0) {
		lua_pushinteger(L, pipefd[0]);
		lua_rawseti(L, 1, 1);
		lua_pushinteger(L, pipefd[1]);
		lua_rawseti(L, 1, 2);
	}

	lua_pushinteger(L, res);
	lua_pushinteger(L, errno);

	return 2;
}

#ifdef _GNU_SOURCE

/*** Create a pipe, with flags.
Not available on all systems.
@tparam table pipe A table for which this function will fill in the keys 1 and 2
@tparam number flags
@treturn number return value
@treturn errno
@function pipe2
*/
static int
luxio_pipe2(lua_State *L) /* GNU extension */
{
	int res, pipefd[2];
	int flags;

	luaL_checktype(L, 1, LUA_TTABLE);
	flags = luaL_checkinteger(L, 2);

	res = pipe2(pipefd, flags);
	if (res == 0) {
		lua_pushinteger(L, pipefd[0]);
		lua_rawseti(L, 1, 1);
		lua_pushinteger(L, pipefd[1]);
		lua_rawseti(L, 1, 2);
	}

	lua_pushinteger(L, res);
	lua_pushinteger(L, errno);

	return 2;
}
#endif

/*** Create a pair of connected sockets.
@tparam number domain
@tparam number type
@tparam number protocol
@tparam table fdarray The values [1] and [2] are filled in with descriptors
@treturn number return value
@treturn errno
@function socketpair
*/
static int
luxio_socketpair(lua_State *L) /* POSIX.1-2001 */
{
	int domain = luaL_checkinteger(L, 1);
	int type = luaL_checkinteger(L, 2);
	int protocol = luaL_checkinteger(L, 3);
	int sv[2];
	int res;
	luaL_checktype(L, 4, LUA_TTABLE);

	res = socketpair(domain, type, protocol, sv);
	if (res == 0) {
		lua_pushinteger(L, sv[0]);
		lua_rawseti(L, 4, 1);
		lua_pushinteger(L, sv[1]);
		lua_rawseti(L, 4, 2);
	}

	lua_pushinteger(L, res);
	lua_pushinteger(L, errno);

	return 2;
}

/*** File descriptor manipulation.
@section fdmanip
*/

/*** Duplicate a file descriptor.
@tparam number oldfd
@treturn number return value
@treturn errno
@function dup
*/
static int
luxio_dup(lua_State *L) /* 6.2.1 */
{
	int oldfd = luaL_checkint(L, 1);

	lua_pushinteger(L, dup(oldfd));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Duplicate a file descriptor to a specific one
@tparam number oldfd
@tparam number newfd
@treturn number return value
@treturn errno
@function dup2
*/
static int
luxio_dup2(lua_State *L) /* 6.2.1 */
{
	int oldfd = luaL_checkint(L, 1);
	int newfd = luaL_checkint(L, 2);

	lua_pushinteger(L, dup2(oldfd, newfd));
	lua_pushinteger(L, errno);

	return 2;
}

#ifdef _GNU_SOURCE
/** Duplicate a file descriptor to a specific one, with flags.
Not available on all platforms.
@tparam number oldfd
@tparam number newfd
@tparam number flags
@treturn number return value
@treturn errno
@function dup3
*/
static int
luxio_dup3(lua_State *L) /* GNU extension */
{
	int oldfd = luaL_checkint(L, 1);
	int newfd = luaL_checkint(L, 2);
	int flags = luaL_checkint(L, 3);

	lua_pushinteger(L, dup3(oldfd, newfd, flags));
	lua_pushinteger(L, errno);

	return 2;
}
#endif

/*** File descriptor deassignment.
@section fileclose
*/

/*** Close a file descriptor.
@tparam number fd
@treturn number return value
@treturn errno
@function close
*/
static int
luxio_close(lua_State *L) /* 6.3.1 */
{
	lua_pushinteger(L, close(luaL_checkint(L, 1)));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Input and output
@section io
*/

/*** Read from a file descriptor.
@tparam number fd
@tparam number count
@treturn number|string return value or read data
@treturn errno
@function read
*/
static int
luxio_read(lua_State *L) /* 6.4.1 */
{
    int fd = luaL_checkint(L, 1);
    int count = luaL_checkint(L, 2);
    ssize_t result;
    char *buf = malloc(count);

    if (buf == NULL) {
        lua_pushstring(L, "unable to allocate read buffer: memory exhausted");
        lua_error(L);
    }

    result = read(fd, buf, count);

    if (result == -1) {
        lua_pushinteger(L, result);
        lua_pushinteger(L, errno);
    } else {
        /* sadly there appears to be no way to avoid this copy.
         * luaL_Buffer actually builds things on the C stack bytes at a time,
         * and there is no way to pre-allocate a Lua type other than a
         * userdatum.  Additionally, should Lua call its panic function because
         * it can't allocate memory to copy this into, our buf will be leaked.
         * We could perhaps fix this with a lot of faff, involving creating
         * a userdatum for our buffer, and setting a __gc metamethod.
         */
        lua_pushlstring(L, buf, result);
        lua_pushinteger(L, errno);
    }

    free(buf);

    return 2;
}

/*** Write to a file descriptor.
@tparam number fd
@tparam string data
@tparam[opt=0] number start_offset
@treturn number return value
@treturn errno
@function write
*/
static int
luxio_write(lua_State *L) /* 6.4.2 */
{
	int fd = luaL_checkint(L, 1);
	size_t count;
	const char *buf = luaL_checklstring(L, 2, &count);
	size_t offset = luaL_optinteger(L, 3, 0);

	if (offset > count) offset = count;

	lua_pushinteger(L, write(fd, buf + offset, count - offset));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Write data from multiple buffers.
@tparam number fd
@tparam string ...
@treturn number return value
@treturn errno
@function writev
*/
static int
luxio_writev(lua_State *L) /* POSIX.1-2001 */
{
	int fd = luaL_checkint(L, 1);
	int blks = lua_gettop(L) - 1;
	int c;
	struct iovec *iov;

	/* check there is at least one string to write */
	luaL_checkstring(L, 2);

	iov = malloc(blks * sizeof(*iov));

	for (c = 0; c < blks; c++) {
		iov[c].iov_base = (void *)luaL_checkstring(L, c + 2);
		iov[c].iov_len = lua_rawlen(L, c + 2);
	}

	lua_pushinteger(L, writev(fd, iov, blks));
	lua_pushinteger(L, errno);

	free(iov);

	return 2;
}

#ifdef HAVE_SENDFILE
/*** Transfer data between descriptors.
Not available on all systems.
@tparam number out_fd
@tparam number in_fd
@tparam[opt=nil] number offset
@tparam number count
@treturn number return value
@treturn errno
@function sendfile
*/
static int
luxio_sendfile(lua_State *L) /* Linux-specific */
{
	int out_fd = luaL_checkint(L, 1);
	int in_fd = luaL_checkint(L, 2);
	off_t offset;
	size_t count = luaL_checkint(L, 4);
	ssize_t r;

	if (lua_isnil(L, 3)) {
		r = sendfile(out_fd, in_fd, NULL, count);
		lua_pushinteger(L, r);
		lua_pushinteger(L, errno);
		return 2;
	}

	offset = luaL_checkint(L, 3);
	r = sendfile(out_fd, in_fd, &offset, count);
	lua_pushinteger(L, r);
	lua_pushinteger(L, errno);
	lua_pushinteger(L, offset);

	return 3;
}
#endif /* HAVE_SENDFILE */

#ifdef HAVE_SPLICE
/*** Splice data to or from a pipe.
Not available on all systems.
@tparam number fd_in
@tparam number off_in
@tparam number fd_out
@tparam number off_out
@tparam number len
@tparam number flags
@treturn number return value
@treturn errno
@function splice
*/
static int
luxio_splice(lua_State *L) /* Linux-specific */
{
	int fd_in = luaL_checkinteger(L, 1);
	loff_t off_in = luaL_optlong(L, 2, -1);
	int fd_out = luaL_checkinteger(L, 3);
	loff_t off_out = luaL_optlong(L, 4, -1);
	size_t len = luaL_checkinteger(L, 5);
	unsigned int flags = luaL_checkinteger(L, 6);

	loff_t *poff_in = &off_in;
	loff_t *poff_out = &off_out;

	if (off_in == -1) poff_in = NULL;
	if (off_out == -1) poff_out = NULL;

	lua_pushinteger(L, splice(fd_in, poff_in, fd_out, poff_out,
				  len, flags));
	lua_pushinteger(L, errno);

	return 2;
}
#endif

/*** Control operations on files
@section fcntl
*/

/*** Manipulate file descriptor.
Supported commands: F_GETFD/F_SETFD, F_GETFL/F_SETFL,
F_GETPIPE_SZ/F_SETPIPE_SZ, F_DUPFD, F_DUPFD_CLOEXEC,
F_SETLK, F_SETLKW, F_GETLK.

Commands that take a struct, such as F_SETLK, accept
a table as the argument, with keys named as the struct's.

@tparam number fd
@tparam number command
@tparam ... ...
@treturn number return value
@treturn errno
@function fcntl
*/
static int
luxio_fcntl(lua_State *L) /* 6.5.2 */
{
	int fd = luaL_checkint(L, 1);
	int cmd = luaL_checkint(L, 2);
	long arg_long;
	struct flock flock;

	switch (cmd) {
	/* commands that take no argument */
	case F_GETFD:
	case F_GETFL:
#ifdef F_GETPIPE_SZ
	case F_GETPIPE_SZ:
#endif
		lua_pushinteger(L, fcntl(fd, cmd));
		lua_pushinteger(L, errno);
		return 2;

	/* commands that take a long */
	case F_DUPFD:
#ifdef F_DUPFD_CLOEXEC
	case F_DUPFD_CLOEXEC:
#endif
	case F_SETFD:
	case F_SETFL:
#ifdef F_SETPIPE_SZ
	case F_SETPIPE_SZ:
#endif
		arg_long = luaL_checkinteger(L, 3);
		lua_pushinteger(L, fcntl(fd, cmd, arg_long));
		lua_pushinteger(L, errno);

		return 2;

	/* commands that take exciting things */
	case F_SETLK:
	case F_SETLKW:
	case F_GETLK:
		luaL_checktype(L, 3, LUA_TTABLE);

		lua_getfield(L, 3, "l_type");
		lua_getfield(L, 3, "l_whence");
		lua_getfield(L, 3, "l_start");
		lua_getfield(L, 3, "l_len");
		flock.l_type = lua_tonumber(L, -4);
		flock.l_whence = lua_tonumber(L, -3);
		flock.l_start = lua_tonumber(L, -2);
		flock.l_len = lua_tonumber(L, -1);
		flock.l_pid = 0;

		lua_pushinteger(L, fcntl(fd, cmd, &flock));
		lua_pushinteger(L, errno);

		if (cmd == F_GETLK) {
			lua_pushnumber(L, flock.l_type);
			lua_pushnumber(L, flock.l_whence);
			lua_pushnumber(L, flock.l_start);
			lua_pushnumber(L, flock.l_len);
			lua_pushnumber(L, flock.l_pid);
			lua_setfield(L, 3, "l_pid");
			lua_setfield(L, 3, "l_len");
			lua_setfield(L, 3, "l_start");
			lua_setfield(L, 3, "l_whence");
			lua_setfield(L, 3, "l_type");
		}

		return 2;

	default:
		lua_pushstring(L, "unhandled fcntl() command");
		lua_error(L);
	}

	return 0; /* never get here, but keep compiler happy */
}

#if _XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L

/*** Predeclare an access pattern for file data
@tparam number fd
@tparam number offset
@tparam number len
@tparam number advice
@treturn errno
@function posix_fadvise
*/
static int
luxio_posix_fadvise(lua_State *L)
{
    int fd = luaL_checkint(L, 1);
    off_t offset = luaL_checkint(L, 2);
    off_t len = luaL_checkint(L, 3);
    int advice = luaL_checkint(L, 4);
    
    lua_pushinteger(L, posix_fadvise(fd, offset, len, advice));
    return 1;
}
#endif

#ifdef _LARGEFILE64_SOURCE
static int
luxio_lseek(lua_State *L) /* 6.5.3 */
{
	int fd = luaL_checkint(L, 1);
	off64_t offset = (off64_t)luaL_checknumber(L, 2); /* 56b is enough! */
	int whence = luaL_checkint(L, 3);

	lua_pushinteger(L, (lua_Number)lseek64(fd, offset, whence));
	lua_pushinteger(L, errno);

	return 2;
}
#else
/*** Reposition read/write file offset.
@tparam number fd
@tparam number offset
@tparam number whence
@treturn number return value
@treturn errno
@function lseek
*/
static int
luxio_lseek(lua_State *L) /* 6.5.3 */
{
	int fd = luaL_checkint(L, 1);
	off_t offset = luaL_checkinteger(L, 2);
	int whence = luaL_checkint(L, 3);

	lua_pushinteger(L, lseek(fd, offset, whence));
	lua_pushinteger(L, errno);

	return 2;
}
#endif

/*** File synchronisation.
@section filesync
*/

/*** Synchronise a file's in-core state with storage device.
@tparam number fd
@treturn number return value
@treturn errno
@function fsync
*/
static int
luxio_fsync(lua_State *L) /* 6.6.1 */
{
	int fildes = luaL_checkinteger(L, 1);

	lua_pushinteger(L, fsync(fildes));
	lua_pushinteger(L, errno);

	return 2;
}

#ifdef HAVE_FDATASYNC
/*** Synchronise only a file's data and not unnessercery metadata.
Not available on all systems.
@tparam number fd
@treturn number return value
@treturn errno
@function fdatasync
*/
static int
luxio_fdatasync(lua_State *L) /* 6.6.2 */
{
	int fildes = luaL_checkinteger(L, 1);

	lua_pushinteger(L, fdatasync(fildes));
	lua_pushinteger(L, errno);

	return 2;
}
#endif

/* 6.7 Asynchronous input and output */

/* TODO: aio_read() 6.7.2 */
/* TODO: aio_write() 6.7.3 */
/* TODO: lio_listio() 6.7.4 */
/* TODO: aio_error() 6.7.5 */
/* TODO: aio_return() 6.7.6 */
/* TODO: aio_cancel() 6.7.7 */
/* TODO: aio_suspend() 6.7.8 */
/* TODO: aio_fsync() 6.7.9 */

/*** General Terminal Interface.
@section genterm
*/

/* TODO: cfgetispeed(), cfgetospeed(), cfsetispeed(), cfsetospeed() 7.1.3 */
/* TODO: tcgetattr(), tcsetattr() 7.2.1 */
/* TODO: tcsendbreak(), tcdrain(), tcflush(), tcflow() 7.2.2 */

/*** Get terminal forground process group.
@tparam number fd
@treturn number return value
@treturn errno
@function tcgetpgrp
*/
static int
luxio_tcgetpgrp(lua_State *L) /* 7.2.3 */
{
	lua_pushinteger(L, tcgetpgrp(luaL_checkinteger(L, 1)));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Set terminal forground process group.
@tparam number fd
@tparam number pgrp_id
@treturn number return value
@treturn errno
@function tcsetpgrp
*/
static int
luxio_tcsetpgrp(lua_State *L) /* 7.2.4 */
{
	int fildes = luaL_checkinteger(L, 1);
	pid_t pgrp_id = luaL_checkinteger(L, 2);

	lua_pushinteger(L, tcsetpgrp(fildes, pgrp_id));
	lua_pushinteger(L, errno);

	return 2;
}

/* 8.1 Referenced C Language Routines ****************************************/

/* These are ANSI C functions POSIX imports.  TODO any Lua doesn't already */

/* 9.1 Database access *******************************************************/

/* TODO: getgrgid(), getgrgid_r(), getgrnam(), getgrnam_r() 9.2.1 */
/* TODO: getpwuid(), getpwuid_r(), getpwnam(), getpwnam_r() 9.2.2 */

/* 10 Data interchange format ************************************************/

/* This is just related to data structures and file formats, not functions */

/* 11 Synchronisation ********************************************************/

/* Semaphores, mutexes, etc should be handled by a dedicated threading lib */

/* 12 Memory management ******************************************************/

/* While it might be interesting to bind mmap and mlock etc, it's difficult to
 * see how this might work in Lua.  Perhaps emulate a string?
 */

/* 13 Execution scheduling ***************************************************/

/* TODO: all of this. */

/*** Clock and timer functions.
@section clocktimer
*/

/* TODO: clock_settime(), clock_gettime(), clock_getres() 14.2.1 */
/* Timer functions excluded, based on signals */

/*** High-resolution sleep.
@tparam number seconds
@tparam number nanoseconds
@treturn number return value
@treturn errno
@treturn number remaining seconds
@treturn number remaining nanosections
@function nanosleep
*/
static int
luxio_nanosleep(lua_State *L) /* 14.2.5 */
{
	struct timespec req, rem = { 0, 0 };

	req.tv_sec = luaL_checkinteger(L, 1);
	req.tv_nsec = luaL_checkinteger(L, 2);

	lua_pushinteger(L, nanosleep(&req, &rem));
	lua_pushinteger(L, errno);
	lua_pushinteger(L, rem.tv_sec);
	lua_pushinteger(L, rem.tv_nsec);

	return 4;
}

/*** Message passing.
POSIX message passing is not available on all platforms.
@section msgpass
*/
#if _POSIX_MESSAGE_PASSING >= 0

#include <mqueue.h>

#define LUXIO_MQ_METATABLE_NAME "luxio.mq"

struct luxio_mq_data {
	mqd_t mq;
	char name[NAME_MAX];
};

static int
luxio__mq_tostring(lua_State *L)
{
	char buf[NAME_MAX + 64];

	struct luxio_mq_data *m =
		luaL_checkudata(L, 1, LUXIO_MQ_METATABLE_NAME);

	sprintf(buf, "<mq %p %s>", (void *)(intptr_t)m->mq, m->name);

	lua_pushstring(L, buf);
	return 1;
}

/*** Open a message queue.
@tparam string name
@tparam number oflag
@tparam[opt] number mode
@treturn mq|number message queue, or return value
@treturn errno
@function mq_open
*/
static int
luxio_mq_open(lua_State *L) /* 15.2.1 */
{
	const char *name = luaL_checkstring(L, 1);
	int oflag = luaL_checkinteger(L, 2);
	mode_t mode = luaL_optinteger(L, 3, INVALID_MODE);
	mqd_t mq;
	struct luxio_mq_data *m;

	if ((oflag & O_CREAT) && mode == INVALID_MODE) {
		lua_pushstring(L, "mq_open with O_CREATE called with no mode");
		lua_error(L);
	}

	if (oflag & O_CREAT) {
		mq = mq_open(name, oflag, mode, NULL);
	} else {
		mq = mq_open(name, oflag);
	}

	if (mq == (mqd_t)-1) {
		lua_pushnumber(L, -1);
		lua_pushinteger(L, errno);

		return 2;
	}

	m = lua_newuserdata(L, sizeof(*m));
	m->mq = mq;
	strncpy(m->name, name, NAME_MAX);

	if (luaL_newmetatable(L, LUXIO_MQ_METATABLE_NAME) != 0) {
		lua_pushcfunction(L, luxio__mq_tostring);
		lua_setfield(L, -2, "__tostring");
	}

	lua_setmetatable(L, -2);
	lua_pushinteger(L, errno);

	return 2;
}

/*** Close a message queue descriptor.
@tparam mq mqdes
@treturn number return value
@treturn errno
@function mq_close
*/
static int
luxio_mq_close(lua_State *L) /* 15.2.2 */
{
	struct luxio_mq_data *m =
		luaL_checkudata(L, 1, LUXIO_MQ_METATABLE_NAME);

	lua_pushinteger(L, mq_close(m->mq));
	lua_pushinteger(L, errno);
	return 2;
}

/*** Remove a message queue.
@tparam string name
@treturn number return value
@treturn errno
@function mq_unlink
*/
static int
luxio_mq_unlink(lua_State *L) /* 15.2.3 */
{
	const char *name = luaL_checkstring(L, 1);

	lua_pushinteger(L, mq_unlink(name));
	lua_pushinteger(L, errno);
	return 2;
}

/*** Send a message to a message queue.
@tparam mq queue
@tparam string message
@tparam number priority
@treturn number return value
@treturn errno
@function mq_send
*/
static int
luxio_mq_send(lua_State *L) /* 15.2.4 */
{
	struct luxio_mq_data *m =
		luaL_checkudata(L, 1, LUXIO_MQ_METATABLE_NAME);
	size_t msg_len;
	const char *msg_ptr = luaL_checklstring(L, 2, &msg_len);
	unsigned int msg_prio = luaL_checkinteger(L, 3);

	lua_pushinteger(L, mq_send(m->mq, msg_ptr, msg_len, msg_prio));
	lua_pushinteger(L, errno);
	return 2;
}


/*** Receive a message from a message queue.
@tparam mq queue
@treturn number return value
@treturn errno
@treturn string|nil message data, or nil in case of error
@treturn number|nil message priority, or nil in case of error
@function mq_receive
*/
static int
luxio_mq_receive(lua_State *L) /* 15.2.5 */
{
	struct luxio_mq_data *m =
		luaL_checkudata(L, 1, LUXIO_MQ_METATABLE_NAME);
	unsigned int msg_prio;
	struct mq_attr attr;

	/* Find out the maximum size of a message */
	if (mq_getattr(m->mq, &attr) == -1) {
		lua_pushinteger(L, -1);
		lua_pushinteger(L, errno);
		return 2;
	} else {
		char msg_ptr[attr.mq_msgsize];
		int r = mq_receive(m->mq, msg_ptr, sizeof(msg_ptr), &msg_prio);
		lua_pushinteger(L, r);
		lua_pushinteger(L, errno);
		if (r == -1) {
			return 2;
		}
		lua_pushlstring(L, msg_ptr, r);
		lua_pushinteger(L, msg_prio);
		return 4;
	}
}

/* TODO: mq_notify() 15.2.6 */

/*** Message queue attributes table.
@field mq_flags 0 or O_NONBLOCK
@field mq_maxmsg Maximum number of messages on queue
@field mq_msgsize Maximum size of message (in bytes)
@field mq_curmsgs Number of messages currently on queue
@table mqattr-table
*/
static int
luxio_make_attr_table(lua_State *L, struct mq_attr *attr)
{
	int top = lua_gettop(L) + 1;

	lua_createtable(L, 0, 4);

#define PUSH_ENTRY(e) do { lua_pushstring(L, "mq_" #e); \
	lua_pushinteger(L, attr->mq_##e); \
	lua_settable(L, top); } while (0)

	PUSH_ENTRY(flags);
	PUSH_ENTRY(maxmsg);
	PUSH_ENTRY(msgsize);
	PUSH_ENTRY(curmsgs);

#undef PUSH_ENTRY

	return 1;
}

/*** Set message queue attributes.
As only the flags can be changed, this does not take a table.
@tparam mq mqdes
@tparam number flags
@treturn number return value
@treturn errno
@treturn mqattr-table new attribute table
@function mq_setattr
*/
static int
luxio_mq_setattr(lua_State *L) /* 15.2.7 */
{
	struct luxio_mq_data *m =
		luaL_checkudata(L, 1, LUXIO_MQ_METATABLE_NAME);
	struct mq_attr mqstat = { luaL_checkinteger(L, 2), 0, 0, 0 };
	struct mq_attr omqstat = { 0, 0, 0, 0 };

	lua_pushinteger(L, mq_setattr(m->mq, &mqstat, &omqstat));
	lua_pushinteger(L, errno);
	luxio_make_attr_table(L, &omqstat);

	return 3;
}

/*** Get message queue attributes.
@tparam mq mqdes
@treturn number return value
@treturn errno
@treturn mqattr-table current queue attributes
@function mq_getattr
*/
static int
luxio_mq_getattr(lua_State *L) /* 15.2.8 */
{
	struct luxio_mq_data *m =
		luaL_checkudata(L, 1, LUXIO_MQ_METATABLE_NAME);
	struct mq_attr mqstat;

	lua_pushinteger(L, mq_getattr(m->mq, &mqstat));
	lua_pushinteger(L, errno);
	luxio_make_attr_table(L, &mqstat);

	return 3;
}

#if _XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L

/*** Send a message to a queue, with a timeout.
Not available on some systems.
@tparam mq queue
@tparam string message
@tparam number priority
@tparam number tv_sec
@tparam number tv_nsec
@treturn number return value
@treturn errno
@function mq_timedsend
*/
/**% mq_timedsend
 * retval = mq_timedsend(mq, msg, len, prio, timeout)
 * retval, errno = mq_timedsend(mq, msg, prio, tv_secs, tv_nsec)
 */
static int
luxio_mq_timedsend(lua_State *L) /* POSIX.1-2001 */
{
	struct luxio_mq_data *m =
		luaL_checkudata(L, 1, LUXIO_MQ_METATABLE_NAME);
	size_t msg_len;
	const char *msg_ptr = luaL_checklstring(L, 2, &msg_len);
	unsigned int msg_prio = luaL_checkinteger(L, 3);
	time_t tv_secs = luaL_checkinteger(L, 4);
	long tv_nsec = luaL_checkinteger(L, 5);
	struct timespec abs_timeout = { tv_secs, tv_nsec };

	lua_pushinteger(L, mq_timedsend(m->mq, msg_ptr, msg_len, msg_prio,
				&abs_timeout));
	lua_pushinteger(L, errno);
	return 2;
}

/*** Receive a message from a message queue, with a timeout
@tparam mq queue
@treturn number return value
@treturn errno
@tparam number tv_sec
@tparam number tv_nsec
@treturn string|nil message data, or nil in case of error
@treturn number|nil message priority, or nil in case of error
@function mq_timedreceive
*/
/**% mq_timedreceive
 * retval = mq_timedsend(mq, bug, len, prio, timeout)
 * retval, errno, msg, prio = mq_timedreceive(mq, tv_secs, tv_nsec)
 */
static int
luxio_mq_timedreceive(lua_State *L) /* POSIX.1-2001 */
{
	struct luxio_mq_data *m =
		luaL_checkudata(L, 1, LUXIO_MQ_METATABLE_NAME);
	unsigned int msg_prio;
	struct mq_attr attr;
	time_t tv_secs = luaL_checkinteger(L, 2);
	long tv_nsec = luaL_checkinteger(L, 3);
	struct timespec abs_timeout = { tv_secs, tv_nsec };

	/* Find out the maximum size of a message */
	if (mq_getattr(m->mq, &attr) == -1) {
		lua_pushinteger(L, -1);
		lua_pushinteger(L, errno);
		return 2;
	} else {
		char msg_ptr[attr.mq_msgsize];
		int r = mq_timedreceive(m->mq, msg_ptr, sizeof(msg_ptr),
				&msg_prio, &abs_timeout);
		lua_pushinteger(L, r);
		lua_pushinteger(L, errno);
		if (r == -1) {
			return 2;
		}
		lua_pushlstring(L, msg_ptr, r);
		lua_pushinteger(L, msg_prio);
		return 4;
	}
}
#endif /* POSIX.1-2001 check */
#endif /* _POSIX_MESSAGE_PASSING */

/* 16 Thread management ******************************************************/

/* Nope: use a threading library. */

/*** Socket handling.
This interface is slightly cooked.  We provide userdata encapsulations for
sockaddr and addrinfo types.  Use `getaddrinfo()` to obtain an addrinfo
object, then use `ipairs()` over it to get each entry to try.

  r, addrinfo = getaddrinfo("www.rjek.com", "80", 0, l.AF_UNSPEC, l.SOCK_STREAM)
  for _, ai in ipairs(addrinfo) do
    sock = socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
    if connect(sock, ai.ai_addr) >= 0 then break end
  end
@section sock
*/

#define LUXIO_SOCKADDR_METATABLE_NAME "luxio.sockaddr"
#ifndef UNIX_PATH_MAX
/* From man 7 unix */
#define UNIX_PATH_MAX   108
#endif

static int
luxio__sockaddr_index(lua_State *L)
{
	struct sockaddr *sa = luaL_checkudata(L, 1, LUXIO_SOCKADDR_METATABLE_NAME);
	const char *var = luaL_checkstring(L, 2);
	if (strcmp(var, "family") == 0) {
		lua_pushnumber(L, sa->sa_family);
		return 1;
	}
	if (sa->sa_family == AF_INET) {
		struct sockaddr_in *sa_in = (struct sockaddr_in *)sa;
		if (strcmp(var, "port") == 0) {
			lua_pushnumber(L, ntohs(sa_in->sin_port));
			return 1;
		} else if (strcmp(var, "address") == 0) {
			char tmp_buf[INET_ADDRSTRLEN];
			lua_pushstring(L, inet_ntop(AF_INET, &sa_in->sin_addr, tmp_buf, INET_ADDRSTRLEN));
			return 1;
		}
	}
	if (sa->sa_family == AF_INET6) {
		struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)sa;
		if (strcmp(var, "port") == 0) {
			lua_pushnumber(L, ntohs(sa_in->sin6_port));
			return 1;
		} else if (strcmp(var, "flowinfo") == 0) {
			lua_pushnumber(L, sa_in->sin6_flowinfo);
			return 1;
		} else if (strcmp(var, "scope_id") == 0) {
			lua_pushnumber(L, sa_in->sin6_scope_id);
			return 1;
		} else if (strcmp(var, "address") == 0) {
			char tmp_buf[INET6_ADDRSTRLEN];
			lua_pushstring(L, inet_ntop(AF_INET6, &sa_in->sin6_addr, tmp_buf, INET6_ADDRSTRLEN));
			return 1;
		}
	}
	if (sa->sa_family == AF_UNIX) {
		struct sockaddr_un *sa_un = (struct sockaddr_un *)sa;
		if (strcmp(var, "path") == 0) {
			lua_pushstring(L, sa_un->sun_path);
			return 1;
		}
	}
	return luaL_error(L, "unknown field %s in sockaddr", var);
}

static int
luxio__sockaddr_tostring(lua_State *L)
{
	struct sockaddr *sa = luaL_checkudata(L, 1, LUXIO_SOCKADDR_METATABLE_NAME);
	if (sa->sa_family == AF_INET) {
		struct sockaddr_in *sa_in = (struct sockaddr_in *)sa;
		char tmp_buf[INET_ADDRSTRLEN];
		inet_ntop(AF_INET, &sa_in->sin_addr, tmp_buf, INET_ADDRSTRLEN);
		lua_pushfstring(L, "sockaddr: AF_INET %d %s", ntohs(sa_in->sin_port), tmp_buf);
	} else if (sa->sa_family == AF_INET6) {
		struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)sa;
		char tmp_buf[INET6_ADDRSTRLEN];
		inet_ntop(AF_INET6, &sa_in->sin6_addr, tmp_buf, INET6_ADDRSTRLEN);
		lua_pushfstring(L, "sockaddr: AF_INET6 %d %s", ntohs(sa_in->sin6_port), tmp_buf);
	} else if (sa->sa_family == AF_UNIX) {
		struct sockaddr_un *sa_un = (struct sockaddr_un *)sa;
		lua_pushfstring(L, "sockaddr: AF_UNIX %s", sa_un->sun_path);
	} else {
		lua_pushfstring(L, "sockaddr: unknown family %d", sa->sa_family);
	}
	return 1;
}

/* Label the userdata on the top of the stack as a sockaddr */
static int
luxio___makesockaddr(lua_State *L)
{
	int create_mt = luaL_newmetatable(L, LUXIO_SOCKADDR_METATABLE_NAME);

	if (create_mt) {
		lua_pushcfunction(L, luxio__sockaddr_index);
		lua_setfield(L, -2, "__index");
		lua_pushcfunction(L, luxio__sockaddr_tostring);
		lua_setfield(L, -2, "__tostring");
	}

	lua_setmetatable(L, -2);

	return 1;
}

/* Copy the given sockaddr and push a userdata onto the stack labelled as a sockaddr */
static int
luxio__makesockaddr(lua_State *L, const struct sockaddr *sa, socklen_t len)
{
	struct sockaddr *sa_copy = lua_newuserdata(L, len);

	memcpy(sa_copy, sa, len);

	return luxio___makesockaddr(L);
}

/* Utility for sizing supported socket addresses */
static socklen_t
luxio___sockaddr_len(lua_State *L, const struct sockaddr *sa)
{
	switch (sa->sa_family) {
	case AF_INET:
		return sizeof(struct sockaddr_in);
	case AF_INET6:
		return sizeof(struct sockaddr_in6);
	case AF_UNIX:
		return SUN_LEN((struct sockaddr_un *)sa);
	}

	return luaL_error(L, "unknown address family %d", sa->sa_family);
}

static int
luxio_makesockaddr(lua_State *L)
{
	int family = luaL_checkinteger(L, 1);
	if (family == AF_INET) {
		struct sockaddr_in *sa_in;
		int port = luaL_checkinteger(L, 2);
		const char *address = luaL_checkstring(L, 3);
		sa_in = lua_newuserdata(L, sizeof(*sa_in));
		if (inet_pton(AF_INET, address, &sa_in->sin_addr) != 1) {
			return luaL_error(L, "unable to parse address: %s", address);
		}
		if (port < 0 || port > 65535) {
			return luaL_error(L, "port %d out of range", port);
		}
		sa_in->sin_family = AF_INET;
		sa_in->sin_port = htons(port);
		return luxio___makesockaddr(L);
	}
	if (family == AF_INET6) {
		struct sockaddr_in6 *sa_in;
		int port = luaL_checkinteger(L, 2);
		const char *address = luaL_checkstring(L, 3);
		sa_in = lua_newuserdata(L, sizeof(*sa_in));
		if (inet_pton(AF_INET6, address, &sa_in->sin6_addr) != 1) {
			return luaL_error(L, "unable to parse address: %s", address);
		}
		if (port < 0 || port > 65535) {
			return luaL_error(L, "port %d out of range", port);
		}
		/* TODO: Support flow and scope */
		sa_in->sin6_family = AF_INET6;
		sa_in->sin6_port = htons(port);
		sa_in->sin6_flowinfo = 0;
		sa_in->sin6_scope_id = 0;
		return luxio___makesockaddr(L);
	}
	if (family == AF_UNIX) {
		struct sockaddr_un *sa_un;
		size_t pathlen;
		const char *path = luaL_checklstring(L, 2, &pathlen);
		if (pathlen >= UNIX_PATH_MAX) {
			return luaL_error(L, "unable to create local socket, path too long (%d chars)",
					  pathlen);
		}
		sa_un = lua_newuserdata(L, sizeof(sa_un->sun_family) + pathlen + 1);
		sa_un->sun_family = AF_UNIX;
		strcpy(&sa_un->sun_path[0], path);
		return luxio___makesockaddr(L);
	}
	return luaL_error(L, "unknown socket family %d", family);
}

/**% socket
 * retval = socket(domain, type, protocol);
 * retval, errno = socket(domain, type, protocol)
 */
/*** Create an endpoint for communication.
@tparam number domain
@tparam number type
@tparam number protocol
@treturn number return value
@treturn errno
@function socket
*/
static int
luxio_socket(lua_State *L)
{
	int domain = luaL_checkint(L, 1);
	int type = luaL_checkint(L, 2);
	int protocol = luaL_checkint(L, 3);

	lua_pushinteger(L, socket(domain, type, protocol));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Listen for connections on a socket.
@tparam number sockfd
@tparam number backlog
@treturn number return value
@treturn errno
@function listen
*/
static int
luxio_listen(lua_State *L)
{
	int sockfd = luaL_checkint(L, 1);
	int backlog = luaL_checkint(L, 2);

	lua_pushinteger(L, listen(sockfd, backlog));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Shut down part of a full-duplex connection.
@tparam number sockfd
@tparam number how
@treturn number return value
@treturn errno
@function shutdown
*/
static int
luxio_shutdown(lua_State *L)
{
	int sockfd = luaL_checkint(L, 1);
	int how = luaL_checkint(L, 2);

	lua_pushinteger(L, shutdown(sockfd, how));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Initiate a connection on a socket.
@tparam number fd
@tparam sockaddr sockaddr
@treturn number return value
@treturn errno
@function connect
*/
static int
luxio_connect(lua_State *L)
{
	int sockfd = luaL_checkint(L, 1);
	struct sockaddr *addr = luaL_checkudata(L, 2, LUXIO_SOCKADDR_METATABLE_NAME);
	socklen_t l = luxio___sockaddr_len(L, addr);

	lua_pushinteger(L, connect(sockfd, addr, l));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Bind a name to a socket.
@tparam number fd
@tparam sockaddr sockaddr
@treturn number return value
@treturn errno
@function bind
*/
static int
luxio_bind(lua_State *L)
{
	int sockfd = luaL_checkint(L, 1);
	struct sockaddr *addr = luaL_checkudata(L, 2, LUXIO_SOCKADDR_METATABLE_NAME);
	socklen_t l = luxio___sockaddr_len(L, addr);

	lua_pushinteger(L, bind(sockfd, addr, l));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Accept a connection on a socket.
@tparam number fd
@treturn number return value
@treturn errno|sockaddr
@function accept
*/
static int
luxio_accept(lua_State *L)
{
	int listenfd = luaL_checkint(L, 1);
	int clientfd;
	struct sockaddr_storage addr;
	socklen_t l = sizeof(addr);

	clientfd = accept(listenfd, (struct sockaddr *)&addr, &l);

	lua_pushinteger(L, clientfd);

	if (clientfd > -1) {
		luxio__makesockaddr(L, (const struct sockaddr *)&addr, l);
	} else {
		lua_pushinteger(L, errno);
	}

	return 2;
}

/*** Get options on a socket.
@tparam number fd
@tparam number level
@tparam number optname
@treturn number return value
@treturn errno|number|string
@function getsockopt
*/
static int
luxio_getsockopt(lua_State *L)
{
	int sockfd = luaL_checkint(L, 1);
	int level = luaL_checkint(L, 2);
	int optname = luaL_checkint(L, 3);
	int res, r_int;
	char r_ifname[IFNAMSIZ];
	socklen_t l;

	switch (level) {
	case SOL_SOCKET:
		switch (optname) {
		/* options that involve strings */
#ifdef SO_BINDTODEVICE
		case SO_BINDTODEVICE:
#endif
			l = IFNAMSIZ;
			res = getsockopt(sockfd, level, optname, r_ifname, &l);
			lua_pushinteger(L, res);
			if (res == -1) {
				lua_pushinteger(L, errno);
			} else {
				lua_pushstring(L, r_ifname);
			}

			return 2;

                /* other options probably expect integers */
		default:
			l = sizeof(r_int);
			res = getsockopt(sockfd, level, optname, &r_int, &l);
			lua_pushinteger(L, res);
			if (res == -1) {
				lua_pushinteger(L, errno);
			} else {
				lua_pushinteger(L, r_int);
			}

			return 2;
		}
	case IPPROTO_IP:
		switch (optname) {
#ifdef TCP_CORK
		case TCP_CORK:
#endif
#ifdef TCP_DEFER_ACCEPT
		case TCP_DEFER_ACCEPT:
#endif
#ifdef TCP_NODELAY
		case TCP_NODELAY:
#endif
			l = sizeof(r_int);
			res = getsockopt(sockfd, level, optname, &r_int, &l);
			lua_pushinteger(L, res);
			if (res == -1) {
				lua_pushinteger(L, errno);
			} else {
				lua_pushinteger(L, r_int);
			}

			return 2;

		default:
			return luaL_error(L, "unhandled IPPROTO_IP option %d",
					  optname);
		}
	}

	return luaL_error(L, "unhandled socket level %d", level);
}

/*** Set an option on a socket.
@tparam number fd
@tparam number level
@tparam number optname
@param optvalue
@treturn number return value
@treturn errno
@function setsockopt
*/
static int
luxio_setsockopt(lua_State *L)
{
	int sockfd = luaL_checkint(L, 1);
	int level = luaL_checkint(L, 2);
	int optname = luaL_checkint(L, 3);
	int res, r_int;
	const char *r_ifname;
	socklen_t l;
	size_t sz;

	switch (level) {
	case SOL_SOCKET:
		switch (optname) {
		/* options that involve strings */
#ifdef SO_BINDTODEVICE
		case SO_BINDTODEVICE:
#endif
			r_ifname = luaL_checklstring(L, 4, &sz);
			res = setsockopt(sockfd, level, optname,
					 (void *)r_ifname, (socklen_t)sz);
			lua_pushinteger(L, res);
			lua_pushinteger(L, errno);

			return 2;
		/* other options are probably integers */
		default:
			l = sizeof(r_int);
			r_int = luaL_checkint(L, 4);
			res = setsockopt(sockfd, level, optname, &r_int, l);
			lua_pushinteger(L, res);
			lua_pushinteger(L, errno);

			return 2;
		}
	case IPPROTO_IP:
		switch (optname) {
#ifdef TCP_CORK
		case TCP_CORK:
#endif
#ifdef TCP_DEFER_ACCEPT
		case TCP_DEFER_ACCEPT:
#endif
#ifdef TCP_NODELAY
		case TCP_NODELAY:
#endif
			l = sizeof(r_int);
			r_int = luaL_checkint(L, 4);
			res = setsockopt(sockfd, level, optname, &r_int, l);
			lua_pushinteger(L, res);
			lua_pushinteger(L, errno);

			return 2;

		default:
			return luaL_error(L, "unhandled IPPROTO_IP option %d",
					  optname);
		}
	}

	return luaL_error(L, "unhandled socket level %d", level);
}

/*** Convert getaddrinfo-specific errors to strings.
@tparam errno errno
@treturn string error string
@function gai_strerror
*/
static int
luxio_gai_strerror(lua_State *L)
{
	lua_pushstring(L, gai_strerror(luaL_checkint(L, 1)));

	return 1;
}

/*** Result table from `getaddrinfo`.
@field ai_flags number
@field ai_family number
@field ai_socktype number
@field ai_protocol number
@field ai_canonname string
@field ai_addr sockaddr type containing address information.
@table addrinfo
*/

/*** Network address and service translation.
@tparam string node
@tparam string service
@tparam[opt=0] number ai_flags
@tparam[opt=AF_UNSPEC] number ai_family
@tparam[opt=0] number ai_socktype
@tparam[opt=0] number ai_protocol
@treturn number return value
@treturn errno|table table of result `addrinfo` entries
@function getaddrinfo
*/
static int
luxio_getaddrinfo(lua_State *L)
{
	const char *node = luaL_checkstring(L, 1);
	const char *serv = luaL_checkstring(L, 2);
	struct addrinfo hints, *results, *rp;
	int r, c;

	memset(&hints, '\0', sizeof(hints));
	hints.ai_flags = luaL_optint(L, 3, 0);
	hints.ai_family = luaL_optint(L, 4, AF_UNSPEC);
	hints.ai_socktype = luaL_optint(L, 5, 0);
	hints.ai_protocol = luaL_optint(L, 6, 0);

	if (node[0] == '\0')
		node = NULL;

	if (serv[0] == '\0')
		serv = NULL;

	r = getaddrinfo(node, serv, &hints, &results);

	lua_pushinteger(L, r);

	if (r < 0)
		return 1;

	lua_newtable(L); /* table we return with entries */

	for (rp = results, c = 1; rp != NULL; rp = rp->ai_next, c++) {
		lua_createtable(L, 0, 6); /* entry table */

		lua_pushliteral(L, "ai_flags");
		lua_pushinteger(L, rp->ai_flags);
		lua_rawset(L, -3);

		lua_pushliteral(L, "ai_family");
		lua_pushinteger(L, rp->ai_family);
		lua_rawset(L, -3);

		lua_pushliteral(L, "ai_socktype");
		lua_pushinteger(L, rp->ai_socktype);
		lua_rawset(L, -3);

		lua_pushliteral(L, "ai_protocol");
		lua_pushinteger(L, rp->ai_protocol);
		lua_rawset(L, -3);

		lua_pushliteral(L, "ai_canonname");
		lua_pushstring(L, rp->ai_canonname);
		lua_rawset(L, -3);

		lua_pushliteral(L, "ai_addr");
		luxio__makesockaddr(L, rp->ai_addr, rp->ai_addrlen);
		lua_rawset(L, -3);

		lua_rawseti(L, -2, c);
	}

	freeaddrinfo(results);

	return 2;
}

/*** Socket-related send and receive functions.
@section socksendrecv
*/

/*** Send a message on a socket.
@tparam number fd
@tparam string data
@tparam[opt=0] number flags
@treturn number return value
@treturn errno
@function send
*/
static int
luxio_send(lua_State *L)
{
    int fd = luaL_checkint(L, 1);
    size_t count;
    const char *buf = luaL_checklstring(L, 2, &count);
    int flags = luaL_optint(L, 3, 0);
    
    lua_pushinteger(L, send(fd, buf, count, flags));
    lua_pushinteger(L, errno);
    
    return 2;
}

/*** Send a message on a socket to a specific destination.
@tparam number fd
@tparam string data
@tparam[opt=0] number flags
@tparam sockaddr sockaddr
@treturn number return value
@treturn errno
@function sendto
*/
static int
luxio_sendto(lua_State *L)
{
    int fd = luaL_checkint(L, 1);
    size_t count;
    const char *buf = luaL_checklstring(L, 2, &count);
    int flags = luaL_optint(L, 3, 0);
    struct sockaddr *addr = luaL_checkudata(L, 4, LUXIO_SOCKADDR_METATABLE_NAME);
    socklen_t l = luxio___sockaddr_len(L, addr);

    lua_pushinteger(L, sendto(fd, buf, count, flags, addr, l));
    lua_pushinteger(L, errno);
    
    return 2;
}

/*** Receive a message from a socket.
@tparam number fd
@tparam number count
@tparam[opt=0] number flags
@treturn number|string return value if error, otherwise string
@treturn errno
@function recv
*/
static int
luxio_recv(lua_State *L)
{
    int fd = luaL_checkint(L, 1);
    int count = luaL_checkint(L, 2);
    int flags = luaL_optint(L, 3, 0);
    ssize_t result;
    char *buf = malloc(count);
    
    if (buf == NULL) {
        lua_pushstring(L, "unable to allocate read buffer: memory exhausted");
        lua_error(L);
    }
    
    result = recv(fd, buf, count, flags);
    
    if (result == -1) {
        lua_pushinteger(L, result);
        lua_pushinteger(L, errno);
    } else {
        /* sadly there appears to be no way to avoid this copy.
         * luaL_Buffer actually builds things on the C stack bytes at a time,
         * and there is no way to pre-allocate a Lua type other than a
         * userdatum.  Additionally, should Lua call its panic function because
         * it can't allocate memory to copy this into, our buf will be leaked.
         * We could perhaps fix this with a lot of faff, involving creating
         * a userdatum for our buffer, and setting a __gc metamethod.
         */
        lua_pushlstring(L, buf, result);
        lua_pushinteger(L, errno);
    }

    free(buf);

    return 2;
}

/*** Receive a message from a socket, also returning sender information.
@tparam number fd
@tparam number count
@tparam[opt=0] number flags
@treturn number|string return value if error, otherwise string
@treturn errno
@treturn sockaddr|nil
@function recvfrom
*/
static int
luxio_recvfrom(lua_State *L)
{
    int fd = luaL_checkint(L, 1);
    int count = luaL_checkint(L, 2);
    int flags = luaL_optint(L, 3, 0);
    struct sockaddr_storage addr;
    socklen_t l = sizeof(addr);
    ssize_t result;
    char *buf = malloc(count);
    
    if (buf == NULL) {
        lua_pushstring(L, "unable to allocate read buffer: memory exhausted");
        lua_error(L);
    }
    
    result = recvfrom(fd, buf, count, flags, (struct sockaddr *)&addr, &l);
    
    if (result == -1) {
        free(buf);
        lua_pushinteger(L, result);
        lua_pushinteger(L, errno);
        return 2;
    }
    
    /* sadly there appears to be no way to avoid this copy.
     * luaL_Buffer actually builds things on the C stack bytes at a time,
     * and there is no way to pre-allocate a Lua type other than a
     * userdatum.  Additionally, should Lua call its panic function because
     * it can't allocate memory to copy this into, our buf will be leaked.
     * We could perhaps fix this with a lot of faff, involving creating
     * a userdatum for our buffer, and setting a __gc metamethod.
     */
    lua_pushlstring(L, buf, result);
    free(buf);
    lua_pushinteger(L, errno);
    luxio__makesockaddr(L, (const struct sockaddr *)&addr, l);
    
    return 3;
}

/*** Poll-binding functions.
@section poll
*/

#define LUXIO_TIMEVAL_METATABLE "luxio.timeval"

#define LUXIO_POLLFD_METATABLE "luxio.pollfdarray"
#define LUXIO_FD_SET_METATABLE "luxio.fd_set"

typedef struct {
	fd_set *fd_set;
	int allocated;
} luxio_fd_set;

typedef struct {
	struct pollfd *pollfds;
	int allocated;
} luxio_pollfds;

static int
luxio__fd_set_gc(lua_State *L)
{
	luxio_fd_set *fs = luaL_checkudata(L, 1, LUXIO_FD_SET_METATABLE);
	free(fs->fd_set);
	fs->fd_set = NULL;
	fs->allocated = 0;

	return 0;
}

static int
luxio__fd_set_tostring(lua_State *L)
{
	luxio_fd_set *fs = luaL_checkudata(L, 1, LUXIO_FD_SET_METATABLE);
	char out[FD_SETSIZE * 10];
	char s[100];
	int i, found = 0, total_set = 0;

	for (i = 0; i < FD_SETSIZE; i++) {
		if (FD_ISSET(i, fs->fd_set)) {
			total_set++;
		}
	}

	if (total_set == 0) {
		lua_pushstring(L, "{}");
		return 1;
	}

	sprintf(out, "{");
	for (i = 0; i < FD_SETSIZE; i++) {
		if (FD_ISSET(i, fs->fd_set)) {
			sprintf(s, ++found < total_set ? "%d, " : "%d}", i);
			strcat(out, s);
		}
	}

	lua_pushstring(L, out);

	return 1;
}

static int
luxio__fd_set_len(lua_State *L)
{
	luxio_fd_set *fs = luaL_checkudata(L, 1, LUXIO_FD_SET_METATABLE);
	lua_pushnumber(L, fs->allocated);
	return 1;
}

static int
luxio__pollfds_gc(lua_State *L)
{
	luxio_pollfds *pfds = luaL_checkudata(L, 1, LUXIO_POLLFD_METATABLE);
	free(pfds->pollfds);
	pfds->pollfds = NULL;
	pfds->allocated = 0;
	return 0;
}

static int
luxio__pollfds_tostring(lua_State *L)
{
	luxio_pollfds *pfds = luaL_checkudata(L, 1, LUXIO_POLLFD_METATABLE);
	lua_pushfstring(L, "pollfds: %d slot%s", pfds->allocated, pfds->allocated == 1 ? "" : "s");
	return 1;
}

static int
luxio__pollfds_len(lua_State *L)
{
	luxio_pollfds *pfds = luaL_checkudata(L, 1, LUXIO_POLLFD_METATABLE);
	lua_pushnumber(L, pfds->allocated);
	return 1;
}

static int
luxio_pollfds_new(lua_State *L)
{
	luxio_pollfds *pfds = lua_newuserdata(L, sizeof(*pfds));
	int create_table = luaL_newmetatable(L, LUXIO_POLLFD_METATABLE);
	pfds->pollfds = NULL;
	pfds->allocated = 0;

	if (create_table) {
		lua_pushcfunction(L, luxio__pollfds_gc);
		lua_setfield(L, -2, "__gc");
		lua_pushcfunction(L, luxio__pollfds_tostring);
		lua_setfield(L, -2, "__tostring");
		lua_pushcfunction(L, luxio__pollfds_len);
		lua_setfield(L, -2, "__len");
	}

	lua_setmetatable(L, -2);

	return 1;
}

static int
luxio_FD_CLR(lua_State *L)
{
	int fd = luaL_checkint(L, 1);
	luxio_fd_set *fs = luaL_checkudata(L, 2, LUXIO_FD_SET_METATABLE);

	FD_CLR(fd, fs->fd_set);

	return 0;
}

static int
luxio_FD_SET(lua_State *L)
{
	int fd = luaL_checkint(L, 1);
	luxio_fd_set *fs = luaL_checkudata(L, 2, LUXIO_FD_SET_METATABLE);

	FD_SET(fd, fs->fd_set);

	return 0;
}

static int
luxio_FD_ISSET(lua_State *L)
{
	int fd = luaL_checkint(L, 1);
	luxio_fd_set *fs = luaL_checkudata(L, 2, LUXIO_FD_SET_METATABLE);

	lua_pushboolean(L, FD_ISSET(fd, fs->fd_set));

	return 1;
}

static int
luxio_FD_ZERO(lua_State *L)
{
	luxio_fd_set *fs = luaL_checkudata(L, 1, LUXIO_FD_SET_METATABLE);

	FD_ZERO(fs->fd_set);

	return 0;
}

static int
luxio_fd_set_new(lua_State *L)
{
	luxio_fd_set *fs = lua_newuserdata(L, sizeof(*fs));
	int create_table = luaL_newmetatable(L, LUXIO_FD_SET_METATABLE);
	fs->fd_set = NULL;
	fs->allocated = 0;

	if (create_table) {
		lua_pushcfunction(L, luxio__fd_set_gc);
		lua_setfield(L, -2, "__gc");
		lua_pushcfunction(L, luxio__fd_set_tostring);
		lua_setfield(L, -2, "__tostring");
		lua_pushcfunction(L, luxio__fd_set_len);
		lua_setfield(L, -2, "__len");
	}

	lua_setmetatable(L, -2);

	return 1;
}

static int
luxio_fd_set_resize(lua_State *L)
{
	luxio_fd_set *fs = luaL_checkudata(L, 1, LUXIO_FD_SET_METATABLE);
	int desired_size = luaL_checkint(L, 2);
	int idx;
	fd_set *new_fs = realloc(fs->fd_set, sizeof(fd_set) * desired_size);
	if (new_fs != NULL) {
		if (desired_size > fs->allocated) {
			for (idx = fs->allocated; idx < desired_size; ++idx) {
				memset(new_fs + idx, 0, sizeof(*new_fs));
			}
		}

		fs->fd_set = new_fs;
		fs->allocated = desired_size;
	} else {
		return luaL_error(L, "Unable to resize fd_set array");
	}
	/* Return the fd_set array for neatness */
	return 1;
}

static int
luxio_pollfds_resize(lua_State *L)
{
	luxio_pollfds *pfds = luaL_checkudata(L, 1, LUXIO_POLLFD_METATABLE);
	int desired_size = luaL_checkint(L, 2);
	int idx;
	struct pollfd *newfds = realloc(pfds->pollfds, sizeof(struct pollfd) * desired_size);
	if (newfds != NULL) {
		if (desired_size > pfds->allocated) {
			for (idx = pfds->allocated; idx < desired_size; ++idx) {
				newfds[idx].fd = -1;
				newfds[idx].events = newfds[idx].revents = 0;
			}
		}
		pfds->pollfds = newfds;
		pfds->allocated = desired_size;
	} else {
		return luaL_error(L, "Unable to resize pollfds array");
	}
	/* Return the pollfds array for neatness */
	return 1;
}

static int
luxio_pollfds_set_slot(lua_State *L)
{
	luxio_pollfds *pfds = luaL_checkudata(L, 1, LUXIO_POLLFD_METATABLE);
	int slot = luaL_checkint(L, 2);
	int fd = luaL_checkint(L, 3);
	short events = luaL_checkint(L, 4);
	short revents;
	if (slot == 0 || slot > pfds->allocated || slot < -pfds->allocated) {
		return luaL_error(L, "slot out of range 1 .. %d", pfds->allocated);
	}

	revents = luaL_optint(L, 4, pfds->pollfds[slot - 1].revents);

	pfds->pollfds[slot - 1].fd = fd;
	pfds->pollfds[slot - 1].events = events;
	pfds->pollfds[slot - 1].revents = revents;

	return 0;
}

static int
luxio_pollfds_get_slot(lua_State *L)
{
	luxio_pollfds *pfds = luaL_checkudata(L, 1, LUXIO_POLLFD_METATABLE);
	int slot = luaL_checkint(L, 2);

	if (slot == 0 || slot > pfds->allocated || slot < -pfds->allocated) {
		return luaL_error(L, "slot out of range 1 .. %d", pfds->allocated);
	}

	lua_pushnumber(L, pfds->pollfds[slot - 1].fd);
	lua_pushnumber(L, pfds->pollfds[slot - 1].events);
	lua_pushnumber(L, pfds->pollfds[slot - 1].revents);
	return 3;
}

static int
luxio_poll(lua_State *L)
{
	luxio_pollfds *pfds = luaL_checkudata(L, 1, LUXIO_POLLFD_METATABLE);
	int timeout = luaL_checkint(L, 2);

	lua_pushinteger(L, poll(pfds->pollfds, pfds->allocated, timeout));
	lua_pushinteger(L, errno);

	return 2;
}

static int
luxio_select(lua_State *L)
{
	int nfds = luaL_checkint(L, 1);
	luxio_fd_set *readfds = luaL_testudata(L, 2, LUXIO_FD_SET_METATABLE);
	luxio_fd_set *writefds = luaL_testudata(L, 3, LUXIO_FD_SET_METATABLE);
	luxio_fd_set *exceptfds = luaL_testudata(L, 4, LUXIO_FD_SET_METATABLE);
	struct timeval *timeout = luaL_testudata(L, 5, LUXIO_TIMEVAL_METATABLE);

	lua_pushinteger(L, select(nfds,
		readfds != NULL ? readfds->fd_set : NULL,
		writefds != NULL ? writefds->fd_set : NULL,
		exceptfds != NULL ? exceptfds->fd_set : NULL,
		timeout));
	lua_pushinteger(L, errno);

	return 2;
}

/*** Bit and flag operation functions.
@section bit
*/

static int
luxio_bitop_or(lua_State *L)
{
	int value = luaL_checkint(L, 1);
	int n = lua_gettop(L);

	while (n > 1) {
		value |= luaL_checkint(L, n--);
	}

	lua_pushnumber(L, value);

	return 1;
}

static int
luxio_bitop_and(lua_State *L)
{
	int value = luaL_checkint(L, 1);
	int n = lua_gettop(L);

	while (n > 1) {
		value &= luaL_checkint(L, n--);
	}

	lua_pushnumber(L, value);

	return 1;
}

static int
luxio_bitop_clear(lua_State *L)
{
	int value = luaL_checkint(L, 1);
	int n = lua_gettop(L);

	while (n > 1) {
		value &= ~luaL_checkint(L, n--);
	}

	lua_pushnumber(L, value);

	return 1;
}

static int
luxio_bitop_invert(lua_State *L)
{
	int value = luaL_checkint(L, 1);
	int n = lua_gettop(L);

	/* Special case, passed 1 value, we invert that rather than
	 * inverting the other bits supplied
	 */
	if (n == 1) {
		value = ~value;
	} else {
		while (n > 1) {
		     value ^= luaL_checkint(L, n--);
		}
	}

	lua_pushnumber(L, value);

	return 1;
}

static int
luxio_bitop_test(lua_State *L)
{
	int value = luaL_checkint(L, 1);
	int goal = 0;
	int n = lua_gettop(L);

	while (n > 1) {
		goal |= luaL_checkint(L, n--);
	}

	lua_pushboolean(L, (value & goal) == goal);

	return 1;
}

/*** Time-related functions.
The time-related functions in Luxio are medium-rare.  A timeval type is exposed
as a userdata type, complete with comparison, addition/subtraction, and tostring
metamethods.  You can set the fields tv_sec, tv_usec, seconds, and useconds.
@section time
*/

static int
luxio_timeval_lt(lua_State *L)
{
	struct timeval *a = luaL_checkudata(L, 1, LUXIO_TIMEVAL_METATABLE);
	struct timeval *b = luaL_checkudata(L, 2, LUXIO_TIMEVAL_METATABLE);

	lua_pushboolean(L, timercmp(a, b, <));

	return 1;
}

static int
luxio_timeval_le(lua_State *L)
{
	struct timeval *a = luaL_checkudata(L, 1, LUXIO_TIMEVAL_METATABLE);
	struct timeval *b = luaL_checkudata(L, 2, LUXIO_TIMEVAL_METATABLE);

	/* <= is not portable, so use ! > */
	lua_pushboolean(L, !timercmp(a, b, >));

	return 1;
}

static int
luxio_timeval_eq(lua_State *L)
{
	struct timeval *a = luaL_checkudata(L, 1, LUXIO_TIMEVAL_METATABLE);
	struct timeval *b = luaL_checkudata(L, 2, LUXIO_TIMEVAL_METATABLE);

	/* == is not portable, so use ! != */
	lua_pushboolean(L, !timercmp(a, b, !=));

	return 1;
}

#define LUXIO_TIME_BUFLEN (1024)
static int
luxio_timeval_tostring(lua_State *L)
{
	struct timeval *a = luaL_checkudata(L, 1, LUXIO_TIMEVAL_METATABLE);
	char buffer[LUXIO_TIME_BUFLEN];

	snprintf(buffer, LUXIO_TIME_BUFLEN, "timeval: %ld.%06ld",
		 (long)a->tv_sec, (long)a->tv_usec);

	lua_pushstring(L, buffer);

	return 1;
}

static int
luxio_timeval_index(lua_State *L)
{
	struct timeval *a = luaL_checkudata(L, 1, LUXIO_TIMEVAL_METATABLE);
	const char *s = luaL_checkstring(L, 2);

	if (strcmp(s, "tv_sec") == 0)
		lua_pushinteger(L, a->tv_sec);
	else if (strcmp(s, "tv_usec") == 0)
		lua_pushinteger(L, a->tv_usec);
	else if (strcmp(s, "seconds") == 0)
		lua_pushnumber(L, (lua_Number)(a->tv_sec) +
			       ((lua_Number)(a->tv_usec) / 1000000));
	else if (strcmp(s, "useconds") == 0)
		lua_pushinteger(L, a->tv_usec + (a->tv_sec * 1000000));
	else
		luaL_error(L, "Unknown field %s in timeval", s);

	return 1;
}

static int
luxio_timeval_newindex(lua_State *L)
{
	struct timeval *a = luaL_checkudata(L, 1, LUXIO_TIMEVAL_METATABLE);
	const char *s = luaL_checkstring(L, 2);

	if (strcmp(s, "tv_sec") == 0)
		a->tv_sec = luaL_checkinteger(L, 3);
	else if (strcmp(s, "tv_usec") == 0)
		a->tv_usec = luaL_checkinteger(L, 3);
	else if (strcmp(s, "seconds") == 0) {
		lua_Number v = luaL_checknumber(L, 3);
		a->tv_sec = (time_t)v;
		a->tv_usec = (suseconds_t)((v - a->tv_sec) * 1000000);
	} else if (strcmp(s, "useconds") == 0) {
		lua_Number v = luaL_checknumber(L, 3);
		a->tv_sec = (time_t)(v / 1000000);
		a->tv_usec = (suseconds_t)v % 1000000;
	} else
		luaL_error(L, "Unknown field %s in timeval", s);

	return 0;
}

static void luxio__bless_timeval(lua_State *L);

static int
luxio_timeval_add(lua_State *L)
{
	struct timeval *a = luaL_checkudata(L, 1, LUXIO_TIMEVAL_METATABLE);
	struct timeval *b = luaL_checkudata(L, 2, LUXIO_TIMEVAL_METATABLE);
	struct timeval *ret = lua_newuserdata(L, sizeof(*ret));

	timeradd(a, b, ret);

	luxio__bless_timeval(L);

	return 1;
}

static int
luxio_timeval_sub(lua_State *L)
{
	struct timeval *a = luaL_checkudata(L, 1, LUXIO_TIMEVAL_METATABLE);
	struct timeval *b = luaL_checkudata(L, 2, LUXIO_TIMEVAL_METATABLE);
	struct timeval *ret = lua_newuserdata(L, sizeof(*ret));

	timersub(a, b, ret);

	luxio__bless_timeval(L);

	return 1;
}

static void
luxio__bless_timeval(lua_State *L)
{
	int create = luaL_newmetatable(L, LUXIO_TIMEVAL_METATABLE);

	if (create) {
		lua_pushcfunction(L, luxio_timeval_le);
		lua_setfield(L, -2, "__le");
		lua_pushcfunction(L, luxio_timeval_lt);
		lua_setfield(L, -2, "__lt");
		lua_pushcfunction(L, luxio_timeval_eq);
		lua_setfield(L, -2, "__eq");
		lua_pushcfunction(L, luxio_timeval_tostring);
		lua_setfield(L, -2, "__tostring");
		lua_pushcfunction(L, luxio_timeval_index);
		lua_setfield(L, -2, "__index");
		lua_pushcfunction(L, luxio_timeval_newindex);
		lua_setfield(L, -2, "__newindex");
		lua_pushcfunction(L, luxio_timeval_add);
		lua_setfield(L, -2, "__add");
		lua_pushcfunction(L, luxio_timeval_sub);
		lua_setfield(L, -2, "__sub");
	}

	lua_setmetatable(L, -2);
}

/*** Create a new timeval, set to the epoch.
@treturn timeval
@function zero_timeval
*/
static int
luxio_timeval_zero(lua_State *L)
{
	struct timeval *r = lua_newuserdata(L, sizeof(*r));

	timerclear(r);

	luxio__bless_timeval(L);

	return 1;
}

/*** Get the time of day.
@treturn timeval|number return value
@treturn errno
@function gettimeofday
*/
static int
luxio_gettimeofday(lua_State *L)
{
	struct timeval *r = lua_newuserdata(L, sizeof(*r));

	int ret = gettimeofday(r, NULL);

	if (ret == -1) {
		lua_pushinteger(L, -1);
		lua_pushinteger(L, errno);
		return 2;
	}

	luxio__bless_timeval(L);

	return 1;
}

/*** Misc utility functions.
@section misc
*/

/*** Return a string describing an error number.
@tparam errno errno
@treturn string
@function strerror
*/
static int
luxio_strerror(lua_State *L)
{
	lua_pushstring(L, strerror(luaL_checkint(L, 1)));

	return 1;
}

static char *luxio_openlog_ident = NULL;

/*** Open a log file.
@tparam string ident
@tparam number option
@tparam number facility
@function openlog
*/
static int
luxio_openlog(lua_State *L)
{
	size_t len;
	const char *ident = luaL_checklstring(L, 1, &len);
	int option = luaL_checkint(L, 2);
	int facility = luaL_checkint(L, 3);

	/* openlog doesn't make its own copy of ident
	 * and lua could garbage collect ident
	 * so take a copy of ident
	 */
	free(luxio_openlog_ident);
	luxio_openlog_ident = malloc(len);
	strncpy(luxio_openlog_ident, ident, len);

	openlog(ident, option, facility);

	return 0;
}

/*** Write a message to the open log.
@tparam number priority
@tparam string log message
@function syslog
*/
static int
luxio_syslog(lua_State *L)
{
	int priority = luaL_checkint(L, 1);
	const char *msg = luaL_checkstring(L, 2);

	syslog(priority, "%s", msg);

	return 0;
}

/*** Close the open log.
@function closelog
*/
static int
luxio_closelog(lua_State *L)
{
	free(luxio_openlog_ident);
	luxio_openlog_ident = NULL;
	closelog();

	return 0;
}

/*** Set the log priority mask.
@tparam number newmask
@tparam number old mask
@function setlogmask
*/
static int
luxio_setlogmask(lua_State *L)
{
	int mask = luaL_checkint(L, 1);

	int oldmask = setlogmask(mask);
	lua_pushinteger(L, oldmask);

	return 1;
}

/*** Discover the bit used for a specific priority.
@tparam number priority
@treturn number mask
@function LOG_MASK
*/
static int
luxio_LOG_MASK(lua_State *L)
{
	int priority = luaL_checkint(L, 1);

	int mask = LOG_MASK(priority);
	lua_pushinteger(L, mask);

	return 1;
}

/*** Character set conversion.
@section iconv
*/

#define LUXIO_ICONV_METATABLE "luxio.iconv"

static int
luxio__iconv_gc(lua_State *L)
{
	iconv_t *ic = (iconv_t*)(lua_touserdata(L, 1));
	if (*ic != NULL && *ic != (iconv_t)(-1)) {
		iconv_close(*ic);
		*ic = NULL;
	}
	return 0;
}

static int
luxio__iconv_tostring(lua_State *L)
{
	iconv_t *ic = (iconv_t*)(lua_touserdata(L, 1));
	lua_pushfstring(L, "<iconv %p>", *ic);
	return 1;
}

static iconv_t*
luxio__create_iconv(lua_State *L)
{
	iconv_t *r = lua_newuserdata(L, sizeof(iconv_t));
	int create = luaL_newmetatable(L, LUXIO_ICONV_METATABLE);

	if (create != 0) {
		lua_pushcfunction(L, luxio__iconv_gc);
		lua_setfield(L, -2, "__gc");
		lua_pushcfunction(L, luxio__iconv_tostring);
		lua_setfield(L, -2, "__tostring");
	}

	*r = NULL;

	lua_setmetatable(L, -2);

	return r;
}

/*** Allocate descriptor for character set conversion.
@tparam string tocode
@tparam string fromcode
@treturn iconv|number return value
@treturn errno
@function icon_open
*/
static int
luxio_iconv_open(lua_State *L)
{
	const char *tocode = luaL_checkstring(L, 1);
	const char *fromcode = luaL_checkstring(L, 2);
	iconv_t *r = luxio__create_iconv(L);

	*r = iconv_open(tocode, fromcode);

	if (*r == (iconv_t)-1) {
		lua_pushnumber(L, -1);
		lua_pushnumber(L, errno);
		return 2;
	}

	/* On the top of the stack is the iconv userdata */
	return 1;
}

/*** Close a previously-allocated iconv descriptor.
@tparam iconv handle
@treturn number return vlaue
@treturn errno
@function iconv_close
*/
static int
luxio_iconv_close(lua_State *L)
{
	iconv_t *_c = (iconv_t*)lua_touserdata(L, 1);
	iconv_t c = *_c;

	*_c = NULL;

	if (iconv_close(c) == -1) {
		lua_pushnumber(L, -1);
	} else {
		lua_pushnumber(L, 0);
	}

	lua_pushnumber(L, errno);
	return 2;
}

#define ICONV_BUF_SIZE 256

/*** Perform character set conversion.
@tparam iconv handle
@tparam string buf
@treturn string|number resulting string or return value in case of error
@treturn errno
@treturn string|nil partial result when error.
@function iconv
*/
static int
luxio_iconv(lua_State *L)
{
	/* based on Alexandre Erwin Ittner <alexandre@ittner.com.br>'s code */
	/* either returns completed string, or -1, errno, partial result */
	iconv_t *_cd = (iconv_t*)lua_touserdata(L, 1);
	iconv_t cd = *_cd;
	size_t ibleft;
	char *inbuf = (char* )luaL_checklstring(L, 2, &ibleft);
	char outbufs[ICONV_BUF_SIZE];
	char *outbuf = outbufs;
	size_t obleft = ICONV_BUF_SIZE;
	size_t ret = -1;

	luaL_Buffer b;
	luaL_buffinit(L, &b);

	do {
		ret = iconv(cd, (ICONV_IN_TYPE)&inbuf, &ibleft, &outbuf, &obleft);
		if (ret == (size_t)(-1)) {
			luaL_addlstring(&b, outbufs, ICONV_BUF_SIZE - obleft);

			if (errno == E2BIG) {
				obleft = ICONV_BUF_SIZE;
				outbuf = outbufs;
			} else {
				lua_pushnumber(L, -1);
				lua_pushnumber(L, errno);
				luaL_pushresult(&b);
				return 3;
			}
		}
	} while (ret == (size_t)-1);

	luaL_addlstring(&b, outbufs, ICONV_BUF_SIZE - obleft);
	luaL_pushresult(&b);
	return 1;
}

#undef ICONV_BUF_SIZE

static const struct luaL_Reg
luxio_functions[] = {
	{ "open", luxio_open },
	{ "creat", luxio_creat },
	{ "close", luxio_close },
	{ "read", luxio_read },
	{ "write", luxio_write },
	{ "writev", luxio_writev },
	{ "lseek", luxio_lseek },
	{ "ftruncate", luxio_ftruncate },
	{ "fsync", luxio_fsync },
#ifdef HAVE_FDATASYNC
	{ "fdatasync", luxio_fdatasync },
#endif
	{ "rename", luxio_rename },
	{ "link", luxio_link },
	{ "unlink", luxio_unlink },
	{ "symlink", luxio_symlink },
	{ "readlink", luxio_readlink },
	{ "mkstemp", luxio_mkstemp },
#ifdef HAVE_SENDFILE
	{ "sendfile", luxio_sendfile },
#endif
#ifdef HAVE_SPLICE
	{ "splice", luxio_splice },
#endif
	{ "dup", luxio_dup },
	{ "dup2", luxio_dup2 },
#ifdef _GNU_SOURCE
	{ "dup3", luxio_dup3 },
#endif
        { "pipe", luxio_pipe },
#ifdef _GNU_SOURCE
        { "pipe2", luxio_pipe2 },
#endif
	{ "socketpair", luxio_socketpair },
	{ "fcntl", luxio_fcntl },
	{ "umask", luxio_umask },
	{ "chmod", luxio_chmod },
	{ "fchmod", luxio_fchmod },
	{ "chown", luxio_chown },
	{ "mkfifo", luxio_mkfifo },
	{ "mkdir", luxio_mkdir },
	{ "rmdir", luxio_rmdir },

#define STAT_IS_ENTRY(x) { "S_IS" #x, luxio_S_IS##x }
	STAT_IS_ENTRY(REG),
	STAT_IS_ENTRY(DIR),
	STAT_IS_ENTRY(CHR),
	STAT_IS_ENTRY(BLK),
	STAT_IS_ENTRY(FIFO),
#ifdef S_ISLNK
	STAT_IS_ENTRY(LNK),
#endif
#ifdef S_ISSOCK
	STAT_IS_ENTRY(SOCK),
#endif
#undef STAT_IS_ENTRY

	{ "stat", luxio_stat },
	{ "lstat", luxio_lstat },
	{ "fstat", luxio_fstat },
	{ "access", luxio_access },

	{ "socket", luxio_socket },
	{ "listen", luxio_listen },
	{ "shutdown", luxio_shutdown },
	{ "connect", luxio_connect },
	{ "bind", luxio_bind },
	{ "accept", luxio_accept },
	{ "getsockopt", luxio_getsockopt },
	{ "setsockopt", luxio_setsockopt },

	{ "getaddrinfo", luxio_getaddrinfo },
	{ "gai_strerror", luxio_gai_strerror },

	{ "make_sockaddr", luxio_makesockaddr },

    { "send", luxio_send },
    { "sendto", luxio_sendto },
    { "recv", luxio_recv },
    { "recvfrom", luxio_recvfrom },
    
	{ "pollfds_new", luxio_pollfds_new },
	{ "pollfds_resize", luxio_pollfds_resize },
	{ "pollfds_setslot", luxio_pollfds_set_slot },
	{ "pollfds_getslot", luxio_pollfds_get_slot },
	{ "poll", luxio_poll },

	{ "fd_set_new", luxio_fd_set_new },
	{ "fd_set_resize", luxio_fd_set_resize },
	{ "FD_CLR", luxio_FD_CLR },
	{ "FD_SET", luxio_FD_SET },
	{ "FD_ISSET", luxio_FD_ISSET },
	{ "FD_ZERO", luxio_FD_ZERO },

	{ "select", luxio_select },

	{ "zero_timeval", luxio_timeval_zero },
	{ "gettimeofday", luxio_gettimeofday },

	{ "fork", luxio_fork },
	{ "exec", luxio_exec },
	{ "execp", luxio_execp },
	{ "waitpid", luxio_waitpid },

#define WAITPID_STATUS_ENTRY(x) { #x, luxio_##x }
	WAITPID_STATUS_ENTRY(WIFEXITED),
	WAITPID_STATUS_ENTRY(WEXITSTATUS),
	WAITPID_STATUS_ENTRY(WIFSIGNALED),
	WAITPID_STATUS_ENTRY(WTERMSIG),
#ifdef WCOREDUMP
	WAITPID_STATUS_ENTRY(WCOREDUMP),
#endif
	WAITPID_STATUS_ENTRY(WIFSTOPPED),
	WAITPID_STATUS_ENTRY(WSTOPSIG),
#ifdef WIFCONTINUED
	WAITPID_STATUS_ENTRY(WIFCONTINUED),
#endif
#undef WAITPID_STATUS_ENTRY

	{ "kill", luxio_kill },

	{ "strerror",  luxio_strerror },
	{ "_exit", luxio__exit },

	{ "setenv", luxio_setenv },
	{ "unsetenv", luxio_unsetenv },
	{ "getenv", luxio_getenv },

	{ "opendir", luxio_opendir },
	{ "fdopendir", luxio_fdopendir },
	{ "closedir", luxio_closedir },
	{ "readdir", luxio_readdir },
	{ "rewinddir", luxio_rewinddir },

	{ "chdir", luxio_chdir },
	{ "getcwd", luxio_getcwd },

	{ "newsigset", luxio_newsigset },
	{ "sigemptyset", luxio_sigemptyset },
	{ "sigfillset", luxio_sigfillset },
	{ "sigaddset", luxio_sigaddset },
	{ "sigdelset", luxio_sigdelset },
	{ "sigismember", luxio_sigismember },

	{ "sigaction", luxio_sigaction },
	{ "sigprocmask", luxio_sigprocmask },
	{ "sigpending", luxio_sigpending },
	{ "sigsuspend", luxio_sigsuspend },
	{ "sigwait", luxio_sigwait },
#ifdef __linux__
	{ "sigwaitinfo", luxio_sigwaitinfo },
	{ "sigtimedwait", luxio_sigtimedwait },
#endif

	{ "raise", luxio_raise },
	{ "alarm", luxio_alarm },
	{ "pause", luxio_pause },
	{ "sleep", luxio_sleep },

	{ "getpid", luxio_getpid },
	{ "getppid", luxio_getppid },

	{ "getpgrp", luxio_getpgrp },

	{ "getuid", luxio_getuid },
	{ "geteuid", luxio_geteuid },
	{ "getgid", luxio_getgid },
	{ "getegid", luxio_getegid },
	{ "setuid", luxio_setuid },
	{ "setgid", luxio_setgid },
	{ "setsid", luxio_setsid },
	{ "setpgid", luxio_setpgid },
	{ "getlogin", luxio_getlogin },

	{ "uname", luxio_uname },

	{ "time", luxio_time },
	{ "times", luxio_times },

	{ "tcgetpgrp", luxio_tcgetpgrp},
	{ "tcsetpgrp", luxio_tcsetpgrp},

	{ "nanosleep", luxio_nanosleep },

#if _POSIX_MESSAGE_PASSING >= 0

#if _XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L
	{ "mq_timedsend", luxio_mq_timedsend },
	{ "mq_timedreceive", luxio_mq_timedreceive },
#endif
	{ "mq_open", luxio_mq_open },
	{ "mq_close", luxio_mq_close },
	{ "mq_unlink", luxio_mq_unlink },
	{ "mq_send", luxio_mq_send },
	{ "mq_receive", luxio_mq_receive },
	{ "mq_setattr", luxio_mq_setattr },
	{ "mq_getattr", luxio_mq_getattr },
#endif
	{ "openlog", luxio_openlog },
	{ "syslog", luxio_syslog },
	{ "closelog", luxio_closelog },
	{ "setlogmask", luxio_setlogmask },
	{ "LOG_MASK", luxio_LOG_MASK },

	{ "iconv_open", luxio_iconv_open },
	{ "iconv_close", luxio_iconv_close },
	{ "iconv", luxio_iconv },

#if _XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L
    { "posix_fadvise", luxio_posix_fadvise },
#endif

	{ "ctermid", luxio_ctermid },
	{ "ttyname", luxio_ttyname },
	{ "isatty", luxio_isatty },

	{ "sysconf", luxio_sysconf },

	{ NULL, NULL }
};

static const struct luaL_Reg
luxio_bitop_functions[] = {
	{ "bor", luxio_bitop_or },
	{ "band", luxio_bitop_and },
	{ "binvert", luxio_bitop_invert },
	{ "btest", luxio_bitop_test },
	{ "bclear", luxio_bitop_clear },

	{ NULL, NULL }
};

#include "luxio_constants.inc"

#define NUMERIC_CONSTANT(x) do { lua_pushstring(L, #x);  \
				 lua_pushinteger(L, x); \
				 lua_settable(L, -3); } while (0)

int
luaopen_luxio(lua_State *L)
{
	int e;
	const char *n;
	lua_Number v;

#if (LUA_VERSION_NUM > 501)
	luaL_newlib(L, luxio_functions);
	luaL_newlib(L, luxio_bitop_functions);
#else
	luaL_register(L, "luxio", luxio_functions);
	lua_createtable(L, 0, (sizeof(luxio_bitop_functions) /
			       sizeof(struct luaL_Reg)) - 1);
	luaL_register(L, NULL, luxio_bitop_functions);
#endif
	lua_setfield(L, -2, "bit");

	for (e = 0;; e++) {
		n = luxio_numeric_constants[e].name;
		v = luxio_numeric_constants[e].number;

		if (n == NULL) break;
		lua_pushstring(L, n);
		lua_pushnumber(L, v);
		lua_settable(L, -3);
	}

	lua_pushstring(L, "_VERSION");
	lua_pushfstring(L, "Luxio %d", LUXIO_RELEASE);
	lua_settable(L, -3);

	lua_pushstring(L, "_COPYRIGHT");
	lua_pushstring(L, LUXIO_COPYRIGHT);
	lua_settable(L, -3);

	lua_pushstring(L, "_RELEASE");
	lua_pushnumber(L, LUXIO_RELEASE);
	lua_settable(L, -3);

	lua_pushstring(L, "_ABI");
	lua_pushnumber(L, LUXIO_ABI);
	lua_settable(L, -3);

	/* push values that are not compile-time known */
#ifdef SIGRTMIN
	NUMERIC_CONSTANT(SIGRTMIN);
	NUMERIC_CONSTANT(SIGRTMAX);
#endif
#ifdef HAVE_D_TYPE
	NUMERIC_CONSTANT(DT_UNKNOWN);
	NUMERIC_CONSTANT(DT_FIFO);
	NUMERIC_CONSTANT(DT_CHR);
	NUMERIC_CONSTANT(DT_DIR);
	NUMERIC_CONSTANT(DT_BLK);
	NUMERIC_CONSTANT(DT_REG);
	NUMERIC_CONSTANT(DT_LNK);
	NUMERIC_CONSTANT(DT_SOCK);
#endif

	return 1;
}

#undef NUMERIC_CONSTANT