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

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

E-mail: