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

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

E-mail: