Annotation of parser3/src/main/pa_http.C, revision 1.73
1.1 paf 1: /** @file
2: Parser: http support functions.
3:
1.69 moko 4: Copyright (c) 2001-2015 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"
10: #include "pa_charsets.h"
11: #include "pa_request_charsets.h"
1.22 misha 12: #include "pa_request.h"
13: #include "pa_vfile.h"
14: #include "pa_random.h"
1.1 paf 15:
1.73 ! moko 16: volatile const char * IDENT_PA_HTTP_C="$Id: pa_http.C,v 1.72 2016/07/26 13:20:23 moko Exp $" IDENT_PA_HTTP_H;
1.59 moko 17:
18: #ifdef _MSC_VER
19: #include <windows.h>
20: #else
21: #define closesocket close
22: #endif
1.53 moko 23:
1.1 paf 24: // defines
25:
1.19 misha 26: #define HTTP_METHOD_NAME "method"
27: #define HTTP_FORM_NAME "form"
28: #define HTTP_BODY_NAME "body"
29: #define HTTP_TIMEOUT_NAME "timeout"
30: #define HTTP_HEADERS_NAME "headers"
1.22 misha 31: #define HTTP_FORM_ENCTYPE_NAME "enctype"
1.19 misha 32: #define HTTP_ANY_STATUS_NAME "any-status"
1.59 moko 33: #define HTTP_OMIT_POST_CHARSET_NAME "omit-post-charset" // ^file::load[...;http://...;$.method[post]] by default adds charset to content-type
1.12 misha 34:
1.1 paf 35: #define HTTP_USER "user"
36: #define HTTP_PASSWORD "password"
37:
1.70 moko 38: #define HTTP_USER_AGENT "user-agent"
1.1 paf 39: #define DEFAULT_USER_AGENT "parser3"
40:
1.59 moko 41: #ifndef INADDR_NONE
42: #define INADDR_NONE ((ulong) -1)
43: #endif
1.1 paf 44:
45: #undef CRLF
46: #define CRLF "\r\n"
47:
1.54 misha 48: // helpers
1.56 misha 49:
1.54 misha 50: class Cookies_table_template_columns: public ArrayString {
51: public:
52: Cookies_table_template_columns() {
53: *this+=new String("name");
54: *this+=new String("value");
55: *this+=new String("expires");
56: *this+=new String("max-age");
57: *this+=new String("domain");
58: *this+=new String("path");
59: *this+=new String("httponly");
60: *this+=new String("secure");
61: }
62: };
63:
64:
1.1 paf 65: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
1.22 misha 66: memset(addr, 0, sizeof(*addr));
67: addr->sin_family=AF_INET;
68: addr->sin_port=htons(port);
69: if(host) {
1.65 moko 70: struct hostent *hostIP=gethostbyname(host);
71: if(hostIP && hostIP->h_addrtype == AF_INET){
72: memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length);
73: return true;
74: }
75: }
76: return false;
1.1 paf 77: }
78:
79: size_t guess_content_length(char* buf) {
80: char* ptr;
81: if((ptr=strstr(buf, "Content-Length:"))) // Apache
82: goto found;
1.37 misha 83: if((ptr=strstr(buf, "content-length:"))) // Parser 3 before 3.4.0
1.1 paf 84: goto found;
85: if((ptr=strstr(buf, "Content-length:"))) // maybe 1
86: goto found;
87: if((ptr=strstr(buf, "CONTENT-LENGTH:"))) // maybe 2
88: goto found;
89: return 0;
90: found:
91: char *error_pos;
1.37 misha 92: size_t result=(size_t)strtol(ptr+15/*strlen("Content-Length:")*/, &error_pos, 0);
1.1 paf 93:
94: const size_t reasonable_initial_max=0x400*0x400*10 /*10M*/;
95: if(result>reasonable_initial_max) // sanity check
96: return reasonable_initial_max;
97: return 0;//result;
98: }
99:
100: static int http_read_response(char*& response, size_t& response_size, int sock, bool fail_on_status_ne_200) {
101: int result=0;
1.37 misha 102: // fetching some to local buffer, guessing on possible Content-Length
103: response_size=0x400*20; // initial size if Content-Length could not be determined
1.1 paf 104: const size_t preview_size=0x400*20;
105: char preview_buf[preview_size+1/*terminator*/]; // 20K buffer to preview headers
106: ssize_t received_size=recv(sock, preview_buf, preview_size, 0);
107: if(received_size==0)
108: goto done;
109: if(received_size<0) {
110: if(int no=pa_socks_errno())
1.73 ! moko 111: throw Exception("http.timeout", 0, "error receiving response header: %s (%d)", pa_socks_strerr(no), no);
1.1 paf 112: goto done;
113: }
1.2 paf 114: // terminator [helps futher string searches]
115: preview_buf[received_size]=0;
116: // checking status
117: if(char* EOLat=strstr(preview_buf, "\n")) {
118: const String status_line(pa_strdup(preview_buf, EOLat-preview_buf));
119: ArrayString astatus;
120: size_t pos_after=0;
121: status_line.split(astatus, pos_after, " ");
122: const String& status_code=*astatus.get(astatus.count()>1?1:0);
123: result=status_code.as_int();
124:
125: if(fail_on_status_ne_200 && result!=200)
1.73 ! moko 126: throw Exception("http.status", &status_code, "invalid HTTP response status");
1.2 paf 127: }
1.1 paf 128: // detecting response_size
129: {
130: if(size_t content_length=guess_content_length(preview_buf))
131: response_size=preview_size+content_length; // a little more than needed, will adjust response_size by actual received size later
132: }
133:
134: // [gcc is happier this way, see goto above]
135: {
136: // allocating initial buf
137: response=(char*)pa_malloc_atomic(response_size+1/*terminator*/); // just setting memory block type
138: char* ptr=response;
139: size_t todo_size=response_size;
140: // coping part of already received body
141: memcpy(ptr, preview_buf, received_size);
142: ptr+=received_size;
143: todo_size-=received_size;
144:
145: // we use terminator byte for two purposes here:
146: // 1. we return there zero always, not knowing: maybe they would want to create String form $file.body?
147: // invariant: all Strings should have zero-terminated buffers
1.37 misha 148: // 2. we use that out-of-size byte to detect if our Content-Length guess was wrong
1.1 paf 149: // when recv gets more than we expected
1.37 misha 150: // a) we know that the Content-Length guess was wrong
1.1 paf 151: // b) we have space to put the first byte of extra data
152: // c) we use less code to detect normal situation: on last while-cycle recv expected to just return 0
153: while(true) {
154: received_size=recv(sock, ptr, todo_size+1/*there is always a place for terminator*/, 0);
155: if(received_size==0) {
156: response_size-=todo_size; // in case we received less than expected, cut down the reported size
157: break;
158: }
159: if(received_size<0) {
160: if(int no=pa_socks_errno())
1.73 ! moko 161: throw Exception("http.timeout", 0, "error receiving response body: %s (%d)", pa_socks_strerr(no), no);
1.1 paf 162: break;
163: }
164: // they've touched the terminator?
165: if((size_t)received_size>todo_size)
166: {
167: // that means that our guessed response_size was not big enough
168: const size_t grow_chunk_size=0x400*0x400; // 1M
169: response_size+=grow_chunk_size;
170: size_t ptr_offset=ptr-response;
171: response=(char*)pa_realloc(response, response_size+1/*terminator*/);
172: ptr=response+ptr_offset;
173: todo_size+=grow_chunk_size;
174: }
175: // can't do this before realloc: we need <todo_size check
176: ptr+=received_size;
177: todo_size-=received_size;
178: }
179: }
180: done:
181: if(result)
182: {
183: response[response_size]=0;
184: return result;
185: }
186: else
1.73 ! moko 187: throw Exception("http.response", 0, "bad response from host - no status found (size=%u)", response_size);
1.1 paf 188: }
189:
190: /* ********************** request *************************** */
191:
192: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
193: # define PA_USE_ALARM
194: #endif
195:
196: #ifdef PA_USE_ALARM
197: static sigjmp_buf timeout_env;
198: static void timeout_handler(int /*sig*/){
1.22 misha 199: siglongjmp(timeout_env, 1);
1.1 paf 200: }
201: #endif
202:
203: static int http_request(char*& response, size_t& response_size,
204: const char* host, short port,
1.22 misha 205: const char* request, size_t request_size,
1.1 paf 206: int timeout_secs,
207: bool fail_on_status_ne_200) {
208: if(!host)
1.73 ! moko 209: throw Exception("http.host", 0, "zero hostname"); //never
1.1 paf 210:
211: volatile // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning]
212: int sock=-1;
213: #ifdef PA_USE_ALARM
214: signal(SIGALRM, timeout_handler);
215: #endif
216: #ifdef PA_USE_ALARM
217: if(sigsetjmp(timeout_env, 1)) {
218: // stupid gcc [2.95.4] generated bad code
219: // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
220: // rewritten simplier [athough duplicating closesocket code]
221: if(sock>=0)
222: closesocket(sock);
1.73 ! moko 223: throw Exception("http.timeout", 0, "timeout occured while retrieving document");
1.1 paf 224: return 0; // never
225: } else {
226: alarm(timeout_secs);
227: #endif
228: try {
229: int result;
230: struct sockaddr_in dest;
231:
232: if(!set_addr(&dest, host, port))
1.73 ! moko 233: throw Exception("http.host", 0, "can not resolve hostname \"%s\"", host);
1.1 paf 234:
235: if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0) {
236: int no=pa_socks_errno();
1.73 ! moko 237: throw Exception("http.connect", 0, "can not make socket: %s (%d)", pa_socks_strerr(no), no);
1.1 paf 238: }
239:
240: // To enable SO_DONTLINGER (that is, disable SO_LINGER)
241: // l_onoff should be set to zero and setsockopt should be called
242: linger dont_linger={0,0};
243: setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger));
244:
245: #ifdef WIN32
246: // SO_*TIMEO can be defined in .h but not implemlemented in protocol,
247: // failing subsequently with Option not supported by protocol (99) message
248: // could not suppress that, so leaving this only for win32
249: int timeout_ms=timeout_secs*1000;
250: setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
251: setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
252: #endif
253:
254: if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
255: int no=pa_socks_errno();
1.73 ! moko 256: throw Exception("http.connect", 0, "can not connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no);
1.1 paf 257: }
1.22 misha 258:
1.1 paf 259: if(send(sock, request, request_size, 0)!=(ssize_t)request_size) {
260: int no=pa_socks_errno();
1.73 ! moko 261: throw Exception("http.timeout", 0, "error sending request: %s (%d)", pa_socks_strerr(no), no);
1.1 paf 262: }
263:
264: result=http_read_response(response, response_size, sock, fail_on_status_ne_200);
265: closesocket(sock);
266: #ifdef PA_USE_ALARM
267: alarm(0);
268: #endif
269: return result;
270: } catch(...) {
271: #ifdef PA_USE_ALARM
272: alarm(0);
273: #endif
274: if(sock>=0)
275: closesocket(sock);
276: rethrow;
277: }
278: #ifdef PA_USE_ALARM
279: }
280: #endif
281: }
282:
283: #ifndef DOXYGEN
284: struct Http_pass_header_info {
285: Request_charsets* charsets;
286: String* request;
1.35 misha 287: bool* user_agent_specified;
288: bool* content_type_specified;
289: bool* content_type_url_encoded;
1.1 paf 290: };
291: #endif
1.50 moko 292:
293: char *pa_http_safe_header_name(const char *name) {
294: char *result=pa_strdup(name);
295: char *n=result;
1.52 misha 296: if(!pa_isalpha((unsigned char)*n))
1.50 moko 297: *n++ = '_';
298: for(; *n; ++n) {
1.52 misha 299: if (!pa_isalnum((unsigned char)*n) && *n != '-' && *n != '_')
1.50 moko 300: *n = '_';
301: }
302: return result;
303: }
304:
1.35 misha 305: static void http_pass_header(HashStringValue::key_type aname,
306: HashStringValue::value_type avalue,
1.22 misha 307: Http_pass_header_info *info) {
1.9 misha 308:
1.41 misha 309: const char* name_cstr=aname.cstr();
310:
1.38 misha 311: if(strcasecmp(name_cstr, HTTP_CONTENT_LENGTH)==0)
312: return;
313:
1.50 moko 314: String name=String(pa_http_safe_header_name(capitalize(name_cstr)), String::L_AS_IS);
315: String value=attributed_meaning_to_string(*avalue, String::L_HTTP_HEADER, true);
1.9 misha 316:
1.35 misha 317: *info->request << name << ": " << value << CRLF;
1.1 paf 318:
1.38 misha 319: if(strcasecmp(name_cstr, HTTP_USER_AGENT)==0)
1.35 misha 320: *info->user_agent_specified=true;
1.38 misha 321: if(strcasecmp(name_cstr, HTTP_CONTENT_TYPE)==0){
1.35 misha 322: *info->content_type_specified=true;
1.62 moko 323: *info->content_type_url_encoded=pa_strncasecmp(value.cstr(), HTTP_CONTENT_TYPE_FORM_URLENCODED)==0;
1.35 misha 324: }
1.1 paf 325: }
326:
1.10 misha 327: static void http_pass_cookie(HashStringValue::key_type name,
1.20 misha 328: HashStringValue::value_type value,
329: Http_pass_header_info *info) {
1.10 misha 330:
1.17 misha 331: *info->request << String(name, String::L_HTTP_COOKIE) << "="
1.31 misha 332: << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, true)
1.10 misha 333: << "; ";
334:
335: }
1.1 paf 336:
337: static const String* basic_authorization_field(const char* user, const char* pass) {
338: if(!user&& !pass)
339: return 0;
340:
341: String combined;
342: if(user)
343: combined<<user;
344: combined<<":";
345: if(pass)
346: combined<<pass;
347:
1.20 misha 348: String* result=new String("Basic ");
349: *result<<pa_base64_encode(combined.cstr(), combined.length());
1.1 paf 350: return result;
351: }
352:
1.73 ! moko 353: static void form_string_value2string(HashStringValue::key_type key, const String& value, String& result) {
1.30 misha 354: result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1 paf 355: }
1.20 misha 356:
1.1 paf 357: #ifndef DOXYGEN
358: struct Form_table_value2string_info {
359: HashStringValue::key_type key;
360: String& result;
361:
362: Form_table_value2string_info(HashStringValue::key_type akey, String& aresult):
363: key(akey), result(aresult) {}
364: };
365: #endif
366: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
367: form_string_value2string(info->key, *row->get(0), info->result);
368: }
1.73 ! moko 369:
! 370: static void form_value2string(HashStringValue::key_type key, HashStringValue::value_type value, String* result) {
1.1 paf 371: if(const String* svalue=value->get_string())
372: form_string_value2string(key, *svalue, *result);
373: else if(Table* tvalue=value->get_table()) {
374: Form_table_value2string_info info(key, *result);
375: tvalue->for_each(form_table_value2string, &info);
376: } else
1.73 ! moko 377: throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED),
1.63 moko 378: "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 379: }
1.20 misha 380:
1.5 misha 381: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1 paf 382: String string;
1.3 paf 383: form.for_each<String*>(form_value2string, &string);
1.44 misha 384: return string.untaint_and_transcode_cstr(String::L_URI, &charsets);
1.1 paf 385: }
1.22 misha 386:
387: struct FormPart {
388: Request* r;
389: const char* boundary;
1.48 moko 390: String* string;
1.22 misha 391: Form_table_value2string_info* info;
1.48 moko 392:
393: struct BinaryBlock{
394: const char* ptr;
395: size_t length;
396:
397: BinaryBlock(String* astring, Request* r): ptr(astring->untaint_and_transcode_cstr(String::L_AS_IS, &r->charsets)), length(strlen(ptr)){}
398: BinaryBlock(const char* aptr, size_t alength): ptr(aptr), length(alength){}
399: };
400:
401: Array<BinaryBlock> blocks;
402:
403: FormPart(Request* ar, const char* aboundary): r(ar), boundary(aboundary), string(new String()){}
404:
405: const char *post(size_t &length){
406: if(blocks.count()){
407: blocks+=BinaryBlock(string, r);
408:
409: length=0;
410: for(size_t i=0; i<blocks.count(); i++)
411: length+=blocks[i].length;
412:
413: char *result=(char *)pa_malloc_atomic(length);
414: char *ptr=result;
415:
416: for(size_t i=0; i<blocks.count(); i++){
417: memcpy(ptr, blocks[i].ptr, blocks[i].length);
418: ptr+=blocks[i].length;
419: }
420:
421: return result;
422: } else {
423: BinaryBlock result(string, r);
424: length=result.length;
425: return result.ptr;
426: }
427: }
1.22 misha 428: };
429:
1.73 ! moko 430: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0) {
! 431: *part.string << "--" << part.boundary << CRLF CONTENT_DISPOSITION_CAPITALIZED ": form-data; name=\"" << name << "\"";
1.22 misha 432: if(file_name){
433: if(strcmp(file_name, NONAME_DAT)!=0)
1.48 moko 434: *part.string << "; filename=\"" << file_name << "\"";
435: *part.string << CRLF HTTP_CONTENT_TYPE_CAPITALIZED ": " << part.r->mime_type_of(file_name);
1.22 misha 436: }
1.48 moko 437: *part.string << CRLF CRLF;
1.22 misha 438: }
439:
1.73 ! moko 440: static void form_string_value2part(HashStringValue::key_type key, const String& value, FormPart& part) {
1.28 misha 441: form_part_boundary_header(part, key);
1.48 moko 442: *part.string << value << CRLF;
1.22 misha 443: }
444:
1.73 ! moko 445: static void form_file_value2part(HashStringValue::key_type key, VFile& vfile, FormPart& part) {
1.28 misha 446: form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.48 moko 447: part.blocks+=FormPart::BinaryBlock(part.string, part.r);
448: part.blocks+=FormPart::BinaryBlock(vfile.value_ptr(), vfile.value_size());
449: part.string=new String();
450: *part.string << CRLF;
1.22 misha 451: }
452:
453: static void form_table_value2part(Table::element_type row, FormPart* part) {
454: form_string_value2part(part->info->key, *row->get(0), *part);
455: }
456:
1.73 ! moko 457: static void form_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) {
1.22 misha 458: if(const String* svalue=value->get_string())
459: form_string_value2part(key, *svalue, part);
460: else if(Table* tvalue=value->get_table()) {
1.48 moko 461: Form_table_value2string_info info(key, *part.string);
1.22 misha 462: part.info = &info;
463: tvalue->for_each(form_table_value2part, &part);
1.33 misha 464: } else if(VFile* vfile=static_cast<VFile *>(value->as("file"))){
1.22 misha 465: form_file_value2part(key, *vfile, part);
466: } else
1.73 ! moko 467: 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 468: }
469:
470: const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){
1.48 moko 471: FormPart formpart(&r, boundary);
1.22 misha 472: form.for_each<FormPart&>(form_value2part, formpart);
1.48 moko 473: *formpart.string << "--" << boundary << "--";
474: // @todo: return binary blocks here to save memory in pa_internal_file_read_http
475: return formpart.post(post_size);
1.22 misha 476: }
477:
1.73 ! moko 478: static void find_headers_end(char* p, char*& headers_end_at, char*& raw_body) {
1.1 paf 479: raw_body=p;
480: // \n\n
481: // \r\n\r\n
482: while((p=strchr(p, '\n'))) {
483: headers_end_at=++p; // \n>.<
484: if(*p=='\r') // \r\n>\r?<\n
485: p++;
486: if(*p=='\n') { // \r\n\r>\n?<
487: raw_body=p+1;
488: return;
489: }
490: }
491: headers_end_at=0;
492: }
493:
1.54 misha 494: // Set-Cookie: name=value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly
495: static ArrayString* parse_cookie(Request& r, const String& cookie) {
1.64 moko 496: char *current=pa_strdup(cookie.cstr());
1.54 misha 497:
498: const String* name=0;
1.55 moko 499: const String* value=&String::Empty;
500: const String* expires=&String::Empty;
501: const String* max_age=&String::Empty;
502: const String* path=&String::Empty;
503: const String* domain=&String::Empty;
504: const String* httponly=&String::Empty;
505: const String* secure=&String::Empty;
1.54 misha 506:
507: bool first_pair=true;
508:
509: do {
510: if(char *meaning=search_stop(current, ';'))
511: if(char *attribute=search_stop(meaning, '=')) {
512: const String* sname=new String(unescape_chars(attribute, strlen(attribute), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
513: const String* smeaning=0;
514: if(meaning)
515: smeaning=new String(unescape_chars(meaning, strlen(meaning), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
516:
517: if(first_pair) {
518: // name + value
519: name=sname;
520: value=smeaning;
521: first_pair=false;
522: } else {
523: const String& slower=sname->change_case(r.charsets.source(), String::CC_LOWER);
524:
525: if(slower == "expires")
526: expires=smeaning;
527: else if(slower == "max-age")
528: max_age=smeaning;
529: else if(slower == "domain")
530: domain=smeaning;
531: else if(slower == "path")
532: path=smeaning;
533: else if(slower == "httponly")
534: httponly=new String("1", String::L_CLEAN);
535: else if(slower == "secure")
536: secure=new String("1", String::L_CLEAN);
537: else {
538: // todo@ ?
539: }
540: }
541: }
542: } while(current);
543:
544: if(!name)
545: return 0;
546:
547: ArrayString* result=new ArrayString(8);
548: *result+=name;
549: *result+=value;
550: *result+=expires;
551: *result+=max_age;
552: *result+=domain;
553: *result+=path;
554: *result+=httponly;
555: *result+=secure;
556:
557: return result;
558: }
559:
1.56 misha 560: Table* parse_cookies(Request& r, Table *cookies){
561: Table& result=*new Table(new Cookies_table_template_columns);
562:
563: for(Array_iterator<Table::element_type> i(*cookies); i.has_next(); )
564: if(ArrayString* row=parse_cookie(r, *i.next()->get(0)))
565: result+=row;
566:
567: return &result;
568: }
569:
1.72 moko 570: void *tables_update(HashStringValue& tables, const String::Body name, const String& value){
571: Table *table;
572: if(Value *valready=tables.get(name)) {
573: // second+ appearence
574: table=valready->get_table();
575: } else {
576: // first appearence
577: Table::columns_type columns=new ArrayString(1);
578: *columns+=new String("value");
579: table=new Table(columns);
580: tables.put(name, new VTable(table));
581: }
582: // this string becomes next row
583: ArrayString& row=*new ArrayString(1);
584: row+=&value;
585: *table+=&row;
586: }
587:
1.1 paf 588: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.72 moko 589: 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 590: File_read_http_result result;
1.20 misha 591: char host[MAX_STRING];
1.66 moko 592: const char *idna_host;
1.1 paf 593: const char* uri;
1.49 moko 594: short port=80;
1.10 misha 595: const char* method="GET";
1.21 misha 596: bool method_is_get=true;
1.1 paf 597: HashStringValue* form=0;
598: int timeout_secs=2;
599: bool fail_on_status_ne_200=true;
1.12 misha 600: bool omit_post_charset=false;
1.1 paf 601: Value* vheaders=0;
1.10 misha 602: Value* vcookies=0;
1.11 misha 603: Value* vbody=0;
1.72 moko 604: Charset* asked_remote_charset=0;
1.58 moko 605: Charset* real_remote_charset=0;
1.1 paf 606: const char* user_cstr=0;
607: const char* password_cstr=0;
1.22 misha 608: const char* encode=0;
609: bool multipart=false;
1.1 paf 610:
611: if(options) {
612: int valid_options=pa_get_valid_file_options_count(*options);
613:
614: if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
615: valid_options++;
1.21 misha 616: method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
617: method_is_get=strcmp(method, "GET")==0;
1.1 paf 618: }
1.22 misha 619: if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
620: valid_options++;
621: encode=vencode->as_string().cstr();
622: }
1.1 paf 623: if(Value* vform=options->get(HTTP_FORM_NAME)) {
624: valid_options++;
625: form=vform->get_hash();
626: }
1.11 misha 627: if(vbody=options->get(HTTP_BODY_NAME)) {
1.1 paf 628: valid_options++;
629: }
630: if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
631: valid_options++;
632: timeout_secs=vtimeout->as_int();
633: }
1.11 misha 634: if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1 paf 635: valid_options++;
636: }
1.11 misha 637: if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10 misha 638: valid_options++;
639: }
1.1 paf 640: if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
641: valid_options++;
642: fail_on_status_ne_200=!vany_status->as_bool();
1.12 misha 643: }
1.20 misha 644: if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12 misha 645: valid_options++;
646: omit_post_charset=vomit_post_charset->as_bool();
647: }
1.6 misha 648: if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.58 moko 649: asked_remote_charset=&charsets.get(vcharset_name->as_string().change_case(r.charsets.source(), String::CC_UPPER));
650: }
651: if(Value* vresponse_charset_name=options->get(PA_RESPONSE_CHARSET_NAME)) {
1.61 moko 652: valid_options++;
1.58 moko 653: real_remote_charset=&charsets.get(vresponse_charset_name->as_string().change_case(r.charsets.source(), String::CC_UPPER));
1.1 paf 654: }
655: if(Value* vuser=options->get(HTTP_USER)) {
656: valid_options++;
657: user_cstr=vuser->as_string().cstr();
658: }
659: if(Value* vpassword=options->get(HTTP_PASSWORD)) {
660: valid_options++;
661: password_cstr=vpassword->as_string().cstr();
662: }
663:
664: if(valid_options!=options->count())
1.46 misha 665: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 paf 666: }
667: if(!asked_remote_charset) // defaulting to $request:charset
1.22 misha 668: asked_remote_charset=&(r.charsets).source();
669:
670: if(encode){
671: if(method_is_get)
1.72 moko 672: throw Exception(PARSER_RUNTIME, 0, "you can not use $." HTTP_FORM_ENCTYPE_NAME " option with method GET");
1.22 misha 673:
674: multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
675:
676: if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
1.72 moko 677: 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 678: }
1.1 paf 679:
1.11 misha 680: if(vbody){
681: if(method_is_get)
1.72 moko 682: throw Exception(PARSER_RUNTIME, 0, "you can not use $." HTTP_BODY_NAME " option with method GET");
1.11 misha 683:
684: if(form)
1.72 moko 685: throw Exception(PARSER_RUNTIME, 0, "you can not use options $." HTTP_BODY_NAME " and $." HTTP_FORM_NAME " together");
1.11 misha 686: }
1.1 paf 687:
688: //preparing request
1.29 misha 689: String& connect_string=*new String(file_spec);
1.1 paf 690:
1.48 moko 691: const char* request;
692: size_t request_size;
1.1 paf 693: {
694: // influence URLencoding of tainted pieces to String::L_URI lang
1.22 misha 695: Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1 paf 696:
1.44 misha 697: const char* connect_string_cstr=connect_string.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1 paf 698:
699: const char* current=connect_string_cstr;
700: if(strncmp(current, "http://", 7)!=0)
1.72 moko 701: throw Exception(PARSER_RUNTIME, &connect_string, "does not start with http://"); //never
1.1 paf 702: current+=7;
703:
704: strncpy(host, current, sizeof(host)-1); host[sizeof(host)-1]=0;
1.34 misha 705: char* host_uri=lsplit(host, '/');
706: uri=host_uri?current+(host_uri-1-host):"/";
707: char* port_cstr=lsplit(host, ':');
1.49 moko 708:
709: if (port_cstr){
710: char* error_pos=0;
711: port=(short)strtol(port_cstr, &error_pos, 10);
712: if(port==0 || *error_pos)
713: throw Exception(PARSER_RUNTIME, &connect_string, "invalid port number '%s'", port_cstr);
714: }
1.1 paf 715:
1.66 moko 716: idna_host=pa_idna_encode(host, r.charsets.source());
717:
1.11 misha 718: // making request head
1.1 paf 719: String head;
1.11 misha 720: head << method << " " << uri;
1.28 misha 721: if(method_is_get && form)
722: head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11 misha 723:
1.66 moko 724: head <<" HTTP/1.0" CRLF "Host: "<< idna_host;
1.49 moko 725: if (port != 80)
726: head << ":" << port_cstr;
727: head << CRLF;
1.11 misha 728:
1.71 moko 729: char* boundary= multipart ? get_uuid_boundary() : 0;
1.22 misha 730:
1.35 misha 731: String user_headers;
732: bool user_agent_specified=false;
733: bool content_type_specified=false;
734: bool content_type_url_encoded=false;
735: if(vheaders && !vheaders->is_string()) { // allow empty
736: if(HashStringValue *headers=vheaders->get_hash()) {
737: Http_pass_header_info info={
738: &(r.charsets),
739: &user_headers,
740: &user_agent_specified,
741: &content_type_specified,
742: &content_type_url_encoded};
743: headers->for_each<Http_pass_header_info*>(http_pass_header, &info);
744: } else
1.72 moko 745: throw Exception(PARSER_RUNTIME, 0, "headers param must be hash");
1.35 misha 746: };
747:
1.48 moko 748: const char* request_body=0;
1.22 misha 749: size_t post_size=0;
750: if(form && !method_is_get) {
1.38 misha 751: head << "Content-Type: " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
1.28 misha 752:
753: if(!omit_post_charset)
754: head << "; charset=" << asked_remote_charset->NAME_CSTR();
755:
1.22 misha 756: if(multipart) {
1.28 misha 757: head << "; boundary=" << boundary;
1.48 moko 758: request_body=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22 misha 759: } else {
1.48 moko 760: request_body=pa_form2string(*form, r.charsets);
761: post_size=strlen(request_body);
1.22 misha 762: }
1.28 misha 763: head << CRLF;
1.35 misha 764: } else if(vbody) {
1.38 misha 765: // $.body was specified
1.35 misha 766: if(content_type_url_encoded){
1.36 misha 767: // transcode + url-encode
1.48 moko 768: request_body=vbody->as_string().untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.35 misha 769: } else {
1.36 misha 770: // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.72 moko 771: const String &sbody=vbody->as_string();
772: request_body=Charset::transcode(String::C(sbody.cstr(), sbody.length()), r.charsets.source(), *asked_remote_charset).str;
1.35 misha 773: }
1.48 moko 774: post_size=strlen(request_body);
1.1 paf 775: }
776:
777: // http://www.ietf.org/rfc/rfc2617.txt
778: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.38 misha 779: head << "Authorization: " << *authorization_field_value << CRLF;
1.1 paf 780:
1.35 misha 781: head << user_headers;
782:
1.1 paf 783: if(!user_agent_specified) // defaulting
1.38 misha 784: head << "User-Agent: " DEFAULT_USER_AGENT CRLF;
1.1 paf 785:
1.12 misha 786: if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
1.72 moko 787: throw Exception(PARSER_RUNTIME, 0, "$.content-type can't be specified with method POST");
1.12 misha 788:
1.11 misha 789: if(vcookies && !vcookies->is_string()){ // allow empty
1.10 misha 790: if(HashStringValue* cookies=vcookies->get_hash()) {
1.37 misha 791: head << "Cookie: ";
1.35 misha 792: Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10 misha 793: cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info);
794: head << CRLF;
795: } else
1.72 moko 796: throw Exception(PARSER_RUNTIME, 0, "cookies param must be hash");
1.10 misha 797: }
798:
1.48 moko 799: if(request_body)
1.38 misha 800: head << "Content-Length: " << format(post_size, "%u") << CRLF;
1.48 moko 801:
802: head << CRLF;
803:
804: const char *request_head=head.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1 paf 805:
1.48 moko 806: if(request_body){
807: size_t head_size = strlen(request_head);
808: request_size=post_size + head_size;
809: char *ptr=(char *)pa_malloc_atomic(request_size);
810: memcpy(ptr, request_head, head_size);
811: memcpy(ptr+head_size, request_body, post_size);
812: request=ptr;
813: } else {
814: request_size=strlen(request_head);
815: request=request_head;
816: }
1.1 paf 817: }
818:
1.72 moko 819: char* response_str;
1.1 paf 820: size_t response_size;
1.22 misha 821:
1.28 misha 822: // sending request
1.72 moko 823: int status_code=http_request(response_str, response_size, idna_host, port, request, request_size, timeout_secs, fail_on_status_ne_200);
1.1 paf 824:
1.72 moko 825: // processing results
1.1 paf 826: char* raw_body; size_t raw_body_size;
827: char* headers_end_at;
1.72 moko 828: find_headers_end(response_str, headers_end_at, raw_body);
829: raw_body_size=response_size-(raw_body-response_str);
1.1 paf 830:
831: result.headers=new HashStringValue;
832: VHash* vtables=new VHash;
1.72 moko 833: result.headers->put("tables", vtables);
834:
835: ResponseHeaders response;
1.1 paf 836:
837: if(headers_end_at) {
838: *headers_end_at=0;
1.72 moko 839: const String header_block(String::C(response_str, headers_end_at-response_str), String::L_TAINTED);
1.1 paf 840:
841: ArrayString aheaders;
842:
843: size_t pos_after=0;
844: header_block.split(aheaders, pos_after, "\n");
845:
1.72 moko 846: Array_iterator<const String*> i(aheaders);
847: i.next(); // skipping status
848: for(;i.has_next();){
849: const char *line=i.next()->cstr();
850: if(!response.add_header(line))
851: throw Exception("http.response", &connect_string, "bad response from host - bad header \"%s\"", line);
1.1 paf 852: }
1.72 moko 853: }
1.54 misha 854:
1.72 moko 855: if (!real_remote_charset && !response.content_type.is_empty())
856: real_remote_charset= detect_charset(response.content_type.cstr());
1.1 paf 857:
1.72 moko 858: if(as_text)
1.68 moko 859: real_remote_charset=charsets.checkBOM(raw_body, raw_body_size, real_remote_charset);
1.72 moko 860:
861: if (!real_remote_charset)
862: real_remote_charset=asked_remote_charset; // never null
863:
864: for(Array_iterator<ResponseHeaders::Header> i(response.headers); i.has_next(); ){
865: ResponseHeaders::Header header=i.next();
866:
867: header.transcode(*real_remote_charset, r.charsets.source());
868:
869: String &header_value=*new String(header.value, String::L_TAINTED);
870:
871: tables_update(vtables->hash(), header.name, header_value);
872: result.headers->put(header.name, new VString(header_value));
1.16 misha 873: }
874:
1.72 moko 875: // filling $.cookies
876: if(Value *vcookies=vtables->hash().get("SET-COOKIE"))
877: result.headers->put(HTTP_COOKIES_NAME, new VTable(parse_cookies(r, vcookies->get_table())));
878:
1.1 paf 879: // output response
880: String::C real_body=String::C(raw_body, raw_body_size);
1.16 misha 881:
882: 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 883: real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.1 paf 884: }
885:
886: result.str=const_cast<char *>(real_body.str); // hacking a little
887: result.length=real_body.length;
1.16 misha 888:
1.22 misha 889: if(as_text && result.length)
890: fix_line_breaks(result.str, result.length);
891:
1.1 paf 892: result.headers->put(file_status_name, new VInt(status_code));
1.16 misha 893:
1.1 paf 894: return result;
895: }
E-mail: