1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Ole Christian Eidheim
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "http-server/http_server.h"
#include "http_client_tcp.h"
#include "http_client_icn.h"
typedef icn_httpserver::HttpServer HttpServer;
typedef icn_httpserver::Response Response;
typedef icn_httpserver::Request Request;
namespace std {
void default_resource_send(const HttpServer &server,
shared_ptr<Response> response,
shared_ptr<ifstream> ifs,
shared_ptr<vector<char>> buffer,
std::size_t bytes_to_read) {
streamsize read_length;
if ((read_length = ifs->read(&(*buffer)[0], buffer->size()).gcount()) > 0) {
response->write(&(*buffer)[0], read_length);
if (bytes_to_read <= static_cast<streamsize>(buffer->size())) {
// If this is the last part of the response, send it at the pointer deletion!
return;
}
std::size_t to_read = bytes_to_read - read_length;
server.send(response, [&server, response, ifs, buffer, to_read](const boost::system::error_code &ec) {
if (!ec) {
default_resource_send(server, response, ifs, buffer, to_read);
} else {
cerr << "Connection interrupted" << endl;
}
});
}
}
void afterSignal(HttpServer *webServer, const boost::system::error_code &errorCode) {
cout << "\nGracefully terminating http-server... wait." << endl;
webServer->stop();
}
void usage(const char *programName) {
cerr << programName << " [-p PATH_TO_ROOT_FOOT_FOLDER] [-o TCP_LISTEN_PORT] [-l WEBSERVER_PREFIX] [-x TCP_PROXY_ADDRESS] [-z ICN_PROXY_PREFIX]\n"
<< "Web server able to publish content and generate http responses over TCP/ICN\n" << endl;
exit(1);
}
int main(int argc, char **argv) {
// Parse command line arguments
string root_folder = "/var/www/html";
string webserver_prefix = "http://webserver";
string tcp_proxy_address;
string icn_proxy_prefix;
int port = 8080;
int opt = 0;
while ((opt = getopt(argc, argv, "p:l:o:hx:z:")) != -1) {
switch (opt) {
case 'p':
root_folder = optarg;
break;
case 'l':
webserver_prefix = optarg;
break;
case 'x':
tcp_proxy_address = optarg;
break;
case 'o':
port = atoi(optarg);
break;
case 'z':
icn_proxy_prefix = optarg;
break;
case 'h':
default:
usage(argv[0]);
break;
}
}
if (!boost::filesystem::exists(boost::filesystem::path(root_folder))) {
// Try to create it
try {
if (!boost::filesystem::create_directories(boost::filesystem::path(root_folder))) {
throw boost::filesystem::filesystem_error("", boost::system::error_code());
}
} catch (boost::filesystem::filesystem_error) {
std::cerr << "The web root folder " << root_folder << " does not exist and its creation failed. Exiting.."
<< std::endl;
return (EXIT_FAILURE);
}
}
std::cout << "Using web root folder: [" << root_folder << "]" << std::endl;
std::cout << "Using locator: [" << webserver_prefix << "]" << std::endl;
if (!tcp_proxy_address.empty()) {
std::cout << "Using TCP proxy: [" << tcp_proxy_address << "]" << std::endl;
}
if (!icn_proxy_prefix.empty()) {
std::cout << "Using ICN proxy: [" << icn_proxy_prefix << "]" << std::endl;
}
boost::asio::io_service io_service;
HttpServer server(port, webserver_prefix, 50, 5, 300, io_service);
// GET for the path /info
// Responds with some server info
server.resource["^/info$"]["GET"] = [](shared_ptr<Response> response, shared_ptr<Request> request) {
stringstream content_stream;
content_stream << "<h1>This webserver is able to reply to HTTP over TCP/ICN</h1>";
content_stream << request->getMethod() << " " << request->getPath() << " HTTP/" << request->getHttp_version()
<< "<br>";
for (auto &header: request->getHeader()) {
content_stream << header.first << ": " << header.second << "<br>";
}
//find length of content_stream (length received using content_stream.tellp())
content_stream.seekp(0, ios::end);
*response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n"
<< content_stream.rdbuf();
};
// Default GET-example. If no other matches, this anonymous function will be called.
// Will respond with content in the web/-directory, and its subdirectories.
// Default file: index.html
// Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
server.default_resource["GET"] = [&server, &root_folder, &tcp_proxy_address, &icn_proxy_prefix]
(shared_ptr<Response> response, shared_ptr<Request> request) {
const auto web_root_path = boost::filesystem::canonical(root_folder);
boost::filesystem::path path = web_root_path;
path /= request->getPath();
auto socket_request = dynamic_cast<icn_httpserver::SocketRequest *>(request.get());
std::chrono::milliseconds response_lifetime;
if (path.extension().string() == ".mpd" || path.stem() == "latest") {
std::cout << "Setting lifetime to 1 second" << std::endl;
response_lifetime = std::chrono::milliseconds(1000);
} else {
std::cout << "Setting lifetime to 5 second" << std::endl;
response_lifetime = std::chrono::milliseconds(5000);
}
response->setResponseLifetime(response_lifetime);
if (boost::filesystem::exists(path)) {
path = boost::filesystem::canonical(path);
//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())) {
if (boost::filesystem::is_directory(path)) {
path /= "index.html";
} // default path
if (boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path)) {
auto ifs = make_shared<ifstream>();
ifs->open(path.string(), ifstream::in | ios::binary);
if (*ifs) {
//read and send 15 MB at a time
streamsize buffer_size = 15 * 1024 * 1024;
auto buffer = make_shared<vector<char> >(buffer_size);
ifs->seekg(0, ios::end);
auto length = ifs->tellg();
ifs->seekg(0, ios::beg);
response->setResponseLength(length);
*response << "HTTP/1.0 200 OK\r\nContent-Length: " << length << "\r\n\r\n";
default_resource_send(server, response, ifs, buffer, length);
return;
}
}
}
}
string proxy;
HTTPClient* client = nullptr;
if (tcp_proxy_address.empty() && !icn_proxy_prefix.empty()) {
proxy = icn_proxy_prefix;
client = new HTTPClientIcn(20);
} else if (!tcp_proxy_address.empty() && icn_proxy_prefix.empty()) {
proxy = tcp_proxy_address;
client = new HTTPClientTcp;
} else if (!tcp_proxy_address.empty() && !icn_proxy_prefix.empty()) {
if (socket_request) {
proxy = icn_proxy_prefix;
client = new HTTPClientIcn(20);
} else {
proxy = tcp_proxy_address;
client = new HTTPClientTcp;
}
}
if (!proxy.empty()) {
// Fetch content from remote origin
std::stringstream ss;
if (strncmp("http://", proxy.c_str(), 7) != 0) {
if (strncmp("https://", proxy.c_str(), 8) != 0) {
ss << "https://";
} else {
ss << "http://";
}
}
ss << proxy;
ss << request->getPath();
std::cout << "Forwarding request to " << ss.str() << std::endl;
client->download(ss.str(), *response);
delete client;
if (response->size() == 0) {
*response << "HTTP/1.1 504 Gateway Timeout\r\n\r\n";
}
return;
}
string content = "Could not open path " + request->getPath() + "\n";
*response << "HTTP/1.1 404 Not found\r\nContent-Length: " << content.length() << "\r\n\r\n" << content;
};
// Let the main thread to catch SIGINT and SIGQUIT
boost::asio::signal_set signals(io_service, SIGINT, SIGQUIT);
signals.async_wait(bind(afterSignal, &server, placeholders::_1));
thread server_thread([&server]() {
//Start server
server.start();
});
server_thread.join();
return 0;
}
} // end namespace std
int main(int argc, char **argv) {
return std::main(argc, argv);
}
|