Annotation of parser3/src/main/pa_common.C, revision 1.245
1.15 paf 1: /** @file
1.16 paf 2: Parser: commonly functions.
3:
1.242 misha 4: Copyright(c) 2001-2009 ArtLebedev Group (http://www.artlebedev.com)
1.101 paf 5: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.16 paf 6:
1.210 paf 7: * BASE64 part
8: * Authors: Michael Zucchi <notzed@ximian.com>
9: * Jeffrey Stedfast <fejj@ximian.com>
10: *
11: * Copyright 2000-2004 Ximian, Inc. (www.ximian.com)
12: *
13: * This program is free software; you can redistribute it and/or modify
14: * it under the terms of the GNU General Public License as published by
15: * the Free Software Foundation; either version 2 of the License, or
16: * (at your option) any later version.
17: *
18: * This program is distributed in the hope that it will be useful,
19: * but WITHOUT ANY WARRANTY; without even the implied warranty of
20: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21: * GNU General Public License for more details.
22: *
23: * You should have received a copy of the GNU General Public License
24: * along with this program; if not, write to the Free Software
25: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
26: *
27: */
28:
1.245 ! misha 29: static const char * const IDENT_COMMON_C="$Date: 2009-05-13 07:35:41 $";
1.1 paf 30:
31: #include "pa_common.h"
1.4 paf 32: #include "pa_exception.h"
1.154 paf 33: #include "pa_hash.h"
1.14 paf 34: #include "pa_globals.h"
1.154 paf 35: #include "pa_charsets.h"
1.214 paf 36: #include "pa_http.h"
1.223 misha 37: #include "pa_request_charsets.h"
1.237 misha 38: #include "pcre.h"
1.241 misha 39: #include "pa_request.h"
1.98 paf 40:
1.93 paf 41: // some maybe-undefined constants
42:
1.82 paf 43: #ifndef _O_TEXT
44: # define _O_TEXT 0
45: #endif
46: #ifndef _O_BINARY
47: # define _O_BINARY 0
1.47 paf 48: #endif
1.80 paf 49:
1.138 paf 50: #ifdef HAVE_FTRUNCATE
51: # define PA_O_TRUNC 0
52: #else
53: # ifdef _O_TRUNC
54: # define PA_O_TRUNC _O_TRUNC
55: # else
56: # error you must have either ftruncate function or _O_TRUNC bit declared
57: # endif
1.154 paf 58: #endif
1.176 paf 59:
1.154 paf 60: // defines for globals
61:
62: #define FILE_STATUS_NAME "status"
63:
64: // globals
65:
66: const String file_status_name(FILE_STATUS_NAME);
67:
68: // functions
1.127 paf 69:
1.154 paf 70: void fix_line_breaks(char *str, size_t& length) {
1.87 paf 71: //_asm int 3;
1.154 paf 72: const char* const eob=str+length;
73: char* dest=str;
1.72 parser 74: // fix DOS: \r\n -> \n
75: // fix Macintosh: \r -> \n
1.154 paf 76: char* bol=str;
1.137 paf 77: while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72 parser 78: size_t len=eol-bol;
79: if(dest!=bol)
1.126 paf 80: memcpy(dest, bol, len);
1.72 parser 81: dest+=len;
1.126 paf 82: *dest++='\n';
1.72 parser 83:
1.126 paf 84: if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72 parser 85: bol=eol+2;
1.154 paf 86: length--;
1.126 paf 87: } else // \r, not \n = Macintosh
1.72 parser 88: bol=eol+1;
89: }
1.154 paf 90: // last piece without \r
1.72 parser 91: if(dest!=bol)
1.126 paf 92: memcpy(dest, bol, eob-bol);
1.154 paf 93: str[length]=0; // terminating
1.72 parser 94: }
1.18 paf 95:
1.154 paf 96: char* file_read_text(Request_charsets& charsets,
1.229 misha 97: const String& file_spec,
98: bool fail_on_read_problem,
1.234 misha 99: HashStringValue* params,
100: bool transcode_result) {
1.154 paf 101: File_read_result file=
1.234 misha 102: file_read(charsets, file_spec, true, params, fail_on_read_problem, 0, 0, 0, transcode_result);
1.154 paf 103: return file.success?file.str:0;
1.126 paf 104: }
105:
1.241 misha 106: char* file_load_text(Request& r,
107: const String& file_spec,
108: bool fail_on_read_problem,
109: HashStringValue* params,
110: bool transcode_result) {
111: File_read_result file=
112: file_load(r, file_spec, true, params, fail_on_read_problem, 0, 0, 0, transcode_result);
113: return file.success?file.str:0;
114: }
115:
1.206 paf 116: /// these options were handled but not checked elsewhere, now check them
1.239 misha 117: int pa_get_valid_file_options_count(HashStringValue& options) {
1.206 paf 118: int result=0;
119: if(options.get(PA_SQL_LIMIT_NAME))
120: result++;
121: if(options.get(PA_SQL_OFFSET_NAME))
122: result++;
123: if(options.get(PA_COLUMN_SEPARATOR_NAME))
124: result++;
125: if(options.get(PA_COLUMN_ENCLOSER_NAME))
126: result++;
1.223 misha 127: if(options.get(PA_CHARSET_NAME))
128: result++;
1.206 paf 129: return result;
130: }
131:
1.123 paf 132: #ifndef DOXYGEN
133: struct File_read_action_info {
1.154 paf 134: char **data; size_t *data_size;
1.188 paf 135: char* buf; size_t offset; size_t count;
1.126 paf 136: };
1.123 paf 137: #endif
1.154 paf 138: static void file_read_action(
1.229 misha 139: struct stat& finfo,
140: int f,
141: const String& file_spec, const char* /*fname*/, bool as_text,
142: void *context) {
1.126 paf 143: File_read_action_info& info=*static_cast<File_read_action_info *>(context);
1.188 paf 144: size_t to_read_size=info.count;
145: if(!to_read_size)
146: to_read_size=(size_t)finfo.st_size;
147: assert( !(info.buf && as_text) );
148: if(to_read_size) {
149: if(info.offset)
150: lseek(f, info.offset, SEEK_SET);
151: *info.data=info.buf
152: ? info.buf
153: : new(PointerFreeGC) char[to_read_size+(as_text?1:0)];
1.126 paf 154: *info.data_size=(size_t)read(f, *info.data, to_read_size);
1.123 paf 155:
156: if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.238 misha 157: throw Exception("file.read",
1.123 paf 158: &file_spec,
1.173 paf 159: "read failed: actually read %u bytes count not in [0..%u] valid range",
1.126 paf 160: *info.data_size, to_read_size);
1.123 paf 161: } else { // empty file
1.209 paf 162: // for both, text and binary: for text we need that terminator, for binary we need nonzero pointer to be able to save such files
163: *info.data=new(PointerFreeGC) char[1];
164: *(char*)(*info.data)=0;
1.123 paf 165: *info.data_size=0;
166: return;
167: }
1.126 paf 168: }
1.241 misha 169:
1.154 paf 170: File_read_result file_read(Request_charsets& charsets, const String& file_spec,
1.229 misha 171: bool as_text, HashStringValue *params,
172: bool fail_on_read_problem,
1.234 misha 173: char* buf, size_t offset, size_t count, bool transcode_text_result) {
1.167 paf 174: File_read_result result={false, 0, 0, 0};
1.241 misha 175: if(params){
176: int valid_options=pa_get_valid_file_options_count(*params);
177: if(valid_options!=params->count())
1.224 misha 178: throw Exception(PARSER_RUNTIME,
1.203 paf 179: 0,
1.241 misha 180: "invalid option passed");
181: }
1.203 paf 182:
1.241 misha 183: File_read_action_info info={&result.str, &result.length, buf, offset, count};
1.161 paf 184:
1.241 misha 185: result.success=file_read_action_under_lock(file_spec,
186: "read", file_read_action, &info,
187: as_text, fail_on_read_problem);
1.223 misha 188:
1.241 misha 189: if(as_text){
190: if(result.success){
1.236 misha 191: if(result.length>=3 && strncmp(result.str, "\xEF\xBB\xBF", 3)==0){
1.240 misha 192: // skip UTF-8 signature (BOM code)
1.236 misha 193: result.str+=3;
194: result.length-=3;
195: }
196:
197: if(result.length && transcode_text_result && params){ // must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
1.240 misha 198: if(Value* vcharset_name=params->get(PA_CHARSET_NAME)){
1.236 misha 199: Charset asked_charset=::charsets.get(vcharset_name->as_string().
200: change_case(charsets.source(), String::CC_UPPER));
201:
202: String::C body=String::C(result.str, result.length);
203: body=Charset::transcode(body, asked_charset, charsets.source());
1.123 paf 204:
1.236 misha 205: result.str=const_cast<char*>(body.str); // hacking a little
206: result.length=body.length;
207: }
1.131 paf 208: }
209: }
1.241 misha 210: if(result.length)
211: fix_line_breaks(result.str, result.length);
1.123 paf 212: }
1.241 misha 213:
214: return result;
215: }
216:
217: File_read_result file_load(Request& r, const String& file_spec,
218: bool as_text, HashStringValue *params,
219: bool fail_on_read_problem,
220: char* buf, size_t offset, size_t count, bool transcode_text_result) {
221:
222: File_read_result result={false, 0, 0, 0};
223: if(file_spec.starts_with("http://")) {
224: if(offset || count)
225: throw Exception(PARSER_RUNTIME,
226: 0,
227: "offset and load options are not supported for HTTP:// file load");
228:
229: // fail on read problem
230: File_read_http_result http=pa_internal_file_read_http(r, file_spec, as_text, params, transcode_text_result);
231: result.success=true;
232: result.str=http.str;
233: result.length=http.length;
234: result.headers=http.headers;
235: } else
236: result=
237: file_read(r.charsets, file_spec, as_text, params, fail_on_read_problem, buf, offset, count, transcode_text_result);
1.126 paf 238:
239: return result;
1.123 paf 240: }
241:
1.154 paf 242: #ifdef PA_SAFE_MODE
243: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) {
244: if(finfo.st_uid/*foreign?*/!=geteuid()
245: && finfo.st_gid/*foreign?*/!=getegid())
1.224 misha 246: throw Exception(PARSER_RUNTIME,
1.154 paf 247: &file_spec,
248: "parser is in safe mode: "
249: "reading files of foreign group and user disabled "
250: "[recompile parser with --disable-safe-mode configure option], "
251: "actual filename '%s', "
252: "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",
253: fname,
254: finfo.st_uid, geteuid(),
255: finfo.st_gid, getegid());
256: }
257: #endif
1.149 paf 258:
1.154 paf 259: bool file_read_action_under_lock(const String& file_spec,
1.126 paf 260: const char* action_name, File_read_action action, void *context,
261: bool as_text,
1.123 paf 262: bool fail_on_read_problem) {
1.154 paf 263: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.33 paf 264: int f;
265:
266: // first open, next stat:
1.45 paf 267: // directory update of NTFS hard links performed on open.
1.33 paf 268: // ex:
269: // a.html:^test[] and b.html hardlink to a.html
270: // user inserts ! before ^test in a.html
1.126 paf 271: // directory entry of b.html in NTFS not updated at once,
1.35 paf 272: // they delay update till open, so we would receive "!^test[" string
273: // if would do stat, next open.
1.123 paf 274: // later: it seems, even this does not help sometimes
1.229 misha 275: if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123 paf 276: try {
1.162 paf 277: if(pa_lock_shared_blocking(f)!=0)
1.126 paf 278: throw Exception("file.lock",
1.123 paf 279: &file_spec,
280: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 281: strerror(errno), errno, fname);
1.123 paf 282:
1.124 paf 283: struct stat finfo;
284: if(stat(fname, &finfo)!=0)
285: throw Exception("file.missing", // hardly possible: we just opened it OK
286: &file_spec,
287: "stat failed: %s (%d), actual filename '%s'",
1.154 paf 288: strerror(errno), errno, fname);
1.124 paf 289:
1.140 paf 290: #ifdef PA_SAFE_MODE
1.149 paf 291: check_safe_mode(finfo, file_spec, fname);
1.105 paf 292: #endif
1.32 paf 293:
1.154 paf 294: action(finfo, f, file_spec, fname, as_text, context);
1.123 paf 295: } catch(...) {
1.162 paf 296: pa_unlock(f);close(f);
1.123 paf 297: if(fail_on_read_problem)
1.154 paf 298: rethrow;
1.123 paf 299: return false;
300: }
1.87 paf 301:
1.162 paf 302: pa_unlock(f);close(f);
1.72 parser 303: return true;
1.229 misha 304: } else {
1.118 paf 305: if(fail_on_read_problem)
1.126 paf 306: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.118 paf 307: &file_spec,
1.123 paf 308: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 309: action_name, strerror(errno), errno, fname);
1.118 paf 310: return false;
311: }
1.8 paf 312: }
313:
1.202 paf 314: void create_dir_for_file(const String& file_spec) {
1.63 parser 315: size_t pos_after=1;
1.154 paf 316: size_t pos_before;
317: while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
318: mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775);
1.63 parser 319: pos_after=pos_before+1;
320: }
321: }
322:
1.98 paf 323: bool file_write_action_under_lock(
1.28 paf 324: const String& file_spec,
1.225 misha 325: const char* action_name,
326: File_write_action action,
327: void *context,
1.126 paf 328: bool as_text,
329: bool do_append,
330: bool do_block,
1.110 paf 331: bool fail_on_lock_problem) {
1.154 paf 332: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.28 paf 333: int f;
1.80 paf 334: if(access(fname, W_OK)!=0) // no
1.126 paf 335: create_dir_for_file(file_spec);
1.50 paf 336:
1.80 paf 337: if((f=open(fname,
338: O_CREAT|O_RDWR
339: |(as_text?_O_TEXT:_O_BINARY)
1.138 paf 340: |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162 paf 341: if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126 paf 342: Exception e("file.lock",
1.110 paf 343: &file_spec,
344: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 345: strerror(errno), errno, fname);
1.126 paf 346: close(f);
1.110 paf 347: if(fail_on_lock_problem)
348: throw e;
1.98 paf 349: return false;
350: }
1.96 paf 351:
1.158 paf 352: try {
1.126 paf 353: action(f, context);
1.158 paf 354: } catch(...) {
1.138 paf 355: #ifdef HAVE_FTRUNCATE
1.104 paf 356: if(!do_append)
1.125 paf 357: ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138 paf 358: #endif
1.162 paf 359: pa_unlock(f);close(f);
1.154 paf 360: rethrow;
1.158 paf 361: }
1.80 paf 362:
1.138 paf 363: #ifdef HAVE_FTRUNCATE
1.104 paf 364: if(!do_append)
1.125 paf 365: 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 366: #endif
1.162 paf 367: pa_unlock(f);close(f);
1.98 paf 368: return true;
1.80 paf 369: } else
1.126 paf 370: throw Exception(errno==EACCES?"file.access":0,
1.80 paf 371: &file_spec,
1.96 paf 372: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 373: action_name, strerror(errno), errno, fname);
1.96 paf 374: // here should be nothing, see rethrow above
375: }
376:
377: #ifndef DOXYGEN
378: struct File_write_action_info {
1.154 paf 379: const char* str; size_t length;
1.126 paf 380: };
1.96 paf 381: #endif
382: static void file_write_action(int f, void *context) {
1.126 paf 383: File_write_action_info& info=*static_cast<File_write_action_info *>(context);
1.154 paf 384: if(info.length) {
385: int written=write(f, info.str, info.length);
1.116 paf 386: if(written<0)
1.238 misha 387: throw Exception("file.access",
1.126 paf 388: 0,
389: "write failed: %s (%d)", strerror(errno), errno);
1.113 paf 390: }
1.96 paf 391: }
392: void file_write(
393: const String& file_spec,
1.154 paf 394: const char* data, size_t size,
1.126 paf 395: bool as_text,
1.96 paf 396: bool do_append) {
1.126 paf 397: File_write_action_info info={data, size};
1.225 misha 398:
1.98 paf 399: file_write_action_under_lock(
1.154 paf 400: file_spec,
1.225 misha 401: "write",
402: file_write_action,
403: &info,
1.154 paf 404: as_text,
405: do_append);
1.30 paf 406: }
407:
1.63 parser 408: // throws nothing! [this is required in file_move & file_delete]
1.50 paf 409: static void rmdir(const String& file_spec, size_t pos_after) {
1.154 paf 410: size_t pos_before;
411: if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126 paf 412: rmdir(file_spec, pos_before+1);
1.50 paf 413:
1.154 paf 414: rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC));
1.50 paf 415: }
1.239 misha 416:
1.164 paf 417: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.154 paf 418: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.54 parser 419: if(unlink(fname)!=0)
1.164 paf 420: if(fail_on_problem)
1.126 paf 421: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.93 paf 422: &file_spec,
423: "unlink failed: %s (%d), actual filename '%s'",
1.154 paf 424: strerror(errno), errno, fname);
1.93 paf 425: else
426: return false;
1.50 paf 427:
1.126 paf 428: rmdir(file_spec, 1);
1.93 paf 429: return true;
1.60 parser 430: }
1.239 misha 431:
1.95 paf 432: void file_move(const String& old_spec, const String& new_spec) {
1.154 paf 433: const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC);
434: const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC);
1.63 parser 435:
1.126 paf 436: create_dir_for_file(new_spec);
1.63 parser 437:
1.60 parser 438: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 439: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.60 parser 440: &old_spec,
441: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.154 paf 442: strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 443:
1.126 paf 444: rmdir(old_spec, 1);
1.31 paf 445: }
446:
1.51 paf 447:
1.126 paf 448: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 449: struct stat lfinfo;
450: bool result=stat(fname, &lfinfo)==0;
451: if(afinfo)
452: *afinfo=lfinfo;
453: return result;
1.119 paf 454: }
455:
456: bool entry_exists(const String& file_spec) {
1.154 paf 457: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.126 paf 458: return entry_exists(fname, 0);
1.118 paf 459: }
460:
1.51 paf 461: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154 paf 462: char* fname=file_spec.cstrm(String::L_FILE_SPEC);
1.120 paf 463: if(need_dir) {
1.126 paf 464: size_t size=strlen(fname);
1.120 paf 465: while(size) {
1.126 paf 466: char c=fname[size-1];
1.120 paf 467: if(c=='/' || c=='\\')
468: fname[--size]=0;
469: else
470: break;
471: }
472: }
1.51 paf 473: struct stat finfo;
1.118 paf 474: if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109 paf 475: bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51 paf 476: return is_dir==need_dir;
477: }
478: return false;
479: }
1.239 misha 480:
1.215 paf 481: bool file_exist(const String& file_spec) {
1.126 paf 482: return entry_readable(file_spec, false);
1.51 paf 483: }
1.239 misha 484:
1.215 paf 485: bool dir_exists(const String& file_spec) {
1.126 paf 486: return entry_readable(file_spec, true);
1.65 parser 487: }
1.239 misha 488:
1.215 paf 489: const String* file_exist(const String& path, const String& name) {
1.154 paf 490: String& result=*new String(path);
491: result << "/";
492: result << name;
1.215 paf 493: return file_exist(result)?&result:0;
1.43 paf 494: }
1.239 misha 495:
1.43 paf 496: bool file_executable(const String& file_spec) {
1.239 misha 497: return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44 paf 498: }
499:
1.64 parser 500: bool file_stat(const String& file_spec,
1.229 misha 501: size_t& rsize,
502: time_t& ratime,
503: time_t& rmtime,
504: time_t& rctime,
505: bool fail_on_read_problem) {
1.154 paf 506: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
507: struct stat finfo;
1.44 paf 508: if(stat(fname, &finfo)!=0)
1.64 parser 509: if(fail_on_read_problem)
1.126 paf 510: throw Exception("file.missing",
1.67 parser 511: &file_spec,
512: "getting file size failed: %s (%d), real filename '%s'",
1.154 paf 513: strerror(errno), errno, fname);
1.64 parser 514: else
515: return false;
1.58 parser 516: rsize=finfo.st_size;
517: ratime=finfo.st_atime;
518: rmtime=finfo.st_mtime;
519: rctime=finfo.st_ctime;
1.64 parser 520: return true;
1.18 paf 521: }
522:
1.126 paf 523: char* getrow(char* *row_ref, char delim) {
1.229 misha 524: char* result=*row_ref;
525: if(result) {
1.126 paf 526: *row_ref=strchr(result, delim);
1.8 paf 527: if(*row_ref)
528: *((*row_ref)++)=0;
529: else if(!*result)
530: return 0;
1.229 misha 531: }
532: return result;
1.8 paf 533: }
534:
1.126 paf 535: char* lsplit(char* string, char delim) {
1.229 misha 536: if(string) {
1.126 paf 537: char* v=strchr(string, delim);
1.8 paf 538: if(v) {
539: *v=0;
540: return v+1;
541: }
1.229 misha 542: }
543: return 0;
1.8 paf 544: }
545:
1.126 paf 546: char* lsplit(char* *string_ref, char delim) {
1.229 misha 547: char* result=*string_ref;
1.126 paf 548: char* next=lsplit(*string_ref, delim);
1.229 misha 549: *string_ref=next;
550: return result;
1.9 paf 551: }
552:
1.126 paf 553: char* rsplit(char* string, char delim) {
1.229 misha 554: if(string) {
1.126 paf 555: char* v=strrchr(string, delim);
1.18 paf 556: if(v) {
1.9 paf 557: *v=0;
558: return v+1;
559: }
1.229 misha 560: }
561: return NULL;
1.10 paf 562: }
563:
1.229 misha 564:
565: // format: %[flags][width][.precision]type http://msdn.microsoft.com/ru-ru/library/56e442dc(en-us,VS.80).aspx
566: // flags: '-', '+', ' ', '#', '0' http://msdn.microsoft.com/ru-ru/library/8aky45ct(en-us,VS.80).aspx
567: // width, precision: non negative decimal number
568: enum FormatType {
569: FormatInvalid,
570: FormatInt,
571: FormatUInt,
572: FormatDouble
573: };
574: FormatType format_type(char* fmt){
575: enum FormatState {
576: Percent,
577: Flags,
578: Width,
579: Precision,
580: Done
581: } state=Percent;
582:
583: FormatType result=FormatInvalid;
584:
585: char* pos=fmt;
586: while(char c=*(pos++)){
587: switch(state){
588: case Percent:
589: if(c=='%'){
590: state=Flags;
591: } else {
592: return FormatInvalid; // 1st char must be '%' only
593: }
594: break;
595: case Flags:
596: if(strchr("-+ #0", c)!=0){
597: break;
598: }
599: // go to the next step
600: case Width:
601: if(c=='.'){
602: state=Precision;
603: break;
604: }
605: // go to the next step
606: case Precision:
607: if(c>='0' && c<='9'){
608: if(state == Flags) state=Width; // no more flags
609: break;
610: } else if(c=='d' || c=='i'){
611: result=FormatInt;
612: } else if(strchr("feEgG", c)!=0){
613: result=FormatDouble;
614: } else if(strchr("uoxX", c)!=0){
615: result=FormatUInt;
616: } else {
617: return FormatInvalid; // invalid char
618: }
619: state=Done;
620: break;
621: case Done:
622: return FormatInvalid; // no chars allowed after 'type'
623: }
624: }
625: return result;
626: }
627:
628:
1.154 paf 629: const char* format(double value, char* fmt) {
1.229 misha 630: char local_buf[MAX_NUMBER];
1.235 misha 631: int size=-1;
1.229 misha 632:
633: if(fmt && strlen(fmt)){
634: switch(format_type(fmt)){
635: case FormatDouble:
636: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
637: break;
638: case FormatInt:
639: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
640: break;
641: case FormatUInt:
1.126 paf 642: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.229 misha 643: break;
644: case FormatInvalid:
645: throw Exception(PARSER_RUNTIME,
646: 0,
647: "Incorrect format string '%s' was specified.", fmt);
648: }
649: } else
650: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
651:
652: if(size < 0 || size >= MAX_NUMBER-1){ // on win32 we manually reduce max size while printing
653: throw Exception(PARSER_RUNTIME,
654: 0,
655: "Error occure white executing snprintf with format string '%s'.", fmt);
656: }
657:
1.235 misha 658: return pa_strdup(local_buf, (size_t)size);
1.12 paf 659: }
660:
1.36 paf 661: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 662: #ifdef WIN32
1.187 paf 663: size_t to_write = size;
1.12 paf 664: do{
1.154 paf 665: int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 666: if(chunk_written<=0)
667: break;
668: size-=chunk_written;
1.36 paf 669: buf=((const char*)buf)+chunk_written;
1.126 paf 670: } while(size>0);
1.12 paf 671:
1.187 paf 672: return to_write-size;
1.12 paf 673: #else
1.126 paf 674: return fwrite(buf, 1, size, stdout);
1.12 paf 675: #endif
1.2 paf 676: }
1.14 paf 677:
1.229 misha 678: enum EscapeState {
679: EscapeRest,
680: EscapeFirst,
681: EscapeSecond,
682: EscapeUnicode
683: };
684:
1.236 misha 685: // @todo prescan for reduce required size (unescaped sting in 1 byte charset requires less memory usually)
686: char* unescape_chars(const char* cp, int len, Charset* charset, bool ignore_plus){
687: char* s=new(PointerFreeGC) char[len+1]; // must be enough (%uXXXX==6 bytes, max utf-8 char length==6 bytes)
1.230 misha 688: char* dst=s;
1.229 misha 689: EscapeState escapeState=EscapeRest;
690: uint escapedValue=0;
691: int srcPos=0;
1.230 misha 692: short int jsCnt=0;
1.236 misha 693: while(srcPos<len){
1.229 misha 694: uchar c=(uchar)cp[srcPos];
695: if(c=='%'){
696: escapeState=EscapeFirst;
697: } else {
698: switch(escapeState) {
699: case EscapeRest:
1.236 misha 700: if(!ignore_plus && c=='+'){
1.230 misha 701: *dst++=' ';
1.229 misha 702: } else {
1.230 misha 703: *dst++=c;
1.229 misha 704: }
705: break;
706: case EscapeFirst:
1.232 misha 707: if(charset && c=='u'){
1.229 misha 708: // escaped unicode value: %u0430
709: jsCnt=0;
710: escapedValue=0;
711: escapeState=EscapeUnicode;
712: } else {
1.231 misha 713: if(isxdigit(c)){
1.229 misha 714: escapedValue=hex_value[c] << 4;
715: escapeState=EscapeSecond;
716: } else {
1.230 misha 717: *dst++=c;
1.229 misha 718: escapeState=EscapeRest;
719: }
720: }
721: break;
722: case EscapeSecond:
1.231 misha 723: if(isxdigit(c)){
1.229 misha 724: escapedValue+=hex_value[c];
1.230 misha 725: *dst++=(char)escapedValue;
1.229 misha 726: }
727: escapeState=EscapeRest;
728: break;
729: case EscapeUnicode:
1.231 misha 730: if(isxdigit(c)){
1.229 misha 731: escapedValue=(escapedValue << 4) + hex_value[c];
732: if(++jsCnt==4){
1.230 misha 733: // transcode utf8 char to client charset (we can lost some chars here)
1.232 misha 734: charset->store_Char((XMLByte*&)dst, (XMLCh)escapedValue, '?');
1.229 misha 735: escapeState=EscapeRest;
736: }
737: } else {
738: // not full unicode value
739: escapeState=EscapeRest;
740: }
741: break;
742: }
743: }
744:
745: srcPos++;
746: }
747:
1.230 misha 748: *dst=0; // zero-termination
1.229 misha 749: return s;
750: }
1.24 paf 751:
752: #ifdef WIN32
1.126 paf 753: void back_slashes_to_slashes(char* s) {
1.24 paf 754: if(s)
755: for(; *s; s++)
756: if(*s=='\\')
1.126 paf 757: *s='/';
1.24 paf 758: }
1.42 paf 759: /*
1.126 paf 760: void slashes_to_back_slashes(char* s) {
1.42 paf 761: if(s)
762: for(; *s; s++)
763: if(*s=='/')
1.126 paf 764: *s='\\';
1.42 paf 765: }
766: */
1.24 paf 767: #endif
1.41 paf 768:
1.231 misha 769: bool StrStartFromNC(const char* str, const char* substr, bool equal){
1.41 paf 770: while(true) {
1.231 misha 771: if(!(*substr)){
772: if(!(*str))
1.41 paf 773: return true;
774: else
1.231 misha 775: return !equal;
776: }
777: if(!(*str))
778: return false;
779: if(isalpha((unsigned char)*str)) {
780: if(tolower((unsigned char)*str)!=tolower((unsigned char)*substr))
1.41 paf 781: return false;
1.231 misha 782: } else if((*str) != (*substr))
1.41 paf 783: return false;
1.231 misha 784: str++;
785: substr++;
1.41 paf 786: }
1.57 parser 787: }
788:
1.232 misha 789: size_t strpos(const char *str, const char *substr) {
790: const char *p = strstr(str, substr);
791: return (p==0)?STRING_NOT_FOUND:p-str;
792: }
793:
794: // content-type: xxx; charset=WE-NEED-THIS
795: // content-type: xxx; charset="WE-NEED-THIS"
796: // content-type: xxx; charset="WE-NEED-THIS";
1.245 ! misha 797: Charset* detect_charset(const char* content_type, bool already_uppercased){
1.233 misha 798: if(content_type){
1.245 ! misha 799: char* CONTENT_TYPE=pa_strdup(content_type);
! 800: if(!already_uppercased)
! 801: for(char *p=CONTENT_TYPE; *p; p++)
! 802: *p=(char)toupper((unsigned char)*p);
1.233 misha 803:
804: if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
805: begin+=8; // skip "CHARSET="
806: char* end=0;
807: if(*begin && (*begin=='"' || *begin =='\'')){
808: char quote=*begin;
809: begin++;
810: end=(char*)strchr(begin, quote);
811: }
812: if(!end)
813: end=(char*)strchr(begin, ';');
814:
1.244 misha 815: if(end)
1.233 misha 816: *end=0; // terminator
817:
1.245 ! misha 818: return *begin?&charsets.get(begin):0;
1.232 misha 819: }
820: }
821: return 0;
822: }
823:
824:
1.84 paf 825: static bool isLeap(int year) {
1.229 misha 826: return !(
827: (year % 4) || ((year % 400) && !(year % 100))
828: );
1.57 parser 829: }
830:
831: int getMonthDays(int year, int month) {
1.220 misha 832: static int monthDays[]={
1.229 misha 833: 31,
834: 28,
835: 31,
836: 30,
837: 31,
838: 30,
839: 31,
840: 31,
841: 30,
842: 31,
843: 30,
844: 31
845: };
1.228 misha 846: return (month == 1 /* january -- 0 */ && isLeap(year)) ? 29 : monthDays[month];
1.41 paf 847: }
1.69 parser 848:
1.226 misha 849: int remove_crlf(char* start, char* end) {
850: char* from=start;
851: char* to=start;
852: bool skip=false;
853: while(from < end){
854: switch(*from){
855: case '\n':
856: case '\r':
857: case '\t':
858: case ' ':
859: if(!skip){
860: *to=' ';
861: to++;
862: skip=true;
863: }
864: break;
865: default:
866: if(from != to)
867: *to=*from;
868: to++;
869: skip=false;
1.69 parser 870: }
1.226 misha 871: from++;
872: }
873: return to-start;
1.91 paf 874: }
875:
876:
877: /// must be last in this file
878: #undef vsnprintf
1.126 paf 879: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 880: if(!s)
881: return 0;
882:
883: int r;
884: // note: on win32& maybe somewhere else
885: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
886: --s;
1.172 paf 887:
888: // clients do not check for negative 's', feature: ignore such prints
889: if((ssize_t)s<0)
890: return 0;
891:
1.91 paf 892: #if _MSC_VER
893: /*
894: win32:
895: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
896:
1.154 paf 897: if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91 paf 898: */
1.126 paf 899: r=_vsnprintf(b, s, f, l);
1.91 paf 900: if(r<0)
901: r=s;
902: #else
1.126 paf 903: r=vsnprintf(b, s, f, l);
1.91 paf 904: /*
905: solaris:
906: man vsnprintf
907:
908: The snprintf() function returns the number of characters
909: formatted, that is, the number of characters that would have
910: been written to the buffer if it were large enough. If the
911: value of n is 0 on a call to snprintf(), an unspecified
912: value less than 1 is returned.
913: */
914:
915: if(r<0)
916: r=0;
1.167 paf 917: else if((size_t)r>s)
1.91 paf 918: r=s;
919: #endif
920: b[r]=0;
921: return r;
922: }
923:
1.126 paf 924: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 925: va_list l;
1.241 misha 926: va_start(l, f);
927: int r=__vsnprintf(b, s, f, l);
928: va_end(l);
1.91 paf 929: return r;
1.178 paf 930: }
931:
932: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
933: /*
934: * Authors: Michael Zucchi <notzed@helixcode.com>
935: * Jeffrey Stedfast <fejj@helixcode.com>
936: *
937: * Copyright 2000 Helix Code, Inc. (www.helixcode.com)
938: *
939: * This program is free software; you can redistribute it and/or modify
940: * it under the terms of the GNU General Public License as published by
941: * the Free Software Foundation; either version 2 of the License, or
942: * (at your option) any later version.
943: *
944: * This program is distributed in the hope that it will be useful,
945: * but WITHOUT ANY WARRANTY; without even the implied warranty of
946: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
947: * GNU General Public License for more details.
948: *
949: * You should have received a copy of the GNU General Public License
950: * along with this program; if not, write to the Free Software
951: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
952: *
953: */
954: static char *base64_alphabet =
955: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
956:
957: /**
958: * g_mime_utils_base64_encode_step:
959: * @in: input stream
960: * @inlen: length of the input
961: * @out: output string
962: * @state: holds the number of bits that are stored in @save
963: * @save: leftover bits that have not yet been encoded
964: *
965: * Base64 encodes a chunk of data. Performs an 'encode step', only
966: * encodes blocks of 3 characters to the output at a time, saves
967: * left-over state in state and save (initialise to 0 on first
968: * invocation).
969: *
970: * Returns the number of bytes encoded.
971: **/
972: static size_t
973: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
974: {
1.186 paf 975: register const unsigned char *inptr;
1.178 paf 976: register unsigned char *outptr;
977:
978: if (inlen <= 0)
979: return 0;
980:
981: inptr = in;
982: outptr = out;
983:
984: if (inlen + ((unsigned char *)save)[0] > 2) {
985: const unsigned char *inend = in + inlen - 2;
986: register int c1 = 0, c2 = 0, c3 = 0;
987: register int already;
988:
989: already = *state;
990:
991: switch (((char *)save)[0]) {
992: case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
993: case 2: c1 = ((unsigned char *)save)[1];
994: c2 = ((unsigned char *)save)[2]; goto skip2;
995: }
996:
997: /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
998: while (inptr < inend) {
999: c1 = *inptr++;
1000: skip1:
1001: c2 = *inptr++;
1002: skip2:
1003: c3 = *inptr++;
1004: *outptr++ = base64_alphabet [c1 >> 2];
1005: *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
1006: *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
1007: *outptr++ = base64_alphabet [c3 & 0x3f];
1008: /* this is a bit ugly ... */
1009: if ((++already) >= 19) {
1010: *outptr++ = '\n';
1011: already = 0;
1012: }
1013: }
1014:
1015: ((unsigned char *)save)[0] = 0;
1016: inlen = 2 - (inptr - inend);
1017: *state = already;
1018: }
1019:
1020: //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
1021:
1022: if (inlen > 0) {
1023: register char *saveout;
1024:
1025: /* points to the slot for the next char to save */
1026: saveout = & (((char *)save)[1]) + ((char *)save)[0];
1027:
1028: /* inlen can only be 0 1 or 2 */
1029: switch (inlen) {
1030: case 2: *saveout++ = *inptr++;
1031: case 1: *saveout++ = *inptr++;
1032: }
1.216 paf 1033: *(char *)save = *(char *)save+(char)inlen;
1.178 paf 1034: }
1035:
1036: /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
1037: (int)((char *)save)[0],
1038: (int)((char *)save)[1],
1039: (int)((char *)save)[2]));*/
1040:
1041: return (outptr - out);
1042: }
1043:
1044: /**
1045: * g_mime_utils_base64_encode_close:
1046: * @in: input stream
1047: * @inlen: length of the input
1048: * @out: output string
1049: * @state: holds the number of bits that are stored in @save
1050: * @save: leftover bits that have not yet been encoded
1051: *
1052: * Base64 encodes the input stream to the output stream. Call this
1053: * when finished encoding data with g_mime_utils_base64_encode_step to
1054: * flush off the last little bit.
1055: *
1056: * Returns the number of bytes encoded.
1057: **/
1058: static size_t
1059: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1060: {
1061: unsigned char *outptr = out;
1062: int c1, c2;
1063:
1064: if (inlen > 0)
1065: outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
1066:
1067: c1 = ((unsigned char *)save)[1];
1068: c2 = ((unsigned char *)save)[2];
1069:
1070: switch (((unsigned char *)save)[0]) {
1071: case 2:
1072: outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
1073: goto skip;
1074: case 1:
1075: outptr[2] = '=';
1076: skip:
1077: outptr[0] = base64_alphabet [c1 >> 2];
1078: outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
1079: outptr[3] = '=';
1080: outptr += 4;
1081: break;
1082: }
1083:
1084: *outptr++ = 0;
1085:
1086: *save = 0;
1087: *state = 0;
1088:
1089: return (outptr - out);
1090: }
1091:
1.210 paf 1092: static unsigned char gmime_base64_rank[256] = {
1093: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1094: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1095: 255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
1096: 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255, 0,255,255,
1097: 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
1098: 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
1099: 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
1100: 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
1101: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1102: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1103: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1104: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1105: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1106: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1107: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1108: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1109: };
1110:
1111: /**
1112: * g_mime_utils_base64_decode_step:
1113: * @in: input stream
1114: * @inlen: max length of data to decode
1115: * @out: output stream
1116: * @state: holds the number of bits that are stored in @save
1117: * @save: leftover bits that have not yet been decoded
1118: *
1119: * Decodes a chunk of base64 encoded data.
1120: *
1121: * Returns the number of bytes decoded (which have been dumped in @out).
1122: **/
1123: size_t
1124: g_mime_utils_base64_decode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1125: {
1.213 paf 1126: const unsigned char *inptr;
1127: unsigned char *outptr;
1.210 paf 1128: const unsigned char *inend;
1.213 paf 1129: int saved;
1.210 paf 1130: unsigned char c;
1131: int i;
1132:
1133: inend = in + inlen;
1134: outptr = out;
1135:
1136: /* convert 4 base64 bytes to 3 normal bytes */
1137: saved = *save;
1138: i = *state;
1139: inptr = in;
1140: while (inptr < inend) {
1141: c = gmime_base64_rank[*inptr++];
1142: if (c != 0xff) {
1143: saved = (saved << 6) | c;
1144: i++;
1145: if (i == 4) {
1.217 paf 1146: *outptr++ = (unsigned char)(saved >> 16);
1147: *outptr++ = (unsigned char)(saved >> 8);
1148: *outptr++ = (unsigned char)(saved);
1.210 paf 1149: i = 0;
1150: }
1151: }
1152: }
1153:
1154: *save = saved;
1155: *state = i;
1156:
1157: /* quick scan back for '=' on the end somewhere */
1158: /* fortunately we can drop 1 output char for each trailing = (upto 2) */
1159: i = 2;
1160: while (inptr > in && i) {
1161: inptr--;
1162: if (gmime_base64_rank[*inptr] != 0xff) {
1163: if (*inptr == '=' && outptr > out)
1164: outptr--;
1165: i--;
1166: }
1167: }
1168:
1169: /* if i != 0 then there is a truncation error! */
1170: return (outptr - out);
1171: }
1172:
1173:
1.239 misha 1174: char* pa_base64_encode(const char *in, size_t in_size){
1.178 paf 1175: /* wont go to more than 2x size (overly conservative) */
1.210 paf 1176: char* result=new(PointerFreeGC) char[in_size * 2 + 6];
1.178 paf 1177: int state=0;
1178: int save=0;
1.183 paf 1179: #ifndef NDEBUG
1180: size_t filled=
1181: #endif
1.210 paf 1182: g_mime_utils_base64_encode_close ((const unsigned char*)in, in_size,
1.178 paf 1183: (unsigned char*)result, &state, &save);
1.210 paf 1184: assert(filled <= in_size * 2 + 6);
1.178 paf 1185:
1186: return result;
1.98 paf 1187: }
1.210 paf 1188:
1.222 misha 1189:
1.239 misha 1190: char* pa_base64_encode(const String& file_spec){
1.222 misha 1191: unsigned char* base64=0;
1192: File_base64_action_info info={&base64};
1193:
1194: file_read_action_under_lock(file_spec,
1195: "pa_base64_encode", file_base64_file_action, &info);
1196:
1197: return (char*)base64;
1198: }
1199:
1200:
1201: static void file_base64_file_action(
1.229 misha 1202: struct stat& finfo,
1203: int f,
1204: const String&, const char* /*fname*/, bool,
1205: void *context) {
1.222 misha 1206:
1207: if(finfo.st_size) {
1208: File_base64_action_info& info=*static_cast<File_base64_action_info *>(context);
1209: *info.base64=new(PointerFreeGC) unsigned char[finfo.st_size * 2 + 6];
1210: unsigned char* base64 = *info.base64;
1211: int state=0;
1212: int save=0;
1213: int nCount;
1214: do {
1215: unsigned char buffer[FILE_BUFFER_SIZE];
1216: nCount = file_block_read(f, buffer, sizeof(buffer));
1217: if( nCount ){
1218: size_t filled=g_mime_utils_base64_encode_step ((const unsigned char*)buffer, nCount, base64, &state, &save);
1219: base64+=filled;
1220: }
1221: } while(nCount > 0);
1222: g_mime_utils_base64_encode_close (0, 0, base64, &state, &save);
1223: }
1224: }
1225:
1.239 misha 1226: void pa_base64_decode(const char *in, size_t in_size, char*& result, size_t& result_size) {
1.210 paf 1227: /* wont go to more than had (overly conservative) */
1.211 paf 1228: result=new(PointerFreeGC) char[in_size+1/*terminator*/];
1.210 paf 1229: int state=0;
1230: int save=0;
1231: result_size=
1232: g_mime_utils_base64_decode_step ((const unsigned char*)in, in_size,
1233: (unsigned char*)result, &state, &save);
1234: assert(result_size <= in_size);
1.211 paf 1235: result[result_size]=0; // for text files
1.210 paf 1236: }
1.218 misha 1237:
1238:
1.221 misha 1239: int file_block_read(const int f, unsigned char* buffer, const size_t size){
1240: int nCount = read(f, buffer, size);
1241: if (nCount < 0)
1.238 misha 1242: throw Exception("file.read",
1.221 misha 1243: 0,
1244: "read failed: %s (%d)", strerror(errno), errno);
1245: return nCount;
1246: }
1247:
1.239 misha 1248: const unsigned long pa_crc32(const char *in, size_t in_size){
1.218 misha 1249: unsigned long crc32=0xFFFFFFFF;
1.220 misha 1250:
1.240 misha 1251: InitCrc32Table();
1.239 misha 1252: for(size_t i = 0; i<in_size; i++)
1253: CalcCrc32(in[i], crc32);
1.220 misha 1254:
1.218 misha 1255: return ~crc32;
1256: }
1257:
1.239 misha 1258: const unsigned long pa_crc32(const String& file_spec){
1.218 misha 1259: unsigned long crc32=0xFFFFFFFF;
1260: file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
1261: return ~crc32;
1262: }
1263:
1264: static void file_crc32_file_action(
1.229 misha 1265: struct stat& finfo,
1266: int f,
1267: const String&, const char* /*fname*/, bool,
1.239 misha 1268: void *context) {
1.218 misha 1269: unsigned long& crc32=*static_cast<unsigned long *>(context);
1270: if(finfo.st_size) {
1271: InitCrc32Table();
1.220 misha 1272: int nCount=0;
1.218 misha 1273: do {
1.221 misha 1274: unsigned char buffer[FILE_BUFFER_SIZE];
1275: nCount = file_block_read(f, buffer, sizeof(buffer));
1.220 misha 1276: for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
1277: } while(nCount > 0);
1.218 misha 1278: }
1279: }
1280:
E-mail: