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

1.1       paf         1: /** @file
                      2:        Parser: http support functions.
                      3: 
1.129   ! moko        4:        Copyright (c) 2001-2024 Art. Lebedev Studio (http://www.artlebedev.com)
1.121     moko        5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.1       paf         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.129   ! moko       17: volatile const char * IDENT_PA_HTTP_C="$Id: pa_http.C,v 1.128 2024/10/02 22:54:03 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: 
1.124     moko      176:                ArrayString::Iterator i(aheaders);
1.78      moko      177:                i.next(); // skipping status
1.125     moko      178:                for(;i;){
1.78      moko      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.127     moko      291:                                throw Exception("http.host", 0, "cannot 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.127     moko      295:                                throw Exception("http.connect", 0, "cannot 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.127     moko      314:                                throw Exception("http.connect", 0, "cannot 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.126     moko      514:        } else if(VFile* vfile=dynamic_cast<VFile *>(value)){
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;
1.122     moko      554:                                        if(smeaning)
                    555:                                                value=smeaning;
1.54      misha     556:                                        first_pair=false;
                    557:                                } else {
                    558:                                        const String& slower=sname->change_case(r.charsets.source(), String::CC_LOWER);
                    559: 
                    560:                                        if(slower == "expires")
                    561:                                                expires=smeaning;
                    562:                                        else if(slower == "max-age")
                    563:                                                max_age=smeaning;
                    564:                                        else if(slower == "domain")
                    565:                                                domain=smeaning;
                    566:                                        else if(slower == "path")
                    567:                                                path=smeaning;
                    568:                                        else if(slower == "httponly")
                    569:                                                httponly=new String("1", String::L_CLEAN);
                    570:                                        else if(slower == "secure")
                    571:                                                secure=new String("1", String::L_CLEAN);
                    572:                                        else {
                    573:                                                // todo@ ?
                    574:                                        }
                    575:                                }
                    576:                        }
                    577:        } while(current);
                    578: 
                    579:        if(!name)
                    580:                return 0;
                    581: 
                    582:        ArrayString* result=new ArrayString(8);
                    583:        *result+=name;
                    584:        *result+=value;
                    585:        *result+=expires;
                    586:        *result+=max_age;
                    587:        *result+=domain;
                    588:        *result+=path;
                    589:        *result+=httponly;
                    590:        *result+=secure;
                    591: 
                    592:        return result;
                    593: }
                    594: 
1.56      misha     595: Table* parse_cookies(Request& r, Table *cookies){
                    596:        Table& result=*new Table(new Cookies_table_template_columns);
                    597: 
1.125     moko      598:        for(Array_iterator<Table::element_type> i(*cookies); i; )
1.56      misha     599:                if(ArrayString* row=parse_cookie(r, *i.next()->get(0)))
                    600:                        result+=row;
                    601: 
                    602:        return &result;
                    603: }
                    604: 
1.75      moko      605: void tables_update(HashStringValue& tables, const String::Body name, const String& value){
1.72      moko      606:        Table *table;
                    607:        if(Value *valready=tables.get(name)) {
                    608:                // second+ appearence
                    609:                table=valready->get_table();
                    610:        } else {
                    611:                // first appearence
                    612:                Table::columns_type columns=new ArrayString(1);
                    613:                *columns+=new String("value");
                    614:                table=new Table(columns);
                    615:                tables.put(name, new VTable(table));
                    616:        }
                    617:        // this string becomes next row
                    618:        ArrayString& row=*new ArrayString(1);
                    619:        row+=&value;
                    620:        *table+=&row;
                    621: }
                    622: 
1.1       paf       623: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.72      moko      624: 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       625:        File_read_http_result result;
1.20      misha     626:        char host[MAX_STRING];
1.66      moko      627:        const char *idna_host;
1.1       paf       628:        const char* uri; 
1.49      moko      629:        short port=80;
1.10      misha     630:        const char* method="GET";
1.21      misha     631:        bool method_is_get=true;
1.1       paf       632:        HashStringValue* form=0;
                    633:        int timeout_secs=2;
                    634:        bool fail_on_status_ne_200=true;
1.12      misha     635:        bool omit_post_charset=false;
1.1       paf       636:        Value* vheaders=0;
1.10      misha     637:        Value* vcookies=0;
1.11      misha     638:        Value* vbody=0;
1.72      moko      639:        Charset* asked_remote_charset=0;
1.58      moko      640:        Charset* real_remote_charset=0;
1.1       paf       641:        const char* user_cstr=0;
                    642:        const char* password_cstr=0;
1.22      misha     643:        const char* encode=0;
                    644:        bool multipart=false;
1.1       paf       645: 
                    646:        if(options) {
                    647:                int valid_options=pa_get_valid_file_options_count(*options);
                    648: 
                    649:                if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
                    650:                        valid_options++;
1.21      misha     651:                        method=vmethod->as_string().change_case(r.charsets.source(), String::CC_UPPER).cstr();
                    652:                        method_is_get=strcmp(method, "GET")==0;
1.1       paf       653:                }
1.22      misha     654:                if(Value* vencode=options->get(HTTP_FORM_ENCTYPE_NAME)) {
                    655:                        valid_options++;
                    656:                        encode=vencode->as_string().cstr();
                    657:                }
1.1       paf       658:                if(Value* vform=options->get(HTTP_FORM_NAME)) {
                    659:                        valid_options++;
                    660:                        form=vform->get_hash(); 
                    661:                } 
1.11      misha     662:                if(vbody=options->get(HTTP_BODY_NAME)) {
1.1       paf       663:                        valid_options++;
                    664:                } 
                    665:                if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
                    666:                        valid_options++;
                    667:                        timeout_secs=vtimeout->as_int(); 
                    668:                } 
1.11      misha     669:                if(vheaders=options->get(HTTP_HEADERS_NAME)) {
1.1       paf       670:                        valid_options++;
                    671:                } 
1.11      misha     672:                if(vcookies=options->get(HTTP_COOKIES_NAME)) {
1.10      misha     673:                        valid_options++;
                    674:                } 
1.1       paf       675:                if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
                    676:                        valid_options++;
                    677:                        fail_on_status_ne_200=!vany_status->as_bool(); 
1.12      misha     678:                }
1.20      misha     679:                if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET_NAME)){
1.12      misha     680:                        valid_options++;
                    681:                        omit_post_charset=vomit_post_charset->as_bool();
                    682:                }
1.6       misha     683:                if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
1.77      moko      684:                        asked_remote_charset=&pa_charsets.get(vcharset_name->as_string());
1.58      moko      685:                } 
                    686:                if(Value* vresponse_charset_name=options->get(PA_RESPONSE_CHARSET_NAME)) {
1.61      moko      687:                        valid_options++;
1.77      moko      688:                        real_remote_charset=&pa_charsets.get(vresponse_charset_name->as_string());
1.1       paf       689:                } 
                    690:                if(Value* vuser=options->get(HTTP_USER)) {
                    691:                        valid_options++;
                    692:                        user_cstr=vuser->as_string().cstr();
                    693:                } 
                    694:                if(Value* vpassword=options->get(HTTP_PASSWORD)) {
                    695:                        valid_options++;
                    696:                        password_cstr=vpassword->as_string().cstr();
                    697:                }
                    698: 
                    699:                if(valid_options!=options->count())
1.46      misha     700:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       paf       701:        }
                    702:        if(!asked_remote_charset) // defaulting to $request:charset
1.22      misha     703:                asked_remote_charset=&(r.charsets).source();
                    704: 
                    705:        if(encode){
                    706:                if(method_is_get)
1.127     moko      707:                        throw Exception(PARSER_RUNTIME, 0, "you cannot use $." HTTP_FORM_ENCTYPE_NAME " option with method GET");
1.22      misha     708: 
                    709:                multipart=strcasecmp(encode, HTTP_CONTENT_TYPE_MULTIPART_FORMDATA)==0;
                    710: 
                    711:                if(!multipart && strcasecmp(encode, HTTP_CONTENT_TYPE_FORM_URLENCODED)!=0)
1.72      moko      712:                        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     713:        }
1.1       paf       714: 
1.11      misha     715:        if(vbody){
                    716:                if(method_is_get)
1.127     moko      717:                        throw Exception(PARSER_RUNTIME, 0, "you cannot use $." HTTP_BODY_NAME " option with method GET");
1.11      misha     718: 
                    719:                if(form)
1.127     moko      720:                        throw Exception(PARSER_RUNTIME, 0, "you cannot use options $." HTTP_BODY_NAME " and $." HTTP_FORM_NAME " together");
1.11      misha     721:        }
1.1       paf       722: 
                    723:        //preparing request
1.29      misha     724:        String& connect_string=*new String(file_spec);
1.1       paf       725: 
1.48      moko      726:        const char* request;
                    727:        size_t request_size;
1.1       paf       728:        {
                    729:                // influence URLencoding of tainted pieces to String::L_URI lang
1.22      misha     730:                Temp_client_charset temp(r.charsets, *asked_remote_charset);
1.1       paf       731: 
1.44      misha     732:                const char* connect_string_cstr=connect_string.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1       paf       733: 
                    734:                const char* current=connect_string_cstr;
                    735:                if(strncmp(current, "http://", 7)!=0)
1.72      moko      736:                        throw Exception(PARSER_RUNTIME, &connect_string, "does not start with http://"); //never
1.1       paf       737:                current+=7;
                    738: 
1.119     moko      739:                pa_strncpy(host, current, sizeof(host));
1.34      misha     740:                char* host_uri=lsplit(host, '/');
                    741:                uri=host_uri?current+(host_uri-1-host):"/";
                    742:                char* port_cstr=lsplit(host, ':');
1.49      moko      743:                
                    744:                if (port_cstr){
                    745:                        char* error_pos=0;
                    746:                        port=(short)strtol(port_cstr, &error_pos, 10);
                    747:                        if(port==0 || *error_pos)
                    748:                                throw Exception(PARSER_RUNTIME, &connect_string, "invalid port number '%s'", port_cstr);
                    749:                }
1.1       paf       750: 
1.66      moko      751:                idna_host=pa_idna_encode(host, r.charsets.source());
                    752: 
1.11      misha     753:                // making request head
1.1       paf       754:                String head;
1.11      misha     755:                head << method << " " << uri;
1.28      misha     756:                if(method_is_get && form)
                    757:                        head << (strchr(uri, '?')!=0?"&":"?") << pa_form2string(*form, r.charsets);
1.11      misha     758: 
1.66      moko      759:                head <<" HTTP/1.0" CRLF "Host: "<< idna_host;
1.49      moko      760:                if (port != 80)
                    761:                        head << ":" << port_cstr;
                    762:                head << CRLF;
1.11      misha     763: 
1.71      moko      764:                char* boundary= multipart ? get_uuid_boundary() : 0;
1.22      misha     765: 
1.35      misha     766:                String user_headers;
                    767:                bool user_agent_specified=false;
                    768:                bool content_type_specified=false;
                    769:                bool content_type_url_encoded=false;
                    770:                if(vheaders && !vheaders->is_string()) { // allow empty
                    771:                        if(HashStringValue *headers=vheaders->get_hash()) {
                    772:                                Http_pass_header_info info={
                    773:                                        &(r.charsets),
                    774:                                        &user_headers,
                    775:                                        &user_agent_specified,
                    776:                                        &content_type_specified,
                    777:                                        &content_type_url_encoded};
                    778:                                headers->for_each<Http_pass_header_info*>(http_pass_header, &info); 
                    779:                        } else
1.72      moko      780:                                throw Exception(PARSER_RUNTIME, 0, "headers param must be hash"); 
1.35      misha     781:                };
                    782: 
1.48      moko      783:                const char* request_body=0;
1.22      misha     784:                size_t post_size=0;
                    785:                if(form && !method_is_get) {
1.38      misha     786:                        head << "Content-Type: " << (multipart ? HTTP_CONTENT_TYPE_MULTIPART_FORMDATA : HTTP_CONTENT_TYPE_FORM_URLENCODED);
1.28      misha     787: 
                    788:                        if(!omit_post_charset)
                    789:                                head << "; charset=" << asked_remote_charset->NAME_CSTR();
                    790: 
1.22      misha     791:                        if(multipart) {
1.28      misha     792:                                head << "; boundary=" << boundary;
1.48      moko      793:                                request_body=pa_form2string_multipart(*form, r/*charsets & mime_type needed*/, boundary, post_size/*correct post_size returned here*/);
1.22      misha     794:                        } else {
1.48      moko      795:                                request_body=pa_form2string(*form, r.charsets);
                    796:                                post_size=strlen(request_body);
1.22      misha     797:                        }
1.28      misha     798:                        head << CRLF;
1.35      misha     799:                } else if(vbody) {
1.38      misha     800:                        // $.body was specified
1.35      misha     801:                        if(content_type_url_encoded){
1.36      misha     802:                                // transcode + url-encode
1.48      moko      803:                                request_body=vbody->as_string().untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.35      misha     804:                        } else {
1.36      misha     805:                                // content-type != application/x-www-form-urlencoded -> transcode only, don't url-encode!
1.72      moko      806:                                const String &sbody=vbody->as_string();
                    807:                                request_body=Charset::transcode(String::C(sbody.cstr(), sbody.length()), r.charsets.source(), *asked_remote_charset).str;
1.35      misha     808:                        }
1.48      moko      809:                        post_size=strlen(request_body);
1.1       paf       810:                }
                    811: 
                    812:                // http://www.ietf.org/rfc/rfc2617.txt
                    813:                if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.38      misha     814:                        head << "Authorization: " << *authorization_field_value << CRLF;
1.1       paf       815: 
1.35      misha     816:                head << user_headers;
                    817: 
1.1       paf       818:                if(!user_agent_specified) // defaulting
1.38      misha     819:                        head << "User-Agent: " DEFAULT_USER_AGENT CRLF;
1.1       paf       820: 
1.12      misha     821:                if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
1.72      moko      822:                        throw Exception(PARSER_RUNTIME, 0, "$.content-type can't be specified with method POST"); 
1.12      misha     823: 
1.11      misha     824:                if(vcookies && !vcookies->is_string()){ // allow empty
1.10      misha     825:                        if(HashStringValue* cookies=vcookies->get_hash()) {
1.37      misha     826:                                head << "Cookie: ";
1.35      misha     827:                                Http_pass_header_info info={&(r.charsets), &head, 0, 0, 0};
1.10      misha     828:                                cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info); 
                    829:                                head << CRLF;
                    830:                        } else
1.72      moko      831:                                throw Exception(PARSER_RUNTIME, 0, "cookies param must be hash");
1.10      misha     832:                }
                    833: 
1.48      moko      834:                if(request_body)
1.128     moko      835:                        head << "Content-Length: " << pa_uitoa(post_size) << CRLF;
1.48      moko      836:                
                    837:                head << CRLF;
                    838:                
                    839:                const char *request_head=head.untaint_and_transcode_cstr(String::L_URI, &(r.charsets));
1.1       paf       840: 
1.48      moko      841:                if(request_body){
                    842:                        size_t head_size = strlen(request_head);
                    843:                        request_size=post_size + head_size;
                    844:                        char *ptr=(char *)pa_malloc_atomic(request_size);
                    845:                        memcpy(ptr, request_head, head_size);
                    846:                        memcpy(ptr+head_size, request_body, post_size);
                    847:                        request=ptr;
                    848:                } else {
                    849:                        request_size=strlen(request_head);
                    850:                        request=request_head;
                    851:                }
1.1       paf       852:        }
                    853:        
1.78      moko      854: 
1.97      moko      855:        HTTP_response response;
1.22      misha     856: 
1.28      misha     857:        // sending request
1.95      moko      858:        int status_code;
                    859:        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      860: 
1.72      moko      861:        // processing results
1.78      moko      862:        char* raw_body=response.buf + response.body_offset;
                    863:        size_t raw_body_size=response.length - response.body_offset;
                    864: 
1.1       paf       865:        result.headers=new HashStringValue;
                    866:        VHash* vtables=new VHash;
1.72      moko      867:        result.headers->put("tables", vtables);
                    868: 
1.78      moko      869:        if (!real_remote_charset && !response.headers.content_type.is_empty())
                    870:                real_remote_charset=detect_charset(response.headers.content_type.cstr());
1.1       paf       871: 
1.72      moko      872:        if(as_text)
1.77      moko      873:                real_remote_charset=pa_charsets.checkBOM(raw_body, raw_body_size, real_remote_charset);
1.72      moko      874: 
                    875:        if (!real_remote_charset)
                    876:                real_remote_charset=asked_remote_charset; // never null
                    877: 
1.125     moko      878:        for(Array_iterator<HTTP_Headers::Header> i(response.headers.headers); i; ){
1.85      moko      879:                HTTP_Headers::Header header=i.next();
1.72      moko      880: 
                    881:                header.transcode(*real_remote_charset, r.charsets.source());
                    882: 
                    883:                String &header_value=*new String(header.value, String::L_TAINTED);
                    884: 
                    885:                tables_update(vtables->hash(), header.name, header_value);
                    886:                result.headers->put(header.name, new VString(header_value));
1.16      misha     887:        }
                    888: 
1.72      moko      889:        // filling $.cookies
1.89      moko      890:        if(vcookies=vtables->hash().get("SET-COOKIE"))
1.72      moko      891:                result.headers->put(HTTP_COOKIES_NAME, new VTable(parse_cookies(r, vcookies->get_table())));
                    892: 
1.1       paf       893:        // output response
                    894:        String::C real_body=String::C(raw_body, raw_body_size);
1.16      misha     895: 
                    896:        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     897:                real_body=Charset::transcode(real_body, *real_remote_charset, r.charsets.source());
1.1       paf       898:        }
                    899: 
                    900:        result.str=const_cast<char *>(real_body.str); // hacking a little
                    901:        result.length=real_body.length;
1.16      misha     902: 
1.22      misha     903:        if(as_text && result.length)
                    904:                fix_line_breaks(result.str, result.length);
                    905: 
1.1       paf       906:        result.headers->put(file_status_name, new VInt(status_code));
1.16      misha     907: 
1.1       paf       908:        return result;
                    909: }
1.84      moko      910: 
                    911: /* ********************** httpd *************************** */
                    912: 
1.111     moko      913: #ifdef HTTPD_DEBUG
                    914: void pa_log(const char* fmt, ...);
                    915: #define LOG(action) action
                    916: #else
                    917: #define LOG(action)
                    918: #endif
                    919: 
1.100     moko      920: enum EscapeState {
                    921:         Initial,
                    922:         Default,
                    923:         EscapeFirst,
                    924:         EscapeSecond
                    925: };
                    926: 
                    927: static bool check_uri(const char *uri){
                    928:        EscapeState state=Initial;
1.120     moko      929:        uint escapedValue=0;
1.100     moko      930: 
                    931:        const char *pattern="/../";
                    932:        const char *pos=pattern;
                    933: 
                    934:        while(*uri){
                    935:                uchar c=(uchar)*(uri++);
                    936:                switch(state) {
                    937:                        case Initial:
                    938:                                if(c!='/')
                    939:                                        return false;
                    940:                                state=Default;
                    941:                                break;
                    942:                        case Default:
                    943:                                if(c=='%'){
                    944:                                        state=EscapeFirst;
                    945:                                        continue;
                    946:                                }
                    947:                                if(c=='?')
                    948:                                        return true;
                    949:                                break;
                    950:                        case EscapeFirst:
                    951:                                if(isxdigit(c)){
                    952:                                        state=EscapeSecond;
                    953:                                        escapedValue=hex_value[c] << 4;
                    954:                                        continue;
                    955:                                }
                    956:                                return false;
                    957:                        case EscapeSecond:
                    958:                                if(isxdigit(c)){
                    959:                                        state=Default;
1.105     moko      960:                                        c=(uchar)(escapedValue + hex_value[c]);
1.100     moko      961: 
                    962:                                        // implementing Apache AllowEncodedSlashes Off just in case
                    963:                                        if(c=='/' || c=='\\')
                    964:                                                return false;
                    965: 
                    966:                                        break;
                    967:                                }
                    968:                                return false;
                    969:                }
                    970: 
                    971:                if(c==*pos || c=='\\' && *pos=='/'){
                    972:                        if(!*(++pos))
                    973:                                return false;
                    974:                } else {
                    975:                        pos=pattern;
                    976:                }
                    977:        }
                    978:        return true;
                    979: }
                    980: 
1.84      moko      981: class HTTPD_request : public HTTP_response {
                    982: public:
                    983:        const char *method;
                    984:        const char *uri;
                    985: 
1.97      moko      986:        HTTPD_request() : HTTP_response(), method(NULL), uri(NULL){};
1.84      moko      987: 
1.120     moko      988:        ssize_t pa_recv(SOCKET sockfd, char *buf, size_t len);
1.103     moko      989: 
1.120     moko      990:        bool read(SOCKET sock, size_t size){
1.103     moko      991:                if(length + size > buf_size)
                    992:                        resize(buf_size * 2 + size);
                    993:                ssize_t received_size=pa_recv(sock, buf + length, size);
                    994:                if(received_size == 0)
                    995:                        return false;
                    996:                if(received_size < 0) {
                    997:                        if(int no = pa_socks_errno())
1.111     moko      998:                                throw Exception("httpd.read", 0, "error receiving request: %s (%d)", pa_socks_strerr(no), no);
1.103     moko      999:                        return false;
                   1000:                }
                   1001:                length+=received_size;
                   1002:                buf[length]='\0';
                   1003:                return true;
                   1004:        }
                   1005: 
1.84      moko     1006:        const char *extract_method(char *method_line){
                   1007:                char* uri_start = strchr(method_line, ' ');
                   1008: 
                   1009:                if(!uri_start || uri_start == method_line)
                   1010:                        return NULL;
                   1011: 
                   1012:                char* uri_end=strchr(uri_start+1, ' ');
                   1013: 
                   1014:                if(!uri_end || uri_end == uri_start+1)
                   1015:                        return NULL;
                   1016: 
                   1017:                uri=pa_strdup(uri_start+1, uri_end-uri_start-1);
1.100     moko     1018:                if(!check_uri(uri))
                   1019:                        throw Exception("httpd.request", 0, "invalid uri '%s'", uri);
                   1020: 
1.84      moko     1021:                return str_upper(method_line, uri_start-method_line);
                   1022:        }
                   1023: 
1.103     moko     1024: 
1.120     moko     1025:        bool read_header(SOCKET);
                   1026:        size_t read_post(SOCKET, char *, size_t);
1.84      moko     1027: };
                   1028: 
                   1029: enum HTTPD_request_state {
                   1030:        HTTPD_METHOD,
                   1031:        HTTPD_HEADERS
                   1032: };
                   1033: 
1.120     moko     1034: ssize_t HTTPD_request::pa_recv(SOCKET sockfd, char *buffer, size_t len){
1.111     moko     1035:        LOG(pa_log("httpd [%d] recv %d appending to %d ...", sockfd, len, length));
1.107     moko     1036: 
                   1037: #ifdef PA_USE_ALARM
1.118     moko     1038:        if(PA_NO_THREADS) signal(SIGALRM, timeout_handler);
                   1039:        if(PA_NO_THREADS && sigsetjmp(timeout_env, 1)) {
1.111     moko     1040:                LOG(pa_log("httpd [%d] recv got %d sec timeout", sockfd, pa_httpd_timeout));
                   1041:                if(length) // timeout on "void" connection is normal
                   1042:                        throw Exception("httpd.timeout", 0, "timeout occurred while receiving request");
                   1043:                return 0;
1.103     moko     1044:        } else
1.107     moko     1045: #endif
1.103     moko     1046:        {
1.107     moko     1047:                ALARM(pa_httpd_timeout);
1.104     moko     1048:                ssize_t result=recv(sockfd, buffer, len, 0);
1.107     moko     1049:                ALARM(0);
1.111     moko     1050:                LOG(pa_log("httpd [%d] recv got %d bytes", sockfd, result));
1.112     moko     1051:                LOG(pa_log("httpd [%d] %s", sockfd, buffer));
1.103     moko     1052:                return result;
                   1053:        }
                   1054: }
                   1055: 
1.115     moko     1056: static bool valid_http_method(const char * method){
                   1057:        return method && (
                   1058:                !strcmp(method, "GET") ||
                   1059:                !strcmp(method, "HEAD") ||
                   1060:                !strcmp(method, "POST") ||
                   1061:                !strcmp(method, "PUT") ||
                   1062:                !strcmp(method, "DELETE") ||
                   1063:                !strcmp(method, "CONNECT") ||
                   1064:                !strcmp(method, "OPTIONS") ||
                   1065:                !strcmp(method, "TRACE") ||
                   1066:                !strcmp(method, "PATCH")
                   1067:        );
                   1068: }
                   1069: 
1.120     moko     1070: bool HTTPD_request::read_header(SOCKET sock) {
1.84      moko     1071:        enum HTTPD_request_state state = HTTPD_METHOD;
                   1072: 
                   1073:        size_t chunk_size = 0x400*4;
                   1074:        resize(chunk_size);
                   1075: 
                   1076:        while(read(sock, chunk_size)){
                   1077:                switch(state){
                   1078:                        case HTTPD_METHOD: {
                   1079:                                size_t method_size = first_line();
                   1080:                                if(!method_size)
                   1081:                                        break;
                   1082: 
                   1083:                                char *method_line = pa_strdup(buf, method_size);
                   1084:                                method = extract_method(method_line);
                   1085: 
1.115     moko     1086:                                if(!valid_http_method(method))
1.84      moko     1087:                                        throw Exception("httpd.method", new String(method ? method : method_line), "invalid request method");
                   1088:                                state = HTTPD_HEADERS;
                   1089:                        }
                   1090: 
                   1091:                        case HTTPD_HEADERS: {
                   1092:                                if(!body_start())
                   1093:                                        break;
                   1094: 
                   1095:                                parse_headers();
1.110     moko     1096:                                return true;
1.84      moko     1097:                        }
                   1098:                }
                   1099:        }
                   1100: 
1.111     moko     1101:        if(!length){ // browsers open connections in advance and they will be empty unless user requests more pages
                   1102:                LOG(pa_log("httpd [%d] void request", sock));
1.110     moko     1103:                return false;
1.111     moko     1104:        }
1.110     moko     1105: 
1.84      moko     1106:        if(state == HTTPD_METHOD)
                   1107:                throw Exception("httpd.request", 0, "bad request from host - no method found (size=%u)", length);
                   1108: 
                   1109:        if(state == HTTPD_HEADERS){
                   1110:                parse_headers();
                   1111:                body_offset=length;
                   1112:        }
1.110     moko     1113: 
                   1114:        return true;
1.84      moko     1115: }
                   1116: 
1.120     moko     1117: size_t HTTPD_request::read_post(SOCKET sock, char *body, size_t max_bytes) {
1.87      moko     1118:        size_t total_read = min(length - body_offset, max_bytes);
1.98      moko     1119:        memcpy(body, buf + body_offset, total_read);
1.87      moko     1120: 
                   1121:        while (total_read < max_bytes){
1.103     moko     1122:                ssize_t received_size = pa_recv(sock, body + total_read, max_bytes - total_read);
1.87      moko     1123:                if(received_size == 0)
                   1124:                        return total_read;
                   1125:                if(received_size < 0) {
                   1126:                        if(int no = pa_socks_errno())
1.111     moko     1127:                                throw Exception("httpd.read", new String(uri), "error receiving request body: %s (%d)", pa_socks_strerr(no), no);
1.87      moko     1128:                        return total_read;
                   1129:                }
                   1130:                total_read += received_size;
                   1131:        }
                   1132:        return total_read;
                   1133: }
                   1134: 
1.84      moko     1135: /* ********************************************************** */
                   1136: 
1.85      moko     1137: Array<HTTP_Headers::Header> &HTTPD_Connection::headers() {
1.84      moko     1138:        return request->headers.headers;
                   1139: }
                   1140: 
                   1141: const char *HTTPD_Connection::method() {
                   1142:        return request->method;
                   1143: }
                   1144: 
                   1145: const char *HTTPD_Connection::uri() {
                   1146:        return request->uri;
                   1147: }
                   1148: 
                   1149: const char *HTTPD_Connection::content_type() {
                   1150:        return request->headers.content_type.cstr();
                   1151: }
                   1152: 
                   1153: uint64_t HTTPD_Connection::content_length(){
                   1154:        return request->headers.content_length;
                   1155: }
                   1156: 
1.110     moko     1157: bool HTTPD_Connection::read_header(){
1.84      moko     1158:        request = new HTTPD_request();
1.111     moko     1159:        bool result = request->read_header(sock);
                   1160:        LOG(if(result){
                   1161:                pa_log("httpd [%d] got %s \"%s\"", sock, method(), uri());
                   1162:        })
                   1163:        return result;
1.84      moko     1164: }
                   1165: 
1.87      moko     1166: size_t HTTPD_Connection::read_post(char *body, size_t max_bytes) {
                   1167:        return request->read_post(sock, body, max_bytes);
                   1168: }
                   1169: 
1.90      moko     1170: size_t HTTPD_Connection::send_body(const void *buf, size_t size) {
1.112     moko     1171:        LOG(pa_log("httpd [%d] response %d bytes", sock, size));
                   1172:        LOG(pa_log("httpd [%d] %s", sock, buf));
1.91      moko     1173:        if(send(sock, (const char*)buf, size, 0) != (ssize_t)size) {
1.90      moko     1174:                int no=pa_socks_errno();
1.111     moko     1175:                throw Exception("httpd.write", 0, "error sending response: %s (%d)", pa_socks_strerr(no), no);
1.90      moko     1176:        }
                   1177:        return size;
                   1178: }
                   1179: 
1.93      moko     1180: HTTPD_Connection::~HTTPD_Connection(){
1.120     moko     1181:        if(sock != INVALID_SOCKET){
1.111     moko     1182:                LOG(pa_log("httpd [%d] closed", sock));
1.93      moko     1183:                closesocket(sock);
1.111     moko     1184:        }
1.93      moko     1185: }
                   1186: 
1.120     moko     1187: static int sock_ready(SOCKET fd, int operation, int timeout_value){
1.93      moko     1188:        struct timeval timeout = {0, timeout_value * 1000};
                   1189:        fd_set fds;
                   1190:        FD_ZERO(&fds);
                   1191:        FD_SET(fd, &fds);
1.120     moko     1192:        int nfds = (int)fd + 1; /* typecast as nfds is ignored in MSVC anyway */
1.93      moko     1193:        switch (operation){
1.120     moko     1194:                case 0: return select(nfds, &fds, NULL, NULL, &timeout)>0;  /* read */
                   1195:                case 1: return select(nfds, NULL, &fds, NULL, &timeout)>0;  /* write */
                   1196:                default: return select(nfds, &fds, &fds, NULL, &timeout)>0;  /* both */
1.93      moko     1197:        }
                   1198: }
                   1199: 
1.120     moko     1200: bool HTTPD_Connection::accept(SOCKET server_sock, int timeout_value) {
1.93      moko     1201:        int ready = sock_ready(server_sock, 0, timeout_value);
                   1202:        if (ready < 0) {
                   1203:                int no=pa_socks_errno();
                   1204:                if(no == EINTR)
                   1205:                        return false;
                   1206:                throw Exception("httpd.accept", 0, "error waiting for connection: %s (%d)", pa_socks_strerr(no), no);
                   1207:        }
                   1208:        if (ready == 0)
                   1209:                return false; /* Timeout */
                   1210: 
                   1211:        struct sockaddr_in addr;
                   1212:        socklen_t sock_addr_len = sizeof(struct sockaddr_in);
                   1213:        memset(&addr, 0, sock_addr_len);
                   1214: 
                   1215:        sock = ::accept(server_sock, (struct sockaddr *)&addr, &sock_addr_len);
1.120     moko     1216:        if(sock == INVALID_SOCKET){
1.93      moko     1217:                int no=pa_socks_errno();
                   1218:                throw Exception("httpd.accept", 0, "error accepting connection: %s (%d)", pa_socks_strerr(no), no);
                   1219:        }
                   1220: 
1.123     moko     1221: //     Has no positive performance effect, requires include <netinet/tcp.h>
                   1222: //     static int sock_on=1;
                   1223: //     setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&sock_on, sizeof(sock_on));
                   1224: 
1.93      moko     1225:        remote_addr = pa_strdup(inet_ntoa(addr.sin_addr));
1.111     moko     1226:        LOG(pa_log("httpd [%d] accepted from %s", sock, remote_addr));
1.93      moko     1227:        return true;
                   1228: }
1.84      moko     1229: 
1.107     moko     1230: HTTPD_Server::HTTPD_MODE HTTPD_Server::mode = HTTPD_Server::SEQUENTIAL;
1.114     moko     1231: const char *HTTPD_Server::port=NULL;
1.106     moko     1232: 
1.108     moko     1233: void HTTPD_Server::set_mode(const String &value){
                   1234:                 if(value == "sequental") mode = SEQUENTIAL;
1.113     moko     1235: #ifdef HAVE_TLS
1.108     moko     1236:                 else if (value == "threaded") mode = MULTITHREADED;
1.113     moko     1237: #endif
1.108     moko     1238: #ifdef _MSC_VER
1.117     moko     1239:                else throw Exception("httpd.mode", &value, "$MAIN:HTTPD.mode must be 'sequental' or 'threaded'");
1.108     moko     1240: #else
                   1241:                 else if (value == "parallel") mode = PARALLEL;
1.117     moko     1242:                else throw Exception("httpd.mode", &value, "$MAIN:HTTPD.mode must be 'sequental', 'parallel' or 'threaded'");
1.108     moko     1243: #endif
                   1244: }
                   1245: 
1.120     moko     1246: SOCKET HTTPD_Server::bind(const char *host_port){
1.84      moko     1247:        struct sockaddr_in me;
                   1248: 
1.114     moko     1249:        port = strchr(host_port, ':');
1.86      moko     1250:        const char *host = NULL;
1.116     moko     1251:        if(port){
1.114     moko     1252:                if(port > host_port)
                   1253:                        host = pa_strdup(host_port, port - host_port);
1.86      moko     1254:                port += 1;
                   1255:        } else {
                   1256:                port = host_port;
                   1257:        }
                   1258: 
1.105     moko     1259:        if(!set_addr(&me, host, (short)pa_atoui(port))){
1.84      moko     1260:                if (host)
1.127     moko     1261:                        throw Exception("httpd.bind", 0, "cannot resolve hostname \"%s\"", host);
1.84      moko     1262:                me.sin_addr.s_addr=INADDR_ANY;
                   1263:        }
                   1264: 
1.120     moko     1265:        SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/);
1.84      moko     1266: 
1.120     moko     1267:        if(sock == INVALID_SOCKET){
1.84      moko     1268:                int no=pa_socks_errno();
1.127     moko     1269:                throw Exception("httpd.bind", 0, "cannot make socket: %s (%d)", pa_socks_strerr(no), no);
1.84      moko     1270:        }
                   1271: 
1.93      moko     1272:        static int sock_on = 1;
                   1273: 
1.84      moko     1274:        if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&sock_on, sizeof(sock_on)) ||
                   1275:            setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&sock_on, sizeof(sock_on)) ||
                   1276:            ::bind(sock, (struct sockaddr*)&me, sizeof(me)) ||
                   1277:            listen(sock, 16)) {
1.89      moko     1278:                closesocket(sock);
1.84      moko     1279:                int no = pa_socks_errno();
1.127     moko     1280:                throw Exception("httpd.bind", 0, "cannot bind socket: %s (%d)", pa_socks_strerr(no), no);
1.84      moko     1281:        }
                   1282:        return sock;
                   1283: }

E-mail: