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