-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.cpp
More file actions
327 lines (277 loc) · 11.1 KB
/
HttpServer.cpp
File metadata and controls
327 lines (277 loc) · 11.1 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
#include "../include/HttpServer.h"
#include "../include/constants.h"
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <netdb.h>
#include <string>
#include <sys/socket.h>
#include <unistd.h>
#include <unordered_map>
constexpr size_t compile_time_method_hash(std::string_view method) {
size_t hash = 0;
for (char c : method) {
hash += c;
}
return hash;
}
size_t method_hash(std::string_view method) {
size_t hash = 0;
for (char c : method) {
hash += c;
}
return hash;
}
HttpServer::HttpServer() {
stop_flag.store(false);
for (int i = 0; i < Constants::max_worker_count; i++) {
threads.emplace_back(&HttpServer::handle_client, this);
}
}
HttpServer::~HttpServer() {
this->stop_listening();
for (int i = 0; i < threads.size(); i++) {
threads[i].join();
// std::cout << "thread removed: " << i << "\n";
}
threads.clear();
}
void HttpServer::listen(int port) {
listener_fd = get_listener_socket(port);
if (listener_fd < 0) {
throw std::runtime_error("unable to obtain listener socket, exiting\n");
}
std::cout << "server listening now...\n";
while (!stop_flag.load()) {
struct sockaddr_storage incoming_addr {};
socklen_t addr_size {sizeof(incoming_addr)};
int conn_file_descriptor = accept(listener_fd, reinterpret_cast<struct sockaddr *>(&incoming_addr), &addr_size);
if (conn_file_descriptor == -1) {
// If we're stopping, accept failures are expected; don't spam logs.
if (stop_flag.load()) break;
// Interrupted system call - retry.
if (errno == EINTR) continue;
// If socket was closed or not valid, stop the loop quietly.
if (errno == EBADF || errno == EINVAL || errno == EOPNOTSUPP) break;
// Otherwise log and continue or break as appropriate.
throw std::runtime_error("unable to obtain a valid connection file descriptor, exiting\n");
}
this->store_conn_fd(conn_file_descriptor);
}
if (listener_fd != -1) {
close(listener_fd);
listener_fd = -1;
}
}
void HttpServer::start_listening(int port) {
threads.emplace_back(&HttpServer::listen, this, port);
}
void HttpServer::stop_listening() {
stop_flag.store(true);
if (listener_fd != -1) {
shutdown(listener_fd, SHUT_RDWR); // interrupt the accept()
close(listener_fd);
listener_fd = -1;
}
}
void HttpServer::store_conn_fd(int conn_fd) {
queue.push(conn_fd);
}
void HttpServer::handle_client() {
while (!stop_flag.load()) {
// Read the incoming HTTP request
char request_buffer[4096];
int conn_fd {};
// if queue is empty
if (!queue.pop(conn_fd, stop_flag)) {
if (stop_flag.load()) return;
continue;
}
ssize_t bytes_read = recv(conn_fd, request_buffer, sizeof(request_buffer) - 1, 0);
if (bytes_read <= 0) {
close(conn_fd);
if (stop_flag.load()) return;
std::cerr << "Invalid request formatting: 0 bytes read\n";
continue;
}
request_buffer[bytes_read] = '\0'; // Null-terminate for safety
std::string_view path {request_buffer};
// find the method
size_t method_itr = path.find(' ');
if (method_itr == std::string_view::npos) {
close(conn_fd);
std::cerr << "Invalid request formatting: no spaces\n";
continue;
}
// check for valid method
std::string_view method = path.substr(0, method_itr);
// std::cout << "method: " << method << '\n';
// get the route which is the second word
size_t route_start = method_itr + 1;
size_t route_end = path.find(' ', route_start);
if (route_end == std::string_view::npos) {
close(conn_fd);
std::cerr << "Invalid request formatting: no valid route\n";
continue;
}
std::string_view route = path.substr(route_start, route_end - route_start);
// std::cout << "route: " << route << '\n';
// get body
size_t req_body_delimiter = path.find("\r\n\r\n");
if (req_body_delimiter == std::string_view::npos) {
close (conn_fd);
std::cerr << "Invalid request formatting: the start of the request body is malformed\n";
continue;
}
size_t req_body_start = req_body_delimiter + 4;
std::string_view req_body = path.substr(req_body_start, path.size() - req_body_start);
// std::cout << "body: " << req_body << '\n';
// TODO: create a map that has a key route and function pointer
Response res {};
std::string response {};
switch (method_hash(method)) {
case compile_time_method_hash("GET"):
case compile_time_method_hash("DELETE"):
case compile_time_method_hash("HEAD"):
case compile_time_method_hash("OPTIONS"):
case compile_time_method_hash("CONNECT"):
case compile_time_method_hash("TRACE"): {
const Request req { path, ""};
if (routes[method].find(route) != routes[method].end()) {
Handler route_fn = routes[method][route];
route_fn(req, res);
response =
"HTTP/1.1 200 OK\r\n"
"Content-Length: " + std::to_string(res.body.size()) + "\r\n"
"Connection: close\r\n"
"\r\n" +
std::string(res.body);
} else {
res.body = "{\"error\": \"The requested API route does not exist\"}";
response =
"HTTP/1.1 404 Not Found\r\n"
"Content-Length: " + std::to_string(res.body.size()) + "\r\n"
"Connection: close\r\n"
"\r\n" +
std::string(res.body);
}
break;
}
case compile_time_method_hash("POST"):
case compile_time_method_hash("PUT"):
case compile_time_method_hash("PATCH"): {
const Request req { path, std::string(req_body)};
if (routes[method].find(route) != routes[method].end()) {
Handler route_fn = routes[method][route];
if (route_fn != nullptr) {
route_fn(req, res);
}
response =
"HTTP/1.1 200 OK\r\n"
"Content-Length: " + std::to_string(res.body.size()) + "\r\n"
"Connection: close\r\n"
"\r\n" +
std::string(res.body);
} else {
res.body = "{\"error\": \"The requested endpoint does not exist\"}";
response =
"HTTP/1.1 404 Not Found\r\n"
"Content-Length: " + std::to_string(res.body.size()) + "\r\n"
"Connection: close\r\n"
"\r\n" +
std::string(res.body);
}
break;
}
default: {
res.body = "{\"error\": \"The request does not have a valid HTTP method\"}";
response =
"HTTP/1.1 500 Error\r\n"
"Content-Length: " + std::to_string(res.body.size()) + "\r\n"
"Connection: close\r\n"
"\r\n" +
std::string(res.body);
// std::cout << request_buffer << "\n";
}
}
int bytes_sent = send(conn_fd, response.c_str(), response.size(), 0);
if (bytes_sent == -1) {
close(conn_fd);
std::cerr << "\n\n" << strerror(errno) << ": issue sending message to connection\n";
continue;
}
// std::cout << request_buffer << "\n";
close(conn_fd);
}
}
int HttpServer::get_listener_socket(int port) {
std::string port_str = std::to_string(port);
struct addrinfo hints {};
struct addrinfo* addrinfo_ptr {};
struct addrinfo* results {};
int socket_file_descriptor {};
hints.ai_family = AF_UNSPEC; // can be IPv4 or 6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in IP for us
int status = getaddrinfo(Constants::hostname, port_str.c_str(), &hints, &results);
if (status != 0) {
throw std::runtime_error("gai error: " + std::string(gai_strerror(status)));
}
// find the first file descriptor that does not fail
for (addrinfo_ptr = results; addrinfo_ptr != nullptr; addrinfo_ptr = addrinfo_ptr->ai_next) {
socket_file_descriptor = socket(addrinfo_ptr->ai_family, addrinfo_ptr->ai_socktype, addrinfo_ptr->ai_protocol);
if (socket_file_descriptor == -1) {
std::cerr << "\n\n" << strerror(errno) << ": issue fetching the socket file descriptor\n";
continue;
}
// set socket options
int yes = 1;
int sockopt_status = setsockopt(socket_file_descriptor, SOL_SOCKET,SO_REUSEADDR, &yes, sizeof(int));
if (sockopt_status == -1) {
throw std::runtime_error(std::string(strerror(errno)) + ": issue setting socket options");
}
// associate the socket descriptor with the port passed into getaddrinfo()
int bind_status = bind(socket_file_descriptor, addrinfo_ptr->ai_addr, addrinfo_ptr->ai_addrlen);
if (bind_status == -1) {
std::cerr << "\n\n" << strerror(errno) << ": issue binding the socket descriptor with a port";
continue;
}
break;
}
freeaddrinfo(results);
if (addrinfo_ptr == nullptr) {
throw std::runtime_error(std::string(strerror(errno)) + ": failed to bind port to socket");
}
int listen_status = ::listen(socket_file_descriptor, Constants::backlog);
if (listen_status == -1) {
throw std::runtime_error(std::string(strerror(errno)) + ": issue trying to call listen()");
}
return socket_file_descriptor;
}
void HttpServer::get_mapping(std::string_view route, const Handler& fn) {
routes["GET"][route] = fn;
}
void HttpServer::post_mapping(std::string_view route, const Handler& fn) {
routes["POST"][route] = fn;
}
void HttpServer::put_mapping(std::string_view route, const Handler& fn) {
routes["PUT"][route] = fn;
}
void HttpServer::patch_mapping(std::string_view route, const Handler& fn) {
routes["PATCH"][route] = fn;
}
void HttpServer::delete_mapping(std::string_view route, const Handler& fn) {
routes["DELETE"][route] = fn;
}
void HttpServer::head_mapping(std::string_view route, const Handler& fn) {
routes["HEAD"][route] = fn;
}
void HttpServer::options_mapping(std::string_view route, const Handler& fn) {
routes["OPTIONS"][route] = fn;
}
void HttpServer::connect_mapping(std::string_view route, const Handler& fn) {
routes["CONNECT"][route] = fn;
}
void HttpServer::trace_mapping(std::string_view route, const Handler& fn) {
routes["TRACE"][route] = fn;
}