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

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

E-mail: