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