-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
587 lines (486 loc) · 16.5 KB
/
server.c
File metadata and controls
587 lines (486 loc) · 16.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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <signal.h>
#include "threadpool.h"
#define RFC1123FMT "%a, %d %b %Y %H:%M:%S GMT"
/* ===================== Date helpers ===================== */
static void make_date_now(char out[128])
{
time_t now = time(NULL);
strftime(out, 128, RFC1123FMT, gmtime(&now));
}
static void make_date_from_time(time_t t, char out[128])
{
strftime(out, 128, RFC1123FMT, gmtime(&t));
}
/* ===================== MIME types (given) ===================== */
static char *get_mime_type(char *name)
{
char *ext = strrchr(name, '.');
if (!ext) return NULL;
if (strcmp(ext, ".html") == 0 || strcmp(ext, ".htm") == 0) return "text/html";
if (strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0) return "image/jpeg";
if (strcmp(ext, ".gif") == 0) return "image/gif";
if (strcmp(ext, ".png") == 0) return "image/png";
if (strcmp(ext, ".css") == 0) return "text/css";
if (strcmp(ext, ".au") == 0) return "audio/basic";
if (strcmp(ext, ".wav") == 0) return "audio/wav";
if (strcmp(ext, ".avi") == 0) return "video/x-msvideo";
if (strcmp(ext, ".mpeg") == 0 || strcmp(ext, ".mpg") == 0) return "video/mpeg";
if (strcmp(ext, ".mp3") == 0) return "audio/mpeg";
return NULL;
}
/* ===================== Exact HTML bodies ===================== */
static const char *BODY_400 =
"<HTML><HEAD><TITLE>400 Bad Request</TITLE></HEAD>\n"
"<BODY><H4>400 Bad request</H4>\n"
"Bad Request.\n"
"</BODY></HTML>";
static const char *BODY_403 =
"<HTML><HEAD><TITLE>403 Forbidden</TITLE></HEAD>\n"
"<BODY><H4>403 Forbidden</H4>\n"
"Access denied.\n"
"</BODY></HTML>";
static const char *BODY_404 =
"<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD>\n"
"<BODY><H4>404 Not Found</H4>\n"
"File not found.\n"
"</BODY></HTML>";
static const char *BODY_500 =
"<HTML><HEAD><TITLE>500 Internal Server Error</TITLE></HEAD>\n"
"<BODY><H4>500 Internal Server Error</H4>\n"
"Some server side error.\n"
"</BODY></HTML>\n\n";
static const char *BODY_501 =
"<HTML><HEAD><TITLE>501 Not supported</TITLE></HEAD>\n"
"<BODY><H4>501 Not supported</H4>\n"
"Method is not supported.\n"
"</BODY></HTML>";
static const char *BODY_302 =
"<HTML><HEAD><TITLE>302 Found</TITLE></HEAD>\n"
"<BODY><H4>302 Found</H4>\n"
"Directories must end with a slash.\n"
"</BODY></HTML>";
/* ===================== Response sender ===================== */
static void send_html_response(int fd,
int code,
const char *phrase,
const char *location_or_null,
const char *body)
{
char date[128];
make_date_now(date);
long body_len = (long)strlen(body);
char header[4096];
if (location_or_null) {
snprintf(header, sizeof(header),
"HTTP/1.0 %d %s\r\n"
"Server: webserver/1.0\r\n"
"Date: %s\r\n"
"Location: %s\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"\r\n",
code, phrase, date, location_or_null, body_len);
} else {
snprintf(header, sizeof(header),
"HTTP/1.0 %d %s\r\n"
"Server: webserver/1.0\r\n"
"Date: %s\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"\r\n",
code, phrase, date, body_len);
}
send(fd, header, strlen(header), MSG_NOSIGNAL);
send(fd, body, (size_t)body_len, MSG_NOSIGNAL);
}
static void send_400(int fd) { send_html_response(fd, 400, "Bad Request", NULL, BODY_400); }
static void send_403(int fd) { send_html_response(fd, 403, "Forbidden", NULL, BODY_403); }
static void send_404(int fd) { send_html_response(fd, 404, "Not Found", NULL, BODY_404); }
static void send_500(int fd) { send_html_response(fd, 500, "Internal Server Error", NULL, BODY_500); }
static void send_501(int fd) { send_html_response(fd, 501, "Not supported", NULL, BODY_501); }
static void send_302(int fd, const char *location_path_with_slash)
{
send_html_response(fd, 302, "Found", location_path_with_slash, BODY_302);
}
/* ===================== Permission checks using stat() ===================== */
/*
* FIX 1: Use stat() st_mode bits to check permissions instead of access().
* access() checks as the real UID/GID of the running process (the owner),
* so a file with -rw------- owned by the server user would pass access(R_OK).
* We need to check the OTHER bits (world-readable) to enforce proper access control.
*/
static int check_readable(struct stat *st)
{
/* Check world-readable bit */
return (st->st_mode & S_IROTH) != 0;
}
static int check_executable(struct stat *st)
{
/* Check world-executable bit */
return (st->st_mode & S_IXOTH) != 0;
}
static int parent_dirs_have_x(const char *path)
{
char temp[4096];
if (!path || path[0] == '\0') return 0;
strncpy(temp, path, sizeof(temp) - 1);
temp[sizeof(temp) - 1] = '\0';
char build[4096] = "";
char *saveptr = NULL;
char *tok = strtok_r(temp, "/", &saveptr);
while (tok) {
char *next = strtok_r(NULL, "/", &saveptr);
if (!next) break; /* tok is file name, stop at parents */
if (build[0] == '\0')
snprintf(build, sizeof(build), "%s", tok);
else {
if (strlen(build) + 1 < sizeof(build)) strcat(build, "/");
if (strlen(build) + strlen(tok) < sizeof(build)) strcat(build, tok);
}
if (access(build, X_OK) != 0) return 0;
tok = next;
}
return 1;
}
static int dir_can_list_and_enter(const char *dirpath)
{
struct stat st;
if (stat(dirpath, &st) < 0) return 0;
/* Need read+execute (world bits) on directory to list */
return ((st.st_mode & S_IROTH) && (st.st_mode & S_IXOTH));
}
/* ===================== 200 OK file sender ===================== */
static void send_file_200(int client_fd, const char *filepath, struct stat *st)
{
int fd = open(filepath, O_RDONLY);
if (fd < 0) {
/* FIX: open() failed unexpectedly -> 500 Internal Server Error */
send_500(client_fd);
return;
}
char date[128], lastmod[128];
make_date_now(date);
make_date_from_time(st->st_mtime, lastmod);
char *mime = get_mime_type((char *)filepath);
char header[4096];
if (mime) {
snprintf(header, sizeof(header),
"HTTP/1.0 200 OK\r\n"
"Server: webserver/1.0\r\n"
"Date: %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %ld\r\n"
"Last-Modified: %s\r\n"
"Connection: close\r\n"
"\r\n",
date, mime, (long)st->st_size, lastmod);
} else {
snprintf(header, sizeof(header),
"HTTP/1.0 200 OK\r\n"
"Server: webserver/1.0\r\n"
"Date: %s\r\n"
"Content-Length: %ld\r\n"
"Last-Modified: %s\r\n"
"Connection: close\r\n"
"\r\n",
date, (long)st->st_size, lastmod);
}
send(client_fd, header, strlen(header), MSG_NOSIGNAL);
char buf[4096];
int r;
while ((r = read(fd, buf, sizeof(buf))) > 0) {
if (send(client_fd, buf, r, MSG_NOSIGNAL) < 0) break;
}
close(fd);
}
/* ===================== Directory listing ===================== */
static void append_str(char *dst, size_t dstsz, const char *src)
{
size_t dlen = strlen(dst);
size_t slen = strlen(src);
if (dlen + slen + 1 >= dstsz) return;
memcpy(dst + dlen, src, slen);
dst[dlen + slen] = '\0';
}
static void send_dir_listing_200(int client_fd, const char *fs_dirpath, const char *req_path_with_slash)
{
DIR *dir = opendir(fs_dirpath);
if (!dir) {
send_403(client_fd);
return;
}
struct stat dst;
if (stat(fs_dirpath, &dst) < 0) {
closedir(dir);
send_403(client_fd);
return;
}
char lastmod_dir[128];
make_date_from_time(dst.st_mtime, lastmod_dir);
char body[65536];
body[0] = '\0';
append_str(body, sizeof(body),
"<HTML>\n"
"<HEAD><TITLE>Index of ");
append_str(body, sizeof(body), req_path_with_slash);
append_str(body, sizeof(body),
"</TITLE></HEAD>\n"
"\r<BODY>\n"
"<H4>Index of ");
append_str(body, sizeof(body), req_path_with_slash);
append_str(body, sizeof(body),
"</H4>\n"
"\r<table CELLSPACING=8>\n"
"<tr><th>Name</th><th>Last Modified</th><th>Size</th></tr>\n"
"\r\r");
struct dirent *ent;
while ((ent = readdir(dir)) != NULL) {
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char child_fs[4096];
if (strcmp(fs_dirpath, ".") == 0) {
snprintf(child_fs, sizeof(child_fs), "%s", ent->d_name);
} else {
snprintf(child_fs, sizeof(child_fs), "%s%s", fs_dirpath, ent->d_name);
}
struct stat st;
if (stat(child_fs, &st) < 0) continue;
char modt[128];
make_date_from_time(st.st_mtime, modt);
char sizebuf[64] = "";
if (S_ISREG(st.st_mode)) {
snprintf(sizebuf, sizeof(sizebuf), "%ld", (long)st.st_size);
} else {
sizebuf[0] = '\0';
}
append_str(body, sizeof(body), "<tr>\r<td><A HREF=\"");
append_str(body, sizeof(body), ent->d_name);
append_str(body, sizeof(body), "\">");
append_str(body, sizeof(body), ent->d_name);
append_str(body, sizeof(body), "</A></td><td>");
append_str(body, sizeof(body), modt);
append_str(body, sizeof(body), "</td>\r<td>");
append_str(body, sizeof(body), sizebuf);
append_str(body, sizeof(body), "</td>\r</tr>\r\n");
}
closedir(dir);
append_str(body, sizeof(body),
"</table>\r\n"
"<HR>\r\n"
"<ADDRESS>webserver/1.0</ADDRESS>\r\n"
"</BODY></HTML>\r\n");
long body_len = (long)strlen(body);
char date[128];
make_date_now(date);
char header[4096];
snprintf(header, sizeof(header),
"HTTP/1.0 200 OK\r\n"
"Server: webserver/1.0\r\n"
"Date: %s\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %ld\r\n"
"Last-Modified: %s\r\n"
"Connection: close\r\n"
"\r\n",
date, body_len, lastmod_dir);
send(client_fd, header, strlen(header), MSG_NOSIGNAL);
send(client_fd, body, (size_t)body_len, MSG_NOSIGNAL);
}
/* ===================== Request handler ===================== */
static void read_first_line(int fd, char out[4000])
{
int i = 0;
int bytes;
while (i < 3999) {
bytes = recv(fd, &out[i], 1, 0);
if (bytes <= 0) break;
if (i > 0 && out[i] == '\n' && out[i - 1] == '\r') break;
i++;
}
out[i] = '\0';
}
void handle_request(int client_fd)
{
char line[4000];
read_first_line(client_fd, line);
/* FIX 3: If client disconnected (empty line), send 500 and return */
if (line[0] == '\0') {
send_500(client_fd);
close(client_fd);
return;
}
char *method = strtok(line, " ");
char *path = strtok(NULL, " ");
char *proto = strtok(NULL, " \r\n");
if (!method || !path || !proto || strtok(NULL, " ") != NULL) {
send_400(client_fd);
close(client_fd);
return;
}
if (strcmp(proto, "HTTP/1.0") != 0 && strcmp(proto, "HTTP/1.1") != 0) {
send_400(client_fd);
close(client_fd);
return;
}
if (strcmp(method, "GET") != 0) {
send_501(client_fd);
close(client_fd);
return;
}
char req_path[4000];
strncpy(req_path, path, sizeof(req_path) - 1);
req_path[sizeof(req_path) - 1] = '\0';
const char *p = path;
if (p[0] == '/') p++;
char fs_path[4096];
if (p[0] == '\0') {
strcpy(fs_path, ".");
} else {
snprintf(fs_path, sizeof(fs_path), "%s", p);
}
struct stat st;
if (stat(fs_path, &st) < 0) {
send_404(client_fd);
close(client_fd);
return;
}
if (S_ISDIR(st.st_mode)) {
int req_len = (int)strlen(req_path);
/* FIX 4: Check permissions BEFORE doing 302 redirect */
if (!dir_can_list_and_enter(fs_path)) {
send_403(client_fd);
close(client_fd);
return;
}
if (req_len == 0 || req_path[req_len - 1] != '/') {
char location[4096];
snprintf(location, sizeof(location), "%s/", req_path);
send_302(client_fd, location);
close(client_fd);
return;
}
if (strcmp(fs_path, ".") != 0 && !parent_dirs_have_x(fs_path)) {
send_403(client_fd);
close(client_fd);
return;
}
/* build index path safely */
char index_path[4096];
int need = snprintf(index_path, sizeof(index_path),
(fs_path[strlen(fs_path) - 1] == '/') ? "%sindex.html" : "%s/index.html",
fs_path);
if (need < 0 || need >= (int)sizeof(index_path)) {
send_403(client_fd);
close(client_fd);
return;
}
struct stat ist;
if (stat(index_path, &ist) == 0) {
/* FIX 1: use stat st_mode bits instead of access() */
if (!S_ISREG(ist.st_mode) || !check_readable(&ist) || !parent_dirs_have_x(index_path)) {
send_403(client_fd);
close(client_fd);
return;
}
send_file_200(client_fd, index_path, &ist);
close(client_fd);
return;
}
send_dir_listing_200(client_fd, fs_path, req_path);
close(client_fd);
return;
}
/* file - FIX 1: use stat st_mode bits instead of access() */
if (!S_ISREG(st.st_mode) || !check_readable(&st) || !parent_dirs_have_x(fs_path)) {
send_403(client_fd);
close(client_fd);
return;
}
send_file_200(client_fd, fs_path, &st);
close(client_fd);
}
/* ===================== Threadpool wrapper ===================== */
static int handle_request_job(void *arg)
{
int client_fd = *(int *)arg;
free(arg);
handle_request(client_fd);
return 0;
}
/* ===================== main ===================== */
int main(int argc, char *argv[])
{
/* FIX 3: Ignore SIGPIPE so server doesn't crash when client disconnects */
signal(SIGPIPE, SIG_IGN);
if (argc != 5) {
fprintf(stderr,
"Usage: server <port> <pool-size> <max-queue-size> <max-number-of-requests>\n");
exit(1);
}
int port = atoi(argv[1]);
int pool_size = atoi(argv[2]);
int max_q = atoi(argv[3]);
int max_req = atoi(argv[4]);
threadpool *pool = create_threadpool(pool_size, max_q);
if (!pool) {
fprintf(stderr, "Failed to create threadpool\n");
exit(1);
}
int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
perror("socket");
exit(1);
}
int opt = 1;
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in srv;
memset(&srv, 0, sizeof(srv));
srv.sin_family = AF_INET;
srv.sin_port = htons((unsigned short)port);
srv.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listen_fd, (struct sockaddr *)&srv, sizeof(srv)) < 0) {
perror("bind");
close(listen_fd);
exit(1);
}
if (listen(listen_fd, 1024) < 0) {
perror("listen");
close(listen_fd);
exit(1);
}
for (int i = 0; i < max_req; i++) {
int client_fd = accept(listen_fd, NULL, NULL);
if (client_fd < 0) {
perror("accept");
close(listen_fd);
destroy_threadpool(pool);
exit(1);
}
int *pfd = (int *)malloc(sizeof(int));
if (!pfd) {
send_500(client_fd);
close(client_fd);
continue;
}
*pfd = client_fd;
dispatch(pool, handle_request_job, pfd);
}
close(listen_fd);
destroy_threadpool(pool);
return 0;
}