/
init.lua
584 lines (507 loc) · 16 KB
/
init.lua
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
--[[
POSIX library for Lua 5.1, 5.2 & 5.3.
Copyright (C) 2013-2018 Gary V. Vaughan
Copyright (C) 2010-2013 Reuben Thomas <rrt@sc3d.org>
Copyright (C) 2008-2010 Natanael Copa <natanael.copa@gmail.com>
]]
--[[--
Lua POSIX bindings.
In addition to the convenience functions documented in this module, many
APIs from submodules are copied into the return table for backwards
compatibility and, if necessary, wrapped to match the deprecated API.
This means that your old code will continue to work, but that you can
use the improved documented APIs in new code.
@module posix
]]
local bit = require "bit32"
local M = {}
-- For backwards compatibility, copy all table entries into M namespace.
for _, sub in ipairs {
"ctype", "dirent", "errno", "fcntl", "fnmatch", "glob", "grp",
"libgen", "poll", "pwd", "sched", "signal", "stdio", "stdlib", "sys.msg",
"sys.resource", "sys.socket", "sys.stat", "sys.statvfs", "sys.time",
"sys.times", "sys.utsname", "sys.wait", "syslog", "termio", "time",
"unistd", "utime"
} do
local t = require ("posix." .. sub)
for k, v in pairs (t) do
if k ~= "version" then
assert(M[k] == nil, "posix namespace clash: " .. sub .. "." .. k)
M[k] = v
end
end
end
-- Inject deprecated APIs (overwriting submodules) for backwards compatibility.
for k, v in pairs (require "posix.deprecated") do
M[k] = v
end
for k, v in pairs (require "posix.compat") do
M[k] = v
end
local argerror, argtypeerror, checkstring, checktable, toomanyargerror =
M.argerror, M.argtypeerror, M.checkstring, M.checktable, M.toomanyargerror
-- Code extracted from lua-stdlib with minimal modifications
local list = {
sub = function (l, from, to)
local r = {}
local len = #l
from = from or 1
to = to or len
if from < 0 then
from = from + len + 1
end
if to < 0 then
to = to + len + 1
end
for i = from, to do
table.insert (r, l[i])
end
return r
end
}
-- end of stdlib code
--- Check permissions like @{posix.unistd.access}, but for euid.
-- Based on the glibc function of the same name. Does not always check
-- for read-only file system, text busy, etc., and does not work with
-- ACLs &c.
-- @function euidaccess
-- @string file file to check
-- @string mode checks to perform (as for access)
-- @return 0 if access allowed; <code>nil</code> otherwise (and errno is set)
local access, set_errno, stat = M.access, M.set_errno, M.stat
local getegid, geteuid, getgid, getuid =
M.getegid, M.geteuid, M.getgid, M.getuid
local function euidaccess (file, mode)
local euid, egid = geteuid (), getegid ()
if getuid () == euid and getgid () == egid then
-- If we are not set-uid or set-gid, access does the same.
return access (file, mode)
end
local stats = stat (file)
if not stats then
return
end
-- The super-user can read and write any file, and execute any file
-- that anyone can execute.
if euid == 0 and ((not string.match (mode, "x")) or
string.match (stats.st_mode, "x")) then
return 0
end
-- Convert to simple list of modes.
mode = string.gsub (mode, "[^rwx]", "")
if mode == "" then
return 0 -- The file exists.
end
-- Get the modes we need.
local granted = stats.st_mode:sub (1, 3)
if euid == stats.st_uid then
granted = stats.st_mode:sub (7, 9)
elseif egid == stats.st_gid or set.new (posix.getgroups ()):member (stats.st_gid) then
granted = stats.st_mode:sub (4, 6)
end
granted = string.gsub (granted, "[^rwx]", "")
if string.gsub ("[^" .. granted .. "]", mode) == "" then
return 0
end
set_errno (EACCESS)
end
if _DEBUG ~= false then
M.euidaccess = function (...)
local argt = {...}
checkstring ("euidaccess", 1, argt[1])
checkstring ("euidaccess", 2, argt[2])
if #argt > 2 then toomanyargerror ("euidaccess", 2, #argt) end
return euidaccess (...)
end
else
M.euidaccess = euidaccess
end
--- Open a pseudo-terminal.
-- Based on the glibc function of the same name.
-- @fixme add support for term and win arguments
-- @treturn[1] int master file descriptor
-- @treturn[1] int slave file descriptor
-- @treturn[1] string slave file name
-- @return[2] nil
-- @treturn[2] string error message
local bit = require "bit32"
local fcntl = require "posix.fcntl"
local stdlib = require "posix.stdlib"
local unistd = require "posix.unistd"
local bor = bit.bor
local open, O_RDWR, O_NOCTTY = fcntl.open, fcntl.O_RDWR, fcntl.O_NOCTTY
local grantpt, openpt, ptsname, unlockpt =
stdlib.grantpt, stdlib.openpt, stdlib.ptsname, stdlib.unlockpt
local close = unistd.close
local function openpty (term, win)
local ok, errmsg, master, slave, slave_name
master, errmsg = openpt (bor (O_RDWR, O_NOCTTY))
if master then
ok, errmsg = grantpt (master)
if ok then
ok, errmsg = unlockpt (master)
if ok then
slave_name, errmsg = ptsname (master)
if slave_name then
slave, errmsg = open (slave_name, bor (O_RDWR, O_NOCTTY))
if slave then
return master, slave, slave_name
end
end
end
end
close (master)
end
return nil, errmsg
end
if _DEBUG ~= false then
M.openpty = function (...)
local argt = {...}
if #argt > 0 then toomanyargerror ("openpty", 0, #argt) end
return openpty (...)
end
else
M.openpty = openpty
end
--- Exec a command or Lua function.
-- @function execx
-- @tparam table task argument list for @{posix.unistd.execp} or a Lua
-- function, which should read from standard input, write to standard
-- output, and return an exit code
-- @param ... positional arguments to the function
-- @treturn nil on error (normally does not return)
-- @treturn string error message
local unpack = table.unpack or unpack -- 5.3 compatibility
local errno, execp, _exit =
M.errno, M.execp, M._exit
local function execx (task, ...)
if type (task) == "table" then
execp (unpack (task))
-- Only get here if there's an error; kill the fork
local _, n = errno ()
_exit (n)
else
_exit (task (...) or 0)
end
end
if _DEBUG ~= false then
M.execx = function (task, ...)
local argt, typetask = {task, ...}, type (task)
if typetask ~= "table" and typetask ~= "function" then
argtypeerror ("execx", 1, "table or function", task)
end
return execx (task, ...)
end
else
M.execx = execx
end
--- Run a command or function in a sub-process using @{posix.execx}.
-- @function spawn
-- @tparam table task argument list for @{posix.unistd.execp} or a Lua
-- function, which should read from standard input, write to standard
-- output, and return an exit code
-- @param ... as for @{posix.execx}
-- @return values as for @{posix.sys.wait.wait}
local unpack = table.unpack or unpack -- 5.3 compatibility
local fork, wait =
M.fork, M.wait
local function spawn (task, ...)
local pid, err = fork ()
if pid == nil then
return pid, err
elseif pid == 0 then
execx (task, ...)
else
local _, reason, status = wait (pid)
return status, reason -- If wait failed, status is nil & reason is error
end
end
if _DEBUG ~= false then
M.spawn = function (task, ...)
local argt, typetask = {task, ...}, type (task)
if typetask ~= "table" and typetask ~= "function" then
argtypeerror ("spawn", 1, "table or function", task)
end
return spawn (task, ...)
end
else
M.spawn = spawn
end
local close, dup2, fork, pipe, wait, _exit =
M.close, M.dup2, M.fork, M.pipe, M.wait, M._exit
local STDIN_FILENO, STDOUT_FILENO = M.STDIN_FILENO, M.STDOUT_FILENO
--- Close a pipeline opened with popen or popen_pipeline.
-- @function pclose
-- @tparam table pfd pipeline object
-- @return values as for @{posix.sys.wait.wait}, for the last (or only)
-- stage of the pipeline
local function pclose (pfd)
close (pfd.fd)
for i = 1, #pfd.pids - 1 do
wait (pfd.pids[i])
end
local _, reason, status = wait (pfd.pids[#pfd.pids])
return reason, status
end
if _DEBUG ~= false then
M.pclose = function (...)
local argt = {...}
checktable ("pclose", 1, argt[1])
if #argt > 2 then toomanyargerror ("pclose", 1, #argt) end
return pclose (...)
end
else
M.pclose = pclose
end
local function move_fd (from_fd, to_fd)
if from_fd ~= to_fd then
if not dup2 (from_fd, to_fd) then
error "error dup2-ing"
end
close (from_fd)
end
end
--- Run a commands or Lua function in a sub-process.
-- @function popen
-- @tparam table task argument list for @{posix.unistd.execp} or a Lua
-- function, which should read from standard input, write to standard
-- output, and return an exit code
-- @tparam string mode `"r"` for read or `"w"` for write
-- @func[opt] pipe_fn function returning a paired read and
-- write file descriptor (*default* @{posix.unistd.pipe})
-- @treturn pfd pipeline object
-- @see posix.execx
-- @see posix.spawn
local function popen (task, mode, pipe_fn)
local read_fd, write_fd = (pipe_fn or pipe) ()
if not read_fd then
error "error opening pipe"
end
local parent_fd, child_fd, in_fd, out_fd
if mode == "r" then
parent_fd, child_fd, in_fd, out_fd = read_fd, write_fd, STDIN_FILENO, STDOUT_FILENO
elseif mode == "w" then
parent_fd, child_fd, in_fd, out_fd = write_fd, read_fd, STDOUT_FILENO, STDIN_FILENO
else
error "invalid mode"
end
local pid = fork ()
if pid == nil then
error "error forking"
elseif pid == 0 then -- child process
move_fd (child_fd, out_fd)
close (parent_fd)
_exit (execx (task, child_fd, in_fd, out_fd))
end -- parent process
close (child_fd)
return {pids = {pid}, fd = parent_fd}
end
if _DEBUG ~= false then
M.popen = function (task, ...)
local argt, typetask = {task, ...}, type (task)
if typetask ~= "table" and typetask ~= "function" then
argtypeerror ("popen", 1, "table or function", task)
end
checkstring ("popen", 2, argt[2])
if argt[3] ~= nil and type (argt[3]) ~= "function" then
argtypeerror ("popen", 3, "function or nil", argt[3])
end
if #argt > 3 then toomanyargerror ("popen", 3, #argt) end
return popen (task, ...)
end
else
M.popen = popen
end
--- Perform a series of commands and Lua functions as a pipeline.
-- @function popen_pipeline
-- @tparam table t tasks for @{posix.execx}
-- @tparam string mode `"r"` for read or `"w"` for write
-- @func[opt] pipe_fn function returning a paired read and
-- write file descriptor (*default* @{posix.unistd.pipe})
-- @treturn pfd pipeline object
local close, _exit = M.close, M._exit
local function popen_pipeline (tasks, mode, pipe_fn)
local first, from, to, inc = 1, 2, #tasks, 1
if mode == "w" then
first, from, to, inc = #tasks, #tasks - 1, 1, -1
end
local pfd = popen (tasks[first], mode, pipe_fn)
for i = from, to, inc do
local pfd_next = popen (function (fd, in_fd, out_fd)
move_fd (pfd.fd, in_fd)
_exit (execx (tasks[i]))
end,
mode,
pipe_fn)
close (pfd.fd)
pfd.fd = pfd_next.fd
table.insert (pfd.pids, pfd_next.pids[1])
end
return pfd
end
if _DEBUG ~= false then
M.popen_pipeline = function (...)
local argt = {...}
checktable ("popen_pipeline", 1, argt[1])
checkstring ("popen_pipeline", 2, argt[2])
if argt[3] ~= nil and type (argt[3]) ~= "function" then
argtypeerror ("popen_pipeline", 3, "function or nil", argt[3])
end
if #argt > 3 then toomanyargerror ("popen_pipeline", 3, #argt) end
return popen_pipeline (...)
end
else
M.popen_pipeline = popen_pipeline
end
--- Add one gettimeofday() returned timeval to another.
-- @function timeradd
-- @param x a timeval
-- @param y another timeval
-- @return x + y, adjusted for usec overflow
local function timeradd (x, y)
local sec, usec = 0, 0
if x.tv_sec or x.tv_usec then
sec = sec + (tonumber (x.tv_sec) or 0)
usec = usec + (tonumber (x.tv_usec) or 0)
else
sec = sec + (tonumber (x.sec) or 0)
usec = usec + (tonumber (x.usec) or 0)
end
if y.tv_sec or y.tv_usec then
sec = sec + (tonumber (y.tv_sec) or 0)
usec = usec + (tonumber (y.tv_usec) or 0)
else
sec = sec + (tonumber (y.sec) or 0)
usec = usec + (tonumber (y.usec) or 0)
end
while usec > 1000000 do
sec = sec + 1
usec = usec - 1000000
end
return { sec = sec, usec = usec }
end
if _DEBUG ~= false then
M.timeradd = function (...)
local argt = {...}
checktable ("timeradd", 1, argt[1])
checktable ("timeradd", 2, argt[2])
if #argt > 2 then toomanyargerror ("timeradd", 2, #argt) end
return timeradd (...)
end
end
--- Compare one gettimeofday() returned timeval with another
-- @function timercmp
-- @param x a timeval
-- @param y another timeval
-- @return 0 if x and y are equal, >0 if x is newer, <0 if y is newer
local function timercmp (x, y)
local x = { sec = x.tv_sec or x.sec or 0, usec = x.tv_usec or x.usec or 0 }
local y = { sec = y.tv_sec or y.sec or 0, usec = y.tv_usec or y.usec or 0 }
if x.sec ~= y.sec then
return x.sec - y.sec
else
return x.usec - y.usec
end
end
if _DEBUG ~= false then
M.timercmp = function (...)
local argt = {...}
checktable ("timercmp", 1, argt[1])
checktable ("timercmp", 2, argt[2])
if #argt > 2 then toomanyargerror ("timercmp", 2, #argt) end
return timercmp (...)
end
end
--- Subtract one gettimeofday() returned timeval from another.
-- @function timersub
-- @param x a timeval
-- @param y another timeval
-- @return x - y, adjusted for usec underflow
local function timersub (x,y)
local sec, usec = 0, 0
if x.tv_sec or x.tv_usec then
sec = (tonumber (x.tv_sec) or 0)
usec =(tonumber (x.tv_usec) or 0)
else
sec = (tonumber (x.sec) or 0)
usec = (tonumber (x.usec) or 0)
end
if y.tv_sec or y.tv_usec then
sec = sec - (tonumber (y.tv_sec) or 0)
usec = usec - (tonumber (y.tv_usec) or 0)
else
sec = sec - (tonumber (y.sec) or 0)
usec = usec - (tonumber (y.usec) or 0)
end
while usec < 0 do
sec = sec - 1
usec = usec + 1000000
end
return { sec = sec, usec = usec }
end
if _DEBUG ~= false then
M.timersub = function (...)
local argt = {...}
checktable ("timersub", 1, argt[1])
checktable ("timersub", 2, argt[2])
if #argt > 2 then toomanyargerror ("timersub", 2, #argt) end
return timersub (...)
end
end
--- Find all files in this directory matching a shell pattern.
-- The flag MARK appends a trailing slash to matches that are directories.
-- @function glob
-- @tparam table|string|nil args the three possible parameters can be used to
-- override the default values for `pattern` and `MARK`, which are `"*"` and
-- `false` respectively. A table will be checked for optional keys `pattern`
-- and `MARK`. A string will be used as the glob pattern.
-- @treturn table matching files and directories
local posix_glob = require "posix.glob"
local function glob (args)
-- Support previous `glob ".*"` style calls.
if type(args) == "string" then
args = {pattern=args}
elseif type(args) ~= "table" then
args = {}
end
local flags = 0
if args.MARK then
flags = posix_glob.GLOB_MARK
end
return posix_glob.glob(args.pattern, flags)
end
if _DEBUG ~= false then
local validtypes = { ["table"] = true, ["string"] = true, ["nil"] = true }
M.glob = function (...)
local argt = {...}
local argtype = type(argt[1])
if validtypes[argtype] ~= true then
argtypeerror ("glob", 1, "table, string or nil", argt[1])
elseif #argt > 1 then
toomanyargerror ("glob", 1, #argt)
end
return glob (...)
end
else
M.glob = glob
end
return setmetatable (M, {
--- Metamethods
-- @section metamethods
--- Lazy loading of luaposix modules.
-- Don't load everything on initial startup, wait until first attempt
-- to access a submodule, and then load it on demand.
-- @function __index
-- @string name submodule name
-- @treturn table|nil the submodule that was loaded to satisfy the missing
-- `name`, otherise `nil` if nothing was found
-- @usage
-- local version = require 'posix'.version
__index = function (self, name)
local ok, t = pcall (require, 'posix.' ..name)
if ok then
rawset (self, name, t)
return t
end
end,
})