-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstorage.lua
93 lines (83 loc) · 2.78 KB
/
storage.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
local storage = {}
--[[
This is a module that allows plugins to manage their own storage. Each plugin
basically gets assigned a folder in which it can read and/or write [to] whatever
file it needs. There's no size limit, so a plugin can "easily" fill up the
entire hard disk rendering the system useless. Plugins are kind of sandboxed
to prevent most kinds of damage, but you're still supposed to check them before
downloading/installing/enabling/whatever any from an untrusted source.
]]
storage.new = function(name)
if not name or name:match("[/'\n]") then return end
-- No slashes allowed in folder name. Any attempt to do so will result in naught. Single quotes and newlines are out, too.
local f, e, c = io.open("storage/" .. name)
-- Checking if the folder exists
if not f then
-- Could not open folder
if c == 2 then
-- Folder doesn't exist, creating it
os.execute("mkdir -p storage/" .. name)
else
-- Any other reason, bail out
return nil, e, c
end
else
-- Folder exists. Or a file with its name, but that's f***ed up.
f:close()
end
local t = {}
t.write = function(filename, ...)
if filename:match("/") then return end
-- No slashes allowed in file name. Not allowing any kind of directory access.
local f, e, c = io.open("storage/" .. name .. "/" .. filename, "wb")
if not f then
-- File does not exist.
return f, e, c
end
local s, r, e, c = pcall(f.write, f, ...)
-- Trying to write to the file; errors are "propagated" as return nil, stuff
if not s then return s, r end
if not r then return r, e, c end
f:close()
end
t.read = function(filename, what)
if filename:match("/") then return end
-- No slashes allowed in file name. Not allowing any kind of directory access.
local f, e, c = io.open("storage/" .. name .. "/" .. filename, "rb")
if not f then
-- File does not exist.
return f, e, c
end
local s, r, e, c = pcall(f.read, f, what or "*a")
-- Trying to read from the file; errors are "propagated" as return nil, stuff
if not s then return s, r end
if not r then return r, e, c end
f:close()
return r
end
t.append = function(filename, ...)
-- Same thing as above; appends to a file.
if filename:match("/") then return end
local f, e, c = io.open("storage/" .. name .. "/" .. filename, "ab")
if not f then
return f, e, c
end
local s, r, e, c = pcall(f.write, f, ...)
if not s then return s, r end
if not r then return r, e, c end
f:close()
end
t.list = function()
local p = io.popen("ls 'storage/" .. name .. "'")
local line = p:read '*l'
local t = {}
while line do
t[#t+1] = line
line = p:read '*l'
end
p:close()
return t
end
return t
end
return storage