Refactor staticcontent class file validation
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
#include "../http/mime.hpp"
|
||||
#include "../logger.hpp"
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <ios>
|
||||
#include "staticcontent.hpp"
|
||||
@@ -8,9 +7,14 @@
|
||||
|
||||
namespace Middleware
|
||||
{
|
||||
void ReadAllBytes(std::filesystem::path const & path, std::vector<char> & buffer)
|
||||
bool TryReadAllBytes(std::string const & filePath, std::vector<char> & 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;
|
||||
|
||||
Reference in New Issue
Block a user