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