-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpserver.c
More file actions
770 lines (643 loc) · 21.9 KB
/
Copy pathhttpserver.c
File metadata and controls
770 lines (643 loc) · 21.9 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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> // for strcasecmp
#include <pthread.h>
#include "httpserver.h"
#include <netinet/in.h>
#include <signal.h>
#include <arpa/inet.h>
#include "queue.h"
#include <regex.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <ctype.h>
#include <sys/stat.h>
#define MAX_REQUEST_SIZE 8192
queue *job_queue = NULL;
pthread_mutex_t fs_lock = PTHREAD_MUTEX_INITIALIZER; // protects file ops + log
// alec
// takes in port from the user inputted command that is run
// creates socket and returns the file descriptor that specifes the socket itself
int create_socket(int port) {
signal(SIGPIPE, SIG_IGN);
struct sockaddr_in addr;
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0) {
return -2;
}
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (bind(listenfd, (struct sockaddr *) &addr, sizeof addr) < 0) {
close(listenfd);
return -3;
}
if (listen(listenfd, 500) < 0) {
close(listenfd);
return -4;
}
return listenfd;
}
// accepts a single connection off the front of the queue
// takes in the serves file descriptor from the create socket function
// returns the users file descriptor
// put this in a while loop
int accept_connection(int server_fd) {
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
int client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &len);
if (client_fd < 0) {
perror("accept failed");
}
return client_fd;
}
// parse_request now:
// - reads until it sees \r\n\r\n (or buffer full / error)
// - enforces method/URI/version syntax
// - parses headers, including Request-Id and Content-Length
// - if Content-Length is present, reads exactly that many bytes
// - on success: returns 0
// - on failure: returns an HTTP status code (400 or 500)
// and leaves req->body NULL (or freed)
int parse_request(int client_fd, http_request_t *req) {
memset(req, 0, sizeof(*req));
char buffer[MAX_REQUEST_SIZE];
ssize_t n = 0;
int status = 400; // default for parse errors
// ---- read until we get full headers (\r\n\r\n) or buffer full ----
char *hdr_end = NULL;
while (n < (ssize_t) (sizeof(buffer) - 1)) {
ssize_t r = recv(client_fd, buffer + n, sizeof(buffer) - 1 - n, 0);
if (r <= 0) {
// connection closed or error during header read
return 400;
}
n += r;
buffer[n] = '\0';
hdr_end = strstr(buffer, "\r\n\r\n");
if (hdr_end != NULL) {
break;
}
}
if (!hdr_end) {
// headers never completed
return 400;
}
// total bytes of header (including final \r\n\r\n)
ssize_t header_bytes = (hdr_end - buffer) + 4;
// ---- 1. Parse REQUEST LINE (char-by-char) ----
int i = 0;
// method: [A-Za-z]{1,8}
int method_start = i;
int method_len = 0;
while (i < header_bytes && buffer[i] != ' ' && buffer[i] != '\r' && buffer[i] != '\n') {
unsigned char c = (unsigned char) buffer[i];
if (!isalpha(c))
return 400; // invalid char in method
if (method_len >= 8)
return 400; // too long
method_len++;
i++;
}
if (method_len == 0 || i >= header_bytes || buffer[i] != ' ')
return 400; // must end with space and be non-empty
if (method_len >= (int) sizeof(req->method))
return 400; // avoid overflow of method buffer
memcpy(req->method, &buffer[method_start], method_len);
req->method[method_len] = '\0';
i++; // skip space after method
// URI: /[A-Za-z0-9.-]{1,63}
if (i >= header_bytes || buffer[i] != '/')
return 400; // must start with '/'
int uri_start = i;
int uri_len = 0;
// first character is '/'
uri_len++;
i++;
int tail_len = 0; // number of chars after '/'
while (i < header_bytes && buffer[i] != ' ' && buffer[i] != '\r' && buffer[i] != '\n') {
unsigned char c = (unsigned char) buffer[i];
if (!isalnum(c) && c != '.' && c != '-')
return 400; // invalid URI character
tail_len++;
if (tail_len > 63)
return 400; // too long after '/'
uri_len++;
i++;
}
if (tail_len == 0)
return 400; // need at least one char after '/'
if (i >= header_bytes || buffer[i] != ' ')
return 400; // URI must end with a space
if (uri_len >= (int) sizeof(req->uri))
return 400; // avoid overflow of URI buffer
memcpy(req->uri, &buffer[uri_start], uri_len);
req->uri[uri_len] = '\0';
i++; // skip space after URI
// version: HTTP/[0-9].[0-9]\r\n
int ver_start = i;
int ver_len = 0;
// walk until CR or LF
while (i < header_bytes && buffer[i] != '\r' && buffer[i] != '\n') {
ver_len++;
i++;
}
if (i + 1 >= header_bytes)
return 400; // need room for \r\n
if (buffer[i] != '\r' || buffer[i + 1] != '\n')
return 400; // must end with CRLF
// version must match HTTP/[0-9].[0-9]
if (ver_len != 8)
return 400; // length of "HTTP/x.y" is 8
if (strncmp(&buffer[ver_start], "HTTP/", 5) != 0)
return 400;
unsigned char d1 = (unsigned char) buffer[ver_start + 5];
unsigned char dot = (unsigned char) buffer[ver_start + 6];
unsigned char d2 = (unsigned char) buffer[ver_start + 7];
if (!isdigit(d1) || dot != '.' || !isdigit(d2))
return 400;
if (ver_len >= (int) sizeof(req->version))
return 400; // avoid overflow of version buffer
memcpy(req->version, &buffer[ver_start], ver_len);
req->version[ver_len] = '\0';
// advance past CRLF at end of request line
i += 2;
// ---- 2. Parse HEADERS (using regex, but now with Content-Length) ----
char *p = buffer + i;
size_t content_length = 0;
int have_content_length = 0;
regex_t hdr;
const char *hdr_regex = "^([A-Za-z0-9.-]{1,128}): ([ -~]{1,128})\r\n";
if (regcomp(&hdr, hdr_regex, REG_EXTENDED) != 0) {
return 500; // internal error compiling regex
}
int ok = 1;
while (1) {
// Empty line = end of headers
if (strncmp(p, "\r\n", 2) == 0) {
p += 2;
break;
}
regmatch_t hm[3];
if (regexec(&hdr, p, 3, hm, 0) != 0) {
ok = 0;
status = 400;
break;
}
size_t line_len = hm[0].rm_eo;
size_t key_len = hm[1].rm_eo - hm[1].rm_so;
size_t val_len = hm[2].rm_eo - hm[2].rm_so;
char key[129];
char value[129];
if (key_len >= sizeof(key) || val_len >= sizeof(value)) {
ok = 0;
status = 400;
break;
}
memcpy(key, p + hm[1].rm_so, key_len);
key[key_len] = '\0';
memcpy(value, p + hm[2].rm_so, val_len);
value[val_len] = '\0';
// Request-Id header
if (strcasecmp(key, "Request-Id") == 0) {
req->request_id = atoi(value);
} else if (strcasecmp(key, "Content-Length") == 0) {
char *endptr = NULL;
errno = 0;
long v = strtol(value, &endptr, 10);
if (errno != 0 || endptr == value || *endptr != '\0' || v < 0) {
ok = 0;
status = 400;
break;
}
have_content_length = 1;
content_length = (size_t) v;
}
p += line_len;
}
regfree(&hdr);
if (!ok) {
return status;
}
// ---- 3. Read BODY based on Content-Length ----
size_t body_bytes_in_buffer = (buffer + n) - p;
if (have_content_length) {
if (content_length == 0) {
// explicitly empty body
req->body = NULL;
req->body_length = 0;
} else {
req->body = malloc(content_length);
if (!req->body) {
return 500;
}
size_t to_copy
= body_bytes_in_buffer > content_length ? content_length : body_bytes_in_buffer;
if (to_copy > 0) {
memcpy(req->body, p, to_copy);
}
size_t copied = to_copy;
while (copied < content_length) {
ssize_t r = recv(client_fd, req->body + copied, content_length - copied, 0);
if (r <= 0) {
free(req->body);
req->body = NULL;
req->body_length = 0;
return 400;
}
copied += (size_t) r;
}
req->body_length = content_length;
}
} else {
// No Content-Length: treat as no body (spec says PUT with no CL -> empty file)
req->body = NULL;
req->body_length = 0;
}
return 0;
}
// closes the connection from a single user to the server; allows the next connection to be made
void close_connection(int client_fd) {
close(client_fd);
}
// charan
void *worker(void *arg) {
(void) arg;
while (1) {
int client_fd = dequeue();
http_request_t req = { 0 };
http_response_t rep = { 0 };
int status = parse_request(client_fd, &req);
if (status != 0) {
// Parse error or internal error: no filesystem changes.
rep.status = status;
if (status == 400) {
rep.status_phrase = (char *) "Bad Request";
set_body_text(&rep, "Bad Request\n");
} else if (status == 500) {
rep.status_phrase = (char *) "Internal Server Error";
set_body_text(&rep, "Internal Server Error\n");
} else {
// fallback: treat as Bad Request
rep.status_phrase = (char *) "Bad Request";
set_body_text(&rep, "Bad Request\n");
}
// Serialize log lines to avoid interleaving
pthread_mutex_lock(&fs_lock);
log_request(&req, &rep);
pthread_mutex_unlock(&fs_lock);
// Response can be sent without holding the lock
send_response(client_fd, &rep);
close_connection(client_fd);
if (req.body)
free(req.body);
if (rep.body)
free(rep.body);
continue;
}
// ---- Valid request: serialize filesystem + logging ----
pthread_mutex_lock(&fs_lock);
// This will call exec_get/exec_put as needed and set rep fields.
handle_request(&req, &rep);
// Log while still under the same lock so log order matches
// the order of filesystem operations.
log_request(&req, &rep);
pthread_mutex_unlock(&fs_lock);
// ---- Send response after releasing the lock ----
send_response(client_fd, &rep);
close_connection(client_fd);
if (req.body)
free(req.body);
if (rep.body)
free(rep.body);
}
}
void enqueue(int client_fd) {
job_t *new_job = malloc(sizeof(job_t));
if (!new_job) {
// If malloc fails, we can just close the connection (best-effort)
close(client_fd);
return;
}
new_job->client_fd = client_fd;
queue_push(job_queue, new_job);
}
int dequeue(void) {
void *item = NULL;
queue_pop(job_queue, &item);
job_t *new_job = (job_t *) item; // get response from pop and cast into job_t
int client_fd = new_job->client_fd;
free(new_job);
return client_fd;
}
static void set_body_text(http_response_t *rep, const char *text) {
size_t len = strlen(text);
uint8_t *buf = malloc(len);
if (!buf) {
rep->body = NULL;
rep->body_length = 0;
return;
}
memcpy(buf, text, len);
rep->body = buf;
rep->body_length = len;
}
// spencer
int handle_request(http_request_t *req, http_response_t *rep) {
if (strcmp(req->version, "HTTP/1.1") != 0) {
rep->status = 505;
rep->status_phrase = (char *) "Version Not Supported";
set_body_text(rep, "Version Not Supported\n");
return 505;
}
if (strcmp(req->method, "GET") == 0) {
return exec_get(req, rep);
} else if (strcmp(req->method, "PUT") == 0) {
return exec_put(req, rep);
} else {
rep->status = 501;
rep->status_phrase = (char *) "Not Implemented";
set_body_text(rep, "Not Implemented\n");
return 501;
}
}
int exec_get(http_request_t *req, http_response_t *rep) {
// map URI "/foo" -> "foo" in current directory
const char *path = (req->uri[0] == '/') ? (req->uri + 1) : req->uri;
struct stat st;
if (stat(path, &st) < 0) {
if (errno == ENOENT) {
rep->status = 404;
rep->status_phrase = (char *) "Not Found";
set_body_text(rep, "Not Found\n");
return 404;
}
if (errno == EACCES) {
rep->status = 403;
rep->status_phrase = (char *) "Forbidden";
set_body_text(rep, "Forbidden\n");
return 403;
}
rep->status = 500;
rep->status_phrase = (char *) "Internal Server Error";
set_body_text(rep, "Internal Server Error\n");
return 500;
}
// if it's a directory, forbid it
if (S_ISDIR(st.st_mode)) {
rep->status = 403;
rep->status_phrase = (char *) "Forbidden";
set_body_text(rep, "Forbidden\n");
return 403;
}
int fd = open(path, O_RDONLY);
if (fd < 0) {
if (errno == ENOENT) { // file not found
rep->status = 404;
rep->status_phrase = (char *) "Not Found";
set_body_text(rep, "Not Found\n");
return 404;
}
if (errno == EACCES) { // permission denied
rep->status = 403;
rep->status_phrase = (char *) "Forbidden";
set_body_text(rep, "Forbidden\n");
return 403;
}
// unexpected error
rep->status = 500;
rep->status_phrase = (char *) "Internal Server Error";
set_body_text(rep, "Internal Server Error\n");
return 500;
}
// getting the file length
off_t fsize = lseek(fd, 0, SEEK_END);
if (fsize < 0) {
close(fd);
rep->status = 500;
rep->status_phrase = (char *) "Internal Server Error";
set_body_text(rep, "Internal Server Error\n");
return 500;
}
if (lseek(fd, 0, SEEK_SET) < 0) {
close(fd);
rep->status = 500;
rep->status_phrase = (char *) "Internal Server Error";
set_body_text(rep, "Internal Server Error\n");
return 500;
}
// reading content from file
rep->body = malloc((size_t) fsize);
if (!rep->body) {
close(fd);
rep->status = 500;
rep->status_phrase = (char *) "Internal Server Error";
set_body_text(rep, "Internal Server Error\n");
return 500;
}
size_t total = 0;
while (total < (size_t) fsize) {
ssize_t r = read(fd, rep->body + total, (size_t) fsize - total);
if (r < 0) {
perror("error reading file");
free(rep->body);
rep->body = NULL;
rep->body_length = 0;
close(fd);
rep->status = 500;
rep->status_phrase = (char *) "Internal Server Error";
set_body_text(rep, "Internal Server Error\n");
return 500;
}
if (r == 0) {
break;
}
total += (size_t) r;
}
rep->body_length = total;
if (close(fd) != 0) {
perror("error closing file");
}
rep->status = 200;
rep->status_phrase = (char *) "OK";
return 0;
}
int exec_put(http_request_t *req, http_response_t *rep) {
// map URI "/foo" -> "foo" in current directory
const char *path = (req->uri[0] == '/') ? (req->uri + 1) : req->uri;
// checking if the file already exists
int existed = (access(path, F_OK) == 0);
// opening file, creating one if it doesn't exist and overwriting if it does
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0) {
if (errno == EACCES) { // permission denied
rep->status = 403;
rep->status_phrase = (char *) "Forbidden";
set_body_text(rep, "Forbidden\n");
return 403;
}
// unexpected error
rep->status = 500;
rep->status_phrase = (char *) "Internal Server Error";
set_body_text(rep, "Internal Server Error\n");
return 500;
}
// write to file (if there is a body)
if (req->body && req->body_length > 0) {
size_t total = 0;
while (total < req->body_length) {
ssize_t w = write(fd, req->body + total, req->body_length - total);
if (w < 0) {
close(fd);
rep->status = 500;
rep->status_phrase = (char *) "Internal Server Error";
set_body_text(rep, "Internal Server Error\n");
return 500;
}
if (w == 0) {
break;
}
total += (size_t) w;
}
}
close(fd);
// returning proper code based on existence or not
if (existed) {
rep->status = 200;
rep->status_phrase = (char *) "OK";
set_body_text(rep, "OK\n");
return 200;
} else {
rep->status = 201;
rep->status_phrase = (char *) "Created";
set_body_text(rep, "Created\n");
return 201;
}
}
// response ::= status-line header-field-list empty-line message-body
// status-line ::= HTTP/1.1␣status-code␣status-phrase\r\n
void send_response(int client_fd, http_response_t *rep) {
// --- decide body pointer + length ---
const uint8_t *body_ptr = NULL;
size_t body_len = 0;
if (rep->body != NULL && rep->body_length > 0) {
body_ptr = rep->body;
body_len = rep->body_length;
} else {
body_ptr = (const uint8_t *) "";
body_len = 0;
}
const char *phrase = rep->status_phrase ? rep->status_phrase : "";
// --- build header block ---
char header[512];
int header_len = snprintf(header, sizeof(header),
"HTTP/1.1 %d %s\r\n"
"Content-Length: %zu\r\n"
"\r\n",
rep->status, phrase, body_len);
if (header_len < 0) {
// formatting error, best-effort minimal 500
const char *fallback = "HTTP/1.1 500 Internal Server Error\r\n"
"Content-Length: 0\r\n"
"\r\n";
(void) write(client_fd, fallback, strlen(fallback));
return;
}
if (header_len > (int) sizeof(header)) {
header_len = (int) sizeof(header);
}
// --- write header (loop to handle partial writes) ---
size_t total = 0;
while (total < (size_t) header_len) {
ssize_t n = write(client_fd, header + total, header_len - (int) total);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return; // can't do much on error
}
if (n == 0) {
break;
}
total += (size_t) n;
}
// --- write body ---
total = 0;
while (total < body_len) {
ssize_t n = write(client_fd, body_ptr + total, body_len - total);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return;
}
if (n == 0) {
break;
}
total += (size_t) n;
}
}
void log_request(http_request_t *req, http_response_t *rep) {
fprintf(stderr, "%s,%s,%d,%d\n", req->method, req->uri, rep->status, req->request_id);
}
int main(int argc, char **argv) {
int workers = 1; // default
int port;
// Expect either: ./httpserver <port>
// or: ./httpserver -p <workers> <port>
if (argc != 2 && !(argc == 4 && strcmp(argv[1], "-p") == 0)) {
fprintf(stderr, "Invalid Port\n");
return 1;
}
if (argc == 4) {
workers = atoi(argv[2]);
if (workers <= 0)
workers = 1;
port = atoi(argv[3]);
} else {
port = atoi(argv[1]);
}
if (port < 1 || port > 65535) {
fprintf(stderr, "Invalid Port\n");
return 1;
}
int server_fd = create_socket(port);
if (server_fd < 0) {
fprintf(stderr, "Invalid Port\n");
return 1;
}
job_queue = queue_new(2048);
if (!job_queue) {
fprintf(stderr, "Internal Error\n");
close(server_fd);
return 1;
}
pthread_t *thread_worker = malloc(sizeof(pthread_t) * workers);
if (!thread_worker) {
fprintf(stderr, "Internal Error\n");
close(server_fd);
queue_delete(job_queue);
return 1;
}
for (int w = 0; w < workers; w++) {
pthread_create(&thread_worker[w], NULL, worker, NULL);
}
// main loop
while (1) {
int client_fd = accept_connection(server_fd);
if (client_fd < 0) {
// accept failed; keep trying
continue;
}
enqueue(client_fd);
}
// unreachable in normal runs, but here for completeness
close(server_fd);
queue_delete(job_queue);
free(thread_worker);
return 0;
}