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

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

E-mail: