1 #include "server_http.hpp"
2 #include "client_http.hpp"
3
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>
8
9 //Added for the default_resource example
10 #include <fstream>
11 #include <boost/filesystem.hpp>
12 #include <vector>
13 #include <algorithm>
14 #ifdef HAVE_OPENSSL
15 #include "crypto.hpp"
16 #endif
17
18 using namespace std;
19 //Added for the json-example:
20 using namespace boost::property_tree;
21
22 typedef SimpleWeb::Server<SimpleWeb::HTTP> HttpServer;
23 typedef SimpleWeb::Client<SimpleWeb::HTTP> HttpClient;
24
25 //Added for the default_resource example
26 void default_resource_send(const HttpServer &server, const shared_ptr<HttpServer::Response> &response,
27 const shared_ptr<ifstream> &ifs);
28
main()29 int main() {
30 //HTTP-server at port 8080 using 1 thread
31 //Unless you do more heavy non-threaded processing in the resources,
32 //1 thread is usually faster than several threads
33 HttpServer server;
34 server.config.port=80;
35
36 //Add resources using path-regex and method-string, and an anonymous function
37 //POST-example for the path /string, responds the posted string
38 server.resource["^/string$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
39 //Retrieve string:
40 auto content=request->content.string();
41 //request->content.string() is a convenience function for:
42 //stringstream ss;
43 //ss << request->content.rdbuf();
44 //string content=ss.str();
45
46 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
47 };
48
49 //POST-example for the path /json, responds firstName+" "+lastName from the posted json
50 //Responds with an appropriate error message if the posted json is not valid, or if firstName or lastName is missing
51 //Example posted json:
52 //{
53 // "firstName": "John",
54 // "lastName": "Smith",
55 // "age": 25
56 //}
57 server.resource["^/json$"]["POST"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
58 try {
59 ptree pt;
60 read_json(request->content, pt);
61
62 string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
63
64 *response << "HTTP/1.1 200 OK\r\n"
65 << "Content-Type: application/json\r\n"
66 << "Content-Length: " << name.length() << "\r\n\r\n"
67 << name;
68 }
69 catch(exception& e) {
70 *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
71 }
72 };
73
74 //GET-example for the path /info
75 //Responds with request-information
76 server.resource["^/info$"]["GET"]=[](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
77 stringstream content_stream;
78 content_stream << "<h1>Request from " << request->remote_endpoint_address << " (" << request->remote_endpoint_port << ")</h1>";
79 content_stream << request->method << " " << request->path << " HTTP/" << request->http_version << "<br>";
80 for(auto& header: request->header) {
81 content_stream << header.first << ": " << header.second << "<br>";
82 }
83
84 //find length of content_stream (length received using content_stream.tellp())
85 content_stream.seekp(0, ios::end);
86
87 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n" << content_stream.rdbuf();
88 };
89
90 //GET-example for the path /match/[number], responds with the matched string in path (number)
91 //For instance a request GET /match/123 will receive: 123
92 server.resource["^/match/([0-9]+)$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
93 string number=request->path_match[1];
94 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n" << number;
95 };
96
97 //Get example simulating heavy work in a separate thread
98 server.resource["^/work$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
99 thread work_thread([response] {
100 this_thread::sleep_for(chrono::seconds(5));
101 string message="Work done";
102 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << message.length() << "\r\n\r\n" << message;
103 });
104 work_thread.detach();
105 };
106
107 server.resource["^/getAvailableNetwork$"]["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
108 thread work_thread([response] {
109 this_thread::sleep_for(chrono::seconds(5));
110 // string message="Work done";
111 string json_string="{\"result\":[{\"ch\":13,\"ha\":\"18B43000003D2785\",\"nn\":\"NEST-PAN-C1E7\",\"pi\":\"0xC19B\",\"xp\":\"EEA74CE1EDFA2E8A\"}]}";
112 // string json_string="{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}";
113 *response << "HTTP/1.1 200 OK\r\nContent-Length: " << json_string.length() << "\r\nContent-Type:application/json; charset=utf-8" << "\r\n\r\n" << json_string;
114 });
115 work_thread.detach();
116 };
117
118 //Default GET-example. If no other matches, this anonymous function will be called.
119 //Will respond with content in the web/-directory, and its subdirectories.
120 //Default file: index.html
121 //Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
122 server.default_resource["GET"]=[&server](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
123 try {
124 auto web_root_path=boost::filesystem::canonical("web");
125 auto path=boost::filesystem::canonical(web_root_path/request->path);
126 //Check if path is within web_root_path
127 if(distance(web_root_path.begin(), web_root_path.end())>distance(path.begin(), path.end()) ||
128 !equal(web_root_path.begin(), web_root_path.end(), path.begin()))
129 throw invalid_argument("path must be within root path");
130 if(boost::filesystem::is_directory(path))
131 path/="index.html";
132 if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)))
133 throw invalid_argument("file does not exist");
134
135 std::string cache_control, etag;
136
137 // Uncomment the following line to enable Cache-Control
138 // cache_control="Cache-Control: max-age=86400\r\n";
139
140 #ifdef HAVE_OPENSSL
141 // Uncomment the following lines to enable ETag
142 // {
143 // ifstream ifs(path.string(), ifstream::in | ios::binary);
144 // if(ifs) {
145 // auto hash=SimpleWeb::Crypto::to_hex_string(SimpleWeb::Crypto::md5(ifs));
146 // etag = "ETag: \""+hash+"\"\r\n";
147 // auto it=request->header.find("If-None-Match");
148 // if(it!=request->header.end()) {
149 // if(!it->second.empty() && it->second.compare(1, hash.size(), hash)==0) {
150 // *response << "HTTP/1.1 304 Not Modified\r\n" << cache_control << etag << "\r\n\r\n";
151 // return;
152 // }
153 // }
154 // }
155 // else
156 // throw invalid_argument("could not read file");
157 // }
158 #endif
159
160 auto ifs=make_shared<ifstream>();
161 ifs->open(path.string(), ifstream::in | ios::binary | ios::ate);
162
163 if(*ifs) {
164 auto length=ifs->tellg();
165 ifs->seekg(0, ios::beg);
166
167 *response << "HTTP/1.1 200 OK\r\n" << cache_control << etag << "Content-Length: " << length << "\r\n\r\n";
168 default_resource_send(server, response, ifs);
169 }
170 else
171 throw invalid_argument("could not read file");
172 }
173 catch(const exception &e) {
174 string content="Could not open path "+request->path+": "+e.what();
175 *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
176 }
177 };
178
179 thread server_thread([&server](){
180 //Start server
181 server.start();
182 });
183
184 //Wait for server to start so that the client can connect
185 this_thread::sleep_for(chrono::seconds(1));
186
187 // //Client examples
188 // HttpClient client("localhost:8080");
189 // auto r1=client.request("GET", "/match/123");
190 // cout << r1->content.rdbuf() << endl;
191
192 // string json_string="{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}";
193 // auto r2=client.request("POST", "/string", json_string);
194 // cout << r2->content.rdbuf() << endl;
195
196 // auto r3=client.request("POST", "/json", json_string);
197 // cout << r3->content.rdbuf() << endl;
198
199 server_thread.join();
200
201 return 0;
202 }
203
default_resource_send(const HttpServer & server,const shared_ptr<HttpServer::Response> & response,const shared_ptr<ifstream> & ifs)204 void default_resource_send(const HttpServer &server, const shared_ptr<HttpServer::Response> &response,
205 const shared_ptr<ifstream> &ifs) {
206 //read and send 128 KB at a time
207 static vector<char> buffer(131072); // Safe when server is running on one thread
208 streamsize read_length;
209 if((read_length=ifs->read(&buffer[0], buffer.size()).gcount())>0) {
210 response->write(&buffer[0], read_length);
211 if(read_length==static_cast<streamsize>(buffer.size())) {
212 server.send(response, [&server, response, ifs](const boost::system::error_code &ec) {
213 if(!ec)
214 default_resource_send(server, response, ifs);
215 else
216 cerr << "Connection interrupted" << endl;
217 });
218 }
219 }
220 }
221