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