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

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

E-mail: