-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_parser.c
More file actions
820 lines (654 loc) · 21 KB
/
command_parser.c
File metadata and controls
820 lines (654 loc) · 21 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
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
#include "command_parser.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifndef PATH_MAX
#define PATH_MAX MAX_PATH
#endif
#ifdef _WIN32
#include <windows.h>
#elif __unix__
#include <linux/limits.h>
#endif
#ifndef PATH_MAX
#define PATH_MAX MAX_PATH
#endif
#ifndef strtok_r
/*-
* Copyright (c) 1998 Softweyr LLC. All rights reserved.
*
* strtok_r, from Berkeley strtok
* Oct 13, 1998 by Wes Peters <wes@softweyr.com>
*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notices, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notices, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY SOFTWEYR LLC, THE REGENTS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOFTWEYR LLC, THE
* REGENTS, OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define _POSIX_SOURCE 1
/*
* strtok_r documentation:
* http://pubs.opengroup.org/onlinepubs/009695399/functions/strtok.html
*
* Implementation:
* http://svnweb.freebsd.org/base/head/lib/libc/string/strtok.c?view=co
*
* strtok_r cannot completely be implemented by strtok because of the internal state.
* It breaks when used on 2 strings where they are scanned A, B then A, B.
* Thread-safety is not the issue.
*
* Sample strtok implemenatation, note the internal state:
* char *strtok(char *s, const char *d) { static char *t; return strtok_r(s,d,t); }
*
*/
char *
strtok_r(char * __restrict s, const char * __restrict delim, char ** __restrict last)
{
char *spanp, *tok;
int c, sc;
if (s == NULL && (s = *last) == NULL)
return (NULL);
/*
* Skip (span) leading delimiters (s += strspn(s, delim), sort of).
*/
cont:
c = *s++;
for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
if (c == sc)
goto cont;
}
if (c == 0) { /* no non-delimiter characters */
*last = NULL;
return (NULL);
}
tok = s - 1;
/*
* Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
* Note that delim must have one NUL; we stop if we see that, too.
*/
for (;;) {
c = *s++;
spanp = (char *)delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = NULL;
else
s[-1] = '\0';
*last = s;
return (tok);
}
} while (sc != 0);
}
/* NOTREACHED */
}
#endif
#define MAX_BUFF_LEN 8000
int is_options_error (options opt) {
if (opt.commands == NULL) return 1;
return 0;
}
/**
*
* @param command Command String
* @param opt Commands data struct
* @return NULL if command isn't contained inside options,
* otherwise a pointer to a string containing the command value.
*/
char* get_command_value (char command[], options opt) {
if (opt.commands == NULL) return NULL;
for (int i = 0; i < opt.comm_len; i++) {
if (strcmp(opt.commands[i].name, command) == 0) {
return opt.commands[i].value;
}
}
return NULL;
}
int contains (const char name[MAX_OPTION_LEN],const char value[MAX_OPTION_LEN], options opt) {
for (int i = 0; i < opt.comm_len; i++ ) {
if (strcmp(opt.commands[i].name, name) == 0
&& strcmp(opt.commands[i].value , value) == 0) {
return 1;
}
}
return 0;
}
void free_options (options opt) {
free(opt.commands);
}
/**
*
* @param src on form: Basic am9lYjp4eDEyMw==
* @param res Struct: Username, Password
*/
authorization parse_authorization (const char * src) {
char buff[strlen(src)];
strcpy(buff,src);
authorization auth;
auth.free_pointer = NULL;
char * pointer;
char * token = NULL;
if ( ((token = strtok_r(buff, " ", &pointer)) == NULL)
|| ((token = strtok_r(NULL, " ", &pointer)) == NULL)) {
return auth;
}
unsigned char * decode = b64_decode(token, strlen(token));
if (decode == NULL) return auth;
pointer = NULL;
if ( ((token = strtok_r(decode, ":", &pointer)) == NULL)) {
free(decode);
return auth;
}
auth.name = token;
if ( ((token = strtok_r(NULL, ":", &pointer)) == NULL)) {
free(decode);
return auth;
}
auth.password = token;
auth.free_pointer = decode;
return auth;
}
/**
* @param argc
* @param argv
* @param command_list List of Archetypes used to parse the parameters.
* @param len_comm Length of command_list
* @return options struct, after use it is required to free options.commands.
*/
options options_parse (int argc, char *argv[], command_arc command_list[], int len_comm) {
int pos = 0;
int len = 6;
options option;
command* comm = calloc(sizeof(command), len);
if (comm == NULL) {
fprintf(stderr, "Malloc failed during options parsing\n");
exit(EXIT_FAILURE);
}
for (int i = 1; i < argc ; i++) {
for (int j = 0; j < len_comm; j++) {
if (strcmp(argv[i], command_list[j].name ) == 0) {
if (pos >= len) {
len += REALLOC_INC_SIZE;
comm = (command*) realloc(comm, sizeof(command) * len);
if (comm == NULL) {
fprintf(stderr, "Realloc failed in options_parse\n");
exit(EXIT_FAILURE);
}
}
if (strlen(argv[i]) > MAX_OPTION_LEN) {
fprintf(stderr, "Command %s exceeds the maximum command length\n", argv[i]);
exit(EXIT_FAILURE);
}
strcpy(comm[pos].name,argv[i]);
if ( strcmp(command_list[j].type, "null") == 0 ) {
command c ;
strcpy(comm[pos].value,"NOT VALUE");
pos++;
break;
}
// Passo all'indice dell'input
if (++i >= argc) {
fprintf(stderr, "Input for command %s not passed\n", argv[i-1]);
exit(EXIT_FAILURE);
}
// Controllo che l'input non superi la lunghezza massima
if (strlen(argv[i]) > MAX_OPTION_LEN) {
fprintf(stderr, "Command input %s exceeds the maximum command length\n", argv[i]);
exit(EXIT_FAILURE);
}
if ( strcmp(command_list[j].type, "int") == 0 ) {
sprintf( comm[pos].value,"%d",atoi(argv[i]));
pos++;
break;
}
if ( strcmp(command_list[j].type, "float") == 0 ) {
sprintf( comm[pos].value,"%f",atof(argv[i]));
pos++;
break;
}
if ( strcmp(command_list[j].type, "str") == 0 ) {
strcpy(comm[pos].value, argv[i]);
pos++;
break;
}
}
}
}
option.comm_len = pos;
option.commands = comm;
return option;
}
command extract_command(char *string) {
/**
* Receives one string whose format is "field=value" and
* extracts information from it.
* @return a command struct containing the extracted info.
*/
char delimiter = '=';
char *ptr = strchr(string, delimiter);
command comm;
if (ptr != NULL) {
//int index = ptr - string;
*(ptr) = '\0';
if (strlen(string) > MAX_OPTION_LEN || strlen(ptr) > MAX_OPTION_LEN) {
fprintf(stderr, "Command %s exceeds the maximum command length\n", string);
exit(EXIT_FAILURE);
}
strcpy(comm.name,string);
strcpy(comm.value,ptr+1);
return comm;
}
comm.name[0] = '\0';
comm.value[0] = '\0';
fprintf(stderr, "Extraction failed.\n");
return comm;
}
options parse_file(char *name, command_arc * cmd_arc, int arc_len) {
/**
* Parses a file following the format "Name=Val\n".
*/
options ret;
ret.commands = NULL;
FILE *fname = fopen(name, "rb");
if (fname == NULL) {
fprintf(stderr, "Unable to open file %s\n", name);
return ret;
//exit(EXIT_FAILURE);
}
fseek(fname, 0, SEEK_END);
long fsize = ftell(fname);
fseek(fname, 0, SEEK_SET);
char buff[fsize + 2];
if(fread(buff, 1, fsize, fname) < fsize) {
fprintf(stderr, "Unable to read from %s\n", name);
return ret;
}
fclose(fname);
buff[fsize] = '\0';
char * pointer = NULL;
int len = 20;
command* comm = calloc(sizeof(command), len);
if (comm == NULL) {
fprintf(stderr, "Malloc failed in parse_file\n");
return ret;
}
char * p = buff;
char * lines;
int k = 0;
while ((lines = strtok_r(p, "\r\n", &pointer)) != NULL) {
fflush(stdout);
p = NULL;
command cmd = extract_command(lines);
if (strlen(cmd.name) == 0 || strlen(cmd.value) == 0) {
free(comm);
fprintf(stderr, "Config file format error\n");
return ret;
}
if (k >= len) {
len+= REALLOC_INC_SIZE;
command * app;
app = (command*) realloc(comm, sizeof(command) * len);
if (app == NULL) {
free(comm);
fprintf(stderr,"Realloc Failed\n");
return ret;
}
comm = app;
}
if (cmd_arc == NULL){
strcpy(comm[k].value, cmd.value);
strcpy(comm[k].name, cmd.name);
k++;
continue;
}
for (int j = 0; j < arc_len; j++) {
if (strcmp(cmd_arc[j].name, cmd.name) == 0) {
strcpy(comm[k].name, cmd.name);
if (strcmp(cmd_arc[j].type, "null") == 0) {
strcpy(comm[k].value, "NOT VALUE");
break;
}
if (strcmp(cmd_arc[j].type, "int") == 0) {
sprintf(comm[k].value, "%d", atoi(cmd.value));
break;
}
if (strcmp(cmd_arc[j].type, "float") == 0) {
sprintf(comm[k].value, "%f", atof(cmd.value));
break;
}
if (strcmp(cmd_arc[j].type, "str") == 0) {
strcpy(comm[k].value, cmd.value);
break;
}
}
}
k++;
}
ret.comm_len = k;
ret.commands = comm;
return ret;
}
http_header http_attribute_parser (http_header http_h, char* data_attr) {
char attr_separator[] = ":";
char line_end[] = "\r\n";
char * in_pointer = NULL;
char * token = NULL;
char * sub_token = NULL;
char * attr_value = NULL;
while ((token = strtok_r(NULL, line_end, &data_attr )) != NULL) {
in_pointer = NULL;
sub_token = strtok_r(token, attr_separator, &in_pointer);
attr_value = strtok_r(NULL, attr_separator, &in_pointer);
if (strcmp(sub_token,"Authorization") == 0 && attr_value != NULL) {
http_h.attribute.authorization = attr_value;
}
if (strcmp(sub_token,"User-Agent") == 0 && attr_value != NULL) {
http_h.attribute.user_agent = attr_value;
}
if (strcmp(sub_token,"Content-Length") == 0 && attr_value != NULL) {
http_h.attribute.content_length = atoi(attr_value);
}
if (strcmp(sub_token,"Content-Type") == 0 && attr_value != NULL) {
http_h.attribute.content_type = attr_value;
}
if (strcmp(sub_token,"Connection") == 0 && attr_value != NULL) {
http_h.attribute.connection = attr_value;
}
}
return http_h;
}
http_header parse_http_header_response(const char *data, int data_len) {
char line_end[] = "\r\n";
char header_end[] = "\r\n\r\n";
char element_separator[] = " ";
http_header http_h = {0} ;
http_h.is_request = 0;
if (data_len > MAX_BUFF_LEN) {
http_h.is_request = -1;
return http_h;
}
// Copy of data
char * data_copy = malloc(data_len+1);
if (data_copy == NULL) {
http_h.is_request = -1;
return http_h;
}
http_h.pointer_to_free = data_copy;
memcpy(data_copy, data, data_len);
data_copy[data_len] = '\0';
char * token;
char * sub_token;
char * in_pointer = NULL;
char * ext_pointer = NULL;
// Take first line
token = strtok_r(data_copy, line_end, &ext_pointer);
if (token == NULL
|| ((sub_token = strtok_r(token, element_separator, &in_pointer)) == NULL)
|| (strcmp("HTTP/1.1", sub_token) != 0 && strcmp("HTTP/1.0", sub_token) != 0) ) {
http_h.is_request = -1;
free(data_copy);
return http_h;
}
http_h.protocol_type = sub_token;
if ( ((sub_token = strtok_r(NULL, element_separator, &in_pointer)) == NULL)
|| (http_h.code_response = atoi(sub_token)) == 0) {
http_h.is_request = -1;
free(data_copy);
return http_h;
}
http_h = http_attribute_parser(http_h, ext_pointer);
return http_h;
}
http_header parse_http_header_request (const char* data, int data_len) {
char line_end[] = "\r\n";
char header_end[] = "\r\n\r\n";
char element_separator[] = " ";
http_header http_h = {0};
http_h.is_request = 1;
if (data_len > MAX_BUFF_LEN) {
http_h.is_request = -1;
return http_h;
}
// Copy of data
char * data_copy = malloc(data_len+1);
if (data_copy == NULL) {
http_h.is_request = -1;
return http_h;
}
http_h.pointer_to_free = data_copy;
memcpy(data_copy, data, data_len);
data_copy[data_len] = '\0';
char * token;
char * sub_token;
char * in_pointer = NULL;
char * ext_pointer = NULL;
// Take first line
token = strtok_r(data_copy, line_end, &ext_pointer);
if (token == NULL
|| ((sub_token = strtok_r(token, element_separator, &in_pointer)) == NULL)
|| (strcmp(sub_token,"GET") != 0 && strcmp(sub_token,"PUT") != 0) ) {
http_h.is_request = -1;
free(data_copy);
return http_h;
}
http_h.type_req = sub_token;
if ((sub_token = strtok_r(NULL, element_separator, &in_pointer)) == NULL) {
http_h.is_request = -1;
free(data_copy);
return http_h;
}
http_h.url = sub_token;
if ((sub_token = strtok_r(NULL, element_separator, &in_pointer)) == NULL) {
http_h.is_request = -1;
free(data_copy);
return http_h;
}
http_h.protocol_type = sub_token;
if (strcmp("HTTP/1.1", http_h.protocol_type) != 0 && strcmp("HTTP/1.0", http_h.protocol_type) != 0) {
http_h.is_request = -1;
free(data_copy);
return http_h;
}
http_h = http_attribute_parser(http_h, ext_pointer);
return http_h;
}
char *code_to_message(int code) {
switch (code){
case 100:
return "Continue";
case 200:
return "OK";
case 201:
return "Created";
case 202:
return "Accepted";
case 204:
return "No Content";
case 205:
return "Reset Content";
case 206:
return "Partial Content";
case 302:
return "Found";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 423:
return "Locked";
case 431:
return "Request Header Fields Too Large";
case 500:
return "Internal Server Error";
case 501:
return "Not Implemented";
}
}
char *create_http_response(int response_code, unsigned long content_len, char * content_type, char *filename, char *location) {
const unsigned int MAX_CONTENT_LEN = (52 + 20 + MAX_HTTP_FIELD_LEN);
if ( (content_type != NULL && strlen(content_type) > PATH_MAX)
|| (location != NULL && strlen(location) > MAX_HTTP_FIELD_LEN)) {
return NULL;
}
int len_fn = filename == NULL ? 0 : strlen(filename);
const int resp_len = MAX_CONTENT_LEN + PATH_MAX + 200 + len_fn ;
char *response = calloc(resp_len, 1);
if (response == NULL) return NULL;
char *content = NULL;
if (content_len != -1 && content_type != NULL) {
content = malloc(MAX_CONTENT_LEN);
if (content == NULL) {
free(response);
return NULL;
}
int err = snprintf(content, MAX_CONTENT_LEN, "Accept-Ranges: bytes\r\n"
"Connection: keep-alive\r\n"
"Content-Length: %ld\r\n"
"Content Type: %s\r\n",
content_len, content_type);
if (err == -1) {
free(content);
free(response);
return NULL;
}
}
char *file = NULL;
if (filename != NULL) {
file = malloc(strlen(filename)+50);
if (file == NULL) {
free(content);
free(response);
return NULL;
}
int err = snprintf(file, strlen(filename)+50, "Content-Disposition: attachment; filename=\"%s\"\r\n", filename);
if (err == -1) {
free(content);
free(response);
free(file);
return NULL;
}
}
char *loc = NULL;
if (location != NULL) {
loc = malloc(PATH_MAX + 13);
if (loc == NULL) {
free(content);
free(response);
free(file);
return NULL;
}
int err = snprintf(loc, PATH_MAX + 13, "Location: %s\r\n", location);
if (err == -1) {
free(content);
free(response);
free(file);
free(loc);
return NULL;
}
}
int len = snprintf(response, resp_len, "HTTP/1.0 %d %s\r\n"
"%s%s%s"
"\r\n"
, response_code, code_to_message(response_code), content == NULL ? "" : content, loc == NULL ? "" : loc, file == NULL ? "" : file);
if (len == -1) {
free(file);
free(content);
free(loc);
free(response);
return NULL;
}
free(file);
free(content);
free(loc);
return response;
}
void free_http_header(http_header http_h) {
free(http_h.pointer_to_free);
}
int startsWith(const char *pre, const char *str)
{
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? 0 : strncmp(pre, str, lenpre) == 0;
}
struct operation_command parser_operation (char * url) {
struct operation_command out;
out.args = NULL;
out.comm = NULL;
if (!startsWith("/command/", url)) return out;
char * com = malloc(strlen(url) - 8);
if (com == NULL) {
out.comm = NULL;
out.args = NULL;
return out;
}
strcpy(com, url + 9);
char * mem_point = NULL;
if (*com == '?') {
out.comm = NULL;
out.args = NULL;
free(com);
return out;
}
char * token = strtok_r(com,"?", &mem_point);
if (token == NULL) {
out.args = NULL;
out.comm = com;
if (strlen(com) == 0) {
out.comm = NULL;
free(com);
}
return out;
}
if (strlen(token) == 0) {
out.comm = NULL;
out.args = NULL;
free(com);
return out;
}
out.comm = token;
token = strtok_r(NULL, "?", &mem_point);
out.args = token;
while ((token = strtok_r(NULL, "?", &mem_point)) != NULL) {
*(token-1) = ' ';
}
return out;
}
void free_operation_command(struct operation_command op) {
free(op.comm);
}
char * get_file_name (char * path) {
int path_len = strlen(path);
for (int i = path_len-1; i >= 0 ; i--) {
if (path[i] == '/') {
return path + (i + 1);
}
}
return NULL;
}