Annotation of parser3/src/main/pa_common.C, revision 1.178
1.15 paf 1: /** @file
1.16 paf 2: Parser: commonly functions.
3:
1.174 paf 4: Copyright(c) 2001-2004 ArtLebedev Group (http://www.artlebedev.com)
1.101 paf 5: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.111 paf 6: */
1.16 paf 7:
1.178 ! paf 8: static const char * const IDENT_COMMON_C="$Date: 2004/03/05 10:32:17 $";
1.1 paf 9:
10: #include "pa_common.h"
1.4 paf 11: #include "pa_exception.h"
1.154 paf 12: #include "pa_hash.h"
1.14 paf 13: #include "pa_globals.h"
1.154 paf 14: #include "pa_request_charsets.h"
15: #include "pa_charsets.h"
16:
17: #define PA_HTTP
18:
19: #ifdef PA_HTTP
1.126 paf 20: #include "pa_vstring.h"
1.154 paf 21: #include "pa_vint.h"
1.155 paf 22: #include "pa_vhash.h"
23: #include "pa_vtable.h"
1.154 paf 24:
25: #ifdef CYGWIN
26: #define _GNU_H_WINDOWS32_SOCKETS
27: // for PASCAL
28: #include <windows.h>
29: // SOCKET
30: typedef u_int SOCKET;
31: int PASCAL closesocket(SOCKET);
32: #else
33: # if defined(WIN32)
34: # include <windows.h>
35: # else
36: # define closesocket close
37: # endif
38: #endif
1.1 paf 39:
1.126 paf 40: #else
1.154 paf 41:
42: # if defined(WIN32)
43: # include <windows.h>
44: # endif
45:
1.98 paf 46: #endif
47:
1.93 paf 48: // some maybe-undefined constants
49:
1.82 paf 50: #ifndef _O_TEXT
51: # define _O_TEXT 0
52: #endif
53: #ifndef _O_BINARY
54: # define _O_BINARY 0
1.47 paf 55: #endif
1.80 paf 56:
1.138 paf 57: #ifdef HAVE_FTRUNCATE
58: # define PA_O_TRUNC 0
59: #else
60: # ifdef _O_TRUNC
61: # define PA_O_TRUNC _O_TRUNC
62: # else
63: # error you must have either ftruncate function or _O_TRUNC bit declared
64: # endif
1.154 paf 65: #endif
1.176 paf 66:
67: # ifndef INADDR_NONE
68: # define INADDR_NONE ((ulong) -1)
69: # endif
1.154 paf 70:
71: // defines for globals
72:
73: #define FILE_STATUS_NAME "status"
74:
75: // globals
76:
77: const String file_status_name(FILE_STATUS_NAME);
78:
1.178 ! paf 79: // defines
1.154 paf 80:
81: #define HTTP_METHOD_NAME "method"
82: #define HTTP_TIMEOUT_NAME "timeout"
83: #define HTTP_HEADERS_NAME "headers"
84: #define HTTP_ANY_STATUS_NAME "any-status"
85: #define HTTP_CHARSET_NAME "charset"
1.155 paf 86: #define HTTP_TABLES_NAME "tables"
1.178 ! paf 87: #define HTTP_USER "user"
! 88: #define HTTP_PASSWORD "password"
1.154 paf 89:
90: // defines
91:
1.127 paf 92: #define DEFAULT_USER_AGENT "parser3"
93:
1.154 paf 94: // functions
1.127 paf 95:
1.154 paf 96: void fix_line_breaks(char *str, size_t& length) {
1.87 paf 97: //_asm int 3;
1.154 paf 98: const char* const eob=str+length;
99: char* dest=str;
1.72 parser 100: // fix DOS: \r\n -> \n
101: // fix Macintosh: \r -> \n
1.154 paf 102: char* bol=str;
1.137 paf 103: while(char* eol=(char*)memchr(bol, '\r', eob -bol)) {
1.72 parser 104: size_t len=eol-bol;
105: if(dest!=bol)
1.126 paf 106: memcpy(dest, bol, len);
1.72 parser 107: dest+=len;
1.126 paf 108: *dest++='\n';
1.72 parser 109:
1.126 paf 110: if(&eol[1]<eob && eol[1]=='\n') { // \r, \n = DOS
1.72 parser 111: bol=eol+2;
1.154 paf 112: length--;
1.126 paf 113: } else // \r, not \n = Macintosh
1.72 parser 114: bol=eol+1;
115: }
1.154 paf 116: // last piece without \r
1.72 parser 117: if(dest!=bol)
1.126 paf 118: memcpy(dest, bol, eob-bol);
1.154 paf 119: str[length]=0; // terminating
1.72 parser 120: }
1.18 paf 121:
1.154 paf 122: char* file_read_text(Request_charsets& charsets,
123: const String& file_spec,
124: bool fail_on_read_problem,
125: HashStringValue* params/*, HashStringValue* * out_fields*/) {
126: File_read_result file=
127: file_read(charsets, file_spec, true, params, fail_on_read_problem);
128: return file.success?file.str:0;
1.126 paf 129: }
130:
1.178 ! paf 131: //http request stuff
1.154 paf 132: #ifdef PA_HTTP
133:
134: #undef CRLF
135: #define CRLF "\r\n"
1.126 paf 136:
137: static bool set_addr(struct sockaddr_in *addr, const char* host, const short port){
138: memset(addr, 0, sizeof(*addr));
139: addr->sin_family=AF_INET;
140: addr->sin_port=htons(port);
141: if(host) {
1.175 paf 142: ulong packed_ip=inet_addr(host);
143: struct hostent *hostIP = packed_ip==INADDR_NONE?
144: gethostbyname(host)
145: : gethostbyaddr((char *)&packed_ip, sizeof(packed_ip), AF_INET);
146: if(hostIP)
1.126 paf 147: memcpy(&addr->sin_addr, hostIP->h_addr, hostIP->h_length);
148: else
149: return false;
150: } else
151: addr->sin_addr.s_addr=INADDR_ANY;
152: return true;
153: }
154:
1.171 paf 155: static int http_read_response(char*& response, size_t& response_size, int sock, bool fail_on_status_ne_200){
156: response=(char*)pa_malloc_atomic(1/*terminator*/); // setting memory block type
157: response[(response_size=0)]=0;
1.154 paf 158: int result=0;
1.171 paf 159: char* EOLat=0;
1.126 paf 160: while(true) {
1.171 paf 161: char buf[MAX_STRING*10];
162: ssize_t received_size=recv(sock, buf, sizeof(buf), 0);
163: if(received_size<=0)
1.126 paf 164: break;
1.171 paf 165: response=(char*)pa_realloc(response, response_size+received_size+1/*terminator*/);
166: memcpy(response+response_size, buf, received_size);
167: response_size+=received_size;
168: response[response_size]=0;
169:
170: if(!result && (EOLat=strstr(response, CRLF))) { // checking status in first response
171: const String status_line(pa_strdup(response, EOLat-response));
1.154 paf 172: ArrayString astatus;
173: size_t pos_after=0;
174: status_line.split(astatus, pos_after, " ");
175: const String& status_code=*astatus.get(1);
176: result=status_code.as_int();
1.142 paf 177:
1.154 paf 178: if(fail_on_status_ne_200 && result!=200)
1.142 paf 179: throw Exception("http.status",
1.154 paf 180: &status_code,
1.142 paf 181: "invalid HTTP response status");
182: }
183: }
1.154 paf 184: if(result)
185: return result;
1.142 paf 186: else
187: throw Exception("http.response",
188: 0,
1.173 paf 189: "bad response from host - no status found (size=%u)", response_size);
1.126 paf 190: }
191:
192: /* ********************** request *************************** */
193:
194: #if defined(SIGALRM) && defined(HAVE_SIGSETJMP) && defined(HAVE_SIGLONGJMP)
1.145 paf 195: # define PA_USE_ALARM
1.126 paf 196: #endif
197:
1.145 paf 198: #ifdef PA_USE_ALARM
1.126 paf 199: static sigjmp_buf timeout_env;
200: static void timeout_handler(int sig){
201: siglongjmp(timeout_env, 1);
202: }
203: #endif
204:
1.171 paf 205: static int http_request(char*& response, size_t& response_size,
1.152 paf 206: const char* host, int port,
207: const char* request,
1.166 paf 208: int
209: #ifdef PA_USE_ALARM
210: timeout
211: #endif
212: ,
1.152 paf 213: bool fail_on_status_ne_200) {
1.126 paf 214: if(!host)
215: throw Exception("http.host",
1.154 paf 216: 0,
1.126 paf 217: "zero hostname"); //never
218:
1.145 paf 219: #ifdef PA_USE_ALARM
1.146 paf 220: signal(SIGALRM, timeout_handler);
1.126 paf 221: #endif
222: int sock=-1;
1.145 paf 223: #ifdef PA_USE_ALARM
224: if(sigsetjmp(timeout_env, 1)) {
225: // stupid gcc [2.95.4] generated bad code
226: // which failed to handle sigsetjmp+throw: crashed inside of pre-throw code.
227: // rewritten simplier [though duplicating closesocket code]
228: if(sock>=0)
229: closesocket(sock);
230: throw Exception("http.timeout",
231: origin_string,
232: "timeout occured while retrieving document");
1.146 paf 233: return 0; // never
1.145 paf 234: } else {
235: alarm(timeout);
236: #endif
1.146 paf 237: try {
238: int result;
1.126 paf 239: struct sockaddr_in dest;
1.154 paf 240:
241: if(!set_addr(&dest, host, port))
1.126 paf 242: throw Exception("http.host",
1.154 paf 243: 0,
1.127 paf 244: "can not resolve hostname \"%s\"", host);
1.126 paf 245:
246: if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP/*0*/))<0)
247: throw Exception("http.connect",
1.154 paf 248: 0,
1.127 paf 249: "can not make socket: %s (%d)", strerror(errno), errno);
1.126 paf 250: if(connect(sock, (struct sockaddr *)&dest, sizeof(dest)))
251: throw Exception("http.connect",
1.154 paf 252: 0,
1.127 paf 253: "can not connect to host \"%s\": %s (%d)", host, strerror(errno), errno);
1.126 paf 254: size_t request_size=strlen(request);
255: if(send(sock, request, request_size, 0)!=(ssize_t)request_size)
256: throw Exception("http.connect",
1.154 paf 257: 0,
1.127 paf 258: "error sending request: %s (%d)", strerror(errno), errno);
1.126 paf 259:
1.171 paf 260: result=http_read_response(response, response_size, sock, fail_on_status_ne_200);
1.142 paf 261: closesocket(sock);
1.145 paf 262: #ifdef PA_USE_ALARM
1.142 paf 263: alarm(0);
1.126 paf 264: #endif
1.147 paf 265: return result;
1.146 paf 266: } catch(...) {
1.145 paf 267: #ifdef PA_USE_ALARM
1.146 paf 268: alarm(0);
1.126 paf 269: #endif
1.146 paf 270: if(sock>=0)
271: closesocket(sock);
1.154 paf 272: rethrow;
1.146 paf 273: }
1.148 paf 274: #ifdef PA_USE_ALARM
1.126 paf 275: }
1.148 paf 276: #endif
1.126 paf 277: }
278:
1.127 paf 279: #ifndef DOXYGEN
280: struct Http_pass_header_info {
1.154 paf 281: Request_charsets* charsets;
1.127 paf 282: String* request;
283: bool user_agent_specified;
284: };
285: #endif
1.154 paf 286: static void http_pass_header(HashStringValue::key_type key,
287: HashStringValue::value_type value,
288: Http_pass_header_info *info) {
289: *info->request <<key<<": "
290: << attributed_meaning_to_string(*value, String::L_HTTP_HEADER, false)
291: << CRLF;
1.135 paf 292:
1.154 paf 293: if(String(key, String::L_TAINTED).change_case(info->charsets->source(), String::CC_UPPER)=="USER-AGENT")
294: info->user_agent_specified=true;
1.126 paf 295: }
1.154 paf 296:
297:
298: static Charset* detect_charset(Charset& source_charset, const String& content_type_value) {
1.156 paf 299: const String::Body CONTENT_TYPE_VALUE=
1.154 paf 300: content_type_value.change_case(source_charset, String::CC_UPPER);
301: // content-type: xxx/xxx; source_charset=WE-NEED-THIS
302: // content-type: xxx/xxx; source_charset="WE-NEED-THIS"
303: // content-type: xxx/xxx; source_charset="WE-NEED-THIS";
304: size_t before_charseteq_pos=CONTENT_TYPE_VALUE.pos("CHARSET=");
305: if(before_charseteq_pos!=STRING_NOT_FOUND) {
306: size_t charset_begin=before_charseteq_pos+8/*CHARSET="*/;
307: size_t open_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
308: bool quoted=open_quote_pos==charset_begin;
309: if(quoted)
310: charset_begin++; // skip opening '"'
311: size_t charset_end=CONTENT_TYPE_VALUE.length();
312: if(quoted) {
313: size_t close_quote_pos=CONTENT_TYPE_VALUE.pos('"', charset_begin);
314: if(close_quote_pos!=STRING_NOT_FOUND)
315: charset_end=close_quote_pos;
316: } else {
317: size_t delim_pos=CONTENT_TYPE_VALUE.pos(';', charset_begin);
318: if(delim_pos!=STRING_NOT_FOUND)
319: charset_end=delim_pos;
320: }
1.156 paf 321: const String::Body CHARSET_NAME_BODY=
1.154 paf 322: CONTENT_TYPE_VALUE.mid(charset_begin, charset_end);
323:
324: return &charsets.get(CHARSET_NAME_BODY);
325: }
326:
327: return 0;
328: }
329:
1.178 ! paf 330: static const String* basic_authorization_field(const char* user, const char* pass) {
! 331: if(!user&& !pass)
! 332: return 0;
! 333:
! 334: String combined;
! 335: if(user)
! 336: combined<<user;
! 337: combined<<":";
! 338: if(pass)
! 339: combined<<pass;
! 340:
! 341: String* result=new String("Basic "); *result<<pa_base64(combined.cstr(), combined.length());
! 342: return result;
! 343: }
1.154 paf 344:
345: #ifndef DOXYGEN
346: struct File_read_http_result {
347: char *str; size_t length;
348: HashStringValue* headers;
349: };
350: #endif
1.155 paf 351: /// @todo build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now
1.154 paf 352: static File_read_http_result file_read_http(Request_charsets& charsets,
353: const String& file_spec,
1.169 paf 354: bool as_text,
355: HashStringValue *options=0) {
1.154 paf 356: File_read_http_result result;
1.126 paf 357: char host[MAX_STRING];
1.129 paf 358: const char* uri;
1.126 paf 359: int port;
1.154 paf 360: const char* method=0;
1.126 paf 361: int timeout=2;
1.142 paf 362: bool fail_on_status_ne_200=true;
1.154 paf 363: Value* vheaders=0;
364: Charset *asked_remote_charset=0;
1.178 ! paf 365: const char* user_cstr=0;
! 366: const char* password_cstr=0;
1.126 paf 367:
1.127 paf 368: if(options) {
369: int valid_options=0;
1.177 paf 370: if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
1.127 paf 371: valid_options++;
1.154 paf 372: method=vmethod->as_string().cstr();
1.127 paf 373: }
1.177 paf 374: if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
1.127 paf 375: valid_options++;
376: timeout=vtimeout->as_int();
377: }
1.177 paf 378: if((vheaders=options->get(HTTP_HEADERS_NAME))) {
1.127 paf 379: valid_options++;
380: }
1.177 paf 381: if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
1.142 paf 382: valid_options++;
383: fail_on_status_ne_200=!vany_status->as_bool();
384: }
1.177 paf 385: if(Value* vcharset_name=options->get(HTTP_CHARSET_NAME)) {
1.154 paf 386: valid_options++;
387: asked_remote_charset=&::charsets.get(vcharset_name->as_string().
388: change_case(charsets.source(), String::CC_UPPER));
389: }
1.178 ! paf 390: if(Value* vuser=options->get(HTTP_USER)) {
! 391: valid_options++;
! 392: user_cstr=vuser->as_string().cstr();
! 393: }
! 394: if(Value* vpassword=options->get(HTTP_PASSWORD)) {
! 395: valid_options++;
! 396: password_cstr=vpassword->as_string().cstr();
! 397: }
1.142 paf 398:
1.154 paf 399: if(valid_options!=options->count())
1.127 paf 400: throw Exception("parser.runtime",
401: 0,
402: "invalid option passed");
1.154 paf 403: }
404: if(!asked_remote_charset) // defaulting to $request:charset
405: asked_remote_charset=&charsets.source();
406:
407: //preparing request
408: String& connect_string=*new String;
409: // not in ^sql{... L_SQL ...} spirit, but closer to ^file::load one
410: connect_string.append(file_spec, String::L_URI); // tainted pieces -> URI pieces
411:
412: const char* request_cstr;
413: {
414: // influence URLencoding of tainted pieces to String::L_URI lang
415: Temp_client_charset temp(charsets, *asked_remote_charset);
416:
417: const char* connect_string_cstr=connect_string.cstr(String::L_UNSPECIFIED);
1.126 paf 418:
1.154 paf 419: const char* current=connect_string_cstr;
420: if(strncmp(current, "http://", 7)!=0)
421: throw Exception(0,
422: &connect_string,
423: "does not start with http://"); //never
424: current+=7;
425:
426: strncpy(host, current, sizeof(host)-1); host[sizeof(host)-1]=0;
427: char* host_uri=lsplit(host, '/');
428: uri=host_uri?current+(host_uri-1-host):"/";
429: char* port_cstr=lsplit(host, ':');
430: char* error_pos=0;
431: port=port_cstr?strtol(port_cstr, &error_pos, 0):80;
432:
433: //making request
434: String request;
435: if(method)
436: request<<method;
437: else
438: request<<"GET";
439: request<< " "<< uri <<" HTTP/1.0" CRLF
440: "host: "<< host << CRLF;
1.178 ! paf 441:
! 442: if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
! 443: request<<"Authorization: "<<*authorization_field_value<<CRLF;
! 444:
1.154 paf 445: bool user_agent_specified=false;
446: if(vheaders && !vheaders->is_string()) { // allow empty
447: if(HashStringValue *headers=vheaders->get_hash()) {
1.167 paf 448: Http_pass_header_info info={&charsets, &request, false};
1.154 paf 449: headers->for_each(http_pass_header, &info);
450: user_agent_specified=info.user_agent_specified;
451: } else
452: throw Exception("parser.runtime",
453: &connect_string,
454: "headers param must be hash");
455: };
456: if(!user_agent_specified) // defaulting
457: request << "user-agent: " DEFAULT_USER_AGENT CRLF;
458: request << CRLF;
459:
460: request_cstr=request.cstr(String::L_UNSPECIFIED);
461: }
462: // recode those pieces which are not in String::L_URI lang
463: // [those violating HTTP standard, but widly used]
464: request_cstr=Charset::transcode(
465: String::C(request_cstr, strlen(request_cstr)),
466: charsets.source(),
467: *asked_remote_charset);
1.126 paf 468:
469: //sending request
1.171 paf 470: char* response;
471: size_t response_size;
472: int status_code=http_request(response, response_size,
1.154 paf 473: host, port, request_cstr,
1.142 paf 474: timeout, fail_on_status_ne_200);
1.126 paf 475:
476: //processing results
1.171 paf 477: char* raw_body; size_t raw_body_size;
478: char* headers_end_at=strstr(response, CRLF CRLF /*change '4' below along!*/);
479: if(headers_end_at) {
480: raw_body=headers_end_at+4;
481: raw_body_size=response_size-(raw_body-response);
482: } else
1.126 paf 483: throw Exception("http.response",
1.133 paf 484: &connect_string,
1.126 paf 485: "bad response from host - no headers found");
1.171 paf 486:
487: *headers_end_at=0;
488: const String header_block(response, headers_end_at-response, true);
1.126 paf 489:
1.154 paf 490: ArrayString aheaders;
491: result.headers=new HashStringValue;
1.155 paf 492: VHash* vtables=new VHash;
1.177 paf 493: result.headers->put(HTTP_TABLES_NAME, vtables);
1.155 paf 494: HashStringValue& tables=vtables->hash();
495:
1.154 paf 496: size_t pos_after=0;
497: header_block.split(aheaders, pos_after, CRLF);
1.126 paf 498:
499: //processing headers
1.154 paf 500: size_t aheaders_count=aheaders.count();
501: Charset* real_remote_charset=0; // undetected, yet
502: for(size_t i=1; i<aheaders_count; i++) {
503: const String& line=*aheaders.get(i);
1.171 paf 504: size_t pos=line.pos(": ", 2);
1.154 paf 505: if(pos==STRING_NOT_FOUND || pos<1)
1.126 paf 506: throw Exception("http.response",
1.154 paf 507: &connect_string,
508: "bad response from host - bad header \"%s\"", line.cstr());
1.156 paf 509: const String::Body HEADER_NAME=
1.154 paf 510: line.mid(0, pos).change_case(charsets.source(), String::CC_UPPER);
511: const String& header_value=line.mid(pos+2, line.length());
512: if(HEADER_NAME=="CONTENT-TYPE")
513: real_remote_charset=detect_charset(charsets.source(), header_value);
1.155 paf 514:
515: // tables
516: {
517: Value *valready=(Value *)tables.get(HEADER_NAME);
518: bool existed=valready!=0;
519: Table *table;
520: if(existed) {
521: // second+ appearence
522: table=valready->get_table();
523: } else {
524: // first appearence
525: Table::columns_type columns =new ArrayString(1);
526: *columns+=new String("value");
527: table=new Table(columns);
528: }
529: // this string becomes next row
530: ArrayString& row=*new ArrayString(1);
531: row+=&header_value;
532: *table+=&row;
533: // not existed before? add it
534: if(!existed)
535: tables.put(HEADER_NAME, new VTable(table));
536: }
537:
1.154 paf 538: result.headers->put(HEADER_NAME, new VString(header_value));
1.126 paf 539: }
1.154 paf 540: // defaulting to used-asked charset [it's never empty!]
541: if(!real_remote_charset)
542: real_remote_charset=asked_remote_charset;
1.126 paf 543:
544: // output response
1.171 paf 545: String::C real_body=String::C(raw_body, raw_body_size);
546: if(as_text && raw_body_size) // must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
1.169 paf 547: real_body=Charset::transcode(real_body, *real_remote_charset, charsets.source());
1.154 paf 548:
549: result.str=const_cast<char *>(real_body.str); // hacking a little
550: result.length=real_body.length;
551: result.headers->put(file_status_name, new VInt(status_code));
552: return result;
1.34 paf 553: }
1.123 paf 554:
1.154 paf 555: #endif
556:
1.123 paf 557: #ifndef DOXYGEN
558: struct File_read_action_info {
1.154 paf 559: char **data; size_t *data_size;
1.126 paf 560: };
1.123 paf 561: #endif
1.154 paf 562: static void file_read_action(
563: struct stat& finfo,
564: int f,
1.166 paf 565: const String& file_spec, const char* /*fname*/, bool as_text,
1.154 paf 566: void *context) {
1.126 paf 567: File_read_action_info& info=*static_cast<File_read_action_info *>(context);
1.123 paf 568: if(size_t to_read_size=(size_t)finfo.st_size) {
1.154 paf 569: *info.data=new(PointerFreeGC) char[to_read_size+(as_text?1:0)];
1.126 paf 570: *info.data_size=(size_t)read(f, *info.data, to_read_size);
1.123 paf 571:
572: if(ssize_t(*info.data_size)<0 || *info.data_size>to_read_size)
1.126 paf 573: throw Exception(0,
1.123 paf 574: &file_spec,
1.173 paf 575: "read failed: actually read %u bytes count not in [0..%u] valid range",
1.126 paf 576: *info.data_size, to_read_size);
1.123 paf 577: } else { // empty file
578: if(as_text) {
1.154 paf 579: *info.data=new(PointerFreeGC) char[1];
1.123 paf 580: *(char*)(*info.data)=0;
581: } else
582: *info.data=0;
583: *info.data_size=0;
584: return;
585: }
1.126 paf 586: }
1.154 paf 587: File_read_result file_read(Request_charsets& charsets, const String& file_spec,
588: bool as_text, HashStringValue *params,
1.126 paf 589: bool fail_on_read_problem) {
1.167 paf 590: File_read_result result={false, 0, 0, 0};
1.154 paf 591: #ifdef PA_HTTP
592: if(file_spec.starts_with("http://")) {
1.126 paf 593: // fail on read problem
1.169 paf 594: File_read_http_result http=file_read_http(charsets, file_spec, as_text, params);
1.154 paf 595: result.success=true;
596: result.str=http.str;
597: result.length=http.length;
598: result.headers=http.headers;
1.126 paf 599: } else {
1.154 paf 600: #endif
1.161 paf 601: if(params && params->count())
602: throw Exception("parser.runtime",
603: 0,
604: "invalid option passed");
605:
1.154 paf 606: File_read_action_info info={&result.str, &result.length};
607: result.success=file_read_action_under_lock(file_spec,
1.126 paf 608: "read", file_read_action, &info,
609: as_text, fail_on_read_problem);
1.154 paf 610: #ifdef PA_HTTP
1.126 paf 611: }
1.154 paf 612: #endif
1.123 paf 613:
1.154 paf 614: if(result.success && as_text) {
1.131 paf 615: // UTF-8 signature: EF BB BF
1.154 paf 616: if(result.length>=3) {
617: char *in=(char *)result.str;
1.159 paf 618: if(strncmp(in, "\xEF\xBB\xBF", 3)==0) {
1.154 paf 619: result.str=in+3; result.length-=3;// skip prefix
1.131 paf 620: }
621: }
622:
1.154 paf 623: fix_line_breaks((char *)(result.str), result.length);
1.123 paf 624: }
1.126 paf 625:
626: return result;
1.123 paf 627: }
628:
1.154 paf 629: #ifdef PA_SAFE_MODE
630: void check_safe_mode(struct stat finfo, const String& file_spec, const char* fname) {
631: if(finfo.st_uid/*foreign?*/!=geteuid()
632: && finfo.st_gid/*foreign?*/!=getegid())
633: throw Exception("parser.runtime",
634: &file_spec,
635: "parser is in safe mode: "
636: "reading files of foreign group and user disabled "
637: "[recompile parser with --disable-safe-mode configure option], "
638: "actual filename '%s', "
639: "fuid(%d)!=euid(%d) or fgid(%d)!=egid(%d)",
640: fname,
641: finfo.st_uid, geteuid(),
642: finfo.st_gid, getegid());
643: }
644: #endif
1.149 paf 645:
1.154 paf 646: bool file_read_action_under_lock(const String& file_spec,
1.126 paf 647: const char* action_name, File_read_action action, void *context,
648: bool as_text,
1.123 paf 649: bool fail_on_read_problem) {
1.154 paf 650: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.33 paf 651: int f;
652:
653: // first open, next stat:
1.45 paf 654: // directory update of NTFS hard links performed on open.
1.33 paf 655: // ex:
656: // a.html:^test[] and b.html hardlink to a.html
657: // user inserts ! before ^test in a.html
1.126 paf 658: // directory entry of b.html in NTFS not updated at once,
1.35 paf 659: // they delay update till open, so we would receive "!^test[" string
660: // if would do stat, next open.
1.123 paf 661: // later: it seems, even this does not help sometimes
1.98 paf 662: if((f=open(fname, O_RDONLY|(as_text?_O_TEXT:_O_BINARY)))>=0) {
1.123 paf 663: try {
1.162 paf 664: if(pa_lock_shared_blocking(f)!=0)
1.126 paf 665: throw Exception("file.lock",
1.123 paf 666: &file_spec,
667: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 668: strerror(errno), errno, fname);
1.123 paf 669:
1.124 paf 670: struct stat finfo;
671: if(stat(fname, &finfo)!=0)
672: throw Exception("file.missing", // hardly possible: we just opened it OK
673: &file_spec,
674: "stat failed: %s (%d), actual filename '%s'",
1.154 paf 675: strerror(errno), errno, fname);
1.124 paf 676:
1.140 paf 677: #ifdef PA_SAFE_MODE
1.149 paf 678: check_safe_mode(finfo, file_spec, fname);
1.105 paf 679: #endif
1.32 paf 680:
1.154 paf 681: action(finfo, f, file_spec, fname, as_text, context);
1.123 paf 682: } catch(...) {
1.162 paf 683: pa_unlock(f);close(f);
1.123 paf 684: if(fail_on_read_problem)
1.154 paf 685: rethrow;
1.123 paf 686: return false;
687: }
1.87 paf 688:
1.162 paf 689: pa_unlock(f);close(f);
1.72 parser 690: return true;
1.118 paf 691: } else {
692: if(fail_on_read_problem)
1.126 paf 693: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.118 paf 694: &file_spec,
1.123 paf 695: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 696: action_name, strerror(errno), errno, fname);
1.118 paf 697: return false;
698: }
1.8 paf 699: }
700:
1.63 parser 701: static void create_dir_for_file(const String& file_spec) {
702: size_t pos_after=1;
1.154 paf 703: size_t pos_before;
704: while((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND) {
705: mkdir(file_spec.mid(0, pos_before).cstr(String::L_FILE_SPEC), 0775);
1.63 parser 706: pos_after=pos_before+1;
707: }
708: }
709:
1.98 paf 710: bool file_write_action_under_lock(
1.28 paf 711: const String& file_spec,
1.126 paf 712: const char* action_name, File_write_action action, void *context,
713: bool as_text,
714: bool do_append,
715: bool do_block,
1.110 paf 716: bool fail_on_lock_problem) {
1.154 paf 717: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.28 paf 718: int f;
1.80 paf 719: if(access(fname, W_OK)!=0) // no
1.126 paf 720: create_dir_for_file(file_spec);
1.50 paf 721:
1.80 paf 722: if((f=open(fname,
723: O_CREAT|O_RDWR
724: |(as_text?_O_TEXT:_O_BINARY)
1.138 paf 725: |(do_append?O_APPEND:PA_O_TRUNC), 0664))>=0) {
1.162 paf 726: if((do_block?pa_lock_exclusive_blocking(f):pa_lock_exclusive_nonblocking(f))!=0) {
1.126 paf 727: Exception e("file.lock",
1.110 paf 728: &file_spec,
729: "shared lock failed: %s (%d), actual filename '%s'",
1.154 paf 730: strerror(errno), errno, fname);
1.126 paf 731: close(f);
1.110 paf 732: if(fail_on_lock_problem)
733: throw e;
1.98 paf 734: return false;
735: }
1.96 paf 736:
1.158 paf 737: try {
1.126 paf 738: action(f, context);
1.158 paf 739: } catch(...) {
1.138 paf 740: #ifdef HAVE_FTRUNCATE
1.104 paf 741: if(!do_append)
1.125 paf 742: ftruncate(f, lseek(f, 0, SEEK_CUR)); // one can not use O_TRUNC, read lower
1.138 paf 743: #endif
1.162 paf 744: pa_unlock(f);close(f);
1.154 paf 745: rethrow;
1.158 paf 746: }
1.80 paf 747:
1.138 paf 748: #ifdef HAVE_FTRUNCATE
1.104 paf 749: if(!do_append)
1.125 paf 750: 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 751: #endif
1.162 paf 752: pa_unlock(f);close(f);
1.98 paf 753: return true;
1.80 paf 754: } else
1.126 paf 755: throw Exception(errno==EACCES?"file.access":0,
1.80 paf 756: &file_spec,
1.96 paf 757: "%s failed: %s (%d), actual filename '%s'",
1.154 paf 758: action_name, strerror(errno), errno, fname);
1.96 paf 759: // here should be nothing, see rethrow above
760: }
761:
762: #ifndef DOXYGEN
763: struct File_write_action_info {
1.154 paf 764: const char* str; size_t length;
1.126 paf 765: };
1.96 paf 766: #endif
767: static void file_write_action(int f, void *context) {
1.126 paf 768: File_write_action_info& info=*static_cast<File_write_action_info *>(context);
1.154 paf 769: if(info.length) {
770: int written=write(f, info.str, info.length);
1.116 paf 771: if(written<0)
1.126 paf 772: throw Exception(0,
773: 0,
774: "write failed: %s (%d)", strerror(errno), errno);
1.113 paf 775: }
1.96 paf 776: }
777: void file_write(
778: const String& file_spec,
1.154 paf 779: const char* data, size_t size,
1.126 paf 780: bool as_text,
1.96 paf 781: bool do_append) {
1.126 paf 782: File_write_action_info info={data, size};
1.98 paf 783: file_write_action_under_lock(
1.154 paf 784: file_spec,
785: "write", file_write_action, &info,
786: as_text,
787: do_append);
1.30 paf 788: }
789:
1.63 parser 790: // throws nothing! [this is required in file_move & file_delete]
1.50 paf 791: static void rmdir(const String& file_spec, size_t pos_after) {
1.154 paf 792: size_t pos_before;
793: if((pos_before=file_spec.pos('/', pos_after))!=STRING_NOT_FOUND)
1.126 paf 794: rmdir(file_spec, pos_before+1);
1.50 paf 795:
1.154 paf 796: rmdir(file_spec.mid(0, pos_after-1/* / */).cstr(String::L_FILE_SPEC));
1.50 paf 797: }
1.164 paf 798: bool file_delete(const String& file_spec, bool fail_on_problem) {
1.154 paf 799: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.54 parser 800: if(unlink(fname)!=0)
1.164 paf 801: if(fail_on_problem)
1.126 paf 802: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.93 paf 803: &file_spec,
804: "unlink failed: %s (%d), actual filename '%s'",
1.154 paf 805: strerror(errno), errno, fname);
1.93 paf 806: else
807: return false;
1.50 paf 808:
1.126 paf 809: rmdir(file_spec, 1);
1.93 paf 810: return true;
1.60 parser 811: }
1.95 paf 812: void file_move(const String& old_spec, const String& new_spec) {
1.154 paf 813: const char* old_spec_cstr=old_spec.cstr(String::L_FILE_SPEC);
814: const char* new_spec_cstr=new_spec.cstr(String::L_FILE_SPEC);
1.63 parser 815:
1.126 paf 816: create_dir_for_file(new_spec);
1.63 parser 817:
1.60 parser 818: if(rename(old_spec_cstr, new_spec_cstr)!=0)
1.126 paf 819: throw Exception(errno==EACCES?"file.access":errno==ENOENT?"file.missing":0,
1.60 parser 820: &old_spec,
821: "rename failed: %s (%d), actual filename '%s' to '%s'",
1.154 paf 822: strerror(errno), errno, old_spec_cstr, new_spec_cstr);
1.63 parser 823:
1.126 paf 824: rmdir(old_spec, 1);
1.31 paf 825: }
826:
1.51 paf 827:
1.126 paf 828: bool entry_exists(const char* fname, struct stat *afinfo) {
1.118 paf 829: struct stat lfinfo;
830: bool result=stat(fname, &lfinfo)==0;
831: if(afinfo)
832: *afinfo=lfinfo;
833: return result;
1.119 paf 834: }
835:
836: bool entry_exists(const String& file_spec) {
1.154 paf 837: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
1.126 paf 838: return entry_exists(fname, 0);
1.118 paf 839: }
840:
1.51 paf 841: static bool entry_readable(const String& file_spec, bool need_dir) {
1.154 paf 842: char* fname=file_spec.cstrm(String::L_FILE_SPEC);
1.120 paf 843: if(need_dir) {
1.126 paf 844: size_t size=strlen(fname);
1.120 paf 845: while(size) {
1.126 paf 846: char c=fname[size-1];
1.120 paf 847: if(c=='/' || c=='\\')
848: fname[--size]=0;
849: else
850: break;
851: }
852: }
1.51 paf 853: struct stat finfo;
1.118 paf 854: if(access(fname, R_OK)==0 && entry_exists(fname, &finfo)) {
1.109 paf 855: bool is_dir=(finfo.st_mode&S_IFDIR) != 0;
1.51 paf 856: return is_dir==need_dir;
857: }
858: return false;
859: }
1.31 paf 860: bool file_readable(const String& file_spec) {
1.126 paf 861: return entry_readable(file_spec, false);
1.51 paf 862: }
863: bool dir_readable(const String& file_spec) {
1.126 paf 864: return entry_readable(file_spec, true);
1.65 parser 865: }
1.154 paf 866: const String* file_readable(const String& path, const String& name) {
867: String& result=*new String(path);
868: result << "/";
869: result << name;
870: return file_readable(result)?&result:0;
1.43 paf 871: }
872: bool file_executable(const String& file_spec) {
1.154 paf 873: return access(file_spec.cstr(String::L_FILE_SPEC), X_OK)==0;
1.44 paf 874: }
875:
1.64 parser 876: bool file_stat(const String& file_spec,
1.58 parser 877: size_t& rsize,
1.126 paf 878: time_t& ratime,
879: time_t& rmtime,
880: time_t& rctime,
1.64 parser 881: bool fail_on_read_problem) {
1.154 paf 882: const char* fname=file_spec.cstr(String::L_FILE_SPEC);
883: struct stat finfo;
1.44 paf 884: if(stat(fname, &finfo)!=0)
1.64 parser 885: if(fail_on_read_problem)
1.126 paf 886: throw Exception("file.missing",
1.67 parser 887: &file_spec,
888: "getting file size failed: %s (%d), real filename '%s'",
1.154 paf 889: strerror(errno), errno, fname);
1.64 parser 890: else
891: return false;
1.58 parser 892: rsize=finfo.st_size;
893: ratime=finfo.st_atime;
894: rmtime=finfo.st_mtime;
895: rctime=finfo.st_ctime;
1.64 parser 896: return true;
1.18 paf 897: }
898:
1.126 paf 899: char* getrow(char* *row_ref, char delim) {
900: char* result=*row_ref;
1.8 paf 901: if(result) {
1.126 paf 902: *row_ref=strchr(result, delim);
1.8 paf 903: if(*row_ref)
904: *((*row_ref)++)=0;
905: else if(!*result)
906: return 0;
907: }
908: return result;
909: }
910:
1.126 paf 911: char* lsplit(char* string, char delim) {
1.23 paf 912: if(string) {
1.126 paf 913: char* v=strchr(string, delim);
1.8 paf 914: if(v) {
915: *v=0;
916: return v+1;
917: }
918: }
919: return 0;
920: }
921:
1.126 paf 922: char* lsplit(char* *string_ref, char delim) {
923: char* result=*string_ref;
924: char* next=lsplit(*string_ref, delim);
1.8 paf 925: *string_ref=next;
926: return result;
1.9 paf 927: }
928:
1.126 paf 929: char* rsplit(char* string, char delim) {
1.18 paf 930: if(string) {
1.126 paf 931: char* v=strrchr(string, delim);
1.18 paf 932: if(v) {
1.9 paf 933: *v=0;
934: return v+1;
935: }
936: }
937: return NULL;
1.10 paf 938: }
939:
1.37 paf 940: /// @todo less stupid type detection
1.154 paf 941: const char* format(double value, char* fmt) {
1.126 paf 942: char local_buf[MAX_NUMBER];
1.108 paf 943: size_t size;
944:
1.10 paf 945: if(fmt)
946: if(strpbrk(fmt, "diouxX"))
947: if(strpbrk(fmt, "ouxX"))
1.126 paf 948: size=snprintf(local_buf, sizeof(local_buf), fmt, (uint)value);
1.10 paf 949: else
1.126 paf 950: size=snprintf(local_buf, sizeof(local_buf), fmt, (int)value);
1.10 paf 951: else
1.126 paf 952: size=snprintf(local_buf, sizeof(local_buf), fmt, value);
1.10 paf 953: else
1.126 paf 954: size=snprintf(local_buf, sizeof(local_buf), "%d", (int)value);
1.10 paf 955:
1.154 paf 956: return pa_strdup(local_buf, size);
1.12 paf 957: }
958:
1.36 paf 959: size_t stdout_write(const void *buf, size_t size) {
1.12 paf 960: #ifdef WIN32
961: do{
1.154 paf 962: int chunk_written=fwrite(buf, 1, min((size_t)8*0x400, size), stdout);
1.12 paf 963: if(chunk_written<=0)
964: break;
965: size-=chunk_written;
1.36 paf 966: buf=((const char*)buf)+chunk_written;
1.126 paf 967: } while(size>0);
1.12 paf 968:
969: return size;
970: #else
1.126 paf 971: return fwrite(buf, 1, size, stdout);
1.12 paf 972: #endif
1.2 paf 973: }
1.14 paf 974:
1.154 paf 975: char* unescape_chars(const char* cp, int len) {
976: char* s=new(PointerFreeGC) char[len + 1];
1.14 paf 977: enum EscapeState {
1.33 paf 978: EscapeRest,
979: EscapeFirst,
1.14 paf 980: EscapeSecond
981: } escapeState=EscapeRest;
982: int escapedValue=0;
983: int srcPos=0;
984: int dstPos=0;
985: while(srcPos < len) {
1.126 paf 986: int ch=cp[srcPos];
1.14 paf 987: switch(escapeState) {
988: case EscapeRest:
989: if(ch=='%') {
990: escapeState=EscapeFirst;
991: } else if(ch=='+') {
1.126 paf 992: s[dstPos++]=' ';
1.14 paf 993: } else {
994: s[dstPos++]=ch;
995: }
996: break;
997: case EscapeFirst:
998: escapedValue=hex_value[ch] << 4;
999: escapeState=EscapeSecond;
1000: break;
1001: case EscapeSecond:
1.126 paf 1002: escapedValue +=hex_value[ch];
1.14 paf 1003: s[dstPos++]=escapedValue;
1004: escapeState=EscapeRest;
1005: break;
1006: }
1.126 paf 1007: srcPos++;
1.14 paf 1008: }
1009: s[dstPos]=0;
1010: return s;
1.24 paf 1011: }
1012:
1013: #ifdef WIN32
1.126 paf 1014: void back_slashes_to_slashes(char* s) {
1.24 paf 1015: if(s)
1016: for(; *s; s++)
1017: if(*s=='\\')
1.126 paf 1018: *s='/';
1.24 paf 1019: }
1.42 paf 1020: /*
1.126 paf 1021: void slashes_to_back_slashes(char* s) {
1.42 paf 1022: if(s)
1023: for(; *s; s++)
1024: if(*s=='/')
1.126 paf 1025: *s='\\';
1.42 paf 1026: }
1027: */
1.24 paf 1028: #endif
1.41 paf 1029:
1.126 paf 1030: bool StrEqNc(const char* s1, const char* s2, bool strict) {
1.41 paf 1031: while(true) {
1032: if(!(*s1)) {
1033: if(!(*s2))
1034: return true;
1035: else
1036: return !strict;
1037: } else if(!(*s2))
1038: return !strict;
1039: if(isalpha(*s1)) {
1040: if(tolower(*s1) !=tolower(*s2))
1041: return false;
1042: } else if((*s1) !=(*s2))
1043: return false;
1.126 paf 1044: s1++;
1045: s2++;
1.41 paf 1046: }
1.57 parser 1047: }
1048:
1.84 paf 1049: static bool isLeap(int year) {
1.57 parser 1050: return !(
1051: (year % 4) || ((year % 400) && !(year % 100))
1.126 paf 1052: );
1.57 parser 1053: }
1054:
1055: int getMonthDays(int year, int month) {
1056: int monthDays[]={
1.126 paf 1057: 31,
1058: isLeap(year) ? 29 : 28,
1059: 31,
1060: 30,
1061: 31,
1062: 30,
1063: 31,
1064: 31,
1065: 30,
1066: 31,
1067: 30,
1.57 parser 1068: 31
1.126 paf 1069: };
1070: return monthDays[month];
1.41 paf 1071: }
1.69 parser 1072:
1.126 paf 1073: void remove_crlf(char* start, char* end) {
1074: for(char* p=start; p<end; p++)
1.69 parser 1075: switch(*p) {
1.126 paf 1076: case '\n': *p='|'; break;
1077: case '\r': *p=' '; break;
1.69 parser 1078: }
1.91 paf 1079: }
1080:
1081:
1082: /// must be last in this file
1083: #undef vsnprintf
1.126 paf 1084: int __vsnprintf(char* b, size_t s, const char* f, va_list l) {
1.91 paf 1085: if(!s)
1086: return 0;
1087:
1088: int r;
1089: // note: on win32& maybe somewhere else
1090: // vsnprintf do not writes terminating 0 in 'buffer full' case, reducing
1091: --s;
1.172 paf 1092:
1093: // clients do not check for negative 's', feature: ignore such prints
1094: if((ssize_t)s<0)
1095: return 0;
1096:
1.91 paf 1097: #if _MSC_VER
1098: /*
1099: win32:
1100: mk:@MSITStore:C:\Program%20Files\Microsoft%20Visual%20Studio\MSDN\2001APR\1033\vccore.chm::/html/_crt__vsnprintf.2c_._vsnwprintf.htm
1101:
1.154 paf 1102: if the number of bytes to write exceeds buffer, then count bytes are written and Ö1 is returned
1.91 paf 1103: */
1.126 paf 1104: r=_vsnprintf(b, s, f, l);
1.91 paf 1105: if(r<0)
1106: r=s;
1107: #else
1.126 paf 1108: r=vsnprintf(b, s, f, l);
1.91 paf 1109: /*
1110: solaris:
1111: man vsnprintf
1112:
1113: The snprintf() function returns the number of characters
1114: formatted, that is, the number of characters that would have
1115: been written to the buffer if it were large enough. If the
1116: value of n is 0 on a call to snprintf(), an unspecified
1117: value less than 1 is returned.
1118: */
1119:
1120: if(r<0)
1121: r=0;
1.167 paf 1122: else if((size_t)r>s)
1.91 paf 1123: r=s;
1124: #endif
1125: b[r]=0;
1126: return r;
1127: }
1128:
1.126 paf 1129: int __snprintf(char* b, size_t s, const char* f, ...) {
1.91 paf 1130: va_list l;
1.126 paf 1131: va_start(l, f);
1132: int r=__vsnprintf(b, s, f, l);
1133: va_end(l);
1.91 paf 1134: return r;
1.178 ! paf 1135: }
! 1136:
! 1137: /* mime64 functions are from libgmime[http://spruce.sourceforge.net/gmime/] lib */
! 1138: /*
! 1139: * Authors: Michael Zucchi <notzed@helixcode.com>
! 1140: * Jeffrey Stedfast <fejj@helixcode.com>
! 1141: *
! 1142: * Copyright 2000 Helix Code, Inc. (www.helixcode.com)
! 1143: *
! 1144: * This program is free software; you can redistribute it and/or modify
! 1145: * it under the terms of the GNU General Public License as published by
! 1146: * the Free Software Foundation; either version 2 of the License, or
! 1147: * (at your option) any later version.
! 1148: *
! 1149: * This program is distributed in the hope that it will be useful,
! 1150: * but WITHOUT ANY WARRANTY; without even the implied warranty of
! 1151: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
! 1152: * GNU General Public License for more details.
! 1153: *
! 1154: * You should have received a copy of the GNU General Public License
! 1155: * along with this program; if not, write to the Free Software
! 1156: * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
! 1157: *
! 1158: */
! 1159: static char *base64_alphabet =
! 1160: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
! 1161:
! 1162: /**
! 1163: * g_mime_utils_base64_encode_step:
! 1164: * @in: input stream
! 1165: * @inlen: length of the input
! 1166: * @out: output string
! 1167: * @state: holds the number of bits that are stored in @save
! 1168: * @save: leftover bits that have not yet been encoded
! 1169: *
! 1170: * Base64 encodes a chunk of data. Performs an 'encode step', only
! 1171: * encodes blocks of 3 characters to the output at a time, saves
! 1172: * left-over state in state and save (initialise to 0 on first
! 1173: * invocation).
! 1174: *
! 1175: * Returns the number of bytes encoded.
! 1176: **/
! 1177: static size_t
! 1178: g_mime_utils_base64_encode_step (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
! 1179: {
! 1180: const register unsigned char *inptr;
! 1181: register unsigned char *outptr;
! 1182:
! 1183: if (inlen <= 0)
! 1184: return 0;
! 1185:
! 1186: inptr = in;
! 1187: outptr = out;
! 1188:
! 1189: if (inlen + ((unsigned char *)save)[0] > 2) {
! 1190: const unsigned char *inend = in + inlen - 2;
! 1191: register int c1 = 0, c2 = 0, c3 = 0;
! 1192: register int already;
! 1193:
! 1194: already = *state;
! 1195:
! 1196: switch (((char *)save)[0]) {
! 1197: case 1: c1 = ((unsigned char *)save)[1]; goto skip1;
! 1198: case 2: c1 = ((unsigned char *)save)[1];
! 1199: c2 = ((unsigned char *)save)[2]; goto skip2;
! 1200: }
! 1201:
! 1202: /* yes, we jump into the loop, no i'm not going to change it, its beautiful! */
! 1203: while (inptr < inend) {
! 1204: c1 = *inptr++;
! 1205: skip1:
! 1206: c2 = *inptr++;
! 1207: skip2:
! 1208: c3 = *inptr++;
! 1209: *outptr++ = base64_alphabet [c1 >> 2];
! 1210: *outptr++ = base64_alphabet [(c2 >> 4) | ((c1 & 0x3) << 4)];
! 1211: *outptr++ = base64_alphabet [((c2 & 0x0f) << 2) | (c3 >> 6)];
! 1212: *outptr++ = base64_alphabet [c3 & 0x3f];
! 1213: /* this is a bit ugly ... */
! 1214: if ((++already) >= 19) {
! 1215: *outptr++ = '\n';
! 1216: already = 0;
! 1217: }
! 1218: }
! 1219:
! 1220: ((unsigned char *)save)[0] = 0;
! 1221: inlen = 2 - (inptr - inend);
! 1222: *state = already;
! 1223: }
! 1224:
! 1225: //d(printf ("state = %d, inlen = %d\n", (int)((char *)save)[0], inlen));
! 1226:
! 1227: if (inlen > 0) {
! 1228: register char *saveout;
! 1229:
! 1230: /* points to the slot for the next char to save */
! 1231: saveout = & (((char *)save)[1]) + ((char *)save)[0];
! 1232:
! 1233: /* inlen can only be 0 1 or 2 */
! 1234: switch (inlen) {
! 1235: case 2: *saveout++ = *inptr++;
! 1236: case 1: *saveout++ = *inptr++;
! 1237: }
! 1238: ((char *)save)[0] += inlen;
! 1239: }
! 1240:
! 1241: /*d(printf ("mode = %d\nc1 = %c\nc2 = %c\n",
! 1242: (int)((char *)save)[0],
! 1243: (int)((char *)save)[1],
! 1244: (int)((char *)save)[2]));*/
! 1245:
! 1246: return (outptr - out);
! 1247: }
! 1248:
! 1249: /**
! 1250: * g_mime_utils_base64_encode_close:
! 1251: * @in: input stream
! 1252: * @inlen: length of the input
! 1253: * @out: output string
! 1254: * @state: holds the number of bits that are stored in @save
! 1255: * @save: leftover bits that have not yet been encoded
! 1256: *
! 1257: * Base64 encodes the input stream to the output stream. Call this
! 1258: * when finished encoding data with g_mime_utils_base64_encode_step to
! 1259: * flush off the last little bit.
! 1260: *
! 1261: * Returns the number of bytes encoded.
! 1262: **/
! 1263: static size_t
! 1264: g_mime_utils_base64_encode_close (const unsigned char *in, size_t inlen, unsigned char *out, int *state, int *save)
! 1265: {
! 1266: unsigned char *outptr = out;
! 1267: int c1, c2;
! 1268:
! 1269: if (inlen > 0)
! 1270: outptr += g_mime_utils_base64_encode_step (in, inlen, outptr, state, save);
! 1271:
! 1272: c1 = ((unsigned char *)save)[1];
! 1273: c2 = ((unsigned char *)save)[2];
! 1274:
! 1275: switch (((unsigned char *)save)[0]) {
! 1276: case 2:
! 1277: outptr[2] = base64_alphabet [(c2 & 0x0f) << 2];
! 1278: goto skip;
! 1279: case 1:
! 1280: outptr[2] = '=';
! 1281: skip:
! 1282: outptr[0] = base64_alphabet [c1 >> 2];
! 1283: outptr[1] = base64_alphabet [c2 >> 4 | ((c1 & 0x3) << 4)];
! 1284: outptr[3] = '=';
! 1285: outptr += 4;
! 1286: break;
! 1287: }
! 1288:
! 1289: *outptr++ = 0;
! 1290:
! 1291: *save = 0;
! 1292: *state = 0;
! 1293:
! 1294: return (outptr - out);
! 1295: }
! 1296:
! 1297: char* pa_base64(const char *in, size_t len)
! 1298: {
! 1299: /* wont go to more than 2x size (overly conservative) */
! 1300: char* result=new(PointerFreeGC) char[len * 2 + 6];
! 1301: int state=0;
! 1302: int save=0;
! 1303: size_t filled=g_mime_utils_base64_encode_close ((const unsigned char*)in, len,
! 1304: (unsigned char*)result, &state, &save);
! 1305: assert(filled <= len * 2 + 6);
! 1306:
! 1307: return result;
1.98 paf 1308: }
E-mail: