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

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

E-mail: