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

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

E-mail: