summaryrefslogtreecommitdiff
path: root/luxio/simple.lua
blob: f2ef5baa6dd92bedafd2b737458a237fa74d5c3b (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
-- Light Unix I/O for Lua
-- Copyright 2012 Rob Kendrick <rjek+luxio@rjek.com>
--
-- Distributed under the same terms as Lua itself (MIT).
--
-- A wrapper around the rather raw interface luxio normally provides to
-- make things simpler.

--- High-level bindings to POSIX functionality.
--- @module luxio.simple

--
-- sio = require "luxio.simple"
--
-- sio.stdin, .stdout, .stderr
--         descriptor objects for standard IO end points
--
-- myfile = assert(sio.open("filename", "flags"[, "mode"]))
--          flags is a string, each flag is a single character:
--             r = open for reading (O_RDONLY)
--             w = open for writing (O_WRONLY)
--             + = open in append mode (O_APPEND)
--             c = create file if it does not already exist (O_CREAT)
--             e = ensure this call creates the file (O_EXCL)
--             n = do not update the access time (O_NOATIME)
--             d = where possible, open non-blocking (O_NONBLOCK)
--             t = truncate file if it already exists (O_TRUNC)
--
--             returns file object, or nil, error string, errno.
--
-- myfile.fd
--         file descriptor number of the object
--
-- myfile.name
--         descriptive name of file (such as file name, sockaddr, etc)
--
-- myfile.closed
--         bool indicating if this descriptor has been closed
--
-- myfile:close()
--         close the file.
--         returns true, or nil, errorstring, errno.
--
-- myfile:nonblocking([bool])
--         bool: true to set non-blocking, false to set blocking, nil to
--               make no change
--         returns bool indicating current state, or nil, error string and
--         errno.
--
-- myfile:write(string[, offset])
--         writes string to the file, optionally starting at offset bytes in
--         returns number of bytes written, or nil, error string, errno
--
-- myfile:writev(...)
--         writes ALL the strings!
--         return number of bytes written, or nil, error string, errno
--
-- myfile:seek([whence][, offset])
--         seek within the file.  whence can be one of cur, set and end.
--         values default to cur and 0.
--         returns new offset, or nil, error string, errno
--
-- myfile:read(pattern[, pattern...])
--         reads data from the file.  pattern can be:
--         a number: read this number of bytes.
--         "*a": read all data until EOF
--         "*l": read a line (warning: inefficient, reads a byte at a time!)
--         returns the results, or nil, error string, errno
--
-- myfile:chmod(mode)
--         Change permissions of an open descriptor's backing file.
--
-- myfile:nogc()
--         do not close the descriptor on garbage collect
--
-- myfile:lock(mode, whence, start, len, wait)
--         Manipulates advisory locks on file regions.
--         mode is one of "r", "w", or "", for read lock, write lock, or
--         unset lock.  whence, like seek, one of "cur", "set", "end".
--         start and len describe the region.  If wait is set, it will
--         wait until the lock is available before claiming it and
--         returning.
--
-- myfile:unlock(whence, start, len)
--         Same as above, except implicitly passes "" on your behave in mode
--
-- myfile:locktest(mode, whence, start, len)
--         As above, but it does not claim the lock, just checks if it
--         is available.  Returns true if the lock would work, or false
--         and a pid of the holder if the lock is already taken.
--
-- myfile = sio.wrap_fd(fd[, nogc][, name])
--         wrap an fd aquired elsewhere with functions here
--         fd: number of file descriptor
--         nogc: do not close file when object is collected (default false)
--         name: symbolic name of descriptor (default "<unknown>")
--
-- read_pipe, write_pipe = sio.pipe()
--         create an anonymous pipe, returning both halves, the read end and
--         the write end, or nil, error message, errno.
--
-- sock1, sock2 = sio.socketpair()
--         creates a pair of stream UNIX domain sockets, returning both.
--         Optionally pass luxio.SOCK_DGRAM if you want a datagram socket.
--
-- mysock = sio.inet([socktype])
--         create an IPv4 socket of socktype, either "tcp" (default) or "udp".
--         returns socket object or nil, error string, errno
--
-- mysock = sio.inet6([socktype])
--         create an IPv6 socket of socktype, either "tcp" (default) or "udp".
--         returns socket object or nil, error string, errno
--
-- mysock = sio.connect(host, service)
--         connects to a remote host via tcp, using getaddrinfo() to find
--         possibilities.  Does resolving, and can connect to both IPv4 and
--         IPv6 hosts.  returns socket object, or nil, error string, errno.
--
-- mysock = sio.bind(host, service[, backlog])
--         creates a TCP socket and binds it to the specified host and service.
--         returns socket object or nil, error string, errno
--
-- mysock:connect(address, port)
--         connects to an address and port.  No host name lookup is done.
--         returns true, or nil, error string, errno.
--
-- mysock:bind(address, port)
--         binds to an address and port.  No host name lookup is done.
--         returns true, or nil, error string, errno
--
-- mysock:listen([backlog])
--         enables listening for connections.
--         returns true, or nil, error string, errno
--
-- mysock:accept()
--         returns the next connection in the queue as a socket object, or
--         nil, error string, errno
--
-- mysock:setsockopt(level, option, value)
--         sets a socket option, such as SOL_SOCKET, SO_REUSEADDR.
--         returns true, or nil, error message, errno
--
-- mysock:getsockopt(level, option)
--         gets a socket option
--         returns the value, or nil, error message, errno
--
-- oldmask = sio.umask(newmask)
--         change the umask
--         returns old umask
--
-- chmod(filename, mode)
--         Changes the permissions of a named file
--
-- opendir(path)
--         Returns an object for directory enumeration,
--         or nil, error message, errno
-- mydir:iterate()
--         Returns an iterator suitable for use with the for loop that
--         returns two values, a file name and a table containing
--         d_ino, d_name and possibly d_type.
-- mydir:next()
--         Returns a table containing d_ino, d_name and possibly d_type,
--         or nil at end of directory.
-- mydir:close()
--         Closes an open directory.
--
-- mkdir(path[, "mode"])
--         Creates a directory.  Mode defaults to 0775.
--         Returns 0, or nil, errmsg, errno
--
-- fork()
--         Forks the process.  Returns 0 to the child, pid of child to
--         parent, or nil, errmsg, errno
-- exec(path, ...)
--         Replaces this proces with another.  Either never returns, or
--         returns nil, errmsg, errno
-- waitpid([pid[, options]])
--         Waits for a child to exit, and returns its exit status.  pid
--         defaults to -1.
-- kill(pid[, signal])
--         Sends a signal to another process.  Signal defaults to SIGTERM.
--         Returns 0, or nil, errmsg, errno
-- setenv(key, value[, overwrite])
--         Sets an environment variable.  overwrite defaults to false.
--         Returns 0, or nil, errmsg, errno
-- getenv(key)
--         Returns the given environment variable, or nil.
-- unsetenv(key)
--         Unsets the given key.  Returns 0 if success (or key didn't
--         exist) or nil, errmsg, errno
-- chdir(path)
--         Changes the current working directory.   Returns 0, or
--         nil, errmsg, errno
-- getcwd()
--         Returns the current working directory, or nil, errmsg, errno
--
-- flags()
--         Parses a list of comma-seperated flag strings, looks them up
--         as UNIX constants, and ORs them together.
--         Common suffixes are optional, and the system is case-insensitive.
--         For example, flags("rdrw,creat,excl") would be the same as ORing
--         together O_RDWR, O_CREAT, and O_EXCL.

local l = require "luxio"

assert(l._ABI == 0, "luxio ABI mismatch")

local l_open = l.open
local l_pipe = l.pipe
local l_socketpair = l.socketpair
local l_socket = l.socket
local l_bind = l.bind
local l_connect = l.connect
local l_listen = l.listen
local l_accept = l.accept
local l_close = l.close
local l_write = l.write
local l_writev = l.writev
local l_read = l.read
local l_stat = l.stat
local l_lstat = l.lstat
local l_fstat = l.fstat
local l_lseek = l.lseek
local l_chmod = l.chmod
local l_fchmod = l.fchmod
local l_umask = l.umask
local l_link = l.link
local l_mkdir = l.mkdir
local l_mkfifo = l.mkfifo
local l_unlink = l.unlink
local l_rmdir = l.rmdir
local l_rename = l.rename
local l_fcntl = l.fcntl
local l_setsockopt = l.setsockopt
local l_getsockopt = l.getsockopt
local l_getaddrinfo = l.getaddrinfo
local l_send = l.send
local l_sendto = l.sendto
local l_recv = l.recv
local l_recvfrom = l.recvfrom
local l_gai_strerror = l.gai_strerror
local l_connect = l.connect
local l_bit_bor = l.bit.bor
local l_bit_bclear = l.bit.bclear
local l_bit_btest = l.bit.btest
local strerror = l.strerror
local l_make_sockaddr = l.make_sockaddr

local getmetatable = getmetatable
local setmetatable = setmetatable
local assert = assert
local error = error
local tostring = tostring
local tonumber = tonumber
local unpack = unpack
local newproxy = newproxy

local lua_version = tonumber(_VERSION:match "Lua (%d.%d)")

local descriptor_mt

local sio_wrap_mt

local function err(s, errno)
    return nil, ("%s: %s"):format(s, strerror(errno)), errno
end

local function sio_mt_gc(o)
    if o.fd and not o.nogcfd then
        l_close(o.fd)
    end
end

--- stat result table.
--- The table that all the stat family returns.
--- @field dev ID of device containing file
--- @field ino inode number
--- @field mode protection mode
--- @field nlink number of hard 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 512 byte blocks allocated
--- @field atime time of last access
--- @field mtime time of last modification
--- @field ctime time of last status change
--- @table stat


--- A file handle.
--- The basic type used to expose file handles.
--- @type file

if lua_version == 5.1 then
    sio_wrap_mt = function(fd, nogcfd, name)
        assert(type(fd) == "number", "expected file descriptor number at #1")
        local p = newproxy(true)
        local r = { 
          --- The file descriptor as a number.
          fd = fd,
          proxy = p,
          nogcfd = nogcfd,
           --- Helpful text representation of file handle.
          name = name,
          closed = false }
        getmetatable(p).__gc = function()
            return sio_mt_gc(r)
        end
        return setmetatable(r, descriptor_mt)
    end
elseif lua_version >= 5.2 then
    sio_wrap_mt = function(fd, nogcfd, name)
        assert(type(fd) == "number", "expected file descriptor number at #1")
        local r = { fd = fd, nogcfd = nogcfd, name = name, closed = false }
        return setmetatable(r, descriptor_mt)
    end
end

local function sio_check_mt(t)
    if getmetatable(t) ~= descriptor_mt then
        error "not passed an sio object"
    end

    if t.closed then
        error "passed closed sio object"
    end

    return true
end

--- Close an open file.
--- @function file:close
--- @treturn bool|nil true on success, nil on failure
--- @treturn string|nil string describing error
--- @treturn errno|nil errno on error
local function close(o)
    sio_check_mt(o)

    local r, errno = l_close(o.fd)
    if r ~= 0 then
        return err("close", errno)
    end

    o.fd = nil
    o.closed = true

    return true
end

--- Disable garbage collection of a file.
--- @function file:nogc
local function nogc(o)
    sio_check_mt(o)

    o.nogcfd = true
end

--- Set the non-blocking flag on a file.
--- @function file:nonblocking
--- @tparam bool blocking true for non-blocking, false or nil for blocking.
local function nonblocking(o, b)
    sio_check_mt(o)

    local fd = o.fd
    local flags, errno = l_fcntl(fd, l.F_GETFL)

    if flags == -1 then
        return err("fcntl", errno)
    end

    if b == nil then
        return l_bit_btest(flags, l.O_NONBLOCK)
    elseif b == false then
        flags = l_bit_bclear(flags, l.O_NONBLOCK)
    elseif b == true then
        flags = l_bit_bor(flags, l.O_NONBLOCK)
    else
        error "expected nil, true or false at #2"
    end

    flags, errno = l_fcntl(fd, l.F_SETFL, flags)

    if flags ~= 0 then
        return err("fcntl", errno)
    else
        return true
    end
end

--- Write data to a file.
--- @function file:write
--- @tparam string data
--- @tparam[opt=1] number offset into string to start write from
--- @treturn number|nil bytes written, or nil on error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function write(o, d, i)
    sio_check_mt(o)
    assert(type(d) == "string", "string expected at #2")
    local r, errno = l_write(o.fd, d, i)

    if r < 0 then
        return err("write", errno)
    end

    return r
end

--- Write a list of strings to a file.
--- @function file:writev
--- @tparam string ... List of strings to write
--- @treturn number|nil Bytes written, or nil in case of error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function writev(o, ...)
    sio_check_mt(o)
    local r, errno = l_writev(o.fd, ...)

    if r < 0 then
        return err("writev", errno)
    end

    return r
end

--- Read data from a file.
--- This function takes a list of patterns to read, based loosely
--- on Lua's own read function.  They are:
---
---  * "*a" - read all data until end of file.
---  * "*l" - read a single line of data, or until end of file.
---  * Or, a number describing the number of bytes to read.
--- @function file:read
--- @tparam string ... List of read patterns.
--- @treturn ...|nil List of return strings, or nil if error
--- @treturn string|nil String describing error if error
--- @treturn errno|nil errno if error
local function read(o, ...)
    local res = { }
    for idx, patt in ipairs { ... } do
        if patt == "*a" then
            local c = { }
            repeat
                local r, errno = l_read(o.fd, l.BUFSIZ)
                if r == -1 then
                    return err("read", errno)
                end
                c[#c + 1] = r
            until #r == 0
            if #c ~= 0 then
                res[#res + 1] = table.concat(c)
            end

        elseif patt == "*l" then
            local c = { }
            local r, errno
            repeat
                r, errno = l_read(o.fd, 1)
                if r == -1 then
                    return err("read", errno)
                end
                if r ~= '\n' and #r ~= 0 then
                    c[#c + 1] = r
                else
                    break
                end
            until #r == 0
            if #c ~= 0 or #r ~= 0 then
                res[#res + 1] = table.concat(c)
            end

        elseif type(patt) == "number" then
            local r, errno = l_read(o.fd, patt)
            if r == -1 then
                return err("read", errno)
            end
            if #r ~= 0 then
                res[#res + 1] = r
            end
        else
            error(("unknown pattern specification '%s' at #%d"):format(patt, idx))
        end
    end

    if #res == 0 then
        return nil
    else
        return unpack(res)
    end
end

--- Get information on an option file.
--- @function file:fstat
--- @treturn stat|nil stat table or nil if error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function fstat(o)
    sio_check_mt(o)
    local r, e = l_fstat(o.fd)

    if r < 0 then
        return err("fstat", e)
    end

    return e
end

local seek_modes = {
    ["cur"] = l.SEEK_CUR,
    ["set"] = l.SEEK_SET,
    ["end"] = l.SEEK_END
}

--- Change the position within a file.
--- @function file:seek
--- @tparam string whence one of "cur", "set", and "end".
--- @tparam number offset signed number describing requested change.
--- @treturn number|nil resulting offset, as measured from beginning of file
--- in bytes, or nil if error.
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function seek(o, whence, offset)
    sio_check_mt(o)
    assert(offset == nil or type(offset) == "number", "offset number expected at #2")
    whence = whence or "cur"
    offset = offset or 0

    whence = seek_modes[whence] or error "unknown seek whence"
    local r, errno = l_lseek(o.fd, offset, whence)

    if r < 0 then
        return err("lseek", errno)
    end

    return r
end

--- Apply or remove an advisory lock on an open file.
--- @function file:lock
--- @tparam string rw Lock type "r" for read, "w" for write, "" for unlock.
--- @tparam string whence one of "cur", "set", and "end"
--- @tparam number offset offset of start of lock/unlock location
--- @tparam number len length in bytes of lock/unlock locations
--- @tparam bool wait true if the call should block until region is unlocked
--- @tparam bool test true if you simply want to check if locked
--- @treturn true|nil nil if error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function lock(o, rw, whence, offset, len, wait, test)
    sio_check_mt(o)
    assert(rw == "r" or rw == "w" or rw == "")
    assert(seek_modes[whence])
    assert(type(offset) == "number")
    assert(type(len) == "number" and len >= 0)

    local flock = {
        l_whence = seek_modes[whence],
        l_start = offset,
        l_len = len
    }

    local cmd = wait and l.F_SETLKW or l.F_SETLK
    if test then cmd = l.F_GETLK end

    if rw == "r" then flock.l_type = l.F_RDLCK
    elseif rw == "w" then flock.l_type = l.F_WRLCK
    else flock.l_type = l.F_UNLCK
    end

    local r, errno = l_fcntl(o.fd, cmd, flock)

    if r < 0 then
        return err("fcntl", errno)
    end

    if not test then
        return true
    else
        if flock.l_type == l.F_UNLCK then
            return true
        else
            return false, flock.l_pid
        end
    end
end

--- Unlock a region of an open file.
--- Convienence function.  Simply calls `file:lock` with an empty rw.
--- @function file:unlock
--- @tparam string whence
--- @tparam number offset
--- @tparam number len
--- @treturn true|nil nil if error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function unlock(o, whence, offset, len)
    return lock(o, "", whence, offset, len)
end

local function locktest(o, type, whence, offset, len)
    return lock(o, type, whence, offset, len, false, true)
end

local function fchmod(o, mode)
    sio_check_mt(o)
    local mode = sio_mode_flags(mode)
    local r, errno = l_fchmod(o.fd, mode)

    if r < 0 then
        return err("fchmod", errno)
    end

    return r
end

--- Helper functions.
--- @section helper

local flag_prefixes = {
    "O_", "SEEK_", "SPLICE_F_", "S_", "F_", "PF_", "AF_", "IPPROTO_", "SOCK_",
    "SHUT_", "SO_", "TCP_", "AI_", "POLL", "LOG_", "EXIT_", "MSG_"
}

local function flags_find_flag(f)
    for flag in pairs(l) do
        if type(l[flag]) == "number" then
            if f == flag or f == flag:lower() then return flag end
            -- now look for both lower and upper using a set of prefixes
            for _, prefix in ipairs(flag_prefixes) do
                local try = prefix .. f
                if try == flag or try:upper() == flag:upper() then return flag end
            end
        end
    end
    
    return nil
end

local flag_cache = { }

--- Convert a string of comma-seperated flag names to a number.
--- This function takes a list of strings, each with comma-seperated flag names
--- and returns a number which is all of those flags ORed together.
--- Flags can optionally be lower-case, and also if they begin with one of
--- the common prefixes, such as O_, S_, F_, AF_, AI_, SO_, TCP_ and many others
--- can be omitted.
--- For example:
---
---     myflags = sio.flags "rdwr,creat,excl"
--- @tparam string ...
--- @treturn number
--- @function flags
local function flags(...)
    local r = 0
    local f = table.concat({ ... }, ",")
    
    if flag_cache[f] then return flag_cache[f] end
    
    
    for i in f:gmatch("([^,]*)") do
        if i ~= "" then
            local flag = flags_find_flag(i)
            if not flag then
                error("unknown flag " .. i)
            end
            r = l_bit_bor(r, luxio[flag])
        end
    end
    
    flag_cache[f] = r
    
    return r
end

local function sio_perm_flags_help(s, read, write, execute, sid)
    local c = { }
    for l in s:gmatch "." do
        if l == "r" then c[#c + 1] = read
        elseif l == "w" then c[#c + 1] = write
        elseif l == "x" then c[#c + 1] = execute
        elseif l == "s" then c[#c + 1] = sid
        elseif l == "t" then c[#c + 1] = l.S_ISVTX
        elseif l == "-" then -- skip -
        else error(("unknown permission flag '%s'"):format(l))
        end
    end

    return l_bit_bor(unpack(c))
end

local S_IRALL = l_bit_bor(l.S_IRUSR, l.S_IRGRP, l.S_IROTH)
local S_IWALL = l_bit_bor(l.S_IWUSR, l.S_IWGRP, l.S_IWOTH)
local S_IXALL = l_bit_bor(l.S_IXUSR, l.S_IXGRP, l.S_IXOTH)
local S_ISUIDGID = l_bit_bor(l.S_ISUID, l.S_ISGID)

--- Convert a string representing a permissions mode to a number.
--- This function converts a string into a mode flag.  It supports
--- many different forms.  For example:
---
---    sio.tomode(0666) -- already a mode, it'll just return it
---    sio.tomode "666" -- converted directly to number, assumed octal
---    sio.tomode "-rw-r--r--" -- as emitted by ls
---    sio.tomode "o+rw,g+r" -- as used by chmod
--- @tparam number|string f mode description to convert
--- @treturn number
--- @function tomode
local function sio_mode_flags(f)
    if type(f) == "number" then
    -- is already a suitable mode
        return f
    end

    if type(f) ~= "string" then
    -- if it's not a string, we don't know how to process it
    error("string describing access mode expected")
    end

    if f:match "0?[0-7][0-7][0-7][0-7]" then
        -- octal number as a string
        return tonumber(f, 8)
    end

    if not f:match "[^-rwx]" then
        -- ls-style
        local usr, grp, oth = f:match "(...)(...)(...)"
        if not (usr and grp and oth) then
            error "incorrect format for ls-style permissions flags"
        end
        local m = l_bit_bor(sio_perm_flags_help(usr, l.S_IRUSR, l.S_IWUSR, l.S_IXUSR),
            sio_perm_flags_help(grp, l.S_IRGRP, l.S_IWGRP, l.S_IXGRP),
            sio_perm_flags_help(oth, l.S_IROTH, l.S_IWOTH, l.S_IXOTH))
        return m
    end

    -- try to parse this as a chmod-style command
    local m = 0
    for e, p in f:gmatch "(.)=([^,]+),?" do
        if e == "u" then
            m = l_bit_bor(m, sio_perm_flags_help(p, l.S_IRUSR, l.S_IWUSR, l.S_IXUSR, l.S_ISUID))
        elseif e == "g" then
            m = l_bit_bor(m, sio_perm_flags_help(p, l.S_IRGRP, l.S_IWGRP, l.S_IXGRP, l.S_ISGID))
        elseif e == "o" then
            m = l_bit_bor(m, sio_perm_flags_help(p, l.S_IROTH, l.S_IWOTH, l.S_IXOTH, 0))
        elseif e == "a" then
            m = l_bit_bor(m, sio_perm_flags_help(p, S_IRALL, S_IWALL, S_IXALL, S_ISUIDGID))
        else
            error(("unknown access group '%s'"):format(e))
        end
    end

    return m
end

local open_flags = {
    r = 0, w = 0,  -- handled manually
    ["+"] = l.O_APPEND,
    c = l.O_CREAT,
    e = l_bit_bor(l.O_EXCL, l.O_CREAT),
    n = l.O_NOATIME,
    d = l.O_NDELAY,
    t = l.O_TRUNC
}

local function sio_open_flags(flags)
    local r = { }
    if flags:match "r" and flags:match "w" then
        r[#r + 1] = l.O_RDWR
    elseif flags:match "r" then
        r[#r + 1] = l.O_RDONLY
    elseif flags:match "w" then
        r[#r + 1] = l.O_WRONLY
    end

    for m in flags:gmatch "(.)" do
        local f = open_flags[m] or error(("unknown open flag '%s'"):format(m))
        r[#r + 1] = f
    end

    return l_bit_bor(unpack(r))
end

--- Opening files.
--- @section open

--- Open a file.
--- The open type may contain the following characters;
---
---   * r - open file for reading
---   * w - open file for writing
---   * \+ - append
---   * e - open and create exclusively (O_EXCL and O_CREAT)
---   * c - create file if it doesn't exist. (O_CREAT)
---   * n - do not modify access time (O_NOATIME)
---   * d - open in non-blocking mode (O_NDELAY)
---   * t - truncate file
--- @tparam string filename
--- @tparam[opt="r"] string flags open type
--- @tparam[opt] mode number permissions mode if creating.
--- @treturn file|nil File handle, or nil if error
--- @treturn string|nil Error string if error
--- @treturn errno|nil Error number if error
--- @function open
local function open(filename, flags, mode)
    mode = mode or tonumber("666", 8)
    assert(type(filename) == "string", "filename string expected at #1")
    flags = sio_open_flags(flags or "r")

    local r, errno = l_open(filename, flags, sio_mode_flags(mode))
    if r < 0 then
        return err("open", errno)
    end

    return sio_wrap_mt(r, false, filename)
end

local pipe_count = 0

--- Create an anonymous pipe.
--- Returns two files, the first one can be used to read data written
--- to the second.
--- @treturn file|nil Reading half of pipe, or nil on error
--- @treturn file|string Writing half of pipe, or string describing error
--- @treturn errno|nil Error number if error
--- @function pipe
local function pipe()
    local fds = { }
    local r, errno = l_pipe(fds)

    if r ~= 0 then
        return err("pipe", errno)
    end

    local pipename1 = ("<anonpipe %d/reader>"):format(pipe_count)
    local pipename2 = ("<anonpipe %d/writer>"):format(pipe_count)
    pipe_count = pipe_count + 1

    return sio_wrap_mt(fds[1], false, pipename1),
        sio_wrap_mt(fds[2], false, pipename2)
end

local socketpair_count = 0

--- Create an anonymous UNIX domain socket pair.
--- Returns two files, which can be considered as each end of a bi-directional
--- pipe.
--- @treturn file|nil First socket of the pair, or nil on error
--- @treturn file|string Second socket of the pair, or string describing error
--- @treturn errno|nil Error number if error
--- @function pipe
local function socketpair(type)
    type = type or l.SOCK_STREAM
    local typen = type == l.SOCK_STREAM and "stream" or "datagram"
    local sv = { }
    local r, errno = l_socketpair(l.AF_UNIX, type or l.SOCK_STREAM, 0, sv)

    if r ~= 0 then
        return err("pipe", errno)
    end

    local spname1 = ("<%s socketpair %d/0>"):format(typen, socketpair_count)
    local spname2 = ("<%s socketpair %d/1>"):format(typen, socketpair_count)
    socketpair_count = socketpair_count + 1

    return sio_wrap_mt(sv[1], false, spname1), sio_wrap_mt(sv[2], false, spname2)
end

local function stat(p)
    local r, e = l_stat(p)

    if r < 0 then
        return err("stat", e)
    end

    return e
end

local function lstat(p)
    local r, e = l_lstat(p)

    if r < 0 then
        return err("lstat", e)
    end

    return e
end

local function chmod(file, mode)
    local mode = sio_mode_flags(mode)
    local r, errno = l_chmod(file, mode)

    if r < 0 then
        return err("chmod", errno)
    end

    return r
end

local function umask(mask)
    return l_umask(sio_mode_flags(mask))
end

local function link(existing, new)
    local r, errno = l_link(existing, new)

    if r ~= 0 then
        return err("link", errno)
    end

    return true
end

local function mkfifo(pathname, mode)
    local mode = sio_mode_flags(mode)
    local r, errno = l_mkfifo(pathname, mode)

    if r ~= 0 then
        return err("mkfifo", errno)
    end

    return true
end

local function unlink(pathname)
    local r, errno = l_unlink(pathname)

    if r ~= 0 then
        return err("unlink", errno)
    end

    return true
end

local function rmdir(pathname)
    local r, errno = l_rmdir(pathname)

    if r ~= 0 then
        return err("rmdir", errno)
    end

    return true
end

local function rename(old, new)
    local r, errno = l_rename(old, new)

    if r ~= 0 then
        return err("rename", errno)
    end

    return true
end

--- Network functions.
--- @section net

local function luxio_socket_create(family, socktype)
    socktype = socktype or "tcp" -- default to tcp socket
    local st

    if socktype == "tcp" then
        st = l.SOCK_STREAM
    elseif socktype == "udp" then
        st = l.SOCK_DGRAM
    end

    assert(st ~= nil, "unknown socket type")

    local sock, errno = l_socket(family, st, 0)

    if sock < 0 then
        return err("socket", errno)
    end

    local sockname = ("<socket %s/%s>"):format(
    family == l.AF_INET and "ipv4" or "ipv6", socktype)
    local r = sio_wrap_mt(sock, false, sockname)
    r.sock = { family = family, type = st }

    return r
end

local function inet(socktype)
    return luxio_socket_create(l.AF_INET, socktype)
end

local function inet6(socktype)
    return luxio_socket_create(l.AF_INET6, socktype)
end

local function connect(host, serv)
    serv = tostring(serv)
    assert(type(host) == "string", "host string expected at #1")
    assert(type(serv) == "string", "service string expected at #2")

    local r, addrinfo = l_getaddrinfo(host, serv, 0, l.AF_UNSPEC, l.SOCK_STREAM)
    if r < 0 then
        return nil, ("getaddrinfo: %s"):format(l_gai_strerror(r)), r
    end

    local sock, addr, errno
    for idx, ai in ipairs(addrinfo) do
        sock, errno = l_socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
        if sock < 0 then
            -- can't create this type of socket
            sock = nil
        else
            r, errno = l_connect(sock, ai.ai_addr)
            if r < 0 then
                -- can't connect to this address
                l_close(sock)
                sock = nil
            else
                -- we connected!
                addr = ai
                break
            end
        end
    end

    if sock == nil then
        -- we couldn't connect, return the last error
        return err("unable to connect", errno)
    end

    local sockname = ("<socket %s/tcp %s %d connected>"):format(
        addr.ai_family == l.AF_INET and "ipv4" or "ipv6",
        addr.ai_addr.address, addr.ai_addr.port)

    r = sio_wrap_mt(sock, false, sockname)
    r.sock = {
        family = addr.ai_family,
        type = addr.ai_socktype,
        addr = addr.ai_addr
    }

    return r
end

local function bind(host, serv, backlog)
    host = host or "::"
    serv = tostring(serv)
    assert(type(serv) == "string", "service string expected at #2")
    backlog = backlog or 32

    local r, addrinfo = l_getaddrinfo(host, serv, l.AI_PASSIVE, l.AF_UNSPEC, l.SOCK_STREAM)
    if r < 0 then
        return nil, ("getaddrinfo: %s"):format(l_gai_strerror(r)), r
    end

    local sock, errno, addr
    for idx, ai in ipairs(addrinfo) do
        sock, errno = l_socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
        if sock < 0 then
            -- can't creat this tpe of socket
            sock = nil
        else
            l_setsockopt(sock, l.SOL_SOCKET, l.SO_REUSEADDR, 1)
            r, errno = l_bind(sock, ai.ai_addr)
            if r < 0 then
                -- can't bind to this address
                l_close(sock)
                sock = nil
            else
                -- we bound!
                addr = ai
                break
            end
        end
    end

    if sock == nil then
        -- we couldn't bind, return the last error
        return err("bind", errno)
    end

    r, errno = l_listen(sock, backlog)
    if r < 0 then
        l_close(sock)
        return err("listen", errno)
    end

    local sockname = ("<socket %s/tcp %s %d bound>"):format(
        addr.ai_family == l.AF_INET and "ipv4" or "ipv6",
        addr.ai_addr.address, addr.ai_addr.port)

    r = sio_wrap_mt(sock, false, sockname)
    r.sock = {
        family = addr.ai_family,
        type = addr.ai_socktype,
        addr = addr.ai_addr
    }

    return r
end

local function accept(o)
    sio_check_mt(o)

    local r, addr = l_accept(o.fd)

    if r < 0 then
        return err("accept", addr)
    end

    local sockname = ("<socket %s/tcp %s %d accepted>"):format(
        addr.family == l.AF_INET and "ipv4" or "ipv6",
        addr.address, addr.port)

    r = sio_wrap_mt(r, false, sockname)
    r.sock = {
        family = addr.family,
        type = l.SOCK_STREAM,
        addr = addr
    }

    return r, addr
end

local function msetsockopt(o, level, option, value)
    sio_check_mt(o)
    assert(type(level) == "number", "level number expected at #2")
    assert(type(option) == "number", "option number expected at #3")
    local r, errno = l_setsockopt(o.fd, level, option, value)
    if r == 0 then
        return true
    end

    return err("setsockopt", errno)
end

local function mgetsockopt(o, level, option)
    sio_check_mt(o)
    assert(type(level) == "number", "level number expected at #2")
    assert(type(option) == "number", "option number expected at #3")
    local r, value = l_getsockopt(o.fd, level, option)
    if r == 0 then
        return value
    end

    return err("getsockopt", errno)
end

local function mbind(o, address, port)
    sio_check_mt(o)
    assert(type(address) == "string", "address string expected at #2")
    assert(type(port) == "number", "port number expected at #3")

    local sockaddr = l_make_sockaddr(o.sock.family, port, address)
    local r, errno = l_bind(o.fd, sockaddr)
    if r < 0 then
        return err("bind", errno)
    end

    o.sock.addr = sockaddr
    o.name = ("<socket %s/%s %s %d bound>"):format(
        o.sock.family == l.AF_INET and "ipv4" or "ipv6",
        o.sock.type == l.SOCK_STREAM and "tcp" or "udp",
        sockaddr.address, sockaddr.port)

    return true
end

local function mlisten(o, backlog)
    sio_check_mt(o)
    backlog = backlog or 32
    local r, errno = l_listen(o.fd, backlog)
    if r < 0 then
        return err("listen", errno)
    end

    return true
end

local function mconnect(o, address, port)
    sio_check_mt(o)
    assert(type(address) == "string", "address string expected at #2")
    assert(type(port) == "number", "port number expected at #3")

    local sockaddr = l_make_sockaddr(o.sock.family, port, address)
    local r, errno = l_connect(o.fd, sockaddr)
    if r < 0 then
        return err("connect", errno)
    end

    o.name = ("<socket %s/%s %s %d connected>"):format(
        o.sock.family == l.AF_INET and "ipv4" or "ipv6",
        o.sock.type == l.SOCK_STREAM and "tcp" or "udp",
        sockaddr.address, sockaddr.port)

    return true
end

local function msend(o, buf, f)
    sio_check_mt(o)
    assert(type(buf) == "string")
    f = flags(f or "")
    
    local r, errno = l_send(o.fd, buf, f);
    
    if r < 0 then
        return err("send", errno);
    end
    
    return r
end

local function mrecv(o, count, f)
    sio_check_mt(o)
    assert(type(count) == "number")
    f = flags(f or "")
    
    local r, errno = l_recv(o.fd, count, f);
    
    if r == -1 then
        return err("recv", errno);
    end
    
    return r
end

descriptor_mt = {
    close = close,
    nogc = nogc,
    nonblocking = nonblocking,

    write = write,
    writev = writev,
    read = read,
    seek = seek,
    chmod = fchmod,
    fchmod = fchmod,
    stat = fstat,
    fstat = stat,
    lock = lock,
    locktest = locktest,

    accept = accept,
    setsockopt = msetsockopt,
    getsockopt = mgetsockopt,
    bind = mbind,
    listen = mlisten,
    connect = mconnect,
    send = msend,
    recv = mrecv,

    __tostring = function(x)
        return ("file descriptor: %s (%s)"):format(
        tostring(x.fd or "closed"), x.name or "<unknown>")
    end,

    __gc = sio_meta_gc,
}

descriptor_mt.__index = descriptor_mt

-- Directory enumeration

local lclosedir = l.closedir
local lreaddir = l.readdir

local function dirent_meta_gc(o)
    if not o.closed then
        lclosedir(o.dir)
    end
end

local dirent_wrap_mt
local dirent_check_mt

local dirent_mt = {
    next = function(o)
        dirent_check_mt(o)

        local r, t = lreaddir(o.dir)

        if r == 0 then
            return t -- next directory entry
        elseif r == nil then
            return nil  -- end of directory
        else
            error("readdir iterator: " .. lstrerror(r))
        end
    end,

    iterate = function(o)
        dirent_check_mt(o)

        return function()
            local r, t = lreaddir(o.dir)
            if r == 0 then
                return t.d_name, t
            elseif r == nil then
                -- end of directory
                return nil
            else
                error("readdir iterator: " .. lstrerror(r))
            end
        end
    end,

    close = function(o)
        dirent_check_mt(o)
        lclosedir(o.dir)
        o.closed = true
    end,

    __gc = dirent_meta_gc
}

dirent_mt.__index = dirent_mt

if lua_version == 5.1 then
    dirent_wrap_mt = function(t)
        t.proxy = newproxy(true)
        getmetatable(t.proxy).__gc = function()
            dirent_meta_gc(t)
        end
        return setmetatable(t, dirent_mt)
    end
else
    dirent_wrap_mt = function(t)
        return setmetatable(t, dirent_mt)
    end
end

dirent_check_mt = function(x)
    if getmetatable(x) ~= dirent_mt then
        error "object passed is not a directory object"
    end
    if x.closed then
        error "directory passed has been closed"
    end
end

local lopendir = l.opendir
local function opendir(path)
    local r, errno = lopendir(path)

    if r == nil then
        return err("opendir", errno)
    end

    return dirent_wrap_mt { dir = r }
end

-- Misc helper functions that do not function on descriptors

local lmkdir = l.mkdir
local function mkdir(path, mode)
    mode = sio_mode_flags(mode or "0755")

    if path == "" or path == "/" then
        return true
    end

    local r, errno = lmkdir(path, mode)

    if r < 0 then
        return err("mkdir", errno)
    end

    return r
end

local lfork = l.fork
local function fork()
    local r, errno = lfork()

    if r == -1 then
        return err("fork", errno)
    end

    return r
end

local lexec = l.exec
local function exec(...)
    local r, errno = lexec(...)

    return err("exec", errno)
end

local lexecp = l.execp
local function execp(...)
    local r, errno = lexecp(...)

    return err("execp", errno)
end

local lwaitpid = l.waitpid
local function waitpid(pid, options)
    pid = pid or -1
    options = options or 0
    local r, errno = waitpid(pid, options)

    if r == -1 then
        return err("waitpid", errno)
    end

    return r
end

local l_kill = l.kill
local SIGTERM = l.SIGTERM
local function kill(pid, signal)
    signal = signal or SIGTERM
    if type(pid) ~= "number" or pid < 1 then
        return nil, "invalid pid passed to kill"
    end

    local r, errno = l_kill(pid, signal)
    if r == -1 then
        return err("kill", errno)
    end

    return r
end

local l_setenv = l.setenv
local function setenv(key, value, overwrite)
    local r, errno = l_setenv(key, value, overwrite and 1 or 0)
    if r == -1 then
        return err("setenv", errno)
    end

    return r
end

local l_unsetenv = l.unsetenv
local function unsetenv(key)
    local r, errno = l_unsetenv(key)

    if r == -1 then
        return err("unsetenv", errno)
    end

    return r
end

local l_chdir = l.chdir
local function chdir(path)
    local r, errno = l_chdir(path)
    if r == -1 then
        return err("chdir", errno)
    end

    return r
end

local l_getcwd = l.getcwd
local function getcwd()
    local r, errno = l_getcwd()

    if r == nil then
        return err("getcwd", errno)
    end

    return r
end

return {
    open = open,
    pipe = pipe,
    socketpair = socketpair,
    inet = inet,
    inet6 = inet6,
    connect = connect,
    bind = bind,

    stat = stat,
    lstat = lstat,

    wrap_fd = sio_wrap_mt,
    tomode = sio_mode_flags,
    umask = umask,
    chmod = chmod,
    link = link,
    mkdir = mkdir,
    mkfifo = mkfifo,
    unlink = unlink,
    rmdir = rmdir,
    rename = rename,
    fork = fork,
    exec = exec,
    execp = execp,
    waitpid = waitpid,
    kill = kill,
    setenv = setenv,
    getenv = l.getenv, -- this call cannot fail
    unsetenv = unsetenv,
    opendir = opendir,
    chdir = chdir,
    getcwd = getcwd,

    stdin = sio_wrap_mt(l.STDIN_FILENO, true, "<stdin>"),
    stdout = sio_wrap_mt(l.STDOUT_FILENO, true, "<stdout>"),
    stderr = sio_wrap_mt(l.STDERR_FILENO, true, "<stderr>"),

    luxio = l,
    
    flags = flags,

    _VERSION = "Luxio Simple Interface " .. tostring(l._RELEASE),
    _COPYRIGHT = "Copyright 2012 Rob Kendrick <rjek+luxio@rjek.com>",
    _RELEASE = l._RELEASE
}