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