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

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.16      paf         6: 
1.210     paf         7:  * BASE64 part
                      8:  *  Authors: Michael Zucchi <notzed@ximian.com>
                      9:  *           Jeffrey Stedfast <fejj@ximian.com>
                     10:  *
                     11:  *  Copyright 2000-2004 Ximian, Inc. (www.ximian.com)
                     12:  *
                     13:  *  This program is free software; you can redistribute it and/or modify
                     14:  *  it under the terms of the GNU General Public License as published by
                     15:  *  the Free Software Foundation; either version 2 of the License, or
                     16:  *  (at your option) any later version.
                     17:  *
                     18:  *  This program is distributed in the hope that it will be useful,
                     19:  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
                     20:  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     21:  *  GNU General Public License for more details.
                     22:  *
                     23:  *  You should have received a copy of the GNU General Public License
                     24:  *  along with this program; if not, write to the Free Software
                     25:  *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
                     26:  *
                     27:  */
                     28: 
1.238   ! misha      29: static const char * const IDENT_COMMON_C="$Date: 2008-08-21 15:57:48 $"; 
1.1       paf        30: 
                     31: #include "pa_common.h"
1.4       paf        32: #include "pa_exception.h"
1.154     paf        33: #include "pa_hash.h"
1.14      paf        34: #include "pa_globals.h"
1.154     paf        35: #include "pa_charsets.h"
1.214     paf        36: #include "pa_http.h"
1.223     misha      37: #include "pa_request_charsets.h"
1.237     misha      38: #include "pcre.h"
1.98      paf        39: 
1.93      paf        40: // some maybe-undefined constants
                     41: 
1.82      paf        42: #ifndef _O_TEXT
                     43: #      define _O_TEXT 0
                     44: #endif
                     45: #ifndef _O_BINARY
                     46: #      define _O_BINARY 0
1.47      paf        47: #endif
1.80      paf        48: 
1.138     paf        49: #ifdef HAVE_FTRUNCATE
                     50: #      define PA_O_TRUNC 0
                     51: #else
                     52: #      ifdef _O_TRUNC
                     53: #              define PA_O_TRUNC _O_TRUNC
                     54: #      else
                     55: #              error you must have either ftruncate function or _O_TRUNC bit declared
                     56: #      endif
1.154     paf        57: #endif
1.176     paf        58: 
1.154     paf        59: // defines for globals
                     60: 
                     61: #define FILE_STATUS_NAME  "status"
                     62: 
                     63: // globals
                     64: 
                     65: const String file_status_name(FILE_STATUS_NAME);
                     66: 
                     67: // functions
1.127     paf        68: 
1.154     paf        69: void fix_line_breaks(char *str, size_t& length) {
1.87      paf        70:        //_asm int 3;
1.154     paf        71:        const char* const eob=str+length;
                     72:        char* dest=str;
1.72      parser     73:        // fix DOS: \r\n -> \n
                     74:        // fix Macintosh: \r -> \n
1.154     paf        75:        char* bol=str;
1.137     paf        76:        while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72      parser     77:                size_t len=eol-bol;
                     78:                if(dest!=bol)
1.126     paf        79:                        memcpy(dest, bol, len); 
1.72      parser     80:                dest+=len;
1.126     paf        81:                *dest++='\n'; 
1.72      parser     82: 
1.126     paf        83:                if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72      parser     84:                        bol=eol+2;
1.154     paf        85:                        length--; 
1.126     paf        86:                } else // \r, not \n = Macintosh
1.72      parser     87:                        bol=eol+1;
                     88:        }
1.154     paf        89:        // last piece without \r
1.72      parser     90:        if(dest!=bol)
1.126     paf        91:                memcpy(dest, bol, eob-bol); 
1.154     paf        92:        str[length]=0; // terminating
1.72      parser     93: }
1.18      paf        94: 
1.154     paf        95: char* file_read_text(Request_charsets& charsets, 
1.229     misha      96:                        const String& file_spec, 
                     97:                        bool fail_on_read_problem,
1.234     misha      98:                        HashStringValue* params,
                     99:                        bool transcode_result) {
1.154     paf       100:        File_read_result file=
1.234     misha     101:                file_read(charsets, file_spec, true, params, fail_on_read_problem, 0, 0, 0, transcode_result);
1.154     paf       102:        return file.success?file.str:0;
1.126     paf       103: }
                    104: 
1.206     paf       105: /// these options were handled but not checked elsewhere, now check them
1.214     paf       106: int pa_get_valid_file_options_count(HashStringValue& options)
1.206     paf       107: {
                    108:        int result=0;
                    109:        if(options.get(PA_SQL_LIMIT_NAME))
                    110:                result++;
                    111:        if(options.get(PA_SQL_OFFSET_NAME))
                    112:                result++;
                    113:        if(options.get(PA_COLUMN_SEPARATOR_NAME))
                    114:                result++;
                    115:        if(options.get(PA_COLUMN_ENCLOSER_NAME))
                    116:                result++;
1.223     misha     117:        if(options.get(PA_CHARSET_NAME))
                    118:                result++;
1.206     paf       119:        return result;
                    120: }
                    121: 
1.123     paf       122: #ifndef DOXYGEN
                    123: struct File_read_action_info {
1.154     paf       124:        char **data; size_t *data_size;
1.188     paf       125:        char* buf; size_t offset; size_t count;
1.126     paf       126: }; 
1.123     paf       127: #endif
1.154     paf       128: static void file_read_action(
1.229     misha     129:                                struct stat& finfo, 
                    130:                                int f, 
                    131:                                const String& file_spec, const char* /*fname*/, bool as_text, 
                    132:                                void *context) {
1.126     paf       133:        File_read_action_info& info=*static_cast<File_read_action_info *>(context); 
1.188     paf       134:        size_t to_read_size=info.count;
                    135:        if(!to_read_size)
                    136:                to_read_size=(size_t)finfo.st_size;
                    137:        assert( !(info.buf && as_text) );
                    138:        if(to_read_size) { 
                    139:                if(info.offset)
                    140:                        lseek(f, info.offset, SEEK_SET);
                    141:                *info.data=info.buf
                    142:                        ? info.buf
                    143:                        : new(PointerFreeGC) char[to_read_size+(as_text?1:0)]; 
1.126     paf       144:                *info.data_size=(size_t)read(f, *info.data, to_read_size); 
1.123     paf       145: 
                    146:                if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.238   ! misha     147:                        throw Exception("file.read", 
1.123     paf       148:                                &file_spec, 
1.173     paf       149:                                "read failed: actually read %u bytes count not in [0..%u] valid range", 
1.126     paf       150:                                        *info.data_size, to_read_size); 
1.123     paf       151:        } else { // empty file
1.209     paf       152:                // for both, text and binary: for text we need that terminator, for binary we need nonzero pointer to be able to save such files
                    153:                *info.data=new(PointerFreeGC) char[1]; 
                    154:                *(char*)(*info.data)=0;
1.123     paf       155:                *info.data_size=0;
                    156:                return;
                    157:        }
1.126     paf       158: }
1.154     paf       159: File_read_result file_read(Request_charsets& charsets, const String& file_spec, 
1.229     misha     160:                        bool as_text, HashStringValue *params,
                    161:                        bool fail_on_read_problem,
1.234     misha     162:                        char* buf, size_t offset, size_t count, bool transcode_text_result) {
1.167     paf       163:        File_read_result result={false, 0, 0, 0};
1.154     paf       164:        if(file_spec.starts_with("http://")) {
1.203     paf       165:                if(offset || count)
1.224     misha     166:                        throw Exception(PARSER_RUNTIME,
1.203     paf       167:                                0,
                    168:                                "offset and load options are not supported for HTTP:// file load");
                    169: 
1.126     paf       170:                // fail on read problem
1.234     misha     171:                File_read_http_result http=pa_internal_file_read_http(charsets, file_spec, as_text, params, transcode_text_result);
1.154     paf       172:                result.success=true;
                    173:                result.str=http.str;
                    174:                result.length=http.length;
                    175:                result.headers=http.headers; 
1.126     paf       176:        } else {
1.236     misha     177:                if(params){
1.214     paf       178:                        int valid_options=pa_get_valid_file_options_count(*params);
1.206     paf       179:                        if(valid_options!=params->count())
1.224     misha     180:                                throw Exception(PARSER_RUNTIME,
1.206     paf       181:                                        0,
                    182:                                        "invalid option passed");
                    183:                }
1.161     paf       184: 
1.188     paf       185:                File_read_action_info info={&result.str, &result.length,
                    186:                        buf, offset, count}; 
1.154     paf       187:                result.success=file_read_action_under_lock(file_spec, 
1.126     paf       188:                        "read", file_read_action, &info, 
                    189:                        as_text, fail_on_read_problem); 
1.223     misha     190: 
1.236     misha     191:                if(as_text && result.success){
                    192:                        if(result.length>=3 && strncmp(result.str, "\xEF\xBB\xBF", 3)==0){
                    193:                                // skip UTF-8 signature: EF BB BF  (BOM code)
                    194:                                result.str+=3;
                    195:                                result.length-=3;
                    196:                        }
                    197:                        
                    198:                        if(result.length && transcode_text_result && params){ // must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
                    199:                                if( Value* vcharset_name=params->get(PA_CHARSET_NAME) ){
                    200:                                        Charset asked_charset=::charsets.get(vcharset_name->as_string().
                    201:                                                change_case(charsets.source(), String::CC_UPPER));
                    202: 
                    203:                                        String::C body=String::C(result.str, result.length);
                    204:                                        body=Charset::transcode(body, asked_charset, charsets.source());
1.123     paf       205: 
1.236     misha     206:                                        result.str=const_cast<char*>(body.str); // hacking a little
                    207:                                        result.length=body.length;
                    208:                                }
1.131     paf       209:                        }
                    210:                }
1.123     paf       211:        }
1.236     misha     212:        
                    213:        if(as_text && result.length)
                    214:                fix_line_breaks(result.str, result.length);
1.126     paf       215: 
                    216:        return result;
1.123     paf       217: }
                    218: 
1.154     paf       219: #ifdef PA_SAFE_MODE 
                    220: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) { 
                    221:        if(finfo.st_uid/*foreign?*/!=geteuid() 
                    222:                && finfo.st_gid/*foreign?*/!=getegid()) 
1.224     misha     223:                throw Exception(PARSER_RUNTIME,  
1.154     paf       224:                        &file_spec,  
                    225:                        "parser is in safe mode: " 
                    226:                        "reading files of foreign group and user disabled " 
                    227:                        "[recompile parser with --disable-safe-mode configure option], " 
                    228:                        "actual filename '%s', " 
                    229:                        "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",  
                    230:                                fname, 
                    231:                                finfo.st_uid, geteuid(), 
                    232:                                finfo.st_gid, getegid()); 
                    233: } 
                    234: #endif 
1.149     paf       235: 
1.154     paf       236: bool file_read_action_under_lock(const String& file_spec, 
1.126     paf       237:                                const char* action_name, File_read_action action, void *context, 
                    238:                                bool as_text, 
1.123     paf       239:                                bool fail_on_read_problem) {
1.154     paf       240:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.33      paf       241:        int f;
                    242: 
                    243:        // first open, next stat:
1.45      paf       244:        // directory update of NTFS hard links performed on open.
1.33      paf       245:        // ex: 
                    246:        //   a.html:^test[] and b.html hardlink to a.html
                    247:        //   user inserts ! before ^test in a.html
1.126     paf       248:        //   directory entry of b.html in NTFS not updated at once, 
1.35      paf       249:        //   they delay update till open, so we would receive "!^test[" string
                    250:        //   if would do stat, next open.
1.123     paf       251:        // later: it seems, even this does not help sometimes
1.229     misha     252:        if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123     paf       253:                try {
1.162     paf       254:                        if(pa_lock_shared_blocking(f)!=0)
1.126     paf       255:                                throw Exception("file.lock", 
1.123     paf       256:                                                &file_spec, 
                    257:                                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       258:                                                        strerror(errno), errno, fname);
1.123     paf       259: 
1.124     paf       260:                        struct stat finfo;
                    261:                        if(stat(fname, &finfo)!=0)
                    262:                                throw Exception("file.missing", // hardly possible: we just opened it OK
                    263:                                        &file_spec, 
                    264:                                        "stat failed: %s (%d), actual filename '%s'", 
1.154     paf       265:                                                strerror(errno), errno, fname);
1.124     paf       266: 
1.140     paf       267: #ifdef PA_SAFE_MODE
1.149     paf       268:                        check_safe_mode(finfo, file_spec, fname);
1.105     paf       269: #endif
1.32      paf       270: 
1.154     paf       271:                        action(finfo, f, file_spec, fname, as_text, context); 
1.123     paf       272:                } catch(...) {
1.162     paf       273:                        pa_unlock(f);close(f); 
1.123     paf       274:                        if(fail_on_read_problem)
1.154     paf       275:                                rethrow;
1.123     paf       276:                        return false;                   
                    277:                } 
1.87      paf       278: 
1.162     paf       279:                pa_unlock(f);close(f); 
1.72      parser    280:                return true;
1.229     misha     281:        } else {
1.118     paf       282:                if(fail_on_read_problem)
1.126     paf       283:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.118     paf       284:                                &file_spec, 
1.123     paf       285:                                "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       286:                                        action_name, strerror(errno), errno, fname);
1.118     paf       287:                return false;
                    288:        }
1.8       paf       289: }
                    290: 
1.202     paf       291: void create_dir_for_file(const String& file_spec) {
1.63      parser    292:        size_t pos_after=1;
1.154     paf       293:        size_t pos_before;
                    294:        while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
                    295:                mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775); 
1.63      parser    296:                pos_after=pos_before+1;
                    297:        }
                    298: }
                    299: 
1.98      paf       300: bool file_write_action_under_lock(
1.28      paf       301:                                const String& file_spec, 
1.225     misha     302:                                const char* action_name,
                    303:                                File_write_action action,
                    304:                                void *context, 
1.126     paf       305:                                bool as_text, 
                    306:                                bool do_append, 
                    307:                                bool do_block, 
1.110     paf       308:                                bool fail_on_lock_problem) {
1.154     paf       309:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.28      paf       310:        int f;
1.80      paf       311:        if(access(fname, W_OK)!=0) // no
1.126     paf       312:                create_dir_for_file(file_spec); 
1.50      paf       313: 
1.80      paf       314:        if((f=open(fname, 
                    315:                O_CREAT|O_RDWR
                    316:                |(as_text?_O_TEXT:_O_BINARY)
1.138     paf       317:                |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162     paf       318:                if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126     paf       319:                        Exception e("file.lock", 
1.110     paf       320:                                &file_spec, 
                    321:                                "shared lock failed: %s (%d), actual filename '%s'", 
1.154     paf       322:                                strerror(errno), errno, fname);
1.126     paf       323:                        close(f); 
1.110     paf       324:                        if(fail_on_lock_problem)
                    325:                                throw e;
1.98      paf       326:                        return false;
                    327:                }
1.96      paf       328: 
1.158     paf       329:                try {
1.126     paf       330:                        action(f, context); 
1.158     paf       331:                } catch(...) {
1.138     paf       332: #ifdef HAVE_FTRUNCATE
1.104     paf       333:                        if(!do_append)
1.125     paf       334:                                ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138     paf       335: #endif
1.162     paf       336:                        pa_unlock(f);close(f); 
1.154     paf       337:                        rethrow;
1.158     paf       338:                }
1.80      paf       339:                
1.138     paf       340: #ifdef HAVE_FTRUNCATE
1.104     paf       341:                if(!do_append)
1.125     paf       342:                        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       343: #endif
1.162     paf       344:                pa_unlock(f);close(f); 
1.98      paf       345:                return true;
1.80      paf       346:        } else
1.126     paf       347:                throw Exception(errno==EACCES?"file.access":0, 
1.80      paf       348:                        &file_spec, 
1.96      paf       349:                        "%s failed: %s (%d), actual filename '%s'", 
1.154     paf       350:                                action_name, strerror(errno), errno, fname);
1.96      paf       351:        // here should be nothing, see rethrow above
                    352: }
                    353: 
                    354: #ifndef DOXYGEN
                    355: struct File_write_action_info {
1.154     paf       356:        const char* str; size_t length;
1.126     paf       357: }; 
1.96      paf       358: #endif
                    359: static void file_write_action(int f, void *context) {
1.126     paf       360:        File_write_action_info& info=*static_cast<File_write_action_info *>(context); 
1.154     paf       361:        if(info.length) {
                    362:                int written=write(f, info.str, info.length); 
1.116     paf       363:                if(written<0)
1.238   ! misha     364:                        throw Exception("file.access", 
1.126     paf       365:                                0, 
                    366:                                "write failed: %s (%d)",  strerror(errno), errno); 
1.113     paf       367:        }
1.96      paf       368: }
                    369: void file_write(
                    370:                                const String& file_spec, 
1.154     paf       371:                                const char* data, size_t size, 
1.126     paf       372:                                bool as_text, 
1.96      paf       373:                                bool do_append) {
1.126     paf       374:        File_write_action_info info={data, size}; 
1.225     misha     375: 
1.98      paf       376:        file_write_action_under_lock(
1.154     paf       377:                file_spec, 
1.225     misha     378:                "write",
                    379:                file_write_action,
                    380:                &info, 
1.154     paf       381:                as_text, 
                    382:                do_append); 
1.30      paf       383: }
                    384: 
1.63      parser    385: // throws nothing! [this is required in file_move & file_delete]
1.50      paf       386: static void rmdir(const String& file_spec, size_t pos_after) {
1.154     paf       387:        size_t pos_before;
                    388:        if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126     paf       389:                rmdir(file_spec, pos_before+1); 
1.50      paf       390:        
1.154     paf       391:        rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC)); 
1.50      paf       392: }
1.164     paf       393: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.154     paf       394:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.54      parser    395:        if(unlink(fname)!=0)
1.164     paf       396:                if(fail_on_problem)
1.126     paf       397:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.93      paf       398:                                &file_spec, 
                    399:                                "unlink failed: %s (%d), actual filename '%s'", 
1.154     paf       400:                                        strerror(errno), errno, fname);
1.93      paf       401:                else
                    402:                        return false;
1.50      paf       403: 
1.126     paf       404:        rmdir(file_spec, 1); 
1.93      paf       405:        return true;
1.60      parser    406: }
1.95      paf       407: void file_move(const String& old_spec, const String& new_spec) {
1.154     paf       408:        const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC); 
                    409:        const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC); 
1.63      parser    410:        
1.126     paf       411:        create_dir_for_file(new_spec); 
1.63      parser    412: 
1.60      parser    413:        if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126     paf       414:                throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0, 
1.60      parser    415:                        &old_spec, 
                    416:                        "rename failed: %s (%d), actual filename '%s' to '%s'", 
1.154     paf       417:                                strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63      parser    418: 
1.126     paf       419:        rmdir(old_spec, 1); 
1.31      paf       420: }
                    421: 
1.51      paf       422: 
1.126     paf       423: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118     paf       424:        struct stat lfinfo;
                    425:        bool result=stat(fname, &lfinfo)==0;
                    426:        if(afinfo)
                    427:                *afinfo=lfinfo;
                    428:        return result;
1.119     paf       429: }
                    430: 
                    431: bool entry_exists(const String& file_spec) {
1.154     paf       432:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
1.126     paf       433:        return entry_exists(fname, 0); 
1.118     paf       434: }
                    435: 
1.51      paf       436: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154     paf       437:        char* fname=file_spec.cstrm(String::L_FILE_SPEC); 
1.120     paf       438:        if(need_dir) {
1.126     paf       439:                size_t size=strlen(fname); 
1.120     paf       440:                while(size) {
1.126     paf       441:                        char c=fname[size-1]; 
1.120     paf       442:                        if(c=='/' || c=='\\')
                    443:                                fname[--size]=0;
                    444:                        else
                    445:                                break;
                    446:                }
                    447:        }
1.51      paf       448:        struct stat finfo;
1.118     paf       449:        if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109     paf       450:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51      paf       451:                return is_dir==need_dir;
                    452:        }
                    453:        return false;
                    454: }
1.215     paf       455: bool file_exist(const String& file_spec) {
1.126     paf       456:        return entry_readable(file_spec, false); 
1.51      paf       457: }
1.215     paf       458: bool dir_exists(const String& file_spec) {
1.126     paf       459:        return entry_readable(file_spec, true); 
1.65      parser    460: }
1.215     paf       461: const String* file_exist(const String& path, const String& name) {
1.154     paf       462:        String& result=*new String(path);
                    463:        result << "/"; 
                    464:        result << name;
1.215     paf       465:        return file_exist(result)?&result:0;
1.43      paf       466: }
                    467: bool file_executable(const String& file_spec) {
1.154     paf       468:     return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44      paf       469: }
                    470: 
1.64      parser    471: bool file_stat(const String& file_spec, 
1.229     misha     472:                        size_t& rsize,
                    473:                        time_t& ratime,
                    474:                        time_t& rmtime,
                    475:                        time_t& rctime,
                    476:                        bool fail_on_read_problem) {
1.154     paf       477:        const char* fname=file_spec.cstr(String::L_FILE_SPEC); 
                    478:        struct stat finfo;
1.44      paf       479:        if(stat(fname, &finfo)!=0)
1.64      parser    480:                if(fail_on_read_problem)
1.126     paf       481:                        throw Exception("file.missing", 
1.67      parser    482:                                &file_spec, 
                    483:                                "getting file size failed: %s (%d), real filename '%s'", 
1.154     paf       484:                                        strerror(errno), errno, fname);
1.64      parser    485:                else
                    486:                        return false;
1.58      parser    487:        rsize=finfo.st_size;
                    488:        ratime=finfo.st_atime;
                    489:        rmtime=finfo.st_mtime;
                    490:        rctime=finfo.st_ctime;
1.64      parser    491:        return true;
1.18      paf       492: }
                    493: 
1.126     paf       494: char* getrow(char* *row_ref, char delim) {
1.229     misha     495:        char* result=*row_ref;
                    496:        if(result) {
1.126     paf       497:                *row_ref=strchr(result, delim); 
1.8       paf       498:                if(*row_ref) 
                    499:                        *((*row_ref)++)=0; 
                    500:                else if(!*result) 
                    501:                        return 0;
1.229     misha     502:        }
                    503:        return result;
1.8       paf       504: }
                    505: 
1.126     paf       506: char* lsplit(char* string, char delim) {
1.229     misha     507:        if(string) {
1.126     paf       508:                char* v=strchr(string, delim); 
1.8       paf       509:                if(v) {
                    510:                        *v=0;
                    511:                        return v+1;
                    512:                }
1.229     misha     513:        }
                    514:        return 0;
1.8       paf       515: }
                    516: 
1.126     paf       517: char* lsplit(char* *string_ref, char delim) {
1.229     misha     518:        char* result=*string_ref;
1.126     paf       519:        char* next=lsplit(*string_ref, delim); 
1.229     misha     520:        *string_ref=next;
                    521:        return result;
1.9       paf       522: }
                    523: 
1.126     paf       524: char* rsplit(char* string, char delim) {
1.229     misha     525:        if(string) {
1.126     paf       526:                char* v=strrchr(string, delim); 
1.18      paf       527:                if(v) {
1.9       paf       528:                        *v=0;
                    529:                        return v+1;
                    530:                }
1.229     misha     531:        }
                    532:        return NULL;    
1.10      paf       533: }
                    534: 
1.229     misha     535: 
                    536: // format: %[flags][width][.precision]type     http://msdn.microsoft.com/ru-ru/library/56e442dc(en-us,VS.80).aspx
                    537: //             flags: '-', '+', ' ', '#', '0'          http://msdn.microsoft.com/ru-ru/library/8aky45ct(en-us,VS.80).aspx
                    538: //             width, precision: non negative decimal number
                    539: enum FormatType {
                    540:        FormatInvalid,
                    541:        FormatInt,
                    542:        FormatUInt,
                    543:        FormatDouble
                    544: };
                    545: FormatType format_type(char* fmt){
                    546:        enum FormatState {
                    547:                Percent, 
                    548:                Flags, 
                    549:                Width,
                    550:                Precision,
                    551:                Done
                    552:        } state=Percent;
                    553: 
                    554:        FormatType result=FormatInvalid;
                    555: 
                    556:        char* pos=fmt;
                    557:        while(char c=*(pos++)){
                    558:                switch(state){
                    559:                        case Percent:
                    560:                                if(c=='%'){
                    561:                                        state=Flags;
                    562:                                } else {
                    563:                                        return FormatInvalid; // 1st char must be '%' only
                    564:                                }
                    565:                                break;
                    566:                        case Flags:
                    567:                                if(strchr("-+ #0", c)!=0){
                    568:                                        break;
                    569:                                }
                    570:                                // go to the next step
                    571:                        case Width:
                    572:                                if(c=='.'){
                    573:                                        state=Precision;
                    574:                                        break;
                    575:                                }
                    576:                                // go to the next step
                    577:                        case Precision:
                    578:                                if(c>='0' && c<='9'){
                    579:                                        if(state == Flags) state=Width; // no more flags
                    580:                                        break;
                    581:                                } else if(c=='d' || c=='i'){
                    582:                                        result=FormatInt;
                    583:                                } else if(strchr("feEgG", c)!=0){
                    584:                                        result=FormatDouble;
                    585:                                } else if(strchr("uoxX", c)!=0){
                    586:                                        result=FormatUInt;
                    587:                                } else {
                    588:                                        return FormatInvalid; // invalid char
                    589:                                }
                    590:                                state=Done;
                    591:                                break;
                    592:                        case Done:
                    593:                                return FormatInvalid; // no chars allowed after 'type'
                    594:                }
                    595:        }
                    596:        return result;
                    597: }
                    598: 
                    599: 
1.154     paf       600: const char* format(double value, char* fmt) {
1.229     misha     601:        char local_buf[MAX_NUMBER];
1.235     misha     602:        int size=-1;
1.229     misha     603: 
                    604:        if(fmt && strlen(fmt)){
                    605:                switch(format_type(fmt)){
                    606:                        case FormatDouble:
                    607:                                size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
                    608:                                break;
                    609:                        case FormatInt:
                    610:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
                    611:                                break;
                    612:                        case FormatUInt:
1.126     paf       613:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.229     misha     614:                                break;
                    615:                        case FormatInvalid:
                    616:                                throw Exception(PARSER_RUNTIME, 
                    617:                                        0, 
                    618:                                        "Incorrect format string '%s' was specified.", fmt);
                    619:                }
                    620:        } else
                    621:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
                    622: 
                    623:        if(size < 0 || size >= MAX_NUMBER-1){ // on win32 we manually reduce max size while printing
                    624:                throw Exception(PARSER_RUNTIME, 
                    625:                        0, 
                    626:                        "Error occure white executing snprintf with format string '%s'.", fmt);
                    627:        }
                    628: 
1.235     misha     629:        return pa_strdup(local_buf, (size_t)size);
1.12      paf       630: }
                    631: 
1.36      paf       632: size_t stdout_write(const void *buf, size_t size) {
1.12      paf       633: #ifdef WIN32
1.187     paf       634:        size_t to_write = size;
1.12      paf       635:        do{
1.154     paf       636:                int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); 
1.12      paf       637:                if(chunk_written<=0)
                    638:                        break;
                    639:                size-=chunk_written;
1.36      paf       640:                buf=((const char*)buf)+chunk_written;
1.126     paf       641:        } while(size>0); 
1.12      paf       642: 
1.187     paf       643:        return to_write-size;
1.12      paf       644: #else
1.126     paf       645:        return fwrite(buf, 1, size, stdout); 
1.12      paf       646: #endif
1.2       paf       647: }
1.14      paf       648: 
1.229     misha     649: enum EscapeState {
                    650:        EscapeRest, 
                    651:        EscapeFirst, 
                    652:        EscapeSecond,
                    653:        EscapeUnicode
                    654: };
                    655: 
1.236     misha     656: // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually)
                    657: char* unescape_chars(const char* cp, int len, Charset* charset, bool ignore_plus){
                    658:        char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
1.230     misha     659:        char* dst=s;
1.229     misha     660:        EscapeState escapeState=EscapeRest;
                    661:        uint escapedValue=0;
                    662:        int srcPos=0;
1.230     misha     663:        short int jsCnt=0;
1.236     misha     664:        while(srcPos<len){
1.229     misha     665:                uchar c=(uchar)cp[srcPos]; 
                    666:                if(c=='%'){
                    667:                        escapeState=EscapeFirst;
                    668:                } else {
                    669:                        switch(escapeState) {
                    670:                                case EscapeRest:
1.236     misha     671:                                        if(!ignore_plus && c=='+'){
1.230     misha     672:                                                *dst++=' ';
1.229     misha     673:                                        } else {
1.230     misha     674:                                                *dst++=c;
1.229     misha     675:                                        }
                    676:                                        break;
                    677:                                case EscapeFirst:
1.232     misha     678:                                        if(charset && c=='u'){
1.229     misha     679:                                                // escaped unicode value: %u0430
                    680:                                                jsCnt=0;
                    681:                                                escapedValue=0;
                    682:                                                escapeState=EscapeUnicode;
                    683:                                        } else {
1.231     misha     684:                                                if(isxdigit(c)){
1.229     misha     685:                                                        escapedValue=hex_value[c] << 4;
                    686:                                                        escapeState=EscapeSecond;
                    687:                                                } else {
1.230     misha     688:                                                        *dst++=c;
1.229     misha     689:                                                        escapeState=EscapeRest;
                    690:                                                }
                    691:                                        }
                    692:                                        break;
                    693:                                case EscapeSecond:
1.231     misha     694:                                        if(isxdigit(c)){
1.229     misha     695:                                                escapedValue+=hex_value[c]; 
1.230     misha     696:                                                *dst++=(char)escapedValue;
1.229     misha     697:                                        }
                    698:                                        escapeState=EscapeRest;
                    699:                                        break;
                    700:                                case EscapeUnicode:
1.231     misha     701:                                        if(isxdigit(c)){
1.229     misha     702:                                                escapedValue=(escapedValue << 4) + hex_value[c];
                    703:                                                if(++jsCnt==4){
1.230     misha     704:                                                        // transcode utf8 char to client charset (we can lost some chars here)
1.232     misha     705:                                                        charset->store_Char((XMLByte*&)dst, (XMLCh)escapedValue, '?');
1.229     misha     706:                                                        escapeState=EscapeRest;
                    707:                                                }
                    708:                                        } else {
                    709:                                                // not full unicode value
                    710:                                                escapeState=EscapeRest;
                    711:                                        }
                    712:                                        break;
                    713:                        }
                    714:                }
                    715: 
                    716:                srcPos++;
                    717:        }
                    718: 
1.230     misha     719:        *dst=0; // zero-termination
1.229     misha     720:        return s;
                    721: }
1.24      paf       722: 
                    723: #ifdef WIN32
1.126     paf       724: void back_slashes_to_slashes(char* s) {
1.24      paf       725:        if(s)
                    726:                for(; *s; s++)
                    727:                        if(*s=='\\')
1.126     paf       728:                                *s='/'; 
1.24      paf       729: }
1.42      paf       730: /*
1.126     paf       731: void slashes_to_back_slashes(char* s) {
1.42      paf       732:        if(s)
                    733:                for(; *s; s++)
                    734:                        if(*s=='/')
1.126     paf       735:                                *s='\\'; 
1.42      paf       736: }
                    737: */
1.24      paf       738: #endif
1.41      paf       739: 
1.231     misha     740: bool StrStartFromNC(const char* str, const char* substr, bool equal){
1.41      paf       741:        while(true) {
1.231     misha     742:                if(!(*substr)){
                    743:                        if(!(*str))
1.41      paf       744:                                return true;
                    745:                        else
1.231     misha     746:                                return !equal;
                    747:                }
                    748:                if(!(*str))
                    749:                        return false;
                    750:                if(isalpha((unsigned char)*str)) {
                    751:                        if(tolower((unsigned char)*str)!=tolower((unsigned char)*substr))
1.41      paf       752:                                return false;
1.231     misha     753:                } else if((*str) != (*substr))
1.41      paf       754:                        return false;
1.231     misha     755:                str++; 
                    756:                substr++; 
1.41      paf       757:        }
1.57      parser    758: }
                    759: 
1.232     misha     760: size_t strpos(const char *str, const char *substr) {
                    761:        const char *p = strstr(str, substr);
                    762:        return (p==0)?STRING_NOT_FOUND:p-str;
                    763: }
                    764: 
                    765: // content-type: xxx; charset=WE-NEED-THIS
                    766: // content-type: xxx; charset="WE-NEED-THIS"
                    767: // content-type: xxx; charset="WE-NEED-THIS";
1.233     misha     768: Charset* detect_charset(const char* content_type){
                    769:        if(content_type){
                    770:                size_t len=strlen(content_type);
                    771:                char* CONTENT_TYPE=new(PointerFreeGC) char[len+1];
                    772:                memcpy(CONTENT_TYPE, content_type, len);
                    773:                for(char *p=CONTENT_TYPE; *p; p++)
                    774:                        *p=(char)toupper((unsigned char)*p);
                    775: 
                    776:                if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
                    777:                        begin+=8; // skip "CHARSET="
                    778:                        char* end=0;
                    779:                        if(*begin && (*begin=='"' || *begin =='\'')){
                    780:                                char quote=*begin;
                    781:                                begin++;
                    782:                                end=(char*)strchr(begin, quote);
                    783:                        }
                    784:                        if(!end)
                    785:                                end=(char*)strchr(begin, ';');
                    786: 
                    787:                        size_t len;
                    788:                        if(end){
                    789:                                *end=0; // terminator
                    790:                                len=end-begin;
                    791:                        } else {
                    792:                                len=strlen(begin);
                    793:                        }
                    794: 
                    795:                        String::Body NAME=String::Body(begin, len);
                    796:                        return &charsets.get(NAME);
1.232     misha     797:                }
                    798:        }
                    799:        return 0;
                    800: }
                    801: 
1.233     misha     802: Charset* detect_charset(Charset& source_charset, const String& content_type){
                    803:        const String& CONTENT_TYPE=content_type.change_case(source_charset, String::CC_UPPER);
                    804:        size_t begin=CONTENT_TYPE.pos("CHARSET=");
                    805:        if(begin!=STRING_NOT_FOUND) {
                    806:                begin+=8; // skip "CHARSET="
                    807:                size_t end=STRING_NOT_FOUND;
                    808: 
                    809:                if(CONTENT_TYPE.pos('"', begin)==begin){
                    810:                        begin++;
                    811:                        end=CONTENT_TYPE.pos('"', begin);
                    812:                } else if(CONTENT_TYPE.pos('\'', begin)==begin){
                    813:                        begin++;
                    814:                        end=CONTENT_TYPE.pos('\'', begin);
                    815:                }
                    816: 
                    817:                if(end==STRING_NOT_FOUND)
                    818:                        end=CONTENT_TYPE.pos(';', begin);
                    819: 
                    820:                if(end==STRING_NOT_FOUND)
                    821:                        end=CONTENT_TYPE.length();
1.232     misha     822: 
1.233     misha     823:                const String::Body NAME=CONTENT_TYPE.mid(begin, end);
                    824:                return &charsets.get(NAME);
                    825:        }
                    826:        return 0;
1.232     misha     827: }
                    828: 
                    829: 
1.84      paf       830: static bool isLeap(int year) {
1.229     misha     831:        return !(
                    832:                                (year % 4) || ((year % 400) && !(year % 100))
                    833:                        ); 
1.57      parser    834: }
                    835: 
                    836: int getMonthDays(int year, int month) {
1.220     misha     837:        static int monthDays[]={
1.229     misha     838:                31, 
                    839:                28, 
                    840:                31, 
                    841:                30, 
                    842:                31, 
                    843:                30, 
                    844:                31, 
                    845:                31, 
                    846:                30, 
                    847:                31, 
                    848:                30, 
                    849:                31
                    850:        }; 
1.228     misha     851:        return (month == 1 /* january -- 0 */ && isLeap(year)) ? 29 : monthDays[month]; 
1.41      paf       852: }
1.69      parser    853: 
1.226     misha     854: int remove_crlf(char* start, char* end) {
                    855:        char* from=start;
                    856:        char* to=start;
                    857:        bool skip=false;
                    858:        while(from < end){
                    859:                switch(*from){
                    860:                        case '\n':
                    861:                        case '\r':
                    862:                        case '\t':
                    863:                        case ' ':
                    864:                                if(!skip){
                    865:                                        *to=' ';
                    866:                                        to++;
                    867:                                        skip=true;
                    868:                                }
                    869:                                break;
                    870:                        default:
                    871:                                if(from != to)
                    872:                                        *to=*from;
                    873:                                to++;
                    874:                                skip=false;
1.69      parser    875:                }
1.226     misha     876:                from++;
                    877:        }
                    878:        return to-start;
1.91      paf       879: }
                    880: 
                    881: 
                    882: /// must be last in this file
                    883: #undef vsnprintf
1.126     paf       884: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91      paf       885:        if(!s)
                    886:                return 0;
                    887: 
                    888:        int r;
                    889:        // note: on win32& maybe somewhere else
                    890:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                    891:        --s;
1.172     paf       892: 
                    893:        // clients do not check for negative 's', feature: ignore such prints
                    894:        if((ssize_t)s<0)
                    895:                return 0;
                    896: 
1.91      paf       897: #if _MSC_VER
                    898:        /*
                    899:        win32: 
                    900:        mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
                    901: 
1.154     paf       902:          if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91      paf       903:        */
1.126     paf       904:        r=_vsnprintf(b, s, f, l); 
1.91      paf       905:        if(r<0) 
                    906:                r=s;
                    907: #else
1.126     paf       908:        r=vsnprintf(b, s, f, l); 
1.91      paf       909:        /*
                    910:        solaris: 
                    911:        man vsnprintf
                    912: 
                    913:          The snprintf() function returns  the  number  of  characters
                    914:        formatted, that is, the number of characters that would have
                    915:        been written to the buffer if it were large enough.  If  the
                    916:        value  of  n  is  0  on a call to snprintf(), an unspecified
                    917:        value less than 1 is returned.
                    918:        */
                    919: 
                    920:        if(r<0)
                    921:                r=0;
1.167     paf       922:        else if((size_t)r>s)
1.91      paf       923:                r=s;
                    924: #endif
                    925:        b[r]=0;
                    926:        return r;
                    927: }
                    928: 
1.126     paf       929: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91      paf       930:        va_list l;
1.126     paf       931:     va_start(l, f); 
                    932:     int r=__vsnprintf(b, s, f, l); 
                    933:     va_end(l); 
1.91      paf       934:        return r;
1.178     paf       935: }
                    936: 
                    937: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
                    938: /*
                    939:  *  Authors: Michael Zucchi <notzed@helixcode.com>
                    940:  *           Jeffrey Stedfast <fejj@helixcode.com>
                    941:  *
                    942:  *  Copyright 2000 Helix Code, Inc. (www.helixcode.com)
                    943:  *
                    944:  *  This program is free software; you can redistribute it and/or modify
                    945:  *  it under the terms of the GNU General Public License as published by
                    946:  *  the Free Software Foundation; either version 2 of the License, or
                    947:  *  (at your option) any later version.
                    948:  *
                    949:  *  This program is distributed in the hope that it will be useful,
                    950:  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
                    951:  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    952:  *  GNU General Public License for more details.
                    953:  *
                    954:  *  You should have received a copy of the GNU General Public License
                    955:  *  along with this program; if not, write to the Free Software
                    956:  *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
                    957:  *
                    958:  */
                    959: static char *base64_alphabet =
                    960:        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                    961: 
                    962: /**
                    963:  * g_mime_utils_base64_encode_step:
                    964:  * @in: input stream
                    965:  * @inlen: length of the input
                    966:  * @out: output string
                    967:  * @state: holds the number of bits that are stored in @save
                    968:  * @save: leftover bits that have not yet been encoded
                    969:  *
                    970:  * Base64 encodes a chunk of data. Performs an 'encode step', only
                    971:  * encodes blocks of 3 characters to the output at a time, saves
                    972:  * left-over state in state and save (initialise to 0 on first
                    973:  * invocation).
                    974:  *
                    975:  * Returns the number of bytes encoded.
                    976:  **/
                    977: static size_t
                    978: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                    979: {
1.186     paf       980:        register const unsigned char *inptr;
1.178     paf       981:        register unsigned char *outptr;
                    982:        
                    983:        if (inlen <= 0)
                    984:                return 0;
                    985:        
                    986:        inptr = in;
                    987:        outptr = out;
                    988:        
                    989:        if (inlen + ((unsigned char *)save)[0] > 2) {
                    990:                const unsigned char *inend = in + inlen - 2;
                    991:                register int c1 = 0, c2 = 0, c3 = 0;
                    992:                register int already;
                    993:                
                    994:                already = *state;
                    995:                
                    996:                switch (((char *)save)[0]) {
                    997:                case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
                    998:                case 2: c1 = ((unsigned char *)save)[1];
                    999:                        c2 = ((unsigned char *)save)[2]; goto skip2;
                   1000:                }
                   1001:                
                   1002:                /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
                   1003:                while (inptr < inend) {
                   1004:                        c1 = *inptr++;
                   1005:                skip1:
                   1006:                        c2 = *inptr++;
                   1007:                skip2:
                   1008:                        c3 = *inptr++;
                   1009:                        *outptr++ = base64_alphabet [c1 >> 2];
                   1010:                        *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
                   1011:                        *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
                   1012:                        *outptr++ = base64_alphabet [c3 & 0x3f];
                   1013:                        /* this is a bit ugly ... */
                   1014:                        if ((++already) >= 19) {
                   1015:                                *outptr++ = '\n';
                   1016:                                already = 0;
                   1017:                        }
                   1018:                }
                   1019:                
                   1020:                ((unsigned char *)save)[0] = 0;
                   1021:                inlen = 2 - (inptr - inend);
                   1022:                *state = already;
                   1023:        }
                   1024:        
                   1025:        //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
                   1026:        
                   1027:        if (inlen > 0) {
                   1028:                register char *saveout;
                   1029:                
                   1030:                /* points to the slot for the next char to save */
                   1031:                saveout = & (((char *)save)[1]) + ((char *)save)[0];
                   1032:                
                   1033:                /* inlen can only be 0 1 or 2 */
                   1034:                switch (inlen) {
                   1035:                case 2: *saveout++ = *inptr++;
                   1036:                case 1: *saveout++ = *inptr++;
                   1037:                }
1.216     paf      1038:                *(char *)save = *(char *)save+(char)inlen;
1.178     paf      1039:        }
                   1040:        
                   1041:        /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
                   1042:                  (int)((char *)save)[0],
                   1043:                  (int)((char *)save)[1],
                   1044:                  (int)((char *)save)[2]));*/
                   1045:        
                   1046:        return (outptr - out);
                   1047: }
                   1048: 
                   1049: /**
                   1050:  * g_mime_utils_base64_encode_close:
                   1051:  * @in: input stream
                   1052:  * @inlen: length of the input
                   1053:  * @out: output string
                   1054:  * @state: holds the number of bits that are stored in @save
                   1055:  * @save: leftover bits that have not yet been encoded
                   1056:  *
                   1057:  * Base64 encodes the input stream to the output stream. Call this
                   1058:  * when finished encoding data with g_mime_utils_base64_encode_step to
                   1059:  * flush off the last little bit.
                   1060:  *
                   1061:  * Returns the number of bytes encoded.
                   1062:  **/
                   1063: static size_t
                   1064: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1065: {
                   1066:        unsigned char *outptr = out;
                   1067:        int c1, c2;
                   1068:        
                   1069:        if (inlen > 0)
                   1070:                outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
                   1071:        
                   1072:        c1 = ((unsigned char *)save)[1];
                   1073:        c2 = ((unsigned char *)save)[2];
                   1074:        
                   1075:        switch (((unsigned char *)save)[0]) {
                   1076:        case 2:
                   1077:                outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
                   1078:                goto skip;
                   1079:        case 1:
                   1080:                outptr[2] = '=';
                   1081:        skip:
                   1082:                outptr[0] = base64_alphabet [c1 >> 2];
                   1083:                outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
                   1084:                outptr[3] = '=';
                   1085:                outptr += 4;
                   1086:                break;
                   1087:        }
                   1088:        
                   1089:        *outptr++ = 0;
                   1090:        
                   1091:        *save = 0;
                   1092:        *state = 0;
                   1093:        
                   1094:        return (outptr - out);
                   1095: }
                   1096: 
1.210     paf      1097: static unsigned char gmime_base64_rank[256] = {
                   1098:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1099:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1100:        255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
                   1101:         52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255,  0,255,255,
                   1102:        255,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
                   1103:         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
                   1104:        255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
                   1105:         41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
                   1106:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1107:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1108:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1109:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1110:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1111:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1112:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1113:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1114: };
                   1115: 
                   1116: /**
                   1117:  * g_mime_utils_base64_decode_step:
                   1118:  * @in: input stream
                   1119:  * @inlen: max length of data to decode
                   1120:  * @out: output stream
                   1121:  * @state: holds the number of bits that are stored in @save
                   1122:  * @save: leftover bits that have not yet been decoded
                   1123:  *
                   1124:  * Decodes a chunk of base64 encoded data.
                   1125:  *
                   1126:  * Returns the number of bytes decoded (which have been dumped in @out).
                   1127:  **/
                   1128: size_t
                   1129: g_mime_utils_base64_decode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1130: {
1.213     paf      1131:        const unsigned char *inptr;
                   1132:        unsigned char *outptr;
1.210     paf      1133:        const unsigned char *inend;
1.213     paf      1134:        int saved;
1.210     paf      1135:        unsigned char c;
                   1136:        int i;
                   1137:        
                   1138:        inend = in + inlen;
                   1139:        outptr = out;
                   1140:        
                   1141:        /* convert 4 base64 bytes to 3 normal bytes */
                   1142:        saved = *save;
                   1143:        i = *state;
                   1144:        inptr = in;
                   1145:        while (inptr < inend) {
                   1146:                c = gmime_base64_rank[*inptr++];
                   1147:                if (c != 0xff) {
                   1148:                        saved = (saved << 6) | c;
                   1149:                        i++;
                   1150:                        if (i == 4) {
1.217     paf      1151:                                *outptr++ = (unsigned char)(saved >> 16);
                   1152:                                *outptr++ = (unsigned char)(saved >> 8);
                   1153:                                *outptr++ = (unsigned char)(saved);
1.210     paf      1154:                                i = 0;
                   1155:                        }
                   1156:                }
                   1157:        }
                   1158:        
                   1159:        *save = saved;
                   1160:        *state = i;
                   1161:        
                   1162:        /* quick scan back for '=' on the end somewhere */
                   1163:        /* fortunately we can drop 1 output char for each trailing = (upto 2) */
                   1164:        i = 2;
                   1165:        while (inptr > in && i) {
                   1166:                inptr--;
                   1167:                if (gmime_base64_rank[*inptr] != 0xff) {
                   1168:                        if (*inptr == '=' && outptr > out)
                   1169:                                outptr--;
                   1170:                        i--;
                   1171:                }
                   1172:        }
                   1173:        
                   1174:        /* if i != 0 then there is a truncation error! */
                   1175:        return (outptr - out);
                   1176: }
                   1177: 
                   1178: 
                   1179: char* pa_base64_encode(const char *in, size_t in_size)
1.178     paf      1180: {
                   1181:        /* wont go to more than 2x size (overly conservative) */
1.210     paf      1182:        char* result=new(PointerFreeGC) char[in_size * 2 + 6];
1.178     paf      1183:        int state=0;
                   1184:        int save=0;
1.183     paf      1185: #ifndef NDEBUG
                   1186:        size_t filled=
                   1187: #endif
1.210     paf      1188:                g_mime_utils_base64_encode_close ((const unsigned char*)in, in_size, 
1.178     paf      1189:                (unsigned char*)result, &state, &save);
1.210     paf      1190:        assert(filled <= in_size * 2 + 6);
1.178     paf      1191: 
                   1192:        return result;
1.98      paf      1193: }
1.210     paf      1194: 
1.222     misha    1195: 
                   1196: char* pa_base64_encode(const String& file_spec)
                   1197: {
                   1198:        unsigned char* base64=0;
                   1199:        File_base64_action_info info={&base64}; 
                   1200: 
                   1201:        file_read_action_under_lock(file_spec, 
                   1202:                "pa_base64_encode", file_base64_file_action, &info);
                   1203: 
                   1204:        return (char*)base64; 
                   1205: }
                   1206: 
                   1207: 
                   1208: static void file_base64_file_action(
1.229     misha    1209:                                struct stat& finfo, 
                   1210:                                int f, 
                   1211:                                const String&, const char* /*fname*/, bool, 
                   1212:                                void *context) {
1.222     misha    1213: 
                   1214:        if(finfo.st_size) { 
                   1215:                File_base64_action_info& info=*static_cast<File_base64_action_info *>(context);
                   1216:                *info.base64=new(PointerFreeGC) unsigned char[finfo.st_size * 2 + 6]; 
                   1217:                unsigned char* base64 = *info.base64;
                   1218:                int state=0;
                   1219:                int save=0;
                   1220:                int nCount;
                   1221:                do {
                   1222:                        unsigned char buffer[FILE_BUFFER_SIZE];
                   1223:                        nCount = file_block_read(f, buffer, sizeof(buffer));
                   1224:                        if( nCount ){
                   1225:                                size_t filled=g_mime_utils_base64_encode_step ((const unsigned char*)buffer, nCount, base64, &state, &save);
                   1226:                                base64+=filled;
                   1227:                        }
                   1228:                } while(nCount > 0);
                   1229:                g_mime_utils_base64_encode_close (0, 0, base64, &state, &save);
                   1230:        }
                   1231: }
                   1232: 
1.211     paf      1233: void pa_base64_decode(const char *in, size_t in_size, char*& result, size_t& result_size)
1.210     paf      1234: {
                   1235:        /* wont go to more than had (overly conservative) */
1.211     paf      1236:        result=new(PointerFreeGC) char[in_size+1/*terminator*/];
1.210     paf      1237:        int state=0;
                   1238:        int save=0;
                   1239:        result_size=
                   1240:                g_mime_utils_base64_decode_step ((const unsigned char*)in, in_size, 
                   1241:                (unsigned char*)result, &state, &save);
                   1242:        assert(result_size <= in_size);
1.211     paf      1243:        result[result_size]=0; // for text files
1.210     paf      1244: }
1.218     misha    1245: 
                   1246: 
1.221     misha    1247: int file_block_read(const int f, unsigned char* buffer, const size_t size){
                   1248:        int nCount = read(f, buffer, size);
                   1249:        if (nCount < 0)
1.238   ! misha    1250:                throw Exception("file.read", 
1.221     misha    1251:                        0, 
                   1252:                        "read failed: %s (%d)",  strerror(errno), errno); 
                   1253:        return nCount;
                   1254: }
                   1255: 
1.218     misha    1256: const unsigned long pa_crc32(const char *in, size_t in_size)
                   1257: {
                   1258:        unsigned long crc32=0xFFFFFFFF;
1.220     misha    1259: 
1.218     misha    1260:                InitCrc32Table();
                   1261:                for(size_t i = 0; i < in_size; i++) CalcCrc32(in[i], crc32);
1.220     misha    1262: 
1.218     misha    1263:        return ~crc32; 
                   1264: }
                   1265: 
                   1266: const unsigned long pa_crc32(const String& file_spec)
                   1267: {
                   1268:        unsigned long crc32=0xFFFFFFFF;
                   1269:        file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
                   1270:        return ~crc32; 
                   1271: }
                   1272: 
                   1273: static void file_crc32_file_action(
1.229     misha    1274:                                struct stat& finfo, 
                   1275:                                int f, 
                   1276:                                const String&, const char* /*fname*/, bool, 
                   1277:                                void *context)
1.218     misha    1278: {
                   1279:        unsigned long& crc32=*static_cast<unsigned long *>(context);
                   1280:        if(finfo.st_size) {
                   1281:                InitCrc32Table();
1.220     misha    1282:                int nCount=0;
1.218     misha    1283:                do {
1.221     misha    1284:                        unsigned char buffer[FILE_BUFFER_SIZE];
                   1285:                        nCount = file_block_read(f, buffer, sizeof(buffer));
1.220     misha    1286:                        for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
                   1287:                } while(nCount > 0);
1.218     misha    1288:        }
                   1289: }
                   1290: 
1.237     misha    1291: char* print_pcre_exec_error_text(int exec_result){
                   1292:        switch(exec_result){
                   1293:                case PCRE_ERROR_BADUTF8:
                   1294:                        return "validation of UTF-8 string failed while pcre_exec (%d).";
                   1295:                        break;
                   1296:                default:
                   1297:                        return "regular expression execute error (%d)";
                   1298:        }
                   1299: }
                   1300: 

E-mail: