Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / ot-br-posix / repo / third_party / Simple-web-server / repo / https_examples.cpp
1 #include "server_https.hpp"
2 #include "client_https.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 #include "crypto.hpp"
15
16 using namespace std;
17 //Added for the json-example:
18 using namespace boost::property_tree;
19
20 typedef SimpleWeb::Server<SimpleWeb::HTTPS> HttpsServer;
21 typedef SimpleWeb::Client<SimpleWeb::HTTPS> HttpsClient;
22
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);
26
27 int main() {
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;
33     
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) {
37         //Retrieve string:
38         auto content=request->content.string();
39         //request->content.string() is a convenience function for:
40         //stringstream ss;
41         //ss << request->content.rdbuf();
42         //string content=ss.str();
43         
44         *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
45     };
46     
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:
50     //{
51     //  "firstName": "John",
52     //  "lastName": "Smith",
53     //  "age": 25
54     //}
55     server.resource["^/json$"]["POST"]=[](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
56         try {
57             ptree pt;
58             read_json(request->content, pt);
59
60             string name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
61
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"
65                       << name;
66         }
67         catch(exception& e) {
68             *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n" << e.what();
69         }
70     };
71     
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>";
80         }
81         
82         //find length of content_stream (length received using content_stream.tellp())
83         content_stream.seekp(0, ios::end);
84         
85         *response <<  "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n" << content_stream.rdbuf();
86     };
87     
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;
93     };
94     
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;
101         });
102         work_thread.detach();
103     };
104     
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) {
110         try {
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))
118                 path/="index.html";
119             if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)))
120                 throw invalid_argument("file does not exist");
121
122             std::string cache_control, etag;
123
124             // Uncomment the following line to enable Cache-Control
125             // cache_control="Cache-Control: max-age=86400\r\n";
126
127             // Uncomment the following lines to enable ETag
128             // {
129             //     ifstream ifs(path.string(), ifstream::in | ios::binary);
130             //     if(ifs) {
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";
137             //                 return;
138             //             }
139             //         }
140             //     }
141             //     else
142             //         throw invalid_argument("could not read file");
143             // }
144
145             auto ifs=make_shared<ifstream>();
146             ifs->open(path.string(), ifstream::in | ios::binary | ios::ate);
147             
148             if(*ifs) {
149                 auto length=ifs->tellg();
150                 ifs->seekg(0, ios::beg);
151                 
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);
154             }
155             else
156                 throw invalid_argument("could not read file");
157         }
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;
161         }
162     };
163     
164     thread server_thread([&server](){
165         //Start server
166         server.start();
167     });
168     
169     //Wait for server to start so that the client can connect
170     this_thread::sleep_for(chrono::seconds(1));
171     
172     //Client examples
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;
177
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;
181     
182     auto r3=client.request("POST", "/json", json_string);
183     cout << r3->content.rdbuf() << endl;
184     
185     server_thread.join();
186     
187     return 0;
188 }
189
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) {
199                 if(!ec)
200                     default_resource_send(server, response, ifs);
201                 else
202                     cerr << "Connection interrupted" << endl;
203             });
204         }
205     }
206 }