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

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.306     moko        6: */
1.210     paf         7: 
1.1       paf         8: #include "pa_common.h"
1.4       paf         9: #include "pa_exception.h"
1.154     paf        10: #include "pa_hash.h"
1.14      paf        11: #include "pa_globals.h"
1.154     paf        12: #include "pa_charsets.h"
1.214     paf        13: #include "pa_http.h"
1.223     misha      14: #include "pa_request_charsets.h"
1.237     misha      15: #include "pcre.h"
1.241     misha      16: #include "pa_request.h"
1.98      paf        17: 
1.283     moko       18: #include "pa_idna.h"
                     19: #include "pa_convert_utf.h"
                     20: 
1.273     moko       21: #ifdef _MSC_VER
1.276     moko       22: #include <windows.h>
1.273     moko       23: #include <direct.h>
                     24: #endif
                     25: 
1.277     moko       26: #ifdef _MSC_VER
                     27: #define pa_mkdir(path, mode) _mkdir(path)
                     28: #else
                     29: #define pa_mkdir(path, mode) mkdir(path, mode)
                     30: #endif
                     31: 
1.310   ! moko       32: volatile const char * IDENT_PA_COMMON_C="$Id: pa_common.C,v 1.309 2019/11/22 23:11:25 moko Exp $" IDENT_PA_COMMON_H IDENT_PA_HASH_H IDENT_PA_ARRAY_H IDENT_PA_STACK_H; 
1.267     moko       33: 
1.93      paf        34: // some maybe-undefined constants
                     35: 
1.82      paf        36: #ifndef _O_TEXT
                     37: #      define _O_TEXT 0
                     38: #endif
                     39: #ifndef _O_BINARY
                     40: #      define _O_BINARY 0
1.47      paf        41: #endif
1.80      paf        42: 
1.138     paf        43: #ifdef HAVE_FTRUNCATE
                     44: #      define PA_O_TRUNC 0
                     45: #else
                     46: #      ifdef _O_TRUNC
                     47: #              define PA_O_TRUNC _O_TRUNC
                     48: #      else
                     49: #              error you must have either ftruncate function or _O_TRUNC bit declared
                     50: #      endif
1.154     paf        51: #endif
1.176     paf        52: 
1.154     paf        53: // defines for globals
                     54: 
                     55: #define FILE_STATUS_NAME  "status"
                     56: 
                     57: // globals
                     58: 
                     59: const String file_status_name(FILE_STATUS_NAME);
                     60: 
1.305     moko       61: String sql_bind_name(SQL_BIND_NAME);
                     62: String sql_limit_name(PA_SQL_LIMIT_NAME);
                     63: String sql_offset_name(PA_SQL_OFFSET_NAME);
                     64: String sql_default_name(SQL_DEFAULT_NAME);
                     65: String sql_distinct_name(SQL_DISTINCT_NAME);
                     66: String sql_value_type_name(SQL_VALUE_TYPE_NAME);
                     67: 
1.301     moko       68: // forwards
                     69: 
                     70: const UTF16* pa_utf16_encode(const char* in, Charset& source_charset);
                     71: 
1.154     paf        72: // functions
1.127     paf        73: 
1.301     moko       74: #ifdef _MSC_VER
                     75: 
                     76: int pa_stat(const char *pathname, struct stat *buffer){
                     77:        const UTF16* utf16name=pa_utf16_encode(pathname, pa_thread_request().charsets.source());
                     78:        return _wstat64((const wchar_t *)utf16name, buffer);
                     79: }
                     80: 
                     81: int pa_open(const char *pathname, int flags, int mode){
                     82:        const UTF16* utf16name=pa_utf16_encode(pathname, pa_thread_request().charsets.source());
                     83:        return _wopen((const wchar_t *)utf16name, flags, mode);
                     84: }
                     85: 
                     86: FILE *pa_fopen(const char *pathname, const char *mode){
                     87:        const UTF16* utf16name=pa_utf16_encode(pathname, pa_thread_request().charsets.source());
                     88:        const UTF16* utf16mode=pa_utf16_encode(mode, pa_thread_request().charsets.source());
                     89:        return _wfopen((const wchar_t *)utf16name, (const wchar_t *)utf16mode);
                     90: }
                     91: 
                     92: #endif
                     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.310   ! moko      113:        char* buf; size_t offset; size_t limit;
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.310   ! moko      118:        File_read_action_info& info = *static_cast<File_read_action_info *>(context); 
        !           119:        size_t to_read_size = info.limit;
1.188     paf       120:        if(!to_read_size)
1.310   ! 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.310   ! 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);
1.271     moko      127:                if(result<0)
                    128:                        throw Exception("file.read", &file_spec, "read failed: %s (%d)", strerror(errno), errno);
1.310   ! moko      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.310   ! moko      132:                *info.data = (char *)pa_malloc_atomic(1);
        !           133:                *(char*)(*info.data) = 0;
        !           134:                *info.data_size = 0;
1.123     paf       135:                return;
                    136:        }
1.126     paf       137: }
1.241     misha     138: 
1.310   ! moko      139: File_read_result file_read_binary(const String& file_spec, bool fail_on_read_problem, char* buf, size_t offset, size_t limit) {
        !           140:        File_read_result result = {false, 0, 0, 0};
        !           141:        File_read_action_info info = {&result.str, &result.length, buf, offset, limit};
1.309     moko      142: 
1.310   ! moko      143:        result.success = file_read_action_under_lock(file_spec, "read", file_read_action, &info, 0, fail_on_read_problem);
1.309     moko      144:        return result;
                    145: }
                    146: 
1.154     paf       147: File_read_result file_read(Request_charsets& charsets, const String& file_spec, 
1.310   ! moko      148:                        bool as_text, HashStringValue *options,
1.229     misha     149:                        bool fail_on_read_problem,
1.310   ! moko      150:                        size_t offset = 0, size_t limit = 0, bool transcode_text_result = true) {
        !           151:        File_read_result result = {false, 0, 0, 0};
        !           152:        if(options){
        !           153:                int valid_options = pa_get_valid_file_options_count(*options);
        !           154:                if(valid_options != options->count())
1.262     misha     155:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.241     misha     156:        }
1.203     paf       157: 
1.310   ! moko      158:        File_read_action_info info = {&result.str, &result.length, 0, offset, limit}; 
1.161     paf       159: 
1.310   ! moko      160:        result.success = file_read_action_under_lock(file_spec, "read", file_read_action, &info, as_text, fail_on_read_problem); 
1.223     misha     161: 
1.241     misha     162:        if(as_text){
                    163:                if(result.success){
1.310   ! moko      164:                        Charset* asked_charset = 0;
        !           165:                        if(options)
        !           166:                                if(Value* vcharset_name = options->get(PA_CHARSET_NAME))
        !           167:                                        asked_charset = &pa_charsets.get(vcharset_name->as_string());
1.263     misha     168: 
1.310   ! moko      169:                        asked_charset = pa_charsets.checkBOM(result.str, result.length, asked_charset);
1.287     moko      170: 
1.263     misha     171:                        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
1.310   ! moko      172:                                String::C body = String::C(result.str, result.length);
1.263     misha     173:                                body=Charset::transcode(body, *asked_charset, charsets.source());
1.236     misha     174: 
1.310   ! moko      175:                                result.str = const_cast<char*>(body.str); // hacking a little
        !           176:                                result.length = body.length;
1.131     paf       177:                        }
                    178:                }
1.241     misha     179:                if(result.length)
                    180:                        fix_line_breaks(result.str, result.length);
1.123     paf       181:        }
1.241     misha     182: 
                    183:        return result;
                    184: }
                    185: 
                    186: File_read_result file_load(Request& r, const String& file_spec, 
1.310   ! moko      187:                        bool as_text, HashStringValue *options,
1.241     misha     188:                        bool fail_on_read_problem,
1.310   ! moko      189:                        bool transcode_text_result) {
        !           190: 
        !           191:        size_t offset = 0;
        !           192:        size_t limit = 0;
        !           193: 
        !           194:        if(options){
        !           195:                if(Value *voffset = (Value *)options->get(sql_offset_name))
        !           196:                        offset = r.process(*voffset).as_int();
        !           197:                if(Value *vlimit = (Value *)options->get(sql_limit_name))
        !           198:                        limit = r.process(*vlimit).as_int();
        !           199:                // no check on options count here
        !           200:        }
1.241     misha     201: 
                    202:        if(file_spec.starts_with("http://")) {
1.310   ! moko      203:                if(offset || limit)
1.289     moko      204:                        throw Exception(PARSER_RUNTIME, 0, "offset and load options are not supported for HTTP:// file load");
1.241     misha     205: 
                    206:                // fail on read problem
1.310   ! moko      207:                File_read_http_result http = pa_internal_file_read_http(r, file_spec, as_text, options, transcode_text_result);
        !           208: 
        !           209:                File_read_result result = {true, http.str, http.length, http.headers};
        !           210:                return result;
1.241     misha     211:        } else
1.310   ! moko      212:                return file_read(r.charsets, file_spec, as_text, options, fail_on_read_problem, offset, limit, transcode_text_result);
        !           213: }
1.126     paf       214: 
1.310   ! moko      215: char* file_read_text(Request_charsets& charsets, const String& file_spec, bool fail_on_read_problem) {
        !           216:        File_read_result file = file_read(charsets, file_spec, true, 0, fail_on_read_problem);
        !           217:        return file.success ? file.str : 0;
1.123     paf       218: }
                    219: 
1.310   ! moko      220: char* file_load_text(Request& r, const String& file_spec, bool fail_on_read_problem, HashStringValue* options, bool transcode_result) {
        !           221:        File_read_result file = file_load(r, file_spec, true, options, fail_on_read_problem, transcode_result);
        !           222:        return file.success ? file.str : 0;
        !           223: }
1.257     pretende  224: 
1.154     paf       225: #ifdef PA_SAFE_MODE 
1.259     misha     226: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) {
1.154     paf       227:        if(finfo.st_uid/*foreign?*/!=geteuid() 
                    228:                && finfo.st_gid/*foreign?*/!=getegid()) 
1.289     moko      229:                throw Exception(PARSER_RUNTIME,
                    230:                        &file_spec,
                    231:                        "parser is in safe mode: reading files of foreign group and user disabled "
                    232:                        "[recompile parser with --disable-safe-mode configure option], "
                    233:                        "actual filename '%s', fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",
                    234:                        fname, finfo.st_uid, geteuid(), finfo.st_gid, getegid()
                    235:                );
1.259     misha     236: }
                    237: #else
                    238: void check_safe_mode(struct stat, const String&, const char*) {
                    239: }
1.257     pretende  240: #endif
1.259     misha     241: 
1.257     pretende  242: 
1.149     paf       243: 
1.154     paf       244: bool file_read_action_under_lock(const String& file_spec, 
1.126     paf       245:                                const char* action_name, File_read_action action, void *context, 
                    246:                                bool as_text, 
1.123     paf       247:                                bool fail_on_read_problem) {
1.247     misha     248:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); 
1.33      paf       249:        int f;
                    250: 
                    251:        // first open, next stat:
1.45      paf       252:        // directory update of NTFS hard links performed on open.
1.33      paf       253:        // ex: 
                    254:        //   a.html:^test[] and b.html hardlink to a.html
                    255:        //   user inserts ! before ^test in a.html
1.126     paf       256:        //   directory entry of b.html in NTFS not updated at once, 
1.35      paf       257:        //   they delay update till open, so we would receive "!^test[" string
                    258:        //   if would do stat, next open.
1.123     paf       259:        // later: it seems, even this does not help sometimes
1.301     moko      260:        if((f=pa_open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123     paf       261:                try {
1.162     paf       262:                        if(pa_lock_shared_blocking(f)!=0)
1.289     moko      263:                                throw Exception("file.lock", &file_spec, "shared lock failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname);
1.123     paf       264: 
1.124     paf       265:                        struct stat finfo;
1.298     moko      266:                        if(pa_fstat(f, &finfo)!=0)
1.124     paf       267:                                throw Exception("file.missing", // hardly possible: we just opened it OK
1.289     moko      268:                                        &file_spec, "stat failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname);
1.124     paf       269: 
1.149     paf       270:                        check_safe_mode(finfo, file_spec, fname);
1.32      paf       271: 
1.289     moko      272:                        action(finfo, f, file_spec, context); 
1.123     paf       273:                } catch(...) {
1.162     paf       274:                        pa_unlock(f);close(f); 
1.123     paf       275:                        if(fail_on_read_problem)
1.154     paf       276:                                rethrow;
1.289     moko      277:                        return false;
1.123     paf       278:                } 
1.87      paf       279: 
1.162     paf       280:                pa_unlock(f);close(f); 
1.72      parser    281:                return true;
1.229     misha     282:        } else {
1.118     paf       283:                if(fail_on_read_problem)
1.289     moko      284:                        throw Exception(errno==EACCES ? "file.access" : (errno==ENOENT || errno==ENOTDIR || errno==ENODEV) ? "file.missing" : 0,
                    285:                                &file_spec, "%s failed: %s (%d), actual filename '%s'", action_name, strerror(errno), errno, fname);
1.118     paf       286:                return false;
                    287:        }
1.8       paf       288: }
                    289: 
1.202     paf       290: void create_dir_for_file(const String& file_spec) {
1.63      parser    291:        size_t pos_after=1;
1.154     paf       292:        size_t pos_before;
                    293:        while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
1.277     moko      294:                pa_mkdir(file_spec.mid(0, pos_before).taint_cstr(String::L_FILE_SPEC), 0775); 
1.63      parser    295:                pos_after=pos_before+1;
                    296:        }
                    297: }
                    298: 
1.98      paf       299: bool file_write_action_under_lock(
1.28      paf       300:                                const String& file_spec, 
1.225     misha     301:                                const char* action_name,
                    302:                                File_write_action action,
                    303:                                void *context, 
1.126     paf       304:                                bool as_text, 
                    305:                                bool do_append, 
                    306:                                bool do_block, 
1.110     paf       307:                                bool fail_on_lock_problem) {
1.247     misha     308:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); 
1.28      paf       309:        int f;
1.80      paf       310:        if(access(fname, W_OK)!=0) // no
1.126     paf       311:                create_dir_for_file(file_spec); 
1.50      paf       312: 
1.301     moko      313:        if((f=pa_open(fname, 
1.80      paf       314:                O_CREAT|O_RDWR
                    315:                |(as_text?_O_TEXT:_O_BINARY)
1.138     paf       316:                |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162     paf       317:                if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.289     moko      318:                        Exception e("file.lock", &file_spec, "shared lock failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname);
1.126     paf       319:                        close(f); 
1.110     paf       320:                        if(fail_on_lock_problem)
                    321:                                throw e;
1.98      paf       322:                        return false;
                    323:                }
1.96      paf       324: 
1.158     paf       325:                try {
1.254     misha     326: #if (defined(HAVE_FCHMOD) && defined(PA_SAFE_MODE))
                    327:                        struct stat finfo;
1.298     moko      328:                        if(pa_fstat(f, &finfo)==0 && finfo.st_mode & 0111)
1.254     misha     329:                                fchmod(f, finfo.st_mode & 0666/*clear executable bits*/); // backward: ignore errors if any
                    330: #endif
                    331:                        action(f, context);
1.158     paf       332:                } catch(...) {
1.138     paf       333: #ifdef HAVE_FTRUNCATE
1.104     paf       334:                        if(!do_append)
1.125     paf       335:                                ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138     paf       336: #endif
1.162     paf       337:                        pa_unlock(f);close(f); 
1.154     paf       338:                        rethrow;
1.158     paf       339:                }
1.80      paf       340:                
1.138     paf       341: #ifdef HAVE_FTRUNCATE
1.104     paf       342:                if(!do_append)
1.125     paf       343:                        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       344: #endif
1.162     paf       345:                pa_unlock(f);close(f); 
1.98      paf       346:                return true;
1.80      paf       347:        } else
1.289     moko      348:                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       349:        // here should be nothing, see rethrow above
                    350: }
                    351: 
                    352: #ifndef DOXYGEN
                    353: struct File_write_action_info {
1.250     misha     354:        const char* str;
                    355:        size_t length;
1.126     paf       356: }; 
1.96      paf       357: #endif
1.271     moko      358: 
1.96      paf       359: static void file_write_action(int f, void *context) {
1.126     paf       360:        File_write_action_info& info=*static_cast<File_write_action_info *>(context); 
1.154     paf       361:        if(info.length) {
1.271     moko      362:                ssize_t written=write(f, info.str, info.length); 
1.116     paf       363:                if(written<0)
1.271     moko      364:                        throw Exception("file.write", 0, "write failed: %s (%d)",  strerror(errno), errno); 
1.275     moko      365:                if((size_t)written!=info.length)
1.271     moko      366:                        throw Exception("file.write", 0, "write failed: %u of %u bytes written", written, info.length);
1.113     paf       367:        }
1.96      paf       368: }
1.271     moko      369: 
1.96      paf       370: void file_write(
1.250     misha     371:                                Request_charsets& charsets,
                    372:                                const String& file_spec,
                    373:                                const char* data,
                    374:                                size_t size, 
1.126     paf       375:                                bool as_text, 
1.250     misha     376:                                bool do_append,
                    377:                                Charset* asked_charset) {
                    378: 
                    379:        if(as_text && asked_charset){
                    380:                String::C body=String::C(data, size);
                    381:                body=Charset::transcode(body, charsets.source(), *asked_charset);
                    382:                data=body.str;
                    383:                size=body.length;
                    384:        };
                    385: 
1.126     paf       386:        File_write_action_info info={data, size}; 
1.225     misha     387: 
1.98      paf       388:        file_write_action_under_lock(
1.154     paf       389:                file_spec, 
1.225     misha     390:                "write",
                    391:                file_write_action,
                    392:                &info, 
1.154     paf       393:                as_text, 
                    394:                do_append); 
1.30      paf       395: }
                    396: 
1.261     misha     397: static size_t get_dir(char* fname, size_t helper_length){
                    398:        bool dir=false;
                    399:        size_t pos=0;
                    400:        for(pos=helper_length; pos; pos--){
                    401:                char c=fname[pos-1];
                    402:                if(c=='/' || c=='\\'){
                    403:                        fname[pos-1]=0;
                    404:                        dir=true;
                    405:                } else if(dir) break;
                    406:        }
                    407:        return pos;
                    408: }
                    409: 
                    410: static bool entry_readable(char* fname, bool need_dir) {
                    411:        if(need_dir){
                    412:                size_t size=strlen(fname);
                    413:                while(size) {
                    414:                        char c=fname[size-1];
                    415:                        if(c=='/' || c=='\\')
                    416:                                fname[--size]=0;
                    417:                        else
                    418:                                break;
                    419:                }
                    420:        }
                    421: 
                    422:        struct stat finfo;
                    423:        if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
                    424:                bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
                    425:                return is_dir==need_dir;
                    426:        }
                    427:        return false;
                    428: }
                    429: 
                    430: static bool entry_readable(const String& file_spec, bool need_dir) {
                    431:        return entry_readable(file_spec.taint_cstrm(String::L_FILE_SPEC), need_dir);
                    432: }
                    433: 
1.63      parser    434: // throws nothing! [this is required in file_move & file_delete]
1.277     moko      435: static void rmdir(const String& file_spec, size_t pos_after) {
1.261     misha     436:        char* dir_spec=file_spec.taint_cstrm(String::L_FILE_SPEC);
                    437:        size_t length=strlen(dir_spec);
                    438:        while( (length=get_dir(dir_spec, length)) && (length > pos_after) ){
1.274     moko      439: #ifdef _MSC_VER
1.261     misha     440:                if(!entry_readable(dir_spec, true))
                    441:                        break;
                    442:                DWORD attrs=GetFileAttributes(dir_spec);
                    443:                if(
                    444:                        (attrs==INVALID_FILE_ATTRIBUTES)
                    445:                        || !(attrs & FILE_ATTRIBUTE_DIRECTORY)
                    446:                        || (attrs & FILE_ATTRIBUTE_REPARSE_POINT)
                    447:                )
                    448:                        break;
                    449: #endif
                    450:                if( rmdir(dir_spec) )
                    451:                        break;
                    452:        };
1.50      paf       453: }
1.239     misha     454: 
1.269     misha     455: bool file_delete(const String& file_spec, bool fail_on_problem, bool keep_empty_dirs) {
1.247     misha     456:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); 
1.282     moko      457:        if(unlink(fname)!=0) {
1.164     paf       458:                if(fail_on_problem)
1.289     moko      459:                        throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
                    460:                                &file_spec, "unlink failed: %s (%d), actual filename '%s'", strerror(errno), errno, fname);
1.93      paf       461:                else
                    462:                        return false;
1.282     moko      463:        }
1.50      paf       464: 
1.269     misha     465:        if(!keep_empty_dirs)
                    466:                rmdir(file_spec, 1); 
                    467: 
1.93      paf       468:        return true;
1.60      parser    469: }
1.239     misha     470: 
1.269     misha     471: void file_move(const String& old_spec, const String& new_spec, bool keep_empty_dirs) {
1.247     misha     472:        const char* old_spec_cstr=old_spec.taint_cstr(String::L_FILE_SPEC); 
                    473:        const char* new_spec_cstr=new_spec.taint_cstr(String::L_FILE_SPEC); 
1.63      parser    474:        
1.126     paf       475:        create_dir_for_file(new_spec); 
1.63      parser    476: 
1.60      parser    477:        if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.289     moko      478:                throw Exception(errno==EACCES ? "file.access" : errno==ENOENT ? "file.missing" : 0,
                    479:                        &old_spec, "rename failed: %s (%d), actual filename '%s' to '%s'", strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63      parser    480: 
1.269     misha     481:        if(!keep_empty_dirs)
                    482:                rmdir(old_spec, 1); 
1.31      paf       483: }
                    484: 
1.51      paf       485: 
1.126     paf       486: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118     paf       487:        struct stat lfinfo;
1.298     moko      488:        bool result=pa_stat(fname, &lfinfo)==0;
1.118     paf       489:        if(afinfo)
                    490:                *afinfo=lfinfo;
                    491:        return result;
1.119     paf       492: }
                    493: 
                    494: bool entry_exists(const String& file_spec) {
1.247     misha     495:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); 
1.126     paf       496:        return entry_exists(fname, 0); 
1.118     paf       497: }
                    498: 
1.215     paf       499: bool file_exist(const String& file_spec) {
1.126     paf       500:        return entry_readable(file_spec, false); 
1.51      paf       501: }
1.239     misha     502: 
1.215     paf       503: bool dir_exists(const String& file_spec) {
1.126     paf       504:        return entry_readable(file_spec, true); 
1.65      parser    505: }
1.239     misha     506: 
1.215     paf       507: const String* file_exist(const String& path, const String& name) {
1.154     paf       508:        String& result=*new String(path);
1.270     moko      509:        if(path.last_char() != '/')
                    510:                result << "/"; 
1.154     paf       511:        result << name;
1.215     paf       512:        return file_exist(result)?&result:0;
1.43      paf       513: }
1.239     misha     514: 
1.43      paf       515: bool file_executable(const String& file_spec) {
1.247     misha     516:        return access(file_spec.taint_cstr(String::L_FILE_SPEC), X_OK)==0;
1.44      paf       517: }
                    518: 
1.296     moko      519: 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     520:        const char* fname=file_spec.taint_cstr(String::L_FILE_SPEC); 
1.154     paf       521:        struct stat finfo;
1.298     moko      522:        if(pa_stat(fname, &finfo)!=0) {
1.64      parser    523:                if(fail_on_read_problem)
1.289     moko      524:                        throw Exception("file.missing", &file_spec, "getting file size failed: %s (%d), real filename '%s'", strerror(errno), errno, fname);
1.64      parser    525:                else
                    526:                        return false;
1.282     moko      527:        }
1.58      parser    528:        rsize=finfo.st_size;
1.299     moko      529:        ratime=(time_t)finfo.st_atime;
                    530:        rmtime=(time_t)finfo.st_mtime;
                    531:        rctime=(time_t)finfo.st_ctime;
1.64      parser    532:        return true;
1.18      paf       533: }
                    534: 
1.300     moko      535: size_t check_file_size(uint64_t size, const String& file_spec){
                    536:        if(size > pa_file_size_limit)
                    537:                throw Exception(PARSER_RUNTIME, &file_spec, "content size of %.15g bytes exceeds the limit (%.15g bytes)", (double)size, (double)pa_file_size_limit);
                    538:        return (size_t)size;
                    539: }
                    540: 
1.278     moko      541: /** 
                    542:        String related functions
                    543: */
                    544: 
                    545: bool capitalized(const char* s){
                    546:        bool upper=true;
                    547:        for(const char* c=s; *c; c++){
                    548:                if(*c != (upper ? toupper((unsigned char)*c) : tolower((unsigned char)*c)))
                    549:                        return false;
                    550:                upper=strchr("-_ ", *c) != 0;
                    551:        }
                    552:        return true;
                    553: }
                    554: 
                    555: const char* capitalize(const char* s){
                    556:        if(!s || capitalized(s))
                    557:                return s;
                    558: 
                    559:        char* result=pa_strdup(s);
                    560:        if(result){
                    561:                bool upper=true;
                    562:                for(char* c=result; *c; c++){
                    563:                        *c=upper ? (char)toupper((unsigned char)*c) : (char)tolower((unsigned char)*c);
                    564:                        upper=strchr("-_ ", *c) != 0;
                    565:                }
                    566:        }
                    567:        return (const char*)result;
                    568: }
                    569: 
1.290     moko      570: char *str_lower(const char *s, size_t helper_length){
                    571:        char *result=pa_strdup(s, helper_length);
                    572:        for(char* c=result; *c; c++)
                    573:                *c=(char)tolower((unsigned char)*c);
                    574:        return result;
                    575: }
                    576: 
                    577: char *str_upper(const char *s, size_t helper_length){
                    578:        char *result=pa_strdup(s, helper_length);
                    579:        for(char* c=result; *c; c++)
                    580:                *c=(char)toupper((unsigned char)*c);
                    581:        return result;
                    582: }
                    583: 
1.278     moko      584: void fix_line_breaks(char *str, size_t& length) {
                    585:        //_asm int 3;
                    586:        const char* const eob=str+length;
                    587:        char* dest=str;
                    588:        // fix DOS: \r\n -> \n
                    589:        // fix Macintosh: \r -> \n
                    590:        char* bol=str;
                    591:        while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
                    592:                size_t len=eol-bol;
                    593:                if(dest!=bol)
                    594:                        memmove(dest, bol, len); 
                    595:                dest+=len;
                    596:                *dest++='\n'; 
                    597: 
                    598:                if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
                    599:                        bol=eol+2;
                    600:                        length--; 
                    601:                } else // \r, not \n = Macintosh
                    602:                        bol=eol+1;
                    603:        }
                    604:        // last piece without \r
                    605:        if(dest!=bol)
                    606:                memmove(dest, bol, eob-bol); 
                    607:        str[length]=0; // terminating
                    608: }
                    609: 
                    610: /**
                    611:        scans for @a delim[default \n] in @a *row_ref, 
                    612:        @return piece of line before it or end of string, if no @a delim found
                    613:        assigns @a *row_ref to point right after delimiter if there were one
                    614:        or to zero if no @a delim were found.
                    615: */
                    616: 
1.126     paf       617: char* getrow(char* *row_ref, char delim) {
1.229     misha     618:        char* result=*row_ref;
                    619:        if(result) {
1.126     paf       620:                *row_ref=strchr(result, delim); 
1.8       paf       621:                if(*row_ref) 
                    622:                        *((*row_ref)++)=0; 
                    623:                else if(!*result) 
                    624:                        return 0;
1.229     misha     625:        }
                    626:        return result;
1.8       paf       627: }
                    628: 
1.126     paf       629: char* lsplit(char* string, char delim) {
1.229     misha     630:        if(string) {
1.126     paf       631:                char* v=strchr(string, delim); 
1.8       paf       632:                if(v) {
                    633:                        *v=0;
                    634:                        return v+1;
                    635:                }
1.229     misha     636:        }
                    637:        return 0;
1.8       paf       638: }
                    639: 
1.126     paf       640: char* lsplit(char* *string_ref, char delim) {
1.229     misha     641:        char* result=*string_ref;
1.126     paf       642:        char* next=lsplit(*string_ref, delim); 
1.229     misha     643:        *string_ref=next;
                    644:        return result;
1.9       paf       645: }
                    646: 
1.126     paf       647: char* rsplit(char* string, char delim) {
1.229     misha     648:        if(string) {
1.126     paf       649:                char* v=strrchr(string, delim); 
1.18      paf       650:                if(v) {
1.9       paf       651:                        *v=0;
                    652:                        return v+1;
                    653:                }
1.229     misha     654:        }
                    655:        return NULL;    
1.10      paf       656: }
                    657: 
1.229     misha     658: 
                    659: // format: %[flags][width][.precision]type     http://msdn.microsoft.com/ru-ru/library/56e442dc(en-us,VS.80).aspx
                    660: //             flags: '-', '+', ' ', '#', '0'          http://msdn.microsoft.com/ru-ru/library/8aky45ct(en-us,VS.80).aspx
                    661: //             width, precision: non negative decimal number
                    662: enum FormatType {
                    663:        FormatInvalid,
                    664:        FormatInt,
                    665:        FormatUInt,
                    666:        FormatDouble
                    667: };
1.272     moko      668: FormatType format_type(const char* fmt){
1.229     misha     669:        enum FormatState {
                    670:                Percent, 
                    671:                Flags, 
                    672:                Width,
                    673:                Precision,
                    674:                Done
                    675:        } state=Percent;
                    676: 
                    677:        FormatType result=FormatInvalid;
                    678: 
1.272     moko      679:        const char* pos=fmt;
1.229     misha     680:        while(char c=*(pos++)){
                    681:                switch(state){
                    682:                        case Percent:
                    683:                                if(c=='%'){
                    684:                                        state=Flags;
                    685:                                } else {
                    686:                                        return FormatInvalid; // 1st char must be '%' only
                    687:                                }
                    688:                                break;
                    689:                        case Flags:
                    690:                                if(strchr("-+ #0", c)!=0){
                    691:                                        break;
                    692:                                }
                    693:                                // go to the next step
                    694:                        case Width:
                    695:                                if(c=='.'){
                    696:                                        state=Precision;
                    697:                                        break;
                    698:                                }
                    699:                                // go to the next step
                    700:                        case Precision:
                    701:                                if(c>='0' && c<='9'){
                    702:                                        if(state == Flags) state=Width; // no more flags
                    703:                                        break;
                    704:                                } else if(c=='d' || c=='i'){
                    705:                                        result=FormatInt;
                    706:                                } else if(strchr("feEgG", c)!=0){
                    707:                                        result=FormatDouble;
                    708:                                } else if(strchr("uoxX", c)!=0){
                    709:                                        result=FormatUInt;
                    710:                                } else {
                    711:                                        return FormatInvalid; // invalid char
                    712:                                }
                    713:                                state=Done;
                    714:                                break;
                    715:                        case Done:
                    716:                                return FormatInvalid; // no chars allowed after 'type'
                    717:                }
                    718:        }
                    719:        return result;
                    720: }
                    721: 
                    722: 
1.272     moko      723: const char* format(double value, const char* fmt) {
1.229     misha     724:        char local_buf[MAX_NUMBER];
1.235     misha     725:        int size=-1;
1.229     misha     726: 
                    727:        if(fmt && strlen(fmt)){
                    728:                switch(format_type(fmt)){
                    729:                        case FormatDouble:
                    730:                                size=snprintf(local_buf, sizeof(local_buf), fmt, value); 
                    731:                                break;
                    732:                        case FormatInt:
                    733:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value); 
                    734:                                break;
                    735:                        case FormatUInt:
1.126     paf       736:                                size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value); 
1.229     misha     737:                                break;
                    738:                        case FormatInvalid:
1.289     moko      739:                                throw Exception(PARSER_RUNTIME, 0, "Incorrect format string '%s' was specified.", fmt);
1.229     misha     740:                }
                    741:        } else
                    742:                size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
                    743: 
                    744:        if(size < 0 || size >= MAX_NUMBER-1){ // on win32 we manually reduce max size while printing
1.304     moko      745:                throw Exception(PARSER_RUNTIME, 0, "Error occurred white executing snprintf with format string '%s'.", fmt);
1.229     misha     746:        }
                    747: 
1.235     misha     748:        return pa_strdup(local_buf, (size_t)size);
1.12      paf       749: }
                    750: 
1.36      paf       751: size_t stdout_write(const void *buf, size_t size) {
1.12      paf       752: #ifdef WIN32
1.187     paf       753:        size_t to_write = size;
1.12      paf       754:        do{
1.154     paf       755:                int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout); 
1.12      paf       756:                if(chunk_written<=0)
                    757:                        break;
                    758:                size-=chunk_written;
1.36      paf       759:                buf=((const char*)buf)+chunk_written;
1.126     paf       760:        } while(size>0); 
1.12      paf       761: 
1.187     paf       762:        return to_write-size;
1.12      paf       763: #else
1.126     paf       764:        return fwrite(buf, 1, size, stdout); 
1.12      paf       765: #endif
1.2       paf       766: }
1.14      paf       767: 
1.229     misha     768: enum EscapeState {
                    769:        EscapeRest, 
                    770:        EscapeFirst, 
                    771:        EscapeSecond,
                    772:        EscapeUnicode
                    773: };
                    774: 
1.236     misha     775: // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually)
1.258     misha     776: char* unescape_chars(const char* cp, int len, Charset* charset, bool js){
1.236     misha     777:        char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
1.230     misha     778:        char* dst=s;
1.229     misha     779:        EscapeState escapeState=EscapeRest;
                    780:        uint escapedValue=0;
                    781:        int srcPos=0;
1.230     misha     782:        short int jsCnt=0;
1.236     misha     783:        while(srcPos<len){
1.229     misha     784:                uchar c=(uchar)cp[srcPos]; 
1.258     misha     785:                if(c=='%' || (c=='\\' && js)){
1.229     misha     786:                        escapeState=EscapeFirst;
                    787:                } else {
                    788:                        switch(escapeState) {
                    789:                                case EscapeRest:
1.286     moko      790:                                        if(c=='+' && !js){
1.230     misha     791:                                                *dst++=' ';
1.229     misha     792:                                        } else {
1.230     misha     793:                                                *dst++=c;
1.229     misha     794:                                        }
                    795:                                        break;
                    796:                                case EscapeFirst:
1.232     misha     797:                                        if(charset && c=='u'){
1.229     misha     798:                                                // escaped unicode value: %u0430
                    799:                                                jsCnt=0;
                    800:                                                escapedValue=0;
                    801:                                                escapeState=EscapeUnicode;
                    802:                                        } else {
1.231     misha     803:                                                if(isxdigit(c)){
1.229     misha     804:                                                        escapedValue=hex_value[c] << 4;
                    805:                                                        escapeState=EscapeSecond;
                    806:                                                } else {
1.230     misha     807:                                                        *dst++=c;
1.229     misha     808:                                                        escapeState=EscapeRest;
                    809:                                                }
                    810:                                        }
                    811:                                        break;
                    812:                                case EscapeSecond:
1.231     misha     813:                                        if(isxdigit(c)){
1.229     misha     814:                                                escapedValue+=hex_value[c]; 
1.230     misha     815:                                                *dst++=(char)escapedValue;
1.229     misha     816:                                        }
                    817:                                        escapeState=EscapeRest;
                    818:                                        break;
                    819:                                case EscapeUnicode:
1.231     misha     820:                                        if(isxdigit(c)){
1.229     misha     821:                                                escapedValue=(escapedValue << 4) + hex_value[c];
                    822:                                                if(++jsCnt==4){
1.230     misha     823:                                                        // transcode utf8 char to client charset (we can lost some chars here)
1.232     misha     824:                                                        charset->store_Char((XMLByte*&)dst, (XMLCh)escapedValue, '?');
1.229     misha     825:                                                        escapeState=EscapeRest;
                    826:                                                }
                    827:                                        } else {
                    828:                                                // not full unicode value
                    829:                                                escapeState=EscapeRest;
                    830:                                        }
                    831:                                        break;
                    832:                        }
                    833:                }
                    834: 
                    835:                srcPos++;
                    836:        }
                    837: 
1.230     misha     838:        *dst=0; // zero-termination
1.229     misha     839:        return s;
                    840: }
1.24      paf       841: 
1.268     misha     842: char *search_stop(char*& current, char cstop_at) {
                    843:        // sanity check
                    844:        if(!current)
                    845:                return 0;
                    846: 
                    847:        // skip leading WS
                    848:        while(*current==' ' || *current=='\t')
                    849:                current++;
                    850:        if(!*current)
                    851:                return current=0;
                    852: 
                    853:        char *result=current;
                    854:        if(char *pstop_at=strchr(current, cstop_at)) {
                    855:                *pstop_at=0;
                    856:                current=pstop_at+1;
                    857:        } else
                    858:                current=0;
                    859:        return result;
                    860: }
                    861: 
1.24      paf       862: #ifdef WIN32
1.126     paf       863: void back_slashes_to_slashes(char* s) {
1.24      paf       864:        if(s)
                    865:                for(; *s; s++)
                    866:                        if(*s=='\\')
1.126     paf       867:                                *s='/'; 
1.24      paf       868: }
                    869: #endif
1.41      paf       870: 
1.232     misha     871: size_t strpos(const char *str, const char *substr) {
                    872:        const char *p = strstr(str, substr);
                    873:        return (p==0)?STRING_NOT_FOUND:p-str;
                    874: }
                    875: 
1.226     misha     876: int remove_crlf(char* start, char* end) {
                    877:        char* from=start;
                    878:        char* to=start;
                    879:        bool skip=false;
                    880:        while(from < end){
                    881:                switch(*from){
                    882:                        case '\n':
                    883:                        case '\r':
                    884:                        case '\t':
                    885:                        case ' ':
                    886:                                if(!skip){
                    887:                                        *to=' ';
                    888:                                        to++;
                    889:                                        skip=true;
                    890:                                }
                    891:                                break;
                    892:                        default:
                    893:                                if(from != to)
                    894:                                        *to=*from;
                    895:                                to++;
                    896:                                skip=false;
1.69      parser    897:                }
1.226     misha     898:                from++;
                    899:        }
                    900:        return to-start;
1.91      paf       901: }
                    902: 
1.279     moko      903: const char* hex_digits="0123456789ABCDEF";
                    904: 
1.278     moko      905: const char* hex_string(unsigned char* bytes, size_t size, bool upcase) {
                    906:        char *bytes_hex=new(PointerFreeGC) char [size*2/*byte->hh*/+1/*for zero-teminator*/];
                    907:        unsigned char *src=bytes;
                    908:        unsigned char *end=bytes+size;
                    909:        char *dest=bytes_hex;
                    910: 
1.279     moko      911:        const char *hex=upcase? hex_digits : "0123456789abcdef";
1.278     moko      912: 
                    913:        for(; src<end; src++) {
                    914:                *dest++=hex[*src/0x10];
                    915:                *dest++=hex[*src%0x10];
                    916:        }
                    917:        *dest=0;
                    918: 
                    919:        return bytes_hex;
                    920: }
1.91      paf       921: 
1.221     misha     922: int file_block_read(const int f, unsigned char* buffer, const size_t size){
                    923:        int nCount = read(f, buffer, size);
                    924:        if (nCount < 0)
1.289     moko      925:                throw Exception("file.read", 0, "read failed: %s (%d)", strerror(errno), errno); 
1.221     misha     926:        return nCount;
                    927: }
                    928: 
1.278     moko      929: static unsigned long crc32Table[256];
                    930: static void InitCrc32Table()
                    931: {
                    932:        if(crc32Table[1] == 0){
                    933:                // This is the official polynomial used by CRC32 in PKZip.
                    934:                // Often times the polynomial shown reversed as 0x04C11DB7.
                    935:                static const unsigned long dwPolynomial = 0xEDB88320;
                    936: 
                    937:                for(int i = 0; i < 256; i++)
                    938:                {
                    939:                        unsigned long dwCrc = i;
                    940:                        for(int j = 8; j > 0; j--)
                    941:                        {
                    942:                                if(dwCrc & 1)
                    943:                                        dwCrc = (dwCrc >> 1) ^ dwPolynomial;
                    944:                                else
                    945:                                        dwCrc >>= 1;
                    946:                        }
                    947:                        crc32Table[i] = dwCrc;
                    948:                }
                    949:        }
                    950: }
                    951: 
                    952: inline void CalcCrc32(const unsigned char byte, unsigned long &crc32)
                    953: {
                    954:        crc32 = ((crc32) >> 8) ^ crc32Table[(byte) ^ ((crc32) & 0x000000FF)];
                    955: }
                    956: 
                    957: 
1.297     moko      958: unsigned long pa_crc32(const char *in, size_t in_size){
1.218     misha     959:        unsigned long crc32=0xFFFFFFFF;
1.220     misha     960: 
1.240     misha     961:        InitCrc32Table();
1.239     misha     962:        for(size_t i = 0; i<in_size; i++)
                    963:                CalcCrc32(in[i], crc32);
1.220     misha     964: 
1.218     misha     965:        return ~crc32; 
                    966: }
                    967: 
1.289     moko      968: static void file_crc32_file_action(struct stat& finfo, int f, const String&, void *context) {
1.218     misha     969:        unsigned long& crc32=*static_cast<unsigned long *>(context);
                    970:        if(finfo.st_size) {
                    971:                InitCrc32Table();
1.220     misha     972:                int nCount=0;
1.218     misha     973:                do {
1.221     misha     974:                        unsigned char buffer[FILE_BUFFER_SIZE];
                    975:                        nCount = file_block_read(f, buffer, sizeof(buffer));
1.220     misha     976:                        for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
                    977:                } while(nCount > 0);
1.218     misha     978:        }
                    979: }
                    980: 
1.297     moko      981: unsigned long pa_crc32(const String& file_spec){
1.278     moko      982:        unsigned long crc32=0xFFFFFFFF;
                    983:        file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
                    984:        return ~crc32; 
                    985: }
                    986: 
                    987: // content-type: xxx; charset=WE-NEED-THIS
                    988: // content-type: xxx; charset="WE-NEED-THIS"
                    989: // content-type: xxx; charset="WE-NEED-THIS";
                    990: Charset* detect_charset(const char* content_type){
                    991:        if(content_type){
1.291     moko      992:                char* CONTENT_TYPE=str_upper(content_type);
1.278     moko      993: 
                    994:                if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
                    995:                        begin+=8; // skip "CHARSET="
                    996:                        char* end=0;
                    997:                        if(*begin && (*begin=='"' || *begin =='\'')){
                    998:                                char quote=*begin;
                    999:                                begin++;
                   1000:                                end=(char*)strchr(begin, quote);
                   1001:                        }
                   1002:                        if(!end)
                   1003:                                end=(char*)strchr(begin, ';');
                   1004: 
                   1005:                        if(end)
                   1006:                                *end=0; // terminator
                   1007: 
1.295     moko     1008:                        return *begin ? &pa_charsets.get_direct(begin) : 0;
1.278     moko     1009:                }
                   1010:        }
                   1011:        return 0;
                   1012: }
                   1013: 
1.301     moko     1014: const UTF16* pa_utf16_encode(const char* in, Charset& source_charset){
1.302     moko     1015:        if(!in)
                   1016:                return 0;
1.301     moko     1017: 
1.302     moko     1018:        String::C sIn(in,strlen(in));
1.301     moko     1019: 
1.302     moko     1020:        UTF16* utf16=(UTF16*)pa_malloc_atomic(sIn.length*2+2);
                   1021:        UTF16* utf16_end=utf16;
1.301     moko     1022: 
1.302     moko     1023:        if(!source_charset.isUTF8())
                   1024:                sIn=Charset::transcode(sIn, source_charset, pa_UTF8_charset);
1.301     moko     1025: 
1.302     moko     1026:        int status=pa_convertUTF8toUTF16((const UTF8**)&sIn.str, (const UTF8*)(sIn.str+sIn.length), &utf16_end, utf16+sIn.length, strictConversion);
                   1027:        if(status != conversionOK)
                   1028:                throw Exception("utf-16 encode", new String(in), "utf-16 conversion failed (%d)", status);
1.301     moko     1029: 
1.302     moko     1030:        *utf16_end=0;
1.301     moko     1031: 
1.302     moko     1032:        return utf16;
1.301     moko     1033: }
                   1034: 
                   1035: const char* pa_utf16_decode(const UTF16* in, Charset& asked_charset){
                   1036:        if(!in)
                   1037:                return 0;
                   1038: 
                   1039:        const UTF16* utf16_start=in;
                   1040:        const UTF16* utf16_end;
                   1041: 
                   1042:        for(utf16_end=in; *utf16_end; utf16_end++);
                   1043: 
                   1044:        char *result = (char *)pa_malloc_atomic((utf16_end-in)*6+1);
                   1045:        char *result_end = result;
                   1046: 
                   1047:        int status=pa_convertUTF16toUTF8(&utf16_start, utf16_end, (UTF8**)&result_end, (UTF8*)(result+(utf16_end-in)*6), strictConversion);
                   1048: 
                   1049:        if(status != conversionOK)
                   1050:                throw Exception("utf-16 decode", 0, "utf conversion failed (%d)", status);
                   1051: 
                   1052:        *result_end='\0';
                   1053: 
1.302     moko     1054:        if(asked_charset.isUTF8())
                   1055:                return result;
1.301     moko     1056: 
1.302     moko     1057:        return Charset::transcode(result, pa_UTF8_charset, asked_charset).cstr();
1.301     moko     1058: }
1.278     moko     1059: 
1.283     moko     1060: static bool is_latin(const char *in){
                   1061:        for(; *in; in++){
                   1062:                if ((unsigned char)(*in) > 0x7F)
                   1063:                        return false;
                   1064:        }
                   1065:        return true;
                   1066: }
                   1067: 
                   1068: #define MAX_IDNA_LENGTH 256
                   1069: 
1.301     moko     1070: const char *pa_idna_encode(const char *in, Charset& source_charset){
1.283     moko     1071:        if(!in || is_latin(in))
                   1072:                return in;
                   1073: 
                   1074:        uint32_t utf32[MAX_IDNA_LENGTH];
                   1075:        uint32_t *utf32_end=utf32;
                   1076: 
                   1077:        String::C sIn(in,strlen(in));
                   1078: 
                   1079:        if(!source_charset.isUTF8())
1.295     moko     1080:                sIn=Charset::transcode(sIn, source_charset, pa_UTF8_charset);
1.283     moko     1081: 
                   1082:        int status=pa_convertUTF8toUTF32((const UTF8**)&sIn.str, (const UTF8*)(sIn.str+sIn.length), &utf32_end, utf32+MAX_IDNA_LENGTH-1, strictConversion);
                   1083:        if(status != conversionOK)
                   1084:                throw Exception("idna encode", new String(in), "utf conversion failed (%d)", status);
                   1085: 
                   1086:        *utf32_end=0;
                   1087: 
                   1088:        char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
                   1089:        status=pa_idna_to_ascii_4z(utf32, result, MAX_IDNA_LENGTH, 0);
                   1090:        if(status != IDNA_SUCCESS)
                   1091:                throw Exception("idna encode", new String(in), "encode failed: %s", pa_idna_strerror(status));
                   1092: 
                   1093:        return result;
                   1094: }
                   1095: 
                   1096: const char *pa_idna_decode(const char *in, Charset &asked_charset){
                   1097:        if(!in || !(*in))
                   1098:                return in;
                   1099: 
                   1100:        uint32_t utf32[MAX_IDNA_LENGTH];
                   1101:        const uint32_t *utf32_start=utf32;
                   1102:        uint32_t *utf32_end;
                   1103: 
                   1104:        int status=pa_idna_to_unicode_4z(in, utf32, MAX_IDNA_LENGTH, 0);
                   1105:        if(status != IDNA_SUCCESS)
                   1106:                throw Exception("idna decode", new String(in), "decode failed: %s", pa_idna_strerror(status));
                   1107: 
                   1108:        for(utf32_end=utf32; *utf32_end; utf32_end++);
                   1109: 
                   1110:        char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
                   1111:        char *result_end = result;
                   1112: 
                   1113:        status=pa_convertUTF32toUTF8(&utf32_start, utf32_end, (UTF8**)&result_end, (UTF8*)(result+MAX_IDNA_LENGTH-1), strictConversion);
                   1114: 
                   1115:        if(status != conversionOK)
                   1116:                throw Exception("idna decode", new String(in), "utf conversion failed (%d)", status);
                   1117: 
                   1118:        *result_end='\0';
                   1119: 
                   1120:        if(!asked_charset.isUTF8())
1.295     moko     1121:                result = (char *)Charset::transcode(result, pa_UTF8_charset, asked_charset).cstr();
1.283     moko     1122: 
                   1123:        return result;
                   1124: }
1.292     moko     1125: /// must be last in this file
                   1126: #undef vsnprintf
                   1127: int pa_vsnprintf(char* b, size_t s, const char* f, va_list l) {
                   1128:        if(!s)
                   1129:                return 0;
                   1130: 
                   1131:        int r;
                   1132:        // note: on win32 & maybe somewhere else
                   1133:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                   1134:        // http://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
                   1135:        --s;
                   1136: 
                   1137:        // clients do not check for negative 's', feature: ignore such prints
                   1138:        if((ssize_t)s<0)
                   1139:                return 0;
                   1140: 
                   1141: #ifdef _MSC_VER
                   1142:        // win32: if the number of bytes to write exceeds buffer, then count bytes are written and -1 is returned
                   1143:        r=_vsnprintf(b, s, f, l); 
                   1144:        if(r<0) 
                   1145:                r=s;
                   1146: #else
                   1147:        r=vsnprintf(b, s, f, l); 
                   1148:        /*
                   1149:        solaris: man vsnprintf
                   1150: 
                   1151:        The snprintf() function returns  the  number  of  characters
                   1152:        formatted, that is, the number of characters that would have
                   1153:        been written to the buffer if it were large enough.  If  the
                   1154:        value  of  n  is  0  on a call to snprintf(), an unspecified
                   1155:        value less than 1 is returned.
                   1156:        */
                   1157: 
                   1158:        if(r<0)
                   1159:                r=0;
                   1160:        else if((size_t)r>s)
                   1161:                r=s;
                   1162: #endif
                   1163:        b[r]=0;
                   1164:        return r;
                   1165: }
                   1166: 
                   1167: int pa_snprintf(char* b, size_t s, const char* f, ...) {
                   1168:        va_list l;
                   1169:        va_start(l, f); 
                   1170:        int r=pa_vsnprintf(b, s, f, l); 
                   1171:        va_end(l); 
                   1172:        return r;
                   1173: }
                   1174: 

E-mail: