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

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

E-mail: