-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
296 lines (235 loc) · 9.5 KB
/
main.cpp
File metadata and controls
296 lines (235 loc) · 9.5 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
#include <arpa/inet.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <netdb.h>
#include <set>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <thread>
#include <unistd.h>
#include <vector>
#include <zlib.h>
// For reading file
#include <fstream>
// For checking if the file exists or not
#include <sys/stat.h>
#include "utils/utils.hpp"
#define OK 200
#define NOT_FOUND 404
#define CREATED 201
const std::set<std::string> supported_compression_techniques = {"gzip"};
std::thread connections[100];
std::string directory_path = "";
void add_crlf(std::string &response_body) {
response_body.append("\r\n");
}
void add_status_code(int status_code, std::string &response_body) {
switch (status_code) {
case OK:
response_body.append("200 OK");
break;
case NOT_FOUND:
response_body.append("404 Not Found");
break;
case CREATED:
response_body.append("201 Created");
break;
}
add_crlf(response_body);
}
void add_content_type(std::string &response_body, std::string content_type) {
response_body.append("Content-Type: ");
response_body.append(content_type);
add_crlf(response_body);
}
void add_encodings(std::string &response_body, std::vector<std::string> &encodings) {
if (encodings.size() < 1)
return;
response_body.append("Content-Encoding: ");
for (int i = 0; i < (int)encodings.size(); i++) {
response_body.append(encodings[i]);
if (i < (int)encodings.size() - 1) {
response_body += ", ";
}
}
add_crlf(response_body);
}
void add_content(std::string &response_body, std::string content) {
int sz = content.size();
response_body.append("Content-Length: ");
response_body.append(std::to_string(sz));
add_crlf(response_body);
add_crlf(response_body);
response_body.append(content);
}
void add_connection(std::string &response_body, bool should_close) {
if (should_close) {
response_body.append("Connection: ");
response_body.append("close");
add_crlf(response_body);
}
}
void accept_connection(int client_socket) {
while (true) {
std::vector<char> buf(5000);
std::fill(buf.begin(), buf.end(), 0);
std::cout << "Reading the request data\n";
int bytes = recv(client_socket, buf.data(), buf.size(), 0);
if (bytes <= 0) {
close(client_socket);
std::cout << "Reading data failed\n";
return;
}
std::string response_body = "HTTP/1.1 ";
std::cout << "Successfully read the data.\n";
std::string requests(buf.data(), bytes);
std::cout << "Request headers and body from the client: \n" << requests << "\n";
std::string http_method = get_http_method(buf);
std::cout << "HTTP method: " << http_method << "\n";
std::string url = get_target_url(buf, http_method);
std::cout << "Target URL: " << url << "\n";
bool should_close = requests.find("Connection: close") != std::string::npos;
std::cout << "Should close " << should_close << "\n";
int idx_of_encoding = requests.find("Accept-Encoding");
std::cout << "Encoding: " << idx_of_encoding << "\n";
if (url.starts_with("/echo/")) {
std::cout << "Url with echo\n";
int idx = url.find_last_of('/');
std::string temp = url.substr(idx + 1);
add_status_code(OK, response_body);
add_connection(response_body, should_close);
std::cout << "URL Param in echo: " << temp << "\n";
if (idx_of_encoding != -1) {
int last_i = requests.find("\r\n", idx_of_encoding + 1);
int first_i = requests.find(":", idx_of_encoding) + 2;
std::string enc_typs = requests.substr(first_i, last_i - first_i);
std::vector<std::string> encoding_types = split_str(enc_typs, ", ");
std::vector<std::string> valid_encodings;
for (auto &encoding : encoding_types) {
if (supported_compression_techniques.find(encoding) != supported_compression_techniques.end())
valid_encodings.push_back(encoding);
}
add_content_type(response_body, "text/plain");
add_encodings(response_body, valid_encodings);
std::string compressed_data = encode_using_gzip(temp);
add_content(response_body, compressed_data);
std::cout << "Response for echo in encoding::\n" << response_body << "\n";
send(client_socket, response_body.c_str(), response_body.size(), 0);
} else {
add_content_type(response_body, "text/plain");
add_content(response_body, temp);
}
}
else if (url.starts_with("/user-agent")) {
std::cout << "URL starting with /user-agent\n";
int idx_of_user = requests.find("User-Agent");
int idx = requests.find(":", idx_of_user);
std::string str_prm = "";
for (int i = idx + 2;; i++) {
if (requests[i] == '\r' && requests[i + 1] == '\n')
break;
str_prm += requests[i];
}
std::cout << "User agent from header: " << str_prm << "\n";
add_status_code(OK, response_body);
add_connection(response_body, should_close);
add_content_type(response_body, "text/plain");
add_content(response_body, str_prm);
}
else if (url == "/") {
add_status_code(OK, response_body);
add_connection(response_body, should_close);
add_crlf(response_body);
}
else if (url.starts_with("/files/")) {
int idx = url.find_last_of('/');
std::string file_name = url.substr(idx + 1);
std::string path = directory_path + file_name;
if (http_method == "POST") {
std::ofstream file(path);
file << get_request_body(requests);
add_status_code(CREATED, response_body);
add_connection(response_body, should_close);
add_crlf(response_body);
} else {
struct stat md;
int is_file_exists = stat(path.c_str(), &md);
std::cout << "File path: " << path << " is file exits: " << is_file_exists << "\n";
if (is_file_exists == 0) {
std::ifstream file(path);
std::string file_content;
getline(file, file_content);
add_status_code(OK, response_body);
add_connection(response_body, should_close);
add_content_type(response_body, "application/octet-stream");
add_content(response_body, file_content);
} else {
add_status_code(NOT_FOUND, response_body);
add_connection(response_body, should_close);
add_crlf(response_body);
}
}
} else {
add_status_code(NOT_FOUND, response_body);
add_connection(response_body, should_close);
add_crlf(response_body);
}
std::cout << "Response body: " << response_body << "\n";
send(client_socket, response_body.c_str(), response_body.size(), 0);
if (should_close) {
close(client_socket);
return;
}
}
}
int main(int argc, char **argv) {
directory_path = get_directory(argv, argc);
// Flush after every std::cout / std::cerr
std::cout << std::unitbuf;
std::cerr << std::unitbuf;
// You can use print statements as follows for debugging, they'll be visible when running tests.
std::cout << "Logs from your program will appear here!\n";
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
std::cerr << "Failed to create server socket\n";
return 1;
}
// Since the tester restarts your program quite often, setting SO_REUSEADDR
// ensures that we don't run into 'Address already in use' errors
int reuse = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
std::cerr << "setsockopt failed\n";
return 1;
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(4221);
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) != 0) {
std::cerr << "Failed to bind to port 4221\n";
return 1;
}
int connection_backlog = 5;
if (listen(server_fd, connection_backlog) != 0) {
std::cerr << "listen failed\n";
return 1;
}
struct sockaddr_in client_addr;
int i = 0;
while (true) {
std::cout << "Waiting for a client to connect...\n";
int client_addr_len = sizeof(client_addr);
int client_socket = accept(server_fd, (struct sockaddr *)&client_addr, (socklen_t *)&client_addr_len);
if (client_socket < 0) {
std::cerr << "Cannot accept connection.\n";
exit(1);
}
// inet_ntoa gives ip of the client.
std::cout << "Client with ip " << inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port)
<< " connected on socket : " << client_socket << "\n";
connections[i++] = std::thread(accept_connection, client_socket);
}
return 0;
}