Annotation of parser3/src/main/pa_common.C, revision 1.294
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.294 ! moko 53: volatile const char * IDENT_PA_COMMON_C="$Id: pa_common.C,v 1.293 2016/09/21 14:12:23 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))
1.291 moko 159: asked_charset=&::charsets.get(vcharset_name->as_string());
1.263 misha 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:
1.178 paf 898: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
899: /*
900: * Authors: Michael Zucchi <notzed@helixcode.com>
901: * Jeffrey Stedfast <fejj@helixcode.com>
902: *
903: * Copyright 2000 Helix Code, Inc. (www.helixcode.com)
904: *
905: * This program is free software; you can redistribute it and/or modify
906: * it under the terms of the GNU General Public License as published by
907: * the Free Software Foundation; either version 2 of the License, or
908: * (at your option) any later version.
909: *
910: * This program is distributed in the hope that it will be useful,
911: * but WITHOUT ANY WARRANTY; without even the implied warranty of
912: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
913: * GNU General Public License for more details.
914: *
915: * You should have received a copy of the GNU General Public License
916: * along with this program; if not, write to the Free Software
917: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
918: *
919: */
1.271 moko 920: static const char *base64_alphabet =
1.178 paf 921: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
922:
923: /**
924: * g_mime_utils_base64_encode_step:
925: * @in: input stream
926: * @inlen: length of the input
927: * @out: output string
928: * @state: holds the number of bits that are stored in @save
929: * @save: leftover bits that have not yet been encoded
930: *
931: * Base64 encodes a chunk of data. Performs an 'encode step', only
932: * encodes blocks of 3 characters to the output at a time, saves
933: * left-over state in state and save (initialise to 0 on first
934: * invocation).
935: *
936: * Returns the number of bytes encoded.
937: **/
1.252 misha 938:
939: #define BASE64_GROUPS_IN_LINE 19
940:
1.178 paf 941: static size_t
942: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
943: {
1.186 paf 944: register const unsigned char *inptr;
1.178 paf 945: register unsigned char *outptr;
946:
947: if (inlen <= 0)
948: return 0;
949:
950: inptr = in;
951: outptr = out;
952:
953: if (inlen + ((unsigned char *)save)[0] > 2) {
954: const unsigned char *inend = in + inlen - 2;
955: register int c1 = 0, c2 = 0, c3 = 0;
956: register int already;
957:
958: already = *state;
959:
960: switch (((char *)save)[0]) {
961: case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
962: case 2: c1 = ((unsigned char *)save)[1];
963: c2 = ((unsigned char *)save)[2]; goto skip2;
964: }
965:
966: /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
967: while (inptr < inend) {
968: c1 = *inptr++;
969: skip1:
970: c2 = *inptr++;
971: skip2:
972: c3 = *inptr++;
973: *outptr++ = base64_alphabet [c1 >> 2];
974: *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
975: *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
976: *outptr++ = base64_alphabet [c3 & 0x3f];
977: /* this is a bit ugly ... */
1.252 misha 978: if ((++already) >= BASE64_GROUPS_IN_LINE) {
1.178 paf 979: *outptr++ = '\n';
980: already = 0;
981: }
982: }
983:
984: ((unsigned char *)save)[0] = 0;
985: inlen = 2 - (inptr - inend);
986: *state = already;
987: }
988:
989: //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
990:
991: if (inlen > 0) {
992: register char *saveout;
993:
994: /* points to the slot for the next char to save */
995: saveout = & (((char *)save)[1]) + ((char *)save)[0];
996:
997: /* inlen can only be 0 1 or 2 */
998: switch (inlen) {
999: case 2: *saveout++ = *inptr++;
1000: case 1: *saveout++ = *inptr++;
1001: }
1.216 paf 1002: *(char *)save = *(char *)save+(char)inlen;
1.178 paf 1003: }
1004:
1005: /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
1006: (int)((char *)save)[0],
1007: (int)((char *)save)[1],
1008: (int)((char *)save)[2]));*/
1009:
1010: return (outptr - out);
1011: }
1012:
1013: /**
1014: * g_mime_utils_base64_encode_close:
1015: * @in: input stream
1016: * @inlen: length of the input
1017: * @out: output string
1018: * @state: holds the number of bits that are stored in @save
1019: * @save: leftover bits that have not yet been encoded
1020: *
1021: * Base64 encodes the input stream to the output stream. Call this
1022: * when finished encoding data with g_mime_utils_base64_encode_step to
1023: * flush off the last little bit.
1024: *
1025: * Returns the number of bytes encoded.
1026: **/
1027: static size_t
1028: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
1029: {
1030: unsigned char *outptr = out;
1031: int c1, c2;
1032:
1033: if (inlen > 0)
1034: outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
1035:
1036: c1 = ((unsigned char *)save)[1];
1037: c2 = ((unsigned char *)save)[2];
1038:
1039: switch (((unsigned char *)save)[0]) {
1040: case 2:
1041: outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
1042: goto skip;
1043: case 1:
1044: outptr[2] = '=';
1045: skip:
1046: outptr[0] = base64_alphabet [c1 >> 2];
1047: outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
1048: outptr[3] = '=';
1049: outptr += 4;
1050: break;
1051: }
1052:
1053: *outptr++ = 0;
1054:
1055: *save = 0;
1056: *state = 0;
1057:
1058: return (outptr - out);
1059: }
1060:
1.210 paf 1061: static unsigned char gmime_base64_rank[256] = {
1.266 misha 1062: 255,255,255,255,255,255,255,255,255,254,254,255,255,254,255,255,
1.210 paf 1063: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1.266 misha 1064: 254,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63,
1.210 paf 1065: 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255, 0,255,255,
1066: 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
1067: 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
1068: 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
1069: 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
1070: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1071: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1072: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1073: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1074: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1075: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1076: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1077: 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1078: };
1079:
1080: /**
1081: * g_mime_utils_base64_decode_step:
1082: * @in: input stream
1083: * @inlen: max length of data to decode
1084: * @out: output stream
1085: * @state: holds the number of bits that are stored in @save
1086: * @save: leftover bits that have not yet been decoded
1.266 misha 1087: * @strict: only base64 and whitespace chars are allowed
1.210 paf 1088: *
1089: * Decodes a chunk of base64 encoded data.
1090: *
1091: * Returns the number of bytes decoded (which have been dumped in @out).
1092: **/
1093: size_t
1.266 misha 1094: 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 1095: {
1.213 paf 1096: const unsigned char *inptr;
1097: unsigned char *outptr;
1.210 paf 1098: const unsigned char *inend;
1.213 paf 1099: int saved;
1.210 paf 1100: unsigned char c;
1101: int i;
1102:
1103: inend = in + inlen;
1104: outptr = out;
1105:
1106: /* convert 4 base64 bytes to 3 normal bytes */
1107: saved = *save;
1108: i = *state;
1109: inptr = in;
1110: while (inptr < inend) {
1111: c = gmime_base64_rank[*inptr++];
1.266 misha 1112: switch(c) {
1113: case 0xff: // non-base64 and non-whitespace chars. not allowed in strict mode
1114: if(strict)
1115: throw Exception(BASE64_FORMAT, 0, "Invalid base64 char on position %d is detected", inptr-in-1);
1116: case 0xfe: // whitespace chars 0x09, 0x0A, 0x0D, 0x20 are allowed in any mode
1117: break;
1118: default:
1119: saved = (saved << 6) | c;
1120: i++;
1121: if (i == 4) {
1122: *outptr++ = (unsigned char)(saved >> 16);
1123: *outptr++ = (unsigned char)(saved >> 8);
1124: *outptr++ = (unsigned char)(saved);
1125: i = 0;
1126: }
1.210 paf 1127: }
1128: }
1129:
1130: *save = saved;
1131: *state = i;
1132:
1133: /* quick scan back for '=' on the end somewhere */
1134: /* fortunately we can drop 1 output char for each trailing = (upto 2) */
1135: i = 2;
1136: while (inptr > in && i) {
1137: inptr--;
1.266 misha 1138: if (gmime_base64_rank[*inptr] <= 0xfe) {
1.210 paf 1139: if (*inptr == '=' && outptr > out)
1140: outptr--;
1141: i--;
1142: }
1143: }
1144:
1145: /* if i != 0 then there is a truncation error! */
1146: return (outptr - out);
1147: }
1148:
1149:
1.239 misha 1150: char* pa_base64_encode(const char *in, size_t in_size){
1.252 misha 1151: size_t new_size = ((in_size / 3 + 1) * 4);
1152: new_size += new_size / (BASE64_GROUPS_IN_LINE * 4)/*new lines*/ + 1/*zero terminator*/;
1153: char* result = new(PointerFreeGC) char[new_size];
1.178 paf 1154: int state=0;
1155: int save=0;
1.183 paf 1156: #ifndef NDEBUG
1157: size_t filled=
1158: #endif
1.251 misha 1159: g_mime_utils_base64_encode_close ((const unsigned char*)in, in_size, (unsigned char*)result, &state, &save);
1160:
1161: //throw Exception(PARSER_RUNTIME, 0, "%d %d %d", in_size, new_size, filled);
1162: assert(filled <= new_size);
1.178 paf 1163:
1164: return result;
1.98 paf 1165: }
1.210 paf 1166:
1.278 moko 1167: struct File_base64_action_info {
1168: unsigned char** base64;
1169: };
1.222 misha 1170:
1.289 moko 1171: static void file_base64_file_action(struct stat& finfo, int f, const String&, void *context) {
1.222 misha 1172:
1173: if(finfo.st_size) {
1174: File_base64_action_info& info=*static_cast<File_base64_action_info *>(context);
1175: *info.base64=new(PointerFreeGC) unsigned char[finfo.st_size * 2 + 6];
1176: unsigned char* base64 = *info.base64;
1177: int state=0;
1178: int save=0;
1179: int nCount;
1180: do {
1181: unsigned char buffer[FILE_BUFFER_SIZE];
1182: nCount = file_block_read(f, buffer, sizeof(buffer));
1183: if( nCount ){
1184: size_t filled=g_mime_utils_base64_encode_step ((const unsigned char*)buffer, nCount, base64, &state, &save);
1185: base64+=filled;
1186: }
1187: } while(nCount > 0);
1188: g_mime_utils_base64_encode_close (0, 0, base64, &state, &save);
1189: }
1190: }
1191:
1.278 moko 1192: char* pa_base64_encode(const String& file_spec){
1193: unsigned char* base64=0;
1194: File_base64_action_info info={&base64};
1195:
1.289 moko 1196: file_read_action_under_lock(file_spec, "pa_base64_encode", file_base64_file_action, &info);
1.278 moko 1197:
1198: return (char*)base64;
1199: }
1200:
1.265 misha 1201: void pa_base64_decode(const char *in, size_t in_size, char*& result, size_t& result_size, bool strict) {
1.264 misha 1202: // every 4 base64 bytes are converted into 3 normal bytes
1203: // not full set (tail) of 4-bytes set is ignored
1204: size_t new_size=in_size/4*3;
1205: result=new(PointerFreeGC) char[new_size+1/*terminator*/];
1206:
1.210 paf 1207: int state=0;
1208: int save=0;
1.289 moko 1209: result_size=g_mime_utils_base64_decode_step ((const unsigned char*)in, in_size, (unsigned char*)result, &state, &save, strict);
1.264 misha 1210: assert(result_size <= new_size);
1.211 paf 1211: result[result_size]=0; // for text files
1.265 misha 1212:
1213: if(strict && state!=0)
1.266 misha 1214: throw Exception(BASE64_FORMAT, 0, "Unexpected end of chars");
1.210 paf 1215: }
1.218 misha 1216:
1217:
1.221 misha 1218: int file_block_read(const int f, unsigned char* buffer, const size_t size){
1219: int nCount = read(f, buffer, size);
1220: if (nCount < 0)
1.289 moko 1221: throw Exception("file.read", 0, "read failed: %s (%d)", strerror(errno), errno);
1.221 misha 1222: return nCount;
1223: }
1224:
1.278 moko 1225: static unsigned long crc32Table[256];
1226: static void InitCrc32Table()
1227: {
1228: if(crc32Table[1] == 0){
1229: // This is the official polynomial used by CRC32 in PKZip.
1230: // Often times the polynomial shown reversed as 0x04C11DB7.
1231: static const unsigned long dwPolynomial = 0xEDB88320;
1232:
1233: for(int i = 0; i < 256; i++)
1234: {
1235: unsigned long dwCrc = i;
1236: for(int j = 8; j > 0; j--)
1237: {
1238: if(dwCrc & 1)
1239: dwCrc = (dwCrc >> 1) ^ dwPolynomial;
1240: else
1241: dwCrc >>= 1;
1242: }
1243: crc32Table[i] = dwCrc;
1244: }
1245: }
1246: }
1247:
1248: inline void CalcCrc32(const unsigned char byte, unsigned long &crc32)
1249: {
1250: crc32 = ((crc32) >> 8) ^ crc32Table[(byte) ^ ((crc32) & 0x000000FF)];
1251: }
1252:
1253:
1.239 misha 1254: const unsigned long pa_crc32(const char *in, size_t in_size){
1.218 misha 1255: unsigned long crc32=0xFFFFFFFF;
1.220 misha 1256:
1.240 misha 1257: InitCrc32Table();
1.239 misha 1258: for(size_t i = 0; i<in_size; i++)
1259: CalcCrc32(in[i], crc32);
1.220 misha 1260:
1.218 misha 1261: return ~crc32;
1262: }
1263:
1.289 moko 1264: static void file_crc32_file_action(struct stat& finfo, int f, const String&, void *context) {
1.218 misha 1265: unsigned long& crc32=*static_cast<unsigned long *>(context);
1266: if(finfo.st_size) {
1267: InitCrc32Table();
1.220 misha 1268: int nCount=0;
1.218 misha 1269: do {
1.221 misha 1270: unsigned char buffer[FILE_BUFFER_SIZE];
1271: nCount = file_block_read(f, buffer, sizeof(buffer));
1.220 misha 1272: for(int i = 0; i < nCount; i++) CalcCrc32(buffer[i], crc32);
1273: } while(nCount > 0);
1.218 misha 1274: }
1275: }
1276:
1.278 moko 1277: const unsigned long pa_crc32(const String& file_spec){
1278: unsigned long crc32=0xFFFFFFFF;
1279: file_read_action_under_lock(file_spec, "crc32", file_crc32_file_action, &crc32);
1280: return ~crc32;
1281: }
1282:
1283: // content-type: xxx; charset=WE-NEED-THIS
1284: // content-type: xxx; charset="WE-NEED-THIS"
1285: // content-type: xxx; charset="WE-NEED-THIS";
1286: Charset* detect_charset(const char* content_type){
1287: if(content_type){
1.291 moko 1288: char* CONTENT_TYPE=str_upper(content_type);
1.278 moko 1289:
1290: if(const char* begin=strstr(CONTENT_TYPE, "CHARSET=")){
1291: begin+=8; // skip "CHARSET="
1292: char* end=0;
1293: if(*begin && (*begin=='"' || *begin =='\'')){
1294: char quote=*begin;
1295: begin++;
1296: end=(char*)strchr(begin, quote);
1297: }
1298: if(!end)
1299: end=(char*)strchr(begin, ';');
1300:
1301: if(end)
1302: *end=0; // terminator
1303:
1.291 moko 1304: return *begin?&charsets.get_direct(begin):0;
1.278 moko 1305: }
1306: }
1307: return 0;
1308: }
1309:
1310:
1.283 moko 1311: static bool is_latin(const char *in){
1312: for(; *in; in++){
1313: if ((unsigned char)(*in) > 0x7F)
1314: return false;
1315: }
1316: return true;
1317: }
1318:
1319: #define MAX_IDNA_LENGTH 256
1320:
1321: const char *pa_idna_encode(const char *in, Charset &source_charset){
1322: if(!in || is_latin(in))
1323: return in;
1324:
1325: uint32_t utf32[MAX_IDNA_LENGTH];
1326: uint32_t *utf32_end=utf32;
1327:
1328: String::C sIn(in,strlen(in));
1329:
1330: if(!source_charset.isUTF8())
1331: sIn=Charset::transcode(sIn, source_charset, UTF8_charset);
1332:
1333: int status=pa_convertUTF8toUTF32((const UTF8**)&sIn.str, (const UTF8*)(sIn.str+sIn.length), &utf32_end, utf32+MAX_IDNA_LENGTH-1, strictConversion);
1334: if(status != conversionOK)
1335: throw Exception("idna encode", new String(in), "utf conversion failed (%d)", status);
1336:
1337: *utf32_end=0;
1338:
1339: char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
1340: status=pa_idna_to_ascii_4z(utf32, result, MAX_IDNA_LENGTH, 0);
1341: if(status != IDNA_SUCCESS)
1342: throw Exception("idna encode", new String(in), "encode failed: %s", pa_idna_strerror(status));
1343:
1344: return result;
1345: }
1346:
1347: const char *pa_idna_decode(const char *in, Charset &asked_charset){
1348: if(!in || !(*in))
1349: return in;
1350:
1351: uint32_t utf32[MAX_IDNA_LENGTH];
1352: const uint32_t *utf32_start=utf32;
1353: uint32_t *utf32_end;
1354:
1355: int status=pa_idna_to_unicode_4z(in, utf32, MAX_IDNA_LENGTH, 0);
1356: if(status != IDNA_SUCCESS)
1357: throw Exception("idna decode", new String(in), "decode failed: %s", pa_idna_strerror(status));
1358:
1359: for(utf32_end=utf32; *utf32_end; utf32_end++);
1360:
1361: char *result = (char *)pa_malloc(MAX_IDNA_LENGTH);
1362: char *result_end = result;
1363:
1364: status=pa_convertUTF32toUTF8(&utf32_start, utf32_end, (UTF8**)&result_end, (UTF8*)(result+MAX_IDNA_LENGTH-1), strictConversion);
1365:
1366: if(status != conversionOK)
1367: throw Exception("idna decode", new String(in), "utf conversion failed (%d)", status);
1368:
1369: *result_end='\0';
1370:
1371: if(!asked_charset.isUTF8())
1372: result = (char *)Charset::transcode(result, UTF8_charset, asked_charset).cstr();
1373:
1374: return result;
1375: }
1.292 moko 1376: /// must be last in this file
1377: #undef vsnprintf
1378: int pa_vsnprintf(char* b, size_t s, const char* f, va_list l) {
1379: if(!s)
1380: return 0;
1381:
1382: int r;
1383: // note: on win32 & maybe somewhere else
1384: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
1385: // http://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010
1386: --s;
1387:
1388: // clients do not check for negative 's', feature: ignore such prints
1389: if((ssize_t)s<0)
1390: return 0;
1391:
1392: #ifdef _MSC_VER
1393: // win32: if the number of bytes to write exceeds buffer, then count bytes are written and -1 is returned
1394: r=_vsnprintf(b, s, f, l);
1395: if(r<0)
1396: r=s;
1397: #else
1398: r=vsnprintf(b, s, f, l);
1399: /*
1400: solaris: man vsnprintf
1401:
1402: The snprintf() function returns the number of characters
1403: formatted, that is, the number of characters that would have
1404: been written to the buffer if it were large enough. If the
1405: value of n is 0 on a call to snprintf(), an unspecified
1406: value less than 1 is returned.
1407: */
1408:
1409: if(r<0)
1410: r=0;
1411: else if((size_t)r>s)
1412: r=s;
1413: #endif
1414: b[r]=0;
1415: return r;
1416: }
1417:
1418: int pa_snprintf(char* b, size_t s, const char* f, ...) {
1419: va_list l;
1420: va_start(l, f);
1421: int r=pa_vsnprintf(b, s, f, l);
1422: va_end(l);
1423: return r;
1424: }
1425:
E-mail: