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

1.1       paf         1: /** @file
                      2:        Parser: http support functions.
                      3: 
1.109   ! moko        4:        Copyright (c) 2001-2020 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"
1.81      moko       10: #include "pa_base64.h"
1.1       paf        11: #include "pa_charsets.h"
                     12: #include "pa_request_charsets.h"
1.22      misha      13: #include "pa_request.h"
                     14: #include "pa_vfile.h"
                     15: #include "pa_random.h"
1.1       paf        16: 
1.109   ! moko       17: volatile const char * IDENT_PA_HTTP_C="$Id: pa_http.C,v 1.108 2020/12/15 10:25:16 moko Exp $" IDENT_PA_HTTP_H; 
1.59      moko       18: 
                     19: #ifdef _MSC_VER
                     20: #include <windows.h>
1.89      moko       21: #define socklen_t int
1.59      moko       22: #else
                     23: #define closesocket close
                     24: #endif
1.53      moko       25: 
1.1       paf        26: // defines
                     27: 
1.19      misha      28: #define HTTP_METHOD_NAME       "method"
                     29: #define HTTP_FORM_NAME "form"
                     30: #define HTTP_BODY_NAME "body"
                     31: #define HTTP_TIMEOUT_NAME      "timeout"
                     32: #define HTTP_HEADERS_NAME      "headers"
1.22      misha      33: #define HTTP_FORM_ENCTYPE_NAME "enctype"
1.19      misha      34: #define HTTP_ANY_STATUS_NAME   "any-status"
1.59      moko       35: #define HTTP_OMIT_POST_CHARSET_NAME    "omit-post-charset"     // ^file::load[...;http://...;$.method[post]] by default adds charset to content-type
1.12      misha      36: 
1.1       paf        37: #define HTTP_USER "user"
                     38: #define HTTP_PASSWORD "password"
                     39: 
1.70      moko       40: #define HTTP_USER_AGENT "user-agent"
1.1       paf        41: #define DEFAULT_USER_AGENT "parser3"
                     42: 
1.59      moko       43: #ifndef INADDR_NONE
                     44: #define INADDR_NONE ((ulong) -1)
                     45: #endif
1.1       paf        46: 
                     47: #undef CRLF
                     48: #define CRLF "\r\n"
                     49: 
1.54      misha      50: // helpers
1.56      misha      51: 
1.85      moko       52: bool HTTP_Headers::add_header(const char *line){
1.78      moko       53:        const char *value=strchr(line, ':');
                     54: 
                     55:        if(value && value != line){ // we need only headers, not the response code
                     56:                Header header(str_upper(line, value-line), String::Body(value+1).trim(String::TRIM_BOTH, " \t\n\r"));
                     57: 
                     58:                if(header.name == String::Body(HTTP_CONTENT_TYPE_UPPER) && content_type.is_empty())
                     59:                        content_type=header.value;
                     60: 
                     61:                if(header.name == String::Body("CONTENT-LENGTH") && content_length==0)
1.95      moko       62:                        ALTER_EXCEPTION_COMMENT(content_length=pa_atoul(header.value.cstr()), " for content-length");
1.78      moko       63: 
                     64:                headers+=header;
                     65: 
                     66:                return true;
                     67:        }
                     68:        return false;
                     69: }
                     70: 
1.54      misha      71: class Cookies_table_template_columns: public ArrayString {
                     72: public:
                     73:        Cookies_table_template_columns() {
                     74:                *this+=new String("name");
                     75:                *this+=new String("value");
                     76:                *this+=new String("expires");
                     77:                *this+=new String("max-age");
                     78:                *this+=new String("domain");
                     79:                *this+=new String("path");
                     80:                *this+=new String("httponly");
                     81:                *this+=new String("secure");
                     82:        }
                     83: };
                     84: 
                     85: 
1.1       paf        86: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
1.22      misha      87:        memset(addr, 0, sizeof(*addr)); 
                     88:        addr->sin_family=AF_INET;
                     89:        addr->sin_port=htons(port); 
                     90:        if(host) {
1.65      moko       91:                struct hostent *hostIP=gethostbyname(host);
                     92:                if(hostIP && hostIP->h_addrtype == AF_INET){
                     93:                        memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length);
                     94:                        return true;
                     95:                }
                     96:        }
                     97:        return false;
1.1       paf        98: }
                     99: 
1.84      moko      100: class HTTP_response : public PA_Allocated {
1.78      moko      101: public:
                    102:        char *buf;
                    103:        size_t length;
                    104:        size_t buf_size;
                    105:        size_t body_offset;
                    106: 
1.85      moko      107:        HTTP_Headers headers;
1.78      moko      108: 
1.97      moko      109:        HTTP_response() : buf(NULL), length(0), buf_size(0), body_offset(0){}
1.78      moko      110: 
                    111:        void resize(size_t size){
                    112:                buf_size=size;
                    113:                buf=(char *)pa_realloc(buf, size + 1);
                    114:        }
                    115: 
                    116:        bool read(int sock, size_t size){
1.103     moko      117:                if(length + size > buf_size)
                    118:                        resize(buf_size * 2 + size);
1.78      moko      119:                ssize_t received_size=recv(sock, buf + length, size, 0);
1.103     moko      120:                if(received_size == 0)
1.78      moko      121:                        return false;
1.103     moko      122:                if(received_size < 0) {
                    123:                        if(int no = pa_socks_errno())
1.102     moko      124:                                throw Exception("http.timeout", 0, "error receiving response: %s (%d)", pa_socks_strerr(no), no);
1.78      moko      125:                        return false;
                    126:                }
                    127:                length+=received_size;
                    128:                buf[length]='\0';
                    129:                return true;
                    130:        }
                    131: 
1.83      moko      132:        size_t first_line(){
1.89      moko      133:                char *header=strchr(buf, '\n');
                    134:                if(!header)
1.78      moko      135:                        return false;
                    136: 
1.89      moko      137:                return header-buf;
1.78      moko      138:        }
                    139: 
                    140:        const char *status_code(char *status_line, int &result){
                    141:                char* status_start = strchr(status_line, ' ');
                    142: 
                    143:                if(!(status_start++))
                    144:                        return status_line;
                    145: 
                    146:                char* status_end=strchr(status_start, ' ');
                    147: 
                    148:                if(!status_end)
                    149:                        return status_line;
                    150: 
                    151:                if(status_end==status_start)
                    152:                        return status_line;
1.1       paf       153: 
1.78      moko      154:                const char *result_str=pa_strdup(status_start, status_end-status_start);
1.95      moko      155:                ALTER_EXCEPTION_COMMENT(result=pa_atoui(result_str), " for HTTP status");
1.78      moko      156:                return result_str;
                    157:        }
1.2       paf       158: 
1.78      moko      159:        bool body_start(){
                    160:                char *p=buf;
                    161:                while((p=strchr(p, '\n'))) {
                    162:                        if(p[1]=='\r' && p[2]=='\n'){  // \r\n\r\n
                    163:                                *p='\0';
                    164:                                body_offset=p-buf+3;
                    165:                                return true;
                    166:                        }
                    167:                        if(p[1]=='\n') { // \n\n
                    168:                                *p='\0';
                    169:                                body_offset=p-buf+2;
                    170:                                return true;
                    171:                        }
                    172:                        p++;
                    173:                }
                    174:                return false;
1.2       paf       175:        }
1.78      moko      176: 
                    177:        void parse_headers(){
                    178:                const String header_block(buf, String::L_TAINTED);
                    179:                
                    180:                ArrayString aheaders;
                    181:                header_block.split(aheaders, 0, "\n");
                    182: 
                    183:                Array_iterator<const String*> i(aheaders);
                    184:                i.next(); // skipping status
                    185:                for(;i.has_next();){
                    186:                        const char *line=i.next()->cstr();
                    187:                        if(!headers.add_header(line))
1.97      moko      188:                                throw Exception("http.response", 0, "bad response from host - bad header \"%s\"", line);
1.78      moko      189:                }
1.1       paf       190:        }
                    191: 
1.88      moko      192:        int read_response(int sock, bool fail_on_status_ne_200);
1.78      moko      193: };
                    194: 
                    195: enum HTTP_response_state {
                    196:        HTTP_STATUS_CODE,
                    197:        HTTP_HEADERS,
                    198:        HTTP_BODY
                    199: };
                    200: 
1.88      moko      201: int HTTP_response::read_response(int sock, bool fail_on_status_ne_200) {
1.78      moko      202:        HTTP_response_state state=HTTP_STATUS_CODE;
                    203:        int result=0;
                    204: 
                    205:        size_t chunk_size=0x400*16;
1.88      moko      206:        resize(2*chunk_size);
1.78      moko      207: 
1.88      moko      208:        while(read(sock, chunk_size)){
1.78      moko      209:                switch(state){
                    210:                        case HTTP_STATUS_CODE: {
1.88      moko      211:                                size_t status_size=first_line();
1.78      moko      212:                                if(!status_size)
                    213:                                        break;
                    214: 
1.88      moko      215:                                const char *status=status_code(pa_strdup(buf, status_size), result);
1.78      moko      216: 
                    217:                                if(!result || fail_on_status_ne_200 && result!=200)
                    218:                                        throw Exception("http.status", status ? new String(status) : &String::Empty, "invalid HTTP response status");
                    219: 
                    220:                                state=HTTP_HEADERS;
                    221:                        }
                    222: 
                    223:                        case HTTP_HEADERS: {
1.88      moko      224:                                if(!body_start())
1.78      moko      225:                                        break;
                    226: 
1.88      moko      227:                                parse_headers();
1.78      moko      228: 
1.97      moko      229:                                size_t content_length=check_file_size(headers.content_length, 0);
1.88      moko      230:                                if(content_length>0 && (content_length + body_offset) > length){
                    231:                                        resize(content_length + body_offset + 0x400*64);
1.78      moko      232:                                }
                    233: 
                    234:                                state=HTTP_BODY;
1.1       paf       235:                                break;
                    236:                        }
1.78      moko      237: 
                    238:                        case HTTP_BODY: {
                    239:                                chunk_size=0x400*64;
1.1       paf       240:                                break;
                    241:                        }
                    242:                }
                    243:        }
1.78      moko      244: 
                    245:        if(state==HTTP_STATUS_CODE)
1.97      moko      246:                throw Exception("http.response", 0, "bad response from host - no status found (size=%u)", length);
1.78      moko      247: 
                    248:        if(state==HTTP_HEADERS){
1.88      moko      249:                parse_headers();
                    250:                body_offset=length;
1.1       paf       251:        }
1.78      moko      252: 
                    253:        return result;
1.1       paf       254: }
                    255: 
                    256: /* ********************** request *************************** */
                    257: 
                    258: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
                    259: #      define PA_USE_ALARM
                    260: #endif
                    261: 
                    262: #ifdef PA_USE_ALARM
                    263: static sigjmp_buf timeout_env;
                    264: static void timeout_handler(int /*sig*/){
1.101     moko      265:        siglongjmp(timeout_env, 1);
1.1       paf       266: }
1.101     moko      267: #define ALARM(value) alarm(value)
                    268: #else
                    269: #define ALARM(value)
1.1       paf       270: #endif
                    271: 
1.78      moko      272: static int http_request(HTTP_response& response, const char* host, short port, const char* request, size_t request_size, int timeout_secs, bool fail_on_status_ne_200) {
1.1       paf       273:        if(!host)
1.73      moko      274:                throw Exception("http.host", 0, "zero hostname");  //never
1.1       paf       275: 
1.101     moko      276:        volatile int sock=-1; // to prevent makeing it register variable, because it will be clobbered by longjmp [thanks gcc warning]
                    277:                
1.1       paf       278: #ifdef PA_USE_ALARM
1.101     moko      279:        signal(SIGALRM, timeout_handler);
1.1       paf       280:        if(sigsetjmp(timeout_env, 1)) {
1.101     moko      281:                // duplicating closesocket to make code more simple for old compilers
                    282:                if(sock>=0)
                    283:                        closesocket(sock);
                    284:                throw Exception("http.timeout", 0, "timeout occurred while retrieving document");
1.1       paf       285:                return 0; // never
1.101     moko      286:        } else
1.1       paf       287: #endif
1.101     moko      288:        {
                    289:                ALARM(timeout_secs);
1.1       paf       290:                try {
                    291:                        int result;
                    292:                        struct sockaddr_in dest;
                    293:                
                    294:                        if(!set_addr(&dest, host, port))
1.73      moko      295:                                throw Exception("http.host", 0, "can not resolve hostname \"%s\"", host); 
1.1       paf       296:                        
                    297:                        if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0) {
                    298:                                int no=pa_socks_errno();
1.73      moko      299:                                throw Exception("http.connect", 0, "can not make socket: %s (%d)", pa_socks_strerr(no), no); 
1.1       paf       300:                        }
                    301: 
                    302:                        // To enable SO_DONTLINGER (that is, disable SO_LINGER) 
                    303:                        // l_onoff should be set to zero and setsockopt should be called
                    304:                        linger dont_linger={0,0};
                    305:                        setsockopt(sock, SOL_SOCKET, SO_LINGER, (const char *)&dont_linger, sizeof(dont_linger));
                    306: 
                    307: #ifdef WIN32
                    308: // SO_*TIMEO can be defined in .h but not implemlemented in protocol,
                    309: // failing subsequently with Option not supported by protocol (99) message
                    310: // could not suppress that, so leaving this only for win32
                    311:                        int timeout_ms=timeout_secs*1000;
                    312:                        setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
                    313:                        setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_ms, sizeof(timeout_ms));
                    314: #endif
                    315: 
                    316:                        if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
                    317:                                int no=pa_socks_errno();
1.78      moko      318:                                throw Exception("http.connect", 0, "can not connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no);
1.1       paf       319:                        }
1.22      misha     320: 
1.1       paf       321:                        if(send(sock, request, request_size, 0)!=(ssize_t)request_size) {
                    322:                                int no=pa_socks_errno();
1.78      moko      323:                                throw Exception("http.timeout", 0, "error sending request: %s (%d)", pa_socks_strerr(no), no);
1.1       paf       324:                        }
                    325: 
1.88      moko      326:                        result=response.read_response(sock, fail_on_status_ne_200);
1.78      moko      327:                        closesocket(sock);
1.101     moko      328:                        ALARM(0);
1.1       paf       329:                        return result;
                    330:                } catch(...) {
1.101     moko      331:                        ALARM(0);
1.78      moko      332:                        if(sock>=0)
                    333:                                closesocket(sock);
1.1       paf       334:                        rethrow;
                    335:                }
                    336:        }
                    337: }
                    338: 
                    339: #ifndef DOXYGEN
                    340: struct Http_pass_header_info {
                    341:        Request_charsets* charsets;
                    342:        String* request;
1.35      misha     343:        bool* user_agent_specified;
                    344:        bool* content_type_specified;
                    345:        bool* content_type_url_encoded;
1.1       paf       346: };
                    347: #endif
1.50      moko      348: 
                    349: char *pa_http_safe_header_name(const char *name) {
                    350:        char *result=pa_strdup(name);
                    351:        char *n=result;
1.52      misha     352:        if(!pa_isalpha((unsigned char)*n))
1.50      moko      353:                *n++ = '_';
                    354:        for(; *n; ++n) {
1.52      misha     355:                if (!pa_isalnum((unsigned char)*n) && *n != '-' && *n != '_')
1.50      moko      356:                        *n = '_';
                    357:        }
                    358:        return result;
                    359: }
                    360: 
1.101     moko      361: static void http_pass_header(HashStringValue::key_type aname, HashStringValue::value_type avalue, Http_pass_header_info *info) {
1.9       misha     362: 
1.41      misha     363:        const char* name_cstr=aname.cstr();
                    364: 
1.38      misha     365:        if(strcasecmp(name_cstr, HTTP_CONTENT_LENGTH)==0)
                    366:                return;
                    367: 
1.50      moko      368:        String name=String(pa_http_safe_header_name(capitalize(name_cstr)), String::L_AS_IS);
                    369:        String value=attributed_meaning_to_string(*avalue, String::L_HTTP_HEADER, true);
1.9       misha     370: 
1.35      misha     371:        *info->request << name << ": " << value << CRLF;
1.1       paf       372:        
1.38      misha     373:        if(strcasecmp(name_cstr, HTTP_USER_AGENT)==0)
1.35      misha     374:                *info->user_agent_specified=true;
1.38      misha     375:        if(strcasecmp(name_cstr, HTTP_CONTENT_TYPE)==0){
1.35      misha     376:                *info->content_type_specified=true;
1.62      moko      377:                *info->content_type_url_encoded=pa_strncasecmp(value.cstr(), HTTP_CONTENT_TYPE_FORM_URLENCODED)==0;
1.35      misha     378:        }
1.1       paf       379: }
                    380: 
1.10      misha     381: static void http_pass_cookie(HashStringValue::key_type name, 
1.20      misha     382:                                HashStringValue::value_type value, 
                    383:                                Http_pass_header_info *info) {
1.10      misha     384:        
1.17      misha     385:        *info->request << String(name, String::L_HTTP_COOKIE) << "="
1.31      misha     386:                << attributed_meaning_to_string(*value, String::L_HTTP_COOKIE, true)
1.10      misha     387:                << "; "; 
                    388: 
                    389: }
1.1       paf       390: 
                    391: static const String* basic_authorization_field(const char* user, const char* pass) {
                    392:        if(!user&& !pass)
                    393:                return 0;
                    394: 
                    395:        String combined;  
                    396:        if(user)
                    397:                combined<<user;
                    398:        combined<<":";
                    399:        if(pass)
                    400:                combined<<pass;
                    401:        
1.20      misha     402:        String* result=new String("Basic ");
1.82      moko      403:        *result<<pa_base64_encode(combined.cstr(), combined.length(), Base64Options(false /*no wrap*/));
1.1       paf       404:        return result;
                    405: }
                    406: 
1.73      moko      407: static void form_string_value2string(HashStringValue::key_type key, const String& value, String& result) {
1.30      misha     408:        result << String(key, String::L_URI) << "=" << String(value, String::L_URI) << "&";
1.1       paf       409: }
1.20      misha     410: 
1.1       paf       411: #ifndef DOXYGEN
                    412: struct Form_table_value2string_info {
                    413:        HashStringValue::key_type key;
                    414:        String& result;
                    415: 
                    416:        Form_table_value2string_info(HashStringValue::key_type akey, String& aresult): 
                    417:                key(akey), result(aresult) {}
                    418: };
                    419: #endif
                    420: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
                    421:        form_string_value2string(info->key, *row->get(0), info->result);
                    422: }
1.73      moko      423: 
                    424: static void form_value2string(HashStringValue::key_type key, HashStringValue::value_type value, String* result) {
1.1       paf       425:        if(const String* svalue=value->get_string())
                    426:                form_string_value2string(key, *svalue, *result);
                    427:        else if(Table* tvalue=value->get_table()) {
                    428:                Form_table_value2string_info info(key, *result);
                    429:                tvalue->for_each(form_table_value2string, &info);
                    430:        } else
1.73      moko      431:                throw Exception(PARSER_RUNTIME, new String(key, String::L_TAINTED),
1.63      moko      432:                        "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       433: }
1.20      misha     434: 
1.5       misha     435: const char* pa_form2string(HashStringValue& form, Request_charsets& charsets) {
1.1       paf       436:        String string;
1.3       paf       437:        form.for_each<String*>(form_value2string, &string);
1.44      misha     438:        return string.untaint_and_transcode_cstr(String::L_URI, &charsets);
1.1       paf       439: }
1.22      misha     440: 
                    441: struct FormPart {
                    442:        Request* r;
                    443:        const char* boundary;
1.48      moko      444:        String* string;
1.22      misha     445:        Form_table_value2string_info* info;
1.48      moko      446: 
                    447:        struct BinaryBlock{
                    448:                const char* ptr;
                    449:                size_t length;
                    450: 
                    451:                BinaryBlock(String* astring, Request* r): ptr(astring->untaint_and_transcode_cstr(String::L_AS_IS, &r->charsets)), length(strlen(ptr)){}
                    452:                BinaryBlock(const char* aptr, size_t alength): ptr(aptr), length(alength){}
                    453:        };
                    454: 
                    455:        Array<BinaryBlock> blocks;
                    456: 
                    457:        FormPart(Request* ar, const char* aboundary): r(ar), boundary(aboundary), string(new String()){}
                    458: 
                    459:        const char *post(size_t &length){
                    460:                if(blocks.count()){
                    461:                        blocks+=BinaryBlock(string, r);
                    462: 
                    463:                        length=0;
                    464:                        for(size_t i=0; i<blocks.count(); i++)
                    465:                                length+=blocks[i].length;
                    466: 
                    467:                        char *result=(char *)pa_malloc_atomic(length);
                    468:                        char *ptr=result;
                    469: 
                    470:                        for(size_t i=0; i<blocks.count(); i++){
                    471:                                memcpy(ptr, blocks[i].ptr, blocks[i].length);
                    472:                                ptr+=blocks[i].length;
                    473:                        }
                    474: 
                    475:                        return result;
                    476:                } else {
                    477:                        BinaryBlock result(string, r);
                    478:                        length=result.length;
                    479:                        return result.ptr;
                    480:                }
                    481:        }
1.22      misha     482: };
                    483: 
1.73      moko      484: static void form_part_boundary_header(FormPart& part, String::Body name, const char* file_name=0) {
                    485:        *part.string << "--" << part.boundary << CRLF CONTENT_DISPOSITION_CAPITALIZED ": form-data; name=\"" << name << "\"";
1.22      misha     486:        if(file_name){
                    487:                if(strcmp(file_name, NONAME_DAT)!=0)
1.48      moko      488:                        *part.string << "; filename=\"" << file_name << "\"";
                    489:                *part.string << CRLF HTTP_CONTENT_TYPE_CAPITALIZED ": " << part.r->mime_type_of(file_name);
1.22      misha     490:        }
1.48      moko      491:        *part.string << CRLF CRLF;
1.22      misha     492: }
                    493: 
1.73      moko      494: static void form_string_value2part(HashStringValue::key_type key, const String& value, FormPart& part) {
1.28      misha     495:        form_part_boundary_header(part, key);
1.48      moko      496:        *part.string << value << CRLF;
1.22      misha     497: }
                    498: 
1.73      moko      499: static void form_file_value2part(HashStringValue::key_type key, VFile& vfile, FormPart& part) {
1.28      misha     500:        form_part_boundary_header(part, key, vfile.fields().get(name_name)->as_string().cstr());
1.48      moko      501:        part.blocks+=FormPart::BinaryBlock(part.string, part.r);
                    502:        part.blocks+=FormPart::BinaryBlock(vfile.value_ptr(), vfile.value_size());
                    503:        part.string=new String();
                    504:        *part.string << CRLF;
1.22      misha     505: }
                    506: 
                    507: static void form_table_value2part(Table::element_type row, FormPart* part) {
                    508:        form_string_value2part(part->info->key, *row->get(0), *part);
                    509: }
                    510: 
1.73      moko      511: static void form_value2part(HashStringValue::key_type key, HashStringValue::value_type value, FormPart& part) {
1.22      misha     512:        if(const String* svalue=value->get_string())
                    513:                form_string_value2part(key, *svalue, part);
                    514:        else if(Table* tvalue=value->get_table()) {
1.48      moko      515:                Form_table_value2string_info info(key, *part.string);
1.22      misha     516:                part.info = &info;
                    517:                tvalue->for_each(form_table_value2part, &part);
1.33      misha     518:        } else if(VFile* vfile=static_cast<VFile *>(value->as("file"))){
1.22      misha     519:                form_file_value2part(key, *vfile, part);
                    520:        } else
1.73      moko      521:                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     522: }
                    523: 
                    524: const char* pa_form2string_multipart(HashStringValue& form, Request& r, const char* boundary, size_t& post_size){
1.48      moko      525:        FormPart formpart(&r, boundary);
1.22      misha     526:        form.for_each<FormPart&>(form_value2part, formpart);
1.48      moko      527:        *formpart.string << "--" << boundary << "--";
                    528:        // @todo: return binary blocks here to save memory in pa_internal_file_read_http
                    529:        return formpart.post(post_size);
1.22      misha     530: }
                    531: 
1.54      misha     532: // Set-Cookie: name=value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly
                    533: static ArrayString* parse_cookie(Request& r, const String& cookie) {
1.64      moko      534:        char *current=pa_strdup(cookie.cstr());
1.54      misha     535:        
                    536:        const String* name=0;
1.55      moko      537:        const String* value=&String::Empty;
                    538:        const String* expires=&String::Empty;
                    539:        const String* max_age=&String::Empty;
                    540:        const String* path=&String::Empty;
                    541:        const String* domain=&String::Empty;
                    542:        const String* httponly=&String::Empty;
                    543:        const String* secure=&String::Empty;
1.54      misha     544: 
                    545:        bool first_pair=true;
                    546: 
                    547:        do {
                    548:                if(char *meaning=search_stop(current, ';'))
                    549:                        if(char *attribute=search_stop(meaning, '=')) {
                    550:                                const String* sname=new String(unescape_chars(attribute, strlen(attribute), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
                    551:                                const String* smeaning=0;
                    552:                                if(meaning)
                    553:                                        smeaning=new String(unescape_chars(meaning, strlen(meaning), &r.charsets.source(), true/*don't convert '"' to space*/), String::L_TAINTED);
                    554: 
                    555:                                if(first_pair) {
                    556:                                        // name + value
                    557:                                        name=sname;
                    558:                                        value=smeaning;
                    559:                                        first_pair=false;
                    560:                                } else {
                    561:                                        const String& slower=sname->change_case(r.charsets.source(), String::CC_LOWER);
                    562: 
                    563:                                        if(slower == "expires")
                    564:                                                expires=smeaning;
                    565:                                        else if(slower == "max-age")
                    566:                                                max_age=smeaning;
                    567:                                        else if(slower == "domain")
                    568:                                                domain=smeaning;
                    569:                                        else if(slower == "path")
                    570:                                                path=smeaning;
                    571:                                        else if(slower == "httponly")
                    572:                                                httponly=new String("1", String::L_CLEAN);
                    573:                                        else if(slower == "secure")
                    574:                                                secure=new String("1", String::L_CLEAN);
                    575:                                        else {
                    576:                                                // todo@ ?
                    577:                                        }
                    578:                                }
                    579:                        }
                    580:        } while(current);
                    581: 
                    582:        if(!name)
                    583:                return 0;
                    584: 
                    585:        ArrayString* result=new ArrayString(8);
                    586:        *result+=name;
                    587:        *result+=value;
                    588:        *result+=expires;
                    589:        *result+=max_age;
                    590:        *result+=domain;
                    591:        *result+=path;
                    592:        *result+=httponly;
                    593:        *result+=secure;
                    594: 
                    595:        return result;
                    596: }
                    597: 
1.56      misha     598: Table* parse_cookies(Request& r, Table *cookies){
                    599:        Table& result=*new Table(new Cookies_table_template_columns);
                    600: 
                    601:        for(Array_iterator<Table::element_type> i(*cookies); i.has_next(); )
                    602:                if(ArrayString* row=parse_cookie(r, *i.next()->get(0)))
                    603:                        result+=row;
                    604: 
                    605:        return &result;
                    606: }
                    607: 
1.75      moko      608: void tables_update(HashStringValue& tables, const String::Body name, const String& value){
1.72      moko      609:        Table *table;
                    610:        if(Value *valready=tables.get(name)) {
                    611:                // second+ appearence
                    612:                table=valready->get_table();
                    613:        } else {
                    614:                // first appearence
                    615:                Table::columns_type columns=new ArrayString(1);
                    616:                *columns+=new String("value");
                    617:                table=new Table(columns);
                    618:                tables.put(name, new VTable(table));
                    619:        }
                    620:        // this string becomes next row
                    621:        ArrayString& row=*new ArrayString(1);
                    622:        row+=&value;
                    623:        *table+=&row;
                    624: }
                    625: 
1.1       paf       626: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.72      moko      627: 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       628:        File_read_http_result result;
1.20      misha     629:        char host[MAX_STRING];
1.66      moko      630:        const char *idna_host;
1.1       paf       631:        const char* uri; 
1.49      moko      632:        short port=80;
1.10      misha     633:        const char* method="GET";
1.21      misha     634:        bool method_is_get=true;
1.1       paf       635:        HashStringValue* form=0;
                    636:        int timeout_secs=2;
                    637:        bool fail_on_status_ne_200=true;
1.12      misha     638:        bool omit_post_charset=false;
1.1       paf       639:        Value* vheaders=0;
1.10      misha     640:        Value* vcookies=0;
1.11      misha     641:        Value* vbody=0;
1.72      moko      642:        Charset* asked_remote_charset=0;
1.58      moko      643:        Charset* real_remote_charset=0;
1.1       paf       644:        const char* user_cstr=0;
                    645:        const char* password_cstr=0;
1.22      misha     646:        const char* encode=0;
                    647:        bool multipart=false;
1.1       paf       648: 
                    649:        if(options) {
                    650:                int valid_options=pa_get_valid_file_options_count(*options);
                    651: 
                    652:                if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
                    653:                        valid_options++;
1.21      misha     654:                        method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
                    655:                        method_is_get=strcmp(method, "GET")==0;
1.1       paf       656:                }
1.22      misha     657:                if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
                    658:                        valid_options++;
                    659:                        encode=vencode->as_string().cstr();
                    660:                }
1.1       paf       661:                if(Value* vform=options->get(HTTP_FORM_NAME)) {
                    662:                        valid_options++;
                    663:                        form=vform->get_hash(); 
                    664:                } 
1.11      misha     665:                if(vbody=options->get(HTTP_BODY_NAME)) {
1.1       paf       666:                        valid_options++;
                    667:                } 
                    668:                if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
                    669:                        valid_options++;
                    670:                        timeout_secs=vtimeout->as_int(); 
                    671:                } 
1.11      misha     672:                if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1       paf       673:                        valid_options++;
                    674:                } 
1.11      misha     675:                if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10      misha     676:                        valid_options++;
                    677:                } 
1.1       paf       678:                if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
                    679:                        valid_options++;
                    680:                        fail_on_status_ne_200=!vany_status->as_bool(); 
1.12      misha     681:                }
1.20      misha     682:                if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12      misha     683:                        valid_options++;
                    684:                        omit_post_charset=vomit_post_charset->as_bool();
                    685:                }
1.6       misha     686:                if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.77      moko      687:                        asked_remote_charset=&pa_charsets.get(vcharset_name->as_string());
1.58      moko      688:                } 
                    689:                if(Value* vresponse_charset_name=options->get(PA_RESPONSE_CHARSET_NAME)) {
1.61      moko      690:                        valid_options++;
1.77      moko      691:                        real_remote_charset=&pa_charsets.get(vresponse_charset_name->as_string());
1.1       paf       692:                } 
                    693:                if(Value* vuser=options->get(HTTP_USER)) {
                    694:                        valid_options++;
                    695:                        user_cstr=vuser->as_string().cstr();
                    696:                } 
                    697:                if(Value* vpassword=options->get(HTTP_PASSWORD)) {
                    698:                        valid_options++;
                    699:                        password_cstr=vpassword->as_string().cstr();
                    700:                }
                    701: 
                    702:                if(valid_options!=options->count())
1.46      misha     703:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       paf       704:        }
                    705:        if(!asked_remote_charset) // defaulting to $request:charset
1.22      misha     706:                asked_remote_charset=&(r.charsets).source();
                    707: 
                    708:        if(encode){
                    709:                if(method_is_get)
1.72      moko      710:                        throw Exception(PARSER_RUNTIME, 0, "you can not use $." HTTP_FORM_ENCTYPE_NAME " option with method GET");
1.22      misha     711: 
                    712:                multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
                    713: 
                    714:                if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
1.72      moko      715:                        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     716:        }
1.1       paf       717: 
1.11      misha     718:        if(vbody){
                    719:                if(method_is_get)
1.72      moko      720:                        throw Exception(PARSER_RUNTIME, 0, "you can not use $." HTTP_BODY_NAME " option with method GET");
1.11      misha     721: 
                    722:                if(form)
1.72      moko      723:                        throw Exception(PARSER_RUNTIME, 0, "you can not use options $." HTTP_BODY_NAME " and $." HTTP_FORM_NAME " together");
1.11      misha     724:        }
1.1       paf       725: 
                    726:        //preparing request
1.29      misha     727:        String& connect_string=*new String(file_spec);
1.1       paf       728: 
1.48      moko      729:        const char* request;
                    730:        size_t request_size;
1.1       paf       731:        {
                    732:                // influence URLencoding of tainted pieces to String::L_URI lang
1.22      misha     733:                Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1       paf       734: 
1.44      misha     735:                const char* connect_string_cstr=connect_string.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1       paf       736: 
                    737:                const char* current=connect_string_cstr;
                    738:                if(strncmp(current, "http://", 7)!=0)
1.72      moko      739:                        throw Exception(PARSER_RUNTIME, &connect_string, "does not start with http://"); //never
1.1       paf       740:                current+=7;
                    741: 
                    742:                strncpy(host, current, sizeof(host)-1);  host[sizeof(host)-1]=0;
1.34      misha     743:                char* host_uri=lsplit(host, '/');
                    744:                uri=host_uri?current+(host_uri-1-host):"/";
                    745:                char* port_cstr=lsplit(host, ':');
1.49      moko      746:                
                    747:                if (port_cstr){
                    748:                        char* error_pos=0;
                    749:                        port=(short)strtol(port_cstr, &error_pos, 10);
                    750:                        if(port==0 || *error_pos)
                    751:                                throw Exception(PARSER_RUNTIME, &connect_string, "invalid port number '%s'", port_cstr);
                    752:                }
1.1       paf       753: 
1.66      moko      754:                idna_host=pa_idna_encode(host, r.charsets.source());
                    755: 
1.11      misha     756:                // making request head
1.1       paf       757:                String head;
1.11      misha     758:                head << method << " " << uri;
1.28      misha     759:                if(method_is_get && form)
                    760:                        head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11      misha     761: 
1.66      moko      762:                head <<" HTTP/1.0" CRLF "Host: "<< idna_host;
1.49      moko      763:                if (port != 80)
                    764:                        head << ":" << port_cstr;
                    765:                head << CRLF;
1.11      misha     766: 
1.71      moko      767:                char* boundary= multipart ? get_uuid_boundary() : 0;
1.22      misha     768: 
1.35      misha     769:                String user_headers;
                    770:                bool user_agent_specified=false;
                    771:                bool content_type_specified=false;
                    772:                bool content_type_url_encoded=false;
                    773:                if(vheaders && !vheaders->is_string()) { // allow empty
                    774:                        if(HashStringValue *headers=vheaders->get_hash()) {
                    775:                                Http_pass_header_info info={
                    776:                                        &(r.charsets),
                    777:                                        &user_headers,
                    778:                                        &user_agent_specified,
                    779:                                        &content_type_specified,
                    780:                                        &content_type_url_encoded};
                    781:                                headers->for_each<Http_pass_header_info*>(http_pass_header, &info); 
                    782:                        } else
1.72      moko      783:                                throw Exception(PARSER_RUNTIME, 0, "headers param must be hash"); 
1.35      misha     784:                };
                    785: 
1.48      moko      786:                const char* request_body=0;
1.22      misha     787:                size_t post_size=0;
                    788:                if(form && !method_is_get) {
1.38      misha     789:                        head << "Content-Type: " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
1.28      misha     790: 
                    791:                        if(!omit_post_charset)
                    792:                                head << "; charset=" << asked_remote_charset->NAME_CSTR();
                    793: 
1.22      misha     794:                        if(multipart) {
1.28      misha     795:                                head << "; boundary=" << boundary;
1.48      moko      796:                                request_body=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22      misha     797:                        } else {
1.48      moko      798:                                request_body=pa_form2string(*form, r.charsets);
                    799:                                post_size=strlen(request_body);
1.22      misha     800:                        }
1.28      misha     801:                        head << CRLF;
1.35      misha     802:                } else if(vbody) {
1.38      misha     803:                        // $.body was specified
1.35      misha     804:                        if(content_type_url_encoded){
1.36      misha     805:                                // transcode + url-encode
1.48      moko      806:                                request_body=vbody->as_string().untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.35      misha     807:                        } else {
1.36      misha     808:                                // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.72      moko      809:                                const String &sbody=vbody->as_string();
                    810:                                request_body=Charset::transcode(String::C(sbody.cstr(), sbody.length()), r.charsets.source(), *asked_remote_charset).str;
1.35      misha     811:                        }
1.48      moko      812:                        post_size=strlen(request_body);
1.1       paf       813:                }
                    814: 
                    815:                // http://www.ietf.org/rfc/rfc2617.txt
                    816:                if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.38      misha     817:                        head << "Authorization: " << *authorization_field_value << CRLF;
1.1       paf       818: 
1.35      misha     819:                head << user_headers;
                    820: 
1.1       paf       821:                if(!user_agent_specified) // defaulting
1.38      misha     822:                        head << "User-Agent: " DEFAULT_USER_AGENT CRLF;
1.1       paf       823: 
1.12      misha     824:                if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
1.72      moko      825:                        throw Exception(PARSER_RUNTIME, 0, "$.content-type can't be specified with method POST"); 
1.12      misha     826: 
1.11      misha     827:                if(vcookies && !vcookies->is_string()){ // allow empty
1.10      misha     828:                        if(HashStringValue* cookies=vcookies->get_hash()) {
1.37      misha     829:                                head << "Cookie: ";
1.35      misha     830:                                Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10      misha     831:                                cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info); 
                    832:                                head << CRLF;
                    833:                        } else
1.72      moko      834:                                throw Exception(PARSER_RUNTIME, 0, "cookies param must be hash");
1.10      misha     835:                }
                    836: 
1.48      moko      837:                if(request_body)
1.38      misha     838:                        head << "Content-Length: " << format(post_size, "%u") << CRLF;
1.48      moko      839:                
                    840:                head << CRLF;
                    841:                
                    842:                const char *request_head=head.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1       paf       843: 
1.48      moko      844:                if(request_body){
                    845:                        size_t head_size = strlen(request_head);
                    846:                        request_size=post_size + head_size;
                    847:                        char *ptr=(char *)pa_malloc_atomic(request_size);
                    848:                        memcpy(ptr, request_head, head_size);
                    849:                        memcpy(ptr+head_size, request_body, post_size);
                    850:                        request=ptr;
                    851:                } else {
                    852:                        request_size=strlen(request_head);
                    853:                        request=request_head;
                    854:                }
1.1       paf       855:        }
                    856:        
1.78      moko      857: 
1.97      moko      858:        HTTP_response response;
1.22      misha     859: 
1.28      misha     860:        // sending request
1.95      moko      861:        int status_code;
                    862:        ALTER_EXCEPTION_SOURCE(status_code=http_request(response, idna_host, port, request, request_size, timeout_secs, fail_on_status_ne_200), &connect_string);
1.78      moko      863: 
1.72      moko      864:        // processing results
1.78      moko      865:        char* raw_body=response.buf + response.body_offset;
                    866:        size_t raw_body_size=response.length - response.body_offset;
                    867: 
1.1       paf       868:        result.headers=new HashStringValue;
                    869:        VHash* vtables=new VHash;
1.72      moko      870:        result.headers->put("tables", vtables);
                    871: 
1.78      moko      872:        if (!real_remote_charset && !response.headers.content_type.is_empty())
                    873:                real_remote_charset=detect_charset(response.headers.content_type.cstr());
1.1       paf       874: 
1.72      moko      875:        if(as_text)
1.77      moko      876:                real_remote_charset=pa_charsets.checkBOM(raw_body, raw_body_size, real_remote_charset);
1.72      moko      877: 
                    878:        if (!real_remote_charset)
                    879:                real_remote_charset=asked_remote_charset; // never null
                    880: 
1.85      moko      881:        for(Array_iterator<HTTP_Headers::Header> i(response.headers.headers); i.has_next(); ){
                    882:                HTTP_Headers::Header header=i.next();
1.72      moko      883: 
                    884:                header.transcode(*real_remote_charset, r.charsets.source());
                    885: 
                    886:                String &header_value=*new String(header.value, String::L_TAINTED);
                    887: 
                    888:                tables_update(vtables->hash(), header.name, header_value);
                    889:                result.headers->put(header.name, new VString(header_value));
1.16      misha     890:        }
                    891: 
1.72      moko      892:        // filling $.cookies
1.89      moko      893:        if(vcookies=vtables->hash().get("SET-COOKIE"))
1.72      moko      894:                result.headers->put(HTTP_COOKIES_NAME, new VTable(parse_cookies(r, vcookies->get_table())));
                    895: 
1.1       paf       896:        // output response
                    897:        String::C real_body=String::C(raw_body, raw_body_size);
1.16      misha     898: 
                    899:        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     900:                real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.1       paf       901:        }
                    902: 
                    903:        result.str=const_cast<char *>(real_body.str); // hacking a little
                    904:        result.length=real_body.length;
1.16      misha     905: 
1.22      misha     906:        if(as_text && result.length)
                    907:                fix_line_breaks(result.str, result.length);
                    908: 
1.1       paf       909:        result.headers->put(file_status_name, new VInt(status_code));
1.16      misha     910: 
1.1       paf       911:        return result;
                    912: }
1.84      moko      913: 
                    914: /* ********************** httpd *************************** */
                    915: 
1.100     moko      916: enum EscapeState {
                    917:         Initial,
                    918:         Default,
                    919:         EscapeFirst,
                    920:         EscapeSecond
                    921: };
                    922: 
                    923: static bool check_uri(const char *uri){
                    924:        EscapeState state=Initial;
                    925:        uint escapedValue;
                    926: 
                    927:        const char *pattern="/../";
                    928:        const char *pos=pattern;
                    929: 
                    930:        while(*uri){
                    931:                uchar c=(uchar)*(uri++);
                    932:                switch(state) {
                    933:                        case Initial:
                    934:                                if(c!='/')
                    935:                                        return false;
                    936:                                state=Default;
                    937:                                break;
                    938:                        case Default:
                    939:                                if(c=='%'){
                    940:                                        state=EscapeFirst;
                    941:                                        continue;
                    942:                                }
                    943:                                if(c=='?')
                    944:                                        return true;
                    945:                                break;
                    946:                        case EscapeFirst:
                    947:                                if(isxdigit(c)){
                    948:                                        state=EscapeSecond;
                    949:                                        escapedValue=hex_value[c] << 4;
                    950:                                        continue;
                    951:                                }
                    952:                                return false;
                    953:                        case EscapeSecond:
                    954:                                if(isxdigit(c)){
                    955:                                        state=Default;
1.105     moko      956:                                        c=(uchar)(escapedValue + hex_value[c]);
1.100     moko      957: 
                    958:                                        // implementing Apache AllowEncodedSlashes Off just in case
                    959:                                        if(c=='/' || c=='\\')
                    960:                                                return false;
                    961: 
                    962:                                        break;
                    963:                                }
                    964:                                return false;
                    965:                }
                    966: 
                    967:                if(c==*pos || c=='\\' && *pos=='/'){
                    968:                        if(!*(++pos))
                    969:                                return false;
                    970:                } else {
                    971:                        pos=pattern;
                    972:                }
                    973:        }
                    974:        return true;
                    975: }
                    976: 
1.84      moko      977: class HTTPD_request : public HTTP_response {
                    978: public:
                    979:        const char *method;
                    980:        const char *uri;
                    981: 
1.97      moko      982:        HTTPD_request() : HTTP_response(), method(NULL), uri(NULL){};
1.84      moko      983: 
1.104     moko      984:        ssize_t pa_recv(int sockfd, char *buf, size_t len);
1.103     moko      985: 
                    986:        bool read(int sock, size_t size){
                    987:                if(length + size > buf_size)
                    988:                        resize(buf_size * 2 + size);
                    989:                ssize_t received_size=pa_recv(sock, buf + length, size);
                    990:                if(received_size == 0)
                    991:                        return false;
                    992:                if(received_size < 0) {
                    993:                        if(int no = pa_socks_errno())
                    994:                                throw Exception("httpd.timeout", 0, "error receiving request: %s (%d)", pa_socks_strerr(no), no);
                    995:                        return false;
                    996:                }
                    997:                length+=received_size;
                    998:                buf[length]='\0';
                    999:                return true;
                   1000:        }
                   1001: 
1.84      moko     1002:        const char *extract_method(char *method_line){
                   1003:                char* uri_start = strchr(method_line, ' ');
                   1004: 
                   1005:                if(!uri_start || uri_start == method_line)
                   1006:                        return NULL;
                   1007: 
                   1008:                char* uri_end=strchr(uri_start+1, ' ');
                   1009: 
                   1010:                if(!uri_end || uri_end == uri_start+1)
                   1011:                        return NULL;
                   1012: 
                   1013:                uri=pa_strdup(uri_start+1, uri_end-uri_start-1);
1.100     moko     1014:                if(!check_uri(uri))
                   1015:                        throw Exception("httpd.request", 0, "invalid uri '%s'", uri);
                   1016: 
1.84      moko     1017:                return str_upper(method_line, uri_start-method_line);
                   1018:        }
                   1019: 
1.103     moko     1020: 
1.87      moko     1021:        void read_header(int);
                   1022:        size_t read_post(int, char *, size_t);
1.84      moko     1023: };
                   1024: 
                   1025: enum HTTPD_request_state {
                   1026:        HTTPD_METHOD,
                   1027:        HTTPD_HEADERS
                   1028: };
                   1029: 
1.104     moko     1030: ssize_t HTTPD_request::pa_recv(int sockfd, char *buffer, size_t len){
1.107     moko     1031:        if(HTTPD_Server::mode == HTTPD_Server::MULTITHREADED)
                   1032:                return recv(sockfd, buffer, len, 0);
                   1033: 
                   1034: #ifdef PA_USE_ALARM
1.103     moko     1035:        signal(SIGALRM, timeout_handler);
                   1036:        if(sigsetjmp(timeout_env, 1)) {
                   1037:                throw Exception("httpd.timeout", 0, "timeout occurred while receiving request");
                   1038:                return 0; // never
                   1039:        } else
1.107     moko     1040: #endif
1.103     moko     1041:        {
1.107     moko     1042:                ALARM(pa_httpd_timeout);
1.104     moko     1043:                ssize_t result=recv(sockfd, buffer, len, 0);
1.107     moko     1044:                ALARM(0);
1.103     moko     1045:                return result;
                   1046:        }
                   1047: }
                   1048: 
1.84      moko     1049: void HTTPD_request::read_header(int sock) {
                   1050:        enum HTTPD_request_state state = HTTPD_METHOD;
                   1051: 
                   1052:        size_t chunk_size = 0x400*4;
                   1053:        resize(chunk_size);
                   1054: 
                   1055:        while(read(sock, chunk_size)){
                   1056:                switch(state){
                   1057:                        case HTTPD_METHOD: {
                   1058:                                size_t method_size = first_line();
                   1059:                                if(!method_size)
                   1060:                                        break;
                   1061: 
                   1062:                                char *method_line = pa_strdup(buf, method_size);
                   1063:                                method = extract_method(method_line);
                   1064: 
1.92      moko     1065:                                if(!method ||
                   1066:                                        strcmp(method, "GET") &&
                   1067:                                        strcmp(method, "HEAD") &&
                   1068:                                        strcmp(method, "POST") &&
                   1069:                                        strcmp(method, "PUT") &&
                   1070:                                        strcmp(method, "DELETE") &&
                   1071:                                        strcmp(method, "PATCH")
                   1072:                                )
1.84      moko     1073:                                        throw Exception("httpd.method", new String(method ? method : method_line), "invalid request method");
                   1074:                                state = HTTPD_HEADERS;
                   1075:                        }
                   1076: 
                   1077:                        case HTTPD_HEADERS: {
                   1078:                                if(!body_start())
                   1079:                                        break;
                   1080: 
                   1081:                                parse_headers();
                   1082:                                return;
                   1083:                        }
                   1084:                }
                   1085:        }
                   1086: 
                   1087:        if(state == HTTPD_METHOD)
                   1088:                throw Exception("httpd.request", 0, "bad request from host - no method found (size=%u)", length);
                   1089: 
                   1090:        if(state == HTTPD_HEADERS){
                   1091:                parse_headers();
                   1092:                body_offset=length;
                   1093:        }
                   1094: }
                   1095: 
1.87      moko     1096: size_t HTTPD_request::read_post(int sock, char *body, size_t max_bytes) {
                   1097:        size_t total_read = min(length - body_offset, max_bytes);
1.98      moko     1098:        memcpy(body, buf + body_offset, total_read);
1.87      moko     1099: 
                   1100:        while (total_read < max_bytes){
1.103     moko     1101:                ssize_t received_size = pa_recv(sock, body + total_read, max_bytes - total_read);
1.87      moko     1102:                if(received_size == 0)
                   1103:                        return total_read;
                   1104:                if(received_size < 0) {
                   1105:                        if(int no = pa_socks_errno())
1.97      moko     1106:                                throw Exception("httpd.timeout", new String(uri), "error receiving request body: %s (%d)", pa_socks_strerr(no), no);
1.87      moko     1107:                        return total_read;
                   1108:                }
                   1109:                total_read += received_size;
                   1110:        }
                   1111:        return total_read;
                   1112: }
                   1113: 
1.84      moko     1114: /* ********************************************************** */
                   1115: 
1.85      moko     1116: Array<HTTP_Headers::Header> &HTTPD_Connection::headers() {
1.84      moko     1117:        return request->headers.headers;
                   1118: }
                   1119: 
                   1120: const char *HTTPD_Connection::method() {
                   1121:        return request->method;
                   1122: }
                   1123: 
                   1124: const char *HTTPD_Connection::uri() {
                   1125:        return request->uri;
                   1126: }
                   1127: 
                   1128: const char *HTTPD_Connection::content_type() {
                   1129:        return request->headers.content_type.cstr();
                   1130: }
                   1131: 
                   1132: uint64_t HTTPD_Connection::content_length(){
                   1133:        return request->headers.content_length;
                   1134: }
                   1135: 
                   1136: void HTTPD_Connection::read_header(){
                   1137:        request = new HTTPD_request();
                   1138:        request->read_header(sock);
                   1139: }
                   1140: 
1.87      moko     1141: size_t HTTPD_Connection::read_post(char *body, size_t max_bytes) {
                   1142:        return request->read_post(sock, body, max_bytes);
                   1143: }
                   1144: 
1.90      moko     1145: size_t HTTPD_Connection::send_body(const void *buf, size_t size) {
1.91      moko     1146:        if(send(sock, (const char*)buf, size, 0) != (ssize_t)size) {
1.90      moko     1147:                int no=pa_socks_errno();
                   1148:                throw Exception("httpd.timeout", 0, "error sending response: %s (%d)", pa_socks_strerr(no), no);
                   1149:        }
                   1150:        return size;
                   1151: }
                   1152: 
1.93      moko     1153: HTTPD_Connection::~HTTPD_Connection(){
                   1154:        if(sock != -1)
                   1155:                closesocket(sock);
                   1156: }
                   1157: 
                   1158: static int sock_ready(int fd,int operation,int timeout_value){
                   1159:        struct timeval timeout = {0, timeout_value * 1000};
                   1160:        fd_set fds;
                   1161:        FD_ZERO(&fds);
                   1162:        FD_SET(fd, &fds);
                   1163:        switch (operation){
                   1164:                case 0: return select(fd + 1, &fds, NULL, NULL, &timeout)>0;  /* read */
                   1165:                case 1: return select(fd + 1, NULL, &fds, NULL, &timeout)>0;  /* write */
                   1166:                default: return select(fd + 1, &fds, &fds, NULL, &timeout)>0;  /* both */
                   1167:        }
                   1168: }
                   1169: 
                   1170: bool HTTPD_Connection::accept(int server_sock, int timeout_value) {
                   1171:        int ready = sock_ready(server_sock, 0, timeout_value);
                   1172:        if (ready < 0) {
                   1173:                int no=pa_socks_errno();
                   1174:                if(no == EINTR)
                   1175:                        return false;
                   1176:                throw Exception("httpd.accept", 0, "error waiting for connection: %s (%d)", pa_socks_strerr(no), no);
                   1177:        }
                   1178:        if (ready == 0)
                   1179:                return false; /* Timeout */
                   1180: 
                   1181:        struct sockaddr_in addr;
                   1182:        socklen_t sock_addr_len = sizeof(struct sockaddr_in);
                   1183:        memset(&addr, 0, sock_addr_len);
                   1184: 
                   1185:        sock = ::accept(server_sock, (struct sockaddr *)&addr, &sock_addr_len);
                   1186:        if(server_sock == -1){
                   1187:                int no=pa_socks_errno();
                   1188:                throw Exception("httpd.accept", 0, "error accepting connection: %s (%d)", pa_socks_strerr(no), no);
                   1189:        }
                   1190: 
                   1191:        remote_addr = pa_strdup(inet_ntoa(addr.sin_addr));
                   1192:        return true;
                   1193: }
1.84      moko     1194: 
1.107     moko     1195: HTTPD_Server::HTTPD_MODE HTTPD_Server::mode = HTTPD_Server::SEQUENTIAL;
1.106     moko     1196: 
1.108     moko     1197: void HTTPD_Server::set_mode(const String &value){
                   1198:                 if(value == "sequental") mode = SEQUENTIAL;
                   1199:                 else if (value == "threaded") mode = MULTITHREADED;
                   1200: #ifdef _MSC_VER
                   1201:                else throw Exception("httpd.mode", &value, "$main:HTTPD.mode must be 'sequental' or 'threaded'");
                   1202: #else
                   1203:                 else if (value == "parallel") mode = PARALLEL;
                   1204:                else throw Exception("httpd.mode", &value, "$main:HTTPD.mode must be 'sequental', 'parallel' or 'threaded'");
                   1205: #endif
                   1206: }
                   1207: 
1.86      moko     1208: int HTTPD_Server::bind(const char *host_port){
1.84      moko     1209:        struct sockaddr_in me;
                   1210: 
1.86      moko     1211:        const char *port = strchr(host_port, ':');
                   1212:        const char *host = NULL;
                   1213:        if(port && port > host_port){
                   1214:                host = pa_strdup(host_port, port - host_port);
                   1215:                port += 1;
                   1216:        } else {
                   1217:                port = host_port;
                   1218:        }
                   1219: 
1.105     moko     1220:        if(!set_addr(&me, host, (short)pa_atoui(port))){
1.84      moko     1221:                if (host)
                   1222:                        throw Exception("httpd.bind", 0, "can not resolve hostname \"%s\"", host);
                   1223:                me.sin_addr.s_addr=INADDR_ANY;
                   1224:        }
                   1225: 
                   1226:        int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/);
                   1227: 
                   1228:        if(sock < 0){
                   1229:                int no=pa_socks_errno();
                   1230:                throw Exception("httpd.bind", 0, "can not make socket: %s (%d)", pa_socks_strerr(no), no);
                   1231:        }
                   1232: 
1.93      moko     1233:        static int sock_on = 1;
                   1234: 
1.84      moko     1235:        if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&sock_on, sizeof(sock_on)) ||
                   1236:            setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&sock_on, sizeof(sock_on)) ||
                   1237:            ::bind(sock, (struct sockaddr*)&me, sizeof(me)) ||
                   1238:            listen(sock, 16)) {
1.89      moko     1239:                closesocket(sock);
1.84      moko     1240:                int no = pa_socks_errno();
                   1241:                throw Exception("httpd.bind", 0, "can not bind socket: %s (%d)", pa_socks_strerr(no), no);
                   1242:        }
                   1243:        return sock;
                   1244: }

E-mail: