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