Skip to content
This repository
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 1128 lines (968 sloc) 32.534 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 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
/*
Onion HTTP server library
Copyright (C) 2010-2014 David Moreno Montero and othes

This library is free software; you can redistribute it and/or
modify it under the terms of, at your choice:
a. the Apache License Version 2.0.
b. the GNU General Public License as published by the
Free Software Foundation; either version 2.0 of the License,
or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of both libraries, if not see
<http://www.gnu.org/licenses/> and
<http://www.apache.org/licenses/LICENSE-2.0>.
*/

#include <string.h>
#include <stdlib.h>
#include <libgen.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>

#include "dict.h"
#include "request.h"
#include "types_internal.h"
#include "codecs.h"
#include "log.h"
#include "block.h"

/**
* @short Known token types. This is merged with onion_connection_status as return value at token readers.
* @private
*/
typedef enum{
STRING=1001, // I start on 1000, to prevent collission with error codes
KEY=1002,
LINE=1003,
NEW_LINE=1004,
URLENCODE=1005,
MULTIPART_BOUNDARY=1006,
MULTIPART_END=1007,
MULTIPART_NEXT=1008,
STRING_NEW_LINE=1009,
}onion_token_token;

/// @private
typedef struct onion_token_s{
char str[256*4*8];
off_t pos;

char *extra; // Only used when need some previous data, like at header value, i need the key
size_t extra_size;
}onion_token;

/// @private
typedef struct onion_buffer_s{
const char *data;
size_t size;
off_t pos;
}onion_buffer;

/**
* @short This struct is mapped at token->extra. The token, _start and data are maped to token->extra area too.
* @private
*
* This is a bit juggling with pointers, but needed to keep the deallocation simple, and the token object minimal in most cases.
*
* token->pos is the pointer to the free area and token->extra_size is the real size.
*/
typedef struct onion_multipart_buffer_s{
char *boundary; /// Pointer to where the boundary is stored
size_t size; /// Size of the boundary
off_t pos; /// Pos at the boundarycheck
off_t startpos; /// Where did the boundary started (\n\r vs \n)
char *data; /// When need a new buffered data (always from stream), get it from here. This advances as used.
char *name; /// point to a in data position
char *filename; /// point to a in data position
size_t file_total_size; /// Total size of all file read data
size_t post_total_size; /// Total size of post, to check limits
int fd; /// If file, the file descriptor.
}onion_multipart_buffer;

static void onion_request_parse_query_to_dict(onion_dict *dict, char *p);
static int onion_request_parse_query(onion_request *req);
static onion_connection_status prepare_POST(onion_request *req);
static onion_connection_status prepare_CONTENT_LENGTH(onion_request *req);
static onion_connection_status prepare_PUT(onion_request *req);

/// Reads a string until a non-string char. Returns an onion_token
int token_read_STRING(onion_token *token, onion_buffer *data){
if (data->pos>=data->size)
return OCS_NEED_MORE_DATA;

char c=data->data[data->pos++];
while (!isspace(c)){
token->str[token->pos++]=c;
if (data->pos>=data->size)
return OCS_NEED_MORE_DATA;
if (token->pos>=(sizeof(token->str)-1)){
char tmp[16];
strncpy(tmp, token->str, 16);
tmp[15]='\0';
ONION_ERROR("Token too long to parse it. Part read start as %s (%d bytes)",tmp,token->pos);
return OCS_INTERNAL_ERROR;
}
c=data->data[data->pos++];
}
int ret;
if (c=='\n')
ret=STRING_NEW_LINE;
else
ret=STRING;

token->str[token->pos]='\0';
token->pos=0;
//ONION_DEBUG0("Found STRING token %s",token->str);
return ret;
}

/**
* @short Reads a string until a delimiter is found. Returns an onion_token. Also detects an empty line.
*
* @returns error code | STRING | STRING_NEW_LINE | NEW_LINE
*
* STRING is a delimited string, string new line is that the string finished witha new line, new line is that I fuond only a new line char.
*/
///
int token_read_until(onion_token *token, onion_buffer *data, char delimiter){
if (data->pos>=data->size)
return OCS_NEED_MORE_DATA;

//ONION_DEBUG0("Read data %d bytes, at token pos %d",data->size-data->pos, token->pos);

char c=data->data[data->pos++];
while (c!=delimiter && c!='\n'){
if (c!='\r') // Just ignore it here
token->str[token->pos++]=c;
if (data->pos>=data->size){
return OCS_NEED_MORE_DATA;
}
if (token->pos>=(sizeof(token->str)-1)){
ONION_ERROR("Token too long to parse it. Part read is %s (%d bytes)",token->str,token->pos);
return OCS_INTERNAL_ERROR;
}
c=data->data[data->pos++];
}
int ret=STRING;
token->str[token->pos]='\0';
if (c!=delimiter){
if ( token->pos==0 && c=='\n' ){
ret=NEW_LINE;
}
else{ // only option left.
ret=STRING_NEW_LINE;
}
}
token->pos=0;

//ONION_DEBUG0("Found KEY token %s",token->str);
return ret;
}

/// Reads a key, that is a string ended with ':'.
int token_read_KEY(onion_token *token, onion_buffer *data){
int res=token_read_until(token, data, ':');
if (res==STRING)
return KEY;
if (res==STRING_NEW_LINE){
ONION_ERROR("When parsing header, found a non valid delimited string token: '%s'",token->str);
return OCS_INTERNAL_ERROR;
}
return res;
}

/// Reads a string until a '\n|\r\n' is found. Returns an onion_token.
int token_read_LINE(onion_token *token, onion_buffer *data){
if (data->pos>=data->size)
return OCS_NEED_MORE_DATA;

char c=data->data[data->pos++];
int ignore_to_end=0;
while (c!='\n'){
if (!ignore_to_end && (token->pos>=(sizeof(token->str)-1))){
ONION_WARNING("Token too long to parse it. Ignoring remaining. ");
#ifdef __DEBUG__
char tmp[16];
strncpy(tmp, token->str, 16);
tmp[15]='\0';
ONION_DEBUG("Long token starts with: %s...",tmp);
#endif
ignore_to_end=1;
}
if (!ignore_to_end)
token->str[token->pos++]=c;
if (data->pos>=data->size)
return OCS_NEED_MORE_DATA;

c=data->data[data->pos++];
}
if (token->str[token->pos-1]=='\r')
token->str[token->pos-1]='\0';
else
token->str[token->pos]='\0';
//token->pos=0;

//ONION_DEBUG0("Found LINE token %s",token->str);
return LINE;
}

/// Reads a string until a '\n|\r\n' is found. Returns an onion_token.
int token_read_URLENCODE(onion_token *token, onion_buffer *data){
int l=data->size-data->pos;
if (l > (token->extra_size-token->pos))
l=token->extra_size-token->pos;
//ONION_DEBUG0("Feed %d bytes",l);

memcpy(&token->extra[token->pos], &data->data[data->pos], l);
token->pos+=l;
data->size-=l;

if (token->extra_size==token->pos){
token->extra[token->pos]='\0';
return URLENCODE;
}
return OCS_NEED_MORE_DATA;
}

/// Reads as much as possible from the boundary.
int token_read_MULTIPART_BOUNDARY(onion_token *token, onion_buffer *data){
onion_multipart_buffer *multipart=(onion_multipart_buffer*)token->extra;
while (multipart->boundary[multipart->pos] && multipart->boundary[multipart->pos]==data->data[data->pos]){
multipart->pos++;
data->pos++;
if (data->pos>=data->size)
return OCS_NEED_MORE_DATA;
}
if (multipart->boundary[multipart->pos]){
ONION_ERROR("Expecting multipart boundary, but not here (pos %d) (%c!=%c)", multipart->pos, data->data[data->pos], multipart->boundary[multipart->pos]);
return OCS_INTERNAL_ERROR;
}
return MULTIPART_BOUNDARY;
}

/// Reads as much as possible from the boundary.
int token_read_MULTIPART_next(onion_token *token, onion_buffer *data){
//onion_multipart_buffer *multipart=(onion_multipart_buffer*)token->extra;
while (token->pos<2 && (data->size-data->pos)>0){
token->str[token->pos++]=data->data[data->pos++];
if (token->pos==1 && token->str[0]=='\n'){
token->pos=0;
return MULTIPART_NEXT;
}
}
//ONION_DEBUG("pos %d, %d %d (%c %c)",token->pos, token->str[0], token->str[1], token->str[0], token->str[1]);
if (token->pos==2){
token->pos=0;
if (token->str[0]=='-' && token->str[1]=='-')
return MULTIPART_END;
if (token->str[0]=='\r' && token->str[1]=='\n')
return MULTIPART_NEXT;
return OCS_INTERNAL_ERROR;
}

return OCS_NEED_MORE_DATA;
}

int token_read_NEW_LINE(onion_token *token, onion_buffer *data){
while (token->pos<2 && (data->size-data->pos)>0){
token->str[token->pos++]=data->data[data->pos++];
if (token->pos==1 && token->str[0]=='\n'){
token->pos=0;
return NEW_LINE;
}
}
//ONION_DEBUG("pos %d, %d %d (%c %c)",token->pos, token->str[0], token->str[1], token->str[0], token->str[1]);
int res=OCS_NEED_MORE_DATA;
if (token->pos==2){
token->pos=0;
if (token->str[0]=='\r' && token->str[1]=='\n')
res=NEW_LINE;
else
res=OCS_INTERNAL_ERROR;
}
token->pos=0;

return res;
}

static char token_peek_next_char(onion_buffer *data){
if (data->pos>=data->size)
return '\0'; // If not enought data, go to safe side.
return data->data[data->pos];
}

static onion_connection_status parse_POST_multipart_next(onion_request *req, onion_buffer *data);


/**
* @short Reads from the data to fulfill content-length data.
*/
static onion_connection_status parse_CONTENT_LENGTH(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int length=data->size-data->pos;
int exit=0;

if (length>=token->extra_size-token->pos){
exit=1;
length=token->extra_size-token->pos;
}

onion_block_add_data(req->data, &data->data[data->pos], length);
data->pos+=length;

if (exit)
return onion_request_process(req);

return OCS_NEED_MORE_DATA;
}

/**
* @short Reads from the data to fulfill content-length data.
*
* All data is writen a temporal file, which will be removed later.
*/
static onion_connection_status parse_PUT(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int length=data->size-data->pos;
int exit=0;

if (length>=token->extra_size-token->pos){
exit=1;
length=token->extra_size-token->pos;
}

//ONION_DEBUG0("Writing %d. %d / %d bytes", length, token->pos+length, token->extra_size);

int *fd=(int*)token->extra;
ssize_t w=write(*fd, &data->data[data->pos], length);
if (w<0){
ONION_ERROR("Could not write all data to temporal file.");
return OCS_INTERNAL_ERROR;
}
data->pos+=length;
token->pos+=length;

#if __DEBUG__
const char *filename=onion_block_data(req->data);
ONION_DEBUG0("Done with PUT. Created %s (%d bytes)", filename, token->pos);
#endif

if (exit){
close (*fd);
free(fd);
token->extra=NULL;
return onion_request_process(req);
}

return OCS_NEED_MORE_DATA;
}


/**
* Hard parser as I must set into the file as I read, until i found the boundary token (or start), try to parse, and if fail,
* write to the file.
*
* The boundary may be in two or N parts.
*/
static onion_connection_status parse_POST_multipart_file(onion_request *req, onion_buffer *data){
char tmp[1024]; /// Read 1024 bytes fo the read on this call, and write. If read less write as read.
int tmppos=0;
onion_token *token=req->parser_data;
onion_multipart_buffer *multipart=(onion_multipart_buffer*)token->extra;
const char *p=data->data+data->pos;
for (;data->pos<data->size;data->pos++){
//ONION_DEBUG("*p %d boundary %d (%s)",*p,multipart->boundary[multipart->pos],multipart->boundary);
if (multipart->pos==0){
if (*p=='\n') // \r is optional.
multipart->startpos=multipart->pos=1;
else
multipart->startpos=0;
}
if (*p==multipart->boundary[multipart->pos]){
multipart->pos++;
if (multipart->pos==multipart->size){
multipart->startpos=multipart->pos=0;
data->pos++; // Not sure why this is needed. FIXME.

int w=write(multipart->fd,tmp,tmppos);
if (w!=tmppos){
ONION_ERROR("Error writing multipart data to file. Check permissions on temp directory, and availabe disk.");
close(multipart->fd);
return OCS_INTERNAL_ERROR;
}

close(multipart->fd);
req->parser=parse_POST_multipart_next;
return OCS_NEED_MORE_DATA;
}
}
else{
if (multipart->file_total_size>req->connection.listen_point->server->max_file_size){
ONION_ERROR("Files on this post too big. Aborting.");
return OCS_INTERNAL_ERROR;
}
if (multipart->pos!=0){
multipart->file_total_size+=multipart->pos;
int r=multipart->pos-multipart->startpos;
//ONION_DEBUG0("Write %d bytes",r);
int w=write(multipart->fd,tmp,tmppos);
if (w!=tmppos){
ONION_ERROR("Error writing multipart data to file. Check permissions on temp directory, and availabe disk.");
close(multipart->fd);
return OCS_INTERNAL_ERROR;
}
tmppos=0;

w=write(multipart->fd, multipart->boundary+multipart->startpos, r);
if (w!=r){
ONION_ERROR("Error writing multipart data to file. Check permissions on temp directory, and availabe disk.");
close(multipart->fd);
return OCS_INTERNAL_ERROR;
}
multipart->startpos=multipart->pos=0;
data->pos--; // Ignore read charater, try again. May be start of boundary.
continue;
}
//ONION_DEBUG0("Write 1 byte");
tmp[tmppos++]=*p;
if (tmppos==sizeof(tmp)){
int w=write(multipart->fd,tmp,tmppos);
if (w!=tmppos){
ONION_ERROR("Error writing multipart data to file. Check permissions on temp directory, and availabe disk.");
close(multipart->fd);
return OCS_INTERNAL_ERROR;
}
tmppos=0;
}
}
multipart->file_total_size++;
p++;
}
int w=write(multipart->fd,tmp,tmppos);
if (w!=tmppos){
ONION_ERROR("Error writing multipart data to file. Check permissions on temp directory, and availabe disk.");
close(multipart->fd);
return OCS_INTERNAL_ERROR;
}
return OCS_NEED_MORE_DATA;
}

/**
* Hard parser as I must set into the file as I read, until i found the boundary token (or start), try to parse, and if fail,
* write to the file.
*
* The boundary may be in two or N parts.
*/
static onion_connection_status parse_POST_multipart_data(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
onion_multipart_buffer *multipart=(onion_multipart_buffer*)token->extra;
const char *p=data->data+data->pos;
char *d=&multipart->data[token->pos];

for (;data->pos<data->size;data->pos++){
if (multipart->pos==0 && *p=='\n') // \r is optional.
multipart->pos=1;
if (*p==multipart->boundary[multipart->pos]){ // Check boundary
multipart->pos++;
if (multipart->pos==multipart->size){
multipart->pos=0;
data->pos++; // Not sure why this is needed. FIXME.
if (token->pos>0 && *(d-1)=='\n'){
token->pos--;
d--;
}
if (token->pos>0 && *(d-1)=='\r')
d--;

*d='\0';
ONION_DEBUG0("Adding POST data '%s'",multipart->name);
onion_dict_add(req->POST, multipart->name, multipart->data, 0);
multipart->data=multipart->data+token->pos+1;
token->pos=0;
req->parser=parse_POST_multipart_next;
return OCS_NEED_MORE_DATA;
}
}
else{ // No boundary
if (multipart->pos!=0){// Maybe i was checking before... so I need to copy as much as I wrongly thought I got.
if (multipart->post_total_size<=multipart->pos){
ONION_ERROR("No space left for this post.");
return OCS_INTERNAL_ERROR;
}
multipart->post_total_size-=multipart->pos;
memcpy(d,p,multipart->pos);
d+=multipart->pos;
token->pos+=multipart->pos;
multipart->pos=0;
}
if (multipart->post_total_size<=0){
ONION_ERROR("No space left for this post.");
return OCS_INTERNAL_ERROR;
}
multipart->post_total_size--;
//ONION_DEBUG0("%d %d",multipart->post_total_size,token->extra_size - (int) (d-token->extra));
*d=*p;
d++;
token->pos++;
}
p++;
}
return OCS_NEED_MORE_DATA;
}

static onion_connection_status parse_POST_multipart_headers_key(onion_request *req, onion_buffer *data);

static onion_connection_status parse_POST_multipart_content_type(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_until(token, data,';');

if (res<=1000)
return res;

//ONION_DEBUG("Got content type %s",token->str);

onion_multipart_buffer *multipart=(onion_multipart_buffer*)token->extra;
const char *name;
name=strstr(token->str, "filename=");
if (name){
int l=strlen(token->str)-9;
if (l>multipart->post_total_size){
ONION_ERROR("Post buffer exhausted. content-Length wrong passed.");
return OCS_INTERNAL_ERROR;
}
multipart->filename=multipart->data;
memcpy(multipart->filename, name+9, l);
multipart->filename[l]=0;
multipart->data=multipart->data+l+1;
if (*multipart->filename=='"' && multipart->filename[l-2]=='"'){
multipart->filename[l-2]='\0';
multipart->filename++;
}
ONION_DEBUG0("Set filename '%s'",multipart->filename);
}
else{
name=strstr(token->str, "name=");
if (name){
int l=strlen(token->str)-5;
if (l>multipart->post_total_size){
ONION_ERROR("Post buffer exhausted. Content-Length had wrong size.");
return OCS_INTERNAL_ERROR;
}
multipart->name=multipart->data;
memcpy(multipart->name, name+5, l);
multipart->name[l]=0;
if (*multipart->name=='"' && multipart->name[l-2]=='"'){
l-=2;
multipart->name[l]='\0';
multipart->name++;
}
multipart->data=multipart->name+l+1;
ONION_DEBUG0("Set field name '%s'",multipart->name);
}
}


if (res==STRING_NEW_LINE){
req->parser=parse_POST_multipart_headers_key;
return OCS_NEED_MORE_DATA;
}
return OCS_NEED_MORE_DATA;
}

static onion_connection_status parse_POST_multipart_ignore_header(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_LINE(token, data);

if (res<=1000)
return res;
token->pos=0;

req->parser=parse_POST_multipart_headers_key;
return OCS_NEED_MORE_DATA;
}

static onion_connection_status parse_POST_multipart_headers_key(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_KEY(token, data);

if (res<=1000)
return res;

if (res==NEW_LINE){
if (!req->POST)
req->POST=onion_dict_new();
ONION_DEBUG("New line");
onion_multipart_buffer *multipart=(onion_multipart_buffer*)token->extra;
multipart->pos=0;

if (multipart->filename){
char filename[]="/tmp/onion-XXXXXX";
multipart->fd=mkstemp(filename);
if (multipart->fd<0)
ONION_ERROR("Could not create temporal file at %s.", filename);
if (!req->FILES)
req->FILES=onion_dict_new();
onion_dict_add(req->POST,multipart->name,multipart->filename, 0);
onion_dict_add(req->FILES,multipart->name, filename, OD_DUP_VALUE);
ONION_DEBUG0("Created temporal file %s",filename);

req->parser=parse_POST_multipart_file;
return parse_POST_multipart_file(req, data);
}
else{
req->parser=parse_POST_multipart_data;
return parse_POST_multipart_data(req, data);
}
}

// Only interested in one header
if (strcmp(token->str,"Content-Disposition")==0){
req->parser=parse_POST_multipart_content_type;
return parse_POST_multipart_content_type(req,data);
}

ONION_DEBUG("Not interested in header '%s'",token->str);
req->parser=parse_POST_multipart_ignore_header;
return parse_POST_multipart_ignore_header(req,data);
}

static onion_connection_status parse_POST_multipart_next(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_MULTIPART_next(token, data);

if (res<=1000)
return res;

//ONION_DEBUG("Found next token: %d",res);

if (res==MULTIPART_END)
return onion_request_process(req);

onion_multipart_buffer *multipart=(onion_multipart_buffer*)token->extra;
multipart->filename=NULL;
multipart->name=NULL;

req->parser=parse_POST_multipart_headers_key;
return parse_POST_multipart_headers_key(req, data);
}

static onion_connection_status parse_POST_multipart_start(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_MULTIPART_BOUNDARY(token, data);

if (res<=1000)
return res;

req->parser=parse_POST_multipart_next;
return parse_POST_multipart_next(req, data);
}

static onion_connection_status parse_POST_urlencode(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_URLENCODE(token, data);

if (res<=1000)
return res;

req->POST=onion_dict_new();
onion_request_parse_query_to_dict(req->POST, token->extra);

return onion_request_process(req);
}

static onion_connection_status parse_headers_KEY(onion_request *req, onion_buffer *data);
static onion_connection_status parse_headers_VALUE(onion_request *req, onion_buffer *data);

static onion_connection_status parse_headers_VALUE_skip_leading_whitespace(onion_request *req, onion_buffer *data){
while (data->pos<data->size){
char peek=data->data[data->pos++];
if (peek!='\t' && peek!=' '){
onion_token *token=req->parser_data;
if (peek=='\n')
return OCS_NEED_MORE_DATA;
token->str[token->pos++]=' ';
token->str[token->pos++]=peek;
req->parser=parse_headers_VALUE;
return parse_headers_VALUE(req, data);
}
}
return OCS_NEED_MORE_DATA;
}

static onion_connection_status parse_headers_VALUE_multiline_if_space(onion_request *req, onion_buffer *data){
char peek=token_peek_next_char(data);
ONION_DEBUG0("Multiline if space, peek %d",peek);
if (peek==0){
req->parser=parse_headers_VALUE_multiline_if_space;
return OCS_NEED_MORE_DATA;
}
if (peek==' ' || peek=='\t'){
req->parser=parse_headers_VALUE_skip_leading_whitespace;
return parse_headers_VALUE_skip_leading_whitespace(req, data);
}
onion_token *token=req->parser_data;
token->pos=0;

char *p=token->str; // skips leading spaces
while (isspace(*p)) p++;

ONION_DEBUG0("Adding header %s : %s",token->extra,p);
onion_dict_add(req->headers,token->extra,p, OD_DUP_VALUE|OD_FREE_KEY);
token->extra=NULL;

req->parser=parse_headers_KEY;
return OCS_NEED_MORE_DATA; // Get back recursion if any, to prevent too long callstack (on long headers) and stack overflow.
}

static onion_connection_status parse_headers_VALUE(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_LINE(token, data);

if (res<=1000)
return res;

return parse_headers_VALUE_multiline_if_space(req, data);
}


static onion_connection_status parse_headers_KEY(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;

int res=token_read_KEY(token, data);

if (res<=1000)
return res;

  ONION_DEBUG0("Got %d at KEY",res);
  
if ( res == NEW_LINE ){
if ((req->flags&OR_METHODS)==OR_POST){
const char *content_type=onion_request_get_header(req, "Content-Type");
if (!content_type || (strstr(content_type,"application/x-www-form-urlencoded") || strstr(content_type, "boundary")))
return prepare_POST(req);
}
if ((req->flags&OR_METHODS)==OR_PUT)
return prepare_PUT(req);
if (onion_request_get_header(req, "Content-Length")){ // Soem length, not POST, get data.
int n=atoi(onion_request_get_header(req, "Content-Length"));
if (n>0)
return prepare_CONTENT_LENGTH(req);
}

return onion_request_process(req);
}

token->extra=strdup(token->str);

req->parser=parse_headers_VALUE;
return parse_headers_VALUE(req, data);
}


static onion_connection_status parse_headers_KEY_skip_NL(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int r=token_read_NEW_LINE(token,data);

if (r<=1000)
return r;

req->parser=parse_headers_KEY;
return parse_headers_KEY(req, data);
}

static onion_connection_status parse_headers_VERSION(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_STRING(token, data);

if (res<=1000)
return res;

if (strcmp(token->str,"HTTP/1.1")==0)
req->flags|=OR_HTTP11;

if (!req->GET)
req->GET=onion_dict_new();

if (res==STRING){
req->parser=parse_headers_KEY_skip_NL;
return parse_headers_KEY_skip_NL(req, data);
}
else{ // STRING_NEW_LINE, only when \n as STRING separator, not \r\n.
req->parser=parse_headers_KEY;
return parse_headers_KEY(req, data);
}
}


static onion_connection_status parse_headers_URL(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_STRING(token, data);

if (res<=1000)
return res;

req->fullpath=strdup(token->str);
onion_request_parse_query(req);
ONION_DEBUG0("URL path is %s", req->fullpath);

  if (res==STRING_NEW_LINE){ // Old HTTP/0? or lazy user, dont set the HTTP version, straigth new line.
    req->parser=parse_headers_KEY;
    return parse_headers_KEY(req, data);
  }
  else{
    req->parser=parse_headers_VERSION;
    return parse_headers_VERSION(req, data);
  }
}

static onion_connection_status parse_headers_GET(onion_request *req, onion_buffer *data){
onion_token *token=req->parser_data;
int res=token_read_STRING(token, data);

if (res<=1000)
return res;

int i;
for (i=0;i<16;i++){
if (!onion_request_methods[i]){
ONION_ERROR("Unknown method '%s' (%d known methods)",token->str, i);
return OCS_NOT_IMPLEMENTED;
}
if (strcmp(onion_request_methods[i], token->str)==0){
ONION_DEBUG0("Method is %s", token->str);
req->flags=(req->flags&~0x0F)+i;
break;
}
}
req->parser=parse_headers_URL;

return parse_headers_URL(req, data);
}



/**
* @short Write some data into the request, and passes it line by line to onion_request_fill
*
* It features a state machine, from req->parse_state.
*
* Depending on the state input is redirected to a diferent parser, one for headers, POST url encoded data...
*
* @return Returns the number of bytes writen, or <=0 if connection should close, according to onion_connection_status
* @see onion_connection_status
*/
onion_connection_status onion_request_write(onion_request *req, const char *data, size_t size){
if (!req->parser_data){
req->parser_data=calloc(1, sizeof(onion_token));
req->parser=parse_headers_GET;
}

onion_connection_status (*parse)(onion_request *req, onion_buffer *data);
parse=req->parser;

if (parse){
onion_buffer odata={ data, size, 0};
while (odata.size>odata.pos){
int r=parse(req, &odata);
if (r!=OCS_NEED_MORE_DATA){
return r;
}
parse=req->parser;
}
return OCS_NEED_MORE_DATA;
}

return OCS_INTERNAL_ERROR;
}

/**
* @short Parses the query to unquote the path and get the query.
*/
static int onion_request_parse_query(onion_request *req){
if (!req->fullpath)
return 0;
if (req->GET) // already done
return 1;

char *p=req->fullpath;
char have_query=0;
while(*p){
if (*p=='?'){
have_query=1;
break;
}
p++;
}
*p='\0';
onion_unquote_inplace(req->fullpath);
if (have_query){ // There are querys.
p++;
req->GET=onion_dict_new();
onion_request_parse_query_to_dict(req->GET, p);
}
return 1;
}

/**
* @short Parses the query part to a given dictionary.
*
* The data is overwriten as necessary. It is NOT dupped, so if you free this char *p, please free the tree too.
*/
static void onion_request_parse_query_to_dict(onion_dict *dict, char *p){
ONION_DEBUG0("Query to dict %s",p);
char *key=NULL, *value=NULL;
int state=0; // 0 key, 1 value
key=p;
while(*p){
if (state==0){
if (*p=='='){
*p='\0';
value=p+1;
state=1;
}
else if (*p=='&'){
*p='\0';
onion_unquote_inplace(key);
ONION_DEBUG0("Adding key %s",key);
onion_dict_add(dict, key, "", 0);
key=p+1;
state=0;
}
}
else{
if (*p=='&'){
*p='\0';
onion_unquote_inplace(key);
onion_unquote_inplace(value);
ONION_DEBUG0("Adding key %s=%-16s",key,value);
onion_dict_add(dict, key, value, 0);
key=p+1;
state=0;
}
}
p++;
}
if (state==0){
if (key[0]!='\0'){
onion_unquote_inplace(key);
ONION_DEBUG0("Adding key %s",key);
onion_dict_add(dict, key, "", 0);
}
}
else{
onion_unquote_inplace(key);
onion_unquote_inplace(value);
ONION_DEBUG0("Adding key %s=%-16s",key,value);
onion_dict_add(dict, key, value, 0);
}
}

/**
* @short Prepares the POST
*/
static onion_connection_status prepare_POST(onion_request *req){
// ok post
onion_token *token=req->parser_data;
const char *content_type=onion_dict_get(req->headers, "Content-Type");
const char *content_size=onion_dict_get(req->headers, "Content-Length");

if (!content_size){
ONION_ERROR("I need the content size header to support POST data");
return OCS_INTERNAL_ERROR;
}
size_t cl=atol(content_size);
if (cl==0)
return onion_request_process(req);

//ONION_DEBUG("Content type %s",content_type);
if (!content_type || (strstr(content_type, "application/x-www-form-urlencoded"))){
if (cl>req->connection.listen_point->server->max_post_size){
ONION_ERROR("Asked to send much POST data. Limit %d. Failing.",req->connection.listen_point->server->max_post_size);
return OCS_INTERNAL_ERROR;
}
token->extra=malloc(cl+1); // Cl + \0
token->extra_size=cl;

req->parser=parse_POST_urlencode;
return OCS_NEED_MORE_DATA;
}

// multipart.

const char *mp_token=strstr(content_type, "boundary=");
if (!mp_token){
ONION_ERROR("No boundary set at content-type");
return OCS_INTERNAL_ERROR;
}
mp_token+=9;
if (cl>req->connection.listen_point->server->max_post_size) // I hope the missing part is files, else error later.
cl=req->connection.listen_point->server->max_post_size;

int mp_token_size=strlen(mp_token);
token->extra_size=cl; // Max size of the multipart->data
onion_multipart_buffer *multipart=malloc(token->extra_size+sizeof(onion_multipart_buffer)+mp_token_size+2);
token->extra=(char*)multipart;

multipart->boundary=(char*)multipart+sizeof(onion_multipart_buffer)+1;
multipart->size=mp_token_size+4;
multipart->pos=2; // First boundary already have [\r]\n readen
multipart->post_total_size=cl;
multipart->file_total_size=0;
multipart->boundary[0]='\r';
multipart->boundary[1]='\n';
multipart->boundary[2]='-';
multipart->boundary[3]='-';
strcpy(&multipart->boundary[4],mp_token);
multipart->data=(char*)multipart+sizeof(onion_multipart_buffer)+multipart->size+1;

//ONION_DEBUG("Multipart POST boundary '%s'",multipart->boundary);

req->parser=parse_POST_multipart_start;

return OCS_NEED_MORE_DATA;
}

/**
* @short Prepares the CONTENT LENGTH
*/
static onion_connection_status prepare_CONTENT_LENGTH(onion_request *req){
onion_token *token=req->parser_data;
const char *content_size=onion_dict_get(req->headers, "Content-Length");
if (!content_size){
ONION_ERROR("I need the Content-Length header to get data");
return OCS_INTERNAL_ERROR;
}
size_t cl=atol(content_size);

if (cl>req->connection.listen_point->server->max_post_size){
ONION_ERROR("Trying to set more data at server than allowed %d", req->connection.listen_point->server->max_post_size);
return OCS_INTERNAL_ERROR;
}

req->data=onion_block_new();

token->extra=NULL;
token->extra_size=cl;
token->pos=0;

req->parser=parse_CONTENT_LENGTH;
return OCS_NEED_MORE_DATA;
}

/**
* @short Prepares the PUT
*
* It saves the data to a temporal file, which name is stored at data.
*/
static onion_connection_status prepare_PUT(onion_request *req){
onion_token *token=req->parser_data;
const char *content_size=onion_dict_get(req->headers, "Content-Length");
if (!content_size){
ONION_ERROR("I need the Content-Length header to get data");
return OCS_INTERNAL_ERROR;
}
size_t cl=atol(content_size);

if (cl>req->connection.listen_point->server->max_file_size){
ONION_ERROR("Trying to PUT a file bigger than allowed size");
return OCS_INTERNAL_ERROR;
}

req->data=onion_block_new();

char filename[]="/tmp/onion-XXXXXX";
int fd=mkstemp(filename);
if (fd<0)
ONION_ERROR("Could not create temporal file at %s.", filename);

onion_block_add_str(req->data, filename);
ONION_DEBUG0("Creating PUT file %s (%d bytes long)", filename, token->extra_size);

if (!req->FILES){
req->FILES=onion_dict_new();
}
{
const char *filename=onion_block_data(req->data);
onion_dict_add(req->FILES,"filename", filename, 0);
}


if (cl==0){
ONION_DEBUG0("Created 0 length file");
close(fd);
return onion_request_process(req);
}

int *pfd=malloc(sizeof(fd));
*pfd=fd;

token->extra=(char*)pfd;
token->extra_size=cl;
token->pos=0;

req->parser=parse_PUT;
return OCS_NEED_MORE_DATA;
}

/**
* @short Frees the parser data.
*/
void onion_request_parser_data_free(void *t){
ONION_DEBUG0("Free parser data");
onion_token *token=t;
if (token->extra){
free(token->extra);
token->extra=NULL;
}
free(token);
}
Something went wrong with that request. Please try again.