-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.cpp
255 lines (235 loc) · 6.76 KB
/
socket.cpp
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
#include <iostream>
#include <sys/socket.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <map>
#include "socket.hpp"
#include "request.hpp"
#include "response.hpp"
#include "cgi.hpp"
#include "delete.hpp"
#include <fcntl.h>
#include <poll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <set>
#include "post.hpp"
#include "list_files.hpp"
#include <sys/stat.h>
/*
* bind a port to a socket
*/
int set_socket_settings(int socket, int port, sockaddr_in &address) {
memset((char *)&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(port);
const int enable = 1;
if (setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {
return (EXIT_FAILURE);
}
if (bind(socket, (struct sockaddr *)&address, sizeof(address)) < 0) {
std::cerr << "Cannot bind to port " << port;
perror(" ");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
/*
* make the socket prepared to accept connections (make it listen)
*/
int listening_socket(int socket, int backlog) {
if (listen(socket, backlog) < 0) {
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
/*
* create a new socket for the first connection request in the queue
* returns new socket id on success
*/
int accept_socket(int socket, sockaddr_in address) {
int new_socket;
int address_len;
address_len = sizeof(address);
new_socket = accept(socket, (struct sockaddr *)&address, (socklen_t *)&address_len);
return (new_socket);
}
int method_allowed(std::string method, t_location location) {
for (unsigned long i = 0; i < location.unaccepted_methods.size(); i++) {
if (method == location.unaccepted_methods[i])
return (0);
}
return (1);
}
t_server get_server(t_settings settings, int port, t_request request) {
std::string host = request.headers["Host"].substr(0, request.headers["Host"].find(':'));
for (size_t i = 0; i < settings.servers.size(); i++) {
if (port == settings.servers[i].listen_port && host == settings.servers[i].name) {
return settings.servers[i];
}
}
for (size_t i = 0; i < settings.servers.size(); i++) {
if (port == settings.servers[i].listen_port) {
return settings.servers[i];
}
}
std::cerr << "port not found in get_server\n";
return (settings.servers[0]);
}
t_location get_location(t_server server, std::string uri) {
t_location empty_location = {};
for (size_t i = 0; i < server.locations.size(); i++) {
if (server.locations[i].location == uri) {
return server.locations[i];
}
}
return empty_location;
}
bool is_directory(std::string path) {
struct stat s;
if( stat(path.c_str(),&s) == 0 )
{
if( s.st_mode & S_IFDIR )
return true;
}
return false;
}
std::string handle_request(t_request request, t_settings settings, int port) {
std::string resp;
std::string uri = request.headers["Request-URI"];
std::string method = request.headers["Method"];
t_server server = get_server(settings, port, request);
std::string path = server.root + uri;
WS_ERROR_CODE error = WS_SUCCESS;
t_location location = get_location(server, uri);
if (!method_allowed(method, location))
return get_response("", 405, 0);
if (!uri.compare(server.redir_src)) {
return get_redir_response(server.redir_dst);
}
std::string webpage;
if (is_directory(path)) {
if (location.index.size()) {
webpage = path + "/" + location.index;
} else {
webpage = path + "/index.html";
}
} else {
webpage = path;
}
if (uri.size() > 1 && uri.find(".py") != std::string::npos) {
if (method == "GET")
return get_cgi(request);
else
return get_response("", 200, 0);
}
if (method == "GET") {
error = get_response_from_page(webpage, resp, 200);
}
else if (method == "DELETE") {
resp = get_delete(webpage);
}
else if (method == "POST") {
std::ifstream input_stream(webpage);
if (!input_stream.is_open()) {
error = WS_ERROR;
} else {
resp = get_post(request, server);
}
} else {
resp = get_response("", 501, 0);
}
if (error != WS_SUCCESS) {
if (method == "GET" && !location.index.size() && is_directory(path) && location.autoindex) {
error = list_files(path, uri, resp);
if (error != WS_SUCCESS)
resp = not_found(server);
}
else {
resp = not_found(server);
}
}
return resp;
}
struct t_connection {
int port;
int fd;
mutable t_request request;
mutable std::string resp;
bool operator <(const t_connection &other) const {
return fd < other.fd;
}
};
int listen_to_new_socket(t_settings settings) {
struct sockaddr_in address;
int backlog = SOMAXCONN; //how many requests can be backlogged
std::set<t_connection> connections;
int nr_servers = settings.servers.size();
std::set<int> ports;
for (int i = 0; i < nr_servers; i++) {
ports.insert(settings.servers[i].listen_port);
}
std::vector<int> port_vec(ports.begin(), ports.end());
int nr_ports = ports.size();
struct pollfd pfd_init = {-1, POLLIN | POLLOUT, 0};
std::vector<struct pollfd> pfd_ports(nr_ports, pfd_init);
/* open ports that are defined in the config */
for (int i = 0; i < nr_ports; i++) {
pfd_ports[i].fd = socket(AF_INET, SOCK_STREAM, 0);
if (pfd_ports[i].fd < 0) {
perror("Failed to create socket: ");
exit(EXIT_FAILURE);
}
if (set_socket_settings(pfd_ports[i].fd, port_vec[i], address) == EXIT_FAILURE)
exit(EXIT_FAILURE);
fcntl(pfd_ports[i].fd, F_SETFL, O_NONBLOCK);
if (listening_socket(pfd_ports[i].fd, backlog) == EXIT_FAILURE)
exit(EXIT_FAILURE);
}
/* handle all requests forever */
while (1) {
poll(&*pfd_ports.begin(), nr_ports, 0);
for (int i = 0; i < nr_ports; i++) {
if (!(pfd_ports[i].revents & POLLIN)) {
continue;
}
pfd_ports[i].revents = 0;
t_connection new_conn;
new_conn.fd = accept_socket(pfd_ports[i].fd, address);
if (new_conn.fd >= 0) {
fcntl(new_conn.fd, F_SETFL, O_NONBLOCK);
if (new_conn.fd == EXIT_FAILURE)
exit(EXIT_FAILURE);
new_conn.request.state = RS_START;
new_conn.request.written = 0;
new_conn.request.content_lenght = 0;
new_conn.request.header_size = 0;
new_conn.request.request_size = 0;
new_conn.port = port_vec[i];
connections.insert(new_conn);
}
}
/* read and write to/from existing connections */
std::set<t_connection>::iterator iter = connections.begin();
while ( iter != connections.end()) {
t_request *rp = &(iter->request);
std::string *resp = &(iter->resp);
get_request_info(iter->fd, rp, resp);
if (iter->request.state == RS_PROCESSING) {
*resp = handle_request(iter->request, settings, iter->port); //only when a whole request is finished
rp->state = RS_WRITING;
}
if (iter->request.state == RS_CANCELLED || iter->request.state == RS_DONE) {
close(iter->fd);
std::set<t_connection>::iterator next = iter;
next++;
connections.erase(iter);
iter = next;
} else {
iter++;
}
}
}
}