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

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

E-mail: