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

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

E-mail: