Made the cache feature secured in #ifdef block and added it to the http

example too
This commit is contained in:
Sébastien Huss 2016-12-20 22:15:58 +01:00
commit d4f5fddba3
3 changed files with 47 additions and 1 deletions

View file

@ -1,6 +1,8 @@
#include "server_https.hpp"
#include "client_https.hpp"
#ifdef HAVE_OPENSSL
#include "crypto.hpp"
#endif
//Added for the json-example
#define BOOST_SPIRIT_THREADSAFE
@ -23,7 +25,9 @@ typedef SimpleWeb::Client<SimpleWeb::HTTPS> HttpsClient;
//Added for the default_resource example
void default_resource_send(const HttpsServer &server, const shared_ptr<HttpsServer::Response> &response,
const shared_ptr<ifstream> &ifs);
#ifdef HAVE_OPENSSL
std::string build_hash(const std::string full_file_name);
#endif
int main() {
//HTTPS-server at port 8080 using 1 thread
//Unless you do more heavy non-threaded processing in the resources,
@ -109,6 +113,7 @@ int main() {
try {
auto web_root_path=boost::filesystem::canonical("web");
auto path=boost::filesystem::canonical(web_root_path/request->path);
std::string cache_ctrl = "";
//Check if path is within web_root_path
if(distance(web_root_path.begin(), web_root_path.end())>distance(path.begin(), path.end()) ||
!equal(web_root_path.begin(), web_root_path.end(), path.begin()))
@ -118,6 +123,7 @@ int main() {
if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)))
throw invalid_argument("file does not exist");
#ifdef HAVE_OPENSSL
//Support for HTTP Cache
std::string hash = build_hash(path.string());
auto it=request->header.find("If-None-Match");
@ -127,6 +133,8 @@ int main() {
return;
}
}
cache_ctrl = "Cache-Control: max-age=86400\r\nETag: \""+hash+"\"\r\n";
#endif
auto ifs=make_shared<ifstream>();
ifs->open(path.string(), ifstream::in | ios::binary);
@ -137,7 +145,7 @@ int main() {
ifs->seekg(0, ios::beg);
*response << "HTTP/1.1 200 OK\r\nCache-Control: max-age=86400\r\nETag: \""+hash+"\"\r\nContent-Length: " << length << "\r\n\r\n";
*response << "HTTP/1.1 200 OK\r\n" << cache_ctrl << "Content-Length: " << length << "\r\n\r\n";
default_resource_send(server, response, ifs);
}
else
@ -193,6 +201,7 @@ void default_resource_send(const HttpsServer &server, const shared_ptr<HttpsServ
}
}
#ifdef HAVE_OPENSSL
std::string build_hash(const std::string full_file_name) {
std::string ret = "";
std::ifstream file(full_file_name, std::ios::binary | std::ios::ate);
@ -204,3 +213,4 @@ std::string build_hash(const std::string full_file_name) {
ret = reinterpret_cast<char*> (&buffer[0]);
return SimpleWeb::Crypto::md5(ret,1);
}
#endif