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

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.300   ! moko       53: volatile const char * IDENT_PA_COMMON_C="$Id: pa_common.C,v 1.299 2016/12/29 15:55:40 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)
1.300   ! moko      121:                to_read_size=check_file_size(finfo.st_size, file_spec);
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.298     moko      243:                        if(pa_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;
1.298     moko      305:                        if(pa_fstat(f, &finfo)==0 && finfo.st_mode & 0111)
1.254     misha     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;
1.298     moko      465:        bool result=pa_stat(fname, &lfinfo)==0;
1.118     paf       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.298     moko      499:        if(pa_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;
1.299     moko      506:        ratime=(time_t)finfo.st_atime;
                    507:        rmtime=(time_t)finfo.st_mtime;
                    508:        rctime=(time_t)finfo.st_ctime;
1.64      parser    509:        return true;
1.18      paf       510: }
                    511: 
1.300   ! moko      512: size_t check_file_size(uint64_t size, const String& file_spec){
        !           513:        if(size > pa_file_size_limit)
        !           514:                throw Exception(PARSER_RUNTIME, &file_spec, "content size of %.15g bytes exceeds the limit (%.15g bytes)", (double)size, (double)pa_file_size_limit);
        !           515:        return (size_t)size;
        !           516: }
        !           517: 
1.278     moko      518: /** 
                    519:        String related functions
                    520: */
                    521: 
                    522: bool capitalized(const char* s){
                    523:        bool upper=true;
                    524:        for(const char* c=s; *c; c++){
                    525:                if(*c != (upper ? toupper((unsigned char)*c) : tolower((unsigned char)*c)))
                    526:                        return false;
                    527:                upper=strchr("-_ ", *c) != 0;
                    528:        }
                    529:        return true;
                    530: }
                    531: 
                    532: const char* capitalize(const char* s){
                    533:        if(!s || capitalized(s))
                    534:                return s;
                    535: 
                    536:        char* result=pa_strdup(s);
                    537:        if(result){
                    538:                bool upper=true;
                    539:                for(char* c=result; *c; c++){
                    540:                        *c=upper ? (char)toupper((unsigned char)*c) : (char)tolower((unsigned char)*c);
                    541:                        upper=strchr("-_ ", *c) != 0;
                    542:                }
                    543:        }
                    544:        return (const char*)result;
                    545: }
                    546: 
1.290     moko      547: char *str_lower(const char *s, size_t helper_length){
                    548:        char *result=pa_strdup(s, helper_length);
                    549:        for(char* c=result; *c; c++)
                    550:                *c=(char)tolower((unsigned char)*c);
                    551:        return result;
                    552: }
                    553: 
                    554: char *str_upper(const char *s, size_t helper_length){
                    555:        char *result=pa_strdup(s, helper_length);
                    556:        for(char* c=result; *c; c++)
                    557:                *c=(char)toupper((unsigned char)*c);
                    558:        return result;
                    559: }
                    560: 
1.278     moko      561: void fix_line_breaks(char *str, size_t& length) {
                    562:        //_asm int 3;
                    563:        const char* const eob=str+length;
                    564:        char* dest=str;
                    565:        // fix DOS: \r\n -> \n
                    566:        // fix Macintosh: \r -> \n
                    567:        char* bol=str;
                    568:        while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
                    569:                size_t len=eol-bol;
                    570:                if(dest!=bol)
                    571:                        memmove(dest, bol, len); 
                    572:                dest+=len;
                    573:                *dest++='\n'; 
                    574: 
                    575:                if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
                    576:                        bol=eol+2;
                    577:                        length--; 
                    578:                } else // \r, not \n = Macintosh
                    579:                        bol=eol+1;
                    580:        }
                    581:        // last piece without \r
                    582:        if(dest!=bol)
                    583:                memmove(dest, bol, eob-bol); 
                    584:        str[length]=0; // terminating
                    585: }
                    586: 
                    587: /**
                    588:        scans for @a delim[default \n] in @a *row_ref, 
                    589:        @return piece of line before it or end of string, if no @a delim found
                    590:        assigns @a *row_ref to point right after delimiter if there were one
                    591:        or to zero if no @a delim were found.
                    592: */
                    593: 
1.126     paf       594: char* getrow(char* *row_ref, char delim) {
1.229     misha     595:        char* result=*row_ref;
                    596:        if(result) {
1.126     paf       597:                *row_ref=strchr(result, delim); 
1.8       paf       598:                if(*row_ref) 
                    599:                        *((*row_ref)++)=0; 
                    600:                else if(!*result) 
                    601:                        return 0;
1.229     misha     602:        }
                    603:        return result;
1.8       paf       604: }
                    605: 
1.126     paf       606: char* lsplit(char* string, char delim) {
1.229     misha     607:        if(string) {
1.126     paf       608:                char* v=strchr(string, delim); 
1.8       paf       609:                if(v) {
                    610:                        *v=0;
                    611:                        return v+1;
                    612:                }
1.229     misha     613:        }
                    614:        return 0;
1.8       paf       615: }
                    616: 
1.126     paf       617: char* lsplit(char* *string_ref, char delim) {
1.229     misha     618:        char* result=*string_ref;
1.126     paf       619:        char* next=lsplit(*string_ref, delim); 
1.229     misha     620:        *string_ref=next;
                    621:        return result;
1.9       paf       622: }
                    623: 
1.126     paf       624: char* rsplit(char* string, char delim) {
1.229     misha     625:        if(string) {
1.126     paf       626:                char* v=strrchr(string, delim); 
1.18      paf       627:                if(v) {
1.9       paf       628:                        *v=0;
                    629:                        return v+1;
                    630:                }
1.229     misha     631:        }
                    632:        return NULL;    
1.10      paf       633: }
                    634: 
1.229     misha     635: 
                    636: // format: %[flags][width][.precision]type     http://msdn.microsoft.com/ru-ru/library/56e442dc(en-us,VS.80).aspx
                    637: //             flags: '-', '+', ' ', '#', '0'          http://msdn.microsoft.com/ru-ru/library/8aky45ct(en-us,VS.80).aspx
                    638: //             width, precision: non negative decimal number
                    639: enum FormatType {
                    640:        FormatInvalid,
                    641:        FormatInt,
                    642:        FormatUInt,
                    643:        FormatDouble
                    644: };
1.272     moko      645: FormatType format_type(const char* fmt){
1.229     misha     646:        enum FormatState {
                    647:                Percent, 
                    648:                Flags, 
                    649:                Width,
                    650:                Precision,
                    651:                Done
                    652:        } state=Percent;
                    653: 
                    654:        FormatType result=FormatInvalid;
                    655: 
1.272     moko      656:        const char* pos=fmt;
1.229     misha     657:        while(char c=*(pos++)){
                    658:                switch(state){
                    659:                        case Percent:
                    660:                                if(c=='%'){
                    661:                                        state=Flags;
                    662:                                } else {
                    663:                                        return FormatInvalid; // 1st char must be '%' only
                    664:                                }
                    665:                                break;
                    666:                        case Flags:
                    667:                                if(strchr("-+ #0", c)!=0){
                    668:                                        break;
                    669:                                }
                    670:                                // go to the next step
                    671:                        case Width:
                    672:                                if(c=='.'){
                    673:                                        state=Precision;
                    674:                                        break;
                    675:                                }
                    676:                                // go to the next step
                    677:                        case Precision:
                    678:                                if(c>='0' && c<='9'){
                    679:                                        if(state == Flags) state=Width; // no more flags
                    680:                                        break;
                    681:                                } else if(c=='d' || c=='i'){
                    682:                                        result=FormatInt;
                    683:                                } else if(strchr("feEgG", c)!=0){
                    684:                                        result=FormatDouble;
                    685:                                } else if(strchr("uoxX", c)!=0){
                    686:                                        result=FormatUInt;
                    687:                                } else {
                    688:                                        return FormatInvalid; // invalid char
                    689:                                }
                    690:                                state=Done;
                    691:                                break;
                    692:                        case Done:
                    693:                                return FormatInvalid; // no chars allowed after 'type'
                    694:                }
                    695:        }
                    696:        return result;
                    697: }
                    698: 
                    699: 
1.272     moko      700: const char* format(double value, const char* fmt) {
1.229     misha     701:        char local_buf[MAX_NUMBER];
1.235     misha     702:        int size=-1;
1.229     misha     703: 
                    704:        if(fmt && strlen(fmt)){
                    705:                switch(format_type(fmt)){
                    706:                        case FormatDouble:
                    707:                                size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
                    708:                                break;
                    709:                        case FormatInt:
                    710:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
                    711:                                break;
                    712:                        case FormatUInt:
1.126     paf       713:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.229     misha     714:                                break;
                    715:                        case FormatInvalid:
1.289     moko      716:                                throw Exception(PARSER_RUNTIME, 0, "Incorrect format string '%s' was specified.", fmt);
1.229     misha     717:                }
                    718:        } else
                    719:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
                    720: 
                    721:        if(size < 0 || size >= MAX_NUMBER-1){ // on win32 we manually reduce max size while printing
1.289     moko      722:                throw Exception(PARSER_RUNTIME, 0, "Error occure white executing snprintf with format string '%s'.", fmt);
1.229     misha     723:        }
                    724: 
1.235     misha     725:        return pa_strdup(local_buf, (size_t)size);
1.12      paf       726: }
                    727: 
1.36      paf       728: size_t stdout_write(const void *buf, size_t size) {
1.12      paf       729: #ifdef WIN32
1.187     paf       730:        size_t to_write = size;
1.12      paf       731:        do{
1.154     paf       732:                int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); 
1.12      paf       733:                if(chunk_written<=0)
                    734:                        break;
                    735:                size-=chunk_written;
1.36      paf       736:                buf=((const char*)buf)+chunk_written;
1.126     paf       737:        } while(size>0); 
1.12      paf       738: 
1.187     paf       739:        return to_write-size;
1.12      paf       740: #else
1.126     paf       741:        return fwrite(buf, 1, size, stdout); 
1.12      paf       742: #endif
1.2       paf       743: }
1.14      paf       744: 
1.229     misha     745: enum EscapeState {
                    746:        EscapeRest, 
                    747:        EscapeFirst, 
                    748:        EscapeSecond,
                    749:        EscapeUnicode
                    750: };
                    751: 
1.236     misha     752: // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually)
1.258     misha     753: char* unescape_chars(const char* cp, int len, Charset* charset, bool js){
1.236     misha     754:        char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
1.230     misha     755:        char* dst=s;
1.229     misha     756:        EscapeState escapeState=EscapeRest;
                    757:        uint escapedValue=0;
                    758:        int srcPos=0;
1.230     misha     759:        short int jsCnt=0;
1.236     misha     760:        while(srcPos<len){
1.229     misha     761:                uchar c=(uchar)cp[srcPos]; 
1.258     misha     762:                if(c=='%' || (c=='\\' && js)){
1.229     misha     763:                        escapeState=EscapeFirst;
                    764:                } else {
                    765:                        switch(escapeState) {
                    766:                                case EscapeRest:
1.286     moko      767:                                        if(c=='+' && !js){
1.230     misha     768:                                                *dst++=' ';
1.229     misha     769:                                        } else {
1.230     misha     770:                                                *dst++=c;
1.229     misha     771:                                        }
                    772:                                        break;
                    773:                                case EscapeFirst:
1.232     misha     774:                                        if(charset && c=='u'){
1.229     misha     775:                                                // escaped unicode value: %u0430
                    776:                                                jsCnt=0;
                    777:                                                escapedValue=0;
                    778:                                                escapeState=EscapeUnicode;
                    779:                                        } else {
1.231     misha     780:                                                if(isxdigit(c)){
1.229     misha     781:                                                        escapedValue=hex_value[c] << 4;
                    782:                                                        escapeState=EscapeSecond;
                    783:                                                } else {
1.230     misha     784:                                                        *dst++=c;
1.229     misha     785:                                                        escapeState=EscapeRest;
                    786:                                                }
                    787:                                        }
                    788:                                        break;
                    789:                                case EscapeSecond:
1.231     misha     790:                                        if(isxdigit(c)){
1.229     misha     791:                                                escapedValue+=hex_value[c]; 
1.230     misha     792:                                                *dst++=(char)escapedValue;
1.229     misha     793:                                        }
                    794:                                        escapeState=EscapeRest;
                    795:                                        break;
                    796:                                case EscapeUnicode:
1.231     misha     797:                                        if(isxdigit(c)){
1.229     misha     798:                                                escapedValue=(escapedValue << 4) + hex_value[c];
                    799:                                                if(++jsCnt==4){
1.230     misha     800:                                                        // transcode utf8 char to client charset (we can lost some chars here)
1.232     misha     801:                                                        charset->store_Char((XMLByte*&)dst, (XMLCh)escapedValue, '?');
1.229     misha     802:                                                        escapeState=EscapeRest;
                    803:                                                }
                    804:                                        } else {
                    805:                                                // not full unicode value
                    806:                                                escapeState=EscapeRest;
                    807:                                        }
                    808:                                        break;
                    809:                        }
                    810:                }
                    811: 
                    812:                srcPos++;
                    813:        }
                    814: 
1.230     misha     815:        *dst=0; // zero-termination
1.229     misha     816:        return s;
                    817: }
1.24      paf       818: 
1.268     misha     819: char *search_stop(char*& current, char cstop_at) {
                    820:        // sanity check
                    821:        if(!current)
                    822:                return 0;
                    823: 
                    824:        // skip leading WS
                    825:        while(*current==' ' || *current=='\t')
                    826:                current++;
                    827:        if(!*current)
                    828:                return current=0;
                    829: 
                    830:        char *result=current;
                    831:        if(char *pstop_at=strchr(current, cstop_at)) {
                    832:                *pstop_at=0;
                    833:                current=pstop_at+1;
                    834:        } else
                    835:                current=0;
                    836:        return result;
                    837: }
                    838: 
1.24      paf       839: #ifdef WIN32
1.126     paf       840: void back_slashes_to_slashes(char* s) {
1.24      paf       841:        if(s)
                    842:                for(; *s; s++)
                    843:                        if(*s=='\\')
1.126     paf       844:                                *s='/'; 
1.24      paf       845: }
                    846: #endif
1.41      paf       847: 
1.232     misha     848: size_t strpos(const char *str, const char *substr) {
                    849:        const char *p = strstr(str, substr);
                    850:        return (p==0)?STRING_NOT_FOUND:p-str;
                    851: }
                    852: 
1.226     misha     853: int remove_crlf(char* start, char* end) {
                    854:        char* from=start;
                    855:        char* to=start;
                    856:        bool skip=false;
                    857:        while(from < end){
                    858:                switch(*from){
                    859:                        case '\n':
                    860:                        case '\r':
                    861:                        case '\t':
                    862:                        case ' ':
                    863:                                if(!skip){
                    864:                                        *to=' ';
                    865:                                        to++;
                    866:                                        skip=true;
                    867:                                }
                    868:                                break;
                    869:                        default:
                    870:                                if(from != to)
                    871:                                        *to=*from;
                    872:                                to++;
                    873:                                skip=false;
1.69      parser    874:                }
1.226     misha     875:                from++;
                    876:        }
                    877:        return to-start;
1.91      paf       878: }
                    879: 
1.279     moko      880: const char* hex_digits="0123456789ABCDEF";
                    881: 
1.278     moko      882: const char* hex_string(unsigned char* bytes, size_t size, bool upcase) {
                    883:        char *bytes_hex=new(PointerFreeGC) char [size*2/*byte->hh*/+1/*for zero-teminator*/];
                    884:        unsigned char *src=bytes;
                    885:        unsigned char *end=bytes+size;
                    886:        char *dest=bytes_hex;
                    887: 
1.279     moko      888:        const char *hex=upcase? hex_digits : "0123456789abcdef";
1.278     moko      889: 
                    890:        for(; src<end; src++) {
                    891:                *dest++=hex[*src/0x10];
                    892:                *dest++=hex[*src%0x10];
                    893:        }
                    894:        *dest=0;
                    895: 
                    896:        return bytes_hex;
                    897: }
1.91      paf       898: 
1.178     paf       899: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
                    900: /*
                    901:  *  Authors: Michael Zucchi <notzed@helixcode.com>
                    902:  *           Jeffrey Stedfast <fejj@helixcode.com>
                    903:  *
                    904:  *  Copyright 2000 Helix Code, Inc. (www.helixcode.com)
                    905:  *
                    906:  *  This program is free software; you can redistribute it and/or modify
                    907:  *  it under the terms of the GNU General Public License as published by
                    908:  *  the Free Software Foundation; either version 2 of the License, or
                    909:  *  (at your option) any later version.
                    910:  *
                    911:  *  This program is distributed in the hope that it will be useful,
                    912:  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
                    913:  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    914:  *  GNU General Public License for more details.
                    915:  *
                    916:  *  You should have received a copy of the GNU General Public License
                    917:  *  along with this program; if not, write to the Free Software
                    918:  *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
                    919:  *
                    920:  */
1.271     moko      921: static const char *base64_alphabet =
1.178     paf       922:        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                    923: 
                    924: /**
                    925:  * g_mime_utils_base64_encode_step:
                    926:  * @in: input stream
                    927:  * @inlen: length of the input
                    928:  * @out: output string
                    929:  * @state: holds the number of bits that are stored in @save
                    930:  * @save: leftover bits that have not yet been encoded
                    931:  *
                    932:  * Base64 encodes a chunk of data. Performs an 'encode step', only
                    933:  * encodes blocks of 3 characters to the output at a time, saves
                    934:  * left-over state in state and save (initialise to 0 on first
                    935:  * invocation).
                    936:  *
                    937:  * Returns the number of bytes encoded.
                    938:  **/
1.252     misha     939: 
                    940: #define BASE64_GROUPS_IN_LINE 19
                    941: 
1.178     paf       942: static size_t
                    943: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                    944: {
1.186     paf       945:        register const unsigned char *inptr;
1.178     paf       946:        register unsigned char *outptr;
                    947:        
                    948:        if (inlen <= 0)
                    949:                return 0;
                    950:        
                    951:        inptr = in;
                    952:        outptr = out;
                    953:        
                    954:        if (inlen + ((unsigned char *)save)[0] > 2) {
                    955:                const unsigned char *inend = in + inlen - 2;
                    956:                register int c1 = 0, c2 = 0, c3 = 0;
                    957:                register int already;
                    958:                
                    959:                already = *state;
                    960:                
                    961:                switch (((char *)save)[0]) {
                    962:                case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
                    963:                case 2: c1 = ((unsigned char *)save)[1];
                    964:                        c2 = ((unsigned char *)save)[2]; goto skip2;
                    965:                }
                    966:                
                    967:                /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
                    968:                while (inptr < inend) {
                    969:                        c1 = *inptr++;
                    970:                skip1:
                    971:                        c2 = *inptr++;
                    972:                skip2:
                    973:                        c3 = *inptr++;
                    974:                        *outptr++ = base64_alphabet [c1 >> 2];
                    975:                        *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
                    976:                        *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
                    977:                        *outptr++ = base64_alphabet [c3 & 0x3f];
                    978:                        /* this is a bit ugly ... */
1.252     misha     979:                        if ((++already) >= BASE64_GROUPS_IN_LINE) {
1.178     paf       980:                                *outptr++ = '\n';
                    981:                                already = 0;
                    982:                        }
                    983:                }
                    984:                
                    985:                ((unsigned char *)save)[0] = 0;
                    986:                inlen = 2 - (inptr - inend);
                    987:                *state = already;
                    988:        }
                    989:        
                    990:        //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
                    991:        
                    992:        if (inlen > 0) {
                    993:                register char *saveout;
                    994:                
                    995:                /* points to the slot for the next char to save */
                    996:                saveout = & (((char *)save)[1]) + ((char *)save)[0];
                    997:                
                    998:                /* inlen can only be 0 1 or 2 */
                    999:                switch (inlen) {
                   1000:                case 2: *saveout++ = *inptr++;
                   1001:                case 1: *saveout++ = *inptr++;
                   1002:                }
1.216     paf      1003:                *(char *)save = *(char *)save+(char)inlen;
1.178     paf      1004:        }
                   1005:        
                   1006:        /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
                   1007:                  (int)((char *)save)[0],
                   1008:                  (int)((char *)save)[1],
                   1009:                  (int)((char *)save)[2]));*/
                   1010:        
                   1011:        return (outptr - out);
                   1012: }
                   1013: 
                   1014: /**
                   1015:  * g_mime_utils_base64_encode_close:
                   1016:  * @in: input stream
                   1017:  * @inlen: length of the input
                   1018:  * @out: output string
                   1019:  * @state: holds the number of bits that are stored in @save
                   1020:  * @save: leftover bits that have not yet been encoded
                   1021:  *
                   1022:  * Base64 encodes the input stream to the output stream. Call this
                   1023:  * when finished encoding data with g_mime_utils_base64_encode_step to
                   1024:  * flush off the last little bit.
                   1025:  *
                   1026:  * Returns the number of bytes encoded.
                   1027:  **/
                   1028: static size_t
                   1029: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
                   1030: {
                   1031:        unsigned char *outptr = out;
                   1032:        int c1, c2;
                   1033:        
                   1034:        if (inlen > 0)
                   1035:                outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
                   1036:        
                   1037:        c1 = ((unsigned char *)save)[1];
                   1038:        c2 = ((unsigned char *)save)[2];
                   1039:        
                   1040:        switch (((unsigned char *)save)[0]) {
                   1041:        case 2:
                   1042:                outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
                   1043:                goto skip;
                   1044:        case 1:
                   1045:                outptr[2] = '=';
                   1046:        skip:
                   1047:                outptr[0] = base64_alphabet [c1 >> 2];
                   1048:                outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
                   1049:                outptr[3] = '=';
                   1050:                outptr += 4;
                   1051:                break;
                   1052:        }
                   1053:        
                   1054:        *outptr++ = 0;
                   1055:        
                   1056:        *save = 0;
                   1057:        *state = 0;
                   1058:        
                   1059:        return (outptr - out);
                   1060: }
                   1061: 
1.210     paf      1062: static unsigned char gmime_base64_rank[256] = {
1.266     misha    1063:        255,255,255,255,255,255,255,255,255,254,254,255,255,254,255,255,
1.210     paf      1064:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1.266     misha    1065:        254,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
1.210     paf      1066:         52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255,  0,255,255,
                   1067:        255,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
                   1068:         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
                   1069:        255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
                   1070:         41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,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:        255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
                   1074:        255,255,255,255,255,255,255,255,255,255,255,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: };
                   1080: 
                   1081: /**
                   1082:  * g_mime_utils_base64_decode_step:
                   1083:  * @in: input stream
                   1084:  * @inlen: max length of data to decode
                   1085:  * @out: output stream
                   1086:  * @state: holds the number of bits that are stored in @save
                   1087:  * @save: leftover bits that have not yet been decoded
1.266     misha    1088:  * @strict: only base64 and whitespace chars are allowed
1.210     paf      1089:  *
                   1090:  * Decodes a chunk of base64 encoded data.
                   1091:  *
                   1092:  * Returns the number of bytes decoded (which have been dumped in @out).
                   1093:  **/
                   1094: size_t
1.266     misha    1095: 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      1096: {
1.213     paf      1097:        const unsigned char *inptr;
                   1098:        unsigned char *outptr;
1.210     paf      1099:        const unsigned char *inend;
1.213     paf      1100:        int saved;
1.210     paf      1101:        unsigned char c;
                   1102:        int i;
                   1103:        
                   1104:        inend = in + inlen;
                   1105:        outptr = out;
                   1106:        
                   1107:        /* convert 4 base64 bytes to 3 normal bytes */
                   1108:        saved = *save;
                   1109:        i = *state;
                   1110:        inptr = in;
                   1111:        while (inptr < inend) {
                   1112:                c = gmime_base64_rank[*inptr++];
1.266     misha    1113:                switch(c) {
                   1114:                        case 0xff: // non-base64 and non-whitespace chars. not allowed in strict mode
                   1115:                                if(strict)
                   1116:                                        throw Exception(BASE64_FORMAT, 0, "Invalid base64 char on position %d is detected", inptr-in-1);
                   1117:                        case 0xfe: // whitespace chars 0x09, 0x0A, 0x0D, 0x20 are allowed in any mode
                   1118:                                break;
                   1119:                        default:
                   1120:                                saved = (saved << 6) | c;
                   1121:                                i++;
                   1122:                                if (i == 4) {
                   1123:                                        *outptr++ = (unsigned char)(saved >> 16);
                   1124:                                        *outptr++ = (unsigned char)(saved >> 8);
                   1125:                                        *outptr++ = (unsigned char)(saved);
                   1126:                                        i = 0;
                   1127:                                }
1.210     paf      1128:                }
                   1129:        }
                   1130:        
                   1131:        *save = saved;
                   1132:        *state = i;
                   1133:        
                   1134:        /* quick scan back for '=' on the end somewhere */
                   1135:        /* fortunately we can drop 1 output char for each trailing = (upto 2) */
                   1136:        i = 2;
                   1137:        while (inptr > in && i) {
                   1138:                inptr--;
1.266     misha    1139:                if (gmime_base64_rank[*inptr] <= 0xfe) {
1.210     paf      1140:                        if (*inptr == '=' && outptr > out)
                   1141:                                outptr--;
                   1142:                        i--;
                   1143:                }
                   1144:        }
                   1145:        
                   1146:        /* if i != 0 then there is a truncation error! */
                   1147:        return (outptr - out);
                   1148: }
                   1149: 
                   1150: 
1.239     misha    1151: char* pa_base64_encode(const char *in, size_t in_size){
1.252     misha    1152:        size_t new_size = ((in_size / 3 + 1) * 4);
                   1153:        new_size += new_size / (BASE64_GROUPS_IN_LINE * 4)/*new lines*/ + 1/*zero terminator*/;
                   1154:        char* result = new(PointerFreeGC) char[new_size];
1.178     paf      1155:        int state=0;
                   1156:        int save=0;
1.183     paf      1157: #ifndef NDEBUG
                   1158:        size_t filled=
                   1159: #endif
1.251     misha    1160:                g_mime_utils_base64_encode_close ((const unsigned char*)in, in_size, (unsigned char*)result, &state, &save);
                   1161: 
                   1162:        //throw Exception(PARSER_RUNTIME, 0, "%d %d %d", in_size, new_size, filled);
                   1163:        assert(filled <= new_size);
1.178     paf      1164: 
                   1165:        return result;
1.98      paf      1166: }
1.210     paf      1167: 
1.278     moko     1168: struct File_base64_action_info {
                   1169:        unsigned char** base64;
                   1170: }; 
1.222     misha    1171: 
1.300   ! moko     1172: static void file_base64_file_action(struct stat& finfo, int f, const String& file_spec, void *context) {
1.222     misha    1173: 
                   1174:        if(finfo.st_size) { 
                   1175:                File_base64_action_info& info=*static_cast<File_base64_action_info *>(context);
1.300   ! moko     1176:                *info.base64=new(PointerFreeGC) unsigned char[check_file_size(finfo.st_size, file_spec) * 2 + 6]; 
1.222     misha    1177:                unsigned char* base64 = *info.base64;
                   1178:                int state=0;
                   1179:                int save=0;
                   1180:                int nCount;
                   1181:                do {
                   1182:                        unsigned char buffer[FILE_BUFFER_SIZE];
                   1183:                        nCount = file_block_read(f, buffer, sizeof(buffer));
                   1184:                        if( nCount ){
                   1185:                                size_t filled=g_mime_utils_base64_encode_step ((const unsigned char*)buffer, nCount, base64, &state, &save);
                   1186:                                base64+=filled;
                   1187:                        }
                   1188:                } while(nCount > 0);
                   1189:                g_mime_utils_base64_encode_close (0, 0, base64, &state, &save);
                   1190:        }
                   1191: }
                   1192: 
1.278     moko     1193: char* pa_base64_encode(const String& file_spec){
                   1194:        unsigned char* base64=0;
                   1195:        File_base64_action_info info={&base64}; 
                   1196: 
1.289     moko     1197:        file_read_action_under_lock(file_spec, "pa_base64_encode", file_base64_file_action, &info);
1.278     moko     1198: 
                   1199:        return (char*)base64; 
                   1200: }
                   1201: 
1.265     misha    1202: void pa_base64_decode(const char *in, size_t in_size, char*& result, size_t& result_size, bool strict) {
1.264     misha    1203:        // every 4 base64 bytes are converted into 3 normal bytes
                   1204:        // not full set (tail) of 4-bytes set is ignored
                   1205:        size_t new_size=in_size/4*3;
                   1206:        result=new(PointerFreeGC) char[new_size+1/*terminator*/];
                   1207: 
1.210     paf      1208:        int state=0;
                   1209:        int save=0;
1.289     moko     1210:        result_size=g_mime_utils_base64_decode_step ((const unsigned char*)in, in_size, (unsigned char*)result, &state, &save, strict);
1.264     misha    1211:        assert(result_size <= new_size);
1.211     paf      1212:        result[result_size]=0; // for text files
1.265     misha    1213: 
                   1214:        if(strict && state!=0)
1.266     misha    1215:                throw Exception(BASE64_FORMAT, 0, "Unexpected end of chars");
1.210     paf      1216: }
1.218     misha    1217: 
                   1218: 
1.221     misha    1219: int file_block_read(const int f, unsigned char* buffer, const size_t size){
                   1220:        int nCount = read(f, buffer, size);
                   1221:        if (nCount < 0)
1.289     moko     1222:                throw Exception("file.read", 0, "read failed: %s (%d)", strerror(errno), errno); 
1.221     misha    1223:        return nCount;
                   1224: }
                   1225: 
1.278     moko     1226: static unsigned long crc32Table[256];
                   1227: static void InitCrc32Table()
                   1228: {
                   1229:        if(crc32Table[1] == 0){
                   1230:                // This is the official polynomial used by CRC32 in PKZip.
                   1231:                // Often times the polynomial shown reversed as 0x04C11DB7.
                   1232:                static const unsigned long dwPolynomial = 0xEDB88320;
                   1233: 
                   1234:                for(int i = 0; i < 256; i++)
                   1235:                {
                   1236:                        unsigned long dwCrc = i;
                   1237:                        for(int j = 8; j > 0; j--)
                   1238:                        {
                   1239:                                if(dwCrc & 1)
                   1240:                                        dwCrc = (dwCrc >> 1) ^ dwPolynomial;
                   1241:                                else
                   1242:                                        dwCrc >>= 1;
                   1243:                        }
                   1244:                        crc32Table[i] = dwCrc;
                   1245:                }
                   1246:        }
                   1247: }
                   1248: 
                   1249: inline void CalcCrc32(const unsigned char byte, unsigned long &crc32)
                   1250: {
                   1251:        crc32 = ((crc32) >> 8) ^ crc32Table[(byte) ^ ((crc32) & 0x000000FF)];
                   1252: }
                   1253: 
                   1254: 
1.297     moko     1255: unsigned long pa_crc32(const char *in, size_t in_size){
1.218     misha    1256:        unsigned long crc32=0xFFFFFFFF;
1.220     misha    1257: 
1.240     misha    1258:        InitCrc32Table();
1.239     misha    1259:        for(size_t i = 0; i<in_size; i++)
                   1260:                CalcCrc32(in[i], crc32);
1.220     misha    1261: 
1.218     misha    1262:        return ~crc32; 
                   1263: }
                   1264: 
1.289     moko     1265: static void file_crc32_file_action(struct stat& finfo, int f, const String&, void *context) {
1.218     misha    1266:        unsigned long& crc32=*static_cast<unsigned long *>(context);
                   1267:        if(finfo.st_size) {
                   1268:                InitCrc32Table();
1.220     misha    1269:                int nCount=0;
1.218     misha    1270:                do {
1.221     misha    1271:                        unsigned char buffer[FILE_BUFFER_SIZE];
                   1272:                        nCount = file_block_read(f, buffer, sizeof(buffer));
1.220     misha    1273:                        for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
                   1274:                } while(nCount > 0);
1.218     misha    1275:        }
                   1276: }
                   1277: 
1.297     moko     1278: unsigned long pa_crc32(const String& file_spec){
1.278     moko     1279:        unsigned long crc32=0xFFFFFFFF;
                   1280:        file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
                   1281:        return ~crc32; 
                   1282: }
                   1283: 
                   1284: // content-type: xxx; charset=WE-NEED-THIS
                   1285: // content-type: xxx; charset="WE-NEED-THIS"
                   1286: // content-type: xxx; charset="WE-NEED-THIS";
                   1287: Charset* detect_charset(const char* content_type){
                   1288:        if(content_type){
1.291     moko     1289:                char* CONTENT_TYPE=str_upper(content_type);
1.278     moko     1290: 
                   1291:                if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
                   1292:                        begin+=8; // skip "CHARSET="
                   1293:                        char* end=0;
                   1294:                        if(*begin && (*begin=='"' || *begin =='\'')){
                   1295:                                char quote=*begin;
                   1296:                                begin++;
                   1297:                                end=(char*)strchr(begin, quote);
                   1298:                        }
                   1299:                        if(!end)
                   1300:                                end=(char*)strchr(begin, ';');
                   1301: 
                   1302:                        if(end)
                   1303:                                *end=0; // terminator
                   1304: 
1.295     moko     1305:                        return *begin ? &pa_charsets.get_direct(begin) : 0;
1.278     moko     1306:                }
                   1307:        }
                   1308:        return 0;
                   1309: }
                   1310: 
                   1311: 
1.283     moko     1312: static bool is_latin(const char *in){
                   1313:        for(; *in; in++){
                   1314:                if ((unsigned char)(*in) > 0x7F)
                   1315:                        return false;
                   1316:        }
                   1317:        return true;
                   1318: }
                   1319: 
                   1320: #define MAX_IDNA_LENGTH 256
                   1321: 
                   1322: const char *pa_idna_encode(const char *in, Charset &source_charset){
                   1323:        if(!in || is_latin(in))
                   1324:                return in;
                   1325: 
                   1326:        uint32_t utf32[MAX_IDNA_LENGTH];
                   1327:        uint32_t *utf32_end=utf32;
                   1328: 
                   1329:        String::C sIn(in,strlen(in));
                   1330: 
                   1331:        if(!source_charset.isUTF8())
1.295     moko     1332:                sIn=Charset::transcode(sIn, source_charset, pa_UTF8_charset);
1.283     moko     1333: 
                   1334:        int status=pa_convertUTF8toUTF32((const UTF8**)&sIn.str, (const UTF8*)(sIn.str+sIn.length), &utf32_end, utf32+MAX_IDNA_LENGTH-1, strictConversion);
                   1335:        if(status != conversionOK)
                   1336:                throw Exception("idna encode", new String(in), "utf conversion failed (%d)", status);
                   1337: 
                   1338:        *utf32_end=0;
                   1339: 
                   1340:        char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
                   1341:        status=pa_idna_to_ascii_4z(utf32, result, MAX_IDNA_LENGTH, 0);
                   1342:        if(status != IDNA_SUCCESS)
                   1343:                throw Exception("idna encode", new String(in), "encode failed: %s", pa_idna_strerror(status));
                   1344: 
                   1345:        return result;
                   1346: }
                   1347: 
                   1348: const char *pa_idna_decode(const char *in, Charset &asked_charset){
                   1349:        if(!in || !(*in))
                   1350:                return in;
                   1351: 
                   1352:        uint32_t utf32[MAX_IDNA_LENGTH];
                   1353:        const uint32_t *utf32_start=utf32;
                   1354:        uint32_t *utf32_end;
                   1355: 
                   1356:        int status=pa_idna_to_unicode_4z(in, utf32, MAX_IDNA_LENGTH, 0);
                   1357:        if(status != IDNA_SUCCESS)
                   1358:                throw Exception("idna decode", new String(in), "decode failed: %s", pa_idna_strerror(status));
                   1359: 
                   1360:        for(utf32_end=utf32; *utf32_end; utf32_end++);
                   1361: 
                   1362:        char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
                   1363:        char *result_end = result;
                   1364: 
                   1365:        status=pa_convertUTF32toUTF8(&utf32_start, utf32_end, (UTF8**)&result_end, (UTF8*)(result+MAX_IDNA_LENGTH-1), strictConversion);
                   1366: 
                   1367:        if(status != conversionOK)
                   1368:                throw Exception("idna decode", new String(in), "utf conversion failed (%d)", status);
                   1369: 
                   1370:        *result_end='\0';
                   1371: 
                   1372:        if(!asked_charset.isUTF8())
1.295     moko     1373:                result = (char *)Charset::transcode(result, pa_UTF8_charset, asked_charset).cstr();
1.283     moko     1374: 
                   1375:        return result;
                   1376: }
1.292     moko     1377: /// must be last in this file
                   1378: #undef vsnprintf
                   1379: int pa_vsnprintf(char* b, size_t s, const char* f, va_list l) {
                   1380:        if(!s)
                   1381:                return 0;
                   1382: 
                   1383:        int r;
                   1384:        // note: on win32 & maybe somewhere else
                   1385:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                   1386:        // http://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
                   1387:        --s;
                   1388: 
                   1389:        // clients do not check for negative 's', feature: ignore such prints
                   1390:        if((ssize_t)s<0)
                   1391:                return 0;
                   1392: 
                   1393: #ifdef _MSC_VER
                   1394:        // win32: if the number of bytes to write exceeds buffer, then count bytes are written and -1 is returned
                   1395:        r=_vsnprintf(b, s, f, l); 
                   1396:        if(r<0) 
                   1397:                r=s;
                   1398: #else
                   1399:        r=vsnprintf(b, s, f, l); 
                   1400:        /*
                   1401:        solaris: man vsnprintf
                   1402: 
                   1403:        The snprintf() function returns  the  number  of  characters
                   1404:        formatted, that is, the number of characters that would have
                   1405:        been written to the buffer if it were large enough.  If  the
                   1406:        value  of  n  is  0  on a call to snprintf(), an unspecified
                   1407:        value less than 1 is returned.
                   1408:        */
                   1409: 
                   1410:        if(r<0)
                   1411:                r=0;
                   1412:        else if((size_t)r>s)
                   1413:                r=s;
                   1414: #endif
                   1415:        b[r]=0;
                   1416:        return r;
                   1417: }
                   1418: 
                   1419: int pa_snprintf(char* b, size_t s, const char* f, ...) {
                   1420:        va_list l;
                   1421:        va_start(l, f); 
                   1422:        int r=pa_vsnprintf(b, s, f, l); 
                   1423:        va_end(l); 
                   1424:        return r;
                   1425: }
                   1426: 

E-mail: