@Override
protected HttpResponse handleRequest(HttpRequest request)
{
BasicHttpResponse response = new BasicHttpResponse();
response.setHeaders(new HashMap<String, String>());
response.getHeaders().put(Http.SERVER, server.getServerSignature());
response.setVersion(request.getHttpVersion());
String requestUri = request.getRequestUri();
if (requestUri.equals("/"))
{
requestUri = "/index.html";
}
File f = new File("webroot/" + requestUri);
File rootDir = new File("webroot/");
try
{
if (!f.getCanonicalPath().startsWith(rootDir.getCanonicalPath()))
{
response.setStatusCode(HttpStatusCode.FORBIDDEN);
return response;
}
}
catch (IOException e1)
{
response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR);
return response;
}
if (f.exists())
{
response.setStatusCode(HttpStatusCode.OK);
InputStream inputStream;
try
{
inputStream = new FileInputStream(f);
byte fileContent[] = new byte[(int) f.length()];
inputStream.read(fileContent);
inputStream.close();
response.setEntity(fileContent);
// guess and set the content type
response.getHeaders().put(Http.CONTENT_TYPE, URLConnection.guessContentTypeFromName(f.getAbsolutePath()));
}
catch (FileNotFoundException e)
{
response.setStatusCode(HttpStatusCode.NOT_FOUND);
}
catch (IOException e)
{
response.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR);
}
}
else
{
response.setStatusCode(HttpStatusCode.NOT_FOUND);
}
return response;
}