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

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

E-mail: