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

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

E-mail: