1
0
mirror of https://github.com/lxsang/antd-web-apps synced 2024-11-20 02:18:20 +01:00

use silk framework for os

This commit is contained in:
Xuan Sang LE 2018-09-12 18:31:25 +02:00
parent 8550dab61c
commit 90f9f116e6
13 changed files with 1233 additions and 0 deletions

10
os/Makefile Normal file
View File

@ -0,0 +1,10 @@
BUILDDIR = ../build/os
copyfiles = views models controllers logs libs router.lua
main:
- mkdir $(BUILDDIR)
- cp -rf $(copyfiles) $(BUILDDIR)
- cd $(BUILDDIR) && ln -s ../grs ./rst
clean:
cd $(BUILDDIR) && rm -rf $(copyfiles)

View File

@ -0,0 +1,33 @@
BaseController:subclass(
"IndexController",
{
registry = {},
models = {}
}
)
function IndexController:actionnotfound(...)
return self:index(table.unpack({...}))
end
function IndexController:index(...)
html()
std.f(WWW_ROOT..DIR_SEP.."index.html")
end
function IndexController:doc(...)
local api = {
author = "Xuan Sang LE",
email = "xsang.le@gmail.com",
api_name = "AntOS API",
version = "0.2.4 a",
documents = {
vfs = HTTP_ROOT.."/VFS",
vdb = HTTP_ROOT.."/VDB",
user = HTTP_ROOT.."/user",
system = HTTP_ROOT.."/system"
}
}
result(api)
return false
end

View File

@ -0,0 +1,196 @@
BaseController:subclass(
"SystemController",
{
registry = {},
models = {}
}
)
function SystemController:actionnotfound(...)
return self:index(table.unpack({...}))
end
function SystemController:index(...)
local api = {
description = "This api handle system operations",
actions = {
["/packages"] = "Handle all operation relate to package: list, install, cache, uninstall",
["/settings"] = "Save user setting",
["/application"] = "Call a specific server side application api",
["/apigateway"] = "Gateway for executing custom server side code"
}
}
result(api)
return false
end
function SystemController:packages(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
local packages = require("packages")
packages.init(rq.args.paths)
if rq ~= nil then
-- check user command here
if (rq.command == "install") then
packages.install(rq.args)
elseif rq.command == "cache" then
packages.cache(rq.args)
elseif rq.command == "list" then
packages.list(rq.args.paths)
elseif rq.command == "uninstall" then
packages.uninstall(rq.args.path)
else
fail("Uknown packages command")
end
else
fail("Uknown request")
end
end
function SystemController:settings(...)
auth_or_die("User unauthorized. Please login")
local user = SESSION.user
if user then
local ospath = require("vfs").ospath("home:///", user)
if REQUEST.query and REQUEST.query.json then
local f = io.open(ospath .. "/" .. ".settings.json", "w")
if f then
f:write(REQUEST.query.json)
f:close()
result(true)
else
fail("Cannot save setting")
end
else
fail("No setting founds")
end
else
fail("User not found")
end
end
function SystemController:application(...)
auth_or_die("User unauthorized. Please login")
local rq = nil
if REQUEST.query.json ~= nil then
rq = (JSON.decodeString(REQUEST.query.json))
else
rq = REQUEST.query
end
if rq.path ~= nil then
local pkg = require("vfs").ospath(rq.path)
if pkg == nil then
pkg = WWW_ROOT .. "/packages/" .. rq.path
--die("unkown request path:"..rq.path)
end
pkg = pkg .. "/api.lua"
if ulib.exists(pkg) then
dofile(pkg).exec(rq.method, rq.arguments)
else
fail("Uknown application handler: " .. pkg)
end
else
fail("Uknown request")
end
end
function SystemController:apigateway(...)
local use_ws = false
if REQUEST.query and REQUEST.query.ws == "1" then
-- override the global echo command
echo = std.ws.swrite
use_ws = true
else
std.json()
end
local exec_with_user_priv = function(data)
local uid = ulib.uid(SESSION.user)
if not ulib.setgid(uid.gid) or not ulib.setuid(uid.id) then
echo("Cannot set permission to execute the code")
return
end
local r, e
e = "{'error': 'Unknow function'}"
if data.code then
r, e = load(data.code)
if r then
local status, result = pcall(r)
if (status) then
echo(JSON.encode(result))
else
echo(result)
end
else
echo(e)
end
elseif data.path then
r, e = loadfile(data.path)
if r then
local status, result = pcall(r, data.parameters)
if (status) then
echo(JSON.encode(result))
else
echo(result)
end
else
echo(e)
end
else
echo(e)
end
end
if (is_auth()) then
local pid = ulib.fork()
if (pid == -1) then
echo("{'error':'Cannot create process'}")
elseif pid > 0 then -- parent
-- wait for the child exit
ulib.waitpid(pid)
print("Parent exit")
else -- child
if use_ws then
if std.ws.enable() then
-- read header
local header = std.ws.header()
if header then
if header.mask == 0 then
print("Data is not masked")
std.ws.close(1012)
elseif header.opcode == std.ws.CLOSE then
print("Connection closed")
std.ws.close(1000)
elseif header.opcode == std.ws.TEXT then
-- read the file
local data = std.ws.read(header)
if data then
data = (JSON.decodeString(data))
exec_with_user_priv(data)
std.ws.close(1011)
else
echo("Error: Invalid request")
std.ws.close(1011)
end
end
else
std.ws.close(1011)
end
else
print("Web socket is not available.")
end
else
if REQUEST.query.json then
data = JSON.decodeString(REQUEST.query.json)
--std.json()
exec_with_user_priv(data)
else
fail("Unkown request")
end
end
print("Child exit")
end
else
echo('{"error":"User unauthorized. Please login"}')
end
end

View File

@ -0,0 +1,96 @@
BaseController:subclass(
"UserController",
{
registry = {},
models = {}
}
)
function UserController:actionnotfound(...)
return self:index(table.unpack({...}))
end
function UserController:index(...)
local api = {
description = "This api handle the user authentification",
actions = {
["/auth"] = "Return user information if a user is alreay logged in",
["/login"] = "Perform a login operation",
["/logout"] = "Perform a logout operation"
}
}
result(api)
return false
end
--[[
request query: none
return:
]]
function UserController:auth(...)
auth_or_die("User unauthorized. Please login")
local user = require("uman").userinfo(SESSION.user)
result(user)
return false
end
--[[ request:
{"username":"mrsang", "password":"pass"}
return:
{} ]]
function UserController:login(...)
if REQUEST.query.json ~= nil then
local request = JSON.decodeString(REQUEST.query.json)
local r = ulib.auth(request.username,request.password)
if r == true then
local cookie = {sessionid=std.sha1(request.username..request.password)} -- iotos_user = request.username
local db = sysdb();
if db == nil then return fail("Cannot setup session") end
local cond = {exp= {["="] = { sessionid = cookie.sessionid }}}
local data = db:find(cond)
--print(data)
if data == nil or data[1] == nil then
--print("insert new data")
data = {sessionid = cookie.sessionid, username=request.username, stamp=os.time(os.date("!*t"))}
else
data = data[1]
--print("Update old data")
data.stamp = os.time(os.date("!*t"))
end
if data.id == nil then
db:insert(data)
else
db:update(data)
end
db:close()
std.cjson(cookie)
SESSION.user = request.username
local user = {
result = require("uman").userinfo(request.username),
error = false
}
std.t(JSON.encode(user))
else
fail("Invalid login")
end
else
fail("Invalid request")
end
return false
end
function UserController:logout(...)
if SESSION.sessionid ~= nil and SESSION.sessionid ~= '0' then
local cookie = {sessionid='0'}
local db = sysdb()
if db ~= nil then
local cond = {["="] = { sessionid = SESSION.sessionid }}
db:delete(cond)
db:close()
end
std.cjson(cookie)
else
std.json()
end
std.t(JSON.encode({error=false,result=true}))
end

View File

@ -0,0 +1,130 @@
BaseController:subclass(
"VDBController",
{
registry = {},
models = {}
}
)
function VDBController:actionnotfound(...)
return self:index(table.unpack({...}))
end
function VDBController:index(...)
local api = {
description = "This api handle database operation",
actions = {
["/save"] = "Save a record to a table",
["/get"] = "Get all records or Get a record by id",
["/select"] = "Select records by a condition",
["/delete"] = "Delete record(s) by condition or by id"
}
}
result(api)
return false
end
function VDBController:save(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if (rq ~= nil and rq.table ~= nil) then
local model = require("dbmodel").get(SESSION.user, rq.table, rq.data)
local ret
if model == nil then
fail("Cannot get table metadata:" .. rq.table)
else
if (rq.data.id ~= nil) then
rq.data.id = tonumber(rq.data.id)
ret = model:update(rq.data)
else
ret = model:insert(rq.data)
end
model:close()
if ret == true then
result(ret)
else
fail("Cannot modify/update table " .. rq.table)
end
end
else
fail("Unknown database request")
end
return false
end
function VDBController:get(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if (rq ~= nil and rq.table ~= nil) then
local model = require("dbmodel").get(SESSION.user, rq.table, nil)
local ret
if model == nil then
fail("Cannot get table metadata:" .. rq.table)
else
if (rq.id == nil) then
ret = model:getAll()
else
ret = model:get(rq.id)
end
model:close()
result(ret)
end
else
fail("Unknown database request")
end
end
function VDBController:select(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if (rq ~= nil and rq.table ~= nil) then
local model = require("dbmodel").get(SESSION.user, rq.table, nil)
local ret
if model == nil then
fail("Cannot get table metadata:" .. rq.table)
else
if (rq.cond == nil) then
model:close()
return fail("Unknow condition")
else
ret = model:find(rq.cond)
end
model:close()
result(ret)
end
else
fail("Unknown database request")
end
end
function VDBController:delete(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if (rq ~= nil and rq.table ~= nil) then
local model = require("dbmodel").get(SESSION.user, rq.table, nil)
local ret
if model == nil then
fail("Cannot get table metadata:" .. rq.table)
else
if (rq.id == nil) then
if (rq.cond) then
ret = model:delete(rq.cond)
model:close()
else
model:close()
return fail("Unknow element to delete")
end
else
ret = model:deleteByID(rq.id)
model:close()
end
if ret then
result(ret)
else
fail("Querry error or database is locked")
end
end
else
fail("Unknown database request")
end
end

View File

@ -0,0 +1,249 @@
BaseController:subclass(
"VFSController",
{
registry = {},
models = {}
}
)
function VFSController:actionnotfound(...)
return self:index(table.unpack({...}))
end
function VFSController:index(...)
local api = {
description = "This api handle file operations",
actions = {
["/fileinfo"] = "Get file information",
["/exists"] = "Check if file exists",
["/delete"] = "Delete a file",
["/get"] = "Get a file content",
["/mkdir"] = "Create directory",
["/move"] = "Move file to a new destination",
["/publish"] = "Share a file to all users",
["/scandir"] = "List all files and folders",
["/write"] = "Write data to file",
["/shared"] = "Get shared file content"
}
}
result(api)
return false
end
function VFSController:fileinfo(...)
auth_or_die("User unauthorized. Please login")
local vfspath = (JSON.decodeString(REQUEST.query.json)).path
local r, m = require("vfs").fileinfo(vfspath)
if r then
result(m)
else
fail(m)
end
return false
end
function VFSController:exists(...)
auth_or_die("User unauthorized. Please login")
local vfs = require("vfs")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
result(vfs.exists(rq.path))
else
fail("Uknown request")
end
return false
end
function VFSController:delete(...)
auth_or_die("User unauthorized. Please login")
local vfs = require("vfs")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local r, e = vfs.delete(rq.path)
if r then
result(r)
else
fail(e)
end
else
fail("Uknown request")
end
return false
end
function VFSController:get(...)
local args = {...}
local uri = implode(args, "/")
auth_or_die("User unauthorized. Please login")
local vfsfile = utils.decodeURI(uri)
local r, m = require("vfs").checkperm(vfsfile, "read")
if r then
local mime = std.mimeOf(m)
if mime == "audio/mpeg" then
local finfo = ulib.file_stat(m)
local len = tostring(math.floor(finfo.size))
local len1 = tostring(math.floor(finfo.size - 1))
std.status(200, "OK")
std.custom_header("Pragma", "public")
std.custom_header("Expires", "0")
std.custom_header("Content-Type", mime)
std.custom_header("Content-Length", len)
std.custom_header("Content-Disposition", "inline; filename=" .. std.basename(m))
std.custom_header("Content-Range:", "bytes 0-" .. len1 .. "/" .. len)
std.custom_header("Accept-Ranges", "bytes")
std.custom_header("X-Pad", "avoid browser bug")
std.custom_header("Content-Transfer-Encoding", "binary")
std.custom_header("Cache-Control", "no-cache, no-store")
std.custom_header("Connection", "Keep-Alive")
std.custom_header("Etag", "a404b-c3f-47c3a14937c80")
std.header_flush()
else
std.header(mime)
end
if std.is_bin(m) then
std.fb(m)
else
std.f(m)
end
else
fail(m)
end
return false
end
function VFSController:mkdir(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local r, m = require("vfs").mkdir(rq.path)
if r then
result(r)
else
fail(m)
end
else
fail("Uknown request")
end
return false
end
function VFSController:move(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local r, m = require("vfs").move(rq.src, rq.dest)
if r then
result(r)
else
fail(m)
end
else
fail("Uknown request")
end
return false
end
function VFSController:publish(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local p = nil
if rq.publish then
p = require("vfs").ospath(rq.path)
else
p = require("shared").ospath(rq.path)
end
local user = SESSION.user
local uid = ulib.uid(user)
local st = ulib.file_stat(p)
if uid.id ~= st.uid then
die("Only the owner can share or unshare this file")
end
local entry = {sid = std.sha1(p), user = SESSION.user, path = p, uid = uid.id}
local db = require("dbmodel").get("sysdb", "shared", entry)
if db == nil then
die("Cannot get system database")
end
local cond = nil
if rq.publish then
cond = {exp = {["="] = {path = p}}}
local data = db:find(cond)
if data == nil or data[0] == nil then
-- insert entry
db:insert(entry)
end
else
cond = {["="] = {sid = rq.path}}
db:delete(cond)
end
db:close()
result(entry.sid)
else
fail("Uknown request")
end
return false
end
function VFSController:scandir(...)
auth_or_die("User unauthorized. Please login")
local rq = JSON.decodeString(REQUEST.query.json)
local vfspath = rq.path
local r = require("vfs").readDir(vfspath)
if r == nil then
fail("Resource not found: " .. rq.path)
else
--print(JSON.encode(readDir(ospath, vfspath)))
result(r)
end
return false
end
function VFSController:upload(...)
auth_or_die("User unauthorized. Please login")
local vfs = require("vfs")
if REQUEST.query then
local r, m = require("vfs").upload(REQUEST.query.path)
if r then
result(r)
else
fail(m)
end
else
fail("Query not found")
end
return false
end
function VFSController:write(...)
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local r, m = require("vfs").write(rq.path, rq.data)
sqlite.dbclose()
if r then
result(r)
else
fail(m)
end
else
fail("Uknown request")
end
return false
end
function VFSController:shared(sid)
require("shared").get(sid)
end

46
os/libs/common.lua Normal file
View File

@ -0,0 +1,46 @@
require("sqlite")
function fail(msg)
std.json()
std.t(JSON.encode({error=msg}))
end
function result(obj)
std.json()
std.t(JSON.encode({result=obj, error=false}))
end
function die (msg)
fail(msg)
debug.traceback=nil
error("Permission denied")
end
-- check if the sysdb is create, otherwise create the table
function sysdb()
local meta = {}
meta.sessionid = ""
meta.username = ""
meta.stamp = 0
return require("dbmodel").get("sysdb", "sessions", meta)
end
function is_auth()
if SESSION.sessionid == nil or SESSION.sessionid == '0' then return false end
-- query session id from database
local db = sysdb()
if db == nil then return false end
local cond = {exp= {["="] = { sessionid = SESSION.sessionid }}}
local data = db:find(cond)
--print(JSON.encode(data))
db:close()
if data == nil or data[1] == nil then die(msg) end
-- next time check the stamp
SESSION.user = data[1].username
return true
end
function auth_or_die(msg)
if(is_auth() == false) then
die(msg)
end
end

20
os/libs/dbmodel.lua Normal file
View File

@ -0,0 +1,20 @@
local model = {}
model.get = function(name, tbl, data)
local db = DBModel:new{db = name, name=tbl}
db:open()
if db:available() then return db end
if data == nil then return nil end
local meta = {}
--print(JSON.encode(data))
for k,v in pairs(data) do
if type(v) == "number" or type(v) == "boolean" then
meta[k] = "NUMERIC"
else
meta[k] = "TEXT"
end
end
db:createTable(meta)
return db
end
return model

119
os/libs/packages.lua Normal file
View File

@ -0,0 +1,119 @@
local packages={}
local vfs = require("vfs")
local uid = ulib.uid(SESSION.user)
packages._cache = function(y)
local p = vfs.ospath(y)
local f = io.open(p.."/packages.json", "w")
local has_cache = false
local i = 1
local meta = {}
if f then
local files = vfs.readDir(y)
for k,v in pairs(files) do
if v.type == "dir" then
local f1 = io.open(vfs.ospath(v.path.."/package.json"))
if f1 then
local name = std.basename(v.path)
local mt = JSON.decodeString(f1:read("*all"))
mt.path = v.path
meta[i] ='"'..name..'":'..JSON.encode(mt)
i = i+1
f1:close()
has_cache = true;
end
end
end
f:write(table.concat(meta, ","))
f:close()
if has_cache == false then
ulib.delete(p.."/packages.json");
end
end
end
-- we will change this later
packages.list = function(paths)
std.json()
std.t("{\"result\" : { ")
local first = true
--std.f(__ROOT__.."/system/packages.json")
for k,v in pairs(paths) do
local osp = vfs.ospath(v.."/packages.json")
if ulib.exists(osp) == false then
packages._cache(v)
end
if ulib.exists(osp) then
if first == false then
std.t(",")
else
first = false
end
std.f(osp)
end
end
std.t("}, \"error\":false}")
end
-- generate the packages caches
packages.cache = function(args)
-- perform a packages caches
for x,y in pairs(args.paths) do
packages._cache(y)
end
result(true)
end
-- install a function from zip file
packages.install = function(args)
local path = vfs.ospath(args.dest)
local zip = vfs.ospath(args.zip)
if(ulib.exists(path) == false) then
-- create directory if not exist
ulib.mkdir(path)
-- change permission
ulib.chown(path, uid.id, uid.gid)
end
-- extract the zip file to it
if(ulib.unzip(zip, path)) then
-- read metadata
local meta = JSON.decodeFile(path.."/metadata.json")
meta.path = args.dest
meta.scope = "user"
local f=io.open(path.."/package.json","w")
if f then
f:write(JSON.encode(meta))
f:close()
end
result(true)
else
fail("Problem extracting zip file")
end
end
-- uninstall the package
packages.uninstall = function(path)
local osf = vfs.ospath(path)
if(osf and ulib.exists(osf) ) then
--remove it
ulib.delete(osf)
result(true)
else
fail("Cannot find package")
end
end
-- set user packages environment
packages.init = function(paths)
if(paths) then
for k,v in pairs(paths) do
local p = vfs.ospath(v)
if p and (ulib.exists(p) == false) then
ulib.mkdir(p)
-- change permission
ulib.chown(p, uid.id, uid.gid)
end
end
end
end
return packages

52
os/libs/shared.lua Normal file
View File

@ -0,0 +1,52 @@
local shared = {}
shared.get = function(sharedid)
if sharedid == "all" then
-- get all shared files
local db = require("dbmodel").get("sysdb", "shared", nil)
if db == nil then die("Cannot get shared database") end
local data = db:getAll()
if data == nil then die("No file found") end
local i = 1
local ret = {}
for k,v in pairs(data) do
if(ulib.exists(v.path)) then
local r = ulib.file_stat(v.path)
if(r.error == nil) then
r.path = "shared://"..v.sid
r.filename = std.basename(v.path)
if r.mime == "application/octet-stream" then
r.mime = std.extra_mime(r.filename)
end
ret[i] = r
i = i+1
end
else
local cond = { ["="] = { sid = v.sid } }
db:delete(cond)
end
end
db:close()
--std.json()
result(ret)
else
local p = shared.ospath(sharedid)
std.header(std.mimeOf(p))
if std.is_bin(p) then
std.fb(p)
else
std.f(p)
end
end
end
shared.ospath = function(sharedid)
local db = require("dbmodel").get("sysdb", "shared", nil)
if db == nil then die("Cannot get shared database") end
local cond = { exp = { ["="] = { sid = sharedid } } }
local data = db:find(cond)
db:close()
if data == nil or data[1] == nil then die("Cannot get shared file with: "..sharedid) end
return data[1].path
end
return shared;

27
os/libs/uman.lua Normal file
View File

@ -0,0 +1,27 @@
local uman={}
uman.userinfo = function(user)
local info = {}
local uid = ulib.uid(user)
if uid then
-- read the setting
-- use the decodeFile function of JSON instead
local file = require('vfs').ospath("home:///").."/.settings.json"
local st = JSON.decodeFile(file)
if(st) then
info = st
end
info.user = {
username = user,
id = uid.id,
name = user,
groups = uid.groups
}
--print(JSON.encode(info))
return info
else
return {}
end
end
return uman

214
os/libs/vfs.lua Normal file
View File

@ -0,0 +1,214 @@
local vfs = {}
vfs.ospath = function(path)
local user = SESSION.user
local prefix = string.match(path, "%a+://")
if(prefix ~= nil) then
local suffix = string.gsub(path,prefix,"")
if prefix == "home://" then
return string.format(VFS_HOME,user)..'/'..suffix
elseif prefix == "desktop://" then
return string.format(VFS_HOME,user).."/.desktop/"..suffix
elseif prefix == "shared://" then
return require("shared").ospath(std.trim(suffix,"/"))
elseif prefix == "os://" then
return WWW_ROOT.."/"..suffix
else
return nil
end
else
return nil;
end
end
vfs.delete = function(path)
local r,m = vfs.checkperm(path,"write")
if r then
if ulib.delete(m) then
-- change permission
return true,nil
else
return false,"Cant not delete the file"
end
else
return r,m
end
end
vfs.exists = function(path)
local osfile = vfs.ospath(path)
return ulib.exists(osfile)
end
vfs.fileinfo = function(vfspath)
local ospath = vfs.ospath(vfspath)
if ospath then
if(ulib.exists(ospath) == false) then return false,"File not found" end
local r = ulib.file_stat(ospath)
if(r.error ~= nil) then return false,r.error end
r.path = vfspath
r.name = std.basename(vfspath)
if r.mime == "application/octet-stream" then
r.mime = std.extra_mime(r.name)
end
return true,r
else
return false,"Resource not found"
end
end
vfs.mkdir = function(path)
local file = std.basename(path)
local folder = string.gsub(path, utils.escape_pattern(file),"")
local r,m = vfs.checkperm(folder,"write")
if r then
local osfile = m.."/"..file
local uid = ulib.uid(SESSION.user)
ulib.mkdir(osfile)
-- change permission
ulib.chown(osfile, uid.id, uid.gid)
return true,nil
else
return r,m
end
end
vfs.move = function(src,dest)
local file = std.basename(dest)
local folder = string.gsub(dest, utils.escape_pattern(file),"")
local sp,sm = vfs.checkperm(src,"write")
if sp then
local dp,dm = vfs.checkperm(folder,"write")
if dp then
ulib.move(sm,dm.."/"..file)
-- change permission
return true,nil
else
return dp,dm
end
else
return sp,sm
end
end
vfs.write = function(path,data)
local file = std.basename(path)
local folder = string.gsub(path, utils.escape_pattern(file),"")
local r,m = vfs.checkperm(folder,"write")
if r then
local osfile = m.."/"..file
if ulib.exists(osfile) then
local r1,m1 = vfs.checkperm(path,"write")
if not r1 then
return r1, m1..": "..path
end
end
local uid = ulib.uid(SESSION.user)
--
if data ~= "" then
local header = string.match(data, "^data%:%w+%/%w+;base64,")
if header ~= nil then
local b64data = string.gsub(data, header,"")
local barr = std.b64decode(b64data)
if std.isBinary(osfile) then
bytes.write(barr,osfile)
else
local f = io.open(osfile, "w")
f:write(bytes.__tostring(barr))
f:close()
end
end
else
bytes.write(bytes.new(0),osfile)
end
--f:close()
-- change permission
ulib.chown(osfile, uid.id, uid.gid)
return true,nil
else
return r,m..": "..folder
end
end
vfs.upload = function(path)
local r,m = vfs.checkperm(path,"write")
if(r) then
local uid = ulib.uid(SESSION.user)
local file = m.."/"..REQUEST.query["upload.file"]
ulib.move(REQUEST.query["upload.tmp"], file)
ulib.chown(file, uid.id, uid.gid)
return true, nil
else
return r,m
end
end
vfs.checkperm = function(path, right)
local osfile = vfs.ospath(path)
local perm = vfs.perm(osfile)
print(osfile)
if not ulib.exists(osfile) then
return false,"Resource does not exist"
end
-- check if user own the file
if perm ~= nil then
if perm[right] == true then
print("Permission granted")
return true,osfile
else
print("Permission denie")
return false,"You dont have "..right.." permission on this file"
end
else
return false,"User is unrecognized"
end
end
vfs.perm = function(file)
local user = SESSION.user
local uid = ulib.uid(user)
local st = ulib.file_stat(file)
-- check if user own the file
if uid ~= nil and st ~= nil and st.perm ~= nil then
--print(JSON.encode({uid, st}))
if(uid.id == st.uid) then -- the user owned the file
print("file belong to user")
return st.perm.owner
elseif uid.groups and uid.groups[st.gid] then
print("User belong to this group")
return st.perm.group
else
print("User belong to other")
return st.perm.other
end
else
return nil
end
end
vfs.readDir = function(vfspath)
if(string.sub(vfspath,-1) == "/") then
prefix = string.sub(vfspath,1,-2)
else
prefix = vfspath
end
local ospath = vfs.ospath(vfspath,SESSION.user)
local r = ulib.read_dir(ospath, prefix)
if(r.error ~= nil) then return nil end
-- add extra mime type
for k,v in pairs(r) do
if v.mime == "application/octet-stream" then
v.mime = std.extra_mime(v.filename)
end
end
return r
end
return vfs

41
os/router.lua Normal file
View File

@ -0,0 +1,41 @@
-- the rewrite rule for the framework
-- should be something like this
-- ^\/apps\/+(.*)$ = /apps/router.lua?r=<1>&<query>
-- some global variables
DIR_SEP = "/"
WWW_ROOT = "/opt/www/htdocs/os"
HTTP_ROOT = "https://wos.localhost:9195"
-- class path: path.to.class
BASE_FRW = ""
-- class path: path.to.class
CONTROLLER_ROOT = BASE_FRW.."os.controllers"
MODEL_ROOT = BASE_FRW.."os.models"
-- file path: path/to/file
VIEW_ROOT = WWW_ROOT..DIR_SEP.."views"
LOG_ROOT = WWW_ROOT..DIR_SEP.."logs"
VFS_HOME = "/home/%s"
package.path = package.path..";"..WWW_ROOT .. '/libs/?.lua'
-- require needed library
require(BASE_FRW.."silk.api")
require("common")
-- registry object store global variables
local REGISTRY = {}
-- set logging level
REGISTRY.logger = Logger:new{ levels = {INFO = true, ERROR = true, DEBUG = true}}
REGISTRY.db = DBHelper:new{db="sysdb"}
REGISTRY.layout = 'default'
REGISTRY.fileaccess = true
REGISTRY.db:open()
local router = Router:new{registry = REGISTRY}
REGISTRY.router = router
router:setPath(CONTROLLER_ROOT)
router:delegate()
if REGISTRY.db then REGISTRY.db:close() end