1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
|
-- Copyright (C) 2007-2016 by Ubaldo Porcheddu <ubaldo@eja.it>
eja.lib.web='ejaWeb'
eja.lib.webStart='ejaWebStart'
eja.lib.webStop='ejaWebStop'
eja.help.webStart='web server start'
eja.help.webStop='web server stopt'
eja.help.webPort='web server port {35248}'
eja.help.webHost='web server ip {0.0.0.0}'
eja.help.webPath='web server path {'..eja.pathVar..'/web/}'
eja.help.webSize='web buffer size {8192}'
function ejaWeb()
eja.web={}
eja.web.count=0
eja.web.timeout=100
eja.web.host=eja.opt.webHost or '0.0.0.0'
eja.web.port=eja.opt.webPort or 35248
eja.web.path=eja.opt.webPath or eja.pathVar..'/web/'
ejaInfo("[web] daemon on port %d and path %s",eja.web.port, eja.web.path)
local client=nil
local s=ejaSocketOpen(AF_INET,SOCK_STREAM,0)
ejaSocketOptionSet(s,SOL_SOCKET,SO_REUSEADDR,1)
ejaSocketBind(s,{ family=AF_INET, addr=eja.web.host, port=eja.web.port },0)
ejaSocketListen(s,5)
while s do
client,t=ejaSocketAccept(s)
if client then
eja.web.count=eja.web.count+1
local forkPid=ejaFork()
if forkPid and forkPid == 0 then
ejaSocketClose(s)
while client do
ejaSocketOptionSet(client,SOL_SOCKET,SO_RCVTIMEO,eja.web.timeout,0)
if ejaWebThread(client,t.addr,t.port) < 1 then
break
end
end
ejaSocketClose(client)
break
else
ejaSocketClose(client)
ejaForkClean()
end
end
end
end
function ejaWebStart(...)
ejaWebStop()
eja.pid.web=ejaFork()
if eja.pid.web and eja.pid.web == 0 then
ejaWeb(...)
else
ejaPidWrite(ejaSprintf('web_%d',eja.opt.webPort or 35248),eja.pid.web)
end
end
function ejaWebStop()
ejaPidKill(ejaSprintf('web_%d',tonumber(eja.opt.webStop) or eja.opt.webPort or 35248))
end
function ejaWebThread(client,ip,port)
local web={}
web.bufferSize=8192
web.timeStart=os.time()
web.socket=client
web.remoteIp=ip or 'null'
web.remotePort=tonumber(port) or 0
web.method=''
web.request=''
web.postFile=''
web.response=''
web.auth=0
web.data=''
web.file=''
web.query=''
web.opt={}
web.status='200 OK'
web.range=-1
web.protocolOut='HTTP/1.1'
web.headerIn={}
web.headerOut={}
web.headerOut['Content-Type']='text/html'
web.headerOut['Connection']='Close'
if ejaNumber(eja.opt.webSize) > 0 then web.bufferSize=ejaNumber(eja.opt.webSize) end
local body=''
local data=ejaSocketRead(client,web.bufferSize)
if data then
body=data:match('\r\n\r\n(.+)') or data:match('\n\n(.+)') or ''
web.request=data:match('(.-)\r\n\r\n') or data:match('(.-)\n\n') or data
end
if web.request and web.request ~= '' then
web.request=web.request:gsub('\r','')
web.method,web.uri,web.protocolIn=web.request:match('(%w+) (.-) (.+)[\n]?')
if web.uri then web.uri=web.uri:gsub('/+','/') end
if web.method then
web.method=web.method:lower()
if web.request:match('\n.+') then
for k,v in web.request:match('\n(.+)'):gmatch('(.-)%: ([^\n]+)') do
local key=k:lower():gsub('\n','')
local value=v:gsub('\n','')
web.headerIn[key]=value
end
end
end
end
if web.headerIn['connection'] and web.headerIn['connection']:lower() == 'keep-alive' then
if web.headerIn['user-agent'] and not web.headerIn['user-agent']:find('%(iP') then --avoid iOS Keep-Alive bug
web.headerOut['Connection']='Keep-Alive'
end
end
if web.headerIn['range'] then
web.range=tonumber( web.headerIn['range']:match("=([0-9]+)") )
end
if web.uri then
web.path=web.uri:gsub("\\.\\.",""):match('([^?|#]+)')
web.query=web.uri:match('%?([^#]+)')
end
if web.method == 'post' and ejaNumber(web.headerIn['content-length']) > 0 then
if web.headerIn['content-type']:match('application/x%-www%-form%-urlencoded') then
if ejaNumber(web.headerIn['content-length']) < web.bufferSize then
while ejaNumber(web.headerIn['content-length']) > #body do
local data=ejaSocketRead(client,web.bufferSize)
if data then
body=body..data
else
break
end
end
web.query=body
else
web.status='413 Request Entity Too Large'
end
end
if web.headerIn['content-type'] and web.headerIn['content-type']:match('multipart%/form%-data') then
web.postFile=eja.pathTmp..'eja.postFile-'..web.remoteIp:gsub('.','')..web.remotePort
local fileLength=tonumber(web.headerIn['content-length'])
local fd=io.open(web.postFile,'w')
if body ~= '' then
fd:write(body)
fileLength=fileLength-#body
end
while fileLength > 0 do
local data=ejaSocketRead(client,web.bufferSize)
if data then
fd:write(data)
fileLength=fileLength-#data
else
break
end
end
fd:close()
end
end
--web query options
if web.query and web.query ~= '' then
web.query=web.query:gsub("&", "&")
web.query=web.query:gsub("<", "<")
web.query=web.query:gsub(">", ">")
web.query=web.query:gsub("+", " ")
for k,v in web.query:gmatch('([^&=]+)=([^&=]*)&?') do
web.opt[k]=ejaUrlDecode(v)
end
end
--web path
if web.path and web.path ~= '' then
web=ejaWebAuth(web)
if web.auth < 0 then
web.status='401 Unauthorized'
else
if web.path:sub(-1) == "/" then
if ejaFileCheck(eja.web.path..web.path..'index.eja') then
web.path = web.path.."index.eja"
else
web.path = web.path.."index.html"
end
end
local ext=web.path:match("([^.]+)$")
web.headerOut['Content-Type']=eja.mime[ext]
if ext == "eja" then web.headerOut['Content-Type']="application/eja" end
if not web.headerOut['Content-Type'] then web.headerOut['Content-Type']="application/octet-stream" end
if web.headerOut['Content-Type']=="application/eja" then
local run=nil
local file=ejaSprintf("%s%s",eja.web.path,web.path:sub(2))
if ejaFileCheck(file) then
web.headerOut['Content-Type']="text/html"
local data=ejaFileRead(file)
if data then
loadstring(ejaVmImport(data) or data)(web)
end
else
web.status='500 Internal Server Error'
end
elseif eja.mimeApp[web.headerOut['Content-Type']] then
web=_G[eja.mimeApp[web.headerOut['Content-Type']]](web)
else
if eja.opt.webCns then web=ejaWebCns(web) end
if not web.cns then
web.file=ejaSprintf('%s/%s',eja.web.path,web.path)
local stat=ejaFileStat(web.file)
if stat then
if ejaSprintf('%o',stat.mode):sub(-5,1)=='4' then
web.file=ejaSprintf('%s/%s/index.html',eja.web.path,web.path)
if not ejaFileStat(web.file) then
web.file=nil
else
web.headerOut['Content-Type']="text/html"
end
end
end
if not stat or not web.file then
web.file=''
web.status='404 Not Found'
else
web.headerOut['Cache-Control']='max-age=3600'
end
end
end
end
else
web.status='501 Not Implemented'
if os.time()-web.timeStart >= eja.web.timeout then
web.status='408 Request Timeout'
end
end
--4XX
if web.status:sub(1,1) == '4' then
local status=web.status:sub(1,3)
local data=ejaFileRead(ejaSprintf('%s/%s.eja',eja.web.path,status))
if data then
loadstring(ejaVmImport(data) or data)(web)
elseif ejaFileCheck(ejaSprintf('%s/%s.html',eja.web.path,status)) then
web.status='301 Moved Permanently'
web.headerOut['Location']=ejaSprintf('/%s.html',status)
end
end
if web.file ~= '' then
web.headerOut['Content-Length'] = ejaFileSize(web.file)
if web.headerOut['Content-Length'] < 1 then web.file='' end
end
if web.file == '' and web.data and #web.data then
web.headerOut['Content-Length'] = #web.data
end
if web.range > 0 then
web.headerOut['Content-Range']=ejaSprintf("bytes %d-%d/%d",web.range,web.headerOut['Content-Length']-1,web.headerOut['Content-Length'])
web.headerOut['Content-Length']=web.headerOut['Content-Length']-web.range
web.status='206 Partial Content'
end
if not web.headerOut['Content-Length'] or web.headerOut['Content-Length'] < 1 then
web.headerOut['Content-Length']=nil
web.headerOut['Content-Type']=nil
end
if web.status:sub(1,1) ~= '2' then web.headerOut['Connection']='Close' end
web.response=web.protocolOut..' '..web.status..'\r\nDate: '..os.date()..'\r\nServer: eja '..eja.version..'\r\n'
for k,v in next,web.headerOut do
web.response=web.response..k..': '..v..'\r\n'
end
ejaSocketWrite(client,web.response..'\r\n')
if web.file ~= '' then
local fd=io.open(web.file,'r')
if fd then
if web.range > 0 then
fd:seek('set',web.range)
end
local data=''
while data do
data=fd:read(web.bufferSize)
if data then
ejaSocketWrite(client,data)
else
break
end
end
fd:close()
end
else
ejaSocketWrite(client,web.data)
end
ejaDebug('[web] %s\t%s\t%s\t%s\t%s\t%s',web.remoteIp,web.status:match("[^ ]+"),os.time()-web.timeStart,web.headerOut['Content-Length'],web.auth,web.uri)
ejaTrace('\n<--\n%s\n-->\n%s\n',web.request,web.response)
if web.headerOut['Connection']=='Keep-Alive' then
return 1
else
return 0
end
end
function ejaWebOpen(host,port)
if ejaNumber(port) < 1 then port=80 end
local res,err=ejaSocketGetAddrInfo(host, port, {family=AF_INET, socktype=SOCK_STREAM})
if res then
local fd=ejaSocketOpen(AF_INET,SOCK_STREAM,0)
if fd and ejaSocketConnect(fd,res[1]) then
ejaSocketOptionSet(fd,SOL_SOCKET,SO_RCVTIMEO,5,0)
ejaSocketOptionSet(fd,SOL_SOCKET,SO_SNDTIMEO,5,0)
return fd
end
end
return nil;
end
function ejaWebWrite(fd,value)
return ejaSocketWrite(fd,value)
end
function ejaWebRead(fd,size)
return ejaSocketRead(fd,size)
end
function ejaWebClose(fd)
return ejaSocketClose(fd)
end
function ejaWebGetOpen(value,...)
url=string.format(value,...)
local protocol,host,port,path=url:match('(.-)://([^/:]+):?([^/]*)/?(.*)')
if ejaNumber(port) < 1 then port=80 end
local fd=ejaWebOpen(host,port)
if fd then
ejaWebWrite(fd,ejaSprintf('GET /%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: eja %s\r\nAccept: */*\r\nConnection: Close\r\n\r\n',path,host,eja.version))
return fd
else
return nil
end
end
function ejaWebGet(value,...)
local url=string.format(value,...)
local t={}
local fd=ejaWebGetOpen(url)
if fd then
while true do
local buf=ejaWebRead(fd,1024)
if not buf or #buf == 0 then break end
t[#t+1]=buf
end
ejaWebClose(fd)
local header,data=table.concat(t):match('(.-)\r?\n\r?\n(.*)')
return data,header
else
return nil
end
end
|