-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
1333 lines (1178 loc) · 31 KB
/
server.c
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// server.c
//
// Computer Science 50
// Problem Set 6
//
// feature test macro requirements
#define _GNU_SOURCE
#define _XOPEN_SOURCE 700
#define _XOPEN_SOURCE_EXTENDED
// limits on an HTTP request's size, based on Apache's
// http://httpd.apache.org/docs/2.2/mod/core.html
#define LimitRequestFields 50
#define LimitRequestFieldSize 4094
#define LimitRequestLine 8190
// number of bytes for buffers
#define BYTES 512
// header files
#include <arpa/inet.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
// types
typedef char BYTE;
// prototypes
bool connected(void);
void error(unsigned short code);
void freedir(struct dirent** namelist, int n);
void handler(int signal);
char* htmlspecialchars(const char* s);
char* indexes(const char* path);
void interpret(const char* path, const char* query);
void list(const char* path);
bool load(FILE* file, BYTE** content, size_t* length);
const char* lookup(const char* path);
bool parse(const char* line, char* path, char* query);
const char* reason(unsigned short code);
void redirect(const char* uri);
bool request(char** message, size_t* length);
void respond(int code, const char* headers, const char* body, size_t length);
void start(short port, const char* path);
void stop(void);
void transfer(const char* path, const char* type);
char* urldecode(const char* s);
// server's root
char* root = NULL;
// file descriptor for sockets
int cfd = -1, sfd = -1;
// flag indicating whether control-c has been heard
bool signaled = false;
int main(int argc, char* argv[])
{
// a global variable defined in errno.h that's "set by system
// calls and some library functions [to a nonzero value]
// in the event of an error to indicate what went wrong"
errno = 0;
// default to port 8080
int port = 8080;
// usage
const char* usage = "Usage: server [-p port] /path/to/root";
// parse command-line arguments
int opt;
while ((opt = getopt(argc, argv, "hp:")) != -1)
{
switch (opt)
{
// -h
case 'h':
printf("%s\n", usage);
return 0;
// -p port
case 'p':
port = atoi(optarg);
break;
}
}
// ensure port is a non-negative short and path to server's root is specified
if (port < 0 || port > SHRT_MAX || argv[optind] == NULL || strlen(argv[optind]) == 0)
{
// announce usage
printf("%s\n", usage);
// return 2 just like bash's builtins
return 2;
}
// start server
start(port, argv[optind]);
// listen for SIGINT (aka control-c)
struct sigaction act;
act.sa_handler = handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGINT, &act, NULL);
// a message and its length
char* message = NULL;
size_t length = 0;
// path requested
char* path = NULL;
// accept connections one at a time
while (true)
{
// free last path, if any
if (path != NULL)
{
free(path);
path = NULL;
}
// free last message, if any
if (message != NULL)
{
free(message);
message = NULL;
}
length = 0;
// close last client's socket, if any
if (cfd != -1)
{
close(cfd);
cfd = -1;
}
// check for control-c
if (signaled)
{
stop();
}
// check whether client has connected
if (connected())
{
// check for request
if (request(&message, &length))
{
// extract message's request-line
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
const char* haystack = message;
const char* needle = strstr(haystack, "\r\n");
if (needle == NULL)
{
error(500);
continue;
}
char line[needle - haystack + 2 + 1];
strncpy(line, haystack, needle - haystack + 2);
line[needle - haystack + 2] = '\0';
// log request-line
printf("%s", line);
// parse request-line
char abs_path[LimitRequestLine + 1];
char query[LimitRequestLine + 1];
if (parse(line, abs_path, query))
{
// URL-decode absolute-path
char* p = urldecode(abs_path);
if (p == NULL)
{
error(500);
continue;
}
// resolve absolute-path to local path
path = malloc(strlen(root) + strlen(p) + 1);
if (path == NULL)
{
error(500);
continue;
}
strcpy(path, root);
strcat(path, p);
free(p);
// ensure path exists
if (access(path, F_OK) == -1)
{
error(404);
continue;
}
// if path to directory
struct stat sb;
if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode))
{
// redirect from absolute-path to absolute-path/
if (abs_path[strlen(abs_path) - 1] != '/')
{
char uri[strlen(abs_path) + 1 + 1];
strcpy(uri, abs_path);
strcat(uri, "/");
redirect(uri);
continue;
}
// use path/index.php or path/index.html, if present, instead of directory's path
char* index = indexes(path);
if (index != NULL)
{
free(path);
path = index;
}
// list contents of directory
else
{
list(path);
continue;
}
}
// look up MIME type for file at path
const char* type = lookup(path);
if (type == NULL)
{
error(501);
continue;
}
// interpret PHP script at path
if (strcasecmp("text/x-php", type) == 0)
{
interpret(path, query);
}
// transfer file at path
else
{
transfer(path, type);
}
}
}
}
}
}
/**
* Checks (without blocking) whether a client has connected to server.
* Returns true iff so.
*/
bool connected(void)
{
struct sockaddr_in cli_addr;
memset(&cli_addr, 0, sizeof(cli_addr));
socklen_t cli_len = sizeof(cli_addr);
cfd = accept(sfd, (struct sockaddr*) &cli_addr, &cli_len);
if (cfd == -1)
{
return false;
}
return true;
}
/**
* Responds to client with specified status code.
*/
void error(unsigned short code)
{
// determine code's reason-phrase
const char* phrase = reason(code);
if (phrase == NULL)
{
return;
}
// template for response's content
char* template = "<html><head><title>%i %s</title></head><body><h1>%i %s</h1></body></html>";
// render template
char body[(strlen(template) - 2 - ((int) log10(code) + 1) - 2 + strlen(phrase)) * 2 + 1];
int length = sprintf(body, template, code, phrase, code, phrase);
if (length < 0)
{
body[0] = '\0';
length = 0;
}
// respond with error
char* headers = "Content-Type: text/html\r\n";
respond(code, headers, body, length);
}
/**
* Frees memory allocated by scandir.
*/
void freedir(struct dirent** namelist, int n)
{
if (namelist != NULL)
{
for (int i = 0; i < n; i++)
{
free(namelist[i]);
}
free(namelist);
}
}
/**
* Handles signals.
*/
void handler(int signal)
{
// control-c
if (signal == SIGINT)
{
signaled = true;
}
}
/**
* Escapes string for HTML. Returns dynamically allocated memory for escaped
* string that must be deallocated by caller.
*/
char* htmlspecialchars(const char* s)
{
// ensure s is not NULL
if (s == NULL)
{
return NULL;
}
// allocate enough space for an unescaped copy of s
char* t = malloc(strlen(s) + 1);
if (t == NULL)
{
return NULL;
}
t[0] = '\0';
// iterate over characters in s, escaping as needed
for (int i = 0, old = strlen(s), new = old; i < old; i++)
{
// escape &
if (s[i] == '&')
{
const char* entity = "&";
new += strlen(entity);
t = realloc(t, new);
if (t == NULL)
{
return NULL;
}
strcat(t, entity);
}
// escape "
else if (s[i] == '"')
{
const char* entity = """;
new += strlen(entity);
t = realloc(t, new);
if (t == NULL)
{
return NULL;
}
strcat(t, entity);
}
// escape '
else if (s[i] == '\'')
{
const char* entity = "'";
new += strlen(entity);
t = realloc(t, new);
if (t == NULL)
{
return NULL;
}
strcat(t, entity);
}
// escape <
else if (s[i] == '<')
{
const char* entity = "<";
new += strlen(entity);
t = realloc(t, new);
if (t == NULL)
{
return NULL;
}
strcat(t, entity);
}
// escape >
else if (s[i] == '>')
{
const char* entity = ">";
new += strlen(entity);
t = realloc(t, new);
if (t == NULL)
{
return NULL;
}
strcat(t, entity);
}
// don't escape
else
{
strncat(t, s + i, 1);
}
}
// escaped string
return t;
}
/**
* Checks, in order, whether index.php or index.html exists inside of path.
* Returns path to first match if so, else NULL.
*/
char* indexes(const char* path)
{
int length = strlen(path);
char* index1 = "index.html";
char* index2 = "index.php";
// allocate some memory for "index.html"
char* temp = malloc(length + 11); // +11 for "index.html\0"
if(temp == NULL)
{
return NULL;
}
// make a path/to/directory/index.html
for(int i = 0 ; i < length; i++)
{
temp[i] = path[i];
}
int n = length;
for(int i = 0; i < 10; i++)
{
temp[n] = index1[i];
n++;
}
temp[length+10] = '\0';
// allocate some memory for "index.php"
char* temp1 = malloc(length + 10); // +11 for index.php\0
if(temp1 == NULL)
{
return NULL;
}
// make a path/to/directory/index.php
for(int i = 0 ; i < length; i++)
{
temp1[i] = path[i];
}
int m = length;
for(int i = 0; i < 10; i++)
{
temp1[m] = index2[i];
m++;
}
// check if path/to/directory/index.html exists
if (access(temp, F_OK) != -1)
{
return temp;
}
// check if path/to/directory/index.php exists
else if (access(temp1, F_OK) != -1)
{
return temp1;
}
else
{
return NULL;
}
}
/**
* Interprets PHP file at path using query string.
*/
void interpret(const char* path, const char* query)
{
// ensure path is readable
if (access(path, R_OK) == -1)
{
error(403);
return;
}
// open pipe to PHP interpreter
char* format = "QUERY_STRING=\"%s\" REDIRECT_STATUS=200 SCRIPT_FILENAME=\"%s\" php-cgi";
char command[strlen(format) + (strlen(path) - 2) + (strlen(query) - 2) + 1];
if (sprintf(command, format, query, path) < 0)
{
error(500);
return;
}
FILE* file = popen(command, "r");
if (file == NULL)
{
error(500);
return;
}
// load interpreter's content
char* content;
size_t length;
if (load(file, &content, &length) == false)
{
error(500);
return;
}
// close pipe
pclose(file);
// subtract php-cgi's headers from content's length to get body's length
char* haystack = content;
char* needle = strstr(haystack, "\r\n\r\n");
if (needle == NULL)
{
free(content);
error(500);
return;
}
// extract headers
char headers[needle + 2 - haystack + 1];
strncpy(headers, content, needle + 2 - haystack);
headers[needle + 2 - haystack] = '\0';
// respond with interpreter's content
respond(200, headers, needle + 4, length - (needle - haystack + 4));
// free interpreter's content
free(content);
}
/**
* Responds to client with directory listing of path.
*/
void list(const char* path)
{
// ensure path is readable and executable
if (access(path, R_OK | X_OK) == -1)
{
error(403);
return;
}
// open directory
DIR* dir = opendir(path);
if (dir == NULL)
{
return;
}
// buffer for list items
char* list = malloc(1);
list[0] = '\0';
// iterate over directory entries
struct dirent** namelist = NULL;
int n = scandir(path, &namelist, NULL, alphasort);
for (int i = 0; i < n; i++)
{
// omit . from list
if (strcmp(namelist[i]->d_name, ".") == 0)
{
continue;
}
// escape entry's name
char* name = htmlspecialchars(namelist[i]->d_name);
if (name == NULL)
{
free(list);
freedir(namelist, n);
error(500);
return;
}
// append list item to buffer
char* template = "<li><a href=\"%s\">%s</a></li>";
list = realloc(list, strlen(list) + strlen(template) - 2 + strlen(name) - 2 + strlen(name) + 1);
if (list == NULL)
{
free(name);
freedir(namelist, n);
error(500);
return;
}
if (sprintf(list + strlen(list), template, name, name) < 0)
{
free(name);
freedir(namelist, n);
free(list);
error(500);
return;
}
// free escaped name
free(name);
}
// free memory allocated by scandir
freedir(namelist, n);
// prepare response
const char* relative = path + strlen(root);
char* template = "<html><head><title>%s</title></head><body><h1>%s</h1><ul>%s</ul></body></html>";
char body[strlen(template) - 2 + strlen(relative) - 2 + strlen(relative) - 2 + strlen(list) + 1];
int length = sprintf(body, template, relative, relative, list);
if (length < 0)
{
free(list);
closedir(dir);
error(500);
return;
}
// free buffer
free(list);
// close directory
closedir(dir);
// respond with list
char* headers = "Content-Type: text/html\r\n";
respond(200, headers, body, length);
}
/**
* Loads a file into memory dynamically allocated on heap.
* Stores address thereof in *content and length thereof in *length.
*/
bool load(FILE* file, BYTE** content, size_t* length)
{
char* data;
// get filesize
fseek(file, 0, SEEK_END);
int size = ftell(file);
fseek(file, 0, SEEK_SET);
// if file is not php file
if(size > 0)
{
// allocate enough memory for the whole file and read it at once into allocated memory
data = malloc(size * (sizeof(char) + 1));
if(data == NULL)
{
return false;
}
fread(data, 1, size, file);
// store length
*length = size;
}
// if file is php file
else
{
// allocate memory for 2 characters
data = malloc(2 * sizeof(char));
if(data == NULL)
{
return false;
}
// read character by character and reallocate more memory until EOF
int i = 1;
for (int c = fgetc(file); c != EOF; c = fgetc(file))
{
data[i-1] = c;
data = realloc(data, sizeof(char) * i + 1);
i++;
}
// store length
*length = i;
}
// store content
*content = data;
return true;
}
/**
* Returns MIME type for supported extensions, else NULL.
*/
const char* lookup(const char* path)
{
// const char*'s for comparison
const char* html = ".html";
const char* css = ".css";
const char* gif = ".gif";
const char* ico = ".ico";
const char* jpg = ".jpg";
const char* php = ".php";
const char* png = ".png";
const char* js = ".js";
// copy of "path" string to be manipulated
int length = strlen(path);
char path1[length + 1];
strcpy(path1, path);
char* temp = (strstr(path, php));
if(temp != NULL)
{
return "text/x-php";
}
// truncate string to check for ".html"
char* temp1[6];
int a = 0;
for(int i = length-5; i < length; i++)
{
temp1[a] = &path1[i];
a++;
}
const char* end1 = *temp1;
if (strcasecmp(html, end1) == 0)
{
return "text/html";
}
// if it's not ".html", shorten again to check for ".###" extension
else
{
char* temp2[5];
int b = 0;
for(int i = 1; i < 6; i++)
{
temp2[b] = temp1[i];
b++;
}
const char* end2 = *temp2;
if (strcasecmp(css, end2) == 0)
{
return "text/css";
}
if (strcasecmp(gif, end2) == 0)
{
return "image/gif";
}
if (strcasecmp(ico, end2) == 0)
{
return "image/x-icon";
}
if (strcasecmp(jpg, end2) == 0)
{
return "image/jpeg";
}
if (strcasecmp(png, end2) == 0)
{
return "image/png";
}
// if nothing is already returned, shorten one more time and check for ".js"
else
{
char* temp3[4];
int c = 0;
for(int i = 1; i < 5; i++)
{
temp3[c] = temp2[i];
c++;
}
const char* end3 = *temp3;
if (strcasecmp(js, end3) == 0)
{
return "text/javascript";
}
// all possible extensions checked, if none found, return NULL
else
{
return NULL;
}
}
}
return NULL;
}
/**
* Parses a request-line, storing its absolute-path at abs_path
* and its query string at query, both of which are assumed
* to be at least of length LimitRequestLine + 1.
*/
bool parse(const char* line, char* abs_path, char* query)
{
// const char*'s for comparison space = 32 (ascii)
const char* methodConst = "GET";
const char* versionConst = " HTTP/1.1\r\n";
const char* queryConst = "?";
// copy line to line1 to be manipulated
int length = strlen(line);
char line1[length + 1];
strcpy(line1, line);
// temp1 substring for method
char temp1[4];
for(int i = 0; i < 3; i++)
{
temp1[i] = line1[i];
}
temp1[3] = '\0';
// check if method is GET
if((strcmp(temp1, methodConst) != 0) || line1[3] != 32)
{
error(405);
return false;
}
// temp2 substring for HTTP-version
int a = 32;
char* temp2 = strrchr(line1, a);
const char* version = temp2;
// check if HTTP-version is HTTP/1.1
if(strcmp(version, versionConst) != 0)
{
error(505);
return false;
}
// temp3 substring for RT (request-target)
char temp3[length - 15]; // [length - 15] because method + version = 15 characters
int aa = 0;
for(int i = 4; i < length - 11; i++)
{
temp3[aa] = line1[i];
aa++;
}
temp3[length-15] = '\0';
// check if RT begins with '/'
if(temp3[0] != '/')
{
error(501);
return false;
}
const char* rt = temp3;
// check if RT contains '"' character
if((strchr(temp3, '\"')) != NULL)
{
error(400);
return false;
}
// temp4 substring for query
char* temp4 = strstr(rt, queryConst);
// check if there is "?", store it at query
if(temp4 != NULL)
{
for(int i = 0; i < strlen(temp4); i++)
{
query[i] = temp4[i+1];
}
}
// if no "?", set query as '\0'
else
{
*query = '\0';
}
// absInt - for absolute-path length
int absInt;
// if query found, subtract it's length from RT length
if(temp4 != NULL)
{
absInt = length - 15 - strlen(temp4);
}
// if no query found, subtract 14 (method + version - 1 (for '\0'))
else
{
absInt = length - 14;
}
// temp5 substring for abs_path
char temp5[absInt];
for (int i = 0; i < absInt; i++)
{
temp5[i] = temp3[i];
}
temp5[absInt] = '\0';
// set abs_path, put '\0' to terminate
for(int i = 0; i < strlen(temp5); i++)
{
abs_path[i] = temp5[i];
}
abs_path[strlen(temp5)] = '\0';
// done!
return true;
}
/**
* Returns status code's reason phrase.
*
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
* https://tools.ietf.org/html/rfc2324
*/
const char* reason(unsigned short code)
{
switch (code)
{
case 200: return "OK";
case 301: return "Moved Permanently";
case 400: return "Bad Request";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 414: return "Request-URI Too Long";
case 418: return "I'm a teapot";
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 505: return "HTTP Version Not Supported";
default: return NULL;
}
}
/**
* Redirects client to uri.
*/
void redirect(const char* uri)
{
char* template = "Location: %s\r\n";
char headers[strlen(template) - 2 + strlen(uri) + 1];
if (sprintf(headers, template, uri) < 0)
{
error(500);
return;
}
respond(301, headers, NULL, 0);
}
/**
* Reads (without blocking) an HTTP request's headers into memory dynamically allocated on heap.
* Stores address thereof in *message and length thereof in *length.
*/
bool request(char** message, size_t* length)
{
// ensure socket is open
if (cfd == -1)
{
return false;
}
// initialize message and its length
*message = NULL;
*length = 0;
// read message
while (*length < LimitRequestLine + LimitRequestFields * LimitRequestFieldSize + 4)
{
// read from socket
BYTE buffer[BYTES];
ssize_t bytes = read(cfd, buffer, BYTES);
if (bytes < 0)
{
if (*message != NULL)