Skip to content

Commit

Permalink
add session
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed Jan 15, 2010
1 parent 771d542 commit a3e8811
Show file tree
Hide file tree
Showing 5 changed files with 249 additions and 13 deletions.
67 changes: 60 additions & 7 deletions luasrv.c
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
//Global Setting
lua_State *L; /* lua state handle */
char *luasrv_settings_rootpath = NULL;
struct evhttp *httpd;
struct evbuffer *buf;
struct evkeyvalq *input_headers;
struct evkeyvalq *output_headers;
Expand All @@ -76,6 +77,61 @@ static void show_help(void)
fprintf(stderr, b, strlen(b));
}

/* 创建多层目录的函数 */
void create_multilayer_dir( char *muldir ) {
int i,len;
char str[512];

strncpy( str, muldir, 512 );
len=strlen(str);
for( i=0; i<len; i++ ) {
if( str[i]=='/' ) {
str[i] = '\0';
//判断此目录是否存在,不存在则创建
if( access(str, F_OK)!=0 ) {
mkdir( str, 0777 );
}
str[i]='/';
}
}
if( len>0 && access(str, F_OK)!=0 ) {
mkdir( str, 0777 );
}

return;
}

static int luaM_mkdir (lua_State *L) {
const char *muldir = luaL_optstring(L, 1, NULL);
create_multilayer_dir((char *)muldir);
if (access(muldir, W_OK) == 0) {
lua_pushboolean(L, 1);
} else {
lua_pushboolean(L, 0);
}
return 1;
}

#define NUL '\0'
#define MICRO_IN_SEC 1000000.00
#define SEC_IN_MIN 60
static int luaM_microtime (lua_State *L) {
struct timeval tp = {0};
int get_as_float = luaL_optnumber(L, 1, 0);

if (gettimeofday(&tp, NULL)) {
lua_pushboolean(L, 0);
}

if (get_as_float) {
lua_pushnumber(L, (double)(tp.tv_sec + tp.tv_usec / MICRO_IN_SEC));
} else {
lua_pushfstring(L, "%f %d", tp.tv_usec / MICRO_IN_SEC, tp.tv_sec);
}

return 1;
}

static int luaM_print (lua_State *L) {
const char *str = luaL_optstring(L, 1, NULL);
evbuffer_add_printf(buf, "%s", str);
Expand All @@ -96,7 +152,6 @@ static int luaM_set_header (lua_State *L) {
return 0;
}


/* 处理模块 */
void luasrv_handler(struct evhttp_request *req, void *arg)
{
Expand All @@ -113,13 +168,10 @@ void luasrv_handler(struct evhttp_request *req, void *arg)
int post_data_len;
post_data_len = EVBUFFER_LENGTH(req->input_buffer);

fprintf(stderr, "\n - %d - \n", post_data_len);
if (post_data_len > 0) {
char *post_data = (char *)malloc(post_data_len + 1);
memset(post_data, '\0', post_data_len + 1);
memcpy (post_data, EVBUFFER_DATA(req->input_buffer), post_data_len);
lua_pushstring(L, post_data);
lua_pushstring(L, (char *)EVBUFFER_DATA(req->input_buffer));
lua_setglobal(L, "POST_DATA");
free(post_data);
}

evhttp_add_header(req->output_headers, "Server", "luasrv" VERSION);
Expand Down Expand Up @@ -227,6 +279,8 @@ int main(int argc, char **argv) {

struct luaL_reg driver[] = {
{ "print", luaM_print },
{ "mkdir", luaM_mkdir },
{ "microtime", luaM_microtime },
{ "get_header", luaM_get_header },
{ "set_header", luaM_set_header },
{ NULL, NULL },
Expand Down Expand Up @@ -306,7 +360,6 @@ int main(int argc, char **argv) {
signal (SIGHUP, kill_signal);

/* 请求处理部分 */
struct evhttp *httpd;


event_init();
Expand Down
4 changes: 4 additions & 0 deletions make.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
make
killall -9 luasrv
killall -9 luasrv
./luasrv -d -x /root/lua-srv/demo
82 changes: 76 additions & 6 deletions script/loader.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package.path = './script/?.lua;./?.lua;';
require "print_r"
require "urlcode"
require "split"
require "serialize"

GET, POST, FILES, COOKIE, REQUEST = {}, {}, {}, {}, {}

Expand Down Expand Up @@ -77,13 +78,19 @@ end
-- name,type,size,tmp_name,error
function parse_post_file(data)
local val = string.match(data, ".+\r\n(.+)")
local ppf = {}
local f = io.tmpfile(); f:write(val);-- f:close()
ppf["tmp_name"] = f
ppf["size"] = string.len(val)
ppf["error"] = 0
return ppf
end

function split_boundary()
--printl(POST_DATA)
local POST_TEMP = split(POST_DATA, boundary)
for i,p in ipairs(POST_TEMP) do
local h = breakheaders(p)
print_r(h)
local t = {}
local hcd = h["content-disposition"]
if hcd then
Expand Down Expand Up @@ -138,15 +145,78 @@ for k,v in pairs(COOKIE) do
REQUEST[k] = v
end

print("<hr>");
-- UPLOAD FUNCTION --
function move_uploaded_file(f, dest)
local d, err = io.open(dest, "w+");
if d == nil then
error("Cannot create upload file.\n"..err)
end
d:write(f:read("*a")); d:close()
f:close()
end


--"\r\n\t <>'\"\\"
-- SESSION FUNCTION --
local session_timeout = 10 * 60 -- 10 minutes

cgi.mkdir(tmp_path .. '/sess') -- save session files

local function session_filename (token)
return string.format ("%s/sess_%s.lua", tmp_path, token)
end

local function session_exists (token)
local fh = io.open(session_filename(token))
if fh then
fh:close ()
return true
else
return false
end
end

function session_new ()
local ver = 0;
local token = cgi.microtime(1)
if session_exists (token) then
repeat
token = token .. '.' .. ver
ver = ver + 1
until not session_exists (token)
end
return token
end

function session_save (token, data)
local fh = assert (io.open(session_filename(token), "w+"))
fh:write "return "
serialize (data, function (s) fh:write(s) end)
fh:close()
end

function session_delete (token)
os.remove (session_filename(token))
end

function session_load (token)
local f, err = loadfile (session_filename(token))
if not f then
return nil, err
else
return f()
end
end

print("<hr>GET<br/>");
print_r(GET)
print("<hr>");
print("<hr>POST<br/>");
print_r(POST)
print("<hr>");
print("<hr>COOKIE<br/>");
print_r(COOKIE)
print("<hr>");
print("<hr>REQUEST<br/>");
print_r(REQUEST)
print("<hr>");
print("<hr>FILES<br/>");
print_r(FILES)
print("<hr>");
--setcookie('wgj', 'yes')
Expand Down
1 change: 1 addition & 0 deletions script/print_r.lua
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
printl = print
print = cgi.print
echo = cgi.print
--local print = echo.print
Expand Down
108 changes: 108 additions & 0 deletions script/serialize.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
----------------------------------------------------------------------------
-- Serialize tables.
-- It works only for tables without cycles and without functions or
-- userdata inside it.
-- @release $Id: serialize.lua,v 1.7 2007/04/16 14:01:32 tomas Exp $
----------------------------------------------------------------------------

local ipairs, pairs, type = ipairs, pairs, type
--
local value = nil

----------------------------------------------------------------------------
-- Serializes a table.
-- @param tab Table representing the session.
-- @param outf Function used to generate the output.
-- @param ind String with indentation pattern (default = "").
-- @param pre String with indentation prefix (default = "").
----------------------------------------------------------------------------
local function tabledump (tab, outf, ind, pre)
local sep_n, sep, _n = ",\n", ", ", "\n"
if (not ind) or (ind == "") then ind = ""; sep_n = ", "; _n = "" end
if not pre then pre = "" end
outf ("{")
local p = pre..ind
-- prepare list of keys
local keys = { boolean = {}, number = {}, string = {} }
local total = 0
for key in pairs (tab) do
total = total + 1
local t = type(key)
if t == "string" then
table.insert (keys.string, key)
else
keys[t][key] = true
end
end
local many = total > 5
if not many then sep_n = sep; _n = " " end
outf (_n)
-- serialize entries with numeric keys
if many then
local _f,_s,_v = ipairs(tab)
if _f(_s,_v) then outf (p) end
end
local num = keys.number
local ok = false
-- entries with automatic index
for key, val in ipairs (tab) do
value (val, outf, ind, p)
outf (sep)
num[key] = nil
ok = true
end
if ok and many then outf (_n) end
-- entries with explicit index
for key in pairs (num) do
if many then outf (p) end
outf ("[")
outf (key)
outf ("] = ")
value (tab[key], outf, ind, p)
outf (sep_n)
end
-- serialize entries with boolean keys
local tr = keys.boolean[true]
if tr then
outf (string.format ("%s[true] = ", many and p or ''))
value (tab[true], outf, ind, p)
outf (sep_n)
end
local fa = keys.boolean[false]
if fa then
outf (string.format ("%s[false] = ", many and p or ''))
value (tab[false], outf, ind, p)
outf (sep_n)
end
-- serialize entries with string keys
table.sort (keys.string)
for _, key in ipairs (keys.string) do
outf (string.format ("%s[%q] = ", many and p or '', key))
value (tab[key], outf, ind, p)
outf (sep_n)
end
if many then outf (pre) end
outf ("}")
end


--
-- Serializes a value.
--
value = function (v, outf, ind, pre)
local t = type (v)
if t == "string" then
outf (string.format ("%q", v))
elseif t == "number" then
outf (tostring(v))
elseif t == "boolean" then
outf (tostring(v))
elseif t == "table" then
tabledump (v, outf, ind, pre)
else
outf (string.format ("%q", tostring(v)))
end
end

----------------------------------------------------------------------------
serialize = tabledump

0 comments on commit a3e8811

Please sign in to comment.