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