Created
May 18, 2019 09:29
-
-
Save cx0der/7ad1de3305d13161b224bf966eda114a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void run() { | |
OutputStream dataOut = null; | |
try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); | |
PrintWriter out = new PrintWriter(client.getOutputStream())) { | |
Map<String, String> requestHeaders = parseRequestHeaders(in); | |
String method = requestHeaders.get(METHOD); | |
String resource = requestHeaders.get(RESOURCE); | |
String protocol = requestHeaders.get(PROTOCOL); | |
String status; | |
String resolvedResourcePath; | |
File outputFile; | |
if (resource.contains("./") || resource.contains("../")) { | |
status = Http.Status.BAD_REQUEST; | |
outputFile = new File(this.serverRoot, BAD_REQUEST); | |
} else if (Http.Method.GET.equals(method)) { | |
resolvedResourcePath = resolveResource(resource); | |
outputFile = new File(this.webRoot, resolvedResourcePath); | |
if (!outputFile.exists()) { | |
status = Http.Status.NOT_FOUND; | |
outputFile = new File(this.serverRoot, NOT_FOUND); | |
} else { | |
if (outputFile.isDirectory()) { | |
outputFile = new File(outputFile, INDEX_HTML); | |
} | |
if (outputFile.exists()) { | |
status = Http.Status.OK; | |
} else { | |
status = Http.Status.NOT_FOUND; | |
outputFile = new File(this.serverRoot, NOT_FOUND); | |
} | |
} | |
} else { | |
outputFile = new File(this.serverRoot, NOT_IMPLEMENTED); | |
status = Http.Status.NOT_IMPLEMENTED; | |
} | |
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("GMT")); | |
String date = now.format(HTTP_FORMATTER); | |
String mimeType = Files.probeContentType(outputFile.toPath()); | |
byte[] data = readFile(outputFile); | |
// write the headers | |
writeResponseHeaders(out, protocol, status, mimeType, date, data.length, getContentEncoding(requestHeaders)); | |
// write the outputFile contents | |
dataOut = getDataOutputStream(requestHeaders, client.getOutputStream()); | |
dataOut.write(data, 0, data.length); | |
if (dataOut instanceof GZIPOutputStream) { | |
((GZIPOutputStream) dataOut).finish(); | |
} else { | |
dataOut.flush(); | |
} | |
// log the request | |
log(client.getInetAddress(), date, method, status, requestHeaders.getOrDefault(UA, ""), resource); | |
} catch (IOException e) { | |
System.out.println(e.getMessage()); | |
} finally { | |
if (dataOut != null) { | |
try { | |
dataOut.close(); | |
} catch (IOException ex) { | |
System.out.println(ex.getMessage()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment