Annotation of parser3/src/main/pa_http.C, revision 1.37
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.37 ! misha 8: static const char * const IDENT_HTTP_C="$Date: 2009-08-22 14:23:51 $";
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:
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;
1.35 misha 316: bool* user_agent_specified;
317: bool* content_type_specified;
318: bool* content_type_url_encoded;
1.1 paf 319: };
320: #endif
1.35 misha 321: static void http_pass_header(HashStringValue::key_type aname,
322: HashStringValue::value_type avalue,
1.22 misha 323: Http_pass_header_info *info) {
1.9 misha 324:
1.35 misha 325: String name=String(aname, String::L_URI);
326: String value=attributed_meaning_to_string(*avalue, String::L_URI, false);
1.9 misha 327:
1.35 misha 328: *info->request << name << ": " << value << CRLF;
1.1 paf 329:
1.37 ! misha 330: const String::Body NAME=name.change_case(info->charsets->source(), String::CC_UPPER);
! 331: if(NAME==HTTP_USER_AGENT_UPPER)
1.35 misha 332: *info->user_agent_specified=true;
1.37 ! misha 333: if(NAME==HTTP_CONTENT_TYPE_UPPER){
1.35 misha 334: *info->content_type_specified=true;
335: *info->content_type_url_encoded=StrStartFromNC(value.cstr(), HTTP_CONTENT_TYPE_FORM_URLENCODED);
336: }
1.1 paf 337: }
338:
1.10 misha 339: static void http_pass_cookie(HashStringValue::key_type name,
1.20 misha 340: HashStringValue::value_type value,
341: Http_pass_header_info *info) {
1.10 misha 342:
1.17 misha 343: *info->request << String(name, String::L_HTTP_COOKIE) << "="
1.31 misha 344: << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, true)
1.10 misha 345: << "; ";
346:
347: }
1.1 paf 348:
349: static const String* basic_authorization_field(const char* user, const char* pass) {
350: if(!user&& !pass)
351: return 0;
352:
353: String combined;
354: if(user)
355: combined<<user;
356: combined<<":";
357: if(pass)
358: combined<<pass;
359:
1.20 misha 360: String* result=new String("Basic ");
361: *result<<pa_base64_encode(combined.cstr(), combined.length());
1.1 paf 362: return result;
363: }
364:
365: static void form_string_value2string(
1.20 misha 366: HashStringValue::key_type key,
367: const String& value,
368: String& result)
1.1 paf 369: {
1.30 misha 370: result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1 paf 371: }
1.20 misha 372:
1.1 paf 373: #ifndef DOXYGEN
374: struct Form_table_value2string_info {
375: HashStringValue::key_type key;
376: String& result;
377:
378: Form_table_value2string_info(HashStringValue::key_type akey, String& aresult):
379: key(akey), result(aresult) {}
380: };
381: #endif
382: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
383: form_string_value2string(info->key, *row->get(0), info->result);
384: }
385: static void form_value2string(
1.20 misha 386: HashStringValue::key_type key,
387: HashStringValue::value_type value,
388: String* result)
1.1 paf 389: {
390: if(const String* svalue=value->get_string())
391: form_string_value2string(key, *svalue, *result);
392: else if(Table* tvalue=value->get_table()) {
393: Form_table_value2string_info info(key, *result);
394: tvalue->for_each(form_table_value2string, &info);
395: } else
1.18 misha 396: throw Exception(PARSER_RUNTIME,
1.1 paf 397: new String(key, String::L_TAINTED),
1.22 misha 398: "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 399: }
1.20 misha 400:
1.5 misha 401: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1 paf 402: String string;
1.3 paf 403: form.for_each<String*>(form_value2string, &string);
1.34 misha 404: return string.transcode_and_untaint_cstr(String::L_URI, &charsets);
1.1 paf 405: }
1.22 misha 406:
407: struct FormPart {
408: Request* r;
409: const char* boundary;
410: String string;
411: Form_table_value2string_info* info;
412: };
413:
1.28 misha 414: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0){
415: part.string << "--" << part.boundary
1.37 ! misha 416: << CRLF CONTENT_DISPOSITION ": form-data; name=\""
1.28 misha 417: << Charset::transcode(name, part.r->charsets.source(), part.r->charsets.client())
418: << "\"";
1.22 misha 419: if(file_name){
420: if(strcmp(file_name, NONAME_DAT)!=0)
421: part.string << "; filename=\"" << file_name << "\"";
422: part.string << CRLF HTTP_CONTENT_TYPE ": " << part.r->mime_type_of(file_name);
423: }
1.28 misha 424: part.string << CRLF CRLF;
1.22 misha 425: }
426:
427: static void form_string_value2part(
1.28 misha 428: HashStringValue::key_type key,
429: const String& value,
430: FormPart& part)
1.22 misha 431: {
1.28 misha 432: form_part_boundary_header(part, key);
433: part.string << Charset::transcode(value, part.r->charsets.source(), part.r->charsets.client()) << CRLF;
1.22 misha 434: }
435:
436: static void form_file_value2part(
1.28 misha 437: HashStringValue::key_type key,
438: VFile& vfile,
439: FormPart& part)
1.22 misha 440: {
1.28 misha 441: form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.22 misha 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(
1.28 misha 451: HashStringValue::key_type key,
452: HashStringValue::value_type value,
453: FormPart& part)
1.22 misha 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);
1.33 misha 461: } else if(VFile* vfile=static_cast<VFile *>(value->as("file"))){
1.22 misha 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.28 misha 476: post_size=formpart.string.length(); // very surprizing, but it calculates correct post_size even with binary files!
1.29 misha 477: return formpart.string.untaint_cstr(String::L_AS_IS); // without transcoding
1.22 misha 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
1.29 misha 610: String& connect_string=*new String(file_spec);
1.1 paf 611:
612: String request_head_and_body;
613: {
614: // influence URLencoding of tainted pieces to String::L_URI lang
1.22 misha 615: Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1 paf 616:
1.34 misha 617: const char* connect_string_cstr=connect_string.transcode_and_untaint_cstr(String::L_URI, &(r.charsets));
1.1 paf 618:
619: const char* current=connect_string_cstr;
620: if(strncmp(current, "http://", 7)!=0)
1.18 misha 621: throw Exception(PARSER_RUNTIME,
1.1 paf 622: &connect_string,
623: "does not start with http://"); //never
624: current+=7;
625:
626: strncpy(host, current, sizeof(host)-1); host[sizeof(host)-1]=0;
1.34 misha 627: char* host_uri=lsplit(host, '/');
628: uri=host_uri?current+(host_uri-1-host):"/";
629: char* port_cstr=lsplit(host, ':');
1.1 paf 630: char* error_pos=0;
631: port=port_cstr?(short)strtol(port_cstr, &error_pos, 0):80;
632:
1.11 misha 633: // making request head
1.1 paf 634: String head;
1.11 misha 635: head << method << " " << uri;
1.28 misha 636: if(method_is_get && form)
637: head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11 misha 638:
1.37 ! misha 639: head <<" HTTP/1.0" CRLF "Host: "<< host << CRLF;
1.11 misha 640:
1.28 misha 641: char* boundary=0;
1.22 misha 642:
643: if(multipart){
644: uuid uuid=get_uuid();
645: const int boundary_bufsize=10+32+1/*for zero-teminator*/+1/*for faulty snprintfs*/;
646: boundary=new(PointerFreeGC) char[boundary_bufsize];
647: snprintf(boundary, boundary_bufsize,
648: "----------%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X",
649: uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
650: uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
651: uuid.node[0], uuid.node[1], uuid.node[2],
652: uuid.node[3], uuid.node[4], uuid.node[5]);
653: }
654:
1.35 misha 655: String user_headers;
656: bool user_agent_specified=false;
657: bool content_type_specified=false;
658: bool content_type_url_encoded=false;
659: if(vheaders && !vheaders->is_string()) { // allow empty
660: if(HashStringValue *headers=vheaders->get_hash()) {
661: Http_pass_header_info info={
662: &(r.charsets),
663: &user_headers,
664: &user_agent_specified,
665: &content_type_specified,
666: &content_type_url_encoded};
667: headers->for_each<Http_pass_header_info*>(http_pass_header, &info);
668: } else
669: throw Exception(PARSER_RUNTIME,
670: 0,
671: "headers param must be hash");
672: };
673:
1.22 misha 674: size_t post_size=0;
675: if(form && !method_is_get) {
1.28 misha 676: head << HTTP_CONTENT_TYPE ": " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
677:
678: if(!omit_post_charset)
679: head << "; charset=" << asked_remote_charset->NAME_CSTR();
680:
1.22 misha 681: if(multipart) {
1.28 misha 682: head << "; boundary=" << boundary;
683: body_cstr=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22 misha 684: } else {
685: body_cstr=pa_form2string(*form, r.charsets);
686: post_size=strlen(body_cstr);
687: }
1.28 misha 688: head << CRLF;
1.35 misha 689: } else if(vbody) {
690: if(content_type_url_encoded){
1.36 misha 691: // transcode + url-encode
1.35 misha 692: body_cstr=vbody->as_string().transcode_and_untaint_cstr(String::L_URI, &(r.charsets));
693: } else {
1.36 misha 694: // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.35 misha 695: body_cstr=Charset::transcode(
696: String::C(vbody->as_string().cstr(), vbody->as_string().length()),
697: r.charsets.source(),
698: *asked_remote_charset
699: );
700: }
1.27 misha 701: post_size=strlen(body_cstr);
1.1 paf 702: }
703:
704: // http://www.ietf.org/rfc/rfc2617.txt
705: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.37 ! misha 706: head<<"Authorization: "<<*authorization_field_value<<CRLF;
1.1 paf 707:
1.35 misha 708: head << user_headers;
709:
1.1 paf 710: if(!user_agent_specified) // defaulting
1.20 misha 711: head << HTTP_USER_AGENT ": " DEFAULT_USER_AGENT CRLF;
1.1 paf 712:
1.12 misha 713: if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
714: throw Exception(PARSER_RUNTIME,
1.35 misha 715: 0,
1.12 misha 716: "$.content-type can't be specified with method POST");
717:
1.11 misha 718: if(vcookies && !vcookies->is_string()){ // allow empty
1.10 misha 719: if(HashStringValue* cookies=vcookies->get_hash()) {
1.37 ! misha 720: head << "Cookie: ";
1.35 misha 721: Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10 misha 722: cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info);
723: head << CRLF;
724: } else
725: throw Exception(PARSER_RUNTIME,
1.35 misha 726: 0,
1.10 misha 727: "cookies param must be hash");
728: }
729:
1.25 misha 730: if(body_cstr)
1.37 ! misha 731: head << HTTP_CONTENT_LENGTH << ": " << format(post_size, "%u") << CRLF;
1.1 paf 732:
733: // head + end of header
1.29 misha 734: request_head_and_body << head.untaint_cstr(String::L_AS_IS, 0, &(r.charsets)) << CRLF;
1.8 misha 735:
1.1 paf 736: // body
737: if(body_cstr)
738: request_head_and_body << body_cstr;
739: }
740:
1.28 misha 741: const char* request_cstr=request_head_and_body.cstr();
742: size_t request_size=strlen(request_cstr);
743:
744: if(multipart)
745: request_size=file_untaint(request_cstr, request_size);
746:
1.1 paf 747: char* response;
748: size_t response_size;
1.22 misha 749:
1.28 misha 750: // sending request
1.1 paf 751: int status_code=http_request(response, response_size,
1.28 misha 752: host, port, request_cstr, request_size,
1.1 paf 753: timeout_secs, fail_on_status_ne_200);
754:
1.28 misha 755: // processing results
1.1 paf 756: char* raw_body; size_t raw_body_size;
757: char* headers_end_at;
758: find_headers_end(response,
759: headers_end_at,
760: raw_body);
761: raw_body_size=response_size-(raw_body-response);
762:
763: result.headers=new HashStringValue;
764: VHash* vtables=new VHash;
765: result.headers->put(HTTP_TABLES_NAME, vtables);
766: Charset* real_remote_charset=0; // undetected, yet
767:
768: if(headers_end_at) {
769: *headers_end_at=0;
1.25 misha 770: const String header_block(String::C(response, headers_end_at-response), String::L_TAINTED);
1.1 paf 771:
772: ArrayString aheaders;
773: HashStringValue& tables=vtables->hash();
774:
775: size_t pos_after=0;
776: header_block.split(aheaders, pos_after, "\n");
777:
1.28 misha 778: // processing headers
1.1 paf 779: size_t aheaders_count=aheaders.count();
780: for(size_t i=1; i<aheaders_count; i++) {
781: const String& line=*aheaders.get(i);
782: size_t pos=line.pos(':');
783: if(pos==STRING_NOT_FOUND || pos<1)
784: throw Exception("http.response",
785: &connect_string,
786: "bad response from host - bad header \"%s\"", line.cstr());
1.22 misha 787: const String::Body HEADER_NAME=line.mid(0, pos).change_case(r.charsets.source(), String::CC_UPPER);
1.14 misha 788: const String& HEADER_VALUE=line.mid(pos+1, line.length()).trim(String::TRIM_BOTH, " \t\r");
1.20 misha 789: if(as_text && HEADER_NAME==HTTP_CONTENT_TYPE_UPPER)
1.32 misha 790: real_remote_charset=detect_charset(HEADER_VALUE.cstr());
1.1 paf 791:
792: // tables
793: {
794: Value *valready=(Value *)tables.get(HEADER_NAME);
795: bool existed=valready!=0;
796: Table *table;
797: if(existed) {
798: // second+ appearence
799: table=valready->get_table();
800: } else {
801: // first appearence
1.14 misha 802: Table::columns_type columns=new ArrayString(1);
1.1 paf 803: *columns+=new String("value");
804: table=new Table(columns);
805: }
806: // this string becomes next row
807: ArrayString& row=*new ArrayString(1);
1.14 misha 808: row+=&HEADER_VALUE;
1.1 paf 809: *table+=&row;
810: // not existed before? add it
811: if(!existed)
812: tables.put(HEADER_NAME, new VTable(table));
813: }
814:
1.14 misha 815: result.headers->put(HEADER_NAME, new VString(HEADER_VALUE));
1.1 paf 816: }
817: }
818:
1.16 misha 819: if(as_text && raw_body_size>=3 && strncmp(raw_body, "\xEF\xBB\xBF", 3)==0){
1.20 misha 820: // skip UTF-8 signature (BOM code)
1.16 misha 821: raw_body+=3;
822: raw_body_size-=3;
823: }
824:
1.1 paf 825: // output response
826: String::C real_body=String::C(raw_body, raw_body_size);
1.16 misha 827:
828: 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 829: // defaulting to used-asked charset [it's never empty!]
830: if(!real_remote_charset)
831: real_remote_charset=asked_remote_charset;
1.16 misha 832:
1.22 misha 833: real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.16 misha 834:
1.1 paf 835: }
836:
837: result.str=const_cast<char *>(real_body.str); // hacking a little
838: result.length=real_body.length;
1.16 misha 839:
1.22 misha 840: if(as_text && result.length)
841: fix_line_breaks(result.str, result.length);
842:
1.1 paf 843: result.headers->put(file_status_name, new VInt(status_code));
1.16 misha 844:
1.1 paf 845: return result;
846: }
E-mail: