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

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

E-mail: