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