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

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

E-mail: