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