-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.hpp
More file actions
337 lines (287 loc) · 11 KB
/
httpserver.hpp
File metadata and controls
337 lines (287 loc) · 11 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#ifndef HTTPSERVER_H
#define HTTPSERVER_H
#include <string>
#include <boost/function.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/algorithm/string.hpp>
#include <thread>
#include <unordered_map>
#include <vector>
#include <iostream>
#include <sstream>
#include <memory>
#include <fstream>
#include <regex>
#define LOG() std::cout << __FILE__ << ":" << __LINE__ << std::endl
namespace httpserver{
class Request;
class Response;
class Connection;
class HttpServer;
enum HttpStatus{OK, NOT_FOUND};
typedef std::unordered_map<std::string, boost::function<bool (Request&, Response&, Connection&)> > res_type;
class HttpStatusUtil{
public:
static const std::string get_status_line(HttpStatus status){
switch (status) {
case NOT_FOUND:
return "404 Not Found";
default: // default to ok
return "200 OK";
}
}
};
class Request
{
friend class Connection;
private:
boost::asio::streambuf streambuf_;
public:
std::string content;
std::unordered_map<std::string, std::string> headers;
std::string method;
std::string path;
std::string http_version;
std::smatch base_match;
void parse_headers(){
std::string line;
std::istream is(&streambuf_);
// parse status line
std::getline(is, line);
std::vector<std::string> split_container;
boost::split(split_container, line, boost::is_any_of(" \r\n"), boost::token_compress_on);
method = split_container[0];
path = split_container[1];
http_version = split_container[2];
while(true){
std::getline(is, line);
size_t index = line.find(':');
if(index == std::string::npos)
break;
std::string key = line.substr(0, index);
std::string value = line.substr(index+1);
boost::trim(key);
boost::trim(value);
//std::cout << key << ": " << value << std::endl;
headers[key] = value;
}
}
};
class Response
{
friend class Connection;
private:
boost::asio::streambuf streambuf_;
bool headers_filled_;
bool key_exists(std::string key){
auto iter = headers.find(key);
return !(iter == headers.end());
}
public:
std::string content;
std::unordered_map<std::string, std::string> headers;
HttpStatus status;
void fill_headers_and_content(){
std::ostream os(&streambuf_);
if(headers_filled_ == false){
if(!key_exists("Content-Length")){
try{
headers["Content-Length"] = boost::lexical_cast<std::string>(content.size());
} catch(const std::exception &e){
headers["Content-Length"] = "0";
}
}
if(!key_exists("Content-type")){
headers["Content-Type"] = "text/plain";
}
os << "HTTP/1.1 " << HttpStatusUtil::get_status_line(status) << "\r\n";
for(auto p : headers){
os << p.first << ": " << p.second << "\r\n";
}
os << "\r\n";
headers_filled_ = true;
}
os << content;
}
Response(): headers_filled_(false){}
};
class Connection : public boost::enable_shared_from_this<Connection> {
private:
boost::shared_ptr<boost::asio::ip::tcp::socket> socket_;
Request request_;
Response response_;
void process_request(const res_type &resources){
bool need_write = true;
for(const auto &i : resources){
std::regex reg(i.first);
std::smatch match;
if(std::regex_match(request_.path, match, reg)){
request_.base_match = match;
need_write = i.second(request_, response_, *this);
if(need_write)
do_write();
return;
}
}
response_.status = NOT_FOUND;
response_.content = "Page Not Found";
std::cout << "404 request: " << request_.path << std::endl;
do_write();
}
void handler_read_request(const boost::system::error_code& e,
std::size_t size,
res_type &resources){
if(e){
std::cerr << __FUNCTION__ << ": " << e.message() << std::endl;
return;
}
request_.parse_headers();
std::cout << "Got Request: " << request_.method << " "
<< request_.path << " "
<< request_.http_version << std::endl;
size_t bytes_remain = request_.streambuf_.size() - size;
auto iter = request_.headers.find("Content-Length");
if(iter != request_.headers.end()){ // content-length found
unsigned long long content_length;
try {
content_length = stoull(iter->second);
}
catch(const std::exception &e) {
std::cerr << "parse content-length failed: " << iter->second << std::endl;
return;
}
if(content_length > bytes_remain) {
boost::asio::async_read(*socket_, request_.streambuf_,
boost::asio::transfer_exactly(content_length - bytes_remain),
[this, resources]
(const boost::system::error_code& ec, size_t) {
if(ec)
std::cerr << __FUNCTION__ << ec.message() << std::endl;
else{
process_request(resources);
}
});
}
} else{
process_request(resources);
}
}
void handler_write_response(const boost::system::error_code &e, std::size_t size){
if(e){
std::cerr << __FUNCTION__ << e.message() << std::endl;
return;
} else{
//std::cout << "write finished with " << size << "bytes" << std::endl;
}
}
public:
explicit Connection(boost::shared_ptr<boost::asio::ip::tcp::socket> socket):socket_(socket){}
// read from socket, fill into @request_
void do_read(res_type &resources){
boost::asio::async_read_until(*socket_,
request_.streambuf_,
"\r\n\r\n",
std::bind(&Connection::handler_read_request,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2,
resources));
}
// write headers and content of response to socket in HTTP format
void do_write(){
response_.fill_headers_and_content();
boost::asio::async_write(*socket_,
response_.streambuf_,
std::bind(&Connection::handler_write_response,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
void write_staticfile(std::string file_path, std::string filename){
std::ifstream ifs(file_path, std::ifstream::binary);
std::stringstream os;
if(!ifs.good()){
boost::asio::write(*socket_, boost::asio::buffer("HTTP/1.1 200 OK\r\nfile not found"));
return;
}
// get length of file:
ifs.seekg(0, ifs.end);
size_t length = ifs.tellg();
ifs.seekg(0, ifs.beg);
os << "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n";
os << "Content-Length: " << length << "\r\n";
os << "Content-Disposition: attachment; filename=" << filename << "\r\n\r\n";
boost::asio::write(*socket_, boost::asio::buffer(os.str()));
while(!ifs.eof()){
std::string str;
size_t transfer_length = length>4096?4096:length;
str.resize(transfer_length, ' '); // reserve space
char* begin = &*str.begin();
ifs.read(begin, transfer_length);
length -= transfer_length;
boost::asio::write(*socket_, boost::asio::buffer(str));
if(length == 0)
break;
}
ifs.close();
}
~Connection(){
}
};
class HttpServer
{
private:
int port_;
size_t thread_num_;
boost::asio::io_service io_service_;
boost::asio::ip::tcp::acceptor acceptor_;
std::vector<std::thread> threads_;
res_type resources;
void handle_accept(boost::shared_ptr<boost::asio::ip::tcp::socket> socket, const boost::system::error_code &err){
accept();
if(!err){
boost::asio::ip::tcp::endpoint remote_endpoint = socket->remote_endpoint();
//std::cout << "new connection from: " << remote_endpoint.address() << ":" << remote_endpoint.port() << std::endl;
boost::shared_ptr<Connection> connection(new Connection(socket));
connection->do_read(resources);
} else{
std::cerr << err.message() << std::endl;
}
}
void accept(){
boost::shared_ptr<boost::asio::ip::tcp::socket> socket(new boost::asio::ip::tcp::socket(io_service_));
acceptor_.async_accept(*socket, std::bind(&HttpServer::handle_accept, this, socket, std::placeholders::_1));
}
public:
HttpServer(int port, size_t thread_num) : port_(port),
thread_num_(thread_num),
acceptor_(io_service_){
}
virtual ~HttpServer(){}
// callback function return false to ask httpserver not send response
void add_resource(std::string url, boost::function<bool (Request&, Response&, Connection&)> fun){
resources[url] = fun;
}
void start(){
if(io_service_.stopped())
io_service_.reset();
boost::asio::ip::tcp::endpoint endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port_);
acceptor_.open(endpoint.protocol());
acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
acceptor_.bind(endpoint);
acceptor_.listen();
accept();
threads_.clear();
for(size_t i=1; i<thread_num_; ++i){
threads_.push_back(std::thread([this](){
io_service_.run();
}));
}
io_service_.run();
}
};
}
#endif