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
| function handleRequest( root, host, path, client )
--
-- Local file
--
file = path;
--
-- File must be beneath the vhost root.
--
file = root .. host .. "/htdocs" .. file ;
--
-- Attempt to sanitize the input Virtual Host + requested path.
--
file = string.strip( file );
--
-- Add a trailing "index.html" to paths ending in / if such
-- a file exists.
--
-- Otherwise if it is a directory then serve it.
--
if ( string.endsWith( file, "/" ) ) then
tmp = file .. "index.html";
if ( fileExists( tmp ) ) then
file = tmp;
else
if ( socket.is_dir( file ) ) then
size = handleDirectory( client, file, path ) ;
socket.close( client );
return size, "200";
end
end
end
--
-- Open the file and return an error if it fails.
--
if ( fileExists( file ) == false ) then
size = sendError( client, 404,"File not found " .. urlEncode( path ) );
socket.close( client );
return size, "404";
end;
--
-- Find the suffix to get the mime.type.
--
_, _, ext = string.find( file, "\.([^\.]+)$" );
if ( ext == nil ) then
ext = "html"; -- HACK
end
type = mime[ext];
if ( type == nil ) then type = 'text/plain' ; end;
--
-- Send out the header.
--
socket.write( client, "HTTP/1.0 200 OK\r\n" );
socket.write( client, "Server: lua-httpd " .. socket.version .. "\r\n" );
socket.write( client, "Content-type: " .. type .. "\r\n" );
socket.write( client, "Connection: close\r\n\r\n" );
--
-- Read the file, and then serve it.
--
f = io.open( file, "rb" );
size = fileSize( f );
local t = f:read("*all")
socket.write( client, t );
f:close();
return size, "200" ;
end |
Partager