package com.jessieamorris.httpserver.handlers;

import com.jessieamorris.httpserver.common.Header;
import com.jessieamorris.httpserver.exceptions.NotFoundException;
import com.jessieamorris.httpserver.logging.Logger;
import com.jessieamorris.httpserver.server.HttpRequest;
import com.jessieamorris.httpserver.server.HttpResponse;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by jessie.
 */
public class BasicFileHttpHandler extends SimpleHttpHandler {
	@Override
	public void onGet(HttpRequest request, HttpResponse response) throws Exception {
		try {
			URI requestUri = request.getURI();

			// TODO: Security issues, could escalate by using "../" in paths
			Path path = Paths.get("./", requestUri.getPath());

			Logger.println("Trying to get a file at: " + path);

			Charset charset = Charset.forName("US-ASCII");
			response.setBodyReader(Files.newBufferedReader(path, charset));

			String mimeType = Files.probeContentType(path);
			if (mimeType == null) {
				mimeType = "text/plain";
			}

			response.setHeader(new Header("Content-Type", mimeType));

			response.handleRequest(request);
		} catch (NoSuchFileException e) {
			response.handleException(new NotFoundException());
		} catch (IOException e) {
			response.handleException(new NotFoundException());
		}
	}
}

@@ -324,16 +324,37 @@
 ponse;%0A%0A
+import java.io.File;%0A
 import j
@@ -645,16 +645,94 @@
 ndler %7B%0A
+%09File currentDirectory = new File(Paths.get(%22./%22).toAbsolutePath().toUri());%0A%0A
 %09@Overri
@@ -867,76 +867,8 @@
 );%0A%0A
-%09%09%09// TODO: Security issues, could escalate by using %22../%22 in paths%0A
 %09%09%09P
@@ -915,16 +915,33 @@
 tPath())
+.toAbsolutePath()
 ;%0A%0A%09%09%09Lo
@@ -991,16 +991,57 @@
 path);%0A%0A
+%09%09%09checkForPathTransversalIssues(path);%0A%0A
 %09%09%09Chars
@@ -1404,33 +1404,76 @@
 %0A%09%09%09
-response.handleException(
+throw new NotFoundException();%0A%09%09%7D catch (IOException e) %7B%0A%09%09%09throw 
 new 
@@ -1495,67 +1495,369 @@
 on()
-)
 ;%0A%09%09%7D
- catch (IOException e) %7B%0A%09%09%09response.handleException(
+%0A%09%7D%0A%0A%0A%09private void checkForPathTransversalIssues(Path path) throws NotFoundException, IOException %7B%0A%09%09File file = new File(path.toUri());%0A%09%09final String canonicalDirPath = currentDirectory.getCanonicalPath() + File.separator;%0A%09%09final String canonicalEntryPath = file.getCanonicalPath();%0A%0A%09%09if (!canonicalEntryPath.startsWith(canonicalDirPath)) %7B%0A%09%09%09throw 
 new 
@@ -1875,17 +1875,16 @@
 eption()
-)
 ;%0A%09%09%7D%0A%09%7D
@@ -1884,10 +1884,11 @@
 %0A%09%09%7D%0A%09%7D%0A
+%0A
 %7D%0A

Add security checks to prevent path transversing issues.