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