forked from bbotfatimezzahra/Webserv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMethods.cpp
More file actions
468 lines (429 loc) · 11.2 KB
/
Copy pathMethods.cpp
File metadata and controls
468 lines (429 loc) · 11.2 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#include"includes/Connection.hpp"
std::string get_extension(std::string str){
ssize_t s = str.size() - 1;
std::string ext;
while(s >= 0){
if(str[s] == '.')
break;
ext.push_back(str[s]);
s--;
}
if(str[s] == '.' && s != 0 && str[s - 1] != '/')
std::reverse(ext.begin(), ext.end());
else
ext.clear();
return ext;
}
std::string get_err5(){
std::string respo;
respo += "HTTP/1.0 500 Internal Server Error\r\n";
respo += "Connection: close\r\n";
respo += "Content-Type: text/html\r\n";
respo += "Content-Length: 186\r\n";
respo += "\r\n";
respo += "<!DOCTYPE html>\n<html>\n<head><title>500 Internal Server Error</title></head>\n<body>\n<h1>500 Internal Server Error</h1>\n<p>Sorry, something went wrong on the server.</p>\n</body>\n</html>";
return respo;
}
void Connection::get_err(int er){
struct stat buf;
std::stringstream ner;
off_t size;
this->_response.clear();
ner << er;
if(er == 204){
this->_response = "HTTP/1.0 204 No Content\r\nConnection: close\r\n\r\n";
return ;
}
if(er == 201){
this->_response = "HTTP/1.0 201 Created\r\nConnection: close\r\nLocation: " + upload_name +"\r\n\r\n";
return;
}
if(stat(this->_server.getError()[er].c_str(), &buf)){
this->_response = get_err5();
return ;
}
size = buf.st_size;
std::fstream file(this->_server.getError()[er].c_str(),std::ios::in);
if(!file){
this->_response = get_err5();
return ;
}
this->_response.append("HTTP/1.0 " + ner.str()+" "+this->_server.getName_err()[ner.str()]+"\r\n");
ner.str("");
ner << size;
_response += "Connection: close\r\n";
_response += "Content-Type: text/html\r\n";
this->_response.append("Content-Length: " + ner.str()+ "\r\n\r\n");
this->_response.append(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
_sendStatus = FINISHED;
}
void redirect_page(std::string &respo, Location *lc, std::string pth){
if(lc->getRedirect().begin()->first == 301){
respo.append("HTTP/1.0 301 Moved Permanently\r\n");
respo.append("Connection: close\r\n");
respo += "Content-Type: text/html\r\n";
respo.append("Content-Length: 199\r\n");
respo += "location: ";
respo += pth;
respo += "\r\n\r\n";
respo.append("<!DOCTYPE html>\n<html>\n<head>\n<title>301 Moved Permanently</title>\n</head>\n<body>\n<h1>301 Moved Permanently</h1>\n<p>The requested resource has been permanently moved to .</p>\n</body>\n</html>");
}
else{
respo.append("HTTP/1.0 302 Moved Found\r\n");
respo.append("Content-Length: 0\r\n");
respo += "Content-Type: text/html\r\n";
respo += "location: ";
respo += pth;
respo += "\r\n\r\n";
}
}
std::string get_content_type(std::string path){
std::string ext = get_extension(path);
if(ext == "png" || ext == "gif" || ext == "webp" || ext == "jpeg")
return("image/"+ext);
else if (ext == "mp4" || ext == "m4v")
return("video/mp4");
else if (ext == "txt" || ext == "py" || ext == "php" || ext == "sh")
return("text/plain");
else if (ext == "html" || ext == "css")
return ("text/"+ext);
else if (ext == "pdf" || ext == "json")
return("text/"+ext);
else
return "application/octet-stream";
}
void get_dire(std::string &respo, DIR **dir, std::string name_d){
struct dirent *d;
std::string body;
std::stringstream ss;
if(name_d[name_d.size() - 1] != '/')
name_d += '/';
body.append("<html>\n<head>\n<title>Index of " + name_d + "</title>\n</head>\n<body>\n<h1>Index of ");
body.append(name_d + "</h1>\n<hr>\n");
while((d = readdir(*dir))){
body.append("<a href=\"");
body += name_d + d->d_name;
body += "\">";
body += d->d_name;
body += "</a><br>\n";
}
respo.append("HTTP/1.0 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n");
body.append("</pre>\n<hr>\n</body>\n</html>");
ss << body.size();
respo.append("Content-Length: "+ss.str()+"\r\n\r\n");
respo += body;
}
bool check_cgi(std::string path, Location lc){
std::string ext = get_extension(path);
std::string c;
if(!ext.empty() && lc.getCgi().size() > 0){
c = "." + ext;
if(!lc.getCgi()[c].empty())
return true;
}
return false;
}
std::string cgi_respo(std::string tmp, std::string path){
size_t get = 0;
std::string respo;
std::string line;
std::string word;
std::string cp;
std::stringstream ss(tmp);
std::string loc;
std::getline(ss,line);
std::stringstream ww(line);
ww >> word;
if(word == "status:"){
ww >> loc;
respo = "HTTP/1.0 ";
respo += line.substr(8);
respo += "\r\nConnection: close\r\n";
get += line.size() + 1;
std::getline(ss,line);
std::stringstream ww(line);
ww >> word;
}
if (word == "Set-Cookie:"){
get += line.size() + 1;
respo += line;
respo += "\r\n";
std::getline(ss,line);
std::stringstream ww(line);
ww >> word;
}
if(word == "Content-Type:"){
get += line.size() + 1;
respo += line;
respo += "\r\n";
std::getline(ss,line);
std::stringstream ww(line);
ww >> word;
}
if(word == "Content-Length:"){
get += line.size() + 1;
respo += line;
respo += "\r\n\r\n";
}
if(respo.find("HTTP/1.0") == std::string::npos){
cp = respo;
respo.clear();
respo = "HTTP/1.0 200 OK\r\nConnection: close\r\n" + cp;
}
if(respo.find("Content-Type:") == std::string::npos){
if(respo.find("200 OK") == std::string::npos){
std::stringstream ss(respo);
ss >> word;
ss >> word;
return word;
}
respo += "Content-Type: " + get_content_type(path) + "\r\n";
}
if(respo.find("Content-Length:") == std::string::npos){
std::stringstream n ;
n << tmp.size() - get;
respo += "Content-Length: " + n.str() + "\r\n\r\n";
}
if(get > tmp.size())
return "502";
respo += tmp.substr(get);
return respo;
}
void sig_handler(int i){
throw MyError ("exit");
(void)i;
}
void Connection::run_cgi_get(std::string path, Location lc, char **env){
std::string pth = lc.getCgi()["." + get_extension(path)];
time_t start = time(NULL);
int status, fd;
char *scri[3];
pid_t pid;
pid_t w = 0;
signal(SIGINT,SIG_IGN);
cgi = generate_name();
fd = open(cgi.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
if(fd == -1)
get_err(500);
pid = fork();
if(pid == -1){
close(fd);
std::remove(cgi.c_str());
return get_err(500);
}
if(pid == 0){
signal(SIGINT,sig_handler);
scri[0] = strdup(pth.c_str());
scri[1] = strdup(path.c_str());
scri[2] = NULL;
dup2(fd, STDOUT_FILENO);
close(fd);
execve(pth.c_str(), scri, env);
free(scri[0]);
free(scri[1]);
free_env(env);
throw MyError ("exit");
}
while(w == 0 && time(NULL) - start < 7){
w = waitpid(pid, &status, WNOHANG);
if(w == pid && WIFEXITED(status) && !WEXITSTATUS(status) ){
close(fd);
if (!get_respo(cgi, true, path)){
std::remove(cgi.c_str());
return get_err(500);
}
return ;
}
if(WIFEXITED(status) && WEXITSTATUS(status) == 1){
close(fd);
std::remove(cgi.c_str());
return get_err(502);
}
}
if(w == 0){
kill(pid,SIGKILL) ;
waitpid(pid,&status,0);
close(fd);
std::remove(cgi.c_str());
return get_err(504);
}
close(fd);
std::remove(cgi.c_str());
return get_err(500);
}
bool Connection::get_respo(std::string content, bool b_cgi, std::string path){
struct stat buf;
std::string tmp;
sent = open(content.c_str(), O_RDONLY);
if(sent != -1){
stat(content.c_str(), &buf);
Chunked_Get(0,buf.st_size);
if(!b_cgi){
_response = "HTTP/1.0 200 OK\r\nConnection: close\r\nContent-Type: ";
_response += get_content_type(content);
_response += "\r\nContent-Length: ";
std::stringstream ss;
ss << buf.st_size;
_response += ss.str() + "\r\n\r\n";
}
size_t i = 1024*1024 ;
char str[i];
ssize_t r = read(sent,str,i);
_response.append(str, r);
if(_sendStatus != SENDING){
if(b_cgi)
std::remove(this->cgi.c_str());
close(sent);
sent = -2;
}
if(b_cgi){
tmp = cgi_respo(_response, path);
_response = tmp;
if(tmp.size() == 3){
if(tmp == "301" || tmp == "302")
get_err(501);
else
get_err(atoi(tmp.c_str()));
}
}
return true ;
}
sent = -2;
return false;
}
void free_env(char **env){
int i = 0;
while(env[i]){
free(env[i]);
i++;
}
delete[] env;
env = NULL;
}
bool Connection::Chunked_Get(int i, long size){
long much = 1024 * 1024 ;
char str[much ];
size_t r;
if(i && _sendStatus == SENDING){
r = read(sent, str, much);
if(!r){
_sendStatus = FINISHED;
if(!cgi.empty())
std::remove(cgi.c_str());
close(sent);
sent = -2;
}
else{
_response.clear();
_response.append(str, r);
}
return true;
}
else if (!i){
if(size > much)
_sendStatus = SENDING;
}
return false;
}
void Connection::MethodGet(Location &lc){
std::string path;
std::string tmp;
struct stat buf;
std::fstream file;
std::vector<std::string> vect = lc.getMethods();
size_t i = 0, j = lc.getIndex().size();
std::vector<std::string>::iterator it = std::find(vect.begin(), vect.end(), "GET");
if(it == vect.end()){
get_err(405);
return ;
}
path = lc.getRoot() + this->route;
int err = stat(path.c_str(), &buf);
if (err)
get_err(404);
else if(S_ISDIR(buf.st_mode)){
while(i < j){
tmp = path;
if(lc.getIndex()[i][0] != '/' && path[path.size() - 1] != '/')
tmp += "/";
tmp += lc.getIndex()[i];
if(!access(tmp.c_str(), F_OK) && check_cgi(tmp,lc)){
char **env = initialize_env(tmp,lc);
run_cgi_get(tmp,lc, env);
free_env(env);
return;
}
if(get_respo(tmp, false,""))
return;
i++;
}
if(lc.getAutoindex() == true){
DIR *dir = opendir(path.c_str());
if(dir){
get_dire(this->_response, &dir, _request.getPath());
closedir(dir);
return;
}
return get_err(403);
}
get_err(403);
}
else if(S_ISREG(buf.st_mode)){
if(check_cgi(path,lc)){
char **env = initialize_env(path,lc);
run_cgi_get(path,lc, env);
free_env(env);
return;
}
if(get_respo(path, false,""))
return;
get_err(403);
}
}
char **Connection::initialize_env(std::string path, Location &lc){
char **env;
std::string tmp;
env = new char*[12];
tmp = "QUERY_STRING=" + _request.getQuery();
env[0] = strdup(tmp.c_str());
tmp = "REQUEST_METHOD=" + _request.getMethod();
env[1] = strdup(tmp.c_str());
env[2] = strdup("SERVER_PROTOCOL=HTTP/1.0");
env[3] = strdup("GATEWAY_INTERFACE=CGI/1.1");
tmp = "HTTP_COOKIE=" + _request.getHeaders()["Cookie"];
env[4] = strdup(tmp.c_str());
tmp = "SCRIPT_PATH=" + path;
env[5] = strdup(tmp.c_str());
tmp = "CONTENT_TYPE=" + _request.getHeaders()["Content-Type"];
env[6] = strdup(tmp.c_str());
tmp = "CONTENT_LENGTH=" + _request.getHeaders()["Content-Length"];
env[7] = strdup(tmp.c_str());
tmp = "SCRIPT_ROOT=" + lc.getRoot() ;
env[8] = strdup(tmp.c_str());
tmp = "SERVER_NAME=" + this->_server.getIp();
env[9] = strdup(tmp.c_str());
tmp = "SERVER_PORT=" + this->_server.getPort();
env[10] = strdup(tmp.c_str());
env[11] = NULL;
return env;
}
void Connection::method(){
Location lc = check_loca(this->_request.getPath(), this->_server, this->route);
std::string mth = this->_request.getMethod();
if(_sendStatus == SENDING)
Chunked_Get(1,0);
else if(mth != "GET" && mth != "POST" && mth != "DELETE")
get_err(501);
else if(lc.getPath().empty())
get_err(404);
else if(lc.getRedirect().size() != 0)
redirect_page(this->_response, &lc, lc.getRedirect().begin()->second);
else if(mth == "GET" )
this->MethodGet(lc);
else if(mth == "POST" )
this->MethodPost(lc);
else if(mth == "DELETE")
this->MethodDelete(lc);
if(_sendStatus != SENDING)
_sendStatus = FINISHED;
}