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

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.16    ! misha       8: static const char * const IDENT_HTTP_C="$Date: 2008-06-11 11:38:35 $"; 
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 const String* basic_authorization_field(const char* user, const char* pass) {
                    321:        if(!user&& !pass)
                    322:                return 0;
                    323: 
                    324:        String combined;  
                    325:        if(user)
                    326:                combined<<user;
                    327:        combined<<":";
                    328:        if(pass)
                    329:                combined<<pass;
                    330:        
                    331:        String* result=new String("Basic "); *result<<pa_base64_encode(combined.cstr(), combined.length());
                    332:        return result;
                    333: }
                    334: 
                    335: static void form_string_value2string(
                    336:                                                                  HashStringValue::key_type key, 
                    337:                                                                  const String& value, 
                    338:                                                                  String& result) 
                    339: {
                    340:        result << String(key, String::L_URI) << "=";
                    341:        result.append(value, String::L_URI, true);
                    342:        result<< "&";
                    343: }
                    344: #ifndef DOXYGEN
                    345: struct Form_table_value2string_info {
                    346:        HashStringValue::key_type key;
                    347:        String& result;
                    348: 
                    349:        Form_table_value2string_info(HashStringValue::key_type akey, String& aresult): 
                    350:                key(akey), result(aresult) {}
                    351: };
                    352: #endif
                    353: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
                    354:        form_string_value2string(info->key, *row->get(0), info->result);
                    355: }
                    356: static void form_value2string(
                    357:                                                                  HashStringValue::key_type key, 
                    358:                                                                  HashStringValue::value_type value, 
                    359:                                                                  String* result) 
                    360: {
                    361:        if(const String* svalue=value->get_string())
                    362:                form_string_value2string(key, *svalue, *result);
                    363:        else if(Table* tvalue=value->get_table()) {
                    364:                Form_table_value2string_info info(key, *result);
                    365:                tvalue->for_each(form_table_value2string, &info);
                    366:        } else
                    367:                throw Exception(0,
                    368:                        new String(key, String::L_TAINTED),
                    369:                        "is %s, "HTTP_FORM_NAME" option value must either string or table", value->type());
                    370: }
1.5       misha     371: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1       paf       372:        String string;
1.3       paf       373:        form.for_each<String*>(form_value2string, &string);
1.5       misha     374:        return string.cstr(String::L_UNSPECIFIED, 0, &charsets);
1.1       paf       375: }
                    376: static void find_headers_end(char* p,
                    377:                char*& headers_end_at,
                    378:                char*& raw_body)
                    379: {
                    380:        raw_body=p;
                    381:        // \n\n
                    382:        // \r\n\r\n
                    383:        while((p=strchr(p, '\n'))) {
                    384:                headers_end_at=++p; // \n>.<
                    385:                if(*p=='\r')  // \r\n>\r?<\n
                    386:                        p++;
                    387:                if(*p=='\n') { // \r\n\r>\n?<
                    388:                        raw_body=p+1;
                    389:                        return;                 
                    390:                }
                    391:        }
                    392:        headers_end_at=0;
                    393: }
                    394: 
                    395: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
                    396: File_read_http_result pa_internal_file_read_http(Request_charsets& charsets, 
                    397:                                            const String& file_spec, 
                    398:                                            bool as_text,
1.15      misha     399:                                                HashStringValue *options,
                    400:                                                bool transcode_text_result) {
1.1       paf       401:        File_read_http_result result;
                    402:        char host[MAX_STRING]; 
                    403:        const char* uri; 
                    404:        short port;
1.10      misha     405:        const char* method="GET";
1.1       paf       406:        HashStringValue* form=0;
                    407:        const char* body_cstr=0;
                    408:        int timeout_secs=2;
                    409:        bool fail_on_status_ne_200=true;
1.12      misha     410:        bool omit_post_charset=false;
1.1       paf       411:        Value* vheaders=0;
1.10      misha     412:        Value* vcookies=0;
1.11      misha     413:        Value* vbody=0;
1.1       paf       414:        Charset *asked_remote_charset=0;
                    415:        const char* user_cstr=0;
                    416:        const char* password_cstr=0;
                    417: 
                    418:        if(options) {
                    419:                int valid_options=pa_get_valid_file_options_count(*options);
                    420: 
                    421:                if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
                    422:                        valid_options++;
                    423:                        method=vmethod->as_string().cstr();
                    424:                }
                    425:                if(Value* vform=options->get(HTTP_FORM_NAME)) {
                    426:                        valid_options++;
                    427:                        form=vform->get_hash(); 
                    428:                } 
1.11      misha     429:                if(vbody=options->get(HTTP_BODY_NAME)) {
1.1       paf       430:                        valid_options++;
                    431:                } 
                    432:                if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
                    433:                        valid_options++;
                    434:                        timeout_secs=vtimeout->as_int(); 
                    435:                } 
1.11      misha     436:                if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1       paf       437:                        valid_options++;
                    438:                } 
1.11      misha     439:                if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10      misha     440:                        valid_options++;
                    441:                } 
1.1       paf       442:                if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
                    443:                        valid_options++;
                    444:                        fail_on_status_ne_200=!vany_status->as_bool(); 
1.12      misha     445:                }
                    446:                if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET)){
                    447:                        valid_options++;
                    448:                        omit_post_charset=vomit_post_charset->as_bool();
                    449:                }
1.6       misha     450:                if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.1       paf       451:                        asked_remote_charset=&::charsets.get(vcharset_name->as_string().
                    452:                                change_case(charsets.source(), String::CC_UPPER));
                    453:                } 
                    454:                if(Value* vuser=options->get(HTTP_USER)) {
                    455:                        valid_options++;
                    456:                        user_cstr=vuser->as_string().cstr();
                    457:                } 
                    458:                if(Value* vpassword=options->get(HTTP_PASSWORD)) {
                    459:                        valid_options++;
                    460:                        password_cstr=vpassword->as_string().cstr();
                    461:                }
                    462: 
                    463:                if(valid_options!=options->count())
1.7       misha     464:                        throw Exception(PARSER_RUNTIME,
1.1       paf       465:                                0,
                    466:                                "invalid option passed");
                    467:        }
                    468:        if(!asked_remote_charset) // defaulting to $request:charset
                    469:                asked_remote_charset=&charsets.source();
                    470: 
1.10      misha     471:        bool method_is_get=strcmp(method, "GET")==0;
1.11      misha     472:        if(vbody){
                    473:                if(method_is_get)
                    474:                        throw Exception(PARSER_RUNTIME,
                    475:                                0,
                    476:                                "you can not use $."HTTP_BODY_NAME" option with method GET");
                    477: 
                    478:                if(form)
                    479:                        throw Exception(PARSER_RUNTIME,
                    480:                                0,
                    481:                                "you can not use options $."HTTP_BODY_NAME" and $."HTTP_FORM_NAME" together");
                    482:        }
1.1       paf       483: 
                    484:        //preparing request
                    485:        String& connect_string=*new String;
                    486:        // not in ^sql{... L_SQL ...} spirit, but closer to ^file::load one
                    487:        connect_string.append(file_spec, String::L_URI); // tainted pieces -> URI pieces
                    488: 
                    489:        String request_head_and_body;
                    490:        {
                    491:                // influence URLencoding of tainted pieces to String::L_URI lang
                    492:                Temp_client_charset temp(charsets, *asked_remote_charset);
                    493: 
1.5       misha     494:                const char* connect_string_cstr=connect_string.cstr(String::L_UNSPECIFIED, 0, &charsets); 
1.1       paf       495: 
                    496:                const char* current=connect_string_cstr;
                    497:                if(strncmp(current, "http://", 7)!=0)
                    498:                        throw Exception(0, 
                    499:                                &connect_string, 
                    500:                                "does not start with http://"); //never
                    501:                current+=7;
                    502: 
                    503:                strncpy(host, current, sizeof(host)-1);  host[sizeof(host)-1]=0;
                    504:                char* host_uri=lsplit(host, '/'); 
                    505:                uri=host_uri?current+(host_uri-1-host):"/"; 
                    506:                char* port_cstr=lsplit(host, ':'); 
                    507:                char* error_pos=0;
                    508:                port=port_cstr?(short)strtol(port_cstr, &error_pos, 0):80;
                    509: 
                    510:                bool uri_has_query_string=strchr(uri, '?')!=0;
                    511: 
1.11      misha     512:                // making request head
1.1       paf       513:                String head;
1.11      misha     514:                head << method << " " << uri;
                    515:                if(form && method_is_get)
                    516:                        head << (uri_has_query_string?"&":"?") << pa_form2string(*form, charsets);
                    517: 
                    518:                head <<" HTTP/1.0" CRLF "host: "<< host << CRLF;
                    519: 
1.12      misha     520:                if(form && !method_is_get) { // POST
                    521:                        head << "content-type: " << HTTP_CONTENT_TYPE_FORM_URLENCODED;
                    522:                        if(!omit_post_charset)
                    523:                                head << "; charset=" << asked_remote_charset->NAME_CSTR() << ";";
                    524:                        head << CRLF;
1.11      misha     525:                        body_cstr=pa_form2string(*form, charsets);
                    526:                }  else if (vbody) {
                    527:                        body_cstr=vbody->as_string().cstr(String::L_UNSPECIFIED, 0, &charsets);
                    528:                        // needed for transcoded $.body[] first of all
                    529:                        body_cstr=Charset::transcode(
                    530:                                String::C(body_cstr, strlen(body_cstr)),
                    531:                                charsets.source(),
                    532:                                *asked_remote_charset
                    533:                        );
1.1       paf       534:                }
                    535: 
                    536:                // http://www.ietf.org/rfc/rfc2617.txt
                    537:                if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
                    538:                        head<<"authorization: "<<*authorization_field_value<<CRLF;
                    539: 
                    540:                bool user_agent_specified=false;
1.12      misha     541:                bool content_type_specified=false;
1.1       paf       542:                if(vheaders && !vheaders->is_string()) { // allow empty
                    543:                        if(HashStringValue *headers=vheaders->get_hash()) {
                    544:                                Http_pass_header_info info={&charsets, &head, false};
1.3       paf       545:                                headers->for_each<Http_pass_header_info*>(http_pass_header, &info); 
1.1       paf       546:                                user_agent_specified=info.user_agent_specified;
1.12      misha     547:                                content_type_specified=info.content_type_specified;
1.1       paf       548:                        } else
1.7       misha     549:                                throw Exception(PARSER_RUNTIME, 
1.1       paf       550:                                        &connect_string,
                    551:                                        "headers param must be hash"); 
                    552:                };
                    553:                if(!user_agent_specified) // defaulting
                    554:                        head << "user-agent: " DEFAULT_USER_AGENT CRLF;
                    555: 
1.12      misha     556:                if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
                    557:                        throw Exception(PARSER_RUNTIME,
                    558:                                &connect_string,
                    559:                                "$.content-type can't be specified with method POST"); 
                    560: 
1.11      misha     561:                if(vcookies && !vcookies->is_string()){ // allow empty
1.10      misha     562:                        if(HashStringValue* cookies=vcookies->get_hash()) {
                    563:                                head << "cookie: ";
                    564:                                Http_pass_header_info info={&charsets, &head, false};
                    565:                                cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info); 
                    566:                                head << CRLF;
                    567:                        } else
                    568:                                throw Exception(PARSER_RUNTIME, 
                    569:                                        &connect_string,
                    570:                                        "cookies param must be hash"); 
                    571:                }
                    572: 
1.1       paf       573:                if(body_cstr) {
                    574:                        head << "content-length: " << format(strlen(body_cstr), "%u") << CRLF;
                    575:                }
                    576: 
1.6       misha     577:                const char* head_cstr=head.cstr(String::L_UNSPECIFIED, 0, &charsets);
1.1       paf       578: 
                    579:                // head + end of header
                    580:                request_head_and_body << head_cstr << CRLF;
1.8       misha     581: 
1.1       paf       582:                // body
                    583:                if(body_cstr)
                    584:                        request_head_and_body << body_cstr;
                    585:        }
                    586:        
                    587:        //sending request
                    588:        char* response;
                    589:        size_t response_size;
                    590:        int status_code=http_request(response, response_size,
                    591:                host, port, request_head_and_body.cstr(), 
                    592:                timeout_secs, fail_on_status_ne_200); 
                    593:        
                    594:        //processing results    
                    595:        char* raw_body; size_t raw_body_size;
                    596:        char* headers_end_at;
                    597:        find_headers_end(response, 
                    598:                headers_end_at,
                    599:                raw_body);
                    600:        raw_body_size=response_size-(raw_body-response);
                    601:        
                    602:        result.headers=new HashStringValue;
                    603:        VHash* vtables=new VHash;
                    604:        result.headers->put(HTTP_TABLES_NAME, vtables);
                    605:        Charset* real_remote_charset=0; // undetected, yet
                    606: 
                    607:        if(headers_end_at) {
                    608:                *headers_end_at=0;
                    609:                const String header_block(String::C(response, headers_end_at-response), true);
                    610:                
                    611:                ArrayString aheaders;
                    612:                HashStringValue& tables=vtables->hash();
                    613: 
                    614:                size_t pos_after=0;
                    615:                header_block.split(aheaders, pos_after, "\n"); 
                    616:                
                    617:                //processing headers
                    618:                size_t aheaders_count=aheaders.count();
                    619:                for(size_t i=1; i<aheaders_count; i++) {
                    620:                        const String& line=*aheaders.get(i);
                    621:                        size_t pos=line.pos(':'); 
                    622:                        if(pos==STRING_NOT_FOUND || pos<1)
                    623:                                throw Exception("http.response", 
                    624:                                        &connect_string,
                    625:                                        "bad response from host - bad header \"%s\"", line.cstr());
1.14      misha     626:                        const String::Body HEADER_NAME=line.mid(0, pos).change_case(charsets.source(), String::CC_UPPER);
                    627:                        const String& HEADER_VALUE=line.mid(pos+1, line.length()).trim(String::TRIM_BOTH, " \t\r");
1.12      misha     628:                        if(as_text && HEADER_NAME==HTTP_CONTENT_TYPE)
1.14      misha     629:                                real_remote_charset=detect_charset(charsets.source(), HEADER_VALUE);
1.1       paf       630: 
                    631:                        // tables
                    632:                        {
                    633:                                Value *valready=(Value *)tables.get(HEADER_NAME);
                    634:                                bool existed=valready!=0;
                    635:                                Table *table;
                    636:                                if(existed) {
                    637:                                        // second+ appearence
                    638:                                        table=valready->get_table();
                    639:                                } else {
                    640:                                        // first appearence
1.14      misha     641:                                        Table::columns_type columns=new ArrayString(1);
1.1       paf       642:                                        *columns+=new String("value");
                    643:                                        table=new Table(columns);
                    644:                                }
                    645:                                // this string becomes next row
                    646:                                ArrayString& row=*new ArrayString(1);
1.14      misha     647:                                row+=&HEADER_VALUE;
1.1       paf       648:                                *table+=&row;
                    649:                                // not existed before? add it
                    650:                                if(!existed)
                    651:                                        tables.put(HEADER_NAME, new VTable(table));
                    652:                        }
                    653: 
1.14      misha     654:                        result.headers->put(HEADER_NAME, new VString(HEADER_VALUE));
1.1       paf       655:                }
                    656:        }
                    657: 
1.16    ! misha     658:        if(as_text && raw_body_size>=3 && strncmp(raw_body, "\xEF\xBB\xBF", 3)==0){
        !           659:                // skip UTF-8 signature: EF BB BF  (BOM code)
        !           660:                raw_body+=3;
        !           661:                raw_body_size-=3;
        !           662:        }
        !           663: 
1.1       paf       664:        // output response
                    665:        String::C real_body=String::C(raw_body, raw_body_size);
1.16    ! misha     666: 
        !           667:        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       668:                // defaulting to used-asked charset [it's never empty!]
                    669:                if(!real_remote_charset)
                    670:                        real_remote_charset=asked_remote_charset;
1.16    ! misha     671: 
1.1       paf       672:                real_body=Charset::transcode(real_body, *real_remote_charset, charsets.source());
1.16    ! misha     673: 
1.1       paf       674:        }
                    675: 
                    676:        result.str=const_cast<char *>(real_body.str); // hacking a little
                    677:        result.length=real_body.length;
1.16    ! misha     678: 
1.1       paf       679:        result.headers->put(file_status_name, new VInt(status_code));
1.16    ! misha     680: 
1.1       paf       681:        return result;
                    682: }

E-mail: