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

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

E-mail: