-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathwebserver.cc
More file actions
313 lines (281 loc) · 9.22 KB
/
webserver.cc
File metadata and controls
313 lines (281 loc) · 9.22 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
#include <signal.h>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <unistd.h> // _SC_NPROCESSORS_ONLN on OS X
#include "uv.h"
#include "llhttp.h"
// stl
#include <string>
#include <sstream>
#include <iostream>
#ifdef DEBUG
#define CHECK(status, msg) \
if (status != 0) { \
fprintf(stderr, "%s: %s\n", msg, uv_err_name(status)); \
exit(1); \
}
#define UVERR(err, msg) fprintf(stderr, "%s: %s\n", msg, uv_err_name(err))
#define LOG_ERROR(msg) puts(msg);
#define LOG(msg) puts(msg);
#define LOGF(...) printf(__VA_ARGS__);
#else
#define CHECK(status, msg)
#define UVERR(err, msg)
#define LOG_ERROR(msg)
#define LOG(msg)
#define LOGF(...)
#endif
static const int PORT = 8000;
static int request_num = 1;
static uv_loop_t* uv_loop;
static uv_tcp_t server;
static llhttp_settings_t parser_settings;
struct client_t {
uv_tcp_t handle;
llhttp_t parser;
uv_write_t write_req;
int request_num;
std::string path;
};
void on_close(uv_handle_t* handle) {
client_t* client = (client_t*) handle->data;
LOGF("[ %5d ] connection closed\n\n", client->request_num);
delete client;
}
void alloc_cb(uv_handle_t * /*handle*/, size_t suggested_size, uv_buf_t* buf) {
*buf = uv_buf_init((char*) malloc(suggested_size), suggested_size);
}
void on_read(uv_stream_t* tcp, ssize_t nread, const uv_buf_t * buf) {
LOGF("on read: %ld\n",nread);
client_t* client = (client_t*) tcp->data;
if (nread >= 0) {
llhttp_errno_t err = llhttp_execute(&client->parser, buf->base, nread);
if (err != HPE_OK) {
LOG_ERROR("parse error");
uv_close((uv_handle_t*) &client->handle, on_close);
}
} else {
if (nread != UV_EOF) {
UVERR(nread, "read");
}
uv_close((uv_handle_t*) &client->handle, on_close);
}
free(buf->base);
}
struct render_baton {
render_baton(client_t * _client) :
client(_client),
request(),
result(),
response_code("200 OK"),
content_type("text/plain"),
error(false) {
request.data = this;
}
client_t* client;
uv_work_t request;
std::string result;
std::string response_code;
std::string content_type;
bool error;
};
void after_write(uv_write_t* req, int status) {
CHECK(status, "write");
if (!uv_is_closing((uv_handle_t*)req->handle)) {
render_baton *closure = static_cast<render_baton *>(req->data);
delete closure;
uv_close((uv_handle_t*)req->handle, on_close);
}
}
bool endswith(std::string const& value, std::string const& search)
{
return value.length() >= search.length() &&
value.compare(value.length() - search.length(), search.length(), search) == 0;
}
void render(uv_work_t* req) {
render_baton *closure = static_cast<render_baton *>(req->data);
client_t* client = (client_t*) closure->client;
LOGF("[ %5d ] render\n", client->request_num);
std::string filepath(".");
filepath += client->path;
std::string index_path = (filepath + "index.html");
bool has_index = (access(index_path.c_str(),R_OK) != -1);
if (filepath[filepath.size()-1] == '/') {
uv_fs_t scandir_req;
int r = uv_fs_scandir(uv_loop, &scandir_req, filepath.c_str(), 0, NULL);
uv_dirent_t dent;
closure->content_type = "text/html";
std::ostringstream html;
html << "<html><body><ul>";
while (UV_EOF != uv_fs_scandir_next(&scandir_req, &dent)) {
std::string name = dent.name;
if (dent.type == UV_DIRENT_DIR) {
name += "/";
}
html << "<li><a href='" << name << "'>" << name << "</a></li>\n";
}
html << "</ul></body></html>";
closure->result = html.str();
uv_fs_req_cleanup(&scandir_req);
} else {
std::string file_to_open = filepath;
if (has_index) {
file_to_open = index_path;
}
bool exists = (access(file_to_open.c_str(),R_OK) != -1);
if (!exists) {
closure->result = "no access";
closure->response_code = "404 Not Found";
return;
}
FILE * f = fopen(file_to_open.c_str(),"rb");
if (f) {
std::fseek(f, 0, SEEK_END);
unsigned size = std::ftell(f);
std::fseek(f, 0, SEEK_SET);
closure->result.resize(size);
size_t bytes_read = std::fread(&closure->result[0], size, 1, f);
fclose(f);
if (bytes_read != 1) {
closure->result = "failed to read file";
closure->response_code = "500 Internal Server Error";
return;
}
if (endswith(file_to_open,"html")) {
closure->content_type = "text/html";
} else if (endswith(file_to_open,"css")) {
closure->content_type = "text/css";
} else if (endswith(file_to_open,"js")) {
closure->content_type = "application/javascript";
}
} else {
closure->result = "failed to open";
closure->response_code = "404 Not Found";
}
}
}
void after_render(uv_work_t* req) {
render_baton *closure = static_cast<render_baton *>(req->data);
client_t* client = (client_t*) closure->client;
LOGF("[ %5d ] after render\n", client->request_num);
std::ostringstream rep;
rep << "HTTP/1.1 " << closure->response_code << "\r\n"
<< "Content-Type: " << closure->content_type << "\r\n"
<< "Connection: keep-alive\r\n"
<< "Content-Length: " << closure->result.size() << "\r\n"
<< "Access-Control-Allow-Origin: *\r\n"
<< "\r\n"
<< closure->result;
std::string res = rep.str();
uv_buf_t resbuf;
resbuf.base = (char *)res.c_str();
resbuf.len = res.size();
client->write_req.data = closure;
// https://github.com/joyent/libuv/issues/344
int r = uv_write(&client->write_req,
(uv_stream_t*)&client->handle,
&resbuf,
1,
after_write);
CHECK(r, "write buff");
}
int on_message_begin(llhttp_t* /*parser*/) {
LOGF("\n***MESSAGE BEGIN***\n");
return 0;
}
int on_headers_complete(llhttp_t* /*parser*/) {
LOGF("\n***HEADERS COMPLETE***\n");
return 0;
}
int on_url(llhttp_t* parser, const char* url, size_t length) {
client_t* client = (client_t*) parser->data;
LOGF("[ %5d ] on_url\n", client->request_num);
LOGF("Url: %.*s\n", (int)length, url);
// Simple URL parsing - just extract the path
std::string url_str(url, length);
size_t path_start = url_str.find('/');
if (path_start != std::string::npos) {
size_t query_start = url_str.find('?', path_start);
if (query_start != std::string::npos) {
client->path = url_str.substr(path_start, query_start - path_start);
} else {
client->path = url_str.substr(path_start);
}
} else {
client->path = "/";
}
return 0;
}
int on_header_field(llhttp_t* /*parser*/, const char* at, size_t length) {
LOGF("Header field: %.*s\n", (int)length, at);
return 0;
}
int on_header_value(llhttp_t* /*parser*/, const char* at, size_t length) {
LOGF("Header value: %.*s\n", (int)length, at);
return 0;
}
int on_body(llhttp_t* /*parser*/, const char* at, size_t length) {
LOGF("Body: %.*s\n", (int)length, at);
return 0;
}
int on_message_complete(llhttp_t* parser) {
client_t* client = (client_t*) parser->data;
LOGF("[ %5d ] on_message_complete\n", client->request_num);
render_baton *closure = new render_baton(client);
int status = uv_queue_work(uv_loop,
&closure->request,
render,
(uv_after_work_cb)after_render);
CHECK(status, "uv_queue_work");
assert(status == 0);
return 0;
}
void on_connect(uv_stream_t* server_handle, int status) {
CHECK(status, "connect");
assert((uv_tcp_t*)server_handle == &server);
client_t* client = new client_t();
client->request_num = request_num;
request_num++;
LOGF("[ %5d ] new connection\n", request_num);
uv_tcp_init(uv_loop, &client->handle);
llhttp_init(&client->parser, HTTP_REQUEST, &parser_settings);
client->parser.data = client;
client->handle.data = client;
int r = uv_accept(server_handle, (uv_stream_t*)&client->handle);
CHECK(r, "accept");
uv_read_start((uv_stream_t*)&client->handle, alloc_cb, on_read);
}
#define MAX_WRITE_HANDLES 1000
int main() {
signal(SIGPIPE, SIG_IGN);
int cores = sysconf(_SC_NPROCESSORS_ONLN);
printf("number of cores %d\n",cores);
char cores_string[10];
snprintf(cores_string, sizeof(cores_string), "%d", cores);
setenv("UV_THREADPOOL_SIZE",cores_string,1);
llhttp_settings_init(&parser_settings);
parser_settings.on_url = on_url;
// notification callbacks
parser_settings.on_message_begin = on_message_begin;
parser_settings.on_headers_complete = on_headers_complete;
parser_settings.on_message_complete = on_message_complete;
// data callbacks
parser_settings.on_header_field = on_header_field;
parser_settings.on_header_value = on_header_value;
parser_settings.on_body = on_body;
uv_loop = uv_default_loop();
int r = uv_tcp_init(uv_loop, &server);
CHECK(r, "tcp_init");
r = uv_tcp_keepalive(&server,1,60);
CHECK(r, "tcp_keepalive");
struct sockaddr_in address;
r = uv_ip4_addr("0.0.0.0", PORT, &address);
CHECK(r, "ip4_addr");
r = uv_tcp_bind(&server, (const struct sockaddr*)&address, 0);
CHECK(r, "tcp_bind");
r = uv_listen((uv_stream_t*)&server, MAX_WRITE_HANDLES, on_connect);
CHECK(r, "uv_listen");
printf("listening on port %d\n", PORT);
uv_run(uv_loop,UV_RUN_DEFAULT);
}