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