Annotation of parser3/src/main/pa_http.C, revision 1.40
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.40 ! misha 8: static const char * const IDENT_HTTP_C="$Date: 2009-09-04 07:31:29 $";
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);
1.39 misha 326: const char* name_cstr=capitalize(name.cstr());
1.38 misha 327:
328: if(strcasecmp(name_cstr, HTTP_CONTENT_LENGTH)==0)
329: return;
330:
1.35 misha 331: String value=attributed_meaning_to_string(*avalue, String::L_URI, false);
1.9 misha 332:
1.35 misha 333: *info->request << name << ": " << value << CRLF;
1.1 paf 334:
1.38 misha 335: if(strcasecmp(name_cstr, HTTP_USER_AGENT)==0)
1.35 misha 336: *info->user_agent_specified=true;
1.38 misha 337: if(strcasecmp(name_cstr, HTTP_CONTENT_TYPE)==0){
1.35 misha 338: *info->content_type_specified=true;
339: *info->content_type_url_encoded=StrStartFromNC(value.cstr(), HTTP_CONTENT_TYPE_FORM_URLENCODED);
340: }
1.1 paf 341: }
342:
1.10 misha 343: static void http_pass_cookie(HashStringValue::key_type name,
1.20 misha 344: HashStringValue::value_type value,
345: Http_pass_header_info *info) {
1.10 misha 346:
1.17 misha 347: *info->request << String(name, String::L_HTTP_COOKIE) << "="
1.31 misha 348: << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, true)
1.10 misha 349: << "; ";
350:
351: }
1.1 paf 352:
353: static const String* basic_authorization_field(const char* user, const char* pass) {
354: if(!user&& !pass)
355: return 0;
356:
357: String combined;
358: if(user)
359: combined<<user;
360: combined<<":";
361: if(pass)
362: combined<<pass;
363:
1.20 misha 364: String* result=new String("Basic ");
365: *result<<pa_base64_encode(combined.cstr(), combined.length());
1.1 paf 366: return result;
367: }
368:
369: static void form_string_value2string(
1.20 misha 370: HashStringValue::key_type key,
371: const String& value,
372: String& result)
1.1 paf 373: {
1.30 misha 374: result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1 paf 375: }
1.20 misha 376:
1.1 paf 377: #ifndef DOXYGEN
378: struct Form_table_value2string_info {
379: HashStringValue::key_type key;
380: String& result;
381:
382: Form_table_value2string_info(HashStringValue::key_type akey, String& aresult):
383: key(akey), result(aresult) {}
384: };
385: #endif
386: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
387: form_string_value2string(info->key, *row->get(0), info->result);
388: }
389: static void form_value2string(
1.20 misha 390: HashStringValue::key_type key,
391: HashStringValue::value_type value,
392: String* result)
1.1 paf 393: {
394: if(const String* svalue=value->get_string())
395: form_string_value2string(key, *svalue, *result);
396: else if(Table* tvalue=value->get_table()) {
397: Form_table_value2string_info info(key, *result);
398: tvalue->for_each(form_table_value2string, &info);
399: } else
1.18 misha 400: throw Exception(PARSER_RUNTIME,
1.1 paf 401: new String(key, String::L_TAINTED),
1.22 misha 402: "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 403: }
1.20 misha 404:
1.5 misha 405: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1 paf 406: String string;
1.3 paf 407: form.for_each<String*>(form_value2string, &string);
1.34 misha 408: return string.transcode_and_untaint_cstr(String::L_URI, &charsets);
1.1 paf 409: }
1.22 misha 410:
411: struct FormPart {
412: Request* r;
413: const char* boundary;
414: String string;
415: Form_table_value2string_info* info;
416: };
417:
1.28 misha 418: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0){
419: part.string << "--" << part.boundary
1.37 misha 420: << CRLF CONTENT_DISPOSITION ": form-data; name=\""
1.28 misha 421: << Charset::transcode(name, part.r->charsets.source(), part.r->charsets.client())
422: << "\"";
1.22 misha 423: if(file_name){
424: if(strcmp(file_name, NONAME_DAT)!=0)
425: part.string << "; filename=\"" << file_name << "\"";
426: part.string << CRLF HTTP_CONTENT_TYPE ": " << part.r->mime_type_of(file_name);
427: }
1.28 misha 428: part.string << CRLF CRLF;
1.22 misha 429: }
430:
431: static void form_string_value2part(
1.28 misha 432: HashStringValue::key_type key,
433: const String& value,
434: FormPart& part)
1.22 misha 435: {
1.28 misha 436: form_part_boundary_header(part, key);
437: part.string << Charset::transcode(value, part.r->charsets.source(), part.r->charsets.client()) << CRLF;
1.22 misha 438: }
439:
440: static void form_file_value2part(
1.28 misha 441: HashStringValue::key_type key,
442: VFile& vfile,
443: FormPart& part)
1.22 misha 444: {
1.28 misha 445: form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.22 misha 446: part.string.append_know_length(vfile.value_ptr(), vfile.value_size(), String::L_FILE_POST);
447: part.string << CRLF;
448: }
449:
450: static void form_table_value2part(Table::element_type row, FormPart* part) {
451: form_string_value2part(part->info->key, *row->get(0), *part);
452: }
453:
454: static void form_value2part(
1.28 misha 455: HashStringValue::key_type key,
456: HashStringValue::value_type value,
457: FormPart& part)
1.22 misha 458: {
459: if(const String* svalue=value->get_string())
460: form_string_value2part(key, *svalue, part);
461: else if(Table* tvalue=value->get_table()) {
462: Form_table_value2string_info info(key, part.string);
463: part.info = &info;
464: tvalue->for_each(form_table_value2part, &part);
1.33 misha 465: } else if(VFile* vfile=static_cast<VFile *>(value->as("file"))){
1.22 misha 466: form_file_value2part(key, *vfile, part);
467: } else
468: throw Exception(PARSER_RUNTIME,
469: new String(key, String::L_TAINTED),
470: "is %s, "HTTP_FORM_NAME" option value can be string, table or file only", value->type());
471: }
472:
473: const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){
474: FormPart formpart;
475: formpart.r=&r;
476: formpart.boundary=boundary;
477: formpart.info=NULL;
478: form.for_each<FormPart&>(form_value2part, formpart);
1.24 misha 479: formpart.string << "--" << boundary << "--";
1.28 misha 480: post_size=formpart.string.length(); // very surprizing, but it calculates correct post_size even with binary files!
1.29 misha 481: return formpart.string.untaint_cstr(String::L_AS_IS); // without transcoding
1.22 misha 482: }
483:
1.1 paf 484: static void find_headers_end(char* p,
485: char*& headers_end_at,
486: char*& raw_body)
487: {
488: raw_body=p;
489: // \n\n
490: // \r\n\r\n
491: while((p=strchr(p, '\n'))) {
492: headers_end_at=++p; // \n>.<
493: if(*p=='\r') // \r\n>\r?<\n
494: p++;
495: if(*p=='\n') { // \r\n\r>\n?<
496: raw_body=p+1;
497: return;
498: }
499: }
500: headers_end_at=0;
501: }
502:
503: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.22 misha 504: File_read_http_result pa_internal_file_read_http(Request& r,
505: const String& file_spec,
1.20 misha 506: bool as_text,
1.15 misha 507: HashStringValue *options,
508: bool transcode_text_result) {
1.1 paf 509: File_read_http_result result;
1.20 misha 510: char host[MAX_STRING];
1.1 paf 511: const char* uri;
512: short port;
1.10 misha 513: const char* method="GET";
1.21 misha 514: bool method_is_get=true;
1.1 paf 515: HashStringValue* form=0;
516: const char* body_cstr=0;
517: int timeout_secs=2;
518: bool fail_on_status_ne_200=true;
1.12 misha 519: bool omit_post_charset=false;
1.1 paf 520: Value* vheaders=0;
1.10 misha 521: Value* vcookies=0;
1.11 misha 522: Value* vbody=0;
1.1 paf 523: Charset *asked_remote_charset=0;
524: const char* user_cstr=0;
525: const char* password_cstr=0;
1.22 misha 526: const char* encode=0;
527: bool multipart=false;
1.1 paf 528:
529: if(options) {
530: int valid_options=pa_get_valid_file_options_count(*options);
531:
532: if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
533: valid_options++;
1.21 misha 534: method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
535: method_is_get=strcmp(method, "GET")==0;
1.1 paf 536: }
1.22 misha 537: if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
538: valid_options++;
539: encode=vencode->as_string().cstr();
540: }
1.1 paf 541: if(Value* vform=options->get(HTTP_FORM_NAME)) {
542: valid_options++;
543: form=vform->get_hash();
544: }
1.11 misha 545: if(vbody=options->get(HTTP_BODY_NAME)) {
1.1 paf 546: valid_options++;
547: }
548: if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
549: valid_options++;
550: timeout_secs=vtimeout->as_int();
551: }
1.11 misha 552: if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1 paf 553: valid_options++;
554: }
1.11 misha 555: if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10 misha 556: valid_options++;
557: }
1.1 paf 558: if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
559: valid_options++;
560: fail_on_status_ne_200=!vany_status->as_bool();
1.12 misha 561: }
1.20 misha 562: if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12 misha 563: valid_options++;
564: omit_post_charset=vomit_post_charset->as_bool();
565: }
1.6 misha 566: if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.23 misha 567: asked_remote_charset=&charsets.get(vcharset_name->as_string().
1.22 misha 568: change_case(r.charsets.source(), String::CC_UPPER));
1.1 paf 569: }
570: if(Value* vuser=options->get(HTTP_USER)) {
571: valid_options++;
572: user_cstr=vuser->as_string().cstr();
573: }
574: if(Value* vpassword=options->get(HTTP_PASSWORD)) {
575: valid_options++;
576: password_cstr=vpassword->as_string().cstr();
577: }
578:
579: if(valid_options!=options->count())
1.7 misha 580: throw Exception(PARSER_RUNTIME,
1.1 paf 581: 0,
1.40 ! misha 582: INVALID_OPTION_PASSED);
1.1 paf 583: }
584: if(!asked_remote_charset) // defaulting to $request:charset
1.22 misha 585: asked_remote_charset=&(r.charsets).source();
586:
587: if(encode){
588: if(method_is_get)
589: throw Exception(PARSER_RUNTIME,
590: 0,
591: "you can not use $."HTTP_FORM_ENCTYPE_NAME" option with method GET");
592:
593: multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
594:
595: if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
596: throw Exception(PARSER_RUNTIME,
597: 0,
598: "$."HTTP_FORM_ENCTYPE_NAME" option value can be "HTTP_CONTENT_TYPE_FORM_URLENCODED" or "HTTP_CONTENT_TYPE_MULTIPART_FORMDATA" only");
599: }
1.1 paf 600:
1.11 misha 601: if(vbody){
602: if(method_is_get)
603: throw Exception(PARSER_RUNTIME,
604: 0,
605: "you can not use $."HTTP_BODY_NAME" option with method GET");
606:
607: if(form)
608: throw Exception(PARSER_RUNTIME,
609: 0,
610: "you can not use options $."HTTP_BODY_NAME" and $."HTTP_FORM_NAME" together");
611: }
1.1 paf 612:
613: //preparing request
1.29 misha 614: String& connect_string=*new String(file_spec);
1.1 paf 615:
616: String request_head_and_body;
617: {
618: // influence URLencoding of tainted pieces to String::L_URI lang
1.22 misha 619: Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1 paf 620:
1.34 misha 621: const char* connect_string_cstr=connect_string.transcode_and_untaint_cstr(String::L_URI, &(r.charsets));
1.1 paf 622:
623: const char* current=connect_string_cstr;
624: if(strncmp(current, "http://", 7)!=0)
1.18 misha 625: throw Exception(PARSER_RUNTIME,
1.1 paf 626: &connect_string,
627: "does not start with http://"); //never
628: current+=7;
629:
630: strncpy(host, current, sizeof(host)-1); host[sizeof(host)-1]=0;
1.34 misha 631: char* host_uri=lsplit(host, '/');
632: uri=host_uri?current+(host_uri-1-host):"/";
633: char* port_cstr=lsplit(host, ':');
1.1 paf 634: char* error_pos=0;
635: port=port_cstr?(short)strtol(port_cstr, &error_pos, 0):80;
636:
1.11 misha 637: // making request head
1.1 paf 638: String head;
1.11 misha 639: head << method << " " << uri;
1.28 misha 640: if(method_is_get && form)
641: head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11 misha 642:
1.37 misha 643: head <<" HTTP/1.0" CRLF "Host: "<< host << CRLF;
1.11 misha 644:
1.28 misha 645: char* boundary=0;
1.22 misha 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:
1.35 misha 659: String user_headers;
660: bool user_agent_specified=false;
661: bool content_type_specified=false;
662: bool content_type_url_encoded=false;
663: if(vheaders && !vheaders->is_string()) { // allow empty
664: if(HashStringValue *headers=vheaders->get_hash()) {
665: Http_pass_header_info info={
666: &(r.charsets),
667: &user_headers,
668: &user_agent_specified,
669: &content_type_specified,
670: &content_type_url_encoded};
671: headers->for_each<Http_pass_header_info*>(http_pass_header, &info);
672: } else
673: throw Exception(PARSER_RUNTIME,
674: 0,
675: "headers param must be hash");
676: };
677:
1.22 misha 678: size_t post_size=0;
679: if(form && !method_is_get) {
1.38 misha 680: head << "Content-Type: " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
1.28 misha 681:
682: if(!omit_post_charset)
683: head << "; charset=" << asked_remote_charset->NAME_CSTR();
684:
1.22 misha 685: if(multipart) {
1.28 misha 686: head << "; boundary=" << boundary;
687: body_cstr=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22 misha 688: } else {
689: body_cstr=pa_form2string(*form, r.charsets);
690: post_size=strlen(body_cstr);
691: }
1.28 misha 692: head << CRLF;
1.35 misha 693: } else if(vbody) {
1.38 misha 694: // $.body was specified
1.35 misha 695: if(content_type_url_encoded){
1.36 misha 696: // transcode + url-encode
1.35 misha 697: body_cstr=vbody->as_string().transcode_and_untaint_cstr(String::L_URI, &(r.charsets));
698: } else {
1.36 misha 699: // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.35 misha 700: body_cstr=Charset::transcode(
701: String::C(vbody->as_string().cstr(), vbody->as_string().length()),
702: r.charsets.source(),
703: *asked_remote_charset
704: );
705: }
1.27 misha 706: post_size=strlen(body_cstr);
1.1 paf 707: }
708:
709: // http://www.ietf.org/rfc/rfc2617.txt
710: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.38 misha 711: head << "Authorization: " << *authorization_field_value << CRLF;
1.1 paf 712:
1.35 misha 713: head << user_headers;
714:
1.1 paf 715: if(!user_agent_specified) // defaulting
1.38 misha 716: head << "User-Agent: " DEFAULT_USER_AGENT CRLF;
1.1 paf 717:
1.12 misha 718: if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
719: throw Exception(PARSER_RUNTIME,
1.35 misha 720: 0,
1.12 misha 721: "$.content-type can't be specified with method POST");
722:
1.11 misha 723: if(vcookies && !vcookies->is_string()){ // allow empty
1.10 misha 724: if(HashStringValue* cookies=vcookies->get_hash()) {
1.37 misha 725: head << "Cookie: ";
1.35 misha 726: Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10 misha 727: cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info);
728: head << CRLF;
729: } else
730: throw Exception(PARSER_RUNTIME,
1.35 misha 731: 0,
1.10 misha 732: "cookies param must be hash");
733: }
734:
1.25 misha 735: if(body_cstr)
1.38 misha 736: head << "Content-Length: " << format(post_size, "%u") << CRLF;
1.1 paf 737:
738: // head + end of header
1.29 misha 739: request_head_and_body << head.untaint_cstr(String::L_AS_IS, 0, &(r.charsets)) << CRLF;
1.8 misha 740:
1.1 paf 741: // body
742: if(body_cstr)
743: request_head_and_body << body_cstr;
744: }
745:
1.28 misha 746: const char* request_cstr=request_head_and_body.cstr();
747: size_t request_size=strlen(request_cstr);
748:
749: if(multipart)
750: request_size=file_untaint(request_cstr, request_size);
751:
1.1 paf 752: char* response;
753: size_t response_size;
1.22 misha 754:
1.28 misha 755: // sending request
1.1 paf 756: int status_code=http_request(response, response_size,
1.28 misha 757: host, port, request_cstr, request_size,
1.1 paf 758: timeout_secs, fail_on_status_ne_200);
759:
1.28 misha 760: // processing results
1.1 paf 761: char* raw_body; size_t raw_body_size;
762: char* headers_end_at;
763: find_headers_end(response,
764: headers_end_at,
765: raw_body);
766: raw_body_size=response_size-(raw_body-response);
767:
768: result.headers=new HashStringValue;
769: VHash* vtables=new VHash;
770: result.headers->put(HTTP_TABLES_NAME, vtables);
771: Charset* real_remote_charset=0; // undetected, yet
772:
773: if(headers_end_at) {
774: *headers_end_at=0;
1.25 misha 775: const String header_block(String::C(response, headers_end_at-response), String::L_TAINTED);
1.1 paf 776:
777: ArrayString aheaders;
778: HashStringValue& tables=vtables->hash();
779:
780: size_t pos_after=0;
781: header_block.split(aheaders, pos_after, "\n");
782:
1.28 misha 783: // processing headers
1.1 paf 784: size_t aheaders_count=aheaders.count();
785: for(size_t i=1; i<aheaders_count; i++) {
786: const String& line=*aheaders.get(i);
787: size_t pos=line.pos(':');
788: if(pos==STRING_NOT_FOUND || pos<1)
789: throw Exception("http.response",
790: &connect_string,
791: "bad response from host - bad header \"%s\"", line.cstr());
1.22 misha 792: const String::Body HEADER_NAME=line.mid(0, pos).change_case(r.charsets.source(), String::CC_UPPER);
1.14 misha 793: const String& HEADER_VALUE=line.mid(pos+1, line.length()).trim(String::TRIM_BOTH, " \t\r");
1.20 misha 794: if(as_text && HEADER_NAME==HTTP_CONTENT_TYPE_UPPER)
1.32 misha 795: real_remote_charset=detect_charset(HEADER_VALUE.cstr());
1.1 paf 796:
797: // tables
798: {
799: Value *valready=(Value *)tables.get(HEADER_NAME);
800: bool existed=valready!=0;
801: Table *table;
802: if(existed) {
803: // second+ appearence
804: table=valready->get_table();
805: } else {
806: // first appearence
1.14 misha 807: Table::columns_type columns=new ArrayString(1);
1.1 paf 808: *columns+=new String("value");
809: table=new Table(columns);
810: }
811: // this string becomes next row
812: ArrayString& row=*new ArrayString(1);
1.14 misha 813: row+=&HEADER_VALUE;
1.1 paf 814: *table+=&row;
815: // not existed before? add it
816: if(!existed)
817: tables.put(HEADER_NAME, new VTable(table));
818: }
819:
1.14 misha 820: result.headers->put(HEADER_NAME, new VString(HEADER_VALUE));
1.1 paf 821: }
822: }
823:
1.16 misha 824: if(as_text && raw_body_size>=3 && strncmp(raw_body, "\xEF\xBB\xBF", 3)==0){
1.20 misha 825: // skip UTF-8 signature (BOM code)
1.16 misha 826: raw_body+=3;
827: raw_body_size-=3;
828: }
829:
1.1 paf 830: // output response
831: String::C real_body=String::C(raw_body, raw_body_size);
1.16 misha 832:
833: 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 834: // defaulting to used-asked charset [it's never empty!]
835: if(!real_remote_charset)
836: real_remote_charset=asked_remote_charset;
1.16 misha 837:
1.22 misha 838: real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.16 misha 839:
1.1 paf 840: }
841:
842: result.str=const_cast<char *>(real_body.str); // hacking a little
843: result.length=real_body.length;
1.16 misha 844:
1.22 misha 845: if(as_text && result.length)
846: fix_line_breaks(result.str, result.length);
847:
1.1 paf 848: result.headers->put(file_status_name, new VInt(status_code));
1.16 misha 849:
1.1 paf 850: return result;
851: }
E-mail: