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