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

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.235   ! misha      29: static const char * const IDENT_COMMON_C="$Date: 2008-06-11 11:38:35 $"; 
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.98      paf        38: 
1.93      paf        39: // some maybe-undefined constants
                     40: 
1.82      paf        41: #ifndef _O_TEXT
                     42: #      define _O_TEXT 0
                     43: #endif
                     44: #ifndef _O_BINARY
                     45: #      define _O_BINARY 0
1.47      paf        46: #endif
1.80      paf        47: 
1.138     paf        48: #ifdef HAVE_FTRUNCATE
                     49: #      define PA_O_TRUNC 0
                     50: #else
                     51: #      ifdef _O_TRUNC
                     52: #              define PA_O_TRUNC _O_TRUNC
                     53: #      else
                     54: #              error you must have either ftruncate function or _O_TRUNC bit declared
                     55: #      endif
1.154     paf        56: #endif
1.176     paf        57: 
1.154     paf        58: // defines for globals
                     59: 
                     60: #define FILE_STATUS_NAME  "status"
                     61: 
                     62: // globals
                     63: 
                     64: const String file_status_name(FILE_STATUS_NAME);
                     65: 
                     66: // functions
1.127     paf        67: 
1.154     paf        68: void fix_line_breaks(char *str, size_t& length) {
1.87      paf        69:        //_asm int 3;
1.154     paf        70:        const char* const eob=str+length;
                     71:        char* dest=str;
1.72      parser     72:        // fix DOS: \r\n -> \n
                     73:        // fix Macintosh: \r -> \n
1.154     paf        74:        char* bol=str;
1.137     paf        75:        while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72      parser     76:                size_t len=eol-bol;
                     77:                if(dest!=bol)
1.126     paf        78:                        memcpy(dest, bol, len); 
1.72      parser     79:                dest+=len;
1.126     paf        80:                *dest++='\n'; 
1.72      parser     81: 
1.126     paf        82:                if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72      parser     83:                        bol=eol+2;
1.154     paf        84:                        length--; 
1.126     paf        85:                } else // \r, not \n = Macintosh
1.72      parser     86:                        bol=eol+1;
                     87:        }
1.154     paf        88:        // last piece without \r
1.72      parser     89:        if(dest!=bol)
1.126     paf        90:                memcpy(dest, bol, eob-bol); 
1.154     paf        91:        str[length]=0; // terminating
1.72      parser     92: }
1.18      paf        93: 
1.154     paf        94: char* file_read_text(Request_charsets& charsets, 
1.229     misha      95:                        const String& file_spec, 
                     96:                        bool fail_on_read_problem,
1.234     misha      97:                        HashStringValue* params,
                     98:                        bool transcode_result) {
1.154     paf        99:        File_read_result file=
1.234     misha     100:                file_read(charsets, file_spec, true, params, fail_on_read_problem, 0, 0, 0, transcode_result);
1.154     paf       101:        return file.success?file.str:0;
1.126     paf       102: }
                    103: 
1.206     paf       104: /// these options were handled but not checked elsewhere, now check them
1.214     paf       105: int pa_get_valid_file_options_count(HashStringValue& options)
1.206     paf       106: {
                    107:        int result=0;
                    108:        if(options.get(PA_SQL_LIMIT_NAME))
                    109:                result++;
                    110:        if(options.get(PA_SQL_OFFSET_NAME))
                    111:                result++;
                    112:        if(options.get(PA_COLUMN_SEPARATOR_NAME))
                    113:                result++;
                    114:        if(options.get(PA_COLUMN_ENCLOSER_NAME))
                    115:                result++;
1.223     misha     116:        if(options.get(PA_CHARSET_NAME))
                    117:                result++;
1.206     paf       118:        return result;
                    119: }
                    120: 
1.123     paf       121: #ifndef DOXYGEN
                    122: struct File_read_action_info {
1.154     paf       123:        char **data; size_t *data_size;
1.188     paf       124:        char* buf; size_t offset; size_t count;
1.126     paf       125: }; 
1.123     paf       126: #endif
1.154     paf       127: static void file_read_action(
1.229     misha     128:                                struct stat& finfo, 
                    129:                                int f, 
                    130:                                const String& file_spec, const char* /*fname*/, bool as_text, 
                    131:                                void *context) {
1.126     paf       132:        File_read_action_info& info=*static_cast<File_read_action_info *>(context); 
1.188     paf       133:        size_t to_read_size=info.count;
                    134:        if(!to_read_size)
                    135:                to_read_size=(size_t)finfo.st_size;
                    136:        assert( !(info.buf && as_text) );
                    137:        if(to_read_size) { 
                    138:                if(info.offset)
                    139:                        lseek(f, info.offset, SEEK_SET);
                    140:                *info.data=info.buf
                    141:                        ? info.buf
                    142:                        : new(PointerFreeGC) char[to_read_size+(as_text?1:0)]; 
1.126     paf       143:                *info.data_size=(size_t)read(f, *info.data, to_read_size); 
1.123     paf       144: 
                    145:                if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126     paf       146:                        throw Exception(0, 
1.123     paf       147:                                &file_spec, 
1.173     paf       148:                                "read failed: actually read %u bytes count not in [0..%u] valid range", 
1.126     paf       149:                                        *info.data_size, to_read_size); 
1.123     paf       150:        } else { // empty file
1.209     paf       151:                // for both, text and binary: for text we need that terminator, for binary we need nonzero pointer to be able to save such files
                    152:                *info.data=new(PointerFreeGC) char[1]; 
                    153:                *(char*)(*info.data)=0;
1.123     paf       154:                *info.data_size=0;
                    155:                return;
                    156:        }
1.126     paf       157: }
1.154     paf       158: File_read_result file_read(Request_charsets& charsets, const String& file_spec, 
1.229     misha     159:                        bool as_text, HashStringValue *params,
                    160:                        bool fail_on_read_problem,
1.234     misha     161:                        char* buf, size_t offset, size_t count, bool transcode_text_result) {
1.167     paf       162:        File_read_result result={false, 0, 0, 0};
1.154     paf       163:        if(file_spec.starts_with("http://")) {
1.203     paf       164:                if(offset || count)
1.224     misha     165:                        throw Exception(PARSER_RUNTIME,
1.203     paf       166:                                0,
                    167:                                "offset and load options are not supported for HTTP:// file load");
                    168: 
1.126     paf       169:                // fail on read problem
1.234     misha     170:                File_read_http_result http=pa_internal_file_read_http(charsets, file_spec, as_text, params, transcode_text_result);
1.154     paf       171:                result.success=true;
                    172:                result.str=http.str;
                    173:                result.length=http.length;
                    174:                result.headers=http.headers; 
1.126     paf       175:        } else {
1.206     paf       176:                if(params) {
1.214     paf       177:                        int valid_options=pa_get_valid_file_options_count(*params);
1.206     paf       178:                        if(valid_options!=params->count())
1.224     misha     179:                                throw Exception(PARSER_RUNTIME,
1.206     paf       180:                                        0,
                    181:                                        "invalid option passed");
                    182:                }
1.161     paf       183: 
1.188     paf       184:                File_read_action_info info={&result.str, &result.length,
                    185:                        buf, offset, count}; 
1.154     paf       186:                result.success=file_read_action_under_lock(file_spec, 
1.126     paf       187:                        "read", file_read_action, &info, 
                    188:                        as_text, fail_on_read_problem); 
1.223     misha     189: 
1.234     misha     190:                if(result.length && as_text && params && transcode_text_result) {
1.223     misha     191:                        if( Value* vcharset_name=params->get(PA_CHARSET_NAME) ) {
                    192:                                Charset asked_charset=::charsets.get(vcharset_name->as_string().
                    193:                                        change_case(charsets.source(), String::CC_UPPER));
                    194: 
                    195:                                String::C body=String::C(result.str, result.length);
                    196:                                body=Charset::transcode(body, asked_charset, charsets.source());
                    197: 
                    198:                                result.str=const_cast<char *>(body.str); // hacking a little
                    199:                                result.length=body.length;
                    200:                        } 
                    201:                }
1.126     paf       202:        }
1.123     paf       203: 
1.154     paf       204:        if(result.success && as_text) {
1.131     paf       205:                // UTF-8 signature: EF BB BF
1.154     paf       206:                if(result.length>=3) {
                    207:                        char *in=(char *)result.str;
1.159     paf       208:                        if(strncmp(in, "\xEF\xBB\xBF", 3)==0) {
1.154     paf       209:                                result.str=in+3; result.length-=3;// skip prefix
1.131     paf       210:                        }
                    211:                }
                    212: 
1.154     paf       213:                fix_line_breaks((char *)(result.str), result.length); 
1.123     paf       214:        }
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.126     paf       364:                        throw Exception(0, 
                    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.154     paf       656: char* unescape_chars(const char* cp, int len) {
                    657:        char* s=new(PointerFreeGC) char[len + 1]; 
1.229     misha     658:        EscapeState escapeState=EscapeRest;
1.216     paf       659:        uint escapedValue=0;
1.14      paf       660:        int srcPos=0;
                    661:        int dstPos=0;
                    662:        while(srcPos < len) {
1.193     paf       663:                uchar ch=(uchar)cp[srcPos]; 
1.14      paf       664:                switch(escapeState) {
                    665:                        case EscapeRest:
1.229     misha     666:                                if(ch=='%') {
                    667:                                        escapeState=EscapeFirst;
                    668:                                } else if(ch=='+'){
                    669:                                        s[dstPos++]=' '; 
                    670:                                } else {
                    671:                                        s[dstPos++]=ch; 
                    672:                                }
                    673:                                break;
1.14      paf       674:                        case EscapeFirst:
1.229     misha     675:                                escapedValue=hex_value[ch] << 4;
                    676:                                escapeState=EscapeSecond;
                    677:                                break;
1.14      paf       678:                        case EscapeSecond:
1.229     misha     679:                                escapedValue +=hex_value[ch]; 
                    680:                                s[dstPos++]=(char)escapedValue;
                    681:                                escapeState=EscapeRest;
                    682:                                break;
1.14      paf       683:                }
1.126     paf       684:                srcPos++; 
1.14      paf       685:        }
                    686:        s[dstPos]=0;
                    687:        return s;
1.24      paf       688: }
1.229     misha     689: */
                    690: 
1.232     misha     691: char* unescape_chars(const char* cp, int len, Charset* charset){
1.230     misha     692:        char* s=new(PointerFreeGC) char[len + 1]; // enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
                    693:        char* dst=s;
1.229     misha     694:        EscapeState escapeState=EscapeRest;
                    695:        uint escapedValue=0;
                    696:        int srcPos=0;
1.230     misha     697:        short int jsCnt=0;
1.229     misha     698:        while(srcPos < len) {
                    699:                uchar c=(uchar)cp[srcPos]; 
                    700:                if(c=='%'){
                    701:                        escapeState=EscapeFirst;
                    702:                } else {
                    703:                        switch(escapeState) {
                    704:                                case EscapeRest:
                    705:                                        if(c=='+'){
1.230     misha     706:                                                *dst++=' ';
1.229     misha     707:                                        } else {
1.230     misha     708:                                                *dst++=c;
1.229     misha     709:                                        }
                    710:                                        break;
                    711:                                case EscapeFirst:
1.232     misha     712:                                        if(charset && c=='u'){
1.229     misha     713:                                                // escaped unicode value: %u0430
                    714:                                                jsCnt=0;
                    715:                                                escapedValue=0;
                    716:                                                escapeState=EscapeUnicode;
                    717:                                        } else {
1.231     misha     718:                                                if(isxdigit(c)){
1.229     misha     719:                                                        escapedValue=hex_value[c] << 4;
                    720:                                                        escapeState=EscapeSecond;
                    721:                                                } else {
1.230     misha     722:                                                        *dst++=c;
1.229     misha     723:                                                        escapeState=EscapeRest;
                    724:                                                }
                    725:                                        }
                    726:                                        break;
                    727:                                case EscapeSecond:
1.231     misha     728:                                        if(isxdigit(c)){
1.229     misha     729:                                                escapedValue+=hex_value[c]; 
1.230     misha     730:                                                *dst++=(char)escapedValue;
1.229     misha     731:                                        }
                    732:                                        escapeState=EscapeRest;
                    733:                                        break;
                    734:                                case EscapeUnicode:
1.231     misha     735:                                        if(isxdigit(c)){
1.229     misha     736:                                                escapedValue=(escapedValue << 4) + hex_value[c];
                    737:                                                if(++jsCnt==4){
1.230     misha     738:                                                        // transcode utf8 char to client charset (we can lost some chars here)
1.232     misha     739:                                                        charset->store_Char((XMLByte*&)dst, (XMLCh)escapedValue, '?');
1.229     misha     740:                                                        escapeState=EscapeRest;
                    741:                                                }
                    742:                                        } else {
                    743:                                                // not full unicode value
                    744:                                                escapeState=EscapeRest;
                    745:                                        }
                    746:                                        break;
                    747:                        }
                    748:                }
                    749: 
                    750:                srcPos++;
                    751:        }
                    752: 
1.230     misha     753:        *dst=0; // zero-termination
1.229     misha     754:        return s;
                    755: }
1.24      paf       756: 
                    757: #ifdef WIN32
1.126     paf       758: void back_slashes_to_slashes(char* s) {
1.24      paf       759:        if(s)
                    760:                for(; *s; s++)
                    761:                        if(*s=='\\')
1.126     paf       762:                                *s='/'; 
1.24      paf       763: }
1.42      paf       764: /*
1.126     paf       765: void slashes_to_back_slashes(char* s) {
1.42      paf       766:        if(s)
                    767:                for(; *s; s++)
                    768:                        if(*s=='/')
1.126     paf       769:                                *s='\\'; 
1.42      paf       770: }
                    771: */
1.24      paf       772: #endif
1.41      paf       773: 
1.231     misha     774: bool StrStartFromNC(const char* str, const char* substr, bool equal){
1.41      paf       775:        while(true) {
1.231     misha     776:                if(!(*substr)){
                    777:                        if(!(*str))
1.41      paf       778:                                return true;
                    779:                        else
1.231     misha     780:                                return !equal;
                    781:                }
                    782:                if(!(*str))
                    783:                        return false;
                    784:                if(isalpha((unsigned char)*str)) {
                    785:                        if(tolower((unsigned char)*str)!=tolower((unsigned char)*substr))
1.41      paf       786:                                return false;
1.231     misha     787:                } else if((*str) != (*substr))
1.41      paf       788:                        return false;
1.231     misha     789:                str++; 
                    790:                substr++; 
1.41      paf       791:        }
1.57      parser    792: }
                    793: 
1.232     misha     794: size_t strpos(const char *str, const char *substr) {
                    795:        const char *p = strstr(str, substr);
                    796:        return (p==0)?STRING_NOT_FOUND:p-str;
                    797: }
                    798: 
                    799: // content-type: xxx; charset=WE-NEED-THIS
                    800: // content-type: xxx; charset="WE-NEED-THIS"
                    801: // content-type: xxx; charset="WE-NEED-THIS";
1.233     misha     802: Charset* detect_charset(const char* content_type){
                    803:        if(content_type){
                    804:                size_t len=strlen(content_type);
                    805:                char* CONTENT_TYPE=new(PointerFreeGC) char[len+1];
                    806:                memcpy(CONTENT_TYPE, content_type, len);
                    807:                for(char *p=CONTENT_TYPE; *p; p++)
                    808:                        *p=(char)toupper((unsigned char)*p);
                    809: 
                    810:                if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
                    811:                        begin+=8; // skip "CHARSET="
                    812:                        char* end=0;
                    813:                        if(*begin && (*begin=='"' || *begin =='\'')){
                    814:                                char quote=*begin;
                    815:                                begin++;
                    816:                                end=(char*)strchr(begin, quote);
                    817:                        }
                    818:                        if(!end)
                    819:                                end=(char*)strchr(begin, ';');
                    820: 
                    821:                        size_t len;
                    822:                        if(end){
                    823:                                *end=0; // terminator
                    824:                                len=end-begin;
                    825:                        } else {
                    826:                                len=strlen(begin);
                    827:                        }
                    828: 
                    829:                        String::Body NAME=String::Body(begin, len);
                    830:                        return &charsets.get(NAME);
1.232     misha     831:                }
                    832:        }
                    833:        return 0;
                    834: }
                    835: 
1.233     misha     836: Charset* detect_charset(Charset& source_charset, const String& content_type){
                    837:        const String& CONTENT_TYPE=content_type.change_case(source_charset, String::CC_UPPER);
                    838:        size_t begin=CONTENT_TYPE.pos("CHARSET=");
                    839:        if(begin!=STRING_NOT_FOUND) {
                    840:                begin+=8; // skip "CHARSET="
                    841:                size_t end=STRING_NOT_FOUND;
                    842: 
                    843:                if(CONTENT_TYPE.pos('"', begin)==begin){
                    844:                        begin++;
                    845:                        end=CONTENT_TYPE.pos('"', begin);
                    846:                } else if(CONTENT_TYPE.pos('\'', begin)==begin){
                    847:                        begin++;
                    848:                        end=CONTENT_TYPE.pos('\'', begin);
                    849:                }
                    850: 
                    851:                if(end==STRING_NOT_FOUND)
                    852:                        end=CONTENT_TYPE.pos(';', begin);
                    853: 
                    854:                if(end==STRING_NOT_FOUND)
                    855:                        end=CONTENT_TYPE.length();
1.232     misha     856: 
1.233     misha     857:                const String::Body NAME=CONTENT_TYPE.mid(begin, end);
                    858:                return &charsets.get(NAME);
                    859:        }
                    860:        return 0;
1.232     misha     861: }
                    862: 
                    863: 
1.84      paf       864: static bool isLeap(int year) {
1.229     misha     865:        return !(
                    866:                                (year % 4) || ((year % 400) && !(year % 100))
                    867:                        ); 
1.57      parser    868: }
                    869: 
                    870: int getMonthDays(int year, int month) {
1.220     misha     871:        static int monthDays[]={
1.229     misha     872:                31, 
                    873:                28, 
                    874:                31, 
                    875:                30, 
                    876:                31, 
                    877:                30, 
                    878:                31, 
                    879:                31, 
                    880:                30, 
                    881:                31, 
                    882:                30, 
                    883:                31
                    884:        }; 
1.228     misha     885:        return (month == 1 /* january -- 0 */ && isLeap(year)) ? 29 : monthDays[month]; 
1.41      paf       886: }
1.69      parser    887: 
1.226     misha     888: int remove_crlf(char* start, char* end) {
                    889:        char* from=start;
                    890:        char* to=start;
                    891:        bool skip=false;
                    892:        while(from < end){
                    893:                switch(*from){
                    894:                        case '\n':
                    895:                        case '\r':
                    896:                        case '\t':
                    897:                        case ' ':
                    898:                                if(!skip){
                    899:                                        *to=' ';
                    900:                                        to++;
                    901:                                        skip=true;
                    902:                                }
                    903:                                break;
                    904:                        default:
                    905:                                if(from != to)
                    906:                                        *to=*from;
                    907:                                to++;
                    908:                                skip=false;
1.69      parser    909:                }
1.226     misha     910:                from++;
                    911:        }
                    912:        return to-start;
1.91      paf       913: }
                    914: 
                    915: 
                    916: /// must be last in this file
                    917: #undef vsnprintf
1.126     paf       918: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91      paf       919:        if(!s)
                    920:                return 0;
                    921: 
                    922:        int r;
                    923:        // note: on win32& maybe somewhere else
                    924:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                    925:        --s;
1.172     paf       926: 
                    927:        // clients do not check for negative 's', feature: ignore such prints
                    928:        if((ssize_t)s<0)
                    929:                return 0;
                    930: 
1.91      paf       931: #if _MSC_VER
                    932:        /*
                    933:        win32: 
                    934:        mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
                    935: 
1.154     paf       936:          if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91      paf       937:        */
1.126     paf       938:        r=_vsnprintf(b, s, f, l); 
1.91      paf       939:        if(r<0) 
                    940:                r=s;
                    941: #else
1.126     paf       942:        r=vsnprintf(b, s, f, l); 
1.91      paf       943:        /*
                    944:        solaris: 
                    945:        man vsnprintf
                    946: 
                    947:          The snprintf() function returns  the  number  of  characters
                    948:        formatted, that is, the number of characters that would have
                    949:        been written to the buffer if it were large enough.  If  the
                    950:        value  of  n  is  0  on a call to snprintf(), an unspecified
                    951:        value less than 1 is returned.
                    952:        */
                    953: 
                    954:        if(r<0)
                    955:                r=0;
1.167     paf       956:        else if((size_t)r>s)
1.91      paf       957:                r=s;
                    958: #endif
                    959:        b[r]=0;
                    960:        return r;
                    961: }
                    962: 
1.126     paf       963: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91      paf       964:        va_list l;
1.126     paf       965:     va_start(l, f); 
                    966:     int r=__vsnprintf(b, s, f, l); 
                    967:     va_end(l); 
1.91      paf       968:        return r;
1.178     paf       969: }
                    970: 
                    971: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
                    972: /*
                    973:  *  Authors: Michael Zucchi <notzed@helixcode.com>
                    974:  *           Jeffrey Stedfast <fejj@helixcode.com>
                    975:  *
                    976:  *  Copyright 2000 Helix Code, Inc. (www.helixcode.com)
                    977:  *
                    978:  *  This program is free software; you can redistribute it and/or modify
                    979:  *  it under the terms of the GNU General Public License as published by
                    980:  *  the Free Software Foundation; either version 2 of the License, or
                    981:  *  (at your option) any later version.
                    982:  *
                    983:  *  This program is distributed in the hope that it will be useful,
                    984:  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
                    985:  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    986:  *  GNU General Public License for more details.
                    987:  *
                    988:  *  You should have received a copy of the GNU General Public License
                    989:  *  along with this program; if not, write to the Free Software
                    990:  *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
                    991:  *
                    992:  */
                    993: static char *base64_alphabet =
                    994:        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                    995: 
                    996: /**
                    997:  * g_mime_utils_base64_encode_step:
                    998:  * @in: input stream
                    999:  * @inlen: length of the input
                   1000:  * @out: output string
                   1001:  * @state: holds the number of bits that are stored in @save
                   1002:  * @save: leftover bits that have not yet been encoded
                   1003:  *
                   1004:  * Base64 encodes a chunk of data. Performs an 'encode step', only
                   1005:  * encodes blocks of 3 characters to the output at a time, saves
                   1006:  * left-over state in state and save (initialise to 0 on first
                   1007:  * invocation).
                   1008:  *
                   1009:  * Returns the number of bytes encoded.
                   1010:  **/
                   1011: static size_t
                   1012: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1013: {
1.186     paf      1014:        register const unsigned char *inptr;
1.178     paf      1015:        register unsigned char *outptr;
                   1016:        
                   1017:        if (inlen <= 0)
                   1018:                return 0;
                   1019:        
                   1020:        inptr = in;
                   1021:        outptr = out;
                   1022:        
                   1023:        if (inlen + ((unsigned char *)save)[0] > 2) {
                   1024:                const unsigned char *inend = in + inlen - 2;
                   1025:                register int c1 = 0, c2 = 0, c3 = 0;
                   1026:                register int already;
                   1027:                
                   1028:                already = *state;
                   1029:                
                   1030:                switch (((char *)save)[0]) {
                   1031:                case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
                   1032:                case 2: c1 = ((unsigned char *)save)[1];
                   1033:                        c2 = ((unsigned char *)save)[2]; goto skip2;
                   1034:                }
                   1035:                
                   1036:                /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
                   1037:                while (inptr < inend) {
                   1038:                        c1 = *inptr++;
                   1039:                skip1:
                   1040:                        c2 = *inptr++;
                   1041:                skip2:
                   1042:                        c3 = *inptr++;
                   1043:                        *outptr++ = base64_alphabet [c1 >> 2];
                   1044:                        *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
                   1045:                        *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
                   1046:                        *outptr++ = base64_alphabet [c3 & 0x3f];
                   1047:                        /* this is a bit ugly ... */
                   1048:                        if ((++already) >= 19) {
                   1049:                                *outptr++ = '\n';
                   1050:                                already = 0;
                   1051:                        }
                   1052:                }
                   1053:                
                   1054:                ((unsigned char *)save)[0] = 0;
                   1055:                inlen = 2 - (inptr - inend);
                   1056:                *state = already;
                   1057:        }
                   1058:        
                   1059:        //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
                   1060:        
                   1061:        if (inlen > 0) {
                   1062:                register char *saveout;
                   1063:                
                   1064:                /* points to the slot for the next char to save */
                   1065:                saveout = & (((char *)save)[1]) + ((char *)save)[0];
                   1066:                
                   1067:                /* inlen can only be 0 1 or 2 */
                   1068:                switch (inlen) {
                   1069:                case 2: *saveout++ = *inptr++;
                   1070:                case 1: *saveout++ = *inptr++;
                   1071:                }
1.216     paf      1072:                *(char *)save = *(char *)save+(char)inlen;
1.178     paf      1073:        }
                   1074:        
                   1075:        /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
                   1076:                  (int)((char *)save)[0],
                   1077:                  (int)((char *)save)[1],
                   1078:                  (int)((char *)save)[2]));*/
                   1079:        
                   1080:        return (outptr - out);
                   1081: }
                   1082: 
                   1083: /**
                   1084:  * g_mime_utils_base64_encode_close:
                   1085:  * @in: input stream
                   1086:  * @inlen: length of the input
                   1087:  * @out: output string
                   1088:  * @state: holds the number of bits that are stored in @save
                   1089:  * @save: leftover bits that have not yet been encoded
                   1090:  *
                   1091:  * Base64 encodes the input stream to the output stream. Call this
                   1092:  * when finished encoding data with g_mime_utils_base64_encode_step to
                   1093:  * flush off the last little bit.
                   1094:  *
                   1095:  * Returns the number of bytes encoded.
                   1096:  **/
                   1097: static size_t
                   1098: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1099: {
                   1100:        unsigned char *outptr = out;
                   1101:        int c1, c2;
                   1102:        
                   1103:        if (inlen > 0)
                   1104:                outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
                   1105:        
                   1106:        c1 = ((unsigned char *)save)[1];
                   1107:        c2 = ((unsigned char *)save)[2];
                   1108:        
                   1109:        switch (((unsigned char *)save)[0]) {
                   1110:        case 2:
                   1111:                outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
                   1112:                goto skip;
                   1113:        case 1:
                   1114:                outptr[2] = '=';
                   1115:        skip:
                   1116:                outptr[0] = base64_alphabet [c1 >> 2];
                   1117:                outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
                   1118:                outptr[3] = '=';
                   1119:                outptr += 4;
                   1120:                break;
                   1121:        }
                   1122:        
                   1123:        *outptr++ = 0;
                   1124:        
                   1125:        *save = 0;
                   1126:        *state = 0;
                   1127:        
                   1128:        return (outptr - out);
                   1129: }
                   1130: 
1.210     paf      1131: static unsigned char gmime_base64_rank[256] = {
                   1132:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1133:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1134:        255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
                   1135:         52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255,  0,255,255,
                   1136:        255,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
                   1137:         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
                   1138:        255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
                   1139:         41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
                   1140:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1141:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1142:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1143:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1144:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1145:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1146:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1147:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1148: };
                   1149: 
                   1150: /**
                   1151:  * g_mime_utils_base64_decode_step:
                   1152:  * @in: input stream
                   1153:  * @inlen: max length of data to decode
                   1154:  * @out: output stream
                   1155:  * @state: holds the number of bits that are stored in @save
                   1156:  * @save: leftover bits that have not yet been decoded
                   1157:  *
                   1158:  * Decodes a chunk of base64 encoded data.
                   1159:  *
                   1160:  * Returns the number of bytes decoded (which have been dumped in @out).
                   1161:  **/
                   1162: size_t
                   1163: g_mime_utils_base64_decode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1164: {
1.213     paf      1165:        const unsigned char *inptr;
                   1166:        unsigned char *outptr;
1.210     paf      1167:        const unsigned char *inend;
1.213     paf      1168:        int saved;
1.210     paf      1169:        unsigned char c;
                   1170:        int i;
                   1171:        
                   1172:        inend = in + inlen;
                   1173:        outptr = out;
                   1174:        
                   1175:        /* convert 4 base64 bytes to 3 normal bytes */
                   1176:        saved = *save;
                   1177:        i = *state;
                   1178:        inptr = in;
                   1179:        while (inptr < inend) {
                   1180:                c = gmime_base64_rank[*inptr++];
                   1181:                if (c != 0xff) {
                   1182:                        saved = (saved << 6) | c;
                   1183:                        i++;
                   1184:                        if (i == 4) {
1.217     paf      1185:                                *outptr++ = (unsigned char)(saved >> 16);
                   1186:                                *outptr++ = (unsigned char)(saved >> 8);
                   1187:                                *outptr++ = (unsigned char)(saved);
1.210     paf      1188:                                i = 0;
                   1189:                        }
                   1190:                }
                   1191:        }
                   1192:        
                   1193:        *save = saved;
                   1194:        *state = i;
                   1195:        
                   1196:        /* quick scan back for '=' on the end somewhere */
                   1197:        /* fortunately we can drop 1 output char for each trailing = (upto 2) */
                   1198:        i = 2;
                   1199:        while (inptr > in && i) {
                   1200:                inptr--;
                   1201:                if (gmime_base64_rank[*inptr] != 0xff) {
                   1202:                        if (*inptr == '=' && outptr > out)
                   1203:                                outptr--;
                   1204:                        i--;
                   1205:                }
                   1206:        }
                   1207:        
                   1208:        /* if i != 0 then there is a truncation error! */
                   1209:        return (outptr - out);
                   1210: }
                   1211: 
                   1212: 
                   1213: char* pa_base64_encode(const char *in, size_t in_size)
1.178     paf      1214: {
                   1215:        /* wont go to more than 2x size (overly conservative) */
1.210     paf      1216:        char* result=new(PointerFreeGC) char[in_size * 2 + 6];
1.178     paf      1217:        int state=0;
                   1218:        int save=0;
1.183     paf      1219: #ifndef NDEBUG
                   1220:        size_t filled=
                   1221: #endif
1.210     paf      1222:                g_mime_utils_base64_encode_close ((const unsigned char*)in, in_size, 
1.178     paf      1223:                (unsigned char*)result, &state, &save);
1.210     paf      1224:        assert(filled <= in_size * 2 + 6);
1.178     paf      1225: 
                   1226:        return result;
1.98      paf      1227: }
1.210     paf      1228: 
1.222     misha    1229: 
                   1230: char* pa_base64_encode(const String& file_spec)
                   1231: {
                   1232:        unsigned char* base64=0;
                   1233:        File_base64_action_info info={&base64}; 
                   1234: 
                   1235:        file_read_action_under_lock(file_spec, 
                   1236:                "pa_base64_encode", file_base64_file_action, &info);
                   1237: 
                   1238:        return (char*)base64; 
                   1239: }
                   1240: 
                   1241: 
                   1242: static void file_base64_file_action(
1.229     misha    1243:                                struct stat& finfo, 
                   1244:                                int f, 
                   1245:                                const String&, const char* /*fname*/, bool, 
                   1246:                                void *context) {
1.222     misha    1247: 
                   1248:        if(finfo.st_size) { 
                   1249:                File_base64_action_info& info=*static_cast<File_base64_action_info *>(context);
                   1250:                *info.base64=new(PointerFreeGC) unsigned char[finfo.st_size * 2 + 6]; 
                   1251:                unsigned char* base64 = *info.base64;
                   1252:                int state=0;
                   1253:                int save=0;
                   1254:                int nCount;
                   1255:                do {
                   1256:                        unsigned char buffer[FILE_BUFFER_SIZE];
                   1257:                        nCount = file_block_read(f, buffer, sizeof(buffer));
                   1258:                        if( nCount ){
                   1259:                                size_t filled=g_mime_utils_base64_encode_step ((const unsigned char*)buffer, nCount, base64, &state, &save);
                   1260:                                base64+=filled;
                   1261:                        }
                   1262:                } while(nCount > 0);
                   1263:                g_mime_utils_base64_encode_close (0, 0, base64, &state, &save);
                   1264:        }
                   1265: }
                   1266: 
1.211     paf      1267: void pa_base64_decode(const char *in, size_t in_size, char*& result, size_t& result_size)
1.210     paf      1268: {
                   1269:        /* wont go to more than had (overly conservative) */
1.211     paf      1270:        result=new(PointerFreeGC) char[in_size+1/*terminator*/];
1.210     paf      1271:        int state=0;
                   1272:        int save=0;
                   1273:        result_size=
                   1274:                g_mime_utils_base64_decode_step ((const unsigned char*)in, in_size, 
                   1275:                (unsigned char*)result, &state, &save);
                   1276:        assert(result_size <= in_size);
1.211     paf      1277:        result[result_size]=0; // for text files
1.210     paf      1278: }
1.218     misha    1279: 
                   1280: 
1.221     misha    1281: int file_block_read(const int f, unsigned char* buffer, const size_t size){
                   1282:        int nCount = read(f, buffer, size);
                   1283:        if (nCount < 0)
                   1284:                throw Exception(0, 
                   1285:                        0, 
                   1286:                        "read failed: %s (%d)",  strerror(errno), errno); 
                   1287:        return nCount;
                   1288: }
                   1289: 
1.218     misha    1290: const unsigned long pa_crc32(const char *in, size_t in_size)
                   1291: {
                   1292:        unsigned long crc32=0xFFFFFFFF;
1.220     misha    1293: 
1.218     misha    1294:                InitCrc32Table();
                   1295:                for(size_t i = 0; i < in_size; i++) CalcCrc32(in[i], crc32);
1.220     misha    1296: 
1.218     misha    1297:        return ~crc32; 
                   1298: }
                   1299: 
                   1300: const unsigned long pa_crc32(const String& file_spec)
                   1301: {
                   1302:        unsigned long crc32=0xFFFFFFFF;
                   1303:        file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
                   1304:        return ~crc32; 
                   1305: }
                   1306: 
                   1307: static void file_crc32_file_action(
1.229     misha    1308:                                struct stat& finfo, 
                   1309:                                int f, 
                   1310:                                const String&, const char* /*fname*/, bool, 
                   1311:                                void *context)
1.218     misha    1312: {
                   1313:        unsigned long& crc32=*static_cast<unsigned long *>(context);
                   1314:        if(finfo.st_size) {
                   1315:                InitCrc32Table();
1.220     misha    1316:                int nCount=0;
1.218     misha    1317:                do {
1.221     misha    1318:                        unsigned char buffer[FILE_BUFFER_SIZE];
                   1319:                        nCount = file_block_read(f, buffer, sizeof(buffer));
1.220     misha    1320:                        for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
                   1321:                } while(nCount > 0);
1.218     misha    1322:        }
                   1323: }
                   1324: 

E-mail: