Annotation of parser3/src/main/pa_common.C, revision 1.343
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.343 ! moko 26: volatile const char * IDENT_PA_COMMON_C="$Id: pa_common.C,v 1.342 2026/04/24 20:14:33 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.270 moko 514: if(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.126 paf 634: char* lsplit(char* string, char delim) {
1.229 misha 635: if(string) {
1.126 paf 636: char* v=strchr(string, delim);
1.8 paf 637: if(v) {
638: *v=0;
639: return v+1;
640: }
1.229 misha 641: }
642: return 0;
1.8 paf 643: }
644:
1.126 paf 645: char* lsplit(char* *string_ref, char delim) {
1.229 misha 646: char* result=*string_ref;
1.126 paf 647: char* next=lsplit(*string_ref, delim);
1.229 misha 648: *string_ref=next;
649: return result;
1.9 paf 650: }
651:
1.126 paf 652: char* rsplit(char* string, char delim) {
1.229 misha 653: if(string) {
1.126 paf 654: char* v=strrchr(string, delim);
1.18 paf 655: if(v) {
1.9 paf 656: *v=0;
657: return v+1;
658: }
1.229 misha 659: }
1.314 moko 660: return NULL;
661: }
662:
1.325 moko 663: void pa_strncpy(char *dst, const char *src, size_t n){
664: size_t left = n;
665:
666: if (left != 0 && src) {
667: while (--left != 0) {
668: if ((*dst++ = *src++) == '\0')
669: return;
670: }
671: }
672: if (n != 0)
673: *dst = '\0';
674: }
675:
1.314 moko 676: #define STRCAT_STEP(str, len) if(str) { memcpy(ptr, str, len); ptr += len; }
677:
678: char *pa_strcat(const char *a, const char *b, const char *c) {
679: size_t len_a = a ? strlen(a) : 0;
1.315 moko 680: size_t len_b = b ? strlen(b) : 0;
681: size_t len_c = c ? strlen(c) : 0;
1.314 moko 682: char *result=new(PointerFreeGC) char[len_a + len_b + len_c +1/*0*/];
683: char *ptr=result;
684: STRCAT_STEP(a, len_a);
685: STRCAT_STEP(b, len_b);
686: STRCAT_STEP(c, len_c);
687: *ptr='\0';
688: return result;
1.10 paf 689: }
690:
1.317 moko 691: const char *pa_filename(const char *path){
692: if(!path)
693: return NULL;
694: for(const char *c = path + strlen(path) - 1; c >= path; c--) {
695: if(*c == '/' || *c == '\\')
696: return c+1;
697: }
698: return path;
699: }
1.229 misha 700:
1.36 paf 701: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 702: #ifdef WIN32
1.187 paf 703: size_t to_write = size;
1.12 paf 704: do{
1.316 moko 705: int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 706: if(chunk_written<=0)
707: break;
708: size-=chunk_written;
1.36 paf 709: buf=((const char*)buf)+chunk_written;
1.316 moko 710: } while(size>0);
1.12 paf 711:
1.316 moko 712: fflush(stdout);
1.187 paf 713: return to_write-size;
1.12 paf 714: #else
1.316 moko 715: size_t result=fwrite(buf, 1, size, stdout);
716: fflush(stdout);
717: return result;
1.12 paf 718: #endif
1.2 paf 719: }
1.14 paf 720:
1.229 misha 721: enum EscapeState {
1.341 moko 722: EscapeRest,
723: EscapeFirst,
1.229 misha 724: EscapeSecond,
725: EscapeUnicode
726: };
727:
1.236 misha 728: // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually)
1.258 misha 729: char* unescape_chars(const char* cp, int len, Charset* charset, bool js){
1.236 misha 730: char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
1.336 moko 731: XMLByte* dst=(XMLByte *)s;
1.229 misha 732: EscapeState escapeState=EscapeRest;
733: uint escapedValue=0;
734: int srcPos=0;
1.230 misha 735: short int jsCnt=0;
1.236 misha 736: while(srcPos<len){
1.229 misha 737: uchar c=(uchar)cp[srcPos];
1.258 misha 738: if(c=='%' || (c=='\\' && js)){
1.229 misha 739: escapeState=EscapeFirst;
740: } else {
741: switch(escapeState) {
742: case EscapeRest:
1.286 moko 743: if(c=='+' && !js){
1.230 misha 744: *dst++=' ';
1.229 misha 745: } else {
1.230 misha 746: *dst++=c;
1.229 misha 747: }
748: break;
749: case EscapeFirst:
1.232 misha 750: if(charset && c=='u'){
1.229 misha 751: // escaped unicode value: %u0430
752: jsCnt=0;
753: escapedValue=0;
754: escapeState=EscapeUnicode;
755: } else {
1.231 misha 756: if(isxdigit(c)){
1.229 misha 757: escapedValue=hex_value[c] << 4;
758: escapeState=EscapeSecond;
759: } else {
1.230 misha 760: *dst++=c;
1.229 misha 761: escapeState=EscapeRest;
762: }
763: }
764: break;
765: case EscapeSecond:
1.231 misha 766: if(isxdigit(c)){
1.229 misha 767: escapedValue+=hex_value[c];
1.230 misha 768: *dst++=(char)escapedValue;
1.229 misha 769: }
770: escapeState=EscapeRest;
771: break;
772: case EscapeUnicode:
1.231 misha 773: if(isxdigit(c)){
1.229 misha 774: escapedValue=(escapedValue << 4) + hex_value[c];
775: if(++jsCnt==4){
1.230 misha 776: // transcode utf8 char to client charset (we can lost some chars here)
1.336 moko 777: charset->store_Char(dst, (XMLCh)escapedValue, '?');
1.229 misha 778: escapeState=EscapeRest;
779: }
780: } else {
781: // not full unicode value
782: escapeState=EscapeRest;
783: }
784: break;
785: }
786: }
787:
788: srcPos++;
789: }
790:
1.230 misha 791: *dst=0; // zero-termination
1.229 misha 792: return s;
793: }
1.24 paf 794:
1.268 misha 795: char *search_stop(char*& current, char cstop_at) {
796: // sanity check
797: if(!current)
798: return 0;
799:
800: // skip leading WS
801: while(*current==' ' || *current=='\t')
802: current++;
803: if(!*current)
804: return current=0;
805:
806: char *result=current;
807: if(char *pstop_at=strchr(current, cstop_at)) {
808: *pstop_at=0;
809: current=pstop_at+1;
810: } else
811: current=0;
812: return result;
813: }
814:
1.24 paf 815: #ifdef WIN32
1.126 paf 816: void back_slashes_to_slashes(char* s) {
1.24 paf 817: if(s)
818: for(; *s; s++)
819: if(*s=='\\')
1.126 paf 820: *s='/';
1.24 paf 821: }
822: #endif
1.41 paf 823:
1.232 misha 824: size_t strpos(const char *str, const char *substr) {
825: const char *p = strstr(str, substr);
826: return (p==0)?STRING_NOT_FOUND:p-str;
827: }
828:
1.326 moko 829: size_t remove_crlf(char* start, char* end) {
1.226 misha 830: char* from=start;
831: char* to=start;
832: bool skip=false;
833: while(from < end){
834: switch(*from){
835: case '\n':
836: case '\r':
837: case '\t':
838: case ' ':
839: if(!skip){
840: *to=' ';
841: to++;
842: skip=true;
843: }
844: break;
845: default:
846: if(from != to)
847: *to=*from;
848: to++;
849: skip=false;
1.69 parser 850: }
1.226 misha 851: from++;
852: }
853: return to-start;
1.91 paf 854: }
855:
1.279 moko 856: const char* hex_digits="0123456789ABCDEF";
857:
1.278 moko 858: const char* hex_string(unsigned char* bytes, size_t size, bool upcase) {
859: char *bytes_hex=new(PointerFreeGC) char [size*2/*byte->hh*/+1/*for zero-teminator*/];
860: unsigned char *src=bytes;
861: unsigned char *end=bytes+size;
862: char *dest=bytes_hex;
863:
1.279 moko 864: const char *hex=upcase? hex_digits : "0123456789abcdef";
1.278 moko 865:
866: for(; src<end; src++) {
867: *dest++=hex[*src/0x10];
868: *dest++=hex[*src%0x10];
869: }
870: *dest=0;
871:
872: return bytes_hex;
873: }
1.91 paf 874:
1.321 moko 875: ssize_t file_block_read(const int f, void* buffer, const size_t size){
876: ssize_t nCount = read(f, buffer, size);
1.221 misha 877: if (nCount < 0)
1.289 moko 878: throw Exception("file.read", 0, "read failed: %s (%d)", strerror(errno), errno);
1.221 misha 879: return nCount;
880: }
881:
1.278 moko 882: static unsigned long crc32Table[256];
883: static void InitCrc32Table()
884: {
885: if(crc32Table[1] == 0){
886: // This is the official polynomial used by CRC32 in PKZip.
887: // Often times the polynomial shown reversed as 0x04C11DB7.
888: static const unsigned long dwPolynomial = 0xEDB88320;
889:
890: for(int i = 0; i < 256; i++)
891: {
892: unsigned long dwCrc = i;
893: for(int j = 8; j > 0; j--)
894: {
895: if(dwCrc & 1)
896: dwCrc = (dwCrc >> 1) ^ dwPolynomial;
897: else
898: dwCrc >>= 1;
899: }
900: crc32Table[i] = dwCrc;
901: }
902: }
903: }
904:
905: inline void CalcCrc32(const unsigned char byte, unsigned long &crc32)
906: {
907: crc32 = ((crc32) >> 8) ^ crc32Table[(byte) ^ ((crc32) & 0x000000FF)];
908: }
909:
910:
1.297 moko 911: unsigned long pa_crc32(const char *in, size_t in_size){
1.218 misha 912: unsigned long crc32=0xFFFFFFFF;
1.220 misha 913:
1.240 misha 914: InitCrc32Table();
1.239 misha 915: for(size_t i = 0; i<in_size; i++)
916: CalcCrc32(in[i], crc32);
1.220 misha 917:
1.218 misha 918: return ~crc32;
919: }
920:
1.289 moko 921: static void file_crc32_file_action(struct stat& finfo, int f, const String&, void *context) {
1.218 misha 922: unsigned long& crc32=*static_cast<unsigned long *>(context);
923: if(finfo.st_size) {
924: InitCrc32Table();
1.220 misha 925: int nCount=0;
1.218 misha 926: do {
1.221 misha 927: unsigned char buffer[FILE_BUFFER_SIZE];
928: nCount = file_block_read(f, buffer, sizeof(buffer));
1.220 misha 929: for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
930: } while(nCount > 0);
1.218 misha 931: }
932: }
933:
1.297 moko 934: unsigned long pa_crc32(const String& file_spec){
1.278 moko 935: unsigned long crc32=0xFFFFFFFF;
936: file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
937: return ~crc32;
938: }
939:
940: // content-type: xxx; charset=WE-NEED-THIS
941: // content-type: xxx; charset="WE-NEED-THIS"
942: // content-type: xxx; charset="WE-NEED-THIS";
943: Charset* detect_charset(const char* content_type){
944: if(content_type){
1.291 moko 945: char* CONTENT_TYPE=str_upper(content_type);
1.278 moko 946:
947: if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
948: begin+=8; // skip "CHARSET="
949: char* end=0;
950: if(*begin && (*begin=='"' || *begin =='\'')){
951: char quote=*begin;
952: begin++;
953: end=(char*)strchr(begin, quote);
954: }
955: if(!end)
956: end=(char*)strchr(begin, ';');
957:
958: if(end)
959: *end=0; // terminator
960:
1.295 moko 961: return *begin ? &pa_charsets.get_direct(begin) : 0;
1.278 moko 962: }
963: }
964: return 0;
965: }
966:
1.301 moko 967: const UTF16* pa_utf16_encode(const char* in, Charset& source_charset){
1.302 moko 968: if(!in)
969: return 0;
1.301 moko 970:
1.302 moko 971: String::C sIn(in,strlen(in));
1.301 moko 972:
1.302 moko 973: UTF16* utf16=(UTF16*)pa_malloc_atomic(sIn.length*2+2);
974: UTF16* utf16_end=utf16;
1.301 moko 975:
1.302 moko 976: if(!source_charset.isUTF8())
977: sIn=Charset::transcode(sIn, source_charset, pa_UTF8_charset);
1.301 moko 978:
1.302 moko 979: int status=pa_convertUTF8toUTF16((const UTF8**)&sIn.str, (const UTF8*)(sIn.str+sIn.length), &utf16_end, utf16+sIn.length, strictConversion);
980: if(status != conversionOK)
981: throw Exception("utf-16 encode", new String(in), "utf-16 conversion failed (%d)", status);
1.301 moko 982:
1.302 moko 983: *utf16_end=0;
1.301 moko 984:
1.302 moko 985: return utf16;
1.301 moko 986: }
987:
988: const char* pa_utf16_decode(const UTF16* in, Charset& asked_charset){
989: if(!in)
990: return 0;
991:
992: const UTF16* utf16_start=in;
993: const UTF16* utf16_end;
994:
995: for(utf16_end=in; *utf16_end; utf16_end++);
996:
997: char *result = (char *)pa_malloc_atomic((utf16_end-in)*6+1);
998: char *result_end = result;
999:
1000: int status=pa_convertUTF16toUTF8(&utf16_start, utf16_end, (UTF8**)&result_end, (UTF8*)(result+(utf16_end-in)*6), strictConversion);
1001:
1002: if(status != conversionOK)
1003: throw Exception("utf-16 decode", 0, "utf conversion failed (%d)", status);
1004:
1005: *result_end='\0';
1006:
1.302 moko 1007: if(asked_charset.isUTF8())
1008: return result;
1.301 moko 1009:
1.302 moko 1010: return Charset::transcode(result, pa_UTF8_charset, asked_charset).cstr();
1.301 moko 1011: }
1.278 moko 1012:
1.283 moko 1013: static bool is_latin(const char *in){
1014: for(; *in; in++){
1015: if ((unsigned char)(*in) > 0x7F)
1016: return false;
1017: }
1018: return true;
1019: }
1020:
1021: #define MAX_IDNA_LENGTH 256
1022:
1.301 moko 1023: const char *pa_idna_encode(const char *in, Charset& source_charset){
1.283 moko 1024: if(!in || is_latin(in))
1025: return in;
1026:
1027: uint32_t utf32[MAX_IDNA_LENGTH];
1028: uint32_t *utf32_end=utf32;
1029:
1030: String::C sIn(in,strlen(in));
1031:
1032: if(!source_charset.isUTF8())
1.295 moko 1033: sIn=Charset::transcode(sIn, source_charset, pa_UTF8_charset);
1.283 moko 1034:
1035: int status=pa_convertUTF8toUTF32((const UTF8**)&sIn.str, (const UTF8*)(sIn.str+sIn.length), &utf32_end, utf32+MAX_IDNA_LENGTH-1, strictConversion);
1036: if(status != conversionOK)
1037: throw Exception("idna encode", new String(in), "utf conversion failed (%d)", status);
1038:
1039: *utf32_end=0;
1040:
1041: char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
1042: status=pa_idna_to_ascii_4z(utf32, result, MAX_IDNA_LENGTH, 0);
1043: if(status != IDNA_SUCCESS)
1044: throw Exception("idna encode", new String(in), "encode failed: %s", pa_idna_strerror(status));
1045:
1046: return result;
1047: }
1048:
1049: const char *pa_idna_decode(const char *in, Charset &asked_charset){
1050: if(!in || !(*in))
1051: return in;
1052:
1053: uint32_t utf32[MAX_IDNA_LENGTH];
1054: const uint32_t *utf32_start=utf32;
1055: uint32_t *utf32_end;
1056:
1057: int status=pa_idna_to_unicode_4z(in, utf32, MAX_IDNA_LENGTH, 0);
1058: if(status != IDNA_SUCCESS)
1059: throw Exception("idna decode", new String(in), "decode failed: %s", pa_idna_strerror(status));
1060:
1061: for(utf32_end=utf32; *utf32_end; utf32_end++);
1062:
1063: char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
1064: char *result_end = result;
1065:
1066: status=pa_convertUTF32toUTF8(&utf32_start, utf32_end, (UTF8**)&result_end, (UTF8*)(result+MAX_IDNA_LENGTH-1), strictConversion);
1067:
1068: if(status != conversionOK)
1069: throw Exception("idna decode", new String(in), "utf conversion failed (%d)", status);
1070:
1071: *result_end='\0';
1072:
1073: if(!asked_charset.isUTF8())
1.295 moko 1074: result = (char *)Charset::transcode(result, pa_UTF8_charset, asked_charset).cstr();
1.283 moko 1075:
1076: return result;
1077: }
1.292 moko 1078: /// must be last in this file
1079: #undef vsnprintf
1080: int pa_vsnprintf(char* b, size_t s, const char* f, va_list l) {
1081: if(!s)
1082: return 0;
1083:
1084: int r;
1085: // note: on win32 & maybe somewhere else
1086: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
1087: // http://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
1088: --s;
1089:
1090: // clients do not check for negative 's', feature: ignore such prints
1091: if((ssize_t)s<0)
1092: return 0;
1093:
1094: #ifdef _MSC_VER
1095: // win32: if the number of bytes to write exceeds buffer, then count bytes are written and -1 is returned
1096: r=_vsnprintf(b, s, f, l);
1097: if(r<0)
1098: r=s;
1099: #else
1100: r=vsnprintf(b, s, f, l);
1101: /*
1102: solaris: man vsnprintf
1103:
1104: The snprintf() function returns the number of characters
1105: formatted, that is, the number of characters that would have
1106: been written to the buffer if it were large enough. If the
1107: value of n is 0 on a call to snprintf(), an unspecified
1108: value less than 1 is returned.
1109: */
1110:
1111: if(r<0)
1112: r=0;
1113: else if((size_t)r>s)
1114: r=s;
1115: #endif
1116: b[r]=0;
1117: return r;
1118: }
1119:
1120: int pa_snprintf(char* b, size_t s, const char* f, ...) {
1121: va_list l;
1122: va_start(l, f);
1123: int r=pa_vsnprintf(b, s, f, l);
1124: va_end(l);
1125: return r;
1126: }
1127:
E-mail: