Annotation of parser3/src/main/pa_http.C, revision 1.30
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.30 ! misha 8: static const char * const IDENT_HTTP_C="$Date: 2009-07-06 12:07:04 $";
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;
69: if((ptr=strstr(buf, "content-length:"))) // Parser 3
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;
78: size_t result=(size_t)strtol(ptr+15/*strlen("CONTENT-LENGTH:")*/, &error_pos, 0);
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;
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
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
138: // 2. we use that out-of-size byte to detect if our content-length guess was wrong
139: // when recv gets more than we expected
140: // a) we know that the content-length guess was wrong
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:
1.22 misha 197: static size_t file_untaint(const char* str, size_t len) {
198: // untaint file from L_FILE_POST encoding
199: char* j=(char *)str;
200: const char* end=str+len-1;
201: for(const char* i=str; i<=end; i++, j++){
202: if(*i=='\\' && i!=end){
203: switch(*(i+1)){
204: case '0':
205: *j='\0';
206: i++;
207: continue;
208: case '\\':
209: *j='\\';
210: i++;
211: continue;
212: }
213: }
214: if(i!=j)
215: *j=*i;
216: }
217: return j-str; // new length
218: }
219:
1.1 paf 220: static int http_request(char*& response, size_t& response_size,
221: const char* host, short port,
1.22 misha 222: const char* request, size_t request_size,
1.1 paf 223: int timeout_secs,
224: bool fail_on_status_ne_200) {
225: if(!host)
226: throw Exception("http.host",
227: 0,
228: "zero hostname"); //never
229:
230: volatile // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning]
231: int sock=-1;
232: #ifdef PA_USE_ALARM
233: signal(SIGALRM, timeout_handler);
234: #endif
235: #ifdef PA_USE_ALARM
236: if(sigsetjmp(timeout_env, 1)) {
237: // stupid gcc [2.95.4] generated bad code
238: // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
239: // rewritten simplier [athough duplicating closesocket code]
240: if(sock>=0)
241: closesocket(sock);
242: throw Exception("http.timeout",
243: 0,
244: "timeout occured while retrieving document");
245: return 0; // never
246: } else {
247: alarm(timeout_secs);
248: #endif
249: try {
250: int result;
251: struct sockaddr_in dest;
252:
253: if(!set_addr(&dest, host, port))
254: throw Exception("http.host",
255: 0,
256: "can not resolve hostname \"%s\"", host);
257:
258: if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0) {
259: int no=pa_socks_errno();
260: throw Exception("http.connect",
261: 0,
262: "can not make socket: %s (%d)", pa_socks_strerr(no), no);
263: }
264:
265: // To enable SO_DONTLINGER (that is, disable SO_LINGER)
266: // l_onoff should be set to zero and setsockopt should be called
267: linger dont_linger={0,0};
268: setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger));
269:
270: #ifdef WIN32
271: // SO_*TIMEO can be defined in .h but not implemlemented in protocol,
272: // failing subsequently with Option not supported by protocol (99) message
273: // could not suppress that, so leaving this only for win32
274: int timeout_ms=timeout_secs*1000;
275: setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
276: setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
277: #endif
278:
279: if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
280: int no=pa_socks_errno();
281: throw Exception("http.connect",
282: 0,
283: "can not connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no);
284: }
1.22 misha 285:
1.1 paf 286: if(send(sock, request, request_size, 0)!=(ssize_t)request_size) {
287: int no=pa_socks_errno();
288: throw Exception("http.timeout",
289: 0,
290: "error sending request: %s (%d)", pa_socks_strerr(no), no);
291: }
292:
293: result=http_read_response(response, response_size, sock, fail_on_status_ne_200);
294: closesocket(sock);
295: #ifdef PA_USE_ALARM
296: alarm(0);
297: #endif
298: return result;
299: } catch(...) {
300: #ifdef PA_USE_ALARM
301: alarm(0);
302: #endif
303: if(sock>=0)
304: closesocket(sock);
305: rethrow;
306: }
307: #ifdef PA_USE_ALARM
308: }
309: #endif
310: }
311:
312: #ifndef DOXYGEN
313: struct Http_pass_header_info {
314: Request_charsets* charsets;
315: String* request;
316: bool user_agent_specified;
1.12 misha 317: bool content_type_specified;
1.1 paf 318: };
319: #endif
1.9 misha 320: static void http_pass_header(HashStringValue::key_type name,
1.22 misha 321: HashStringValue::value_type value,
322: Http_pass_header_info *info) {
1.9 misha 323:
1.10 misha 324: String aname=String(name, String::L_URI);
1.9 misha 325:
1.21 misha 326: *info->request << aname << ": "
1.10 misha 327: << attributed_meaning_to_string(*value, String::L_URI, false)
1.9 misha 328: << CRLF;
1.1 paf 329:
1.12 misha 330: const String::Body name_upper=aname.change_case(info->charsets->source(), String::CC_UPPER);
1.20 misha 331: if(name_upper==HTTP_USER_AGENT_UPPER)
1.9 misha 332: info->user_agent_specified=true;
1.20 misha 333: if(name_upper==HTTP_CONTENT_TYPE_UPPER)
1.12 misha 334: info->content_type_specified=true;
1.1 paf 335: }
336:
1.10 misha 337: static void http_pass_cookie(HashStringValue::key_type name,
1.20 misha 338: HashStringValue::value_type value,
339: Http_pass_header_info *info) {
1.10 misha 340:
1.17 misha 341: *info->request << String(name, String::L_HTTP_COOKIE) << "="
342: << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, false)
1.10 misha 343: << "; ";
344:
345: }
1.1 paf 346:
347: static const String* basic_authorization_field(const char* user, const char* pass) {
348: if(!user&& !pass)
349: return 0;
350:
351: String combined;
352: if(user)
353: combined<<user;
354: combined<<":";
355: if(pass)
356: combined<<pass;
357:
1.20 misha 358: String* result=new String("Basic ");
359: *result<<pa_base64_encode(combined.cstr(), combined.length());
1.1 paf 360: return result;
361: }
362:
363: static void form_string_value2string(
1.20 misha 364: HashStringValue::key_type key,
365: const String& value,
366: String& result)
1.1 paf 367: {
1.30 ! misha 368: result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1 paf 369: }
1.20 misha 370:
1.1 paf 371: #ifndef DOXYGEN
372: struct Form_table_value2string_info {
373: HashStringValue::key_type key;
374: String& result;
375:
376: Form_table_value2string_info(HashStringValue::key_type akey, String& aresult):
377: key(akey), result(aresult) {}
378: };
379: #endif
380: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
381: form_string_value2string(info->key, *row->get(0), info->result);
382: }
383: static void form_value2string(
1.20 misha 384: HashStringValue::key_type key,
385: HashStringValue::value_type value,
386: String* result)
1.1 paf 387: {
388: if(const String* svalue=value->get_string())
389: form_string_value2string(key, *svalue, *result);
390: else if(Table* tvalue=value->get_table()) {
391: Form_table_value2string_info info(key, *result);
392: tvalue->for_each(form_table_value2string, &info);
393: } else
1.18 misha 394: throw Exception(PARSER_RUNTIME,
1.1 paf 395: new String(key, String::L_TAINTED),
1.22 misha 396: "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 397: }
1.20 misha 398:
1.5 misha 399: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1 paf 400: String string;
1.3 paf 401: form.for_each<String*>(form_value2string, &string);
1.29 misha 402: return string.untaint_cstr(String::L_AS_IS, 0, &charsets);
1.1 paf 403: }
1.22 misha 404:
405: struct FormPart {
406: Request* r;
407: const char* boundary;
408: String string;
409: Form_table_value2string_info* info;
410: };
411:
1.28 misha 412: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0){
413: part.string << "--" << part.boundary
414: << CRLF HTTP_CONTENT_DISPOSITION ": form-data; name=\""
415: << Charset::transcode(name, part.r->charsets.source(), part.r->charsets.client())
416: << "\"";
1.22 misha 417: if(file_name){
418: if(strcmp(file_name, NONAME_DAT)!=0)
419: part.string << "; filename=\"" << file_name << "\"";
420: part.string << CRLF HTTP_CONTENT_TYPE ": " << part.r->mime_type_of(file_name);
421: }
1.28 misha 422: part.string << CRLF CRLF;
1.22 misha 423: }
424:
425: static void form_string_value2part(
1.28 misha 426: HashStringValue::key_type key,
427: const String& value,
428: FormPart& part)
1.22 misha 429: {
1.28 misha 430: form_part_boundary_header(part, key);
431: part.string << Charset::transcode(value, part.r->charsets.source(), part.r->charsets.client()) << CRLF;
1.22 misha 432: }
433:
434: static void form_file_value2part(
1.28 misha 435: HashStringValue::key_type key,
436: VFile& vfile,
437: FormPart& part)
1.22 misha 438: {
1.28 misha 439: form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.22 misha 440: part.string.append_know_length(vfile.value_ptr(), vfile.value_size(), String::L_FILE_POST);
441: part.string << CRLF;
442: }
443:
444: static void form_table_value2part(Table::element_type row, FormPart* part) {
445: form_string_value2part(part->info->key, *row->get(0), *part);
446: }
447:
448: static void form_value2part(
1.28 misha 449: HashStringValue::key_type key,
450: HashStringValue::value_type value,
451: FormPart& part)
1.22 misha 452: {
453: if(const String* svalue=value->get_string())
454: form_string_value2part(key, *svalue, part);
455: else if(Table* tvalue=value->get_table()) {
456: Form_table_value2string_info info(key, part.string);
457: part.info = &info;
458: tvalue->for_each(form_table_value2part, &part);
459: } else if(VFile* vfile=static_cast<VFile *>(value->as("file", false))){
460: form_file_value2part(key, *vfile, part);
461: } else
462: throw Exception(PARSER_RUNTIME,
463: new String(key, String::L_TAINTED),
464: "is %s, "HTTP_FORM_NAME" option value can be string, table or file only", value->type());
465: }
466:
467: const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){
468: FormPart formpart;
469: formpart.r=&r;
470: formpart.boundary=boundary;
471: formpart.info=NULL;
472: form.for_each<FormPart&>(form_value2part, formpart);
1.24 misha 473: formpart.string << "--" << boundary << "--";
1.28 misha 474: post_size=formpart.string.length(); // very surprizing, but it calculates correct post_size even with binary files!
1.29 misha 475: return formpart.string.untaint_cstr(String::L_AS_IS); // without transcoding
1.22 misha 476: }
477:
1.1 paf 478: static void find_headers_end(char* p,
479: char*& headers_end_at,
480: char*& raw_body)
481: {
482: raw_body=p;
483: // \n\n
484: // \r\n\r\n
485: while((p=strchr(p, '\n'))) {
486: headers_end_at=++p; // \n>.<
487: if(*p=='\r') // \r\n>\r?<\n
488: p++;
489: if(*p=='\n') { // \r\n\r>\n?<
490: raw_body=p+1;
491: return;
492: }
493: }
494: headers_end_at=0;
495: }
496:
497: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.22 misha 498: File_read_http_result pa_internal_file_read_http(Request& r,
499: const String& file_spec,
1.20 misha 500: bool as_text,
1.15 misha 501: HashStringValue *options,
502: bool transcode_text_result) {
1.1 paf 503: File_read_http_result result;
1.20 misha 504: char host[MAX_STRING];
1.1 paf 505: const char* uri;
506: short port;
1.10 misha 507: const char* method="GET";
1.21 misha 508: bool method_is_get=true;
1.1 paf 509: HashStringValue* form=0;
510: const char* body_cstr=0;
511: int timeout_secs=2;
512: bool fail_on_status_ne_200=true;
1.12 misha 513: bool omit_post_charset=false;
1.1 paf 514: Value* vheaders=0;
1.10 misha 515: Value* vcookies=0;
1.11 misha 516: Value* vbody=0;
1.1 paf 517: Charset *asked_remote_charset=0;
518: const char* user_cstr=0;
519: const char* password_cstr=0;
1.22 misha 520: const char* encode=0;
521: bool multipart=false;
1.1 paf 522:
523: if(options) {
524: int valid_options=pa_get_valid_file_options_count(*options);
525:
526: if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
527: valid_options++;
1.21 misha 528: method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
529: method_is_get=strcmp(method, "GET")==0;
1.1 paf 530: }
1.22 misha 531: if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
532: valid_options++;
533: encode=vencode->as_string().cstr();
534: }
1.1 paf 535: if(Value* vform=options->get(HTTP_FORM_NAME)) {
536: valid_options++;
537: form=vform->get_hash();
538: }
1.11 misha 539: if(vbody=options->get(HTTP_BODY_NAME)) {
1.1 paf 540: valid_options++;
541: }
542: if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
543: valid_options++;
544: timeout_secs=vtimeout->as_int();
545: }
1.11 misha 546: if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1 paf 547: valid_options++;
548: }
1.11 misha 549: if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10 misha 550: valid_options++;
551: }
1.1 paf 552: if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
553: valid_options++;
554: fail_on_status_ne_200=!vany_status->as_bool();
1.12 misha 555: }
1.20 misha 556: if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12 misha 557: valid_options++;
558: omit_post_charset=vomit_post_charset->as_bool();
559: }
1.6 misha 560: if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.23 misha 561: asked_remote_charset=&charsets.get(vcharset_name->as_string().
1.22 misha 562: change_case(r.charsets.source(), String::CC_UPPER));
1.1 paf 563: }
564: if(Value* vuser=options->get(HTTP_USER)) {
565: valid_options++;
566: user_cstr=vuser->as_string().cstr();
567: }
568: if(Value* vpassword=options->get(HTTP_PASSWORD)) {
569: valid_options++;
570: password_cstr=vpassword->as_string().cstr();
571: }
572:
573: if(valid_options!=options->count())
1.7 misha 574: throw Exception(PARSER_RUNTIME,
1.1 paf 575: 0,
576: "invalid option passed");
577: }
578: if(!asked_remote_charset) // defaulting to $request:charset
1.22 misha 579: asked_remote_charset=&(r.charsets).source();
580:
581: if(encode){
582: if(method_is_get)
583: throw Exception(PARSER_RUNTIME,
584: 0,
585: "you can not use $."HTTP_FORM_ENCTYPE_NAME" option with method GET");
586:
587: multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
588:
589: if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
590: throw Exception(PARSER_RUNTIME,
591: 0,
592: "$."HTTP_FORM_ENCTYPE_NAME" option value can be "HTTP_CONTENT_TYPE_FORM_URLENCODED" or "HTTP_CONTENT_TYPE_MULTIPART_FORMDATA" only");
593: }
1.1 paf 594:
1.11 misha 595: if(vbody){
596: if(method_is_get)
597: throw Exception(PARSER_RUNTIME,
598: 0,
599: "you can not use $."HTTP_BODY_NAME" option with method GET");
600:
601: if(form)
602: throw Exception(PARSER_RUNTIME,
603: 0,
604: "you can not use options $."HTTP_BODY_NAME" and $."HTTP_FORM_NAME" together");
605: }
1.1 paf 606:
607: //preparing request
1.29 misha 608: String& connect_string=*new String(file_spec);
1.1 paf 609:
610: String request_head_and_body;
611: {
612: // influence URLencoding of tainted pieces to String::L_URI lang
1.22 misha 613: Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1 paf 614:
1.29 misha 615: const char* connect_string_cstr=connect_string.untaint_cstr(String::L_URI, 0, &(r.charsets));
1.1 paf 616:
617: const char* current=connect_string_cstr;
618: if(strncmp(current, "http://", 7)!=0)
1.18 misha 619: throw Exception(PARSER_RUNTIME,
1.1 paf 620: &connect_string,
621: "does not start with http://"); //never
622: current+=7;
623:
624: strncpy(host, current, sizeof(host)-1); host[sizeof(host)-1]=0;
625: char* host_uri=lsplit(host, '/');
626: uri=host_uri?current+(host_uri-1-host):"/";
627: char* port_cstr=lsplit(host, ':');
628: char* error_pos=0;
629: port=port_cstr?(short)strtol(port_cstr, &error_pos, 0):80;
630:
1.11 misha 631: // making request head
1.1 paf 632: String head;
1.11 misha 633: head << method << " " << uri;
1.28 misha 634: if(method_is_get && form)
635: head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11 misha 636:
637: head <<" HTTP/1.0" CRLF "host: "<< host << CRLF;
638:
1.28 misha 639: char* boundary=0;
1.22 misha 640:
641: if(multipart){
642: uuid uuid=get_uuid();
643: const int boundary_bufsize=10+32+1/*for zero-teminator*/+1/*for faulty snprintfs*/;
644: boundary=new(PointerFreeGC) char[boundary_bufsize];
645: snprintf(boundary, boundary_bufsize,
646: "----------%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X",
647: uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
648: uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
649: uuid.node[0], uuid.node[1], uuid.node[2],
650: uuid.node[3], uuid.node[4], uuid.node[5]);
651: }
652:
653: size_t post_size=0;
654: if(form && !method_is_get) {
1.28 misha 655: head << HTTP_CONTENT_TYPE ": " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
656:
657: if(!omit_post_charset)
658: head << "; charset=" << asked_remote_charset->NAME_CSTR();
659:
1.22 misha 660: if(multipart) {
1.28 misha 661: head << "; boundary=" << boundary;
662: body_cstr=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22 misha 663: } else {
664: body_cstr=pa_form2string(*form, r.charsets);
665: post_size=strlen(body_cstr);
666: }
1.28 misha 667: head << CRLF;
1.22 misha 668: } else if (vbody) {
1.28 misha 669: // transcode tainted pieces and then URI-encode them
1.29 misha 670: body_cstr=vbody->as_string().untaint_cstr(String::L_AS_IS, 0, &(r.charsets));
1.28 misha 671:
672: // now transcode is needed only if own content-type was specified _and_ clean chars with code>127 are in the body
673: // @todo: I don't like the current behaviour
1.11 misha 674: body_cstr=Charset::transcode(
675: String::C(body_cstr, strlen(body_cstr)),
1.22 misha 676: r.charsets.source(),
1.11 misha 677: *asked_remote_charset
678: );
1.27 misha 679: post_size=strlen(body_cstr);
1.1 paf 680: }
681:
682: // http://www.ietf.org/rfc/rfc2617.txt
683: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
684: head<<"authorization: "<<*authorization_field_value<<CRLF;
685:
686: bool user_agent_specified=false;
1.12 misha 687: bool content_type_specified=false;
1.1 paf 688: if(vheaders && !vheaders->is_string()) { // allow empty
689: if(HashStringValue *headers=vheaders->get_hash()) {
1.22 misha 690: Http_pass_header_info info={&(r.charsets), &head, false};
1.3 paf 691: headers->for_each<Http_pass_header_info*>(http_pass_header, &info);
1.1 paf 692: user_agent_specified=info.user_agent_specified;
1.12 misha 693: content_type_specified=info.content_type_specified;
1.1 paf 694: } else
1.7 misha 695: throw Exception(PARSER_RUNTIME,
1.1 paf 696: &connect_string,
697: "headers param must be hash");
698: };
699: if(!user_agent_specified) // defaulting
1.20 misha 700: head << HTTP_USER_AGENT ": " DEFAULT_USER_AGENT CRLF;
1.1 paf 701:
1.12 misha 702: if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
703: throw Exception(PARSER_RUNTIME,
704: &connect_string,
705: "$.content-type can't be specified with method POST");
706:
1.11 misha 707: if(vcookies && !vcookies->is_string()){ // allow empty
1.10 misha 708: if(HashStringValue* cookies=vcookies->get_hash()) {
709: head << "cookie: ";
1.22 misha 710: Http_pass_header_info info={&(r.charsets), &head, false};
1.10 misha 711: cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info);
712: head << CRLF;
713: } else
714: throw Exception(PARSER_RUNTIME,
715: &connect_string,
716: "cookies param must be hash");
717: }
718:
1.25 misha 719: if(body_cstr)
1.22 misha 720: head << "content-length: " << format(post_size, "%u") << CRLF;
1.1 paf 721:
722: // head + end of header
1.29 misha 723: request_head_and_body << head.untaint_cstr(String::L_AS_IS, 0, &(r.charsets)) << CRLF;
1.8 misha 724:
1.1 paf 725: // body
726: if(body_cstr)
727: request_head_and_body << body_cstr;
728: }
729:
1.28 misha 730: const char* request_cstr=request_head_and_body.cstr();
731: size_t request_size=strlen(request_cstr);
732:
733: if(multipart)
734: request_size=file_untaint(request_cstr, request_size);
735:
1.1 paf 736: char* response;
737: size_t response_size;
1.22 misha 738:
1.28 misha 739: // sending request
1.1 paf 740: int status_code=http_request(response, response_size,
1.28 misha 741: host, port, request_cstr, request_size,
1.1 paf 742: timeout_secs, fail_on_status_ne_200);
743:
1.28 misha 744: // processing results
1.1 paf 745: char* raw_body; size_t raw_body_size;
746: char* headers_end_at;
747: find_headers_end(response,
748: headers_end_at,
749: raw_body);
750: raw_body_size=response_size-(raw_body-response);
751:
752: result.headers=new HashStringValue;
753: VHash* vtables=new VHash;
754: result.headers->put(HTTP_TABLES_NAME, vtables);
755: Charset* real_remote_charset=0; // undetected, yet
756:
757: if(headers_end_at) {
758: *headers_end_at=0;
1.25 misha 759: const String header_block(String::C(response, headers_end_at-response), String::L_TAINTED);
1.1 paf 760:
761: ArrayString aheaders;
762: HashStringValue& tables=vtables->hash();
763:
764: size_t pos_after=0;
765: header_block.split(aheaders, pos_after, "\n");
766:
1.28 misha 767: // processing headers
1.1 paf 768: size_t aheaders_count=aheaders.count();
769: for(size_t i=1; i<aheaders_count; i++) {
770: const String& line=*aheaders.get(i);
771: size_t pos=line.pos(':');
772: if(pos==STRING_NOT_FOUND || pos<1)
773: throw Exception("http.response",
774: &connect_string,
775: "bad response from host - bad header \"%s\"", line.cstr());
1.22 misha 776: const String::Body HEADER_NAME=line.mid(0, pos).change_case(r.charsets.source(), String::CC_UPPER);
1.14 misha 777: const String& HEADER_VALUE=line.mid(pos+1, line.length()).trim(String::TRIM_BOTH, " \t\r");
1.20 misha 778: if(as_text && HEADER_NAME==HTTP_CONTENT_TYPE_UPPER)
1.26 misha 779: real_remote_charset=detect_charset(HEADER_VALUE.cstr(), true/*already uppercased*/);
1.1 paf 780:
781: // tables
782: {
783: Value *valready=(Value *)tables.get(HEADER_NAME);
784: bool existed=valready!=0;
785: Table *table;
786: if(existed) {
787: // second+ appearence
788: table=valready->get_table();
789: } else {
790: // first appearence
1.14 misha 791: Table::columns_type columns=new ArrayString(1);
1.1 paf 792: *columns+=new String("value");
793: table=new Table(columns);
794: }
795: // this string becomes next row
796: ArrayString& row=*new ArrayString(1);
1.14 misha 797: row+=&HEADER_VALUE;
1.1 paf 798: *table+=&row;
799: // not existed before? add it
800: if(!existed)
801: tables.put(HEADER_NAME, new VTable(table));
802: }
803:
1.14 misha 804: result.headers->put(HEADER_NAME, new VString(HEADER_VALUE));
1.1 paf 805: }
806: }
807:
1.16 misha 808: if(as_text && raw_body_size>=3 && strncmp(raw_body, "\xEF\xBB\xBF", 3)==0){
1.20 misha 809: // skip UTF-8 signature (BOM code)
1.16 misha 810: raw_body+=3;
811: raw_body_size-=3;
812: }
813:
1.1 paf 814: // output response
815: String::C real_body=String::C(raw_body, raw_body_size);
1.16 misha 816:
817: 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 818: // defaulting to used-asked charset [it's never empty!]
819: if(!real_remote_charset)
820: real_remote_charset=asked_remote_charset;
1.16 misha 821:
1.22 misha 822: real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.16 misha 823:
1.1 paf 824: }
825:
826: result.str=const_cast<char *>(real_body.str); // hacking a little
827: result.length=real_body.length;
1.16 misha 828:
1.22 misha 829: if(as_text && result.length)
830: fix_line_breaks(result.str, result.length);
831:
1.1 paf 832: result.headers->put(file_status_name, new VInt(status_code));
1.16 misha 833:
1.1 paf 834: return result;
835: }
E-mail: