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