1 #include "server_https.hpp"
2 #include "client_https.hpp"
4 //Added for the json-example
5 #define BOOST_SPIRIT_THREADSAFE
6 #include <boost/property_tree/ptree.hpp>
7 #include <boost/property_tree/json_parser.hpp>
9 //Added for the default_resource example
11 #include <boost/filesystem.hpp>
17 //Added for the json-example:
18 using namespace boost::property_tree;
20 typedef SimpleWeb::Server<SimpleWeb::HTTPS> HttpsServer;
21 typedef SimpleWeb::Client<SimpleWeb::HTTPS> HttpsClient;
23 //Added for the default_resource example
24 void default_resource_send(const HttpsServer &server, const shared_ptr<HttpsServer::Response> &response,
25 const shared_ptr<ifstream> &ifs);
28 //HTTPS-server at port 8080 using 1 thread
29 //Unless you do more heavy non-threaded processing in the resources,
30 //1 thread is usually faster than several threads
31 HttpsServer server("server.crt", "server.key");
32 server.config.port=8080;
34 //Add resources using path-regex and method-string, and an anonymous function
35 //POST-example for the path /string, responds the posted string
36 server.resource["^/string$"]["POST"]=[](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
38 auto content=request->content.string();
39 //request->content.string() is a convenience function for:
41 //ss << request->content.rdbuf();
42 //string content=ss.str();
44 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
47 //POST-example for the path /json, responds firstName+" "+lastName from the posted json
48 //Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing
49 //Example posted json:
51 // "firstName": "John",
52 // "lastName": "Smith",
55 server.resource["^/json$"]["POST"]=[](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
58 read_json(request->content, pt);
60 string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
62 *response << "HTTP/1.1 200 OK\r\n"
63 << "Content-Type: application/json\r\n"
64 << "Content-Length: " << name.length() << "\r\n\r\n"
68 *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
72 //GET-example for the path /info
73 //Responds with request-information
74 server.resource["^/info$"]["GET"]=[](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
75 stringstream content_stream;
76 content_stream << "<h1>Request from " << request->remote_endpoint_address << " (" << request->remote_endpoint_port << ")</h1>";
77 content_stream << request->method << " " << request->path << " HTTP/" << request->http_version << "<br>";
78 for(auto& header: request->header) {
79 content_stream << header.first << ": " << header.second << "<br>";
82 //find length of content_stream (length received using content_stream.tellp())
83 content_stream.seekp(0, ios::end);
85 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n" << content_stream.rdbuf();
88 //GET-example for the path /match/[number], responds with the matched string in path (number)
89 //For instance a request GET /match/123 will receive: 123
90 server.resource["^/match/([0-9]+)$"]["GET"]=[&server](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
91 string number=request->path_match[1];
92 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" << number;
95 //Get example simulating heavy work in a separate thread
96 server.resource["^/work$"]["GET"]=[&server](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> /*request*/) {
97 thread work_thread([response] {
98 this_thread::sleep_for(chrono::seconds(5));
99 string message="Work done";
100 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << message.length() << "\r\n\r\n" << message;
102 work_thread.detach();
105 //Default GET-example. If no other matches, this anonymous function will be called.
106 //Will respond with content in the web/-directory, and its subdirectories.
107 //Default file: index.html
108 //Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
109 server.default_resource["GET"]=[&server](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
111 auto web_root_path=boost::filesystem::canonical("web");
112 auto path=boost::filesystem::canonical(web_root_path/request->path);
113 //Check if path is within web_root_path
114 if(distance(web_root_path.begin(), web_root_path.end())>distance(path.begin(), path.end()) ||
115 !equal(web_root_path.begin(), web_root_path.end(), path.begin()))
116 throw invalid_argument("path must be within root path");
117 if(boost::filesystem::is_directory(path))
119 if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)))
120 throw invalid_argument("file does not exist");
122 std::string cache_control, etag;
124 // Uncomment the following line to enable Cache-Control
125 // cache_control="Cache-Control: max-age=86400\r\n";
127 // Uncomment the following lines to enable ETag
129 // ifstream ifs(path.string(), ifstream::in | ios::binary);
131 // auto hash=SimpleWeb::Crypto::to_hex_string(SimpleWeb::Crypto::md5(ifs));
132 // etag = "ETag: \""+hash+"\"\r\n";
133 // auto it=request->header.find("If-None-Match");
134 // if(it!=request->header.end()) {
135 // if(!it->second.empty() && it->second.compare(1, hash.size(), hash)==0) {
136 // *response << "HTTP/1.1 304 Not Modified\r\n" << cache_control << etag << "\r\n\r\n";
142 // throw invalid_argument("could not read file");
145 auto ifs=make_shared<ifstream>();
146 ifs->open(path.string(), ifstream::in | ios::binary | ios::ate);
149 auto length=ifs->tellg();
150 ifs->seekg(0, ios::beg);
152 *response << "HTTP/1.1 200 OK\r\n" << cache_control << etag << "Content-Length: " << length << "\r\n\r\n";
153 default_resource_send(server, response, ifs);
156 throw invalid_argument("could not read file");
158 catch(const exception &e) {
159 string content="Could not open path "+request->path+": "+e.what();
160 *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
164 thread server_thread([&server](){
169 //Wait for server to start so that the client can connect
170 this_thread::sleep_for(chrono::seconds(1));
173 //Second Client() parameter set to false: no certificate verification
174 HttpsClient client("localhost:8080", false);
175 auto r1=client.request("GET", "/match/123");
176 cout << r1->content.rdbuf() << endl;
178 string json_string="{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}";
179 auto r2=client.request("POST", "/string", json_string);
180 cout << r2->content.rdbuf() << endl;
182 auto r3=client.request("POST", "/json", json_string);
183 cout << r3->content.rdbuf() << endl;
185 server_thread.join();
190 void default_resource_send(const HttpsServer &server, const shared_ptr<HttpsServer::Response> &response,
191 const shared_ptr<ifstream> &ifs) {
192 //read and send 128 KB at a time
193 static vector<char> buffer(131072); // Safe when server is running on one thread
194 streamsize read_length;
195 if((read_length=ifs->read(&buffer[0], buffer.size()).gcount())>0) {
196 response->write(&buffer[0], read_length);
197 if(read_length==static_cast<streamsize>(buffer.size())) {
198 server.send(response, [&server, response, ifs](const boost::system::error_code &ec) {
200 default_resource_send(server, response, ifs);
202 cerr << "Connection interrupted" << endl;