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

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

E-mail: