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