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

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.339   ! moko       25: volatile const char * IDENT_PA_COMMON_C="$Id: pa_common.C,v 1.338 2025/07/03 19:45:41 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.339   ! moko       92:        return _wrename(PA_UTF16_ENC(odlpath), 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: 
                    700: // format: %[flags][width][.precision]type     http://msdn.microsoft.com/ru-ru/library/56e442dc(en-us,VS.80).aspx
                    701: //             flags: '-', '+', ' ', '#', '0'          http://msdn.microsoft.com/ru-ru/library/8aky45ct(en-us,VS.80).aspx
                    702: //             width, precision: non negative decimal number
                    703: enum FormatType {
                    704:        FormatInvalid,
                    705:        FormatInt,
                    706:        FormatUInt,
                    707:        FormatDouble
                    708: };
1.272     moko      709: FormatType format_type(const char* fmt){
1.229     misha     710:        enum FormatState {
                    711:                Percent, 
                    712:                Flags, 
                    713:                Width,
                    714:                Precision,
                    715:                Done
                    716:        } state=Percent;
                    717: 
                    718:        FormatType result=FormatInvalid;
                    719: 
1.272     moko      720:        const char* pos=fmt;
1.229     misha     721:        while(char c=*(pos++)){
                    722:                switch(state){
                    723:                        case Percent:
                    724:                                if(c=='%'){
                    725:                                        state=Flags;
                    726:                                } else {
                    727:                                        return FormatInvalid; // 1st char must be '%' only
                    728:                                }
                    729:                                break;
                    730:                        case Flags:
                    731:                                if(strchr("-+ #0", c)!=0){
                    732:                                        break;
                    733:                                }
                    734:                                // go to the next step
                    735:                        case Width:
                    736:                                if(c=='.'){
                    737:                                        state=Precision;
                    738:                                        break;
                    739:                                }
                    740:                                // go to the next step
                    741:                        case Precision:
                    742:                                if(c>='0' && c<='9'){
                    743:                                        if(state == Flags) state=Width; // no more flags
                    744:                                        break;
                    745:                                } else if(c=='d' || c=='i'){
                    746:                                        result=FormatInt;
                    747:                                } else if(strchr("feEgG", c)!=0){
                    748:                                        result=FormatDouble;
                    749:                                } else if(strchr("uoxX", c)!=0){
                    750:                                        result=FormatUInt;
                    751:                                } else {
                    752:                                        return FormatInvalid; // invalid char
                    753:                                }
                    754:                                state=Done;
                    755:                                break;
                    756:                        case Done:
                    757:                                return FormatInvalid; // no chars allowed after 'type'
                    758:                }
                    759:        }
                    760:        return result;
                    761: }
                    762: 
                    763: 
1.333     moko      764: const char* format_double(double value, const char* fmt) {
1.229     misha     765:        char local_buf[MAX_NUMBER];
1.235     misha     766:        int size=-1;
1.229     misha     767: 
                    768:        if(fmt && strlen(fmt)){
                    769:                switch(format_type(fmt)){
                    770:                        case FormatDouble:
1.329     moko      771:                                size=snprintf(local_buf, sizeof(local_buf), fmt, value);
1.229     misha     772:                                break;
1.328     moko      773:                        case FormatUInt:
                    774:                                if(value >= 0){ // on Apple M1 (uint)<negative value> is 0
1.329     moko      775:                                        size=snprintf(local_buf, sizeof(local_buf), fmt, clip2uint(value));
1.328     moko      776:                                        break;
                    777:                                }
1.229     misha     778:                        case FormatInt:
1.329     moko      779:                                size=snprintf(local_buf, sizeof(local_buf), fmt, clip2int(value));
1.229     misha     780:                                break;
                    781:                        case FormatInvalid:
1.289     moko      782:                                throw Exception(PARSER_RUNTIME, 0, "Incorrect format string '%s' was specified.", fmt);
1.229     misha     783:                }
                    784:        } else
1.331     moko      785:                return pa_itoa(clip2int(value));
1.229     misha     786: 
                    787:        if(size < 0 || size >= MAX_NUMBER-1){ // on win32 we manually reduce max size while printing
1.304     moko      788:                throw Exception(PARSER_RUNTIME, 0, "Error occurred white executing snprintf with format string '%s'.", fmt);
1.229     misha     789:        }
                    790: 
1.235     misha     791:        return pa_strdup(local_buf, (size_t)size);
1.12      paf       792: }
                    793: 
1.36      paf       794: size_t stdout_write(const void *buf, size_t size) {
1.12      paf       795: #ifdef WIN32
1.187     paf       796:        size_t to_write = size;
1.12      paf       797:        do{
1.316     moko      798:                int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12      paf       799:                if(chunk_written<=0)
                    800:                        break;
                    801:                size-=chunk_written;
1.36      paf       802:                buf=((const char*)buf)+chunk_written;
1.316     moko      803:        } while(size>0);
1.12      paf       804: 
1.316     moko      805:        fflush(stdout);
1.187     paf       806:        return to_write-size;
1.12      paf       807: #else
1.316     moko      808:        size_t result=fwrite(buf, 1, size, stdout);
                    809:        fflush(stdout);
                    810:        return result;
1.12      paf       811: #endif
1.2       paf       812: }
1.14      paf       813: 
1.229     misha     814: enum EscapeState {
                    815:        EscapeRest, 
                    816:        EscapeFirst, 
                    817:        EscapeSecond,
                    818:        EscapeUnicode
                    819: };
                    820: 
1.236     misha     821: // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually)
1.258     misha     822: char* unescape_chars(const char* cp, int len, Charset* charset, bool js){
1.236     misha     823:        char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
1.336     moko      824:        XMLByte* dst=(XMLByte *)s;
1.229     misha     825:        EscapeState escapeState=EscapeRest;
                    826:        uint escapedValue=0;
                    827:        int srcPos=0;
1.230     misha     828:        short int jsCnt=0;
1.236     misha     829:        while(srcPos<len){
1.229     misha     830:                uchar c=(uchar)cp[srcPos]; 
1.258     misha     831:                if(c=='%' || (c=='\\' && js)){
1.229     misha     832:                        escapeState=EscapeFirst;
                    833:                } else {
                    834:                        switch(escapeState) {
                    835:                                case EscapeRest:
1.286     moko      836:                                        if(c=='+' && !js){
1.230     misha     837:                                                *dst++=' ';
1.229     misha     838:                                        } else {
1.230     misha     839:                                                *dst++=c;
1.229     misha     840:                                        }
                    841:                                        break;
                    842:                                case EscapeFirst:
1.232     misha     843:                                        if(charset && c=='u'){
1.229     misha     844:                                                // escaped unicode value: %u0430
                    845:                                                jsCnt=0;
                    846:                                                escapedValue=0;
                    847:                                                escapeState=EscapeUnicode;
                    848:                                        } else {
1.231     misha     849:                                                if(isxdigit(c)){
1.229     misha     850:                                                        escapedValue=hex_value[c] << 4;
                    851:                                                        escapeState=EscapeSecond;
                    852:                                                } else {
1.230     misha     853:                                                        *dst++=c;
1.229     misha     854:                                                        escapeState=EscapeRest;
                    855:                                                }
                    856:                                        }
                    857:                                        break;
                    858:                                case EscapeSecond:
1.231     misha     859:                                        if(isxdigit(c)){
1.229     misha     860:                                                escapedValue+=hex_value[c]; 
1.230     misha     861:                                                *dst++=(char)escapedValue;
1.229     misha     862:                                        }
                    863:                                        escapeState=EscapeRest;
                    864:                                        break;
                    865:                                case EscapeUnicode:
1.231     misha     866:                                        if(isxdigit(c)){
1.229     misha     867:                                                escapedValue=(escapedValue << 4) + hex_value[c];
                    868:                                                if(++jsCnt==4){
1.230     misha     869:                                                        // transcode utf8 char to client charset (we can lost some chars here)
1.336     moko      870:                                                        charset->store_Char(dst, (XMLCh)escapedValue, '?');
1.229     misha     871:                                                        escapeState=EscapeRest;
                    872:                                                }
                    873:                                        } else {
                    874:                                                // not full unicode value
                    875:                                                escapeState=EscapeRest;
                    876:                                        }
                    877:                                        break;
                    878:                        }
                    879:                }
                    880: 
                    881:                srcPos++;
                    882:        }
                    883: 
1.230     misha     884:        *dst=0; // zero-termination
1.229     misha     885:        return s;
                    886: }
1.24      paf       887: 
1.268     misha     888: char *search_stop(char*& current, char cstop_at) {
                    889:        // sanity check
                    890:        if(!current)
                    891:                return 0;
                    892: 
                    893:        // skip leading WS
                    894:        while(*current==' ' || *current=='\t')
                    895:                current++;
                    896:        if(!*current)
                    897:                return current=0;
                    898: 
                    899:        char *result=current;
                    900:        if(char *pstop_at=strchr(current, cstop_at)) {
                    901:                *pstop_at=0;
                    902:                current=pstop_at+1;
                    903:        } else
                    904:                current=0;
                    905:        return result;
                    906: }
                    907: 
1.24      paf       908: #ifdef WIN32
1.126     paf       909: void back_slashes_to_slashes(char* s) {
1.24      paf       910:        if(s)
                    911:                for(; *s; s++)
                    912:                        if(*s=='\\')
1.126     paf       913:                                *s='/'; 
1.24      paf       914: }
                    915: #endif
1.41      paf       916: 
1.232     misha     917: size_t strpos(const char *str, const char *substr) {
                    918:        const char *p = strstr(str, substr);
                    919:        return (p==0)?STRING_NOT_FOUND:p-str;
                    920: }
                    921: 
1.326     moko      922: size_t remove_crlf(char* start, char* end) {
1.226     misha     923:        char* from=start;
                    924:        char* to=start;
                    925:        bool skip=false;
                    926:        while(from < end){
                    927:                switch(*from){
                    928:                        case '\n':
                    929:                        case '\r':
                    930:                        case '\t':
                    931:                        case ' ':
                    932:                                if(!skip){
                    933:                                        *to=' ';
                    934:                                        to++;
                    935:                                        skip=true;
                    936:                                }
                    937:                                break;
                    938:                        default:
                    939:                                if(from != to)
                    940:                                        *to=*from;
                    941:                                to++;
                    942:                                skip=false;
1.69      parser    943:                }
1.226     misha     944:                from++;
                    945:        }
                    946:        return to-start;
1.91      paf       947: }
                    948: 
1.279     moko      949: const char* hex_digits="0123456789ABCDEF";
                    950: 
1.278     moko      951: const char* hex_string(unsigned char* bytes, size_t size, bool upcase) {
                    952:        char *bytes_hex=new(PointerFreeGC) char [size*2/*byte->hh*/+1/*for zero-teminator*/];
                    953:        unsigned char *src=bytes;
                    954:        unsigned char *end=bytes+size;
                    955:        char *dest=bytes_hex;
                    956: 
1.279     moko      957:        const char *hex=upcase? hex_digits : "0123456789abcdef";
1.278     moko      958: 
                    959:        for(; src<end; src++) {
                    960:                *dest++=hex[*src/0x10];
                    961:                *dest++=hex[*src%0x10];
                    962:        }
                    963:        *dest=0;
                    964: 
                    965:        return bytes_hex;
                    966: }
1.91      paf       967: 
1.321     moko      968: ssize_t file_block_read(const int f, void* buffer, const size_t size){
                    969:        ssize_t nCount = read(f, buffer, size);
1.221     misha     970:        if (nCount < 0)
1.289     moko      971:                throw Exception("file.read", 0, "read failed: %s (%d)", strerror(errno), errno); 
1.221     misha     972:        return nCount;
                    973: }
                    974: 
1.278     moko      975: static unsigned long crc32Table[256];
                    976: static void InitCrc32Table()
                    977: {
                    978:        if(crc32Table[1] == 0){
                    979:                // This is the official polynomial used by CRC32 in PKZip.
                    980:                // Often times the polynomial shown reversed as 0x04C11DB7.
                    981:                static const unsigned long dwPolynomial = 0xEDB88320;
                    982: 
                    983:                for(int i = 0; i < 256; i++)
                    984:                {
                    985:                        unsigned long dwCrc = i;
                    986:                        for(int j = 8; j > 0; j--)
                    987:                        {
                    988:                                if(dwCrc & 1)
                    989:                                        dwCrc = (dwCrc >> 1) ^ dwPolynomial;
                    990:                                else
                    991:                                        dwCrc >>= 1;
                    992:                        }
                    993:                        crc32Table[i] = dwCrc;
                    994:                }
                    995:        }
                    996: }
                    997: 
                    998: inline void CalcCrc32(const unsigned char byte, unsigned long &crc32)
                    999: {
                   1000:        crc32 = ((crc32) >> 8) ^ crc32Table[(byte) ^ ((crc32) & 0x000000FF)];
                   1001: }
                   1002: 
                   1003: 
1.297     moko     1004: unsigned long pa_crc32(const char *in, size_t in_size){
1.218     misha    1005:        unsigned long crc32=0xFFFFFFFF;
1.220     misha    1006: 
1.240     misha    1007:        InitCrc32Table();
1.239     misha    1008:        for(size_t i = 0; i<in_size; i++)
                   1009:                CalcCrc32(in[i], crc32);
1.220     misha    1010: 
1.218     misha    1011:        return ~crc32; 
                   1012: }
                   1013: 
1.289     moko     1014: static void file_crc32_file_action(struct stat& finfo, int f, const String&, void *context) {
1.218     misha    1015:        unsigned long& crc32=*static_cast<unsigned long *>(context);
                   1016:        if(finfo.st_size) {
                   1017:                InitCrc32Table();
1.220     misha    1018:                int nCount=0;
1.218     misha    1019:                do {
1.221     misha    1020:                        unsigned char buffer[FILE_BUFFER_SIZE];
                   1021:                        nCount = file_block_read(f, buffer, sizeof(buffer));
1.220     misha    1022:                        for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
                   1023:                } while(nCount > 0);
1.218     misha    1024:        }
                   1025: }
                   1026: 
1.297     moko     1027: unsigned long pa_crc32(const String& file_spec){
1.278     moko     1028:        unsigned long crc32=0xFFFFFFFF;
                   1029:        file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
                   1030:        return ~crc32; 
                   1031: }
                   1032: 
                   1033: // content-type: xxx; charset=WE-NEED-THIS
                   1034: // content-type: xxx; charset="WE-NEED-THIS"
                   1035: // content-type: xxx; charset="WE-NEED-THIS";
                   1036: Charset* detect_charset(const char* content_type){
                   1037:        if(content_type){
1.291     moko     1038:                char* CONTENT_TYPE=str_upper(content_type);
1.278     moko     1039: 
                   1040:                if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
                   1041:                        begin+=8; // skip "CHARSET="
                   1042:                        char* end=0;
                   1043:                        if(*begin && (*begin=='"' || *begin =='\'')){
                   1044:                                char quote=*begin;
                   1045:                                begin++;
                   1046:                                end=(char*)strchr(begin, quote);
                   1047:                        }
                   1048:                        if(!end)
                   1049:                                end=(char*)strchr(begin, ';');
                   1050: 
                   1051:                        if(end)
                   1052:                                *end=0; // terminator
                   1053: 
1.295     moko     1054:                        return *begin ? &pa_charsets.get_direct(begin) : 0;
1.278     moko     1055:                }
                   1056:        }
                   1057:        return 0;
                   1058: }
                   1059: 
1.301     moko     1060: const UTF16* pa_utf16_encode(const char* in, Charset& source_charset){
1.302     moko     1061:        if(!in)
                   1062:                return 0;
1.301     moko     1063: 
1.302     moko     1064:        String::C sIn(in,strlen(in));
1.301     moko     1065: 
1.302     moko     1066:        UTF16* utf16=(UTF16*)pa_malloc_atomic(sIn.length*2+2);
                   1067:        UTF16* utf16_end=utf16;
1.301     moko     1068: 
1.302     moko     1069:        if(!source_charset.isUTF8())
                   1070:                sIn=Charset::transcode(sIn, source_charset, pa_UTF8_charset);
1.301     moko     1071: 
1.302     moko     1072:        int status=pa_convertUTF8toUTF16((const UTF8**)&sIn.str, (const UTF8*)(sIn.str+sIn.length), &utf16_end, utf16+sIn.length, strictConversion);
                   1073:        if(status != conversionOK)
                   1074:                throw Exception("utf-16 encode", new String(in), "utf-16 conversion failed (%d)", status);
1.301     moko     1075: 
1.302     moko     1076:        *utf16_end=0;
1.301     moko     1077: 
1.302     moko     1078:        return utf16;
1.301     moko     1079: }
                   1080: 
                   1081: const char* pa_utf16_decode(const UTF16* in, Charset& asked_charset){
                   1082:        if(!in)
                   1083:                return 0;
                   1084: 
                   1085:        const UTF16* utf16_start=in;
                   1086:        const UTF16* utf16_end;
                   1087: 
                   1088:        for(utf16_end=in; *utf16_end; utf16_end++);
                   1089: 
                   1090:        char *result = (char *)pa_malloc_atomic((utf16_end-in)*6+1);
                   1091:        char *result_end = result;
                   1092: 
                   1093:        int status=pa_convertUTF16toUTF8(&utf16_start, utf16_end, (UTF8**)&result_end, (UTF8*)(result+(utf16_end-in)*6), strictConversion);
                   1094: 
                   1095:        if(status != conversionOK)
                   1096:                throw Exception("utf-16 decode", 0, "utf conversion failed (%d)", status);
                   1097: 
                   1098:        *result_end='\0';
                   1099: 
1.302     moko     1100:        if(asked_charset.isUTF8())
                   1101:                return result;
1.301     moko     1102: 
1.302     moko     1103:        return Charset::transcode(result, pa_UTF8_charset, asked_charset).cstr();
1.301     moko     1104: }
1.278     moko     1105: 
1.283     moko     1106: static bool is_latin(const char *in){
                   1107:        for(; *in; in++){
                   1108:                if ((unsigned char)(*in) > 0x7F)
                   1109:                        return false;
                   1110:        }
                   1111:        return true;
                   1112: }
                   1113: 
                   1114: #define MAX_IDNA_LENGTH 256
                   1115: 
1.301     moko     1116: const char *pa_idna_encode(const char *in, Charset& source_charset){
1.283     moko     1117:        if(!in || is_latin(in))
                   1118:                return in;
                   1119: 
                   1120:        uint32_t utf32[MAX_IDNA_LENGTH];
                   1121:        uint32_t *utf32_end=utf32;
                   1122: 
                   1123:        String::C sIn(in,strlen(in));
                   1124: 
                   1125:        if(!source_charset.isUTF8())
1.295     moko     1126:                sIn=Charset::transcode(sIn, source_charset, pa_UTF8_charset);
1.283     moko     1127: 
                   1128:        int status=pa_convertUTF8toUTF32((const UTF8**)&sIn.str, (const UTF8*)(sIn.str+sIn.length), &utf32_end, utf32+MAX_IDNA_LENGTH-1, strictConversion);
                   1129:        if(status != conversionOK)
                   1130:                throw Exception("idna encode", new String(in), "utf conversion failed (%d)", status);
                   1131: 
                   1132:        *utf32_end=0;
                   1133: 
                   1134:        char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
                   1135:        status=pa_idna_to_ascii_4z(utf32, result, MAX_IDNA_LENGTH, 0);
                   1136:        if(status != IDNA_SUCCESS)
                   1137:                throw Exception("idna encode", new String(in), "encode failed: %s", pa_idna_strerror(status));
                   1138: 
                   1139:        return result;
                   1140: }
                   1141: 
                   1142: const char *pa_idna_decode(const char *in, Charset &asked_charset){
                   1143:        if(!in || !(*in))
                   1144:                return in;
                   1145: 
                   1146:        uint32_t utf32[MAX_IDNA_LENGTH];
                   1147:        const uint32_t *utf32_start=utf32;
                   1148:        uint32_t *utf32_end;
                   1149: 
                   1150:        int status=pa_idna_to_unicode_4z(in, utf32, MAX_IDNA_LENGTH, 0);
                   1151:        if(status != IDNA_SUCCESS)
                   1152:                throw Exception("idna decode", new String(in), "decode failed: %s", pa_idna_strerror(status));
                   1153: 
                   1154:        for(utf32_end=utf32; *utf32_end; utf32_end++);
                   1155: 
                   1156:        char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
                   1157:        char *result_end = result;
                   1158: 
                   1159:        status=pa_convertUTF32toUTF8(&utf32_start, utf32_end, (UTF8**)&result_end, (UTF8*)(result+MAX_IDNA_LENGTH-1), strictConversion);
                   1160: 
                   1161:        if(status != conversionOK)
                   1162:                throw Exception("idna decode", new String(in), "utf conversion failed (%d)", status);
                   1163: 
                   1164:        *result_end='\0';
                   1165: 
                   1166:        if(!asked_charset.isUTF8())
1.295     moko     1167:                result = (char *)Charset::transcode(result, pa_UTF8_charset, asked_charset).cstr();
1.283     moko     1168: 
                   1169:        return result;
                   1170: }
1.292     moko     1171: /// must be last in this file
                   1172: #undef vsnprintf
                   1173: int pa_vsnprintf(char* b, size_t s, const char* f, va_list l) {
                   1174:        if(!s)
                   1175:                return 0;
                   1176: 
                   1177:        int r;
                   1178:        // note: on win32 & maybe somewhere else
                   1179:        // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
                   1180:        // http://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
                   1181:        --s;
                   1182: 
                   1183:        // clients do not check for negative 's', feature: ignore such prints
                   1184:        if((ssize_t)s<0)
                   1185:                return 0;
                   1186: 
                   1187: #ifdef _MSC_VER
                   1188:        // win32: if the number of bytes to write exceeds buffer, then count bytes are written and -1 is returned
                   1189:        r=_vsnprintf(b, s, f, l); 
                   1190:        if(r<0) 
                   1191:                r=s;
                   1192: #else
                   1193:        r=vsnprintf(b, s, f, l); 
                   1194:        /*
                   1195:        solaris: man vsnprintf
                   1196: 
                   1197:        The snprintf() function returns  the  number  of  characters
                   1198:        formatted, that is, the number of characters that would have
                   1199:        been written to the buffer if it were large enough.  If  the
                   1200:        value  of  n  is  0  on a call to snprintf(), an unspecified
                   1201:        value less than 1 is returned.
                   1202:        */
                   1203: 
                   1204:        if(r<0)
                   1205:                r=0;
                   1206:        else if((size_t)r>s)
                   1207:                r=s;
                   1208: #endif
                   1209:        b[r]=0;
                   1210:        return r;
                   1211: }
                   1212: 
                   1213: int pa_snprintf(char* b, size_t s, const char* f, ...) {
                   1214:        va_list l;
                   1215:        va_start(l, f); 
                   1216:        int r=pa_vsnprintf(b, s, f, l); 
                   1217:        va_end(l); 
                   1218:        return r;
                   1219: }
                   1220: 

E-mail: