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

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

E-mail: