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

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

E-mail: