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

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

E-mail: