Annotation of parser3/src/main/pa_http.C, revision 1.12

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

E-mail: