1
0
mirror of https://github.com/lxsang/antd-lua-plugin synced 2025-07-16 13:59:46 +02:00

48 Commits

Author SHA1 Message Date
4259ec7eef allow lua to log to syslog 2022-08-23 01:18:05 +02:00
6276b0aa1e add sendfile support 2022-08-22 22:58:42 +02:00
1cc681c7e8 add lua API for envar manipulating and home dir query 2022-08-22 20:37:10 +02:00
dfb550308d update API to support binary POST data 2022-08-19 19:59:10 +02:00
ae5dbf081e Update Makefile.am 2022-08-03 10:22:31 +02:00
ef888164b7 Update Makefile.am 2022-08-03 09:44:17 +02:00
c5e2de08ca Update Makefile.am 2022-08-03 09:43:15 +02:00
8dc0c7e133 Update Makefile.am 2022-08-03 09:40:04 +02:00
e370f3f7fe Update configure.ac 2022-08-03 09:34:53 +02:00
deaebf1c01 Update Jenkinsfile 2022-08-02 23:47:48 +02:00
45fcfe8726 Update Jenkinsfile 2022-08-02 22:14:41 +02:00
8b8a79bf90 Update Jenkinsfile 2022-08-02 22:10:40 +02:00
88a5354588 Update Jenkinsfile 2022-08-02 22:06:52 +02:00
ad98d1f666 Update Jenkinsfile 2022-08-02 22:05:11 +02:00
faca12a02b Update Jenkinsfile 2022-08-02 22:02:28 +02:00
3069f0dff2 Update Jenkinsfile 2022-08-02 21:56:46 +02:00
3c602dabd0 Update Jenkinsfile 2022-08-02 21:55:31 +02:00
1396fe3d41 Update Jenkinsfile 2022-08-02 08:43:20 +02:00
2ad3b4dfb4 Update Jenkinsfile 2022-08-02 08:33:46 +02:00
f575dd91a9 Update Jenkinsfile 2022-08-02 08:28:56 +02:00
f995bd7f71 Create Jenkinsfile 2022-08-02 08:26:53 +02:00
8a2cf714df Merge branch 'master' of github.com:lxsang/antd-lua-plugin 2021-03-24 18:31:41 +01:00
8b22577c86 improve json handle 2021-03-24 18:31:21 +01:00
fbc5c1c4bb Update .drone.yml 2021-03-19 10:43:13 +01:00
27d2cbfbfb fix wurl bug 2021-02-09 01:13:10 +01:00
36f4dd0941 Delete lib/pibot directory 2021-01-31 18:04:56 +01:00
fbb72201e2 Delete bugbot.lua 2021-01-31 18:02:53 +01:00
83635bbddb Delete example-app directory 2021-01-31 14:09:52 +01:00
ca57959c6d Update .drone.yml 2021-01-27 19:55:31 +01:00
ba20d5c53d Update .drone.yml 2021-01-27 19:54:22 +01:00
33df50753c Update .drone.yml 2021-01-27 08:53:30 +01:00
c84594a490 Create .drone.yml 2021-01-27 01:04:15 +01:00
daf0f641cf clean up 2021-01-03 00:29:29 +01:00
807e56e331 improvement module loader 2021-01-01 15:22:25 +01:00
7bc0a89ef5 add missing header 2021-01-01 14:00:55 +01:00
454217bea2 add missing header 2021-01-01 13:51:36 +01:00
002151f1e2 fix symbol missing 2020-12-28 22:40:43 +01:00
0b6fc559b3 generate archive 2020-12-26 15:07:37 +01:00
14f59390c6 regenrate file 2020-12-26 14:57:21 +01:00
a586901d44 Merge branch 'master' of https://github.com/lxsang/antd-lua-plugin 2020-12-26 14:56:47 +01:00
5e5b76a267 fix security bug 2020-12-26 14:56:38 +01:00
f387ebdfaf Update Makefile 2020-12-25 19:07:56 +01:00
8d7392bc71 Update Makefile 2020-12-25 19:06:30 +01:00
c6f2a05164 Update Makefile 2020-12-25 18:59:43 +01:00
3f33fa217f Update Makefile 2020-12-25 18:56:55 +01:00
d9adec8869 Update Makefile.am 2020-12-25 18:52:17 +01:00
24a681a962 Update Makefile.am 2020-12-25 18:34:38 +01:00
f4976eeea8 Merge pull request #2 from lxsang/add-license-1
Create LICENSE
2020-12-25 17:55:56 +01:00
58 changed files with 491 additions and 2306 deletions

28
.drone.yml Normal file
View File

@ -0,0 +1,28 @@
---
kind: pipeline
type: exec
name: default
platform:
os: linux
arch: amd64
clone:
disable: true
steps:
- name: clone
commands:
- pwd
- git clone ssh://git@iohub.dev:2222/lxsang/antd-lua-plugin.git
- cd ./antd-lua-plugin && git checkout master
- name: build
commands:
- cd ./antd-lua-plugin
- libtoolize
- aclocal
- autoconf
- automake --add-missing
- ./configure --prefix=/opt/cloud/artifacts/plugins
- make
- make install
trigger:
branch:
- master

View File

@ -1,90 +0,0 @@
local pibot = require("pibot")
local bugbot = {}
local cmd = bytes.new(8)
--1 IRL R
--2 IRR R
--3 SNL R
--4 SNH R
--5 ML RW
--6 MR RW
--7 MLS RW
--8 MRL RW
bugbot.init = function()
return pibot.init()
end
bugbot.scan = function()
local raw = pibot.read(64)
if raw then
local data = {}
data.leftIR = raw[0]
data.rightIR = raw[1]
data.sonar = raw[2] + bit32.lshift(raw[3], 8)
data.motors = {}
data.motors.left = {}
data.motors.right = {}
data.motors.left.status = raw[4]
data.motors.left.speed = raw[5]
data.motors.right.status = raw[6]
data.motors.right.speed = raw[7]
return data
end
return nil
end
bugbot.forward = function(sp)
cmd[5] = 1 -- fw
cmd[6] = sp -- fw
cmd[7] = 1
cmd[8] = sp
pibot.write(cmd)
end
bugbot.action = function(st1,sp1,st2,sp2)
cmd[5] = st1 -- bw
cmd[6] = sp1
cmd[7] = st2 -- bw
cmd[8] = sp2
pibot.write(cmd)
end
bugbot.backward = function(sp)
cmd[5] = 2 -- bw
cmd[6] = sp -- bw
cmd[7] = 2
cmd[8] = sp
pibot.write(cmd)
end
bugbot.stop = function()
cmd[5] = 0 -- s
cmd[6] = 0 -- s
cmd[7] = 0
cmd[8] = 0
pibot.write(cmd)
end
bugbot.rotateLeft = function(sp)
cmd[5] = 2 -- bw
cmd[6] = sp -- fw
cmd[7] = 1
cmd[8] = sp
pibot.write(cmd)
end
bugbot.rotateRight = function(sp)
cmd[5] = 1 -- fw
cmd[6] = sp -- bw
cmd[7] = 2
cmd[8] = sp
pibot.write(cmd)
end
bugbot.release = function()
return pibot.release()
end
return bugbot

104
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,104 @@
def build_plugin()
{
sh '''
set -e
cd $WORKSPACE
mkdir -p build/$arch/opt/www
[ -f Makefile ] && make clean
libtoolize
aclocal
autoconf
automake --add-missing
search_path=$(realpath $WORKSPACE/../ant-http/build/$arch/usr)
CFLAGS="-I$search_path/include" LDFLAGS="-L$search_path/lib" ./configure --prefix=/opt/www
CFLAGS="-I$search_path/include" LDFLAGS="-L$search_path/lib" make
DESTDIR=$WORKSPACE/build/$arch make install
'''
}
pipeline{
agent { node{ label'master' }}
options {
// Limit build history with buildDiscarder option:
// daysToKeepStr: history is only kept up to this many days.
// numToKeepStr: only this many build logs are kept.
// artifactDaysToKeepStr: artifacts are only kept up to this many days.
// artifactNumToKeepStr: only this many builds have their artifacts kept.
buildDiscarder(logRotator(numToKeepStr: "1"))
// Enable timestamps in build log console
timestamps()
// Maximum time to run the whole pipeline before canceling it
timeout(time: 3, unit: 'HOURS')
// Use Jenkins ANSI Color Plugin for log console
ansiColor('xterm')
// Limit build concurrency to 1 per branch
disableConcurrentBuilds()
}
stages
{
stage('Build AMD64') {
agent {
docker {
image 'xsangle/ci-tools:latest-amd64'
args '-v /var/jenkins_home/workspace/ant-http:/var/jenkins_home/workspace/ant-http'
// Run the container on the node specified at the
// top-level of the Pipeline, in the same workspace,
// rather than on a new node entirely:
reuseNode true
registryUrl 'http://workstation:5000/'
}
}
steps {
script{
env.arch = "amd64"
}
build_plugin()
}
}
stage('Build ARM64') {
agent {
docker {
image 'xsangle/ci-tools:latest-arm64'
args '-v /var/jenkins_home/workspace/ant-http:/var/jenkins_home/workspace/ant-http'
// Run the container on the node specified at the
// top-level of the Pipeline, in the same workspace,
// rather than on a new node entirely:
reuseNode true
registryUrl 'http://workstation:5000/'
}
}
steps {
script{
env.arch = "arm64"
}
build_plugin()
}
}
stage('Build ARM') {
agent {
docker {
image 'xsangle/ci-tools:latest-arm'
args '-v /var/jenkins_home/workspace/ant-http:/var/jenkins_home/workspace/ant-http'
// Run the container on the node specified at the
// top-level of the Pipeline, in the same workspace,
// rather than on a new node entirely:
reuseNode true
registryUrl 'http://workstation:5000/'
}
}
steps {
script{
env.arch = "arm"
}
build_plugin()
}
}
stage('Archive') {
steps {
script {
archiveArtifacts artifacts: 'build/', fingerprint: true
}
}
}
}
}

View File

@ -24,6 +24,6 @@ SUBDIRS = . lib
EXTRA_DIST = README.md APIs EXTRA_DIST = README.md APIs
install-data-local: install-data-local:
mkdir -p $(prefix)/lib/lua -mkdir -p $(DESTDIR)/$(prefix)/lib/lua
cp -v APIs/* $(prefix)/lib/lua -cp -v APIs/* $(DESTDIR)/$(prefix)/lib/lua
cp -v lib/core/lua-5.3.4/core.so $(prefix)/lib/lua -cp -v lib/core/lua-5.3.4/core.so $(DESTDIR)/$(prefix)/lib/lua

View File

@ -131,10 +131,10 @@ AC_CONFIG_FILES([
lib/md/Makefile lib/md/Makefile
]) ])
if test x"${has_cmake}" == x"yes" ; then #if test x"${has_cmake}" == x"yes" ; then
AC_CONFIG_FILES([lib/ann/Makefile lib/ann/fann/Makefile]) # AC_CONFIG_FILES([lib/ann/Makefile lib/ann/fann/Makefile])
fi #fi
# AC_SUBST([my_CPPFLAGS]) pass my_CPPFLAGS to the makefile.am # AC_SUBST([my_CPPFLAGS]) pass my_CPPFLAGS to the makefile.am
# output the script: # output the script:
AC_OUTPUT AC_OUTPUT

BIN
dist/lua-0.5.2b.tar.gz vendored

Binary file not shown.

View File

@ -1,18 +0,0 @@
{
"viz": {
"mime": "text/vnd.graphviz",
"binary": false
},
"py": {
"mime": "text/x-python",
"binary": false
},
"coffee":{
"mime": "text/vnd.coffeescript",
"binary": false
},
"apj": {
"mime": "text/antos-project",
"binary": false
}
}

View File

@ -1,97 +0,0 @@
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 = unix.uid(SESSION.iotos_user)
if not unix.setgid(uid.gid) or not unix.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 = unix.fork()
if(pid == -1) then
echo("{'error':'Cannot create process'}")
elseif pid > 0 then -- parent
-- wait for the child exit
unix.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

View File

@ -1,29 +0,0 @@
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("db.model").get(SESSION.iotos_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

View File

@ -1,19 +0,0 @@
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("db.model").get(SESSION.iotos_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

View File

@ -1,20 +0,0 @@
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" then
meta[k] = "NUMERIC"
else
meta[k] = "TEXT"
end
end
db:createTable(meta)
return db
end
return model

View File

@ -1,24 +0,0 @@
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("db.model").get(SESSION.iotos_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

View File

@ -1,20 +0,0 @@
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("db.model").get(SESSION.iotos_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

View File

@ -1,15 +0,0 @@
auth_or_die("User unauthorized. Please login")
local vfs = require("fs.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

View File

@ -1,10 +0,0 @@
auth_or_die("User unauthorized. Please login")
local vfs = require("fs.vfs")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
result(vfs.exists(rq.path))
else
fail("Uknown request")
end

View File

@ -1,8 +0,0 @@
auth_or_die("User unauthorized. Please login")
local vfspath = (JSON.decodeString(REQUEST.query.json)).path
local r,m = require("fs.vfs").fileinfo(vfspath)
if r then
result(m)
else
fail(m)
end

View File

@ -1,6 +0,0 @@
local conf = {
home="/Users/%s/tmp/",
shared="/Users/%s/tmp/Public/"
}
return conf

View File

@ -1,14 +0,0 @@
local handler
handler = function(str)
local func = str:match("^%a+/")
if func == "get/" then
require("fs.get")(str:gsub(func,""))
elseif func == "shared/" then
require("fs.shared").get(str:gsub(func,""))
else
fail("Action is not supported: "..func)
end
end
return handler

View File

@ -1,40 +0,0 @@
local get
get = function(uri)
vfsfile = utils.decodeURI(uri)
auth_or_die("User unauthorized. Please login")
local r,m = require("fs.vfs").checkperm(vfsfile,'read')
if r then
local mime = std.mimeOf(m)
if mime == "audio/mpeg" then
local finfo = unix.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
end
return get;

View File

@ -1,11 +0,0 @@
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local r,m = require("fs.vfs").mkdir(rq.path)
if r then result(r) else fail(m) end
else
fail("Uknown request")
end

View File

@ -1,13 +0,0 @@
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local r,m = require("fs.vfs").move(rq.src,rq.dest)
if r then result(r) else fail(m) end
else
fail("Uknown request")
end

View File

@ -1,36 +0,0 @@
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("fs.vfs").ospath(rq.path)
else
p = require("fs.shared").ospath(rq.path)
end
local user = SESSION.iotos_user
local uid = unix.uid(user)
local st = unix.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.iotos_user, path = p, uid = uid.id }
local db = require("db.model").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

View File

@ -1,10 +0,0 @@
auth_or_die("User unauthorized. Please login")
local vfspath = (JSON.decodeString(REQUEST.query.json)).path
local r = require("fs.vfs").readDir(vfspath)
if r == nil then
fail("Resource not found")
else
--print(JSON.encode(readDir(ospath, vfspath)))
result(r)
end

View File

@ -1,52 +0,0 @@
local shared = {}
shared.get = function(sharedid)
if sharedid == "all" then
-- get all shared files
local db = require("db.model").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(unix.exists(v.path)) then
local r = unix.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("db.model").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;

View File

@ -1,8 +0,0 @@
auth_or_die("User unauthorized. Please login")
local vfs = require("fs.vfs")
if REQUEST.query then
local r,m = require("fs.vfs").upload(REQUEST.query.path)
if r then result(r) else fail(m) end
else
fail("Query not found")
end

View File

@ -1,203 +0,0 @@
local vfs = {}
vfs.ospath = function(path)
local user = SESSION.iotos_user
local conf = require("fs.fsconf")
local prefix = string.match(path, "%a+://")
if(prefix ~= nil) then
local suffix = string.gsub(path,prefix,"")
if prefix == "home://" then
return string.format(conf.home,user)..'/'..suffix
elseif prefix == "desktop://" then
return string.format(conf.home,user).."/.desktop/"..suffix
elseif prefix == "shared://" then
return require("fs.shared").ospath(std.trim(suffix,"/"))
elseif prefix == "os://" then
return OSROOT.."/"..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 unix.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 unix.exists(osfile)
end
vfs.fileinfo = function(vfspath)
local ospath = vfs.ospath(vfspath)
if ospath then
if(unix.exists(ospath) == false) then return false,"File not found" end
local r = unix.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 = unix.uid(SESSION.iotos_user)
unix.mkdir(osfile)
-- change permission
unix.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
unix.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
local uid = unix.uid(SESSION.iotos_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
unix.chown(osfile, uid.id, uid.gid)
return true,nil
else
return r,m
end
end
vfs.upload = function(path)
local r,m = vfs.checkperm(path,"write")
if(r) then
local uid = unix.uid(SESSION.iotos_user)
local file = m.."/"..REQUEST.query["upload.file"]
unix.move(REQUEST.query["upload.tmp"], file)
unix.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)
-- 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.iotos_user
local uid = unix.uid(user)
local st = unix.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.iotos_user)
local r = unix.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

View File

@ -1,13 +0,0 @@
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local r,m = require("fs.vfs").write(rq.path, rq.data)
sqlite.dbclose()
if r then result(r) else fail(m) end
else
fail("Uknown request")
end

View File

@ -1 +0,0 @@
result({r = "Welcome to antOS" })

View File

@ -1,10 +0,0 @@
local handle = function(p)
local hstr = p:match("^%a+/")
if hstr == "fs/" then
--print("require module")
require("fs.fsh")(p:gsub(hstr,"",1))
else
fail("Resource not found for request "..p)
end
end
return handle

View File

@ -1,24 +0,0 @@
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("fs.vfs").ospath(rq.path)
if pkg == nil then
pkg = OSROOT..'/packages/'..rq.path
--die("unkown request path:"..rq.path)
end
pkg = pkg.."/api.lua"
if unix.exists(pkg) then
dofile(pkg).exec(rq.method,rq.arguments)
else
fail("Uknown application handler: "..pkg)
end
else
fail("Uknown request")
end

View File

@ -1,3 +0,0 @@
auth_or_die("User unauthorized. Please login")
local user = require("system.uman").userinfo(SESSION.iotos_user)
result(user)

View File

@ -1,17 +0,0 @@
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq ~= nil then
local r,m = require("web").get(rq.url)
if r then
if r.binary then
result({body="data:"..r.contentType..";base64,"..r.data})
else
result({body=r.data})
end
else
fail(m)
end
else
fail("Uknown request")
end

View File

@ -1,39 +0,0 @@
if REQUEST.query.json ~= nil then
local request = JSON.decodeString(REQUEST.query.json)
local r = unix.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.iotos_user = request.username
local user = {
result = require("system.uman").userinfo(request.username),
error = false
}
std.t(JSON.encode(user))
else
fail("Invalid login")
end
else
fail("Invalid request")
end

View File

@ -1,17 +0,0 @@
if SESSION.sessionid ~= nil and SESSION.sessionid ~= '0' then
local cookie = {sessionid='0'}
local db = sysdb()
if db ~= nil then
--local data = db:find("sessionid ='"..SESSION.sessionid.."'")
--if data and data[0] ~= nil then
-- db:delete(data[0].id)
--end
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}))

View File

@ -1,21 +0,0 @@
[
{
"className": "NotePad",
"name": "Source editor",
"description": "Advance text editor",
"category": "development",
"author": "xsang.le@gmail.com",
"version": "0.1",
"download": "http://192.168.1.49:9191/repo/AceEditor.zip"
},
{
"className": "DummyApp",
"name": "Antos features",
"description": "Antos features show case",
"category": "utilities",
"author": "xsang.le@gmail.com",
"version": "1.0",
"download": "https://os.localhost:9195/repo/DummyApp.zip"
}
]

View File

@ -1,588 +0,0 @@
"default/About": {
"className": "ApplicationAbout",
"name": "About OS.js",
"description": "About OS.js",
"names": {
"bg_BG": " За OS.js",
"de_DE": "Über OS.js",
"fr_FR": "À propos d'OS.js",
"it_IT": "Informazioni su OS.js",
"ko_KR": "OS.js에 대하여",
"nl_NL": "Over OS.js",
"no_NO": "Om OS.js",
"pl_PL": "o OS.js",
"ru_RU": "Об OS.js",
"sk_SK": "o OS.js",
"tr_TR": "hakkında OS.js",
"vi_VN": "Thông tin về OS.js"
},
"descriptions": {
"bg_BG": "За OS.js",
"de_DE": "Über OS.js",
"fr_FR": "À propos d'OS.js",
"it_IT": "Informazioni su OS.js",
"ko_KR": "OS.js에 대하여",
"nl_NL": "Over OS.js",
"no_NO": "Om OS.js",
"pl_PL": "o OS.js",
"ru_RU": "Об OS.js",
"sk_SK": "o OS.js",
"tr_TR": "hakkında OS.js",
"vi_VN": "Thông tin về OS.js"
},
"singular": true,
"category": "system",
"icon": "apps/help-browser.png",
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/About",
"build": {},
"repo": "default"
},
"default/AceEditor": {
"className": "ApplicationAceEditor",
"name": "Source Editor",
"icon": "apps/accessories-text-editor.png",
"category": "development",
"mime": [
"^text",
"inode\\/x\\-empty",
"application\\/x\\-empty",
"application\\/x\\-python",
"application\\/x\\-php",
"application\\/javascript"
],
"build": {
"copy": [
"metadata.json",
"scheme.html",
"main.css",
"main.js",
"vendor/ace"
]
},
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/AceEditor",
"repo": "default"
},
"default/Archiver": {
"className": "ApplicationArchiver",
"name": "Archiver",
"mime": [
"application/zip"
],
"icon": "apps/system-software-install.png",
"category": "utilities",
"compability": [
"file",
"blob"
],
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/Archiver",
"build": {},
"repo": "default"
},
"default/Calculator": {
"className": "ApplicationCalculator",
"name": "Calculator",
"names": {
"bg_Bg": "Клакулатор",
"fr_FR": "Calculatrice",
"it_IT": "Calcolatrice",
"ko_KR": "계산기",
"nl_NL": "Rekenmachine",
"no_NO": "Kalkulator",
"pl_PL": "Kalkulator",
"ru_RU": "Калькулятор",
"sk_SK": "Kalkulačka",
"tr_TR": "Hesap Makinesi",
"vi_VN": "Máy tính"
},
"icon": "apps/calc.png",
"category": "office",
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/Calculator",
"build": {},
"repo": "default"
},
"default/CoreWM": {
"className": "CoreWM",
"name": "OS.js Window Manager",
"names": {
"bg_BG": "Мениджър на прозорци на OS.js",
"de_DE": "OS.js Fenster-Manager",
"es_ES": "OS.js Window Manager",
"fr_FR": "Gestionnaire de fenêtre OS.js",
"it_IT": "OS.js Gestore Finestre",
"ko_KR": "OS.js 윈도우 관리자",
"nl_NL": "OS.js venster beheer",
"no_NO": "OS.js Vinduhåndterer",
"pl_PL": "Menedżer Okien OS.js",
"ru_RU": "OS.js Оконный менеджер",
"sk_SK": "Správca Okien OS.js",
"tr_TR": "OS.js Pencere Yöneticisi",
"vi_VN": "Quản lí cửa sổ OS.js"
},
"singular": true,
"type": "windowmanager",
"icon": "apps/gnome-window-manager.png",
"splash": false,
"preload": [{
"src": "scheme.html",
"type": "scheme"
}, {
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}],
"panelItems": {
"AppMenu": {
"Name": "AppMenu",
"Description": "Application Menu",
"Icon": "actions/stock_about.png",
"HasOptions": false
},
"Buttons": {
"Name": "Buttons",
"Description": "Button Bar",
"Icon": "actions/stock_about.png"
},
"Clock": {
"Name": "Clock",
"Description": "View the time",
"Icon": "status/appointment-soon.png",
"HasOptions": true
},
"NotificationArea": {
"Name": "NotificationArea",
"Description": "View notifications",
"Icon": "apps/gnome-panel-notification-area.png"
},
"Search": {
"Name": "Search",
"Description": "Perform searches",
"Icon": "actions/find.png",
"HasOptions": true
},
"Weather": {
"Name": "Weather",
"Description": "Weather notification",
"Icon": "status/weather-few-clouds.png"
},
"WindowList": {
"Name": "Window List",
"Description": "Toggle between open windows",
"Icon": "apps/xfwm4.png"
}
},
"path": "default/CoreWM",
"build": {},
"repo": "default"
},
"default/FileManager": {
"className": "ApplicationFileManager",
"name": "File Manager",
"description": "The default file manager",
"names": {
"bg_BG": "Файлов мениджър",
"de_DE": "Dateimanager",
"fr_FR": "Explorateur de fichier",
"it_IT": "Gestore File",
"nl_NL": "bestands beheer",
"no_NO": "Fil-håndtering",
"pl_PL": "Menedżer Plików",
"ko_KR": "파일 탐색기",
"sk_SK": "Správca súborov",
"ru_RU": "Файловый менеджер",
"tr_TR": "Dosya Yöneticisi",
"vi_VN": "Quản lí file"
},
"descriptions": {
"bg_BG": "Стандартния файлов мениджър",
"de_DE": "Standardmäßiger Dateimanager",
"fr_FR": "Gestionnaire de fichier par défaut",
"it_IT": "Il gestore file predefinito",
"nl_NL": "Standaard bestands beheerder",
"no_NO": "Standard Fil-håndtering program",
"pl_PL": "Domyślny Menedżer Plików",
"ko_KR": "기본 파일 관리자",
"sk_SK": "Štandardný správca súborov",
"ru_RU": "Стандартный файловый менеджер",
"tr_TR": "Varsayılan dosya yöneticisi",
"vi_VN": "Trình quản lí file mặc định"
},
"category": "utilities",
"icon": "apps/file-manager.png",
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/FileManager",
"build": {},
"repo": "default"
},
"default/MarkOn": {
"className": "ApplicationMarkOn",
"name": "MarkOn",
"mime": [
"^text",
"inode\\/x\\-empty",
"application\\/x\\-empty"
],
"category": "office",
"icon": "apps/libreoffice34-writer.png",
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/MarkOn",
"build": {},
"repo": "default"
},
"default/PDFjs": {
"className": "ApplicationPDFjs",
"name": "PDF Viewer",
"description": "PDF Viewer",
"mime": [
"application/pdf"
],
"category": "office",
"icon": "mimetypes/gnome-mime-application-pdf.png",
"build": {
"copy": [
"metadata.json",
"scheme.html",
"main.css",
"main.js",
"vendor/pdf.js"
]
},
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/PDFjs",
"repo": "default"
},
"default/Preview": {
"className": "ApplicationPreview",
"name": "Preview",
"description": "Preview image files",
"names": {
"bg_BG": "Преглед на изображения",
"de_DE": "Vorschau",
"fr_FR": "Visionneuse",
"it_IT": "Anteprima Immagini",
"ko_KR": "미리보기",
"nl_NL": "Foto viewer",
"no_NO": "Forhåndsviser",
"pl_PL": "Podgląd",
"ru_RU": "Просмотрщик",
"sk_SK": "Prehliadač obrázkov",
"tr_TR": "Önizle",
"vi_VN": "Trình xem ảnh"
},
"descriptions": {
"bg_BG": "Преглед на изображения",
"de_DE": "Bildervorschau",
"fr_FR": "Visionneuse de photos",
"it_IT": "Anteprima Immagini",
"ko_KR": "이미지 파일을 미리 봅니다",
"nl_NL": "Foto viewer",
"no_NO": "Forhåndsvisning av bilde-filer",
"pl_PL": "Podgląd zdjęć",
"ru_RU": "Просмотрщик изображений",
"sk_SK": "Prehliadač obrázkov",
"tr_TR": "resim dosyalarını önizle",
"vi_VN": "Trình xem ảnh"
},
"mime": [
"^image",
"^video"
],
"category": "multimedia",
"icon": "mimetypes/image.png",
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/Preview",
"build": {},
"repo": "default"
},
"default/ProcessViewer": {
"className": "ApplicationProcessViewer",
"name": "Process Viewer",
"description": "View running processes",
"names": {
"bg_BG": "Процеси",
"de_DE": "Prozess-Manager",
"fr_FR": "Gestionnaire de processus",
"it_IT": "Gestore Attività",
"ko_KR": "프로세스 관리자",
"nl_NL": "Proces manager",
"no_NO": "Prosess oversikt",
"pl_PL": "Procesy",
"ru_RU": "Менеджер процессов",
"sk_SK": "Správca procesov",
"tr_TR": "İşlemleri Görüntüle",
"vi_VN": "Xem tiến trình"
},
"descriptions": {
"bg_BG": "Преглед на процеси",
"de_DE": "Laufende Prozesse verwalten",
"fr_FR": "Visualiser les processus en cours",
"it_IT": "Mostri processi attivi",
"ko_KR": "실행 중인 프로세스를 관리합니다",
"nl_NL": "Bekijk de lopende processen",
"no_NO": "Se oversikt over kjørende prosesser",
"pl_PL": "Zobacz działające procesy",
"ru_RU": "Менеджер запущенных процессов",
"sk_SK": "Spravovanie bežiacich procesov",
"tr_TR": "çalışan işlemleri görüntüle",
"vi_VN": "Xem các tiến trình đang chạy"
},
"singular": true,
"category": "system",
"icon": "apps/gnome-monitor.png",
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/ProcessViewer",
"build": {},
"repo": "default"
},
"default/Settings": {
"className": "ApplicationSettings",
"preloadParallel": true,
"name": "Settings",
"mime": null,
"icon": "categories/applications-system.png",
"category": "system",
"singular": true,
"names": {
"bg_BG": "Настройки",
"de_DE": "Einstellungen",
"es_ES": "Settings",
"fr_FR": "Paramètres",
"it_IT": "Settaggi",
"ko_KR": "환경설정",
"nl_NL": "Instellingen",
"no_NO": "Instillinger",
"pl_PL": "Ustawienia",
"ru_RU": "Настройки",
"sk_SK": "Nastavenia",
"tr_TR": "Ayarlar",
"vi_VN": "Cài đặt"
},
"descriptions": {
"bg_BG": "Настройки",
"de_DE": "Einstellungen",
"es_ES": "Settings",
"fr_FR": "Paramètres",
"it_IT": "Settaggi",
"ko_KR": "환경설정",
"nl_NL": "Instellingen",
"no_NO": "Instillinger",
"pl_PL": "Ustawienia",
"ru_RU": "Настройки",
"sk_SK": "Nastavenia",
"tr_TR": "Program Ayarlarını düzenle",
"vi_VN": "Cài đặt"
},
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/Settings",
"build": {},
"repo": "default"
},
"default/Textpad": {
"className": "ApplicationTextpad",
"name": "Textpad",
"description": "Simple text editor",
"names": {
"bg_BG": "Текстов редактор",
"de_DE": "Texteditor",
"fr_FR": "Éditeur de texte",
"it_IT": "Editor Testi",
"ko_KR": "텍스트패드",
"nl_NL": "Notities",
"no_NO": "Tekstblokk",
"pl_PL": "Notatnik",
"ru_RU": "Редактор текста",
"sk_SK": "Poznámkový blok",
"tr_TR": "Basit Bir Metin Düzenleyicisi",
"vi_VN": "Trình sửa văn bản"
},
"descriptions": {
"bg_BG": "Стандартен текстов редактор",
"de_DE": "Einfacher Texteditor",
"fr_FR": "Éditeur de texte simple",
"it_IT": "Semplice editor di testi",
"ko_KR": "간단한 텍스트 편집기",
"nl_NL": "Eenvoudige Tekstverwerker",
"no_NO": "Simpel tekst redigering",
"pl_PL": "Prosty edytor tekstu",
"ru_RU": "Простой текстовый редактор",
"sk_SK": "Jednoduchý textový editor",
"tr_TR": "Basit Bir Metin Düzenleyicisi",
"vi_VN": "Trình sửa văn bản đơn giản"
},
"mime": [
"^text",
"inode\\/x\\-empty",
"application\\/x\\-empty",
"application\\/x\\-lua",
"application\\/x\\-python",
"application\\/javascript",
"application\\/json"
],
"category": "utilities",
"icon": "apps/accessories-text-editor.png",
"preload": [{
"type": "javascript",
"src": "combined.js"
}, {
"type": "stylesheet",
"src": "combined.css"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/Textpad",
"build": {},
"repo": "default"
},
"default/wTerm": {
"className": "ApplicationwTerm",
"name": "wTerm",
"mime": null,
"icon": "apps/terminal.png",
"category": "system",
"preload": [{
"type": "stylesheet",
"src": "combined.css"
}, {
"type": "javascript",
"src": "combined.js"
}, {
"src": "scheme.html",
"type": "scheme"
}],
"type": "application",
"path": "default/wTerm",
"build": {},
"repo": "default"
},
"default/LuaPlayground": {
"className": "ApplicationLuaPlayground",
"name": "Lua Playground",
"mime": null,
"icon": "categories/preferences-other.png",
"category": "development",
"preload": [
{
"type": "javascript",
"src": "combined.js"
},
{
"type": "stylesheet",
"src": "combined.css"
},
{
"src": "scheme.html",
"type": "scheme"
}
],
"type": "application",
"path": "default/LuaPlayground",
"build": {},
"repo": "default"
}

View File

@ -1,140 +0,0 @@
auth_or_die("User unauthorized. Please login")
local packages={}
local vfs = require("fs.vfs")
local uid = unix.uid(SESSION.iotos_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
unix.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 unix.exists(osp) == false then
packages._cache(v)
end
if unix.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(unix.exists(path) == false) then
-- create directory if not exist
unix.mkdir(path)
-- change permission
unix.chown(path, uid.id, uid.gid)
end
-- extract the zip file to it
if(unix.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 unix.exists(osf) ) then
--remove it
unix.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 (unix.exists(p) == false) then
unix.mkdir(p)
-- change permission
unix.chown(p, uid.id, uid.gid)
end
end
end
end
-- main()
local rq = (JSON.decodeString(REQUEST.query.json))
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

View File

@ -1,19 +0,0 @@
auth_or_die("User unauthorized. Please login")
local user = SESSION.iotos_user
if user then
local ospath = require('fs.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

View File

@ -1,27 +0,0 @@
local uman={}
uman.userinfo = function(user)
local info = {}
local uid = unix.uid(user)
if uid then
-- read the setting
-- use the decodeFile function of JSON instead
local file = require('fs.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

View File

@ -1,23 +0,0 @@
auth_or_die("User unauthorized. Please login")
local rq = (JSON.decodeString(REQUEST.query.json))
if rq then
if rq.command == "list" then
users = {}
local uid = unix.uid(SESSION.iotos_user)
if uid then
users[0] = {
username = SESSION.iotos_user,
id = uid.id,
name = SESSION.iotos_user,
groups = {"admin"}
}
result(users)
else
fail("Problem when retreive users")
end
else
fail("command "..rq.command.." is not supported yet")
end
else
fail("Unknow request")
end

View File

@ -1,28 +0,0 @@
<?lua
std.html()
?>
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<ul>
<?lua
local data = {k1 = "One", k2 = "two", k3 = "three"}
for k,v in pairs(data) do
?>
<li class = "<?=k..'1'?>" id = "<?=k..'2'?>" >
<?lua echo(v) ?>
</li>
<?lua
end
echo("end of \" %> lua")
?>
</ul>
</body>
</html>

View File

@ -1,62 +0,0 @@
auth_or_die("User unauthorized. Please login")
if std.ws.enable() then
-- read header
local streaming = true
while streaming do
local header = std.ws.header()
if header then
if header.mask == 0 then
print("Data is not masked")
std.ws.close(1012)
streaming = false
elseif header.opcode == std.ws.CLOSE then
print("Connection closed")
std.ws.close(1000)
streaming = false
elseif header.opcode == std.ws.BIN then
-- read the file
local data = std.ws.read(header)
local cmd = nil
if data then
local str = bytes.__tostring(data)
local b,e = str:find("^%d+")
if(b) then
local size = tonumber(str:sub(b,e))
local path = require("fs.vfs").ospath(str:sub(e+1))
local file = io.open(path, "rb")
if file then
local sum, len = 0,0
repeat
local buffer = file:read(size)
if buffer then
len = len + #buffer
cmd = bytes.new(#buffer)
for i = 1, #buffer do
cmd[i] = buffer:byte(i)
end
std.ws.write_bytes(cmd)
end
until not buffer
file:close()
print("ospath is : "..path)
print("length:",len)
else
print(path.." is not found")
std.ws.close(1011)
end
else
std.ws.close(1011)
end
else
std.ws.close(1011)
streaming = false
end
end
else
streaming = false
end
end
else
print("Web socket is not available.")
end
print("Quit streaming")

View File

@ -1,33 +0,0 @@
if std.ws.enable() then
-- read header
local streaming = true
while streaming do
local header = std.ws.header()
if header then
if header.mask == 0 then
print("Data is not masked")
std.ws.close(1012)
streaming = false
elseif header.opcode == std.ws.CLOSE then
print("Connection closed")
std.ws.close(1000)
streaming = false
elseif header.opcode == std.ws.BIN then
local data = std.ws.read(header)
if data then
local path = (__ROOT__.."/ws/img%d.jpg"):format(data[0])
print("writing : "..path)
std.ws.fwrite(path)
else
std.ws.close(1011)
streaming = false
end
end
else
streaming = false
end
end
else
print("Web socket is not available.")
end
print("Quit streaming")

View File

@ -1,17 +0,0 @@
std.html()
local pid = unix.fork()
if pid == -1 then
echo("Fail to fork")
elseif pid > 0 then
for i = 1,10 do
print("parent "..i)
end
unix.waitpid(pid)
print("Child finish")
else
for i = 1,20 do
print("child "..i)
end
end
print "reach for both"

View File

@ -1,82 +0,0 @@
OSROOT = __ROOT__.."/os"
package.path = package.path..";"..__ROOT__ .. '/os/?.lua'
unix = require("ulib")
require("sqlite")
if HEADER["User-Agent"] and HEADER["User-Agent"]:match("Mobi") then
HEADER.mobile = true
end
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
-- test only
if REQUEST.path:match("^%/*router%.lua$") or REQUEST.path:match("^%/*router$") then
die("Recursive call to index.lua is not allown")
end
-- check if the sysdb is create, otherwise create the table
function sysdb()
local meta = {}
meta.sessionid = ""
meta.username = ""
meta.stamp = 0
return require("db.model").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.iotos_user = data[1].username
return true
end
function auth_or_die(msg)
if(is_auth() == false) then
die(msg)
end
end
local m, s, p = has_module(REQUEST.path)
if m then
-- run the correct module
if s then
local r,e = loadscript(p)
if r then r() else fail(e) end
else
require(p)
end
else
local hstr = REQUEST.path:match("^%a+/")
if hstr == "os/" then
--print("require module")
require("os.router")(REQUEST.path:gsub(hstr,"",1))
elseif hstr == "blog/" then
require("blog.router")(REQUEST.path:gsub(hstr,"",1))
else
fail("Resource not found for request "..REQUEST.path)
end
end

View File

@ -1,5 +1,5 @@
SUBDIRS = core asl md SUBDIRS = core asl md
if HAS_CMAKE #if HAS_CMAKE
SUBDIRS += ann # SUBDIRS += ann
endif #endif
EXTRA_DIST = lualib.h EXTRA_DIST = lualib.h

View File

@ -1,6 +1,6 @@
all: all: clean-local
-mkdir build -mkdir build
cd build && cmake .. && make cd build && cmake .. && make
clean-local: clean-local:
-rm -rf build -rm -rf build

View File

@ -2,6 +2,10 @@ lib_LTLIBRARIES = ulib.la
ulib_la_LDFLAGS = -module -avoid-version -shared ulib_la_LDFLAGS = -module -avoid-version -shared
ulib_la_SOURCES = 3rd/zip/zip.c ulib.c ulib_la_SOURCES = 3rd/zip/zip.c ulib.c
lib_LTLIBRARIES += handle.la
handle_la_LDFLAGS = -module -avoid-version -shared
handle_la_SOURCES = handle.c
lib_LTLIBRARIES += antd.la lib_LTLIBRARIES += antd.la
antd_la_LDFLAGS = -module -avoid-version -shared antd_la_LDFLAGS = -module -avoid-version -shared
antd_la_SOURCES = antd.c antd_la_SOURCES = antd.c
@ -35,4 +39,4 @@ endif
libdir=$(prefix)/lib/lua/ libdir=$(prefix)/lib/lua/
EXTRA_DIST = 3rd/zip/miniz.c 3rd/zip/zip.h 3rd/jsmn/jsmn.h EXTRA_DIST = 3rd/zip/miniz.c 3rd/zip/zip.h 3rd/jsmn/jsmn.h

View File

@ -4,17 +4,37 @@
// add a length field, and // add a length field, and
void lua_new_byte_array(lua_State*L, int n) void lua_new_byte_array(lua_State*L, int n)
{ {
size_t nbytes = sizeof(byte_array_t) + (n-1)*sizeof(unsigned char); size_t nbytes = sizeof(byte_array_t) + n*sizeof(unsigned char);
byte_array_t *a = (byte_array_t *)lua_newuserdata(L, nbytes); byte_array_t *a = (byte_array_t *)lua_newuserdata(L, nbytes);
a->data = &((char*)a)[sizeof(byte_array_t)];
luaL_getmetatable(L, BYTEARRAY); luaL_getmetatable(L, BYTEARRAY);
lua_setmetatable(L, -2); lua_setmetatable(L, -2);
a->size = n; a->size = n;
} }
void lua_new_light_byte_array(lua_State*L, int n, char* ptr)
{
size_t nbytes = sizeof(byte_array_t);
byte_array_t *a = (byte_array_t *)lua_newuserdata(L, nbytes);
a->size = n;
a->data = ptr;
luaL_getmetatable(L, BYTEARRAY);
lua_setmetatable(L, -2);
}
static int l_new_barray (lua_State *L) { static int l_new_barray (lua_State *L) {
int n = luaL_checknumber(L, 1); int n = luaL_checknumber(L, 1);
lua_new_byte_array(L,n); lua_new_byte_array(L,n);
return 1; /* new userdatum is already on the stack */ return 1; /* new userdatum is already on the stack */
} }
static int l_new_lightbarray (lua_State *L) {
unsigned char * ptr = lua_touserdata(L,1);
int n = luaL_checknumber(L, 2);
lua_new_light_byte_array(L,n, ptr);
return 1; /* new userdatum is already on the stack */
}
byte_array_t *l_check_barray (lua_State *L,int idx) { byte_array_t *l_check_barray (lua_State *L,int idx) {
void *ud = luaL_checkudata(L, idx, BYTEARRAY); void *ud = luaL_checkudata(L, idx, BYTEARRAY);
luaL_argcheck(L, ud != NULL, idx, "`byte array' expected"); luaL_argcheck(L, ud != NULL, idx, "`byte array' expected");
@ -78,6 +98,7 @@ static int l_barray_write(lua_State* L)
} }
static const struct luaL_Reg barraylib[] = { static const struct luaL_Reg barraylib[] = {
{"unew", l_new_lightbarray},
{"new", l_new_barray}, {"new", l_new_barray},
{"set", l_set_barray}, {"set", l_set_barray},
{"get", l_get_barray}, {"get", l_get_barray},
@ -293,7 +314,7 @@ static int l_unknow (lua_State *L) {
static int l_log(lua_State *L) static int l_log(lua_State *L)
{ {
const char* s = luaL_checkstring(L,1); const char* s = luaL_checkstring(L,1);
server_log("%s",s); syslog (LOG_NOTICE, "%s", s);
return 0; return 0;
} }

115
lib/asl/handle.c Normal file
View File

@ -0,0 +1,115 @@
#include <antd/plugin.h>
#include <antd/scheduler.h>
#include <antd/dbhelper.h>
#include <sys/stat.h>
#include "../lualib.h"
/**
* convert antd dictionary to lua table
*
*/
static void push_dict_to_lua(lua_State* L, dictionary_t d)
{
lua_newtable(L);
chain_t as;
if(d)
for_each_assoc(as, d)
{
lua_pushstring(L,as->key);
//printf("KEY %s\n", as->key);
if(EQU(as->key,"COOKIE") || EQU(as->key,"REQUEST_HEADER") || EQU(as->key,"REQUEST_DATA") )
push_dict_to_lua(L, (dictionary_t)as->value);
else
{
if(strncmp(as->key,"octet-stream",12) == 0)
{
lua_pushlightuserdata(L, as->value);
}
else
{
lua_pushstring(L,as->value);
}
//printf("VALUE : %s\n",as->value );
}
lua_settable(L, -3);
}
}
void* lua_handle(void* data, void* meta)
{
antd_request_t* rq = (antd_request_t*) data;
char buf[BUFFLEN];
plugin_header_t* __plugin__ = meta;
lua_State* L = NULL;
//char * index = __s("%s/%s",__plugin__.htdocs,"router.lua");
char* cnf = __s("%s%s%s", __plugin__->pdir,DIR_SEP, __plugin__->name);
char * apis = __s("%s/%s",cnf,"api.lua");
L = luaL_newstate();
luaL_openlibs(L);
//module loader
//luaL_newlib(L, modules);
//lua_setglobal(L, "modules");
// set up global variable
// API header
lua_newtable(L);
lua_pushstring(L,"name");
lua_pushstring(L, __plugin__->name);
lua_settable(L,-3);
lua_pushstring(L,"root");
htdocs(rq, buf);
lua_pushstring(L, buf);
lua_settable(L,-3);
lua_pushstring(L,"apiroot");
lua_pushstring(L, cnf);
lua_settable(L,-3);
lua_pushstring(L,"tmpdir");
tmpdir(buf);
lua_pushstring(L, buf);
lua_settable(L,-3);
lua_pushstring(L,"dbpath");
lua_pushstring(L, __plugin__->dbpath);
lua_settable(L,-3);
lua_setglobal(L, "__api__");
// Request
lua_newtable(L);
lua_pushstring(L,"id");
lua_pushlightuserdata(L, rq->client);
//lua_pushnumber(L,client);
lua_settable(L, -3);
lua_pushstring(L,"request");
push_dict_to_lua(L,rq->request);
lua_settable(L, -3);
lua_setglobal(L, "HTTP_REQUEST");
// load major apis
if(is_file(apis))
if (luaL_loadfile(L, apis) || lua_pcall(L, 0, 0, 0))
{
ERROR( "cannot start API file: [%s] %s\n", apis, lua_tostring(L, -1));
}
/*if (luaL_loadfile(L, index) || lua_pcall(L, 0, 0, 0))
{
text(client);
__t(client, "Cannot run router: %s", lua_tostring(L, -1));
}
free(index);*/
LOG("LUA handle exit on %d", rq->client->sock);
// clear request
if(L)
lua_close(L);
if(cnf)
free(cnf);
if(apis)
free(apis);
return antd_create_task(NULL, (void*)rq, NULL,rq->client->last_io);
//lua_close(L);
}

View File

@ -231,6 +231,7 @@ static int token_to_object(lua_State *L, jsmntok_t* t, const char* s, int cid)
break; break;
default: default:
lua_pushnil(L);
return cid + t[cid].size; break; return cid + t[cid].size; break;
} }

View File

@ -3,6 +3,8 @@
#include <limits.h> #include <limits.h>
#include <pwd.h> #include <pwd.h>
#include <shadow.h> #include <shadow.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#endif #endif
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
@ -145,7 +147,7 @@ static int l_setuid(lua_State* L)
uid_t uid = (uid_t) luaL_checknumber(L,1); uid_t uid = (uid_t) luaL_checknumber(L,1);
if((int)uid != -1) if((int)uid != -1)
{ {
if(seteuid(uid) < 0) if(setuid(uid) < 0)
{ {
printf("UID set problem: %s\n", strerror(errno)); printf("UID set problem: %s\n", strerror(errno));
lua_pushboolean(L,0); lua_pushboolean(L,0);
@ -165,7 +167,7 @@ static int l_setgid(lua_State* L)
uid_t gid = (uid_t) luaL_checknumber(L,1); uid_t gid = (uid_t) luaL_checknumber(L,1);
if((int)gid != -1) if((int)gid != -1)
{ {
if(setegid(gid) < 0) if(setgid(gid) < 0)
{ {
printf("GID set problem: %s\n", strerror(errno)); printf("GID set problem: %s\n", strerror(errno));
lua_pushboolean(L,0); lua_pushboolean(L,0);
@ -180,6 +182,13 @@ static int l_setgid(lua_State* L)
lua_pushboolean(L,0); lua_pushboolean(L,0);
return 1; return 1;
} }
static int l_syslog(lua_State* L)
{
const int prio = luaL_checknumber(L,1);
const char* msg = luaL_checkstring(L,2);
syslog(prio, "%s", msg);
return 1;
}
static int l_getuid(lua_State* L) static int l_getuid(lua_State* L)
{ {
const char* name = luaL_checkstring(L,1); const char* name = luaL_checkstring(L,1);
@ -370,6 +379,51 @@ static int l_file_move(lua_State* L)
return 1; return 1;
} }
static int l_send_file(lua_State* L)
{
const char* old = luaL_checkstring(L,1);
const char* new = luaL_checkstring(L,2);
int fromfd, tofd, ret;
off_t off = 0;
if (unlink(new) < 0 && errno != ENOENT) {
lua_pushboolean(L,0);
goto end_send_file;
}
if ((fromfd = open(old, O_RDONLY)) < 0 ||
(tofd = open(new, O_WRONLY | O_CREAT, 0600)) < 0) {
lua_pushboolean(L,0);
goto end_send_file;
}
struct stat st;
if(stat(old, &st)!=0)
{
lua_pushboolean(L,0);
goto end_send_file;
}
size_t sz = st.st_size;
int read = 0;
while (read != sz && (ret = sendfile(tofd, fromfd, &off, sz - read)) == 0)
{
read += ret;
}
if(ret != sz)
{
lua_pushboolean(L,0);
goto end_send_file;
}
lua_pushboolean(L,1);
end_send_file:
if(fromfd >= 0)
{
(void) close(fromfd);
}
if(tofd >= 0)
{
(void) close(tofd);
}
return 1;
}
static int l_read_dir(lua_State* L) static int l_read_dir(lua_State* L)
{ {
const char* path = luaL_checkstring(L,1); const char* path = luaL_checkstring(L,1);
@ -622,6 +676,80 @@ static int l_zip(lua_State* L)
lua_pushboolean(L,0); lua_pushboolean(L,0);
return 1; return 1;
} }
static int l_getenv(lua_State* L)
{
const char* name = luaL_checkstring(L,1);
if(!name)
{
lua_pushnil(L);
return 1;
}
char * value = getenv(name);
lua_pushstring(L, value);
return 1;
}
static int l_setenv(lua_State* L)
{
const char* name = luaL_checkstring(L,1);
const char* value = luaL_checkstring(L,2);
const int force = luaL_checknumber(L,3);
if(!name)
{
lua_pushboolean(L, 0);
return 1;
}
if(!value)
{
lua_pushboolean(L, 0);
return 1;
}
int ret = setenv(name, value, force);
if(ret != 0)
{
lua_pushboolean(L, 0);
return 1;
}
lua_pushboolean(L,1);
return 1;
}
static int l_unsetenv(lua_State* L)
{
const char* name = luaL_checkstring(L,1);
if(!name)
{
lua_pushboolean(L, 0);
return 1;
}
int ret = unsetenv(name);
if(ret != 0)
{
lua_pushboolean(L, 0);
return 1;
}
lua_pushboolean(L,1);
return 1;
}
static int l_gethomedir(lua_State* L)
{
uid_t uid = (uid_t) luaL_checknumber(L,1);
if(uid < 0)
{
lua_pushnil(L);
return 1;
}
struct passwd *pw = getpwuid(uid);
if (pw == NULL) {
lua_pushnil(L);
return 1;
}
lua_pushstring(L, pw->pw_dir);
return 1;
}
static const struct luaL_Reg _lib [] = { static const struct luaL_Reg _lib [] = {
{"auth", l_check_login}, {"auth", l_check_login},
@ -643,6 +771,12 @@ static const struct luaL_Reg _lib [] = {
{"move",l_file_move}, {"move",l_file_move},
{"unzip",l_unzip}, {"unzip",l_unzip},
{"zip",l_zip}, {"zip",l_zip},
{"getenv",l_getenv},
{"setenv",l_setenv},
{"unsetenv",l_unsetenv},
{"home_dir",l_gethomedir},
{"send_file", l_send_file},
{"syslog", l_syslog},
{NULL,NULL} {NULL,NULL}
}; };

View File

@ -18,6 +18,7 @@
#include "../lualib.h" #include "../lualib.h"
//#include "../../lua-api.h" //#include "../../lua-api.h"
#include <antd/utils.h> #include <antd/utils.h>
#include <sys/time.h>
#define CLIENT_NAME "wurl" #define CLIENT_NAME "wurl"
#define CLIENT_HOST "192.168.9.249" #define CLIENT_HOST "192.168.9.249"
@ -34,6 +35,21 @@ typedef struct{
unsigned char* data ; unsigned char* data ;
} wurl_header_t; } wurl_header_t;
byte_array_t *l_check_barray (lua_State *L,int idx) {
void *ud = luaL_checkudata(L, idx, BYTEARRAY);
luaL_argcheck(L, ud != NULL, idx, "`byte array' expected");
return (byte_array_t *)ud;
}
void lua_new_byte_array(lua_State*L, int n)
{
size_t nbytes = sizeof(byte_array_t) + (n-1)*sizeof(unsigned char);
byte_array_t *a = (byte_array_t *)lua_newuserdata(L, nbytes);
luaL_getmetatable(L, BYTEARRAY);
lua_setmetatable(L, -2);
a->size = n;
}
/*get the ip by hostname*/ /*get the ip by hostname*/
int wurl_ip_from_hostname(const char * hostname , char* ip) int wurl_ip_from_hostname(const char * hostname , char* ip)
{ {

View File

@ -6,13 +6,14 @@
# Your platform. See PLATS for possible values. # Your platform. See PLATS for possible values.
PLAT= none PLAT= none
CC= gcc -std=gnu99 CC?= gcc -std=gnu99
CFLAGS= -O2 -g -Wall -Wextra -DLUA_COMPAT_5_2 -fPIC $(SYSCFLAGS) $(MYCFLAGS) CFLAGS= -O2 -g -Wall -Wextra -DLUA_COMPAT_5_2 -fPIC $(SYSCFLAGS) $(MYCFLAGS)
LDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS) LDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS)
LIBS= -lm $(SYSLIBS) $(MYLIBS) LIBS= -lm $(SYSLIBS) $(MYLIBS)
AR= ar rcu AR?= ar
RANLIB= ranlib LAR= $(AR) rcu
RANLIB?= ranlib
RM= rm -f RM= rm -f
SYSCFLAGS= SYSCFLAGS=
@ -56,11 +57,11 @@ o: $(ALL_O)
a: $(ALL_A) a: $(ALL_A)
$(LUA_A): $(BASE_O) $(LUA_A): $(BASE_O)
$(AR) $@ $(BASE_O) $(LAR) $@ $(BASE_O)
$(RANLIB) $@ $(RANLIB) $@
$(LUA_SO): $(BASE_O) $(LUA_SO): $(BASE_O)
gcc -shared $(BASE_O) -o $@ -ldl -lm $(CC) -shared $(BASE_O) -o $@ -ldl -lm
$(LUA_T): $(LUA_O) $(LUA_A) $(LUA_T): $(LUA_O) $(LUA_A)
$(CC) -o $@ $(LDFLAGS) $(LUA_O) $(LUA_A) $(LIBS) $(CC) -o $@ $(LDFLAGS) $(LUA_O) $(LUA_A) $(LIBS)
@ -84,7 +85,7 @@ echo:
@echo "CFLAGS= $(CFLAGS)" @echo "CFLAGS= $(CFLAGS)"
@echo "LDFLAGS= $(SYSLDFLAGS)" @echo "LDFLAGS= $(SYSLDFLAGS)"
@echo "LIBS= $(LIBS)" @echo "LIBS= $(LIBS)"
@echo "AR= $(AR)" @echo "AR= $(LAR)"
@echo "RANLIB= $(RANLIB)" @echo "RANLIB= $(RANLIB)"
@echo "RM= $(RM)" @echo "RM= $(RM)"

View File

@ -20,7 +20,7 @@
// add byte array support // add byte array support
typedef struct{ typedef struct{
int size; int size;
unsigned char data[1]; unsigned char * data;
} byte_array_t; } byte_array_t;
typedef struct{ typedef struct{

View File

@ -1,6 +0,0 @@
include ../../../../var.mk
LIB_NAME=pibot.$(LIB_EXT)
LIB_OBJ= pibot.o
include ../../lib.mk

View File

@ -1,260 +0,0 @@
#include "../lualib.h"
#include "../../lua-api.h"
#include "utils.h"
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
static const char *device = "/dev/spidev0.0";
static uint8_t mode;
static uint8_t bits = 8;
static uint32_t speed = 500000;
static uint16_t delay = 110;
static int fd_spi = -1;
int spi_open()
{
int ret;
int fd = open(device, O_RDWR);
if (fd < 0)
{
perror("can't open device \n");
return -1;
}
/*
* spi mode
*/
ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
if (ret == -1)
{
perror("can't set spi mode \n");
return -1;
}
ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
if (ret == -1)
{
perror("can't get spi mode \n");
return -1;
}
/*
* bits per word
*/
ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
if (ret == -1)
{
perror("can't set bits per word \n");
return -1;
}
ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
if (ret == -1)
{
perror("can't get bits per word");
return -1;
}
/*
* max speed hz
*/
ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
if (ret == -1)
{
perror("can't set max speed hz");
return -1;
}
ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
if (ret == -1)
{
perror("can't get max speed hz");
return -1;
}
printf("spi mode: %d\n", mode);
printf("bits per word: %d\n", bits);
printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);
return fd;
}
int spi_send_cmd(int fd, uint8_t cmd, uint8_t idx, uint8_t value)
{
int ret;
uint8_t tx[3];
uint8_t rx[3] = {0, };
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
.len = 3,
.delay_usecs = delay,
.speed_hz = speed,
.bits_per_word = bits
};
tx[0] = cmd;
tx[1] = idx;
tx[2] = value;
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1)
{
perror("can't send spi message");
return -1;
}
//if(cmd == 255)
// printf("RX %d %d %d \n", rx[0], rx[1], rx[2]);
return (int) rx[0];
}
int spi_set(int fd,uint8_t idx, uint8_t v)
{
return spi_send_cmd(fd,1, idx, v);
}
int spi_get(int fd,uint8_t idx)
{
// send command
int ret;
ret = spi_send_cmd(fd,0,idx,0);
if(ret == -1) return -1;
// read back
return spi_send_cmd(fd,255,255,255);
}
void spi_read_buff(int fd,uint8_t* buf, int size)
{
int ret;
uint8_t tx[size];
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)buf,
.len = size,
.delay_usecs = delay,
.speed_hz = speed,
.bits_per_word = bits
};
spi_send_cmd(fd,2,0,size);
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1)
{
perror("can't send spi message");
return;
}
}
void spi_write_buff(int fd, uint8_t* buf, int size)
{
int i;
for(i=0; i < size; i++)
spi_set(fd,i,buf[i]);
}
static int l_init(lua_State* L)
{
fd_spi = spi_open();
if(fd_spi == -1)
lua_pushboolean(L,0);
else
lua_pushboolean(L,1);
return 1;
}
static int l_release(lua_State* L)
{
if(fd_spi > 0)
close(fd_spi);
fd_spi = -1;
lua_pushboolean(L,1);
return 1;
}
static int l_read(lua_State* L)
{
int size = luaL_checknumber(L,1);
unsigned char data_buf[size];
if(fd_spi == -1)
{
lua_pushnil(L);
return 1;
}
// request data
spi_read_buff(fd_spi,data_buf,size);
lua_newtable(L);
int i;
for(i =0; i < size; i++)
{
lua_pushnumber(L,i);
lua_pushnumber(L,data_buf[i]);
lua_settable(L,-3);
}
return 1;
}
static int l_write(lua_State* L)
{
/* 1st argument must be a table (t) */
byte_array_t* data_buf = l_check_barray(L, 1);
if(fd_spi == -1)
{
lua_pushboolean(L,0);
return 1;
}
spi_write_buff(fd_spi,data_buf->data, data_buf->size);
lua_pushboolean(L,1);
return 1;
}
static int l_set(lua_State* L)
{
int idx = luaL_checknumber(L,1);
int val = luaL_checknumber(L,2);
if(fd_spi == -1)
{
lua_pushboolean(L,0);
return 1;
}
spi_set(fd_spi,idx,val);
lua_pushboolean(L,1);
return 1;
}
static int l_get(lua_State* L)
{
int idx = luaL_checknumber(L,1);
if(fd_spi == -1)
{
lua_pushboolean(L,0);
return 1;
}
spi_get(fd_spi,idx);
lua_pushboolean(L,1);
return 1;
}
static const struct luaL_Reg _lib [] = {
{"init", l_init},
{"release",l_release},
{"read",l_read},
{"write",l_write},
{"set",l_set},
{"get",l_get},
{NULL,NULL}
};
int luaopen_pibot(lua_State *L)
{
luaL_newlib(L, _lib);
return 1;
}

148
lua-api.c
View File

@ -6,126 +6,60 @@
#include <sys/stat.h> #include <sys/stat.h>
#include "lib/lualib.h" #include "lib/lualib.h"
static void* core_handle = NULL; #define LUA_HDL_FN "lua_handle"
static void* core = NULL;
static void* lua_handle = NULL;
static void *(*handle_fn)(void *, void*);
void init() void init()
{ {
char* error;
char* path = __s("%s/lua/core.so", __plugin__.pdir); char* path = __s("%s/lua/core.so", __plugin__.pdir);
core_handle = dlopen(path, RTLD_NOW| RTLD_GLOBAL); core = dlopen(path, RTLD_NOW| RTLD_GLOBAL);
if(!core_handle)
{
ERROR("Cannot load Lua core; %s", dlerror());
}
else
{
LOG("Lua core loaded");
}
free(path); free(path);
if(!core)
{
ERROR("Cannot load Lua core: %s", dlerror());
return;
}
LOG("Lua core loaded");
// now load the handle
path = __s("%s/lua/handle.so", __plugin__.pdir);
lua_handle = dlopen(path, RTLD_LAZY);
free(path);
if(!lua_handle)
{
ERROR("Cannot load lua_handle: %s", dlerror());
return;
}
// find the fn
handle_fn = (void *(*)(void *))dlsym(lua_handle, LUA_HDL_FN);
if ((error = dlerror()) != NULL)
{
ERROR("Problem when finding %s method from handle : %s", LUA_HDL_FN, error);
handle_fn = NULL;
return;
}
LOG("Lua module initialized");
} }
/**
* Plugin handler, reads request from the server and processes it
*
*/
static void push_dict_to_lua(lua_State* L, dictionary_t d)
{
lua_newtable(L);
chain_t as;
if(d)
for_each_assoc(as, d)
{
lua_pushstring(L,as->key);
//printf("KEY %s\n", as->key);
if(EQU(as->key,"COOKIE") || EQU(as->key,"REQUEST_HEADER") || EQU(as->key,"REQUEST_DATA") )
push_dict_to_lua(L, (dictionary_t)as->value);
else
{
lua_pushstring(L,as->value);
//printf("VALUE : %s\n",as->value );
}
lua_settable(L, -3);
}
}
void* handle(void* data) void* handle(void* data)
{ {
antd_request_t* rq = (antd_request_t*) data; plugin_header_t* meta_ptr = (void*)meta();
char buf[BUFFLEN]; antd_request_t *rq = (antd_request_t *)data;
plugin_header_t* __plugin__ = meta(); // find the handle function and execute it
lua_State* L = NULL; if(!handle_fn)
//char * index = __s("%s/%s",__plugin__.htdocs,"router.lua");
char* cnf = config_dir();
char * apis = __s("%s/%s",cnf,"api.lua");
L = luaL_newstate();
luaL_openlibs(L);
//module loader
//luaL_newlib(L, modules);
//lua_setglobal(L, "modules");
// set up global variable
// API header
lua_newtable(L);
lua_pushstring(L,"name");
lua_pushstring(L, __plugin__->name);
lua_settable(L,-3);
lua_pushstring(L,"root");
htdocs(rq, buf);
lua_pushstring(L, buf);
lua_settable(L,-3);
lua_pushstring(L,"apiroot");
lua_pushstring(L, cnf);
lua_settable(L,-3);
lua_pushstring(L,"tmpdir");
tmpdir(buf);
lua_pushstring(L, buf);
lua_settable(L,-3);
lua_pushstring(L,"dbpath");
lua_pushstring(L, __plugin__->dbpath);
lua_settable(L,-3);
lua_setglobal(L, "__api__");
// Request
lua_newtable(L);
lua_pushstring(L,"id");
lua_pushlightuserdata(L, rq->client);
//lua_pushnumber(L,client);
lua_settable(L, -3);
lua_pushstring(L,"request");
push_dict_to_lua(L,rq->request);
lua_settable(L, -3);
lua_setglobal(L, "HTTP_REQUEST");
// load major apis
if(is_file(apis))
if (luaL_loadfile(L, apis) || lua_pcall(L, 0, 0, 0))
{
ERROR( "cannot start API file: [%s] %s\n", apis, lua_tostring(L, -1));
}
/*if (luaL_loadfile(L, index) || lua_pcall(L, 0, 0, 0))
{ {
text(client); antd_error(rq->client, 503, "Requested service not found");
__t(client, "Cannot run router: %s", lua_tostring(L, -1)); return antd_create_task(NULL, (void *)rq, NULL, rq->client->last_io);
} }
free(index);*/ return handle_fn(data, meta_ptr);
// clear request
if(L)
lua_close(L);
if(cnf)
free(cnf);
if(apis)
free(apis);
return antd_create_task(NULL, (void*)rq, NULL,rq->client->last_io);
//lua_close(L);
} }
void destroy() void destroy()
{ {
if(core_handle) if(core)
dlclose(core_handle); (void)dlclose(core);
if(lua_handle)
(void)dlclose(lua_handle);
LOG("Exit LUA Handle"); LOG("Exit LUA Handle");
} }