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

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

E-mail: