cpp_server/static_file_handler.hpp

155 lines
3.9 KiB
C++

#pragma once
#include "http_parser.hpp"
#include "http_response.hpp"
#include "http_common.hpp"
#include <string>
#include <string_view>
#include <unordered_map>
#include <fstream>
#include <filesystem>
#include <chrono>
#include <zlib.h>
#include <cstring>
using std::string_view;
using std::string;
namespace fs = std::filesystem;
class StaticFileHandler {
private:
string root_path_;
std::unordered_map<string, std::pair<string, std::chrono::time_point<std::chrono::file_clock>>> cache_;
size_t max_cache_size_ = 50 * 1024 * 1024; // 50MB cache limit
string compress_gzip(const string& data) const {
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (deflateInit2(&zs, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
return "";
}
zs.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(data.data()));
zs.avail_in = data.size();
string compressed;
compressed.reserve(data.size() / 2);
char buffer[32768];
do {
zs.next_out = reinterpret_cast<Bytef*>(buffer);
zs.avail_out = sizeof(buffer);
int ret = deflate(&zs, Z_FINISH);
if (ret == Z_STREAM_ERROR) break;
size_t have = sizeof(buffer) - zs.avail_out;
compressed.append(buffer, have);
} while (zs.avail_out == 0);
deflateEnd(&zs);
return compressed;
}
string read_file(const string& path) const {
std::ifstream file(path, std::ios::binary);
if (!file.is_open()) return "";
file.seekg(0, std::ios::end);
size_t size = file.tellg();
file.seekg(0, std::ios::beg);
string content(size, '\0');
file.read(content.data(), size);
return content;
}
bool is_path_safe(string_view path) const {
return path.find("..") == string::npos;
}
public:
explicit StaticFileHandler(string_view root_path) : root_path_(root_path) {
if (!root_path_.empty() && root_path_.back() != '/') {
root_path_ += '/';
}
}
void handle(const HttpRequest& req, HttpResponse& res) {
if (req.method != HttpMethod::GET && req.method != HttpMethod::HEAD) {
res.status = 405;
res.set_text("Method Not Allowed");
return;
}
if (!is_path_safe(req.path)) {
res.status = 403;
res.set_text("Forbidden");
return;
}
string file_path = root_path_ + string(req.path.substr(1)); // Remove leading /
// Default to index.html for directories
if (file_path.back() == '/') {
file_path += "index.html";
}
if (!fs::exists(file_path) || !fs::is_regular_file(file_path)) {
res.status = 404;
res.set_text("Not Found");
return;
}
// Get file info
auto last_write = fs::last_write_time(file_path);
auto file_size = fs::file_size(file_path);
// Check cache
auto cache_it = cache_.find(file_path);
if (cache_it != cache_.end() && cache_it->second.second == last_write) {
res.body = cache_it->second.first;
} else {
// Read file
res.body = read_file(file_path);
if (res.body.empty()) {
res.status = 500;
res.set_text("Internal Server Error");
return;
}
// Cache if small enough
if (file_size < max_cache_size_ / 10) {
cache_[file_path] = {res.body, last_write};
}
}
// Set MIME type
string ext = fs::path(file_path).extension();
res.content_type = MimeTypes::get_mime_type(ext);
// Check if client accepts gzip
auto accept_encoding = req.headers.find("Accept-Encoding");
bool client_accepts_gzip = accept_encoding != req.headers.end() &&
accept_encoding->second.find("gzip") != string::npos;
// Compress if appropriate
if (client_accepts_gzip && MimeTypes::should_compress(res.content_type) && res.body.size() > 1024) {
string compressed = compress_gzip(res.body);
if (!compressed.empty() && compressed.size() < res.body.size()) {
res.body = std::move(compressed);
res.headers["Content-Encoding"] = "gzip";
}
}
// Add caching headers
res.headers["Cache-Control"] = "public, max-age=3600";
res.headers["ETag"] = "\"" + std::to_string(std::hash<string>{}(res.body)) + "\"";
if (req.method == HttpMethod::HEAD) {
res.body.clear();
}
}
};