diff --git a/src/middleware/staticcontent.cpp b/src/middleware/staticcontent.cpp index 97b4888..bdd4224 100644 --- a/src/middleware/staticcontent.cpp +++ b/src/middleware/staticcontent.cpp @@ -1,6 +1,5 @@ #include "../http/mime.hpp" #include "../logger.hpp" -#include #include #include #include "staticcontent.hpp" @@ -8,9 +7,14 @@ namespace Middleware { - void ReadAllBytes(std::filesystem::path const & path, std::vector & buffer) + bool TryReadAllBytes(std::string const & filePath, std::vector & buffer) { - std::ifstream ifs(path, std::ios_base::binary | std::ios_base::ate); + std::ifstream ifs(filePath, std::ios_base::binary | std::ios_base::ate); + if (!ifs.is_open()) + { + return false; + } + std::ifstream::pos_type length = ifs.tellg(); auto const oldBufferSize = buffer.size(); @@ -18,6 +22,30 @@ namespace Middleware ifs.seekg(0, std::ios_base::beg); ifs.read(&buffer[oldBufferSize], length); + + return true; + } + + bool ContainsDoubleDots(std::string const & s) + { + bool previousWasDot = false; + for(unsigned i = 0; i < s.size(); ++i) + { + if (s[i] == '.') + { + if(previousWasDot) + { + return true; + } + previousWasDot = true; + } + else + { + previousWasDot = false; + } + } + + return false; } void StaticContent::HandleRequest(Http::Request const & request, Http::Response & response) @@ -33,7 +61,14 @@ namespace Middleware } } - std::filesystem::path path; + if (ContainsDoubleDots(request.url.GetPath())) + { + // We cannot deal with this, we are not going to bother checking if + // this double dot escapes our root directory + return; + } + + std::string path; if (request.url.HasPath()) { path = root + request.url.GetPath(); @@ -44,13 +79,12 @@ namespace Middleware path = root + "/index.html"; } - if (!std::filesystem::exists(path)) + if (!TryReadAllBytes(path, response.content)) { return; } response.code = HttpResponse::Code::OK; - ReadAllBytes(path, response.content); response.contentType = Http::GetMimeType(path); return;