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