Annotation of parser3/src/main/pa_common.C, revision 1.195

1.15      paf         1: /** @file
1.16      paf         2:        Parser: commonly functions.
                      3: 
1.174     paf         4:        Copyright(c) 2001-2004 ArtLebedev Group (http://www.artlebedev.com)
1.101     paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.111     paf         6: */
1.16      paf         7: 
1.195   ! paf         8: static const char * const IDENT_COMMON_C="$Date: 2004/09/09 13:57:27 $"; 
1.1       paf         9: 
                     10: #include "pa_common.h"
1.4       paf        11: #include "pa_exception.h"
1.154     paf        12: #include "pa_hash.h"
1.14      paf        13: #include "pa_globals.h"
1.154     paf        14: #include "pa_request_charsets.h"
                     15: #include "pa_charsets.h"
                     16: 
                     17: #define PA_HTTP
                     18: 
                     19: #ifdef PA_HTTP
1.126     paf        20: #include "pa_vstring.h"
1.154     paf        21: #include "pa_vint.h"
1.155     paf        22: #include "pa_vhash.h"
                     23: #include "pa_vtable.h"
1.195   ! paf        24: #include "pa_socks.h"
1.154     paf        25: 
                     26: #ifdef CYGWIN
                     27: #define _GNU_H_WINDOWS32_SOCKETS
                     28: // for PASCAL
                     29: #include <windows.h>
                     30: // SOCKET
                     31: typedef u_int  SOCKET;
                     32: int PASCAL closesocket(SOCKET);
                     33: #else
                     34: #      if defined(WIN32)
                     35: #              include <windows.h>
                     36: #      else
                     37: #              define closesocket close
                     38: #      endif
                     39: #endif
1.1       paf        40: 
1.126     paf        41: #else
1.154     paf        42: 
                     43: #      if defined(WIN32)
                     44: #              include <windows.h>
                     45: #      endif
                     46: 
1.98      paf        47: #endif
                     48: 
1.93      paf        49: // some maybe-undefined constants
                     50: 
1.82      paf        51: #ifndef _O_TEXT
                     52: #      define _O_TEXT 0
                     53: #endif
                     54: #ifndef _O_BINARY
                     55: #      define _O_BINARY 0
1.47      paf        56: #endif
1.80      paf        57: 
1.138     paf        58: #ifdef HAVE_FTRUNCATE
                     59: #      define PA_O_TRUNC 0
                     60: #else
                     61: #      ifdef _O_TRUNC
                     62: #              define PA_O_TRUNC _O_TRUNC
                     63: #      else
                     64: #              error you must have either ftruncate function or _O_TRUNC bit declared
                     65: #      endif
1.154     paf        66: #endif
1.176     paf        67: 
                     68: #      ifndef INADDR_NONE
                     69: #              define INADDR_NONE ((ulong) -1)
                     70: #      endif
1.154     paf        71: 
                     72: // defines for globals
                     73: 
                     74: #define FILE_STATUS_NAME  "status"
                     75: 
                     76: // globals
                     77: 
                     78: const String file_status_name(FILE_STATUS_NAME);
                     79: 
1.178     paf        80: // defines
1.154     paf        81: 
                     82: #define HTTP_METHOD_NAME  "method"
1.180     paf        83: #define HTTP_FORM_NAME  "form"
                     84: #define HTTP_BODY_NAME  "body"
1.154     paf        85: #define HTTP_TIMEOUT_NAME    "timeout"
                     86: #define HTTP_HEADERS_NAME "headers"
                     87: #define HTTP_ANY_STATUS_NAME "any-status"
                     88: #define HTTP_CHARSET_NAME "charset"
1.155     paf        89: #define HTTP_TABLES_NAME "tables"
1.178     paf        90: #define HTTP_USER "user"
                     91: #define HTTP_PASSWORD "password"
1.154     paf        92: 
                     93: // defines
                     94: 
1.127     paf        95: #define DEFAULT_USER_AGENT "parser3"
                     96: 
1.154     paf        97: // functions
1.127     paf        98: 
1.154     paf        99: void fix_line_breaks(char *str, size_t& length) {
1.87      paf       100:        //_asm int 3;
1.154     paf       101:        const char* const eob=str+length;
                    102:        char* dest=str;
1.72      parser    103:        // fix DOS: \r\n -> \n
                    104:        // fix Macintosh: \r -> \n
1.154     paf       105:        char* bol=str;
1.137     paf       106:        while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72      parser    107:                size_t len=eol-bol;
                    108:                if(dest!=bol)
1.126     paf       109:                        memcpy(dest, bol, len); 
1.72      parser    110:                dest+=len;
1.126     paf       111:                *dest++='\n'; 
1.72      parser    112: 
1.126     paf       113:                if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72      parser    114:                        bol=eol+2;
1.154     paf       115:                        length--; 
1.126     paf       116:                } else // \r, not \n = Macintosh
1.72      parser    117:                        bol=eol+1;
                    118:        }
1.154     paf       119:        // last piece without \r
1.72      parser    120:        if(dest!=bol)
1.126     paf       121:                memcpy(dest, bol, eob-bol); 
1.154     paf       122:        str[length]=0; // terminating
1.72      parser    123: }
1.18      paf       124: 
1.154     paf       125: char* file_read_text(Request_charsets& charsets, 
                    126:                     const String& file_spec, 
                    127:                     bool fail_on_read_problem,
                    128:                     HashStringValue* params/*, HashStringValue* * out_fields*/) {
                    129:        File_read_result file=
                    130:                file_read(charsets, file_spec, true, params, fail_on_read_problem);
                    131:        return file.success?file.str:0;
1.126     paf       132: }
                    133: 
1.178     paf       134: //http request stuff
1.154     paf       135: #ifdef PA_HTTP
                    136: 
                    137: #undef CRLF
                    138: #define CRLF "\r\n"
1.126     paf       139: 
                    140: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
                    141:     memset(addr, 0, sizeof(*addr)); 
                    142:     addr->sin_family=AF_INET;
                    143:     addr->sin_port=htons(port); 
                    144:     if(host) {
1.175     paf       145:                ulong packed_ip=inet_addr(host);
1.184     paf       146:                if(packed_ip!=INADDR_NONE)
1.185     paf       147:                        memcpy(&addr->sin_addr, &packed_ip, sizeof(packed_ip)); 
1.184     paf       148:                else {
                    149:                        struct hostent *hostIP=gethostbyname(host);
                    150:                        if(hostIP) 
                    151:                                memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length); 
                    152:                        else
                    153:                                return false;
                    154:                } 
1.126     paf       155:     } else 
                    156:                addr->sin_addr.s_addr=INADDR_ANY;
                    157:     return true;
                    158: }
                    159: 
1.171     paf       160: static int http_read_response(char*& response, size_t& response_size, int sock, bool fail_on_status_ne_200){
                    161:        response=(char*)pa_malloc_atomic(1/*terminator*/); // setting memory block type
                    162:        response[(response_size=0)]=0;
1.154     paf       163:        int result=0;
1.171     paf       164:        char* EOLat=0;
1.126     paf       165:        while(true) {
1.171     paf       166:                char buf[MAX_STRING*10]; 
                    167:                ssize_t received_size=recv(sock, buf, sizeof(buf), 0); 
                    168:                if(received_size<=0)
1.126     paf       169:                        break;
1.171     paf       170:                response=(char*)pa_realloc(response, response_size+received_size+1/*terminator*/);
                    171:                memcpy(response+response_size, buf, received_size);
                    172:                response_size+=received_size;
                    173:                response[response_size]=0;
                    174: 
1.192     paf       175:                if(!result && (EOLat=strstr(response, "\n"))) { // checking status in first response
1.171     paf       176:                        const String status_line(pa_strdup(response, EOLat-response));
1.154     paf       177:                        ArrayString astatus; 
                    178:                        size_t pos_after=0;
                    179:                        status_line.split(astatus, pos_after, " "); 
1.182     paf       180:                        const String& status_code=*astatus.get(astatus.count()>1?1:0);
1.154     paf       181:                        result=status_code.as_int(); 
1.142     paf       182: 
1.154     paf       183:                        if(fail_on_status_ne_200 && result!=200)
1.142     paf       184:                                throw Exception("http.status",
1.154     paf       185:                                        &status_code,
1.142     paf       186:                                        "invalid HTTP response status");
                    187:                }
                    188:        }
1.154     paf       189:        if(result)
                    190:                return result;
1.142     paf       191:        else
                    192:                throw Exception("http.response",
                    193:                        0,
1.173     paf       194:                        "bad response from host - no status found (size=%u)", response_size); 
1.126     paf       195: }
                    196: 
                    197: /* ********************** request *************************** */
                    198: 
                    199: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
1.145     paf       200: #      define PA_USE_ALARM
1.126     paf       201: #endif
                    202: 
1.145     paf       203: #ifdef PA_USE_ALARM
1.126     paf       204: static sigjmp_buf timeout_env;
                    205: static void timeout_handler(int sig){
                    206:     siglongjmp(timeout_env, 1); 
                    207: }
                    208: #endif
                    209: 
1.171     paf       210: static int http_request(char*& response, size_t& response_size,
1.193     paf       211:                        const char* host, short port, 
1.152     paf       212:                        const char* request, 
1.166     paf       213:                        int 
                    214: #ifdef PA_USE_ALARM
                    215:                        timeout
                    216: #endif
                    217:                        ,
1.152     paf       218:                        bool fail_on_status_ne_200) {
1.126     paf       219:        if(!host)
                    220:                throw Exception("http.host", 
1.154     paf       221:                        0, 
1.126     paf       222:                        "zero hostname");  //never
                    223: 
1.145     paf       224: #ifdef PA_USE_ALARM
1.146     paf       225:        signal(SIGALRM, timeout_handler); 
1.126     paf       226: #endif
                    227:        int sock=-1;
1.145     paf       228: #ifdef PA_USE_ALARM
                    229:        if(sigsetjmp(timeout_env, 1)) {
                    230:                // stupid gcc [2.95.4] generated bad code
                    231:                // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
                    232:                // rewritten simplier [though duplicating closesocket code]
                    233:                if(sock>=0) 
                    234:                        closesocket(sock); 
                    235:                throw Exception("http.timeout", 
                    236:                        origin_string, 
                    237:                        "timeout occured while retrieving document"); 
1.146     paf       238:                return 0; // never
1.145     paf       239:        } else {
                    240:                alarm(timeout); 
                    241: #endif
1.146     paf       242:                try {
                    243:                        int result;
1.126     paf       244:                        struct sockaddr_in dest;
1.154     paf       245:                
                    246:                        if(!set_addr(&dest, host, port))
1.126     paf       247:                                throw Exception("http.host", 
1.154     paf       248:                                        0, 
1.127     paf       249:                                        "can not resolve hostname \"%s\"", host); 
1.126     paf       250:                        
1.195   ! paf       251:                        if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0) {
        !           252:                                int no=pa_socks_errno();
1.126     paf       253:                                throw Exception("http.connect", 
1.154     paf       254:                                        0, 
1.195   ! paf       255:                                        "can not make socket: %s (%d)", pa_socks_strerr(no), no); 
        !           256:                        }
        !           257:                        if(connect(sock, (struct sockaddr *)&dest, sizeof(dest))) {
        !           258:                                int no=pa_socks_errno();
1.126     paf       259:                                throw Exception("http.connect", 
1.154     paf       260:                                        0, 
1.195   ! paf       261:                                        "can not connect to host \"%s\": %s (%d)", host, pa_socks_strerr(no), no); 
        !           262:                        }
1.126     paf       263:                        size_t request_size=strlen(request);
1.195   ! paf       264:                        if(send(sock, request, request_size, 0)!=(ssize_t)request_size) {
        !           265:                                int no=pa_socks_errno();
1.126     paf       266:                                throw Exception("http.connect", 
1.154     paf       267:                                        0, 
1.195   ! paf       268:                                        "error sending request: %s (%d)", pa_socks_strerr(no), no); 
        !           269:                        }
1.126     paf       270: 
1.171     paf       271:                        result=http_read_response(response, response_size, sock, fail_on_status_ne_200); 
1.142     paf       272:                        closesocket(sock); 
1.145     paf       273: #ifdef PA_USE_ALARM
1.142     paf       274:                        alarm(0)1.126     paf       275: #endif
1.147     paf       276:                        return result;
1.146     paf       277:                } catch(...) {
1.145     paf       278: #ifdef PA_USE_ALARM
1.146     paf       279:                        alarm(0)1.126     paf       280: #endif
1.146     paf       281:                        if(sock>=0) 
                    282:                                closesocket(sock); 
1.154     paf       283:                        rethrow;
1.146     paf       284:                }
1.148     paf       285: #ifdef PA_USE_ALARM
1.126     paf       286:        }
1.148     paf       287: #endif
1.126     paf       288: }
                    289: 
1.127     paf       290: #ifndef DOXYGEN
                    291: struct Http_pass_header_info {
1.154     paf       292:        Request_charsets* charsets;
1.127     paf       293:        String* request;
                    294:        bool user_agent_specified;
                    295: };
                    296: #endif
1.154     paf       297: static void http_pass_header(HashStringValue::key_type key, 
                    298:                             HashStringValue::value_type value, 
                    299:                             Http_pass_header_info *info) {
                    300:     *info->request <<key<<": "
                    301:        << attributed_meaning_to_string(*value, String::L_HTTP_HEADER, false)
                    302:        << CRLF; 
1.135     paf       303:        
1.154     paf       304:     if(String(key, String::L_TAINTED).change_case(info->charsets->source(), String::CC_UPPER)=="USER-AGENT")
                    305:        info->user_agent_specified=true;
1.126     paf       306: }
1.154     paf       307: 
                    308: 
                    309: static Charset* detect_charset(Charset& source_charset, const String& content_type_value) {
1.156     paf       310:        const String::Body CONTENT_TYPE_VALUE=
1.154     paf       311:                content_type_value.change_case(source_charset, String::CC_UPPER);
                    312:        // content-type: xxx/xxx; source_charset=WE-NEED-THIS
                    313:        // content-type: xxx/xxx; source_charset="WE-NEED-THIS"
                    314:        // content-type: xxx/xxx; source_charset="WE-NEED-THIS";
                    315:        size_t before_charseteq_pos=CONTENT_TYPE_VALUE.pos("CHARSET=");
                    316:        if(before_charseteq_pos!=STRING_NOT_FOUND) {
                    317:                size_t charset_begin=before_charseteq_pos+8/*CHARSET="*/;
                    318:                size_t open_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
                    319:                bool quoted=open_quote_pos==charset_begin;
                    320:                if(quoted)
                    321:                        charset_begin++; // skip opening '"'
                    322:                size_t charset_end=CONTENT_TYPE_VALUE.length();
                    323:                if(quoted) {
                    324:                        size_t close_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
                    325:                        if(close_quote_pos!=STRING_NOT_FOUND)
                    326:                                charset_end=close_quote_pos;
                    327:                } else {
                    328:                        size_t delim_pos=CONTENT_TYPE_VALUE.pos(';', charset_begin);
                    329:                        if(delim_pos!=STRING_NOT_FOUND)
                    330:                                charset_end=delim_pos;
                    331:                }
1.156     paf       332:                const String::Body CHARSET_NAME_BODY=
1.154     paf       333:                        CONTENT_TYPE_VALUE.mid(charset_begin, charset_end);
                    334: 
                    335:                return &charsets.get(CHARSET_NAME_BODY);
                    336:        }
                    337: 
                    338:        return 0;
                    339: }
                    340: 
1.178     paf       341: static const String* basic_authorization_field(const char* user, const char* pass) {
                    342:        if(!user&& !pass)
                    343:                return 0;
                    344: 
                    345:        String combined;  
                    346:        if(user)
                    347:                combined<<user;
                    348:        combined<<":";
                    349:        if(pass)
                    350:                combined<<pass;
                    351:        
                    352:        String* result=new String("Basic "); *result<<pa_base64(combined.cstr(), combined.length());
                    353:        return result;
                    354: }
1.154     paf       355: 
1.181     paf       356: static void form_string_value2string(
                    357:                                                                  HashStringValue::key_type key, 
                    358:                                                                  const String& value, 
                    359:                                                                  String& result) 
                    360: {
                    361:        result << String(key, String::L_TAINTED) << "=";
                    362:        result.append(value, String::L_URI, true);
                    363:        result<< "&";
                    364: }
                    365: #ifndef DOXYGEN
                    366: struct Form_table_value2string_info {
                    367:        HashStringValue::key_type key;
                    368:        String& result;
                    369: 
                    370:        Form_table_value2string_info(HashStringValue::key_type akey, String& aresult): 
                    371:                key(akey), result(aresult) {}
                    372: };
                    373: #endif
                    374: static void form_table_value2string(Table::element_type row, Form_table_value2string_info* info) {
                    375:        form_string_value2string(info->key, *row->get(0), info->result);
                    376: }
1.180     paf       377: static void form_value2string(
                    378:                                                                  HashStringValue::key_type key, 
                    379:                                                                  HashStringValue::value_type value, 
                    380:                                                                  String* result) 
                    381: {
1.181     paf       382:        if(const String* svalue=value->get_string())
                    383:                form_string_value2string(key, *svalue, *result);
                    384:        else if(Table* tvalue=value->get_table()) {
                    385:                Form_table_value2string_info info(key, *result);
                    386:                tvalue->for_each(form_table_value2string, &info);
                    387:        } else
                    388:                throw Exception(0,
                    389:                        new String(key, String::L_TAINTED),
                    390:                        "is %s, "HTTP_FORM_NAME" option value must either string or table", value->type());
1.180     paf       391: }
                    392: static const char* form2string(HashStringValue& form) {
                    393:        String string;
                    394:        form.for_each(form_value2string, &string);
1.181     paf       395:        return string.cstr(String::L_UNSPECIFIED);
1.180     paf       396: }
1.154     paf       397: #ifndef DOXYGEN
                    398: struct File_read_http_result {
                    399:        char *str; size_t length;
                    400:        HashStringValue* headers;
                    401: }; 
                    402: #endif
1.194     paf       403: static void find_headers_end(char* p,
                    404:                char*& headers_end_at,
                    405:                char*& raw_body)
                    406: {
                    407:        raw_body=p;
                    408:        // \n\n
                    409:        // \r\n\r\n
                    410:        while((p=strchr(p, '\n'))) {
                    411:                headers_end_at=++p; // \n>.<
                    412:                if(*p=='\r')  // \r\n>\r?<\n
                    413:                        p++;
                    414:                if(*p=='\n') { // \r\n\r>\n?<
                    415:                        raw_body=p+1;
                    416:                        return;                 
                    417:                }
                    418:        }
                    419:        headers_end_at=0;
                    420: }
                    421: 
1.155     paf       422: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.154     paf       423: static File_read_http_result file_read_http(Request_charsets& charsets, 
                    424:                                            const String& file_spec, 
1.169     paf       425:                                            bool as_text,
                    426:                                                HashStringValue *options=0) {
1.154     paf       427:        File_read_http_result result;
1.126     paf       428:        char host[MAX_STRING]; 
1.129     paf       429:        const char* uri; 
1.193     paf       430:        short port;
1.180     paf       431:        const char* method="GET"; bool method_is_get;
                    432:        HashStringValue* form=0;
                    433:        const char* body_cstr=0;
1.126     paf       434:        int timeout=2;
1.142     paf       435:        bool fail_on_status_ne_200=true;
1.154     paf       436:        Value* vheaders=0;
                    437:        Charset *asked_remote_charset=0;
1.178     paf       438:        const char* user_cstr=0;
                    439:        const char* password_cstr=0;
1.126     paf       440: 
1.127     paf       441:        if(options) {
                    442:                int valid_options=0;
1.177     paf       443:                if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
1.127     paf       444:                        valid_options++;
1.154     paf       445:                        method=vmethod->as_string().cstr();
1.181     paf       446:                }
                    447:                if(Value* vform=options->get(HTTP_FORM_NAME)) {
1.180     paf       448:                        valid_options++;
                    449:                        form=vform->get_hash(); 
1.181     paf       450:                } 
                    451:                if(Value* vbody=options->get(HTTP_BODY_NAME)) {
1.180     paf       452:                        valid_options++;
                    453:                        body_cstr=vbody->as_string().cstr(String::L_UNSPECIFIED);
1.181     paf       454:                } 
                    455:                if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
1.127     paf       456:                        valid_options++;
                    457:                        timeout=vtimeout->as_int(); 
1.181     paf       458:                } 
                    459:                if((vheaders=options->get(HTTP_HEADERS_NAME))) {
1.127     paf       460:                        valid_options++;
1.181     paf       461:                } 
                    462:                if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
1.142     paf       463:                        valid_options++;
                    464:                        fail_on_status_ne_200=!vany_status->as_bool(); 
1.181     paf       465:                } 
                    466:                if(Value* vcharset_name=options->get(HTTP_CHARSET_NAME)) {
1.154     paf       467:                        valid_options++;
                    468:                        asked_remote_charset=&::charsets.get(vcharset_name->as_string().
                    469:                                change_case(charsets.source(), String::CC_UPPER));
1.181     paf       470:                } 
                    471:                if(Value* vuser=options->get(HTTP_USER)) {
1.178     paf       472:                        valid_options++;
                    473:                        user_cstr=vuser->as_string().cstr();
1.181     paf       474:                } 
                    475:                if(Value* vpassword=options->get(HTTP_PASSWORD)) {
1.178     paf       476:                        valid_options++;
                    477:                        password_cstr=vpassword->as_string().cstr();
                    478:                }
1.142     paf       479: 
1.154     paf       480:                if(valid_options!=options->count())
1.127     paf       481:                        throw Exception("parser.runtime",
                    482:                                0,
                    483:                                "invalid option passed");
1.154     paf       484:        }
                    485:        if(!asked_remote_charset) // defaulting to $request:charset
                    486:                asked_remote_charset=&charsets.source();
                    487: 
1.180     paf       488:        method_is_get=strcmp(method, "GET")==0;
                    489:        if(method_is_get && body_cstr)
                    490:                throw Exception("parser.runtime",
                    491:                        0,
                    492:                        "you can not use $."HTTP_BODY_NAME" option with method GET");
                    493: 
1.154     paf       494:        //preparing request
                    495:        String& connect_string=*new String;
                    496:        // not in ^sql{... L_SQL ...} spirit, but closer to ^file::load one
                    497:        connect_string.append(file_spec, String::L_URI); // tainted pieces -> URI pieces
                    498: 
1.180     paf       499:        String request_head_and_body;
1.154     paf       500:        {
                    501:                // influence URLencoding of tainted pieces to String::L_URI lang
                    502:                Temp_client_charset temp(charsets, *asked_remote_charset);
                    503: 
                    504:                const char* connect_string_cstr=connect_string.cstr(String::L_UNSPECIFIED); 
1.126     paf       505: 
1.154     paf       506:                const char* current=connect_string_cstr;
                    507:                if(strncmp(current, "http://", 7)!=0)
                    508:                        throw Exception(0, 
                    509:                                &connect_string, 
                    510:                                "does not start with http://"); //never
                    511:                current+=7;
                    512: 
                    513:                strncpy(host, current, sizeof(host)-1);  host[sizeof(host)-1]=0;
                    514:                char* host_uri=lsplit(host, '/'); 
                    515:                uri=host_uri?current+(host_uri-1-host):"/"; 
                    516:                char* port_cstr=lsplit(host, ':'); 
                    517:                char* error_pos=0;
1.193     paf       518:                port=port_cstr?(short)strtol(port_cstr, &error_pos, 0):80;
1.154     paf       519: 
1.180     paf       520:                if(strchr(uri, '?') && form)
                    521:                        throw Exception("parser.runtime",
                    522:                                0,
                    523:                                "use either uri with ?params or $."HTTP_FORM_NAME" option");
                    524: 
                    525:                //making request head
                    526:                String head;
                    527:                head << method;
                    528:                head << " " << uri;
                    529:                if(form)
                    530:                        if(method_is_get)
1.181     paf       531:                                head << "?" << form2string(*form);
1.180     paf       532:                head <<" HTTP/1.0" CRLF
1.154     paf       533:                        "host: "<< host << CRLF; 
1.181     paf       534:                if(form && !method_is_get) {
                    535:                        head << "content-type: application/x-www-form-urlencoded" CRLF;
                    536:                        body_cstr = form2string(*form);
                    537:                }
1.178     paf       538: 
1.179     paf       539:                // http://www.ietf.org/rfc/rfc2617.txt
1.178     paf       540:                if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
1.180     paf       541:                        head<<"authorization: "<<*authorization_field_value<<CRLF;
1.178     paf       542: 
1.154     paf       543:                bool user_agent_specified=false;
                    544:                if(vheaders && !vheaders->is_string()) { // allow empty
                    545:                        if(HashStringValue *headers=vheaders->get_hash()) {
1.180     paf       546:                                Http_pass_header_info info={&charsets, &head, false};
1.154     paf       547:                                headers->for_each(http_pass_header, &info); 
                    548:                                user_agent_specified=info.user_agent_specified;
                    549:                        } else
                    550:                                throw Exception("parser.runtime", 
                    551:                                        &connect_string,
                    552:                                        "headers param must be hash"); 
                    553:                };
                    554:                if(!user_agent_specified) // defaulting
1.180     paf       555:                        head << "user-agent: " DEFAULT_USER_AGENT CRLF;
                    556: 
                    557:                if(body_cstr) {
                    558:                        // recode those pieces which are not in String::L_URI lang 
                    559:                        // [those violating HTTP standard, but widly used]
                    560:                        body_cstr=Charset::transcode(
                    561:                                String::C(body_cstr, strlen(body_cstr)),
                    562:                                charsets.source(),
                    563:                                *asked_remote_charset);
1.181     paf       564: 
                    565:                        head << "content-length: " << format(strlen(body_cstr), "%u") << CRLF;
1.180     paf       566:                }
1.154     paf       567: 
1.181     paf       568:                const char* head_cstr=head.cstr(String::L_UNSPECIFIED);
                    569: 
                    570:                // recode those pieces which are not in String::L_URI lang 
                    571:                // [those violating HTTP standard, but widly used]
                    572:                head_cstr=Charset::transcode(
                    573:                        String::C(head_cstr, strlen(head_cstr)),
                    574:                        charsets.source(),
                    575:                        *asked_remote_charset);
1.180     paf       576: 
1.181     paf       577:                // head + end of header
                    578:                request_head_and_body << head_cstr << CRLF;
1.180     paf       579:                // body
                    580:                if(body_cstr)
                    581:                        request_head_and_body << body_cstr;
1.154     paf       582:        }
1.126     paf       583:        
                    584:        //sending request
1.171     paf       585:        char* response;
                    586:        size_t response_size;
                    587:        int status_code=http_request(response, response_size,
1.180     paf       588:                host, port, request_head_and_body.cstr(), 
1.142     paf       589:                timeout, fail_on_status_ne_200); 
1.126     paf       590:        
                    591:        //processing results    
1.171     paf       592:        char* raw_body; size_t raw_body_size;
1.194     paf       593:        char* headers_end_at;
                    594:        find_headers_end(response, 
                    595:                headers_end_at,
                    596:                raw_body);
1.191     paf       597:        raw_body_size=response_size-(raw_body-response);
1.171     paf       598:        
1.154     paf       599:        result.headers=new HashStringValue;
1.155     paf       600:        VHash* vtables=new VHash;
1.177     paf       601:        result.headers->put(HTTP_TABLES_NAME, vtables);
1.194     paf       602:        Charset* real_remote_charset=0; // undetected, yet
                    603: 
                    604:        if(headers_end_at) {
                    605:                *headers_end_at=0;
                    606:                const String header_block(String::C(response, headers_end_at-response), true);
                    607:                
                    608:                ArrayString aheaders;
                    609:                HashStringValue& tables=vtables->hash();
1.155     paf       610: 
1.194     paf       611:                size_t pos_after=0;
                    612:                header_block.split(aheaders, pos_after, "\n"); 
                    613:                
                    614:                //processing headers
                    615:                size_t aheaders_count=aheaders.count();
                    616:                for(size_t i=1; i<aheaders_count; i++) {
                    617:                        const String& line=*aheaders.get(i);
                    618:                        size_t pos=line.pos(':'); 
                    619:                        if(pos==STRING_NOT_FOUND || pos<1)
                    620:                                throw Exception("http.response", 
                    621:                                        &connect_string,
                    622:                                        "bad response from host - bad header \"%s\"", line.cstr());
                    623:                        const String::Body HEADER_NAME=
                    624:                                line.mid(0, pos).change_case(charsets.source(), String::CC_UPPER);
                    625:                        const String& header_value=line.mid(pos+1, line.length()).trim(String::TRIM_BOTH, " \t\r");
                    626:                        if(as_text && HEADER_NAME=="CONTENT-TYPE")
                    627:                                real_remote_charset=detect_charset(charsets.source(), header_value);
                    628: 
                    629:                        // tables
                    630:                        {
                    631:                                Value *valready=(Value *)tables.get(HEADER_NAME);
                    632:                                bool existed=valready!=0;
                    633:                                Table *table;
                    634:                                if(existed) {
                    635:                                        // second+ appearence
                    636:                                        table=valready->get_table();
                    637:                                } else {
                    638:                                        // first appearence
                    639:                                        Table::columns_type columns =new ArrayString(1);
                    640:                                        *columns+=new String("value");
                    641:                                        table=new Table(columns);
                    642:                                }
                    643:                                // this string becomes next row
                    644:                                ArrayString& row=*new ArrayString(1);
                    645:                                row+=&header_value;
                    646:                                *table+=&row;
                    647:                                // not existed before? add it
                    648:                                if(!existed)
                    649:                                        tables.put(HEADER_NAME, new VTable(table));
1.155     paf       650:                        }
1.194     paf       651: 
                    652:                        result.headers->put(HEADER_NAME, new VString(header_value));
1.155     paf       653:                }
1.126     paf       654:        }
                    655: 
                    656:        // output response
1.171     paf       657:        String::C real_body=String::C(raw_body, raw_body_size);
1.192     paf       658:        if(as_text && raw_body_size) { // must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
                    659:                // defaulting to used-asked charset [it's never empty!]
                    660:                if(!real_remote_charset)
                    661:                        real_remote_charset=asked_remote_charset;
1.169     paf       662:                real_body=Charset::transcode(real_body, *real_remote_charset, charsets.source());
1.192     paf       663:        }
1.154     paf       664: 
                    665:        result.str=const_cast<char *>(real_body.str); // hacking a little
                    666:        result.length=real_body.length;
                    667:        result.headers->put(file_status_name, new VInt(status_code));
                    668:        return result;
1.34      paf       669: }
1.123     paf       670: 
1.154     paf       671: #endif
                    672: 
1.123     paf       673: #ifndef DOXYGEN
                    674: struct File_read_action_info {
1.154     paf       675:        char **data; size_t *data_size;
1.188     paf       676:        char* buf; size_t offset; size_t count;
1.126     paf       677: }; 
1.123     paf       678: #endif
1.154     paf       679: static void file_read_action(
                    680:                             struct stat& finfo, 
                    681:                             int f, 
1.166     paf       682:                             const String& file_spec, const char* /*fname*/, bool as_text, 
1.154     paf       683:                             void *context) {
1.126     paf       684:        File_read_action_info& info=*static_cast<File_read_action_info *>(context); 
1.188     paf       685:        size_t to_read_size=info.count;
                    686:        if(!to_read_size)
                    687:                to_read_size=(size_t)finfo.st_size;
                    688:        assert( !(info.buf && as_text) );
                    689:        if(to_read_size) { 
                    690:                if(info.offset)
                    691:                        lseek(f, info.offset, SEEK_SET);
                    692:                *info.data=info.buf
                    693:                        ? info.buf
                    694:                        : new(PointerFreeGC) char[to_read_size+(as_text?1:0)]; 
1.126     paf       695:                *info.data_size=(size_t)read(f, *info.data, to_read_size); 
1.123     paf       696: 
                    697:                if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126     paf       698:                        throw Exception(0, 
1.123     paf       699:                                &file_spec, 
1.173     paf       700:                                "read failed: actually read %u bytes count not in [0..%u] valid range", 
1.126     paf       701:                                        *info.data_size, to_read_size); 
1.123     paf       702:        } else { // empty file
                    703:                if(as_text) {
1.154     paf       704:                        *info.data=new(PointerFreeGC) char[1]; 
1.123     paf       705:                        *(char*)(*info.data)=0;
                    706:                } else 
                    707:                        *info.data=0;
                    708:                *info.data_size=0;
                    709:                return;
                    710:        }
1.126     paf       711: }
1.154     paf       712: File_read_result file_read(Request_charsets& charsets, const String& file_spec, 
                    713:                           bool as_text, HashStringValue *params,
1.188     paf       714:                           bool fail_on_read_problem,
                    715:                           char* buf, size_t offset, size_t count) {
1.167     paf       716:        File_read_result result={false, 0, 0, 0};
1.154     paf       717: #ifdef PA_HTTP
                    718:        if(file_spec.starts_with("http://")) {
1.126     paf       719:                // fail on read problem
1.169     paf       720:                File_read_http_result http=file_read_http(charsets, file_spec, as_text, params);
1.154     paf       721:                result.success=true;
                    722:                result.str=http.str;
                    723:                result.length=http.length;
                    724:                result.headers=http.headers; 
1.126     paf       725:        } else {
1.154     paf       726: #endif
1.161     paf       727:                if(params && params->count())
                    728:                        throw Exception("parser.runtime",
                    729:                                0,
                    730:                                "invalid option passed");
                    731: 
1.188     paf       732:                File_read_action_info info={&result.str, &result.length,
                    733:                        buf, offset, count}; 
1.154     paf       734:                result.success=file_read_action_under_lock(file_spec, 
1.126     paf       735:                        "read", file_read_action, &info, 
                    736:                        as_text, fail_on_read_problem); 
1.154     paf       737: #ifdef PA_HTTP
1.126     paf       738:        }
1.154     paf       739: #endif
1.123     paf       740: 
1.154     paf       741:        if(result.success && as_text) {
1.131     paf       742:                // UTF-8 signature: EF BB BF
1.154     paf       743:                if(result.length>=3) {
                    744:                        char *in=(char *)result.str;
1.159     paf       745:                        if(strncmp(in, "\xEF\xBB\xBF", 3)==0) {
1.154     paf       746:                                result.str=in+3; result.length-=3;// skip prefix
1.131     paf       747:                        }
                    748:                }
                    749: 
1.154     paf       750:                fix_line_breaks((char *)(result.str), result.length); 
1.123     paf       751:        }
1.126     paf       752: 
                    753:        return result;
1.123     paf       754: }
                    755: 
1.154     paf       756: #ifdef PA_SAFE_MODE 
                    757: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) { 
                    758:        if(finfo.st_uid/*foreign?*/!=geteuid() 
                    759:                && finfo.st_gid/*foreign?*/!=getegid()) 
                    760:                throw Exception("parser.runtime",  
                    761:                        &file_spec,  
                    762:                        "parser is in safe mode: " 
                    763:                        "reading files of foreign group and user disabled " 
                    764:                        "[recompile parser with --disable-safe-mode configure option], " 
                    765:                        "actual filename '%s', " 
                    766:                        "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",  
                    767:                                fname, 
                    768:                                finfo.st_uid, geteuid(), 
                    769:                                finfo.st_gid, getegid()); 
                    770: } 
                    771: #endif 
1.149     paf       772: 
1.154     paf       773: bool file_read_action_under_lock(const String& file_spec, 
1.126     paf       774:                                const char* action_name, File_read_action action, void *context, 
                    775:                                bool as_text, 
1.123     paf       776:                                bool fail_on_read_problem) {
1.154     paf       777:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.33      paf       778:        int f;
                    779: 
                    780:        // first open, next stat:
1.45      paf       781:        // directory update of NTFS hard links performed on open.
1.33      paf       782:        // ex: 
                    783:        //   a.html:^test[] and b.html hardlink to a.html
                    784:        //   user inserts ! before ^test in a.html
1.126     paf       785:        //   directory entry of b.html in NTFS not updated at once, 
1.35      paf       786:        //   they delay update till open, so we would receive "!^test[" string
                    787:        //   if would do stat, next open.
1.123     paf       788:        // later: it seems, even this does not help sometimes
1.98      paf       789:     if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123     paf       790:                try {
1.162     paf       791:                        if(pa_lock_shared_blocking(f)!=0)
1.126     paf       792:                                throw Exception("file.lock", 
1.123     paf       793:                                                &file_spec, 
                    794:                                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       795:                                                        strerror(errno), errno, fname);
1.123     paf       796: 
1.124     paf       797:                        struct stat finfo;
                    798:                        if(stat(fname, &finfo)!=0)
                    799:                                throw Exception("file.missing", // hardly possible: we just opened it OK
                    800:                                        &file_spec, 
                    801:                                        "stat failed: %s (%d), actual filename '%s'", 
1.154     paf       802:                                                strerror(errno), errno, fname);
1.124     paf       803: 
1.140     paf       804: #ifdef PA_SAFE_MODE
1.149     paf       805:                        check_safe_mode(finfo, file_spec, fname);
1.105     paf       806: #endif
1.32      paf       807: 
1.154     paf       808:                        action(finfo, f, file_spec, fname, as_text, context); 
1.123     paf       809:                } catch(...) {
1.162     paf       810:                        pa_unlock(f);close(f); 
1.123     paf       811:                        if(fail_on_read_problem)
1.154     paf       812:                                rethrow;
1.123     paf       813:                        return false;                   
                    814:                } 
1.87      paf       815: 
1.162     paf       816:                pa_unlock(f);close(f); 
1.72      parser    817:                return true;
1.118     paf       818:     } else {
                    819:                if(fail_on_read_problem)
1.126     paf       820:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.118     paf       821:                                &file_spec, 
1.123     paf       822:                                "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       823:                                        action_name, strerror(errno), errno, fname);
1.118     paf       824:                return false;
                    825:        }
1.8       paf       826: }
                    827: 
1.63      parser    828: static void create_dir_for_file(const String& file_spec) {
                    829:        size_t pos_after=1;
1.154     paf       830:        size_t pos_before;
                    831:        while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
                    832:                mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775); 
1.63      parser    833:                pos_after=pos_before+1;
                    834:        }
                    835: }
                    836: 
1.98      paf       837: bool file_write_action_under_lock(
1.28      paf       838:                                const String& file_spec, 
1.126     paf       839:                                const char* action_name, File_write_action action, void *context, 
                    840:                                bool as_text, 
                    841:                                bool do_append, 
                    842:                                bool do_block, 
1.110     paf       843:                                bool fail_on_lock_problem) {
1.154     paf       844:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.28      paf       845:        int f;
1.80      paf       846:        if(access(fname, W_OK)!=0) // no
1.126     paf       847:                create_dir_for_file(file_spec); 
1.50      paf       848: 
1.80      paf       849:        if((f=open(fname, 
                    850:                O_CREAT|O_RDWR
                    851:                |(as_text?_O_TEXT:_O_BINARY)
1.138     paf       852:                |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162     paf       853:                if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126     paf       854:                        Exception e("file.lock", 
1.110     paf       855:                                &file_spec, 
                    856:                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       857:                                strerror(errno), errno, fname);
1.126     paf       858:                        close(f); 
1.110     paf       859:                        if(fail_on_lock_problem)
                    860:                                throw e;
1.98      paf       861:                        return false;
                    862:                }
1.96      paf       863: 
1.158     paf       864:                try {
1.126     paf       865:                        action(f, context); 
1.158     paf       866:                } catch(...) {
1.138     paf       867: #ifdef HAVE_FTRUNCATE
1.104     paf       868:                        if(!do_append)
1.125     paf       869:                                ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138     paf       870: #endif
1.162     paf       871:                        pa_unlock(f);close(f); 
1.154     paf       872:                        rethrow;
1.158     paf       873:                }
1.80      paf       874:                
1.138     paf       875: #ifdef HAVE_FTRUNCATE
1.104     paf       876:                if(!do_append)
1.125     paf       877:                        ftruncate(f, lseek(f, 0, SEEK_CUR)); // O_TRUNC truncates even exclusevely write-locked file [thanks to Igor Milyakov <virtan@rotabanner.com> for discovering]
1.138     paf       878: #endif
1.162     paf       879:                pa_unlock(f);close(f); 
1.98      paf       880:                return true;
1.80      paf       881:        } else
1.126     paf       882:                throw Exception(errno==EACCES?"file.access":0, 
1.80      paf       883:                        &file_spec, 
1.96      paf       884:                        "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       885:                                action_name, strerror(errno), errno, fname);
1.96      paf       886:        // here should be nothing, see rethrow above
                    887: }
                    888: 
                    889: #ifndef DOXYGEN
                    890: struct File_write_action_info {
1.154     paf       891:        const char* str; size_t length;
1.126     paf       892: }; 
1.96      paf       893: #endif
                    894: static void file_write_action(int f, void *context) {
1.126     paf       895:        File_write_action_info& info=*static_cast<File_write_action_info *>(context); 
1.154     paf       896:        if(info.length) {
                    897:                int written=write(f, info.str, info.length); 
1.116     paf       898:                if(written<0)
1.126     paf       899:                        throw Exception(0, 
                    900:                                0, 
                    901:                                "write failed: %s (%d)",  strerror(errno), errno); 
1.113     paf       902:        }
1.96      paf       903: }
                    904: void file_write(
                    905:                                const String& file_spec, 
1.154     paf       906:                                const char* data, size_t size, 
1.126     paf       907:                                bool as_text, 
1.96      paf       908:                                bool do_append) {
1.126     paf       909:        File_write_action_info info={data, size}; 
1.98      paf       910:        file_write_action_under_lock(
1.154     paf       911:                file_spec, 
                    912:                "write", file_write_action, &info, 
                    913:                as_text, 
                    914:                do_append); 
1.30      paf       915: }
                    916: 
1.63      parser    917: // throws nothing! [this is required in file_move & file_delete]
1.50      paf       918: static void rmdir(const String& file_spec, size_t pos_after) {
1.154     paf       919:        size_t pos_before;
                    920:        if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126     paf       921:                rmdir(file_spec, pos_before+1); 
1.50      paf       922:        
1.154     paf       923:        rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC)); 
1.50      paf       924: }
1.164     paf       925: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.154     paf       926:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.54      parser    927:        if(unlink(fname)!=0)
1.164     paf       928:                if(fail_on_problem)
1.126     paf       929:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.93      paf       930:                                &file_spec, 
                    931:                                "unlink failed: %s (%d), actual filename '%s'", 
1.154     paf       932:                                        strerror(errno), errno, fname);
1.93      paf       933:                else
                    934:                        return false;
1.50      paf       935: 
1.126     paf       936:        rmdir(file_spec, 1); 
1.93      paf       937:        return true;
1.60      parser    938: }
1.95      paf       939: void file_move(const String& old_spec, const String& new_spec) {
1.154     paf       940:        const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC); 
                    941:        const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC); 
1.63      parser    942:        
1.126     paf       943:        create_dir_for_file(new_spec); 
1.63      parser    944: 
1.60      parser    945:        if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126     paf       946:                throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.60      parser    947:                        &old_spec, 
                    948:                        "rename failed: %s (%d), actual filename '%s' to '%s'", 
1.154     paf       949:                                strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63      parser    950: 
1.126     paf       951:        rmdir(old_spec, 1); 
1.31      paf       952: }
                    953: 
1.51      paf       954: 
1.126     paf       955: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118     paf       956:        struct stat lfinfo;
                    957:        bool result=stat(fname, &lfinfo)==0;
                    958:        if(afinfo)
                    959:                *afinfo=lfinfo;
                    960:        return result;
1.119     paf       961: }
                    962: 
                    963: bool entry_exists(const String& file_spec) {
1.154     paf       964:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.126     paf       965:        return entry_exists(fname, 0); 
1.118     paf       966: }
                    967: 
1.51      paf       968: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154     paf       969:        char* fname=file_spec.cstrm(String::L_FILE_SPEC); 
1.120     paf       970:        if(need_dir) {
1.126     paf       971:                size_t size=strlen(fname); 
1.120     paf       972:                while(size) {
1.126     paf       973:                        char c=fname[size-1]; 
1.120     paf       974:                        if(c=='/' || c=='\\')
                    975:                                fname[--size]=0;
                    976:                        else
                    977:                                break;
                    978:                }
                    979:        }
1.51      paf       980:        struct stat finfo;
1.118     paf       981:        if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109     paf       982:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51      paf       983:                return is_dir==need_dir;
                    984:        }
                    985:        return false;
                    986: }
1.31      paf       987: bool file_readable(const String& file_spec) {
1.126     paf       988:        return entry_readable(file_spec, false); 
1.51      paf       989: }
                    990: bool dir_readable(const String& file_spec) {
1.126     paf       991:        return entry_readable(file_spec, true); 
1.65      parser    992: }
1.154     paf       993: const String* file_readable(const String& path, const String& name) {
                    994:        String& result=*new String(path);
                    995:        result << "/"; 
                    996:        result << name;
                    997:        return file_readable(result)?&result:0;
1.43      paf       998: }
                    999: bool file_executable(const String& file_spec) {
1.154     paf      1000:     return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44      paf      1001: }
                   1002: 
1.64      parser   1003: bool file_stat(const String& file_spec, 
1.58      parser   1004:                           size_t& rsize, 
1.126     paf      1005:                           time_t& ratime, 
                   1006:                           time_t& rmtime, 
                   1007:                           time_t& rctime, 
1.64      parser   1008:                           bool fail_on_read_problem) {
1.154     paf      1009:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
                   1010:        struct stat finfo;
1.44      paf      1011:        if(stat(fname, &finfo)!=0)
1.64      parser   1012:                if(fail_on_read_problem)
1.126     paf      1013:                        throw Exception("file.missing", 
1.67      parser   1014:                                &file_spec, 
                   1015:                                "getting file size failed: %s (%d), real filename '%s'", 
1.154     paf      1016:                                        strerror(errno), errno, fname);
1.64      parser   1017:                else
                   1018:                        return false;
1.58      parser   1019:        rsize=finfo.st_size;
                   1020:        ratime=finfo.st_atime;
                   1021:        rmtime=finfo.st_mtime;
                   1022:        rctime=finfo.st_ctime;
1.64      parser   1023:        return true;
1.18      paf      1024: }
                   1025: 
1.126     paf      1026: char* getrow(char* *row_ref, char delim) {
                   1027:     char* result=*row_ref;
1.8       paf      1028:     if(result) {
1.126     paf      1029:                *row_ref=strchr(result, delim); 
1.8       paf      1030:                if(*row_ref) 
                   1031:                        *((*row_ref)++)=0; 
                   1032:                else if(!*result) 
                   1033:                        return 0;
                   1034:     }
                   1035:     return result;
                   1036: }
                   1037: 
1.126     paf      1038: char* lsplit(char* string, char delim) {
1.23      paf      1039:     if(string) {
1.126     paf      1040:                char* v=strchr(string, delim); 
1.8       paf      1041:                if(v) {
                   1042:                        *v=0;
                   1043:                        return v+1;
                   1044:                }
                   1045:     }
                   1046:     return 0;
                   1047: }
                   1048: 
1.126     paf      1049: char* lsplit(char* *string_ref, char delim) {
                   1050:     char* result=*string_ref;
                   1051:        char* next=lsplit(*string_ref, delim); 
1.8       paf      1052:     *string_ref=next;
                   1053:     return result;
1.9       paf      1054: }
                   1055: 
1.126     paf      1056: char* rsplit(char* string, char delim) {
1.18      paf      1057:     if(string) {
1.126     paf      1058:                char* v=strrchr(string, delim); 
1.18      paf      1059:                if(v) {
1.9       paf      1060:                        *v=0;
                   1061:                        return v+1;
                   1062:                }
                   1063:     }
                   1064:     return NULL;       
1.10      paf      1065: }
                   1066: 
1.37      paf      1067: /// @todo less stupid type detection
1.154     paf      1068: const char* format(double value, char* fmt) {
1.126     paf      1069:        char local_buf[MAX_NUMBER]; 
1.108     paf      1070:        size_t size;
                   1071:        
1.10      paf      1072:        if(fmt)
                   1073:                if(strpbrk(fmt, "diouxX"))
                   1074:                        if(strpbrk(fmt, "ouxX"))
1.126     paf      1075:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.10      paf      1076:                        else
1.126     paf      1077:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
1.10      paf      1078:                else
1.126     paf      1079:                        size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
1.10      paf      1080:        else
1.126     paf      1081:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value); 
1.10      paf      1082:        
1.154     paf      1083:        return pa_strdup(local_buf, size);
1.12      paf      1084: }
                   1085: 
1.36      paf      1086: size_t stdout_write(const void *buf, size_t size) {
1.12      paf      1087: #ifdef WIN32
1.187     paf      1088:        size_t to_write = size;
1.12      paf      1089:        do{
1.154     paf      1090:                int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); 
1.12      paf      1091:                if(chunk_written<=0)
                   1092:                        break;
                   1093:                size-=chunk_written;
1.36      paf      1094:                buf=((const char*)buf)+chunk_written;
1.126     paf      1095:        } while(size>0); 
1.12      paf      1096: 
1.187     paf      1097:        return to_write-size;
1.12      paf      1098: #else
1.126     paf      1099:        return fwrite(buf, 1, size, stdout); 
1.12      paf      1100: #endif
1.2       paf      1101: }
1.14      paf      1102: 
1.154     paf      1103: char* unescape_chars(const char* cp, int len) {
                   1104:        char* s=new(PointerFreeGC) char[len + 1]; 
1.14      paf      1105:        enum EscapeState {
1.33      paf      1106:                EscapeRest, 
                   1107:                EscapeFirst, 
1.14      paf      1108:                EscapeSecond
                   1109:        } escapeState=EscapeRest;
1.193     paf      1110:        uchar escapedValue=0;
1.14      paf      1111:        int srcPos=0;
                   1112:        int dstPos=0;
                   1113:        while(srcPos < len) {
1.193     paf      1114:                uchar ch=(uchar)cp[srcPos]; 
1.14      paf      1115:                switch(escapeState) {
                   1116:                        case EscapeRest:
                   1117:                        if(ch=='%') {
                   1118:                                escapeState=EscapeFirst;
                   1119:                        } else if(ch=='+') {
1.126     paf      1120:                                s[dstPos++]=' '; 
1.14      paf      1121:                        } else {
                   1122:                                s[dstPos++]=ch; 
                   1123:                        }
                   1124:                        break;
                   1125:                        case EscapeFirst:
1.193     paf      1126:                        escapedValue=(uchar)(hex_value[ch] << 4);
1.14      paf      1127:                        escapeState=EscapeSecond;
                   1128:                        break;
                   1129:                        case EscapeSecond:
1.126     paf      1130:                        escapedValue +=hex_value[ch]; 
1.14      paf      1131:                        s[dstPos++]=escapedValue;
                   1132:                        escapeState=EscapeRest;
                   1133:                        break;
                   1134:                }
1.126     paf      1135:                srcPos++; 
1.14      paf      1136:        }
                   1137:        s[dstPos]=0;
                   1138:        return s;
1.24      paf      1139: }
                   1140: 
                   1141: #ifdef WIN32
1.126     paf      1142: void back_slashes_to_slashes(char* s) {
1.24      paf      1143:        if(s)
                   1144:                for(; *s; s++)
                   1145:                        if(*s=='\\')
1.126     paf      1146:                                *s='/'; 
1.24      paf      1147: }
1.42      paf      1148: /*
1.126     paf      1149: void slashes_to_back_slashes(char* s) {
1.42      paf      1150:        if(s)
                   1151:                for(; *s; s++)
                   1152:                        if(*s=='/')
1.126     paf      1153:                                *s='\\'; 
1.42      paf      1154: }
                   1155: */
1.24      paf      1156: #endif
1.41      paf      1157: 
1.126     paf      1158: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41      paf      1159:        while(true) {
                   1160:                if(!(*s1)) {
                   1161:                        if(!(*s2))
                   1162:                                return true;
                   1163:                        else
                   1164:                                return !strict;
                   1165:                } else if(!(*s2))
                   1166:                        return !strict;
1.189     paf      1167:                if(isalpha((unsigned char)*s1)) {
1.190     paf      1168:                        if(tolower((unsigned char)*s1) !=tolower((unsigned char)*s2))
1.41      paf      1169:                                return false;
                   1170:                } else if((*s1) !=(*s2))
                   1171:                        return false;
1.126     paf      1172:                s1++; 
                   1173:                s2++; 
1.41      paf      1174:        }
1.57      parser   1175: }
                   1176: 
1.84      paf      1177: static bool isLeap(int year) {
1.57      parser   1178:     return !(
                   1179:              (year % 4) || ((year % 400) && !(year % 100))
1.126     paf      1180:             ); 
1.57      parser   1181: }
                   1182: 
                   1183: int getMonthDays(int year, int month) {
                   1184:     int monthDays[]={
1.126     paf      1185:         31, 
                   1186:         isLeap(year) ? 29 : 28, 
                   1187:         31, 
                   1188:         30, 
                   1189:         31, 
                   1190:         30, 
                   1191:         31, 
                   1192:         31, 
                   1193:         30, 
                   1194:         31, 
                   1195:         30, 
1.57      parser   1196:         31
1.126     paf      1197:     }; 
                   1198:     return monthDays[month]; 
1.41      paf      1199: }
1.69      parser   1200: 
1.126     paf      1201: void remove_crlf(char* start, char* end) {
                   1202:        for(char* p=start; p<end; p++)
1.69      parser   1203:                switch(*p) {
1.126     paf      1204:                        case '\n': *p='|';  break;
                   1205:                        case '\r': *p=' ';  break;
1.69      parser   1206:                }
1.91      paf      1207: }
                   1208: 
                   1209: 
                   1210: /// must be last in this file
                   1211: #undef vsnprintf
1.126     paf      1212: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91      paf      1213:        if(!s)
                   1214:                return 0;
                   1215: 
                   1216:        int r;
                   1217:        // note: on win32& maybe somewhere else
                   1218:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                   1219:        --s;
1.172     paf      1220: 
                   1221:        // clients do not check for negative 's', feature: ignore such prints
                   1222:        if((ssize_t)s<0)
                   1223:                return 0;
                   1224: 
1.91      paf      1225: #if _MSC_VER
                   1226:        /*
                   1227:        win32: 
                   1228:        mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
                   1229: 
1.154     paf      1230:          if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91      paf      1231:        */
1.126     paf      1232:        r=_vsnprintf(b, s, f, l); 
1.91      paf      1233:        if(r<0) 
                   1234:                r=s;
                   1235: #else
1.126     paf      1236:        r=vsnprintf(b, s, f, l); 
1.91      paf      1237:        /*
                   1238:        solaris: 
                   1239:        man vsnprintf
                   1240: 
                   1241:          The snprintf() function returns  the  number  of  characters
                   1242:        formatted, that is, the number of characters that would have
                   1243:        been written to the buffer if it were large enough.  If  the
                   1244:        value  of  n  is  0  on a call to snprintf(), an unspecified
                   1245:        value less than 1 is returned.
                   1246:        */
                   1247: 
                   1248:        if(r<0)
                   1249:                r=0;
1.167     paf      1250:        else if((size_t)r>s)
1.91      paf      1251:                r=s;
                   1252: #endif
                   1253:        b[r]=0;
                   1254:        return r;
                   1255: }
                   1256: 
1.126     paf      1257: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91      paf      1258:        va_list l;
1.126     paf      1259:     va_start(l, f); 
                   1260:     int r=__vsnprintf(b, s, f, l); 
                   1261:     va_end(l); 
1.91      paf      1262:        return r;
1.178     paf      1263: }
                   1264: 
                   1265: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
                   1266: /*
                   1267:  *  Authors: Michael Zucchi <notzed@helixcode.com>
                   1268:  *           Jeffrey Stedfast <fejj@helixcode.com>
                   1269:  *
                   1270:  *  Copyright 2000 Helix Code, Inc. (www.helixcode.com)
                   1271:  *
                   1272:  *  This program is free software; you can redistribute it and/or modify
                   1273:  *  it under the terms of the GNU General Public License as published by
                   1274:  *  the Free Software Foundation; either version 2 of the License, or
                   1275:  *  (at your option) any later version.
                   1276:  *
                   1277:  *  This program is distributed in the hope that it will be useful,
                   1278:  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
                   1279:  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                   1280:  *  GNU General Public License for more details.
                   1281:  *
                   1282:  *  You should have received a copy of the GNU General Public License
                   1283:  *  along with this program; if not, write to the Free Software
                   1284:  *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
                   1285:  *
                   1286:  */
                   1287: static char *base64_alphabet =
                   1288:        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                   1289: 
                   1290: /**
                   1291:  * g_mime_utils_base64_encode_step:
                   1292:  * @in: input stream
                   1293:  * @inlen: length of the input
                   1294:  * @out: output string
                   1295:  * @state: holds the number of bits that are stored in @save
                   1296:  * @save: leftover bits that have not yet been encoded
                   1297:  *
                   1298:  * Base64 encodes a chunk of data. Performs an 'encode step', only
                   1299:  * encodes blocks of 3 characters to the output at a time, saves
                   1300:  * left-over state in state and save (initialise to 0 on first
                   1301:  * invocation).
                   1302:  *
                   1303:  * Returns the number of bytes encoded.
                   1304:  **/
                   1305: static size_t
                   1306: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1307: {
1.186     paf      1308:        register const unsigned char *inptr;
1.178     paf      1309:        register unsigned char *outptr;
                   1310:        
                   1311:        if (inlen <= 0)
                   1312:                return 0;
                   1313:        
                   1314:        inptr = in;
                   1315:        outptr = out;
                   1316:        
                   1317:        if (inlen + ((unsigned char *)save)[0] > 2) {
                   1318:                const unsigned char *inend = in + inlen - 2;
                   1319:                register int c1 = 0, c2 = 0, c3 = 0;
                   1320:                register int already;
                   1321:                
                   1322:                already = *state;
                   1323:                
                   1324:                switch (((char *)save)[0]) {
                   1325:                case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
                   1326:                case 2: c1 = ((unsigned char *)save)[1];
                   1327:                        c2 = ((unsigned char *)save)[2]; goto skip2;
                   1328:                }
                   1329:                
                   1330:                /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
                   1331:                while (inptr < inend) {
                   1332:                        c1 = *inptr++;
                   1333:                skip1:
                   1334:                        c2 = *inptr++;
                   1335:                skip2:
                   1336:                        c3 = *inptr++;
                   1337:                        *outptr++ = base64_alphabet [c1 >> 2];
                   1338:                        *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
                   1339:                        *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
                   1340:                        *outptr++ = base64_alphabet [c3 & 0x3f];
                   1341:                        /* this is a bit ugly ... */
                   1342:                        if ((++already) >= 19) {
                   1343:                                *outptr++ = '\n';
                   1344:                                already = 0;
                   1345:                        }
                   1346:                }
                   1347:                
                   1348:                ((unsigned char *)save)[0] = 0;
                   1349:                inlen = 2 - (inptr - inend);
                   1350:                *state = already;
                   1351:        }
                   1352:        
                   1353:        //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
                   1354:        
                   1355:        if (inlen > 0) {
                   1356:                register char *saveout;
                   1357:                
                   1358:                /* points to the slot for the next char to save */
                   1359:                saveout = & (((char *)save)[1]) + ((char *)save)[0];
                   1360:                
                   1361:                /* inlen can only be 0 1 or 2 */
                   1362:                switch (inlen) {
                   1363:                case 2: *saveout++ = *inptr++;
                   1364:                case 1: *saveout++ = *inptr++;
                   1365:                }
                   1366:                ((char *)save)[0] += inlen;
                   1367:        }
                   1368:        
                   1369:        /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
                   1370:                  (int)((char *)save)[0],
                   1371:                  (int)((char *)save)[1],
                   1372:                  (int)((char *)save)[2]));*/
                   1373:        
                   1374:        return (outptr - out);
                   1375: }
                   1376: 
                   1377: /**
                   1378:  * g_mime_utils_base64_encode_close:
                   1379:  * @in: input stream
                   1380:  * @inlen: length of the input
                   1381:  * @out: output string
                   1382:  * @state: holds the number of bits that are stored in @save
                   1383:  * @save: leftover bits that have not yet been encoded
                   1384:  *
                   1385:  * Base64 encodes the input stream to the output stream. Call this
                   1386:  * when finished encoding data with g_mime_utils_base64_encode_step to
                   1387:  * flush off the last little bit.
                   1388:  *
                   1389:  * Returns the number of bytes encoded.
                   1390:  **/
                   1391: static size_t
                   1392: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1393: {
                   1394:        unsigned char *outptr = out;
                   1395:        int c1, c2;
                   1396:        
                   1397:        if (inlen > 0)
                   1398:                outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
                   1399:        
                   1400:        c1 = ((unsigned char *)save)[1];
                   1401:        c2 = ((unsigned char *)save)[2];
                   1402:        
                   1403:        switch (((unsigned char *)save)[0]) {
                   1404:        case 2:
                   1405:                outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
                   1406:                goto skip;
                   1407:        case 1:
                   1408:                outptr[2] = '=';
                   1409:        skip:
                   1410:                outptr[0] = base64_alphabet [c1 >> 2];
                   1411:                outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
                   1412:                outptr[3] = '=';
                   1413:                outptr += 4;
                   1414:                break;
                   1415:        }
                   1416:        
                   1417:        *outptr++ = 0;
                   1418:        
                   1419:        *save = 0;
                   1420:        *state = 0;
                   1421:        
                   1422:        return (outptr - out);
                   1423: }
                   1424: 
                   1425: char* pa_base64(const char *in, size_t len)
                   1426: {
                   1427:        /* wont go to more than 2x size (overly conservative) */
                   1428:        char* result=new(PointerFreeGC) char[len * 2 + 6];
                   1429:        int state=0;
                   1430:        int save=0;
1.183     paf      1431: #ifndef NDEBUG
                   1432:        size_t filled=
                   1433: #endif
                   1434:                g_mime_utils_base64_encode_close ((const unsigned char*)in, len, 
1.178     paf      1435:                (unsigned char*)result, &state, &save);
                   1436:        assert(filled <= len * 2 + 6);
                   1437: 
                   1438:        return result;
1.98      paf      1439: }

E-mail: