xref: /aosp_15_r20/external/ot-br-posix/third_party/Simple-web-server/repo/https_examples.cpp (revision 4a64e381480ef79f0532b2421e44e6ee336b8e0d)
1 #include "client_https.hpp"
2 #include "server_https.hpp"
3 #include <future>
4 
5 // Added for the json-example
6 #define BOOST_SPIRIT_THREADSAFE
7 #include <boost/property_tree/json_parser.hpp>
8 #include <boost/property_tree/ptree.hpp>
9 
10 // Added for the default_resource example
11 #include "crypto.hpp"
12 #include <algorithm>
13 #include <boost/filesystem.hpp>
14 #include <fstream>
15 #include <vector>
16 
17 using namespace std;
18 // Added for the json-example:
19 using namespace boost::property_tree;
20 
21 using HttpsServer = SimpleWeb::Server<SimpleWeb::HTTPS>;
22 using HttpsClient = SimpleWeb::Client<SimpleWeb::HTTPS>;
23 
main()24 int main() {
25   // HTTPS-server at port 8080 using 1 thread
26   // Unless you do more heavy non-threaded processing in the resources,
27   // 1 thread is usually faster than several threads
28   HttpsServer server("server.crt", "server.key");
29   server.config.port = 8080;
30 
31   // Add resources using path-regex and method-string, and an anonymous function
32   // POST-example for the path /string, responds the posted string
33   server.resource["^/string$"]["POST"] = [](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
34     // Retrieve string:
35     auto content = request->content.string();
36     // request->content.string() is a convenience function for:
37     // stringstream ss;
38     // ss << request->content.rdbuf();
39     // auto content=ss.str();
40 
41     *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n"
42               << content;
43 
44 
45     // Alternatively, use one of the convenience functions, for instance:
46     // response->write(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<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
58     try {
59       ptree pt;
60       read_json(request->content, pt);
61 
62       auto name = pt.get<string>("firstName") + " " + pt.get<string>("lastName");
63 
64       *response << "HTTP/1.1 200 OK\r\n"
65                 << "Content-Length: " << name.length() << "\r\n\r\n"
66                 << name;
67     }
68     catch(const exception &e) {
69       *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << strlen(e.what()) << "\r\n\r\n"
70                 << e.what();
71     }
72 
73 
74     // Alternatively, using a convenience function:
75     // try {
76     //     ptree pt;
77     //     read_json(request->content, pt);
78 
79     //     auto name=pt.get<string>("firstName")+" "+pt.get<string>("lastName");
80     //     response->write(name);
81     // }
82     // catch(const exception &e) {
83     //     response->write(SimpleWeb::StatusCode::client_error_bad_request, e.what());
84     // }
85   };
86 
87   // GET-example for the path /info
88   // Responds with request-information
89   server.resource["^/info$"]["GET"] = [](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
90     stringstream stream;
91     stream << "<h1>Request from " << request->remote_endpoint().address().to_string() << ":" << request->remote_endpoint().port() << "</h1>";
92 
93     stream << request->method << " " << request->path << " HTTP/" << request->http_version;
94 
95     stream << "<h2>Query Fields</h2>";
96     auto query_fields = request->parse_query_string();
97     for(auto &field : query_fields)
98       stream << field.first << ": " << field.second << "<br>";
99 
100     stream << "<h2>Header Fields</h2>";
101     for(auto &field : request->header)
102       stream << field.first << ": " << field.second << "<br>";
103 
104     response->write(stream);
105   };
106 
107   // GET-example for the path /match/[number], responds with the matched string in path (number)
108   // For instance a request GET /match/123 will receive: 123
109   server.resource["^/match/([0-9]+)$"]["GET"] = [](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
110     response->write(request->path_match[1].str());
111   };
112 
113   // GET-example simulating heavy work in a separate thread
114   server.resource["^/work$"]["GET"] = [](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> /*request*/) {
115     thread work_thread([response] {
116       this_thread::sleep_for(chrono::seconds(5));
117       response->write("Work done");
118     });
119     work_thread.detach();
120   };
121 
122   // Default GET-example. If no other matches, this anonymous function will be called.
123   // Will respond with content in the web/-directory, and its subdirectories.
124   // Default file: index.html
125   // Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
126   server.default_resource["GET"] = [](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) {
127     try {
128       auto web_root_path = boost::filesystem::canonical("web");
129       auto path = boost::filesystem::canonical(web_root_path / request->path);
130       // Check if path is within web_root_path
131       if(distance(web_root_path.begin(), web_root_path.end()) > distance(path.begin(), path.end()) ||
132          !equal(web_root_path.begin(), web_root_path.end(), path.begin()))
133         throw invalid_argument("path must be within root path");
134       if(boost::filesystem::is_directory(path))
135         path /= "index.html";
136 
137       SimpleWeb::CaseInsensitiveMultimap header;
138 
139       // Uncomment the following line to enable Cache-Control
140       // header.emplace("Cache-Control", "max-age=86400");
141 
142 #ifdef HAVE_OPENSSL
143 //    Uncomment the following lines to enable ETag
144 //    {
145 //      ifstream ifs(path.string(), ifstream::in | ios::binary);
146 //      if(ifs) {
147 //        auto hash = SimpleWeb::Crypto::to_hex_string(SimpleWeb::Crypto::md5(ifs));
148 //        header.emplace("ETag", "\"" + hash + "\"");
149 //        auto it = request->header.find("If-None-Match");
150 //        if(it != request->header.end()) {
151 //          if(!it->second.empty() && it->second.compare(1, hash.size(), hash) == 0) {
152 //            response->write(SimpleWeb::StatusCode::redirection_not_modified, header);
153 //            return;
154 //          }
155 //        }
156 //      }
157 //      else
158 //        throw invalid_argument("could not read file");
159 //    }
160 #endif
161 
162       auto ifs = make_shared<ifstream>();
163       ifs->open(path.string(), ifstream::in | ios::binary | ios::ate);
164 
165       if(*ifs) {
166         auto length = ifs->tellg();
167         ifs->seekg(0, ios::beg);
168 
169         header.emplace("Content-Length", to_string(length));
170         response->write(header);
171 
172         // Trick to define a recursive function within this scope (for example purposes)
173         class FileServer {
174         public:
175           static void read_and_send(const shared_ptr<HttpsServer::Response> &response, const shared_ptr<ifstream> &ifs) {
176             // Read and send 128 KB at a time
177             static vector<char> buffer(131072); // Safe when server is running on one thread
178             streamsize read_length;
179             if((read_length = ifs->read(&buffer[0], static_cast<streamsize>(buffer.size())).gcount()) > 0) {
180               response->write(&buffer[0], read_length);
181               if(read_length == static_cast<streamsize>(buffer.size())) {
182                 response->send([response, ifs](const SimpleWeb::error_code &ec) {
183                   if(!ec)
184                     read_and_send(response, ifs);
185                   else
186                     cerr << "Connection interrupted" << endl;
187                 });
188               }
189             }
190           }
191         };
192         FileServer::read_and_send(response, ifs);
193       }
194       else
195         throw invalid_argument("could not read file");
196     }
197     catch(const exception &e) {
198       response->write(SimpleWeb::StatusCode::client_error_bad_request, "Could not open path " + request->path + ": " + e.what());
199     }
200   };
201 
202   server.on_error = [](shared_ptr<HttpsServer::Request> /*request*/, const SimpleWeb::error_code & /*ec*/) {
203     // Handle errors here
204     // Note that connection timeouts will also call this handle with ec set to SimpleWeb::errc::operation_canceled
205   };
206 
207   // Start server and receive assigned port when server is listening for requests
208   promise<unsigned short> server_port;
209   thread server_thread([&server, &server_port]() {
210     // Start server
211     server.start([&server_port](unsigned short port) {
212       server_port.set_value(port);
213     });
214   });
215   cout << "Server listening on port " << server_port.get_future().get() << endl
216        << endl;
217 
218   // Client examples
219   string json_string = "{\"firstName\": \"John\",\"lastName\": \"Smith\",\"age\": 25}";
220 
221   // Synchronous request examples
222   {
223     HttpsClient client("localhost:8080", false);
224     try {
225       cout << "Example GET request to https://localhost:8080/match/123" << endl;
226       auto r1 = client.request("GET", "/match/123");
227       cout << "Response content: " << r1->content.rdbuf() << endl // Alternatively, use the convenience function r1->content.string()
228            << endl;
229 
230       cout << "Example POST request to https://localhost:8080/string" << endl;
231       auto r2 = client.request("POST", "/string", json_string);
232       cout << "Response content: " << r2->content.rdbuf() << endl
233            << endl;
234     }
235     catch(const SimpleWeb::system_error &e) {
236       cerr << "Client request error: " << e.what() << endl;
237     }
238   }
239 
240   // Asynchronous request example
241   {
242     HttpsClient client("localhost:8080", false);
243     cout << "Example POST request to https://localhost:8080/json" << endl;
244     client.request("POST", "/json", json_string, [](shared_ptr<HttpsClient::Response> response, const SimpleWeb::error_code &ec) {
245       if(!ec)
246         cout << "Response content: " << response->content.rdbuf() << endl;
247     });
248     client.io_service->run();
249   }
250 
251   server_thread.join();
252 }
253