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

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

E-mail: