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

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

E-mail: