Annotation of parser3/src/main/pa_http.C, revision 1.98
1.1 paf 1: /** @file
2: Parser: http support functions.
3:
1.79 moko 4: Copyright (c) 2001-2017 Art. Lebedev Studio (http://www.artlebedev.com)
1.1 paf 5: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
6: */
7:
8: #include "pa_http.h"
9: #include "pa_common.h"
1.81 moko 10: #include "pa_base64.h"
1.1 paf 11: #include "pa_charsets.h"
12: #include "pa_request_charsets.h"
1.22 misha 13: #include "pa_request.h"
14: #include "pa_vfile.h"
15: #include "pa_random.h"
1.1 paf 16:
1.98 ! moko 17: volatile const char * IDENT_PA_HTTP_C="$Id: pa_http.C,v 1.97 2020/10/14 21:35:00 moko Exp $" IDENT_PA_HTTP_H;
1.59 moko 18:
19: #ifdef _MSC_VER
20: #include <windows.h>
1.89 moko 21: #define socklen_t int
1.59 moko 22: #else
23: #define closesocket close
24: #endif
1.53 moko 25:
1.1 paf 26: // defines
27:
1.19 misha 28: #define HTTP_METHOD_NAME "method"
29: #define HTTP_FORM_NAME "form"
30: #define HTTP_BODY_NAME "body"
31: #define HTTP_TIMEOUT_NAME "timeout"
32: #define HTTP_HEADERS_NAME "headers"
1.22 misha 33: #define HTTP_FORM_ENCTYPE_NAME "enctype"
1.19 misha 34: #define HTTP_ANY_STATUS_NAME "any-status"
1.59 moko 35: #define HTTP_OMIT_POST_CHARSET_NAME "omit-post-charset" // ^file::load[...;http://...;$.method[post]] by default adds charset to content-type
1.12 misha 36:
1.1 paf 37: #define HTTP_USER "user"
38: #define HTTP_PASSWORD "password"
39:
1.70 moko 40: #define HTTP_USER_AGENT "user-agent"
1.1 paf 41: #define DEFAULT_USER_AGENT "parser3"
42:
1.59 moko 43: #ifndef INADDR_NONE
44: #define INADDR_NONE ((ulong) -1)
45: #endif
1.1 paf 46:
47: #undef CRLF
48: #define CRLF "\r\n"
49:
1.54 misha 50: // helpers
1.56 misha 51:
1.85 moko 52: bool HTTP_Headers::add_header(const char *line){
1.78 moko 53: const char *value=strchr(line, ':');
54:
55: if(value && value != line){ // we need only headers, not the response code
56: Header header(str_upper(line, value-line), String::Body(value+1).trim(String::TRIM_BOTH, " \t\n\r"));
57:
58: if(header.name == String::Body(HTTP_CONTENT_TYPE_UPPER) && content_type.is_empty())
59: content_type=header.value;
60:
61: if(header.name == String::Body("CONTENT-LENGTH") && content_length==0)
1.95 moko 62: ALTER_EXCEPTION_COMMENT(content_length=pa_atoul(header.value.cstr()), " for content-length");
1.78 moko 63:
64: headers+=header;
65:
66: return true;
67: }
68: return false;
69: }
70:
1.54 misha 71: class Cookies_table_template_columns: public ArrayString {
72: public:
73: Cookies_table_template_columns() {
74: *this+=new String("name");
75: *this+=new String("value");
76: *this+=new String("expires");
77: *this+=new String("max-age");
78: *this+=new String("domain");
79: *this+=new String("path");
80: *this+=new String("httponly");
81: *this+=new String("secure");
82: }
83: };
84:
85:
1.1 paf 86: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
1.22 misha 87: memset(addr, 0, sizeof(*addr));
88: addr->sin_family=AF_INET;
89: addr->sin_port=htons(port);
90: if(host) {
1.65 moko 91: struct hostent *hostIP=gethostbyname(host);
92: if(hostIP && hostIP->h_addrtype == AF_INET){
93: memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length);
94: return true;
95: }
96: }
97: return false;
1.1 paf 98: }
99:
1.84 moko 100: class HTTP_response : public PA_Allocated {
1.78 moko 101: public:
102: char *buf;
103: size_t length;
104: size_t buf_size;
105: size_t body_offset;
106:
1.85 moko 107: HTTP_Headers headers;
1.78 moko 108:
1.97 moko 109: HTTP_response() : buf(NULL), length(0), buf_size(0), body_offset(0){}
1.78 moko 110:
111: void resize(size_t size){
112: buf_size=size;
113: buf=(char *)pa_realloc(buf, size + 1);
114: }
115:
116: bool read(int sock, size_t size){
117: if(length+size>buf_size)
118: resize(buf_size*2 + size);
119: ssize_t received_size=recv(sock, buf + length, size, 0);
120: if(received_size==0)
121: return false;
122: if(received_size<0) {
123: if(int no=pa_socks_errno())
1.97 moko 124: throw Exception("http.timeout", 0, "error receiving response body: %s (%d)", pa_socks_strerr(no), no);
1.78 moko 125: return false;
126: }
127: length+=received_size;
128: buf[length]='\0';
129: return true;
130: }
131:
1.83 moko 132: size_t first_line(){
1.89 moko 133: char *header=strchr(buf, '\n');
134: if(!header)
1.78 moko 135: return false;
136:
1.89 moko 137: return header-buf;
1.78 moko 138: }
139:
140: const char *status_code(char *status_line, int &result){
141: char* status_start = strchr(status_line, ' ');
142:
143: if(!(status_start++))
144: return status_line;
145:
146: char* status_end=strchr(status_start, ' ');
147:
148: if(!status_end)
149: return status_line;
150:
151: if(status_end==status_start)
152: return status_line;
1.1 paf 153:
1.78 moko 154: const char *result_str=pa_strdup(status_start, status_end-status_start);
1.95 moko 155: ALTER_EXCEPTION_COMMENT(result=pa_atoui(result_str), " for HTTP status");
1.78 moko 156: return result_str;
157: }
1.2 paf 158:
1.78 moko 159: bool body_start(){
160: char *p=buf;
161: while((p=strchr(p, '\n'))) {
162: if(p[1]=='\r' && p[2]=='\n'){ // \r\n\r\n
163: *p='\0';
164: body_offset=p-buf+3;
165: return true;
166: }
167: if(p[1]=='\n') { // \n\n
168: *p='\0';
169: body_offset=p-buf+2;
170: return true;
171: }
172: p++;
173: }
174: return false;
1.2 paf 175: }
1.78 moko 176:
177: void parse_headers(){
178: const String header_block(buf, String::L_TAINTED);
179:
180: ArrayString aheaders;
181: header_block.split(aheaders, 0, "\n");
182:
183: Array_iterator<const String*> i(aheaders);
184: i.next(); // skipping status
185: for(;i.has_next();){
186: const char *line=i.next()->cstr();
187: if(!headers.add_header(line))
1.97 moko 188: throw Exception("http.response", 0, "bad response from host - bad header \"%s\"", line);
1.78 moko 189: }
1.1 paf 190: }
191:
1.88 moko 192: int read_response(int sock, bool fail_on_status_ne_200);
1.78 moko 193: };
194:
195: enum HTTP_response_state {
196: HTTP_STATUS_CODE,
197: HTTP_HEADERS,
198: HTTP_BODY
199: };
200:
1.88 moko 201: int HTTP_response::read_response(int sock, bool fail_on_status_ne_200) {
1.78 moko 202: HTTP_response_state state=HTTP_STATUS_CODE;
203: int result=0;
204:
205: size_t chunk_size=0x400*16;
1.88 moko 206: resize(2*chunk_size);
1.78 moko 207:
1.88 moko 208: while(read(sock, chunk_size)){
1.78 moko 209: switch(state){
210: case HTTP_STATUS_CODE: {
1.88 moko 211: size_t status_size=first_line();
1.78 moko 212: if(!status_size)
213: break;
214:
1.88 moko 215: const char *status=status_code(pa_strdup(buf, status_size), result);
1.78 moko 216:
217: if(!result || fail_on_status_ne_200 && result!=200)
218: throw Exception("http.status", status ? new String(status) : &String::Empty, "invalid HTTP response status");
219:
220: state=HTTP_HEADERS;
221: }
222:
223: case HTTP_HEADERS: {
1.88 moko 224: if(!body_start())
1.78 moko 225: break;
226:
1.88 moko 227: parse_headers();
1.78 moko 228:
1.97 moko 229: size_t content_length=check_file_size(headers.content_length, 0);
1.88 moko 230: if(content_length>0 && (content_length + body_offset) > length){
231: resize(content_length + body_offset + 0x400*64);
1.78 moko 232: }
233:
234: state=HTTP_BODY;
1.1 paf 235: break;
236: }
1.78 moko 237:
238: case HTTP_BODY: {
239: chunk_size=0x400*64;
1.1 paf 240: break;
241: }
242: }
243: }
1.78 moko 244:
245: if(state==HTTP_STATUS_CODE)
1.97 moko 246: throw Exception("http.response", 0, "bad response from host - no status found (size=%u)", length);
1.78 moko 247:
248: if(state==HTTP_HEADERS){
1.88 moko 249: parse_headers();
250: body_offset=length;
1.1 paf 251: }
1.78 moko 252:
253: return result;
1.1 paf 254: }
255:
256: /* ********************** request *************************** */
257:
258: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
259: # define PA_USE_ALARM
260: #endif
261:
262: #ifdef PA_USE_ALARM
263: static sigjmp_buf timeout_env;
264: static void timeout_handler(int /*sig*/){
1.22 misha 265: siglongjmp(timeout_env, 1);
1.1 paf 266: }
267: #endif
268:
1.78 moko 269: static int http_request(HTTP_response& response, const char* host, short port, const char* request, size_t request_size, int timeout_secs, bool fail_on_status_ne_200) {
1.1 paf 270: if(!host)
1.73 moko 271: throw Exception("http.host", 0, "zero hostname"); //never
1.1 paf 272:
273: volatile // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning]
274: int sock=-1;
275: #ifdef PA_USE_ALARM
276: signal(SIGALRM, timeout_handler);
277: #endif
278: #ifdef PA_USE_ALARM
279: if(sigsetjmp(timeout_env, 1)) {
280: // stupid gcc [2.95.4] generated bad code
281: // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
282: // rewritten simplier [athough duplicating closesocket code]
283: if(sock>=0)
284: closesocket(sock);
1.80 moko 285: throw Exception("http.timeout", 0, "timeout occurred while retrieving document");
1.1 paf 286: return 0; // never
287: } else {
288: alarm(timeout_secs);
289: #endif
290: try {
291: int result;
292: struct sockaddr_in dest;
293:
294: if(!set_addr(&dest, host, port))
1.73 moko 295: throw Exception("http.host", 0, "can not resolve hostname \"%s\"", host);
1.1 paf 296:
297: if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0) {
298: int no=pa_socks_errno();
1.73 moko 299: throw Exception("http.connect", 0, "can not make socket: %s (%d)", pa_socks_strerr(no), no);
1.1 paf 300: }
301:
302: // To enable SO_DONTLINGER (that is, disable SO_LINGER)
303: // l_onoff should be set to zero and setsockopt should be called
304: linger dont_linger={0,0};
305: setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger));
306:
307: #ifdef WIN32
308: // SO_*TIMEO can be defined in .h but not implemlemented in protocol,
309: // failing subsequently with Option not supported by protocol (99) message
310: // could not suppress that, so leaving this only for win32
311: int timeout_ms=timeout_secs*1000;
312: setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
313: setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
314: #endif
315:
316: if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
317: int no=pa_socks_errno();
1.78 moko 318: throw Exception("http.connect", 0, "can not connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no);
1.1 paf 319: }
1.22 misha 320:
1.1 paf 321: if(send(sock, request, request_size, 0)!=(ssize_t)request_size) {
322: int no=pa_socks_errno();
1.78 moko 323: throw Exception("http.timeout", 0, "error sending request: %s (%d)", pa_socks_strerr(no), no);
1.1 paf 324: }
325:
1.88 moko 326: result=response.read_response(sock, fail_on_status_ne_200);
1.78 moko 327: closesocket(sock);
1.1 paf 328: #ifdef PA_USE_ALARM
1.78 moko 329: alarm(0);
1.1 paf 330: #endif
331: return result;
332: } catch(...) {
333: #ifdef PA_USE_ALARM
1.78 moko 334: alarm(0);
1.1 paf 335: #endif
1.78 moko 336: if(sock>=0)
337: closesocket(sock);
1.1 paf 338: rethrow;
339: }
340: #ifdef PA_USE_ALARM
341: }
342: #endif
343: }
344:
345: #ifndef DOXYGEN
346: struct Http_pass_header_info {
347: Request_charsets* charsets;
348: String* request;
1.35 misha 349: bool* user_agent_specified;
350: bool* content_type_specified;
351: bool* content_type_url_encoded;
1.1 paf 352: };
353: #endif
1.50 moko 354:
355: char *pa_http_safe_header_name(const char *name) {
356: char *result=pa_strdup(name);
357: char *n=result;
1.52 misha 358: if(!pa_isalpha((unsigned char)*n))
1.50 moko 359: *n++ = '_';
360: for(; *n; ++n) {
1.52 misha 361: if (!pa_isalnum((unsigned char)*n) && *n != '-' && *n != '_')
1.50 moko 362: *n = '_';
363: }
364: return result;
365: }
366:
1.35 misha 367: static void http_pass_header(HashStringValue::key_type aname,
368: HashStringValue::value_type avalue,
1.22 misha 369: Http_pass_header_info *info) {
1.9 misha 370:
1.41 misha 371: const char* name_cstr=aname.cstr();
372:
1.38 misha 373: if(strcasecmp(name_cstr, HTTP_CONTENT_LENGTH)==0)
374: return;
375:
1.50 moko 376: String name=String(pa_http_safe_header_name(capitalize(name_cstr)), String::L_AS_IS);
377: String value=attributed_meaning_to_string(*avalue, String::L_HTTP_HEADER, true);
1.9 misha 378:
1.35 misha 379: *info->request << name << ": " << value << CRLF;
1.1 paf 380:
1.38 misha 381: if(strcasecmp(name_cstr, HTTP_USER_AGENT)==0)
1.35 misha 382: *info->user_agent_specified=true;
1.38 misha 383: if(strcasecmp(name_cstr, HTTP_CONTENT_TYPE)==0){
1.35 misha 384: *info->content_type_specified=true;
1.62 moko 385: *info->content_type_url_encoded=pa_strncasecmp(value.cstr(), HTTP_CONTENT_TYPE_FORM_URLENCODED)==0;
1.35 misha 386: }
1.1 paf 387: }
388:
1.10 misha 389: static void http_pass_cookie(HashStringValue::key_type name,
1.20 misha 390: HashStringValue::value_type value,
391: Http_pass_header_info *info) {
1.10 misha 392:
1.17 misha 393: *info->request << String(name, String::L_HTTP_COOKIE) << "="
1.31 misha 394: << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, true)
1.10 misha 395: << "; ";
396:
397: }
1.1 paf 398:
399: static const String* basic_authorization_field(const char* user, const char* pass) {
400: if(!user&& !pass)
401: return 0;
402:
403: String combined;
404: if(user)
405: combined<<user;
406: combined<<":";
407: if(pass)
408: combined<<pass;
409:
1.20 misha 410: String* result=new String("Basic ");
1.82 moko 411: *result<<pa_base64_encode(combined.cstr(), combined.length(), Base64Options(false /*no wrap*/));
1.1 paf 412: return result;
413: }
414:
1.73 moko 415: static void form_string_value2string(HashStringValue::key_type key, const String& value, String& result) {
1.30 misha 416: result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1 paf 417: }
1.20 misha 418:
1.1 paf 419: #ifndef DOXYGEN
420: struct Form_table_value2string_info {
421: HashStringValue::key_type key;
422: String& result;
423:
424: Form_table_value2string_info(HashStringValue::key_type akey, String& aresult):
425: key(akey), result(aresult) {}
426: };
427: #endif
428: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
429: form_string_value2string(info->key, *row->get(0), info->result);
430: }
1.73 moko 431:
432: static void form_value2string(HashStringValue::key_type key, HashStringValue::value_type value, String* result) {
1.1 paf 433: if(const String* svalue=value->get_string())
434: form_string_value2string(key, *svalue, *result);
435: else if(Table* tvalue=value->get_table()) {
436: Form_table_value2string_info info(key, *result);
437: tvalue->for_each(form_table_value2string, &info);
438: } else
1.73 moko 439: throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED),
1.63 moko 440: "is %s, " HTTP_FORM_NAME " option value can be string or table only (file is allowed for $." HTTP_METHOD_NAME "[POST] + $." HTTP_FORM_ENCTYPE_NAME "[" HTTP_CONTENT_TYPE_MULTIPART_FORMDATA "])", value->type());
1.1 paf 441: }
1.20 misha 442:
1.5 misha 443: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1 paf 444: String string;
1.3 paf 445: form.for_each<String*>(form_value2string, &string);
1.44 misha 446: return string.untaint_and_transcode_cstr(String::L_URI, &charsets);
1.1 paf 447: }
1.22 misha 448:
449: struct FormPart {
450: Request* r;
451: const char* boundary;
1.48 moko 452: String* string;
1.22 misha 453: Form_table_value2string_info* info;
1.48 moko 454:
455: struct BinaryBlock{
456: const char* ptr;
457: size_t length;
458:
459: BinaryBlock(String* astring, Request* r): ptr(astring->untaint_and_transcode_cstr(String::L_AS_IS, &r->charsets)), length(strlen(ptr)){}
460: BinaryBlock(const char* aptr, size_t alength): ptr(aptr), length(alength){}
461: };
462:
463: Array<BinaryBlock> blocks;
464:
465: FormPart(Request* ar, const char* aboundary): r(ar), boundary(aboundary), string(new String()){}
466:
467: const char *post(size_t &length){
468: if(blocks.count()){
469: blocks+=BinaryBlock(string, r);
470:
471: length=0;
472: for(size_t i=0; i<blocks.count(); i++)
473: length+=blocks[i].length;
474:
475: char *result=(char *)pa_malloc_atomic(length);
476: char *ptr=result;
477:
478: for(size_t i=0; i<blocks.count(); i++){
479: memcpy(ptr, blocks[i].ptr, blocks[i].length);
480: ptr+=blocks[i].length;
481: }
482:
483: return result;
484: } else {
485: BinaryBlock result(string, r);
486: length=result.length;
487: return result.ptr;
488: }
489: }
1.22 misha 490: };
491:
1.73 moko 492: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0) {
493: *part.string << "--" << part.boundary << CRLF CONTENT_DISPOSITION_CAPITALIZED ": form-data; name=\"" << name << "\"";
1.22 misha 494: if(file_name){
495: if(strcmp(file_name, NONAME_DAT)!=0)
1.48 moko 496: *part.string << "; filename=\"" << file_name << "\"";
497: *part.string << CRLF HTTP_CONTENT_TYPE_CAPITALIZED ": " << part.r->mime_type_of(file_name);
1.22 misha 498: }
1.48 moko 499: *part.string << CRLF CRLF;
1.22 misha 500: }
501:
1.73 moko 502: static void form_string_value2part(HashStringValue::key_type key, const String& value, FormPart& part) {
1.28 misha 503: form_part_boundary_header(part, key);
1.48 moko 504: *part.string << value << CRLF;
1.22 misha 505: }
506:
1.73 moko 507: static void form_file_value2part(HashStringValue::key_type key, VFile& vfile, FormPart& part) {
1.28 misha 508: form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.48 moko 509: part.blocks+=FormPart::BinaryBlock(part.string, part.r);
510: part.blocks+=FormPart::BinaryBlock(vfile.value_ptr(), vfile.value_size());
511: part.string=new String();
512: *part.string << CRLF;
1.22 misha 513: }
514:
515: static void form_table_value2part(Table::element_type row, FormPart* part) {
516: form_string_value2part(part->info->key, *row->get(0), *part);
517: }
518:
1.73 moko 519: static void form_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) {
1.22 misha 520: if(const String* svalue=value->get_string())
521: form_string_value2part(key, *svalue, part);
522: else if(Table* tvalue=value->get_table()) {
1.48 moko 523: Form_table_value2string_info info(key, *part.string);
1.22 misha 524: part.info = &info;
525: tvalue->for_each(form_table_value2part, &part);
1.33 misha 526: } else if(VFile* vfile=static_cast<VFile *>(value->as("file"))){
1.22 misha 527: form_file_value2part(key, *vfile, part);
528: } else
1.73 moko 529: throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED), "is %s, " HTTP_FORM_NAME " option value can be string, table or file only", value->type());
1.22 misha 530: }
531:
532: const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){
1.48 moko 533: FormPart formpart(&r, boundary);
1.22 misha 534: form.for_each<FormPart&>(form_value2part, formpart);
1.48 moko 535: *formpart.string << "--" << boundary << "--";
536: // @todo: return binary blocks here to save memory in pa_internal_file_read_http
537: return formpart.post(post_size);
1.22 misha 538: }
539:
1.54 misha 540: // Set-Cookie: name=value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly
541: static ArrayString* parse_cookie(Request& r, const String& cookie) {
1.64 moko 542: char *current=pa_strdup(cookie.cstr());
1.54 misha 543:
544: const String* name=0;
1.55 moko 545: const String* value=&String::Empty;
546: const String* expires=&String::Empty;
547: const String* max_age=&String::Empty;
548: const String* path=&String::Empty;
549: const String* domain=&String::Empty;
550: const String* httponly=&String::Empty;
551: const String* secure=&String::Empty;
1.54 misha 552:
553: bool first_pair=true;
554:
555: do {
556: if(char *meaning=search_stop(current, ';'))
557: if(char *attribute=search_stop(meaning, '=')) {
558: const String* sname=new String(unescape_chars(attribute, strlen(attribute), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
559: const String* smeaning=0;
560: if(meaning)
561: smeaning=new String(unescape_chars(meaning, strlen(meaning), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
562:
563: if(first_pair) {
564: // name + value
565: name=sname;
566: value=smeaning;
567: first_pair=false;
568: } else {
569: const String& slower=sname->change_case(r.charsets.source(), String::CC_LOWER);
570:
571: if(slower == "expires")
572: expires=smeaning;
573: else if(slower == "max-age")
574: max_age=smeaning;
575: else if(slower == "domain")
576: domain=smeaning;
577: else if(slower == "path")
578: path=smeaning;
579: else if(slower == "httponly")
580: httponly=new String("1", String::L_CLEAN);
581: else if(slower == "secure")
582: secure=new String("1", String::L_CLEAN);
583: else {
584: // todo@ ?
585: }
586: }
587: }
588: } while(current);
589:
590: if(!name)
591: return 0;
592:
593: ArrayString* result=new ArrayString(8);
594: *result+=name;
595: *result+=value;
596: *result+=expires;
597: *result+=max_age;
598: *result+=domain;
599: *result+=path;
600: *result+=httponly;
601: *result+=secure;
602:
603: return result;
604: }
605:
1.56 misha 606: Table* parse_cookies(Request& r, Table *cookies){
607: Table& result=*new Table(new Cookies_table_template_columns);
608:
609: for(Array_iterator<Table::element_type> i(*cookies); i.has_next(); )
610: if(ArrayString* row=parse_cookie(r, *i.next()->get(0)))
611: result+=row;
612:
613: return &result;
614: }
615:
1.75 moko 616: void tables_update(HashStringValue& tables, const String::Body name, const String& value){
1.72 moko 617: Table *table;
618: if(Value *valready=tables.get(name)) {
619: // second+ appearence
620: table=valready->get_table();
621: } else {
622: // first appearence
623: Table::columns_type columns=new ArrayString(1);
624: *columns+=new String("value");
625: table=new Table(columns);
626: tables.put(name, new VTable(table));
627: }
628: // this string becomes next row
629: ArrayString& row=*new ArrayString(1);
630: row+=&value;
631: *table+=&row;
632: }
633:
1.1 paf 634: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.72 moko 635: File_read_http_result pa_internal_file_read_http(Request& r, const String& file_spec, bool as_text, HashStringValue *options, bool transcode_text_result) {
1.1 paf 636: File_read_http_result result;
1.20 misha 637: char host[MAX_STRING];
1.66 moko 638: const char *idna_host;
1.1 paf 639: const char* uri;
1.49 moko 640: short port=80;
1.10 misha 641: const char* method="GET";
1.21 misha 642: bool method_is_get=true;
1.1 paf 643: HashStringValue* form=0;
644: int timeout_secs=2;
645: bool fail_on_status_ne_200=true;
1.12 misha 646: bool omit_post_charset=false;
1.1 paf 647: Value* vheaders=0;
1.10 misha 648: Value* vcookies=0;
1.11 misha 649: Value* vbody=0;
1.72 moko 650: Charset* asked_remote_charset=0;
1.58 moko 651: Charset* real_remote_charset=0;
1.1 paf 652: const char* user_cstr=0;
653: const char* password_cstr=0;
1.22 misha 654: const char* encode=0;
655: bool multipart=false;
1.1 paf 656:
657: if(options) {
658: int valid_options=pa_get_valid_file_options_count(*options);
659:
660: if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
661: valid_options++;
1.21 misha 662: method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
663: method_is_get=strcmp(method, "GET")==0;
1.1 paf 664: }
1.22 misha 665: if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
666: valid_options++;
667: encode=vencode->as_string().cstr();
668: }
1.1 paf 669: if(Value* vform=options->get(HTTP_FORM_NAME)) {
670: valid_options++;
671: form=vform->get_hash();
672: }
1.11 misha 673: if(vbody=options->get(HTTP_BODY_NAME)) {
1.1 paf 674: valid_options++;
675: }
676: if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
677: valid_options++;
678: timeout_secs=vtimeout->as_int();
679: }
1.11 misha 680: if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1 paf 681: valid_options++;
682: }
1.11 misha 683: if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10 misha 684: valid_options++;
685: }
1.1 paf 686: if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
687: valid_options++;
688: fail_on_status_ne_200=!vany_status->as_bool();
1.12 misha 689: }
1.20 misha 690: if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12 misha 691: valid_options++;
692: omit_post_charset=vomit_post_charset->as_bool();
693: }
1.6 misha 694: if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.77 moko 695: asked_remote_charset=&pa_charsets.get(vcharset_name->as_string());
1.58 moko 696: }
697: if(Value* vresponse_charset_name=options->get(PA_RESPONSE_CHARSET_NAME)) {
1.61 moko 698: valid_options++;
1.77 moko 699: real_remote_charset=&pa_charsets.get(vresponse_charset_name->as_string());
1.1 paf 700: }
701: if(Value* vuser=options->get(HTTP_USER)) {
702: valid_options++;
703: user_cstr=vuser->as_string().cstr();
704: }
705: if(Value* vpassword=options->get(HTTP_PASSWORD)) {
706: valid_options++;
707: password_cstr=vpassword->as_string().cstr();
708: }
709:
710: if(valid_options!=options->count())
1.46 misha 711: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 paf 712: }
713: if(!asked_remote_charset) // defaulting to $request:charset
1.22 misha 714: asked_remote_charset=&(r.charsets).source();
715:
716: if(encode){
717: if(method_is_get)
1.72 moko 718: throw Exception(PARSER_RUNTIME, 0, "you can not use $." HTTP_FORM_ENCTYPE_NAME " option with method GET");
1.22 misha 719:
720: multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
721:
722: if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
1.72 moko 723: throw Exception(PARSER_RUNTIME, 0, "$." HTTP_FORM_ENCTYPE_NAME " option value can be " HTTP_CONTENT_TYPE_FORM_URLENCODED " or " HTTP_CONTENT_TYPE_MULTIPART_FORMDATA " only");
1.22 misha 724: }
1.1 paf 725:
1.11 misha 726: if(vbody){
727: if(method_is_get)
1.72 moko 728: throw Exception(PARSER_RUNTIME, 0, "you can not use $." HTTP_BODY_NAME " option with method GET");
1.11 misha 729:
730: if(form)
1.72 moko 731: throw Exception(PARSER_RUNTIME, 0, "you can not use options $." HTTP_BODY_NAME " and $." HTTP_FORM_NAME " together");
1.11 misha 732: }
1.1 paf 733:
734: //preparing request
1.29 misha 735: String& connect_string=*new String(file_spec);
1.1 paf 736:
1.48 moko 737: const char* request;
738: size_t request_size;
1.1 paf 739: {
740: // influence URLencoding of tainted pieces to String::L_URI lang
1.22 misha 741: Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1 paf 742:
1.44 misha 743: const char* connect_string_cstr=connect_string.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1 paf 744:
745: const char* current=connect_string_cstr;
746: if(strncmp(current, "http://", 7)!=0)
1.72 moko 747: throw Exception(PARSER_RUNTIME, &connect_string, "does not start with http://"); //never
1.1 paf 748: current+=7;
749:
750: strncpy(host, current, sizeof(host)-1); host[sizeof(host)-1]=0;
1.34 misha 751: char* host_uri=lsplit(host, '/');
752: uri=host_uri?current+(host_uri-1-host):"/";
753: char* port_cstr=lsplit(host, ':');
1.49 moko 754:
755: if (port_cstr){
756: char* error_pos=0;
757: port=(short)strtol(port_cstr, &error_pos, 10);
758: if(port==0 || *error_pos)
759: throw Exception(PARSER_RUNTIME, &connect_string, "invalid port number '%s'", port_cstr);
760: }
1.1 paf 761:
1.66 moko 762: idna_host=pa_idna_encode(host, r.charsets.source());
763:
1.11 misha 764: // making request head
1.1 paf 765: String head;
1.11 misha 766: head << method << " " << uri;
1.28 misha 767: if(method_is_get && form)
768: head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11 misha 769:
1.66 moko 770: head <<" HTTP/1.0" CRLF "Host: "<< idna_host;
1.49 moko 771: if (port != 80)
772: head << ":" << port_cstr;
773: head << CRLF;
1.11 misha 774:
1.71 moko 775: char* boundary= multipart ? get_uuid_boundary() : 0;
1.22 misha 776:
1.35 misha 777: String user_headers;
778: bool user_agent_specified=false;
779: bool content_type_specified=false;
780: bool content_type_url_encoded=false;
781: if(vheaders && !vheaders->is_string()) { // allow empty
782: if(HashStringValue *headers=vheaders->get_hash()) {
783: Http_pass_header_info info={
784: &(r.charsets),
785: &user_headers,
786: &user_agent_specified,
787: &content_type_specified,
788: &content_type_url_encoded};
789: headers->for_each<Http_pass_header_info*>(http_pass_header, &info);
790: } else
1.72 moko 791: throw Exception(PARSER_RUNTIME, 0, "headers param must be hash");
1.35 misha 792: };
793:
1.48 moko 794: const char* request_body=0;
1.22 misha 795: size_t post_size=0;
796: if(form && !method_is_get) {
1.38 misha 797: head << "Content-Type: " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
1.28 misha 798:
799: if(!omit_post_charset)
800: head << "; charset=" << asked_remote_charset->NAME_CSTR();
801:
1.22 misha 802: if(multipart) {
1.28 misha 803: head << "; boundary=" << boundary;
1.48 moko 804: request_body=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22 misha 805: } else {
1.48 moko 806: request_body=pa_form2string(*form, r.charsets);
807: post_size=strlen(request_body);
1.22 misha 808: }
1.28 misha 809: head << CRLF;
1.35 misha 810: } else if(vbody) {
1.38 misha 811: // $.body was specified
1.35 misha 812: if(content_type_url_encoded){
1.36 misha 813: // transcode + url-encode
1.48 moko 814: request_body=vbody->as_string().untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.35 misha 815: } else {
1.36 misha 816: // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.72 moko 817: const String &sbody=vbody->as_string();
818: request_body=Charset::transcode(String::C(sbody.cstr(), sbody.length()), r.charsets.source(), *asked_remote_charset).str;
1.35 misha 819: }
1.48 moko 820: post_size=strlen(request_body);
1.1 paf 821: }
822:
823: // http://www.ietf.org/rfc/rfc2617.txt
824: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.38 misha 825: head << "Authorization: " << *authorization_field_value << CRLF;
1.1 paf 826:
1.35 misha 827: head << user_headers;
828:
1.1 paf 829: if(!user_agent_specified) // defaulting
1.38 misha 830: head << "User-Agent: " DEFAULT_USER_AGENT CRLF;
1.1 paf 831:
1.12 misha 832: if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
1.72 moko 833: throw Exception(PARSER_RUNTIME, 0, "$.content-type can't be specified with method POST");
1.12 misha 834:
1.11 misha 835: if(vcookies && !vcookies->is_string()){ // allow empty
1.10 misha 836: if(HashStringValue* cookies=vcookies->get_hash()) {
1.37 misha 837: head << "Cookie: ";
1.35 misha 838: Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10 misha 839: cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info);
840: head << CRLF;
841: } else
1.72 moko 842: throw Exception(PARSER_RUNTIME, 0, "cookies param must be hash");
1.10 misha 843: }
844:
1.48 moko 845: if(request_body)
1.38 misha 846: head << "Content-Length: " << format(post_size, "%u") << CRLF;
1.48 moko 847:
848: head << CRLF;
849:
850: const char *request_head=head.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1 paf 851:
1.48 moko 852: if(request_body){
853: size_t head_size = strlen(request_head);
854: request_size=post_size + head_size;
855: char *ptr=(char *)pa_malloc_atomic(request_size);
856: memcpy(ptr, request_head, head_size);
857: memcpy(ptr+head_size, request_body, post_size);
858: request=ptr;
859: } else {
860: request_size=strlen(request_head);
861: request=request_head;
862: }
1.1 paf 863: }
864:
1.78 moko 865:
1.97 moko 866: HTTP_response response;
1.22 misha 867:
1.28 misha 868: // sending request
1.95 moko 869: int status_code;
870: ALTER_EXCEPTION_SOURCE(status_code=http_request(response, idna_host, port, request, request_size, timeout_secs, fail_on_status_ne_200), &connect_string);
1.78 moko 871:
1.72 moko 872: // processing results
1.78 moko 873: char* raw_body=response.buf + response.body_offset;
874: size_t raw_body_size=response.length - response.body_offset;
875:
1.1 paf 876: result.headers=new HashStringValue;
877: VHash* vtables=new VHash;
1.72 moko 878: result.headers->put("tables", vtables);
879:
1.78 moko 880: if (!real_remote_charset && !response.headers.content_type.is_empty())
881: real_remote_charset=detect_charset(response.headers.content_type.cstr());
1.1 paf 882:
1.72 moko 883: if(as_text)
1.77 moko 884: real_remote_charset=pa_charsets.checkBOM(raw_body, raw_body_size, real_remote_charset);
1.72 moko 885:
886: if (!real_remote_charset)
887: real_remote_charset=asked_remote_charset; // never null
888:
1.85 moko 889: for(Array_iterator<HTTP_Headers::Header> i(response.headers.headers); i.has_next(); ){
890: HTTP_Headers::Header header=i.next();
1.72 moko 891:
892: header.transcode(*real_remote_charset, r.charsets.source());
893:
894: String &header_value=*new String(header.value, String::L_TAINTED);
895:
896: tables_update(vtables->hash(), header.name, header_value);
897: result.headers->put(header.name, new VString(header_value));
1.16 misha 898: }
899:
1.72 moko 900: // filling $.cookies
1.89 moko 901: if(vcookies=vtables->hash().get("SET-COOKIE"))
1.72 moko 902: result.headers->put(HTTP_COOKIES_NAME, new VTable(parse_cookies(r, vcookies->get_table())));
903:
1.1 paf 904: // output response
905: String::C real_body=String::C(raw_body, raw_body_size);
1.16 misha 906:
907: if(as_text && transcode_text_result && raw_body_size) { // raw_body_size must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
1.22 misha 908: real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.1 paf 909: }
910:
911: result.str=const_cast<char *>(real_body.str); // hacking a little
912: result.length=real_body.length;
1.16 misha 913:
1.22 misha 914: if(as_text && result.length)
915: fix_line_breaks(result.str, result.length);
916:
1.1 paf 917: result.headers->put(file_status_name, new VInt(status_code));
1.16 misha 918:
1.1 paf 919: return result;
920: }
1.84 moko 921:
922: /* ********************** httpd *************************** */
923:
924: class HTTPD_request : public HTTP_response {
925: public:
926: const char *method;
927: const char *uri;
928:
1.97 moko 929: HTTPD_request() : HTTP_response(), method(NULL), uri(NULL){};
1.84 moko 930:
931: const char *extract_method(char *method_line){
932: char* uri_start = strchr(method_line, ' ');
933:
934: if(!uri_start || uri_start == method_line)
935: return NULL;
936:
937: char* uri_end=strchr(uri_start+1, ' ');
938:
939: if(!uri_end || uri_end == uri_start+1)
940: return NULL;
941:
942: uri=pa_strdup(uri_start+1, uri_end-uri_start-1);
943: return str_upper(method_line, uri_start-method_line);
944: }
945:
1.87 moko 946: void read_header(int);
947: size_t read_post(int, char *, size_t);
1.84 moko 948: };
949:
950: enum HTTPD_request_state {
951: HTTPD_METHOD,
952: HTTPD_HEADERS
953: };
954:
955: void HTTPD_request::read_header(int sock) {
956: enum HTTPD_request_state state = HTTPD_METHOD;
957:
958: size_t chunk_size = 0x400*4;
959: resize(chunk_size);
960:
961: while(read(sock, chunk_size)){
962: switch(state){
963: case HTTPD_METHOD: {
964: size_t method_size = first_line();
965: if(!method_size)
966: break;
967:
968: char *method_line = pa_strdup(buf, method_size);
969: method = extract_method(method_line);
970:
1.92 moko 971: if(!method ||
972: strcmp(method, "GET") &&
973: strcmp(method, "HEAD") &&
974: strcmp(method, "POST") &&
975: strcmp(method, "PUT") &&
976: strcmp(method, "DELETE") &&
977: strcmp(method, "PATCH")
978: )
1.84 moko 979: throw Exception("httpd.method", new String(method ? method : method_line), "invalid request method");
980: state = HTTPD_HEADERS;
981: }
982:
983: case HTTPD_HEADERS: {
984: if(!body_start())
985: break;
986:
987: parse_headers();
988: return;
989: }
990: }
991: }
992:
993: if(state == HTTPD_METHOD)
994: throw Exception("httpd.request", 0, "bad request from host - no method found (size=%u)", length);
995:
996: if(state == HTTPD_HEADERS){
997: parse_headers();
998: body_offset=length;
999: }
1000: }
1001:
1.87 moko 1002: size_t HTTPD_request::read_post(int sock, char *body, size_t max_bytes) {
1003: size_t total_read = min(length - body_offset, max_bytes);
1.98 ! moko 1004: memcpy(body, buf + body_offset, total_read);
1.87 moko 1005:
1006: while (total_read < max_bytes){
1007: ssize_t received_size = recv(sock, buf + total_read, max_bytes - total_read, 0);
1008: if(received_size == 0)
1009: return total_read;
1010: if(received_size < 0) {
1011: if(int no = pa_socks_errno())
1.97 moko 1012: throw Exception("httpd.timeout", new String(uri), "error receiving request body: %s (%d)", pa_socks_strerr(no), no);
1.87 moko 1013: return total_read;
1014: }
1015: total_read += received_size;
1016: }
1017: return total_read;
1018: }
1019:
1.84 moko 1020: /* ********************************************************** */
1021:
1.85 moko 1022: Array<HTTP_Headers::Header> &HTTPD_Connection::headers() {
1.84 moko 1023: return request->headers.headers;
1024: }
1025:
1026: const char *HTTPD_Connection::method() {
1027: return request->method;
1028: }
1029:
1030: const char *HTTPD_Connection::uri() {
1031: return request->uri;
1032: }
1033:
1034: const char *HTTPD_Connection::content_type() {
1035: return request->headers.content_type.cstr();
1036: }
1037:
1038: uint64_t HTTPD_Connection::content_length(){
1039: return request->headers.content_length;
1040: }
1041:
1042: void HTTPD_Connection::read_header(){
1043: request = new HTTPD_request();
1044: request->read_header(sock);
1045: }
1046:
1.87 moko 1047: size_t HTTPD_Connection::read_post(char *body, size_t max_bytes) {
1048: return request->read_post(sock, body, max_bytes);
1049: }
1050:
1.90 moko 1051: size_t HTTPD_Connection::send_body(const void *buf, size_t size) {
1.91 moko 1052: if(send(sock, (const char*)buf, size, 0) != (ssize_t)size) {
1.90 moko 1053: int no=pa_socks_errno();
1054: throw Exception("httpd.timeout", 0, "error sending response: %s (%d)", pa_socks_strerr(no), no);
1055: }
1056: return size;
1057: }
1058:
1.93 moko 1059: HTTPD_Connection::~HTTPD_Connection(){
1060: if(sock != -1)
1061: closesocket(sock);
1062: }
1063:
1064: static int sock_ready(int fd,int operation,int timeout_value){
1065: struct timeval timeout = {0, timeout_value * 1000};
1066: fd_set fds;
1067: FD_ZERO(&fds);
1068: FD_SET(fd, &fds);
1069: switch (operation){
1070: case 0: return select(fd + 1, &fds, NULL, NULL, &timeout)>0; /* read */
1071: case 1: return select(fd + 1, NULL, &fds, NULL, &timeout)>0; /* write */
1072: default: return select(fd + 1, &fds, &fds, NULL, &timeout)>0; /* both */
1073: }
1074: }
1075:
1076: bool HTTPD_Connection::accept(int server_sock, int timeout_value) {
1077: int ready = sock_ready(server_sock, 0, timeout_value);
1078: if (ready < 0) {
1079: int no=pa_socks_errno();
1080: if(no == EINTR)
1081: return false;
1082: throw Exception("httpd.accept", 0, "error waiting for connection: %s (%d)", pa_socks_strerr(no), no);
1083: }
1084: if (ready == 0)
1085: return false; /* Timeout */
1086:
1087: struct sockaddr_in addr;
1088: socklen_t sock_addr_len = sizeof(struct sockaddr_in);
1089: memset(&addr, 0, sock_addr_len);
1090:
1091: sock = ::accept(server_sock, (struct sockaddr *)&addr, &sock_addr_len);
1092: if(server_sock == -1){
1093: int no=pa_socks_errno();
1094: throw Exception("httpd.accept", 0, "error accepting connection: %s (%d)", pa_socks_strerr(no), no);
1095: }
1096:
1097: remote_addr = pa_strdup(inet_ntoa(addr.sin_addr));
1098: return true;
1099: }
1.84 moko 1100:
1.86 moko 1101: int HTTPD_Server::bind(const char *host_port){
1.84 moko 1102: struct sockaddr_in me;
1103:
1.86 moko 1104: const char *port = strchr(host_port, ':');
1105: const char *host = NULL;
1106: if(port && port > host_port){
1107: host = pa_strdup(host_port, port - host_port);
1108: port += 1;
1109: } else {
1110: port = host_port;
1111: }
1112:
1.94 moko 1113: if(!set_addr(&me, host, pa_atoui(port))){
1.84 moko 1114: if (host)
1115: throw Exception("httpd.bind", 0, "can not resolve hostname \"%s\"", host);
1116: me.sin_addr.s_addr=INADDR_ANY;
1117: }
1118:
1119: int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/);
1120:
1121: if(sock < 0){
1122: int no=pa_socks_errno();
1123: throw Exception("httpd.bind", 0, "can not make socket: %s (%d)", pa_socks_strerr(no), no);
1124: }
1125:
1.93 moko 1126: static int sock_on = 1;
1127:
1.84 moko 1128: if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&sock_on, sizeof(sock_on)) ||
1129: setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&sock_on, sizeof(sock_on)) ||
1130: ::bind(sock, (struct sockaddr*)&me, sizeof(me)) ||
1131: listen(sock, 16)) {
1.89 moko 1132: closesocket(sock);
1.84 moko 1133: int no = pa_socks_errno();
1134: throw Exception("httpd.bind", 0, "can not bind socket: %s (%d)", pa_socks_strerr(no), no);
1135: }
1136: return sock;
1137: }
E-mail: