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

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

E-mail: