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