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

1.1       paf         1: /** @file
                      2:        Parser: http support functions.
                      3: 
1.25      misha       4:        Copyright(c) 2001-2009 ArtLebedev Group (http://www.artlebedev.com)
1.1       paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
                      6:  */
                      7: 
1.49    ! moko        8: static const char * const IDENT_HTTP_C="$Date: 2010-10-16 22:24:20 $"; 
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"
1.22      misha      14: #include "pa_request.h"
                     15: #include "pa_vfile.h"
                     16: #include "pa_random.h"
1.1       paf        17: 
                     18: // defines
                     19: 
1.19      misha      20: #define HTTP_METHOD_NAME       "method"
                     21: #define HTTP_FORM_NAME "form"
                     22: #define HTTP_BODY_NAME "body"
                     23: #define HTTP_TIMEOUT_NAME      "timeout"
                     24: #define HTTP_HEADERS_NAME      "headers"
                     25: #define HTTP_COOKIES_NAME      "cookies"
1.22      misha      26: #define HTTP_FORM_ENCTYPE_NAME "enctype"
1.19      misha      27: #define HTTP_ANY_STATUS_NAME   "any-status"
1.20      misha      28: #define HTTP_OMIT_POST_CHARSET_NAME    "omit-post-charset"     // ^file::load[...;http://...;$.form[...]$.method[post]]
1.12      misha      29:                                                                                                        // by default add charset to content-type
                     30: 
1.1       paf        31: #define HTTP_TABLES_NAME "tables"
1.12      misha      32: 
1.1       paf        33: #define HTTP_USER "user"
                     34: #define HTTP_PASSWORD "password"
                     35: 
                     36: #define DEFAULT_USER_AGENT "parser3"
                     37: 
                     38: #      ifndef INADDR_NONE
                     39: #              define INADDR_NONE ((ulong) -1)
                     40: #      endif
                     41: 
                     42: #undef CRLF
                     43: #define CRLF "\r\n"
                     44: 
                     45: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
1.22      misha      46:        memset(addr, 0, sizeof(*addr)); 
                     47:        addr->sin_family=AF_INET;
                     48:        addr->sin_port=htons(port); 
                     49:        if(host) {
1.1       paf        50:                ulong packed_ip=inet_addr(host);
                     51:                if(packed_ip!=INADDR_NONE)
                     52:                        memcpy(&addr->sin_addr, &packed_ip, sizeof(packed_ip)); 
                     53:                else {
                     54:                        struct hostent *hostIP=gethostbyname(host);
                     55:                        if(hostIP) 
                     56:                                memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length); 
                     57:                        else
                     58:                                return false;
                     59:                } 
1.22      misha      60:        } else 
1.1       paf        61:                addr->sin_addr.s_addr=INADDR_ANY;
1.22      misha      62:        return true;
1.1       paf        63: }
                     64: 
                     65: size_t guess_content_length(char* buf) {
                     66:        char* ptr;
                     67:        if((ptr=strstr(buf, "Content-Length:"))) // Apache
                     68:                goto found;
1.37      misha      69:        if((ptr=strstr(buf, "content-length:"))) // Parser 3 before 3.4.0
1.1       paf        70:                goto found;
                     71:        if((ptr=strstr(buf, "Content-length:"))) // maybe 1
                     72:                goto found;
                     73:        if((ptr=strstr(buf, "CONTENT-LENGTH:"))) // maybe 2
                     74:                goto found;
                     75:        return 0;
                     76: found:
                     77:        char *error_pos;
1.37      misha      78:        size_t result=(size_t)strtol(ptr+15/*strlen("Content-Length:")*/, &error_pos, 0);
1.1       paf        79:        
                     80:        const size_t reasonable_initial_max=0x400*0x400*10 /*10M*/;
                     81:        if(result>reasonable_initial_max) // sanity check
                     82:                return reasonable_initial_max;
                     83:        return 0;//result;
                     84: }
                     85: 
                     86: static int http_read_response(char*& response, size_t& response_size, int sock, bool fail_on_status_ne_200) {
                     87:        int result=0;
1.37      misha      88:        // fetching some to local buffer, guessing on possible Content-Length
                     89:        response_size=0x400*20; // initial size if Content-Length could not be determined       
1.1       paf        90:        const size_t preview_size=0x400*20;
                     91:        char preview_buf[preview_size+1/*terminator*/];  // 20K buffer to preview headers
                     92:        ssize_t received_size=recv(sock, preview_buf, preview_size, 0); 
                     93:        if(received_size==0)
                     94:                goto done;
                     95:        if(received_size<0) {
                     96:                if(int no=pa_socks_errno())
                     97:                        throw Exception("http.timeout", 
                     98:                                0, 
                     99:                                "error receiving response header: %s (%d)", pa_socks_strerr(no), no); 
                    100:                goto done;
                    101:        }
1.2       paf       102:        // terminator [helps futher string searches]
                    103:        preview_buf[received_size]=0; 
                    104:        // checking status
                    105:        if(char* EOLat=strstr(preview_buf, "\n")) { 
                    106:                const String status_line(pa_strdup(preview_buf, EOLat-preview_buf));
                    107:                ArrayString astatus; 
                    108:                size_t pos_after=0;
                    109:                status_line.split(astatus, pos_after, " "); 
                    110:                const String& status_code=*astatus.get(astatus.count()>1?1:0);
                    111:                result=status_code.as_int(); 
                    112: 
                    113:                if(fail_on_status_ne_200 && result!=200)
                    114:                        throw Exception("http.status",
                    115:                                &status_code,
                    116:                                "invalid HTTP response status");
                    117:        }
1.1       paf       118:        // detecting response_size
                    119:        {
                    120:                if(size_t content_length=guess_content_length(preview_buf))
                    121:                        response_size=preview_size+content_length; // a little more than needed, will adjust response_size by actual received size later
                    122:        }
                    123: 
                    124:        // [gcc is happier this way, see goto above]
                    125:        {
                    126:                // allocating initial buf
                    127:                response=(char*)pa_malloc_atomic(response_size+1/*terminator*/); // just setting memory block type
                    128:                char* ptr=response;
                    129:                size_t todo_size=response_size;
                    130:                // coping part of already received body
                    131:                memcpy(ptr, preview_buf, received_size);
                    132:                ptr+=received_size;
                    133:                todo_size-=received_size;               
                    134: 
                    135:                // we use terminator byte for two purposes here:
                    136:                // 1. we return there zero always, not knowing: maybe they would want to create String form $file.body?
                    137:                //     invariant: all Strings should have zero-terminated buffers
1.37      misha     138:                // 2. we use that out-of-size byte to detect if our Content-Length guess was wrong
1.1       paf       139:                //    when recv gets more than we expected
1.37      misha     140:                //    a) we know that the Content-Length guess was wrong
1.1       paf       141:                //    b) we have space to put the first byte of extra data
                    142:                //    c) we use less code to detect normal situation: on last while-cycle recv expected to just return 0
                    143:                while(true) {
                    144:                        received_size=recv(sock, ptr, todo_size+1/*there is always a place for terminator*/, 0); 
                    145:                        if(received_size==0) {
                    146:                                response_size-=todo_size; // in case we received less than expected, cut down the reported size
                    147:                                break;
                    148:                        }
                    149:                        if(received_size<0) {
                    150:                                if(int no=pa_socks_errno())
                    151:                                        throw Exception("http.timeout", 
                    152:                                                0, 
                    153:                                                "error receiving response body: %s (%d)", pa_socks_strerr(no), no); 
                    154:                                break;
                    155:                        }
                    156:                        // they've touched the terminator?
                    157:                        if((size_t)received_size>todo_size)
                    158:                        {
                    159:                                // that means that our guessed response_size was not big enough
                    160:                                const size_t grow_chunk_size=0x400*0x400; // 1M
                    161:                                response_size+=grow_chunk_size;
                    162:                                size_t ptr_offset=ptr-response;
                    163:                                response=(char*)pa_realloc(response, response_size+1/*terminator*/);
                    164:                                ptr=response+ptr_offset;
                    165:                                todo_size+=grow_chunk_size;
                    166:                        }
                    167:                        // can't do this before realloc: we need <todo_size check
                    168:                        ptr+=received_size;
                    169:                        todo_size-=received_size;
                    170:                }
                    171:        }
                    172: done:
                    173:        if(result)
                    174:        {
                    175:                response[response_size]=0;
                    176:                return result;
                    177:        }
                    178:        else
                    179:                throw Exception("http.response",
                    180:                        0,
                    181:                        "bad response from host - no status found (size=%u)", response_size); 
                    182: }
                    183: 
                    184: /* ********************** request *************************** */
                    185: 
                    186: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
                    187: #      define PA_USE_ALARM
                    188: #endif
                    189: 
                    190: #ifdef PA_USE_ALARM
                    191: static sigjmp_buf timeout_env;
                    192: static void timeout_handler(int /*sig*/){
1.22      misha     193:        siglongjmp(timeout_env, 1); 
1.1       paf       194: }
                    195: #endif
                    196: 
                    197: static int http_request(char*& response, size_t& response_size,
                    198:                        const char* host, short port, 
1.22      misha     199:                        const char* request, size_t request_size,
1.1       paf       200:                        int timeout_secs,
                    201:                        bool fail_on_status_ne_200) {
                    202:        if(!host)
                    203:                throw Exception("http.host", 
                    204:                        0, 
                    205:                        "zero hostname");  //never
                    206: 
                    207:        volatile // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning]
                    208:                int sock=-1;
                    209: #ifdef PA_USE_ALARM
                    210:        signal(SIGALRM, timeout_handler); 
                    211: #endif
                    212: #ifdef PA_USE_ALARM
                    213:        if(sigsetjmp(timeout_env, 1)) {
                    214:                // stupid gcc [2.95.4] generated bad code
                    215:                // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
                    216:                // rewritten simplier [athough duplicating closesocket code]
                    217:                if(sock>=0) 
                    218:                        closesocket(sock); 
                    219:                throw Exception("http.timeout", 
                    220:                        0, 
                    221:                        "timeout occured while retrieving document"); 
                    222:                return 0; // never
                    223:        } else {
                    224:                alarm(timeout_secs); 
                    225: #endif
                    226:                try {
                    227:                        int result;
                    228:                        struct sockaddr_in dest;
                    229:                
                    230:                        if(!set_addr(&dest, host, port))
                    231:                                throw Exception("http.host", 
                    232:                                        0, 
                    233:                                        "can not resolve hostname \"%s\"", host); 
                    234:                        
                    235:                        if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0) {
                    236:                                int no=pa_socks_errno();
                    237:                                throw Exception("http.connect", 
                    238:                                        0, 
                    239:                                        "can not make socket: %s (%d)", pa_socks_strerr(no), no); 
                    240:                        }
                    241: 
                    242:                        // To enable SO_DONTLINGER (that is, disable SO_LINGER) 
                    243:                        // l_onoff should be set to zero and setsockopt should be called
                    244:                        linger dont_linger={0,0};
                    245:                        setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger));
                    246: 
                    247: #ifdef WIN32
                    248: // SO_*TIMEO can be defined in .h but not implemlemented in protocol,
                    249: // failing subsequently with Option not supported by protocol (99) message
                    250: // could not suppress that, so leaving this only for win32
                    251:                        int timeout_ms=timeout_secs*1000;
                    252:                        setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
                    253:                        setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
                    254: #endif
                    255: 
                    256:                        if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
                    257:                                int no=pa_socks_errno();
                    258:                                throw Exception("http.connect", 
                    259:                                        0, 
                    260:                                        "can not connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no); 
                    261:                        }
1.22      misha     262: 
1.1       paf       263:                        if(send(sock, request, request_size, 0)!=(ssize_t)request_size) {
                    264:                                int no=pa_socks_errno();
                    265:                                throw Exception("http.timeout", 
                    266:                                        0, 
                    267:                                        "error sending request: %s (%d)", pa_socks_strerr(no), no); 
                    268:                        }
                    269: 
                    270:                        result=http_read_response(response, response_size, sock, fail_on_status_ne_200); 
                    271:                        closesocket(sock); 
                    272: #ifdef PA_USE_ALARM
                    273:                        alarm(0); 
                    274: #endif
                    275:                        return result;
                    276:                } catch(...) {
                    277: #ifdef PA_USE_ALARM
                    278:                        alarm(0); 
                    279: #endif
                    280:                        if(sock>=0) 
                    281:                                closesocket(sock); 
                    282:                        rethrow;
                    283:                }
                    284: #ifdef PA_USE_ALARM
                    285:        }
                    286: #endif
                    287: }
                    288: 
                    289: #ifndef DOXYGEN
                    290: struct Http_pass_header_info {
                    291:        Request_charsets* charsets;
                    292:        String* request;
1.35      misha     293:        bool* user_agent_specified;
                    294:        bool* content_type_specified;
                    295:        bool* content_type_url_encoded;
1.1       paf       296: };
                    297: #endif
1.35      misha     298: static void http_pass_header(HashStringValue::key_type aname, 
                    299:                                HashStringValue::value_type avalue, 
1.22      misha     300:                                Http_pass_header_info *info) {
1.9       misha     301: 
1.41      misha     302:        const char* name_cstr=aname.cstr();
                    303: 
1.38      misha     304:        if(strcasecmp(name_cstr, HTTP_CONTENT_LENGTH)==0)
                    305:                return;
                    306: 
1.43      misha     307:        String name=String(capitalize(name_cstr), String::L_URI);
1.42      misha     308:        String value=attributed_meaning_to_string(*avalue, String::L_URI, true);
1.9       misha     309: 
1.35      misha     310:        *info->request << name << ": " << value << CRLF;
1.1       paf       311:        
1.38      misha     312:        if(strcasecmp(name_cstr, HTTP_USER_AGENT)==0)
1.35      misha     313:                *info->user_agent_specified=true;
1.38      misha     314:        if(strcasecmp(name_cstr, HTTP_CONTENT_TYPE)==0){
1.35      misha     315:                *info->content_type_specified=true;
                    316:                *info->content_type_url_encoded=StrStartFromNC(value.cstr(), HTTP_CONTENT_TYPE_FORM_URLENCODED);
                    317:        }
1.1       paf       318: }
                    319: 
1.10      misha     320: static void http_pass_cookie(HashStringValue::key_type name, 
1.20      misha     321:                                HashStringValue::value_type value, 
                    322:                                Http_pass_header_info *info) {
1.10      misha     323:        
1.17      misha     324:        *info->request << String(name, String::L_HTTP_COOKIE) << "="
1.31      misha     325:                << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, true)
1.10      misha     326:                << "; "; 
                    327: 
                    328: }
1.1       paf       329: 
                    330: static const String* basic_authorization_field(const char* user, const char* pass) {
                    331:        if(!user&& !pass)
                    332:                return 0;
                    333: 
                    334:        String combined;  
                    335:        if(user)
                    336:                combined<<user;
                    337:        combined<<":";
                    338:        if(pass)
                    339:                combined<<pass;
                    340:        
1.20      misha     341:        String* result=new String("Basic ");
                    342:        *result<<pa_base64_encode(combined.cstr(), combined.length());
1.1       paf       343:        return result;
                    344: }
                    345: 
                    346: static void form_string_value2string(
1.20      misha     347:                                        HashStringValue::key_type key, 
                    348:                                        const String& value, 
                    349:                                        String& result) 
1.1       paf       350: {
1.30      misha     351:        result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1       paf       352: }
1.20      misha     353: 
1.1       paf       354: #ifndef DOXYGEN
                    355: struct Form_table_value2string_info {
                    356:        HashStringValue::key_type key;
                    357:        String& result;
                    358: 
                    359:        Form_table_value2string_info(HashStringValue::key_type akey, String& aresult): 
                    360:                key(akey), result(aresult) {}
                    361: };
                    362: #endif
                    363: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
                    364:        form_string_value2string(info->key, *row->get(0), info->result);
                    365: }
                    366: static void form_value2string(
1.20      misha     367:                                        HashStringValue::key_type key, 
                    368:                                        HashStringValue::value_type value, 
                    369:                                        String* result) 
1.1       paf       370: {
                    371:        if(const String* svalue=value->get_string())
                    372:                form_string_value2string(key, *svalue, *result);
                    373:        else if(Table* tvalue=value->get_table()) {
                    374:                Form_table_value2string_info info(key, *result);
                    375:                tvalue->for_each(form_table_value2string, &info);
                    376:        } else
1.18      misha     377:                throw Exception(PARSER_RUNTIME,
1.1       paf       378:                        new String(key, String::L_TAINTED),
1.22      misha     379:                        "is %s, "HTTP_FORM_NAME" option value can be string or table only (file is allowed for $."HTTP_METHOD_NAME"[POST] + $."HTTP_FORM_ENCTYPE_NAME"["HTTP_CONTENT_TYPE_MULTIPART_FORMDATA"])", value->type());
1.1       paf       380: }
1.20      misha     381: 
1.5       misha     382: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1       paf       383:        String string;
1.3       paf       384:        form.for_each<String*>(form_value2string, &string);
1.44      misha     385:        return string.untaint_and_transcode_cstr(String::L_URI, &charsets);
1.1       paf       386: }
1.22      misha     387: 
                    388: struct FormPart {
                    389:        Request* r;
                    390:        const char* boundary;
1.48      moko      391:        String* string;
1.22      misha     392:        Form_table_value2string_info* info;
1.48      moko      393: 
                    394:        struct BinaryBlock{
                    395:                const char* ptr;
                    396:                size_t length;
                    397: 
                    398:                BinaryBlock(String* astring, Request* r): ptr(astring->untaint_and_transcode_cstr(String::L_AS_IS, &r->charsets)), length(strlen(ptr)){}
                    399:                BinaryBlock(const char* aptr, size_t alength): ptr(aptr), length(alength){}
                    400:        };
                    401: 
                    402:        Array<BinaryBlock> blocks;
                    403: 
                    404:        FormPart(Request* ar, const char* aboundary): r(ar), boundary(aboundary), string(new String()){}
                    405: 
                    406:        const char *post(size_t &length){
                    407:                if(blocks.count()){
                    408:                        blocks+=BinaryBlock(string, r);
                    409: 
                    410:                        length=0;
                    411:                        for(size_t i=0; i<blocks.count(); i++)
                    412:                                length+=blocks[i].length;
                    413: 
                    414:                        char *result=(char *)pa_malloc_atomic(length);
                    415:                        char *ptr=result;
                    416: 
                    417:                        for(size_t i=0; i<blocks.count(); i++){
                    418:                                memcpy(ptr, blocks[i].ptr, blocks[i].length);
                    419:                                ptr+=blocks[i].length;
                    420:                        }
                    421: 
                    422:                        return result;
                    423:                } else {
                    424:                        BinaryBlock result(string, r);
                    425:                        length=result.length;
                    426:                        return result.ptr;
                    427:                }
                    428:        }
1.22      misha     429: };
                    430: 
1.28      misha     431: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0){
1.48      moko      432:        *part.string << "--" << part.boundary
1.41      misha     433:                                << CRLF CONTENT_DISPOSITION_CAPITALIZED ": form-data; name=\"" 
1.48      moko      434:                                << name
1.28      misha     435:                                << "\"";
1.22      misha     436:        if(file_name){
                    437:                if(strcmp(file_name, NONAME_DAT)!=0)
1.48      moko      438:                        *part.string << "; filename=\"" << file_name << "\"";
                    439:                *part.string << CRLF HTTP_CONTENT_TYPE_CAPITALIZED ": " << part.r->mime_type_of(file_name);
1.22      misha     440:        }
1.48      moko      441:        *part.string << CRLF CRLF;
1.22      misha     442: }
                    443: 
                    444: static void form_string_value2part(
1.28      misha     445:                                HashStringValue::key_type key,
                    446:                                const String& value,
                    447:                                FormPart& part)
1.22      misha     448: {
1.28      misha     449:        form_part_boundary_header(part, key);
1.48      moko      450:        *part.string << value << CRLF;
1.22      misha     451: }
                    452: 
                    453: static void form_file_value2part(
1.28      misha     454:                                HashStringValue::key_type key,
                    455:                                VFile& vfile,  
                    456:                                FormPart& part)
1.22      misha     457: {
1.28      misha     458:        form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.48      moko      459:        part.blocks+=FormPart::BinaryBlock(part.string, part.r);
                    460:        part.blocks+=FormPart::BinaryBlock(vfile.value_ptr(), vfile.value_size());
                    461:        part.string=new String();
                    462:        *part.string << CRLF;
1.22      misha     463: }
                    464: 
                    465: static void form_table_value2part(Table::element_type row, FormPart* part) {
                    466:        form_string_value2part(part->info->key, *row->get(0), *part);
                    467: }
                    468: 
                    469: static void form_value2part(
1.28      misha     470:                                HashStringValue::key_type key,
                    471:                                HashStringValue::value_type value,
                    472:                                FormPart& part)
1.22      misha     473: {
                    474:        if(const String* svalue=value->get_string())
                    475:                form_string_value2part(key, *svalue, part);
                    476:        else if(Table* tvalue=value->get_table()) {
1.48      moko      477:                Form_table_value2string_info info(key, *part.string);
1.22      misha     478:                part.info = &info;
                    479:                tvalue->for_each(form_table_value2part, &part);
1.33      misha     480:        } else if(VFile* vfile=static_cast<VFile *>(value->as("file"))){
1.22      misha     481:                form_file_value2part(key, *vfile, part);
                    482:        } else
                    483:                throw Exception(PARSER_RUNTIME,
                    484:                        new String(key, String::L_TAINTED),
                    485:                        "is %s, "HTTP_FORM_NAME" option value can be string, table or file only", value->type());
                    486: }
                    487: 
                    488: const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){
1.48      moko      489:        FormPart formpart(&r, boundary);
1.22      misha     490:        form.for_each<FormPart&>(form_value2part, formpart);
1.48      moko      491:        *formpart.string << "--" << boundary << "--";
                    492:        // @todo: return binary blocks here to save memory in pa_internal_file_read_http
                    493:        return formpart.post(post_size);
1.22      misha     494: }
                    495: 
1.1       paf       496: static void find_headers_end(char* p,
                    497:                char*& headers_end_at,
                    498:                char*& raw_body)
                    499: {
                    500:        raw_body=p;
                    501:        // \n\n
                    502:        // \r\n\r\n
                    503:        while((p=strchr(p, '\n'))) {
                    504:                headers_end_at=++p; // \n>.<
                    505:                if(*p=='\r')  // \r\n>\r?<\n
                    506:                        p++;
                    507:                if(*p=='\n') { // \r\n\r>\n?<
                    508:                        raw_body=p+1;
                    509:                        return;                 
                    510:                }
                    511:        }
                    512:        headers_end_at=0;
                    513: }
                    514: 
                    515: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.22      misha     516: File_read_http_result pa_internal_file_read_http(Request& r,
                    517:                                                const String& file_spec,
1.20      misha     518:                                                bool as_text,
1.15      misha     519:                                                HashStringValue *options,
                    520:                                                bool transcode_text_result) {
1.1       paf       521:        File_read_http_result result;
1.20      misha     522:        char host[MAX_STRING];
1.1       paf       523:        const char* uri; 
1.49    ! moko      524:        short port=80;
1.10      misha     525:        const char* method="GET";
1.21      misha     526:        bool method_is_get=true;
1.1       paf       527:        HashStringValue* form=0;
                    528:        int timeout_secs=2;
                    529:        bool fail_on_status_ne_200=true;
1.12      misha     530:        bool omit_post_charset=false;
1.1       paf       531:        Value* vheaders=0;
1.10      misha     532:        Value* vcookies=0;
1.11      misha     533:        Value* vbody=0;
1.1       paf       534:        Charset *asked_remote_charset=0;
                    535:        const char* user_cstr=0;
                    536:        const char* password_cstr=0;
1.22      misha     537:        const char* encode=0;
                    538:        bool multipart=false;
1.1       paf       539: 
                    540:        if(options) {
                    541:                int valid_options=pa_get_valid_file_options_count(*options);
                    542: 
                    543:                if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
                    544:                        valid_options++;
1.21      misha     545:                        method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
                    546:                        method_is_get=strcmp(method, "GET")==0;
1.1       paf       547:                }
1.22      misha     548:                if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
                    549:                        valid_options++;
                    550:                        encode=vencode->as_string().cstr();
                    551:                }
1.1       paf       552:                if(Value* vform=options->get(HTTP_FORM_NAME)) {
                    553:                        valid_options++;
                    554:                        form=vform->get_hash(); 
                    555:                } 
1.11      misha     556:                if(vbody=options->get(HTTP_BODY_NAME)) {
1.1       paf       557:                        valid_options++;
                    558:                } 
                    559:                if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
                    560:                        valid_options++;
                    561:                        timeout_secs=vtimeout->as_int(); 
                    562:                } 
1.11      misha     563:                if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1       paf       564:                        valid_options++;
                    565:                } 
1.11      misha     566:                if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10      misha     567:                        valid_options++;
                    568:                } 
1.1       paf       569:                if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
                    570:                        valid_options++;
                    571:                        fail_on_status_ne_200=!vany_status->as_bool(); 
1.12      misha     572:                }
1.20      misha     573:                if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12      misha     574:                        valid_options++;
                    575:                        omit_post_charset=vomit_post_charset->as_bool();
                    576:                }
1.6       misha     577:                if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.23      misha     578:                        asked_remote_charset=&charsets.get(vcharset_name->as_string().
1.22      misha     579:                                change_case(r.charsets.source(), String::CC_UPPER));
1.1       paf       580:                } 
                    581:                if(Value* vuser=options->get(HTTP_USER)) {
                    582:                        valid_options++;
                    583:                        user_cstr=vuser->as_string().cstr();
                    584:                } 
                    585:                if(Value* vpassword=options->get(HTTP_PASSWORD)) {
                    586:                        valid_options++;
                    587:                        password_cstr=vpassword->as_string().cstr();
                    588:                }
                    589: 
                    590:                if(valid_options!=options->count())
1.46      misha     591:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       paf       592:        }
                    593:        if(!asked_remote_charset) // defaulting to $request:charset
1.22      misha     594:                asked_remote_charset=&(r.charsets).source();
                    595: 
                    596:        if(encode){
                    597:                if(method_is_get)
                    598:                        throw Exception(PARSER_RUNTIME,
                    599:                                0,
                    600:                                "you can not use $."HTTP_FORM_ENCTYPE_NAME" option with method GET");
                    601: 
                    602:                multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
                    603: 
                    604:                if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
                    605:                        throw Exception(PARSER_RUNTIME,
                    606:                                0,
                    607:                                "$."HTTP_FORM_ENCTYPE_NAME" option value can be "HTTP_CONTENT_TYPE_FORM_URLENCODED" or "HTTP_CONTENT_TYPE_MULTIPART_FORMDATA" only");
                    608:        }
1.1       paf       609: 
1.11      misha     610:        if(vbody){
                    611:                if(method_is_get)
                    612:                        throw Exception(PARSER_RUNTIME,
                    613:                                0,
                    614:                                "you can not use $."HTTP_BODY_NAME" option with method GET");
                    615: 
                    616:                if(form)
                    617:                        throw Exception(PARSER_RUNTIME,
                    618:                                0,
                    619:                                "you can not use options $."HTTP_BODY_NAME" and $."HTTP_FORM_NAME" together");
                    620:        }
1.1       paf       621: 
                    622:        //preparing request
1.29      misha     623:        String& connect_string=*new String(file_spec);
1.1       paf       624: 
1.48      moko      625:        const char* request;
                    626:        size_t request_size;
1.1       paf       627:        {
                    628:                // influence URLencoding of tainted pieces to String::L_URI lang
1.22      misha     629:                Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1       paf       630: 
1.44      misha     631:                const char* connect_string_cstr=connect_string.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1       paf       632: 
                    633:                const char* current=connect_string_cstr;
                    634:                if(strncmp(current, "http://", 7)!=0)
1.18      misha     635:                        throw Exception(PARSER_RUNTIME, 
1.1       paf       636:                                &connect_string, 
                    637:                                "does not start with http://"); //never
                    638:                current+=7;
                    639: 
                    640:                strncpy(host, current, sizeof(host)-1);  host[sizeof(host)-1]=0;
1.34      misha     641:                char* host_uri=lsplit(host, '/');
                    642:                uri=host_uri?current+(host_uri-1-host):"/";
                    643:                char* port_cstr=lsplit(host, ':');
1.49    ! moko      644:                
        !           645:                if (port_cstr){
        !           646:                        char* error_pos=0;
        !           647:                        port=(short)strtol(port_cstr, &error_pos, 10);
        !           648:                        if(port==0 || *error_pos)
        !           649:                                throw Exception(PARSER_RUNTIME, &connect_string, "invalid port number '%s'", port_cstr);
        !           650:                }
1.1       paf       651: 
1.11      misha     652:                // making request head
1.1       paf       653:                String head;
1.11      misha     654:                head << method << " " << uri;
1.28      misha     655:                if(method_is_get && form)
                    656:                        head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11      misha     657: 
1.49    ! moko      658:                head <<" HTTP/1.0" CRLF "Host: "<< host;
        !           659:                if (port != 80)
        !           660:                        head << ":" << port_cstr;
        !           661:                head << CRLF;
1.11      misha     662: 
1.28      misha     663:                char* boundary=0;
1.22      misha     664: 
                    665:                if(multipart){
                    666:                        uuid uuid=get_uuid();
                    667:                        const int boundary_bufsize=10+32+1/*for zero-teminator*/+1/*for faulty snprintfs*/;
                    668:                        boundary=new(PointerFreeGC) char[boundary_bufsize];
                    669:                        snprintf(boundary, boundary_bufsize,
                    670:                                "----------%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X",
                    671:                                uuid.time_low, uuid.time_mid, uuid.time_hi_and_version,
                    672:                                uuid.clock_seq >> 8, uuid.clock_seq & 0xFF,
                    673:                                uuid.node[0], uuid.node[1], uuid.node[2],
                    674:                                uuid.node[3], uuid.node[4], uuid.node[5]);
                    675:                }
                    676: 
1.35      misha     677:                String user_headers;
                    678:                bool user_agent_specified=false;
                    679:                bool content_type_specified=false;
                    680:                bool content_type_url_encoded=false;
                    681:                if(vheaders && !vheaders->is_string()) { // allow empty
                    682:                        if(HashStringValue *headers=vheaders->get_hash()) {
                    683:                                Http_pass_header_info info={
                    684:                                        &(r.charsets),
                    685:                                        &user_headers,
                    686:                                        &user_agent_specified,
                    687:                                        &content_type_specified,
                    688:                                        &content_type_url_encoded};
                    689:                                headers->for_each<Http_pass_header_info*>(http_pass_header, &info); 
                    690:                        } else
                    691:                                throw Exception(PARSER_RUNTIME, 
                    692:                                        0,
                    693:                                        "headers param must be hash"); 
                    694:                };
                    695: 
1.48      moko      696:                const char* request_body=0;
1.22      misha     697:                size_t post_size=0;
                    698:                if(form && !method_is_get) {
1.38      misha     699:                        head << "Content-Type: " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
1.28      misha     700: 
                    701:                        if(!omit_post_charset)
                    702:                                head << "; charset=" << asked_remote_charset->NAME_CSTR();
                    703: 
1.22      misha     704:                        if(multipart) {
1.28      misha     705:                                head << "; boundary=" << boundary;
1.48      moko      706:                                request_body=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22      misha     707:                        } else {
1.48      moko      708:                                request_body=pa_form2string(*form, r.charsets);
                    709:                                post_size=strlen(request_body);
1.22      misha     710:                        }
1.28      misha     711:                        head << CRLF;
1.35      misha     712:                } else if(vbody) {
1.38      misha     713:                        // $.body was specified
1.35      misha     714:                        if(content_type_url_encoded){
1.36      misha     715:                                // transcode + url-encode
1.48      moko      716:                                request_body=vbody->as_string().untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.35      misha     717:                        } else {
1.36      misha     718:                                // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.48      moko      719:                                request_body=Charset::transcode(
1.35      misha     720:                                        String::C(vbody->as_string().cstr(), vbody->as_string().length()),
                    721:                                        r.charsets.source(),
                    722:                                        *asked_remote_charset
                    723:                                );
                    724:                        }
1.48      moko      725:                        post_size=strlen(request_body);
1.1       paf       726:                }
                    727: 
                    728:                // http://www.ietf.org/rfc/rfc2617.txt
                    729:                if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.38      misha     730:                        head << "Authorization: " << *authorization_field_value << CRLF;
1.1       paf       731: 
1.35      misha     732:                head << user_headers;
                    733: 
1.1       paf       734:                if(!user_agent_specified) // defaulting
1.38      misha     735:                        head << "User-Agent: " DEFAULT_USER_AGENT CRLF;
1.1       paf       736: 
1.12      misha     737:                if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
                    738:                        throw Exception(PARSER_RUNTIME,
1.35      misha     739:                                0,
1.12      misha     740:                                "$.content-type can't be specified with method POST"); 
                    741: 
1.11      misha     742:                if(vcookies && !vcookies->is_string()){ // allow empty
1.10      misha     743:                        if(HashStringValue* cookies=vcookies->get_hash()) {
1.37      misha     744:                                head << "Cookie: ";
1.35      misha     745:                                Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10      misha     746:                                cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info); 
                    747:                                head << CRLF;
                    748:                        } else
                    749:                                throw Exception(PARSER_RUNTIME, 
1.35      misha     750:                                        0,
1.44      misha     751:                                        "cookies param must be hash");
1.10      misha     752:                }
                    753: 
1.48      moko      754:                if(request_body)
1.38      misha     755:                        head << "Content-Length: " << format(post_size, "%u") << CRLF;
1.48      moko      756:                
                    757:                head << CRLF;
                    758:                
                    759:                const char *request_head=head.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1       paf       760: 
1.48      moko      761:                if(request_body){
                    762:                        size_t head_size = strlen(request_head);
                    763:                        request_size=post_size + head_size;
                    764:                        char *ptr=(char *)pa_malloc_atomic(request_size);
                    765:                        memcpy(ptr, request_head, head_size);
                    766:                        memcpy(ptr+head_size, request_body, post_size);
                    767:                        request=ptr;
                    768:                } else {
                    769:                        request_size=strlen(request_head);
                    770:                        request=request_head;
                    771:                }
1.1       paf       772:        }
                    773:        
                    774:        char* response;
                    775:        size_t response_size;
1.22      misha     776: 
1.28      misha     777:        // sending request
1.1       paf       778:        int status_code=http_request(response, response_size,
1.48      moko      779:                host, port, request, request_size,
1.1       paf       780:                timeout_secs, fail_on_status_ne_200); 
                    781:        
1.28      misha     782:        // processing results   
1.1       paf       783:        char* raw_body; size_t raw_body_size;
                    784:        char* headers_end_at;
                    785:        find_headers_end(response, 
                    786:                headers_end_at,
                    787:                raw_body);
                    788:        raw_body_size=response_size-(raw_body-response);
                    789:        
                    790:        result.headers=new HashStringValue;
                    791:        VHash* vtables=new VHash;
                    792:        result.headers->put(HTTP_TABLES_NAME, vtables);
                    793:        Charset* real_remote_charset=0; // undetected, yet
                    794: 
                    795:        if(headers_end_at) {
                    796:                *headers_end_at=0;
1.25      misha     797:                const String header_block(String::C(response, headers_end_at-response), String::L_TAINTED);
1.1       paf       798:                
                    799:                ArrayString aheaders;
                    800:                HashStringValue& tables=vtables->hash();
                    801: 
                    802:                size_t pos_after=0;
                    803:                header_block.split(aheaders, pos_after, "\n"); 
                    804:                
1.28      misha     805:                // processing headers
1.1       paf       806:                size_t aheaders_count=aheaders.count();
                    807:                for(size_t i=1; i<aheaders_count; i++) {
                    808:                        const String& line=*aheaders.get(i);
                    809:                        size_t pos=line.pos(':'); 
                    810:                        if(pos==STRING_NOT_FOUND || pos<1)
                    811:                                throw Exception("http.response", 
                    812:                                        &connect_string,
                    813:                                        "bad response from host - bad header \"%s\"", line.cstr());
1.22      misha     814:                        const String::Body HEADER_NAME=line.mid(0, pos).change_case(r.charsets.source(), String::CC_UPPER);
1.14      misha     815:                        const String& HEADER_VALUE=line.mid(pos+1, line.length()).trim(String::TRIM_BOTH, " \t\r");
1.20      misha     816:                        if(as_text && HEADER_NAME==HTTP_CONTENT_TYPE_UPPER)
1.32      misha     817:                                real_remote_charset=detect_charset(HEADER_VALUE.cstr());
1.1       paf       818: 
                    819:                        // tables
                    820:                        {
                    821:                                Value *valready=(Value *)tables.get(HEADER_NAME);
                    822:                                bool existed=valready!=0;
                    823:                                Table *table;
                    824:                                if(existed) {
                    825:                                        // second+ appearence
                    826:                                        table=valready->get_table();
                    827:                                } else {
                    828:                                        // first appearence
1.14      misha     829:                                        Table::columns_type columns=new ArrayString(1);
1.1       paf       830:                                        *columns+=new String("value");
                    831:                                        table=new Table(columns);
                    832:                                }
                    833:                                // this string becomes next row
                    834:                                ArrayString& row=*new ArrayString(1);
1.14      misha     835:                                row+=&HEADER_VALUE;
1.1       paf       836:                                *table+=&row;
                    837:                                // not existed before? add it
                    838:                                if(!existed)
                    839:                                        tables.put(HEADER_NAME, new VTable(table));
                    840:                        }
                    841: 
1.14      misha     842:                        result.headers->put(HEADER_NAME, new VString(HEADER_VALUE));
1.1       paf       843:                }
                    844:        }
                    845: 
1.16      misha     846:        if(as_text && raw_body_size>=3 && strncmp(raw_body, "\xEF\xBB\xBF", 3)==0){
1.20      misha     847:                // skip UTF-8 signature (BOM code)
1.16      misha     848:                raw_body+=3;
                    849:                raw_body_size-=3;
1.47      misha     850:                if(!real_remote_charset)
                    851:                        real_remote_charset=&UTF8_charset;
1.16      misha     852:        }
                    853: 
1.1       paf       854:        // output response
                    855:        String::C real_body=String::C(raw_body, raw_body_size);
1.16      misha     856: 
                    857:        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       858:                // defaulting to used-asked charset [it's never empty!]
                    859:                if(!real_remote_charset)
                    860:                        real_remote_charset=asked_remote_charset;
1.16      misha     861: 
1.22      misha     862:                real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.16      misha     863: 
1.1       paf       864:        }
                    865: 
                    866:        result.str=const_cast<char *>(real_body.str); // hacking a little
                    867:        result.length=real_body.length;
1.16      misha     868: 
1.22      misha     869:        if(as_text && result.length)
                    870:                fix_line_breaks(result.str, result.length);
                    871: 
1.1       paf       872:        result.headers->put(file_status_name, new VInt(status_code));
1.16      misha     873: 
1.1       paf       874:        return result;
                    875: }

E-mail: