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

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

E-mail: