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

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

E-mail: