Annotation of parser3/src/types/pa_vmail.C, revision 1.17
1.1 paf 1: /** @file
2: Parser: @b mail class.
3: relies on gmime library, by Jeffrey Stedfast <fejj@helixcode.com>
4:
5: Copyright(c) 2001, 2002 ArtLebedev Group(http://www.artlebedev.com)
6: Author: Alexandr Petrosian <paf@design.ru>(http://paf.design.ru)
7: */
1.13 paf 8:
1.17 ! paf 9: static const char* IDENT_VMAIL_C="$Date: 2002/08/07 07:28:26 $";
1.1 paf 10:
11: #include "pa_sapi.h"
12: #include "pa_vmail.h"
13: #include "pa_vstring.h"
14: #include "pa_request.h"
15: #include "pa_common.h"
16: #include "pa_charset.h"
17: #include "pa_charsets.h"
18: #include "pa_vdate.h"
19: #include "pa_vfile.h"
20: #include "pa_uue.h"
21:
1.3 paf 22: #ifdef WITH_MAILRECEIVE
1.4 paf 23: extern "C" {
1.1 paf 24: #include "gmime.h"
1.4 paf 25: }
1.1 paf 26: #endif
27:
28: // defines
29:
30: #define RAW_NAME "raw"
31:
32: // internals
33:
34: enum PartType {
35: P_TEXT,
36: P_HTML,
37: P_FILE,
38: P_MESSAGE,
39:
40: P_TYPES_COUNT
41: };
42:
43: static const char * const part_name_starts[P_TYPES_COUNT]={"text", "html", "file", "message"};
44:
45: // VMail
46:
47: extern Methoded *mail_base_class;
48:
49: VMail::VMail(Pool& apool) : VStateless_class(apool, 0, mail_base_class),
50: vreceived(apool) {
51: }
52:
1.3 paf 53: #ifdef WITH_MAILRECEIVE
1.1 paf 54:
55: static const String& maybeUpperCase(Pool& pool, const String& src, bool toUpperCase) {
56: return toUpperCase?src.change_case(pool, String::CC_UPPER):src;
57: }
58:
59: static void UTF8toSource(Pool& pool, const char *source_body, size_t source_content_length,
60: const void *& dest_body, size_t& dest_content_length) {
61: if(source_body) {
62: if(!source_content_length)
63: source_content_length=strlen(source_body);
64: Charset::transcode(pool,
65: *utf8_charset, source_body, source_content_length,
66: pool.get_source_charset(), dest_body, dest_content_length);
67: } else {
68: dest_body=0;
69: dest_content_length=0;
70: }
71: }
72:
73: static void putReceived(Hash& received, const char *name, Value *value, bool nameToUpperCase=false) {
74: Pool& pool=received.pool();
75: if(name && value) {
76: received.put(
77: maybeUpperCase(pool, String::OnPool(pool, name, 0, true/*tainted*/), nameToUpperCase),
78: value);
79: }
80: }
81:
82: static void putReceived(Hash& received, const char *name, const char *value, size_t value_size=0, bool nameToUpperCase=false) {
83: if(value) {
84: Pool& pool=received.pool();
85:
86: const void *value_dest_body;
87: size_t value_dest_content_length;
88: UTF8toSource(pool, value, value_size, value_dest_body, value_dest_content_length);
89:
90: putReceived(received, name,
91: new(pool) VString(
92: String::OnPool(pool,(const char *)value_dest_body, value_dest_content_length, true/*tainted*/)));
93: }
94: }
95:
96: static void putReceived(Hash& received, const char *name, time_t value) {
97: Pool& pool=received.pool();
98: if(name)
99: received.put(String::OnPool(pool, name, 0, true/*tainted*/), new(pool) VDate(pool, value));
100: }
101:
102: static void MimeHeaderField2received(const char *name, const char *value, gpointer data) {
103: Hash& received=*static_cast<Hash *>(data);
104:
105: putReceived(received, name, value, 0, true/*nameInUpperCase*/);
106: }
107:
108: static void parse(GMimeStream *stream, Hash& received);
109:
110: #ifndef DOXYGEN
111: struct MimePart2bodyInfo {
112: Hash *body;
113: int partCounts[P_TYPES_COUNT];
114: };
115: #endif
116: static void MimePart2body(GMimePart *part,
117: gpointer data) {
118: MimePart2bodyInfo& i=*static_cast<MimePart2bodyInfo *>(data);
119: Pool& pool=i.body->pool();
120:
121: if(const GMimeContentType *type=g_mime_part_get_content_type(part)) {
122: if(g_mime_content_type_is_type(type, "multipart", "*"))
123: return; // skipping frames
124:
125: PartType partType;
126: if(g_mime_content_type_is_type(type, "text", "plain"))
127: partType=P_TEXT;
128: else if(g_mime_content_type_is_type(type, "text", "html"))
129: partType=P_HTML;
130: else if(g_mime_content_type_is_type(type, "message", "*"))
131: partType=P_MESSAGE;
132: else
133: partType=P_FILE;
134:
135: // partName
136: const char *partName;
137: char partNameBuf[MAX_STRING];
138: const char *partNameStart=part_name_starts[partType];
139: if(int partNo=i.partCounts[partType]++) {
140: snprintf(partNameBuf, MAX_STRING, "%s%d", partNameStart, partNo);
141: partName=partNameBuf;
142: } else
143: partName=partNameStart;
144:
145: // $.partX[
146: VHash& vpartX=*new(pool) VHash(pool); putReceived(*i.body, partName, &vpartX);
147: Hash& partX=vpartX.hash(0);
148: {
149: // $.raw[
150: VHash& vraw=*new(pool) VHash(pool); putReceived(partX, RAW_NAME, &vraw);
151: g_mime_header_foreach(part->headers, MimeHeaderField2received, &vraw.hash(0));
152: }
153: const char *content_filename=0;
154: {
155: // $.content-type[
156: VHash& vcontent_type=*new(pool) VHash(pool); putReceived(partX, "content-type", &vcontent_type);
157: Hash& content_type=vcontent_type.hash(0);
158: {
159: // $.value[text/plain]
160: char value[MAX_STRING];
161: snprintf(value, MAX_STRING, "%s/%s",
162: type->type?type->type:"x-unknown",
163: type->subtype?type->subtype:"x-unknown");
164: putReceived(content_type, VALUE_NAME, value);
165: }
166: GMimeParam *param=type->params;
167: while(param) {
168: // $.charset[windows-1251] && co
169: putReceived(content_type, param->name, param->value, true);
170: if(strcasecmp(param->name, "name")==0)
171: content_filename=param->value;
172: param=param->next;
173: }
174: }
175: // $.description
176: putReceived(partX, "description", part->description);
177: // $.content-id
178: putReceived(partX, "content-id", part->content_id);
179: // $.content-md5
180: putReceived(partX, "content-md5", part->content_md5);
181: // $.content-location
182: putReceived(partX, "content-location", part->content_location);
183:
184: // todo GMimePart:
185: // GMimePartEncodingType encoding;
186: // GMimeDisposition *disposition;
187: if(part->disposition) {
188: GMimeParam *param=part->disposition->params;
189: while(param) {
190: // $.charset[windows-1251] && co
191: if(strcasecmp(param->name, "filename")==0)
192: content_filename=param->value;
193: param=param->next;
194: }
195: }
196:
197: // MESSAGE
198: if(partType==P_MESSAGE) {
199: if(part->content)
200: if(GMimeStream *stream=part->content->stream)
201: parse(stream, partX);
202: } else {
203: // $.value[string|file]
204: size_t buf_len;
1.15 paf 205: const void *local_buf=g_mime_part_get_content(part, &buf_len);
1.1 paf 206: if(partType==P_FILE) {
207: VFile& vfile=*new(pool) VFile(pool);
1.15 paf 208: char *global_buf=(char *)pool.malloc(buf_len);
209: memcpy(global_buf, local_buf, buf_len);
210: vfile.set(true/*tainted*/, global_buf, buf_len, content_filename);
1.1 paf 211: putReceived(partX, VALUE_NAME, &vfile);
212: } else {
213: // P_TEXT, P_HTML
1.15 paf 214: putReceived(partX, VALUE_NAME,(const char*)local_buf, buf_len);
1.1 paf 215: }
216: }
217: }
218: }
219:
220: static void parse(GMimeStream *stream, Hash& received) {
221: Pool& pool=received.pool();
222:
223: GMimeMessage *message=g_mime_parser_construct_message(stream);
224: try {
225: const GMimeMessageHeader *messageHeader=message->header;
226: if(!messageHeader)
227: return;
228:
229: // firstly user-defined strings go
230: // user headers
231: {
232: // $.raw[
1.5 paf 233: VHash& vraw=*new(pool) VHash(pool); putReceived(received, RAW_NAME, &vraw);
1.1 paf 234: g_mime_header_foreach(messageHeader->headers, MimeHeaderField2received, &vraw.hash(0));
235: }
236:
237: // maybe-todo-recipients
238: // x(messageHeader->recipients)
239:
240: // secondly standard headers&body go
241: // standard header
242: // .from
243: putReceived(received, "from", messageHeader->from);
244: // .reply-to
245: putReceived(received, "reply-to", messageHeader->reply_to);
246: // .to
247: // todo: messageHeader->recipients
248: // .subject
249: putReceived(received, "subject", messageHeader->subject);
250: // .date(date+gmt_offset)
251: int tt_offset =
252: ((messageHeader->gmt_offset / 100) *(60 * 60))
253: +(messageHeader->gmt_offset % 100) * 60;
254: putReceived(received, "date",
255: messageHeader->date // local sender
256: -tt_offset // move local sender to GMT sender
257: -(timezone+(daylight?60*60*sign(timezone):0)) // move GMT sender to our local time
258: );
259: // .message-id
260: putReceived(received, "message-id", messageHeader->message_id);
261:
262: // .body[part/parts
263: GMimePart *part=message->mime_part;
264: const GMimeContentType *type=g_mime_part_get_content_type(part);
265: MimePart2bodyInfo info={&received};
266: g_mime_part_foreach(part, MimePart2body, &info);
267:
268: // normal unref
269: g_mime_object_unref(GMIME_OBJECT(message));
270: } catch(...) {
271: // abnormal unref
272: g_mime_object_unref(GMIME_OBJECT(message));
273: }
274: }
275: #endif
276:
277:
278:
279: void VMail::fill_received(Request& request) {
280: // store letter to received
1.3 paf 281: #ifdef WITH_MAILRECEIVE
1.1 paf 282: if(request.info.mail_received) {
283: // init
284: g_mime_init(GMIME_INIT_FLAG_UTF8);
285:
286: // create stream with CRLF filter
287: GMimeStream *stream = g_mime_stream_fs_new(fileno(stdin));
288: GMimeStream *istream = g_mime_stream_filter_new_with_stream(stream);
289: GMimeFilter *filter = g_mime_filter_crlf_new(GMIME_FILTER_CRLF_DECODE, GMIME_FILTER_CRLF_MODE_CRLF_ONLY);
290: g_mime_stream_filter_add(GMIME_STREAM_FILTER(istream), filter);
291: g_mime_stream_unref(stream);
292: stream = istream;
293: try {
294: // parse incoming stream
295: parse(stream, vreceived.hash(0));
296: // normal stream free
297: g_mime_stream_unref(stream);
298: } catch(...) {
299: // abnormal stream free
300: g_mime_stream_unref(stream);
301: }
302: }
303: #endif
304: }
305:
306: #ifndef DOXYGEN
307: struct Store_message_element_info {
308: Charset *charset;
309: String *header;
1.11 paf 310: const String **from, **to;
311: const String *errors_to;
1.1 paf 312: Array *parts[P_TYPES_COUNT];
313: int parts_count;
314: bool has_content_type;
315: };
316: #endif
1.9 paf 317: typedef int (*string_contains_char_which_check)(int);
318: static bool string_contains_char_which(const char *string, string_contains_char_which_check check) {
319: while(char c=*string++) {
320: if(check(c))
321: return true;
322: }
323: return false;
324: }
325: const String& extractEmail(const String& string) {
326: Pool& pool=string.pool();
327:
328: char *email=string.cstr();
329: lsplit(email, '>'); lsplit(email, '\x0D');lsplit(email, '\x0A');
330: char *next=rsplit(email, '<');
331: if(next) email=next;
332:
333: String& result=*new(pool) String(pool);
334: result.APPEND_TAINTED(email, 0, string.origin().file, string.origin().line);
335:
336: /*
337: http://www.faqs.org/rfcs/rfc822.html
338:
339: addr-spec = local-part "@" domain ; global address
340:
341: local-part = word *("." word) ; uninterpreted case-preserved
342: word = atom / quoted-string
343:
344: domain = sub-domain *("." sub-domain)
345: sub-domain = domain-ref / domain-literal
346: domain-ref = atom ; symbolic reference
347:
348: domain-literal << ignoring for now
349: quoted-string in word << ignoring for now
350:
351: atom = 1*<any CHAR except specials, SPACE and CTLs> << the ONLY to check
352:
353: specials = "(" / ")" / "<" / ">" / "@" ; Must be in quoted-
354: / "," / ";" / ":" / "\" / <"> ; string, to use
355: / "." / "[" / "]" ; within a word.
356:
357: */
1.17 ! paf 358: const char *exception_type="email.format";
1.9 paf 359: if(strpbrk(email, "()<>,;:\\\"[]"/*specials minus @ and . */))
1.17 ! paf 360: throw Exception(exception_type,
1.9 paf 361: &result,
362: "email contains characters (specials)");
363: if(string_contains_char_which(email, (string_contains_char_which_check)isspace))
1.17 ! paf 364: throw Exception(exception_type,
1.9 paf 365: &result,
366: "email contains characters (whitespace)");
367: if(string_contains_char_which(email, (string_contains_char_which_check)iscntrl))
1.17 ! paf 368: throw Exception(exception_type,
1.9 paf 369: &result,
370: "email contains characters (control)");
1.16 paf 371: if(result.is_empty())
1.17 ! paf 372: throw Exception(exception_type,
1.16 paf 373: &string,
374: "email is empty");
1.9 paf 375:
376: return result;
377: }
1.5 paf 378: static void store_message_element(const Hash::Key& raw_element_name, Hash::Val *aelement_value,
1.1 paf 379: void *info) {
380: Value& element_value=*static_cast<Value *>(aelement_value);
1.5 paf 381: const String& low_element_name=raw_element_name.change_case(raw_element_name.pool(), String::CC_LOWER);
1.1 paf 382: Store_message_element_info& i=*static_cast<Store_message_element_info *>(info);
383:
384: // exclude internals
1.5 paf 385: if(low_element_name==CHARSET_NAME
386: || low_element_name==VALUE_NAME
387: || low_element_name==RAW_NAME
388: || low_element_name=="date")
1.1 paf 389: return;
390:
391: // grep parts
392: for(int pt=0; pt<P_TYPES_COUNT; pt++) {
1.5 paf 393: if(low_element_name.starts_with(part_name_starts[pt])) {
1.1 paf 394: *i.parts[pt]+=&element_value;
395: i.parts_count++;
396: return;
397: }
398: }
399:
1.10 paf 400: // fetch some special headers
1.5 paf 401: if(i.from && low_element_name=="from")
1.9 paf 402: *i.from=&extractEmail(element_value.as_string());
1.5 paf 403: if(i.to && low_element_name=="to")
1.9 paf 404: *i.to=&extractEmail(element_value.as_string());
1.12 paf 405: if(low_element_name=="errors-to")
1.11 paf 406: i.errors_to=&extractEmail(element_value.as_string());
1.1 paf 407:
408: // append header line
409: *i.header <<
1.5 paf 410: raw_element_name << ":" <<
1.1 paf 411: attributed_meaning_to_string(element_value, String::UL_MAIL_HEADER).
412: cstr(String::UL_UNSPECIFIED, 0, i.charset, i.charset?i.charset->name().cstr():0) <<
413: "\n";
414:
415: // has content type?
1.5 paf 416: if(low_element_name==CONTENT_TYPE_NAME)
1.1 paf 417: i.has_content_type=true;
418: }
419:
420: static const String& file_value_to_string(Request& r, const String *source,
421: Value& send_value) {
422: Pool& pool=r.pool();
423: const VFile *vfile;
424: const String *file_name;
425: Value *vformat;
426: if(Hash *send_hash=send_value.get_hash(source)) { // hash
427: // $.value
428: if(Value *value=static_cast<Value *>(send_hash->get(*value_name)))
429: vfile=value->as_vfile(String::UL_AS_IS);
430: else
431: throw Exception("parser.runtime",
432: source,
433: "file part has no $value");
434:
435: // $.format
436: vformat=static_cast<Value *>(send_hash->get(*new(pool) String(pool, "format")));
437:
1.6 paf 438: // $.name
1.1 paf 439: if(Value *vfile_name=static_cast<Value *>(send_hash->get(
1.6 paf 440: *new(pool) String(pool, "name")))) // specified $name
1.1 paf 441: file_name=&vfile_name->as_string();
442: } else { // must be VFile
443: vfile=send_value.as_vfile(String::UL_AS_IS);
444: file_name=&static_cast<Value *>(vfile->fields().get(*name_name))->as_string();
445: vformat=0;
446: }
447: const char *file_name_cstr=file_name->cstr();
448:
449: String& result=*new(pool) String(pool);
450:
451: // content-type: application/octet-stream
452: result << "content-type: " << r.mime_type_of(file_name_cstr)
453: << "; name=\"" << file_name_cstr << "\"\n";
454: // content-disposition: attachment; filename="user_file_name"
455: result << "content-disposition: attachment; filename=\"" << file_name_cstr << "\"\n";
456:
457: const String *type=vformat?&vformat->as_string():0;
458: if(!type/*default = uue*/ || *type=="uue") {
459: pa_uuencode(result, file_name_cstr, *vfile);
460: } else // for now
461: throw Exception("parser.runtime",
462: type,
463: "unknown attachment encode format");
464:
465: return result;
466: }
467:
468: static const String& text_value_to_string(Request& r, const String *source,
469: PartType pt, Value& send_value,
470: Store_message_element_info& info) {
471: Pool& pool=r.pool();
472: String& result=*new(pool) String(pool);
473:
474: Value *text_value;
475: if(Hash *send_hash=send_value.get_hash(source)) {
476: // $.USER-HEADERS
477: info.has_content_type=false; // reset
478: send_hash->for_each(store_message_element, &info);
479: // $.value
480: text_value=static_cast<Value *>(send_hash->get(*value_name));
481: if(!text_value)
482: throw Exception("parser.runtime",
483: source,
484: "%s part has no $" VALUE_NAME, part_name_starts[pt]);
485: } else
486: text_value=&send_value;
487:
488: if(!info.has_content_type) {
489: result << "content-type: text/" << (pt==P_TEXT?"plain":"html");
490: if(info.charset)
491: result << "; charset=" << info.charset->name();
492: result << "\n";
493: }
494:
495: // header|body separator
496: result << "\n";
497:
498: // body
499: switch(pt) {
500: case P_TEXT:
501: result.append(text_value->as_string(), String::UL_AS_IS, true /* forced */);
502: break;
503: case P_HTML:
504: {
505: Temp_lang temp_lang(r, String::UL_HTML);
506: if(Junction *junction=text_value->get_junction()) {
507: // execution of found $.html{code} must be in context of ^send[...]
508: // setting code context, would execute in ^.send[>>context<<]
509: //junction->change_context(?.get_junction());
510: junction->root=r.root;
511: junction->rcontext=r.rcontext;
512: junction->wcontext=r.wcontext;
513:
514: result << r.process_to_string(*text_value);
515: } else
516: throw Exception("parser.runtime",
517: source,
518: "html part value must be code");
519:
520: break;
521: }
522: }
523:
524: return result;
525: };
526:
527: /// @todo files and messages in order (file, file2, ...)
528: const String& VMail::message_hash_to_string(Request& r, const String *source,
529: Hash *message_hash, int level,
530: const String **from, const String **to) {
531: if(!message_hash)
532: throw Exception("parser.runtime",
533: source,
534: "message must be hash");
535:
536: String& result=*NEW String(pool());
537:
538: Charset *charset;
539: if(Value *vrecodecharset_name=static_cast<Value *>(message_hash->get(*charset_name)))
540: charset=&charsets->get_charset(vrecodecharset_name->as_string());
541: else
542: charset=&pool().get_source_charset();
543:
544: Store_message_element_info info={
545: charset,
546: &result,
547: from, to
548: };
549: {
550: if(from)
551: *from=0;
552: if(to)
553: *to=0;
554: for(int pt=0; pt<P_TYPES_COUNT; pt++)
555: info.parts[pt]=NEW Array(pool());
556: message_hash->for_each(store_message_element, &info);
1.10 paf 557: if(!info.errors_to)
558: result << "errors-to: postmaster\n"; // errors-to: default
1.1 paf 559: }
560:
561: int textCount=info.parts[P_TEXT]->size();
562: if(textCount>1)
563: throw Exception("parser.runtime",
564: source,
565: "multiple text parts not supported, use file part");
566: int htmlCount=info.parts[P_HTML]->size();
567: if(htmlCount>1)
568: throw Exception("parser.runtime",
569: source,
570: "multiple html parts not supported, use file part");
571:
572:
573: bool multipart=info.parts_count>1;
574: bool alternative=textCount && htmlCount;
575: // header
576: char *boundary=0;
577: if(multipart) {
578: boundary=(char *)malloc(MAX_NUMBER);
579: snprintf(boundary, MAX_NUMBER-5/*lEvEl*/, "lEvEl%d", level);
580: // multi-part
581: result << "content-type: multipart/mixed; boundary=\"" << boundary << "\"\n";
582: result << "\n"
583: "This is a multi-part message in MIME format.";
584: }
585:
586: // alternative or not
587: {
588: if(alternative) {
589: result << "\n\n--" << boundary << "\n"; // intermediate boundary
590: result << "content-type: multipart/alternative; boundary=\"ALT" << boundary << "\"\n";
591: }
592: for(int i=0; i<2; i++) {
593: PartType pt=i==0?P_TEXT:P_HTML;
594: if(info.parts[pt]->size()) {
595: if(alternative)
596: result << "\n\n--ALT" << boundary << "\n"; // intermediate boundary
597: else if(boundary)
598: result << "\n\n--" << boundary << "\n"; // intermediate boundary
599: result << text_value_to_string(r, source, pt,
600: *static_cast<Value *>(info.parts[pt]->get(0)), info);
601: }
602: }
603: if(alternative)
604: result << "\n\n--ALT" << boundary << "--\n";
605: }
606:
607: // files
608: {
609: Array& files=*info.parts[P_FILE];
610: for(int i=0; i<files.size(); i++) {
611: if(boundary)
612: result << "\n\n--" << boundary << "\n"; // intermediate boundary
613: result << file_value_to_string(r, source, *static_cast<Value *>(files.get(i)));
614: }
615: }
616:
617: // messages
618: {
619: Array& messages=*info.parts[P_MESSAGE];
620: for(int i=0; i<messages.size(); i++) {
621: if(boundary)
622: result << "\n\n--" << boundary << "\n"; // intermediate boundary
623:
624: result << message_hash_to_string(r, source,
625: static_cast<Value *>(messages.get(i))->get_hash(source),
626: level+1);
627: }
628: }
629:
630: // tailer
631: if(boundary)
632: result << "\n\n--" << boundary << "--\n"; // finish boundary
633:
634: // return
635: return result;
636: }
637:
638:
639: Value *VMail::get_element(const String& aname) {
640: // $fields
1.3 paf 641: #ifdef WITH_MAILRECEIVE
1.1 paf 642: if(aname==MAIL_RECEIVED_ELEMENT_NAME)
643: return &vreceived;
644: #endif
645:
646: // $CLASS,$method
647: if(Value *result=VStateless_class::get_element(aname))
648: return result;
649:
650: return 0;
651: }
652:
1.3 paf 653: #if defined(WITH_MAILRECEIVE) && defined(_MSC_VER)
1.1 paf 654: # define GNOME_LIBS "/parser3project/win32mailreceive/win32/gnome"
655: # pragma comment(lib, GNOME_LIBS "/glib/lib/libglib-1.3-11.lib")
656: # ifdef _DEBUG
657: # pragma comment(lib, GNOME_LIBS "/gmime-x.x.x/Debug/libgmime.lib")
658: # else
659: # pragma comment(lib, GNOME_LIBS "/gmime-x.x.x/Release/libgmime.lib")
660: # endif
661: #endif
E-mail: