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