|
|
1.1 paf 1: /** @file
2: Parser: http support functions.
3:
4: Copyright(c) 2001-2005 ArtLebedev Group (http://www.artlebedev.com)
5: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
6: */
7:
1.3 ! paf 8: static const char * const IDENT_HTTP_C="$Date: 2006/04/09 12:25:04 $";
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"
14:
15: // defines
16:
17: #define HTTP_METHOD_NAME "method"
18: #define HTTP_FORM_NAME "form"
19: #define HTTP_BODY_NAME "body"
20: #define HTTP_TIMEOUT_NAME "timeout"
21: #define HTTP_HEADERS_NAME "headers"
22: #define HTTP_ANY_STATUS_NAME "any-status"
23: #define HTTP_CHARSET_NAME "charset"
24: #define HTTP_TABLES_NAME "tables"
25: #define HTTP_USER "user"
26: #define HTTP_PASSWORD "password"
27:
28: #define DEFAULT_USER_AGENT "parser3"
29:
30: # ifndef INADDR_NONE
31: # define INADDR_NONE ((ulong) -1)
32: # endif
33:
34: #undef CRLF
35: #define CRLF "\r\n"
36:
37: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
38: memset(addr, 0, sizeof(*addr));
39: addr->sin_family=AF_INET;
40: addr->sin_port=htons(port);
41: if(host) {
42: ulong packed_ip=inet_addr(host);
43: if(packed_ip!=INADDR_NONE)
44: memcpy(&addr->sin_addr, &packed_ip, sizeof(packed_ip));
45: else {
46: struct hostent *hostIP=gethostbyname(host);
47: if(hostIP)
48: memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length);
49: else
50: return false;
51: }
52: } else
53: addr->sin_addr.s_addr=INADDR_ANY;
54: return true;
55: }
56:
57: size_t guess_content_length(char* buf) {
58: char* ptr;
59: if((ptr=strstr(buf, "Content-Length:"))) // Apache
60: goto found;
61: if((ptr=strstr(buf, "content-length:"))) // Parser 3
62: goto found;
63: if((ptr=strstr(buf, "Content-length:"))) // maybe 1
64: goto found;
65: if((ptr=strstr(buf, "CONTENT-LENGTH:"))) // maybe 2
66: goto found;
67: return 0;
68: found:
69: char *error_pos;
70: size_t result=(size_t)strtol(ptr+15/*strlen("CONTENT-LENGTH:")*/, &error_pos, 0);
71:
72: const size_t reasonable_initial_max=0x400*0x400*10 /*10M*/;
73: if(result>reasonable_initial_max) // sanity check
74: return reasonable_initial_max;
75: return 0;//result;
76: }
77:
78: static int http_read_response(char*& response, size_t& response_size, int sock, bool fail_on_status_ne_200) {
79: int result=0;
80: // fetching some to local buffer, guessing on possible content-length
81: response_size=0x400*20; // initial size if content-length could not be determined
82: const size_t preview_size=0x400*20;
83: char preview_buf[preview_size+1/*terminator*/]; // 20K buffer to preview headers
84: ssize_t received_size=recv(sock, preview_buf, preview_size, 0);
85: if(received_size==0)
86: goto done;
87: if(received_size<0) {
88: if(int no=pa_socks_errno())
89: throw Exception("http.timeout",
90: 0,
91: "error receiving response header: %s (%d)", pa_socks_strerr(no), no);
92: goto done;
93: }
1.2 paf 94: // terminator [helps futher string searches]
95: preview_buf[received_size]=0;
96: // checking status
97: if(char* EOLat=strstr(preview_buf, "\n")) {
98: const String status_line(pa_strdup(preview_buf, EOLat-preview_buf));
99: ArrayString astatus;
100: size_t pos_after=0;
101: status_line.split(astatus, pos_after, " ");
102: const String& status_code=*astatus.get(astatus.count()>1?1:0);
103: result=status_code.as_int();
104:
105: if(fail_on_status_ne_200 && result!=200)
106: throw Exception("http.status",
107: &status_code,
108: "invalid HTTP response status");
109: }
1.1 paf 110: // detecting response_size
111: {
112: if(size_t content_length=guess_content_length(preview_buf))
113: response_size=preview_size+content_length; // a little more than needed, will adjust response_size by actual received size later
114: }
115:
116: // [gcc is happier this way, see goto above]
117: {
118: // allocating initial buf
119: response=(char*)pa_malloc_atomic(response_size+1/*terminator*/); // just setting memory block type
120: char* ptr=response;
121: size_t todo_size=response_size;
122: // coping part of already received body
123: memcpy(ptr, preview_buf, received_size);
124: ptr+=received_size;
125: todo_size-=received_size;
126:
127: // we use terminator byte for two purposes here:
128: // 1. we return there zero always, not knowing: maybe they would want to create String form $file.body?
129: // invariant: all Strings should have zero-terminated buffers
130: // 2. we use that out-of-size byte to detect if our content-length guess was wrong
131: // when recv gets more than we expected
132: // a) we know that the content-length guess was wrong
133: // b) we have space to put the first byte of extra data
134: // c) we use less code to detect normal situation: on last while-cycle recv expected to just return 0
135: while(true) {
136: received_size=recv(sock, ptr, todo_size+1/*there is always a place for terminator*/, 0);
137: if(received_size==0) {
138: response_size-=todo_size; // in case we received less than expected, cut down the reported size
139: break;
140: }
141: if(received_size<0) {
142: if(int no=pa_socks_errno())
143: throw Exception("http.timeout",
144: 0,
145: "error receiving response body: %s (%d)", pa_socks_strerr(no), no);
146: break;
147: }
148: // they've touched the terminator?
149: if((size_t)received_size>todo_size)
150: {
151: // that means that our guessed response_size was not big enough
152: const size_t grow_chunk_size=0x400*0x400; // 1M
153: response_size+=grow_chunk_size;
154: size_t ptr_offset=ptr-response;
155: response=(char*)pa_realloc(response, response_size+1/*terminator*/);
156: ptr=response+ptr_offset;
157: todo_size+=grow_chunk_size;
158: }
159: // can't do this before realloc: we need <todo_size check
160: ptr+=received_size;
161: todo_size-=received_size;
162: }
163: }
164: done:
165: if(result)
166: {
167: response[response_size]=0;
168: return result;
169: }
170: else
171: throw Exception("http.response",
172: 0,
173: "bad response from host - no status found (size=%u)", response_size);
174: }
175:
176: /* ********************** request *************************** */
177:
178: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
179: # define PA_USE_ALARM
180: #endif
181:
182: #ifdef PA_USE_ALARM
183: static sigjmp_buf timeout_env;
184: static void timeout_handler(int /*sig*/){
185: siglongjmp(timeout_env, 1);
186: }
187: #endif
188:
189: static int http_request(char*& response, size_t& response_size,
190: const char* host, short port,
191: const char* request,
192: int timeout_secs,
193: bool fail_on_status_ne_200) {
194: if(!host)
195: throw Exception("http.host",
196: 0,
197: "zero hostname"); //never
198:
199: volatile // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning]
200: int sock=-1;
201: #ifdef PA_USE_ALARM
202: signal(SIGALRM, timeout_handler);
203: #endif
204: #ifdef PA_USE_ALARM
205: if(sigsetjmp(timeout_env, 1)) {
206: // stupid gcc [2.95.4] generated bad code
207: // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
208: // rewritten simplier [athough duplicating closesocket code]
209: if(sock>=0)
210: closesocket(sock);
211: throw Exception("http.timeout",
212: 0,
213: "timeout occured while retrieving document");
214: return 0; // never
215: } else {
216: alarm(timeout_secs);
217: #endif
218: try {
219: int result;
220: struct sockaddr_in dest;
221:
222: if(!set_addr(&dest, host, port))
223: throw Exception("http.host",
224: 0,
225: "can not resolve hostname \"%s\"", host);
226:
227: if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0) {
228: int no=pa_socks_errno();
229: throw Exception("http.connect",
230: 0,
231: "can not make socket: %s (%d)", pa_socks_strerr(no), no);
232: }
233:
234: // To enable SO_DONTLINGER (that is, disable SO_LINGER)
235: // l_onoff should be set to zero and setsockopt should be called
236: linger dont_linger={0,0};
237: setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger));
238:
239: #ifdef WIN32
240: // SO_*TIMEO can be defined in .h but not implemlemented in protocol,
241: // failing subsequently with Option not supported by protocol (99) message
242: // could not suppress that, so leaving this only for win32
243: int timeout_ms=timeout_secs*1000;
244: setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
245: setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
246: #endif
247:
248: if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
249: int no=pa_socks_errno();
250: throw Exception("http.connect",
251: 0,
252: "can not connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no);
253: }
254: size_t request_size=strlen(request);
255: if(send(sock, request, request_size, 0)!=(ssize_t)request_size) {
256: int no=pa_socks_errno();
257: throw Exception("http.timeout",
258: 0,
259: "error sending request: %s (%d)", pa_socks_strerr(no), no);
260: }
261:
262: result=http_read_response(response, response_size, sock, fail_on_status_ne_200);
263: closesocket(sock);
264: #ifdef PA_USE_ALARM
265: alarm(0);
266: #endif
267: return result;
268: } catch(...) {
269: #ifdef PA_USE_ALARM
270: alarm(0);
271: #endif
272: if(sock>=0)
273: closesocket(sock);
274: rethrow;
275: }
276: #ifdef PA_USE_ALARM
277: }
278: #endif
279: }
280:
281: #ifndef DOXYGEN
282: struct Http_pass_header_info {
283: Request_charsets* charsets;
284: String* request;
285: bool user_agent_specified;
286: };
287: #endif
288: static void http_pass_header(HashStringValue::key_type key,
289: HashStringValue::value_type value,
290: Http_pass_header_info *info) {
291: *info->request <<key<<": "
292: << attributed_meaning_to_string(*value, String::L_HTTP_HEADER, false)
293: << CRLF;
294:
295: if(String(key, String::L_TAINTED).change_case(info->charsets->source(), String::CC_UPPER)=="USER-AGENT")
296: info->user_agent_specified=true;
297: }
298:
299:
300: static Charset* detect_charset(Charset& source_charset, const String& content_type_value) {
301: const String::Body CONTENT_TYPE_VALUE=
302: content_type_value.change_case(source_charset, String::CC_UPPER);
303: // content-type: xxx/xxx; source_charset=WE-NEED-THIS
304: // content-type: xxx/xxx; source_charset="WE-NEED-THIS"
305: // content-type: xxx/xxx; source_charset="WE-NEED-THIS";
306: size_t before_charseteq_pos=CONTENT_TYPE_VALUE.pos("CHARSET=");
307: if(before_charseteq_pos!=STRING_NOT_FOUND) {
308: size_t charset_begin=before_charseteq_pos+8/*CHARSET="*/;
309: size_t open_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
310: bool quoted=open_quote_pos==charset_begin;
311: if(quoted)
312: charset_begin++; // skip opening '"'
313: size_t charset_end=CONTENT_TYPE_VALUE.length();
314: if(quoted) {
315: size_t close_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
316: if(close_quote_pos!=STRING_NOT_FOUND)
317: charset_end=close_quote_pos;
318: } else {
319: size_t delim_pos=CONTENT_TYPE_VALUE.pos(';', charset_begin);
320: if(delim_pos!=STRING_NOT_FOUND)
321: charset_end=delim_pos;
322: }
323: const String::Body CHARSET_NAME_BODY=
324: CONTENT_TYPE_VALUE.mid(charset_begin, charset_end);
325:
326: return &charsets.get(CHARSET_NAME_BODY);
327: }
328:
329: return 0;
330: }
331:
332: static const String* basic_authorization_field(const char* user, const char* pass) {
333: if(!user&& !pass)
334: return 0;
335:
336: String combined;
337: if(user)
338: combined<<user;
339: combined<<":";
340: if(pass)
341: combined<<pass;
342:
343: String* result=new String("Basic "); *result<<pa_base64_encode(combined.cstr(), combined.length());
344: return result;
345: }
346:
347: static void form_string_value2string(
348: HashStringValue::key_type key,
349: const String& value,
350: String& result)
351: {
352: result << String(key, String::L_URI) << "=";
353: result.append(value, String::L_URI, true);
354: result<< "&";
355: }
356: #ifndef DOXYGEN
357: struct Form_table_value2string_info {
358: HashStringValue::key_type key;
359: String& result;
360:
361: Form_table_value2string_info(HashStringValue::key_type akey, String& aresult):
362: key(akey), result(aresult) {}
363: };
364: #endif
365: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
366: form_string_value2string(info->key, *row->get(0), info->result);
367: }
368: static void form_value2string(
369: HashStringValue::key_type key,
370: HashStringValue::value_type value,
371: String* result)
372: {
373: if(const String* svalue=value->get_string())
374: form_string_value2string(key, *svalue, *result);
375: else if(Table* tvalue=value->get_table()) {
376: Form_table_value2string_info info(key, *result);
377: tvalue->for_each(form_table_value2string, &info);
378: } else
379: throw Exception(0,
380: new String(key, String::L_TAINTED),
381: "is %s, "HTTP_FORM_NAME" option value must either string or table", value->type());
382: }
383: const char* pa_form2string(HashStringValue& form) {
384: String string;
1.3 ! paf 385: form.for_each<String*>(form_value2string, &string);
1.1 paf 386: return string.cstr(String::L_UNSPECIFIED);
387: }
388: static void find_headers_end(char* p,
389: char*& headers_end_at,
390: char*& raw_body)
391: {
392: raw_body=p;
393: // \n\n
394: // \r\n\r\n
395: while((p=strchr(p, '\n'))) {
396: headers_end_at=++p; // \n>.<
397: if(*p=='\r') // \r\n>\r?<\n
398: p++;
399: if(*p=='\n') { // \r\n\r>\n?<
400: raw_body=p+1;
401: return;
402: }
403: }
404: headers_end_at=0;
405: }
406:
407: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
408: File_read_http_result pa_internal_file_read_http(Request_charsets& charsets,
409: const String& file_spec,
410: bool as_text,
411: HashStringValue *options) {
412: File_read_http_result result;
413: char host[MAX_STRING];
414: const char* uri;
415: short port;
416: const char* method="GET"; bool method_is_get;
417: HashStringValue* form=0;
418: const char* body_cstr=0;
419: int timeout_secs=2;
420: bool fail_on_status_ne_200=true;
421: Value* vheaders=0;
422: Charset *asked_remote_charset=0;
423: const char* user_cstr=0;
424: const char* password_cstr=0;
425:
426: if(options) {
427: int valid_options=pa_get_valid_file_options_count(*options);
428:
429: if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
430: valid_options++;
431: method=vmethod->as_string().cstr();
432: }
433: if(Value* vform=options->get(HTTP_FORM_NAME)) {
434: valid_options++;
435: form=vform->get_hash();
436: }
437: if(Value* vbody=options->get(HTTP_BODY_NAME)) {
438: valid_options++;
439: body_cstr=vbody->as_string().cstr(String::L_UNSPECIFIED);
440: }
441: if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
442: valid_options++;
443: timeout_secs=vtimeout->as_int();
444: }
445: if((vheaders=options->get(HTTP_HEADERS_NAME))) {
446: valid_options++;
447: }
448: if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
449: valid_options++;
450: fail_on_status_ne_200=!vany_status->as_bool();
451: }
452: if(Value* vcharset_name=options->get(HTTP_CHARSET_NAME)) {
453: valid_options++;
454: asked_remote_charset=&::charsets.get(vcharset_name->as_string().
455: change_case(charsets.source(), String::CC_UPPER));
456: }
457: if(Value* vuser=options->get(HTTP_USER)) {
458: valid_options++;
459: user_cstr=vuser->as_string().cstr();
460: }
461: if(Value* vpassword=options->get(HTTP_PASSWORD)) {
462: valid_options++;
463: password_cstr=vpassword->as_string().cstr();
464: }
465:
466: if(valid_options!=options->count())
467: throw Exception("parser.runtime",
468: 0,
469: "invalid option passed");
470: }
471: if(!asked_remote_charset) // defaulting to $request:charset
472: asked_remote_charset=&charsets.source();
473:
474: method_is_get=strcmp(method, "GET")==0;
475: if(method_is_get && body_cstr)
476: throw Exception("parser.runtime",
477: 0,
478: "you can not use $."HTTP_BODY_NAME" option with method GET");
479:
480: //preparing request
481: String& connect_string=*new String;
482: // not in ^sql{... L_SQL ...} spirit, but closer to ^file::load one
483: connect_string.append(file_spec, String::L_URI); // tainted pieces -> URI pieces
484:
485: String request_head_and_body;
486: {
487: // influence URLencoding of tainted pieces to String::L_URI lang
488: Temp_client_charset temp(charsets, *asked_remote_charset);
489:
490: const char* connect_string_cstr=connect_string.cstr(String::L_UNSPECIFIED);
491:
492: const char* current=connect_string_cstr;
493: if(strncmp(current, "http://", 7)!=0)
494: throw Exception(0,
495: &connect_string,
496: "does not start with http://"); //never
497: current+=7;
498:
499: strncpy(host, current, sizeof(host)-1); host[sizeof(host)-1]=0;
500: char* host_uri=lsplit(host, '/');
501: uri=host_uri?current+(host_uri-1-host):"/";
502: char* port_cstr=lsplit(host, ':');
503: char* error_pos=0;
504: port=port_cstr?(short)strtol(port_cstr, &error_pos, 0):80;
505:
506: bool uri_has_query_string=strchr(uri, '?')!=0;
507:
508: //making request head
509: String head;
510: head << method;
511: head << " " << uri;
512: if(form)
513: if(method_is_get)
514: head << (uri_has_query_string?"&":"?") << pa_form2string(*form);
515: head <<" HTTP/1.0" CRLF
516: "host: "<< host << CRLF;
517: if(form && !method_is_get) {
518: head << "content-type: application/x-www-form-urlencoded" CRLF;
519: body_cstr = pa_form2string(*form);
520: }
521:
522: // http://www.ietf.org/rfc/rfc2617.txt
523: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
524: head<<"authorization: "<<*authorization_field_value<<CRLF;
525:
526: bool user_agent_specified=false;
527: if(vheaders && !vheaders->is_string()) { // allow empty
528: if(HashStringValue *headers=vheaders->get_hash()) {
529: Http_pass_header_info info={&charsets, &head, false};
1.3 ! paf 530: headers->for_each<Http_pass_header_info*>(http_pass_header, &info);
1.1 paf 531: user_agent_specified=info.user_agent_specified;
532: } else
533: throw Exception("parser.runtime",
534: &connect_string,
535: "headers param must be hash");
536: };
537: if(!user_agent_specified) // defaulting
538: head << "user-agent: " DEFAULT_USER_AGENT CRLF;
539:
540: if(body_cstr) {
541: // recode those pieces which are not in String::L_URI lang
542: // [those violating HTTP standard, but widly used]
543: body_cstr=Charset::transcode(
544: String::C(body_cstr, strlen(body_cstr)),
545: charsets.source(),
546: *asked_remote_charset);
547:
548: head << "content-length: " << format(strlen(body_cstr), "%u") << CRLF;
549: }
550:
551: const char* head_cstr=head.cstr(String::L_UNSPECIFIED);
552:
553: // recode those pieces which are not in String::L_URI lang
554: // [those violating HTTP standard, but widly used]
555: head_cstr=Charset::transcode(
556: String::C(head_cstr, strlen(head_cstr)),
557: charsets.source(),
558: *asked_remote_charset);
559:
560: // head + end of header
561: request_head_and_body << head_cstr << CRLF;
562: // body
563: if(body_cstr)
564: request_head_and_body << body_cstr;
565: }
566:
567: //sending request
568: char* response;
569: size_t response_size;
570: int status_code=http_request(response, response_size,
571: host, port, request_head_and_body.cstr(),
572: timeout_secs, fail_on_status_ne_200);
573:
574: //processing results
575: char* raw_body; size_t raw_body_size;
576: char* headers_end_at;
577: find_headers_end(response,
578: headers_end_at,
579: raw_body);
580: raw_body_size=response_size-(raw_body-response);
581:
582: result.headers=new HashStringValue;
583: VHash* vtables=new VHash;
584: result.headers->put(HTTP_TABLES_NAME, vtables);
585: Charset* real_remote_charset=0; // undetected, yet
586:
587: if(headers_end_at) {
588: *headers_end_at=0;
589: const String header_block(String::C(response, headers_end_at-response), true);
590:
591: ArrayString aheaders;
592: HashStringValue& tables=vtables->hash();
593:
594: size_t pos_after=0;
595: header_block.split(aheaders, pos_after, "\n");
596:
597: //processing headers
598: size_t aheaders_count=aheaders.count();
599: for(size_t i=1; i<aheaders_count; i++) {
600: const String& line=*aheaders.get(i);
601: size_t pos=line.pos(':');
602: if(pos==STRING_NOT_FOUND || pos<1)
603: throw Exception("http.response",
604: &connect_string,
605: "bad response from host - bad header \"%s\"", line.cstr());
606: const String::Body HEADER_NAME=
607: line.mid(0, pos).change_case(charsets.source(), String::CC_UPPER);
608: const String& header_value=line.mid(pos+1, line.length()).trim(String::TRIM_BOTH, " \t\r");
609: if(as_text && HEADER_NAME=="CONTENT-TYPE")
610: real_remote_charset=detect_charset(charsets.source(), header_value);
611:
612: // tables
613: {
614: Value *valready=(Value *)tables.get(HEADER_NAME);
615: bool existed=valready!=0;
616: Table *table;
617: if(existed) {
618: // second+ appearence
619: table=valready->get_table();
620: } else {
621: // first appearence
622: Table::columns_type columns =new ArrayString(1);
623: *columns+=new String("value");
624: table=new Table(columns);
625: }
626: // this string becomes next row
627: ArrayString& row=*new ArrayString(1);
628: row+=&header_value;
629: *table+=&row;
630: // not existed before? add it
631: if(!existed)
632: tables.put(HEADER_NAME, new VTable(table));
633: }
634:
635: result.headers->put(HEADER_NAME, new VString(header_value));
636: }
637: }
638:
639: // output response
640: String::C real_body=String::C(raw_body, raw_body_size);
641: if(as_text && raw_body_size) { // must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
642: // defaulting to used-asked charset [it's never empty!]
643: if(!real_remote_charset)
644: real_remote_charset=asked_remote_charset;
645: real_body=Charset::transcode(real_body, *real_remote_charset, charsets.source());
646: }
647:
648: result.str=const_cast<char *>(real_body.str); // hacking a little
649: result.length=real_body.length;
650: result.headers->put(file_status_name, new VInt(status_code));
651: return result;
652: }