summaryrefslogtreecommitdiff
path: root/luxio.c
blob: 033e9a8e3eab936e7460670f704475b3fa1daf59 (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
/* 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 6 /* 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 <unistd.h>
#include <dirent.h>
#include <time.h>
#include <limits.h>
#include <signal.h>
#include <syslog.h>
#include <iconv.h>

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

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

#define INVALID_MODE ((mode_t) -1)

/* 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
*/

/*** Create a child process.

@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 file.
Calls 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 file, searching PATH.
Calls 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.

@tparam number pid pid 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.
@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
@tparam number status code from `waitpid`()
@treturn number exit status code
@function WEXITSTATUS
*/
WAITPID_STATUS(WEXITSTATUS)

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

/*** Obtain signal used to kill child.
@tparam number status code from `waitpid`()
@treturn number signal number
@function WTERMSIG
*/
WAITPID_STATUS(WTERMSIG)

#ifdef WCOREDUMP
/**% WCOREDUMP
 *  retval = WCOREDUMP(status);
 *  retval = WCOREDUMP(status)
 */
/*** Check status macro for WCOREDUMP.
@tparam number status code from `waitpid`()
@treturn number true or false
@function WCOREDUMP
*/
WAITPID_STATUS(WCOREDUMP)
#endif

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

/*** Obtain signal number used to stop child.
@tparam number status code from `waitpid`()
@treturn number signal number
@function WSTOPSIG
*/
WAITPID_STATUS(WSTOPSIG)

#ifdef WIFCONTINUED
/*** Check status macro for WIFCONTINUED.
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.
@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.
@section signals
*/

/**% kill
 *  retval = kill(pid, sig);
 *  retval, errno = kill(pid, sig)
 */
/*** Send signal to a process.
@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. */

/* TODO: Manipulate Signal Sets 3.3.3 */
/* TODO: sigaction() 3.3.4 */
/* TODO: pthread_sigmask(), sigprocmask() 3.3.5 */
/* TODO: sigpending() 3.3.6 */
/* TODO: sigsuspend() 3.3.7 */
/* TODO: sigwait(), sigwaitinfo(), sigtimedwait() 3.3.8 */
/* TODO: sigqueue() 3.3.9 */
/* TODO: pthread_kill() 3.3.10 */

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

/*** Set an alarm clock for delivery of a signal.
@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.
@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.
@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.
@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.
@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.
@treturn number uid
@function geteuid
*/
static int
luxio_geteuid(lua_State *L) /* 4.2.1 */
{
	lua_pushinteger(L, geteuid());

	return 1;
}

/*** Get group identity.
@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.
@treturn number gid
@function getegid
*/
static int
luxio_getegid(lua_State *L) /* 4.2.1 */
{
	lua_pushinteger(L, getegid());

	return 1;
}

/*** Set user identity.
@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
@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.
@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
*/

/* TODO: getpgrp() 4.3.1 */
/* TODO: setsid() 4.3.2 */
/* TODO: setpgid() 4.3.3 */

/*** 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
@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.
@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.
@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.
@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.
@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 ***********************************************/

/* TODO: ctermid() 4.7.1 */
/* TODO: ttyname(), ttyname_r(), isatty() 4.7.2 */

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

/* TODO: sysconf() 4.8.1 */

/*** Directories.
readdir() is a hideous API.  As such, we need to be reasonably high-level here,
otherwise everything is just too painful.
@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) + 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) + 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
@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);
	int err;

	err = readdir_r(s->dirp, s->buf, &s->ent);

	if (err == 0 && s->ent != NULL) {
		lua_pushinteger(L, 0);
		lua_createtable(L, 0, 3);
		lua_pushinteger(L, s->ent->d_ino);
		lua_setfield(L, -2, "d_ino");
		lua_pushstring(L, s->ent->d_name);
		lua_setfield(L, -2, "d_name");
#ifdef HAVE_D_TYPE
		lua_pushinteger(L, s->ent->d_type);
		lua_setfield(L, -2, "d_type");
#endif
		return 2;
	}

	if (s->ent == NULL) {
		/* end of directory */
		lua_pushnil(L);

		return 1;
	}

	lua_pushinteger(L, err);

	return 1;
}

/*** 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.
@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 */
{
	char buf[PATH_MAX];

	if (getcwd(buf, PATH_MAX) == 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.
@tparam string path
@tparam number flags
@tparam[opt] number mode, must be specified if creating.
@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;
}

/* TODO: creat() 5.3.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 */
{
	char buffer[PATH_MAX];
	ssize_t ret;
	const char *path = luaL_checkstring(L, 1);

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

	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
@atime time of last access
@mtime time of last modification
@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

/* TODO: access() 5.6.3 */

/*** 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
@tprarm 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
@tparamnumber 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 *******************************************************************/

/**% pipe
 * retval = pipe(pipearray);
 * retval, errno = pipe(pipetable) -- fills in [1] and [2] in pipetable
 */
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

/**% pipe2
 * retval = pipe2(pipearray, flags);
 * retval, errno = pipe2(pipetable, flags) -- fills in [1] and [2] in pipetable
 */
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

/**% socketpair
 * retval = socketpair(domain, type, protocol, fdarray)
 * retval, errno = socketpair(domain, type, protocol, fdtable)
 */
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 ********************************************/

/**% dup
 * retval = dup(oldfd);
 * retval, errno = dup(oldfd)
 */
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;
}

/**% dup2
 * retval = dup2(oldfd, newfd);
 * retval, errno = dup2(oldfd, newfd)
 */
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
/**% dup3
 * retval = dup3(oldfd, newfd, flags);
 * retval, errno = dup2(oldfd, newfd, flags)
 */
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 ********************************************/

/**% close
 * retval = close(fd);
 * retval, errno = close(fd)
 */
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 ********************************************************/

/**% read
 * retval = read(fd, buf, count);
 * retval, errno = read(fd, count)
 * string, errno = read(fd, count)
 */
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
 * retval = write(fd, buf, count);
 * retval, errno = write(fd, string[, start_offset/0])
 */
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;
}

/**% writev
 * retval = writev(fd, iov, blks);
 * retval, errno = writev(fd, string[, ...])
 */
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
/**% sendfile
 * retval = sendfile(out_fd, in_fd, offset/NULL, count);
 * retval, errno = sendfile(out_fd, in_fd, offset/nil, count)
 */
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
 * retval = splice(fd_in, off_in, fd_out, off_out, len, flags);
 * retval, errno = splice(fd_in, off_in, fd_out, off_out, len, flags)
 */
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 *********************************************/

/**> fcntl
 * 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
 *
 * C-Style: retval = fcntl(fd, cmd[, argument]);
 *
 * Lua-Style: retval, errno = fcntl(fd, cmd[, argument])
 */
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 */
}

#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
/**% lseek
 * retval = lseek(fd, offset, whence);
 * retval, errno = lseek(fd, offset, whence)
 */
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 ****************************************************/

/**% fsync
 * retval = fsync(filedes);
 * retval, errno = fsync(filedes)
 */
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
/**% fdatasync
 * retval = fdatasync(filedes);
 * retval = fdatasync(filedes)
 */
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 **********************************************/

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

/**% tcgetpgrp
 * retval = tcgetpgrp(filedes);
 * retval, errno = tcgetpgrp(filedes)
 */
static int
luxio_tcgetpgrp(lua_State *L) /* 7.2.3 */
{
	lua_pushinteger(L, tcgetpgrp(luaL_checkinteger(L, 1)));
	lua_pushinteger(L, errno);

	return 2;
}

/**% tcsetpgrp
 * retval = tcsetpgrp(filedes, pgrp_id);
 * retval = tcsetpgrp(filedes, pgrp_id)
 */
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 ***********************************************/

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

/**% nanosleep
 * retval = nanosleep(req_timespec, rem_timespec);
 * retval, errno, rem_sec, rem_nsec = nanosleep(req_sec, req_nsec)
 */
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 *********************************************************/

#if defined(_POSIX_MESSAGE_PASSING)

#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;
}

/**% mq_open
 * retval = mq_open(name, oflag[, mode, attr]);
 * retval, errno = mq_open(name, oflag[, mode])
 */
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;
}

/**% mq_close
 * retval = mq_close(mq);
 * retval, errno = mq_close(mq)
 */
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;
}

/**% mq_unlink
 * retval = mq_unlink(name);
 * retval, errno = mq_unlink(name)
 */
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;
}

/**% mq_send
 * retval = mq_send(mq, msg_ptr, msg_len, msg_prio);
 * retval, errno = mq_send(mq, string, prio)
 */
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;
}

/**% mq_receive
 * retval = mq_receive(mq, msg_ptr, msg_ptr_sz, msg_prio);
 * retval, errno, msg, prio = mq_receive(mq)
 */
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 */

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;
}

/**% mq_setattr
 * retval = mq_setattr(mq, new, old);
 * retval, errno, old = mq_setattr(mq, flags)
 */
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;
}

/**% mq_getattr
 * retval = mq_getattr(mq, old);
 * retval, errno, old = mq_getattr(mq)
 */
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

/**% 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;
}

/**% 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.
 *
 * \t r, addrinfo = getaddrinfo("www.rjek.com", "80", 0, l.AF_UNSPEC, l.SOCK_STREAM)
 * \t for _, ai in ipairs(addrinfo) do
 * \t    sock = socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
 * \t    if connect(sock, ai.ai_addr) >= 0 then break end
 * \t end
 */

#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)
 */
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
 * retval = listen(fd, backlog);
 * retval, errno = listen(fd, backlog)
 */
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;
}

/**% shutdown
 * retval = shutdown(fd, how);
 * retval, errno = shutdown(fd, how)
 */
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;
}

/**% connect
 * retval = connect(fd, sockaddr, sockaddrlen);
 * retval, errno = connect(fd, sockaddr)
 */
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
 * retval = bind(fd, sockaddr, sockaddrlen);
 * retval, errno = bind(fd, sockaddr)
 */
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
 * retval = accept(fd, sockaddrinfo, sockaddrlen);
 * retval, sockaddr = accept(fd)
 * retval, errno = accept(fd)
 */
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;
}

/**% getsockopt
 * retval = getsockopt(fd, level, optname, optval, optlen);
 * retval, errno = getsockopt(fd, level, optname)
 * retval, opt = getsockopet(fd, level, optname)
 */
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);
}

/**% setsockopt
 * retval = setsockopt(fd, level, optname, optval, optlen);
 * retval, errno = setsockopt(fd, level, optname, optval)
 */
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);
}

/**% gai_strerror
 * retval = gai_strerror(errnum);
 * retval = gai_strerror(errno)
 */
static int
luxio_gai_strerror(lua_State *L)
{
	lua_pushstring(L, gai_strerror(luaL_checkint(L, 1)));

	return 1;
}

/**% getaddrinfo
 * retval = getaddrinfo(node, service, hints, res);
 * errcode = getaddrinfo(node, service[, ai_flags/0, ai_family/AF_UNSPEC, ai_socktype/0, ai_protocol/0])
 * addrinfo = getaddrinfo(node, service[, ai_flags/0, ai_family/AF_UNSPEC, ai_socktype/0, ai_protocol/0])
 */
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 *********************************/

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;
}

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;
}

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;
}

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 ****************************************************/

#define LUXIO_POLLFD_METATABLE "luxio.pollfdarray"

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

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_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;
}

/* Bit/flag operation functions **********************************************/

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 ****************************************************/

#define LUXIO_TIMEVAL_METATABLE "luxio.timeval"

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);
}

static int
luxio_timeval_zero(lua_State *L)
{
	struct timeval *r = lua_newuserdata(L, sizeof(*r));

	timerclear(r);

	luxio__bless_timeval(L);

	return 1;
}

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 **************************************************/

/**% strerror
 * retval = strerror(errno);
 * retval = strerror(errno)
 */
static int
luxio_strerror(lua_State *L)
{
	lua_pushstring(L, strerror(luaL_checkint(L, 1)));

	return 1;
}

static char *luxio_openlog_ident = NULL;

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;
}

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;
}

static int
luxio_closelog(lua_State *L)
{
	free(luxio_openlog_ident);
	luxio_openlog_ident = NULL;
	closelog();

	return 0;
}

static int
luxio_setlogmask(lua_State *L)
{
	int mask = luaL_checkint(L, 1);

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

	return 1;
}

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;
}

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 = iconv_open(tocode, fromcode);

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

static int
luxio_iconv_close(lua_State *L)
{
	iconv_t c = (iconv_t)lua_touserdata(L, 1);

	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

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);
    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 },
	{ "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 },
#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 },

	{ "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 },

	{ "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 },

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

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

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

	{ "uname", luxio_uname },

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

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

	{ "nanosleep", luxio_nanosleep },

#if defined(_POSIX_MESSAGE_PASSING)

#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 },

	{ 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.h"

#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