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

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

E-mail: