Annotation of parser3/src/types/pa_vmail.C, revision 1.152
1.1 paf 1: /** @file
2: Parser: @b mail class.
3: relies on gmime library, by Jeffrey Stedfast <fejj@helixcode.com>
4:
1.149 moko 5: Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)
1.141 moko 6: Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.1 paf 7: */
1.13 paf 8:
1.1 paf 9: #include "pa_sapi.h"
10: #include "pa_vmail.h"
11: #include "pa_vstring.h"
12: #include "pa_request.h"
13: #include "pa_common.h"
1.127 moko 14: #include "pa_base64.h"
1.1 paf 15: #include "pa_charset.h"
16: #include "pa_charsets.h"
1.118 moko 17: #include "pa_random.h"
1.1 paf 18: #include "pa_vdate.h"
19: #include "pa_vfile.h"
1.146 moko 20: #include "pa_varray.h"
1.1 paf 21: #include "pa_uue.h"
1.151 moko 22: #include "pa_threads.h"
1.1 paf 23:
1.152 ! moko 24: volatile const char * IDENT_PA_VMAIL_C="$Id: pa_vmail.C,v 1.151 2026/11/05 11:40:32 moko Exp $" IDENT_PA_VMAIL_H;
1.98 moko 25:
1.3 paf 26: #ifdef WITH_MAILRECEIVE
1.4 paf 27: extern "C" {
1.99 moko 28: #include "gmime/gmime.h"
1.4 paf 29: }
1.45 paf 30:
31: #include "pa_charsets.h"
1.1 paf 32: #endif
33:
34: // defines
35:
36: #define RAW_NAME "raw"
1.146 moko 37: #define ELEMENTS_NAME "elements"
1.1 paf 38:
39: // internals
40:
41: enum PartType {
42: P_TEXT,
43: P_HTML,
44: P_FILE,
45: P_MESSAGE,
46: P_TYPES_COUNT
47: };
48:
1.99 moko 49: static const char* const part_name_begins[P_TYPES_COUNT] = {
50: "text",
51: "html",
52: "file",
53: "message"
54: };
1.45 paf 55:
56: // defines for statics
57:
58: #define FORMAT_NAME "format"
59: #define CHARSET_NAME "charset"
1.76 misha 60: #define CID_NAME "content-id"
1.45 paf 61:
1.112 moko 62: #define CONTENT_TRANSFER_ENCODING_NAME "content-transfer-encoding"
63: #define CONTENT_TRANSFER_ENCODING_CAPITALIZED "Content-Transfer-Encoding"
64:
1.45 paf 65: // statics
66:
67: static const String format_name(FORMAT_NAME);
68: static const String charset_name(CHARSET_NAME);
1.76 misha 69: static const String cid_name(CID_NAME);
1.1 paf 70:
1.112 moko 71: static const String content_transfer_encoding_name(CONTENT_TRANSFER_ENCODING_NAME);
72:
1.61 paf 73: // consts
74:
1.126 moko 75: const int MAX_CHARS_IN_HEADER_LINE = (991 - 9 /* Subject: */ - 19 /* =?Windows-1251?Q?...?= */ - 128 /* just in case */) / 3 /* quote-printable */ - 5 /* maximum part of trancated UTF-8 char */;
1.61 paf 76:
1.1 paf 77: // VMail
78:
1.116 moko 79: extern Methoded* mail_class;
1.1 paf 80:
1.117 moko 81: VMail::VMail(): VStateless_class(mail_class) {}
1.1 paf 82:
1.3 paf 83: #ifdef WITH_MAILRECEIVE
1.1 paf 84:
1.48 paf 85: #define EXCEPTION_VALUE "x-exception"
86:
1.151 moko 87: static THREAD_LOCAL Charset* source_charset;
88:
89: /// releases the reference to the object [stream, filter, parser, message] when the scope is left
90: class Temp_gobject_ref {
91: gpointer fobject;
92: public:
93: Temp_gobject_ref(gpointer aobject): fobject(aobject) {}
94: ~Temp_gobject_ref() { g_object_unref(fobject); }
95: };
96:
97: /// the stream keeps the filter, so the reference of the caller is released
98: static void add_filter(GMimeStream *stream, GMimeFilter *filter) {
99: if(filter) {
100: g_mime_stream_filter_add(GMIME_STREAM_FILTER(stream), filter);
101: g_object_unref(filter);
102: }
103: }
1.99 moko 104:
1.107 moko 105: static const char *transcode(const char *value) {
106: if(value && !source_charset->isUTF8()){
1.121 moko 107: String::C transcoded=Charset::transcode(String::C(value, strlen(value)), pa_UTF8_charset, *source_charset);
1.107 moko 108: value=transcoded.str;
109: }
110: return value;
111: }
112:
1.99 moko 113: static void putReceived(HashStringValue& received, const char* name, Value* value, bool capitalizeName=false) {
114: if(name && value)
115: received.put(capitalizeName ? capitalize(pa_strdup(name)) : pa_strdup(name), value);
1.1 paf 116: }
117:
1.99 moko 118: static void putReceived(HashStringValue& received, const char* name, const char* value, bool capitalizeName=false) {
119: if(name && value)
1.148 moko 120: putReceived(received, name, new VString(pa_strdup(value)), capitalizeName);
1.1 paf 121: }
122:
1.99 moko 123: static void putReceived(HashStringValue& received, const char* name, time_t value) {
124: if(name)
125: received.put(pa_strdup(name), new VDate(value) );
1.1 paf 126: }
127:
1.140 moko 128: struct Field2received_info {
129: HashStringValue *hash;
1.146 moko 130: HashStringValue *elements;
1.140 moko 131:
132: Field2received_info(HashStringValue& part){
133: VHash* vhash(new VHash);
1.146 moko 134: VHash* velements(new VHash);
1.140 moko 135: putReceived(part, RAW_NAME, vhash);
1.146 moko 136: putReceived(part, ELEMENTS_NAME, velements);
1.140 moko 137: hash=&vhash->hash();
1.146 moko 138: elements=&velements->hash();
1.140 moko 139: }
140: };
141:
142:
1.99 moko 143: static void MimeHeaderField2received(const char* name, const char* value, gpointer data) {
1.140 moko 144: Field2received_info* info=static_cast<Field2received_info*>(data);
145:
146: if(name && value){
147: name = capitalize(pa_strdup(name));
1.148 moko 148: VString *svalue = new VString(pa_strdup(value));
1.140 moko 149:
1.146 moko 150: info->hash->put(name, svalue);
1.140 moko 151:
1.146 moko 152: // elements
153: VArray* varray=(VArray*)(info->elements->get(name));
154: if(!varray)
155: info->elements->put(name, varray=new VArray());
156: varray->array()+=svalue;
1.140 moko 157: }
1.1 paf 158: }
159:
1.99 moko 160: static void parse(Request& r, GMimeMessage *message, HashStringValue& received);
1.1 paf 161:
162: #ifndef DOXYGEN
1.45 paf 163: struct MimePart2body_info {
164: Request* r;
165: HashStringValue* body;
1.1 paf 166: int partCounts[P_TYPES_COUNT];
167: };
168: #endif
1.99 moko 169:
1.128 moko 170: #if GMIME_MAJOR_VERSION > 2
171: typedef void (* GMimeHeaderForeachFunc) (const char *name, const char *value, gpointer user_data);
172:
1.130 moko 173: void g_mime_header_list_foreach (GMimeHeaderList *headers, GMimeHeaderForeachFunc func, gpointer user_data) {
1.128 moko 174: int cnt = g_mime_header_list_get_count(headers);
175: for(int i = 0; i < cnt; i++){
176: GMimeHeader *header = g_mime_header_list_get_header_at(headers, i);
177: func (g_mime_header_get_name(header), g_mime_header_get_value(header), user_data);
178: }
179: }
180:
181: #define g_mime_part_get_content_object(arg) g_mime_part_get_content(arg)
1.129 moko 182: #define g_mime_filter_crlf_new(encode, dots) g_mime_filter_dos2unix_new(encode)
1.128 moko 183:
1.131 moko 184: #define G_MIME_CTYPE_PARAMS(action) { \
185: GMimeParamList *params=g_mime_content_type_get_parameters(type); \
186: int cnt = g_mime_param_list_length(params); \
187: for(int i = 0; i < cnt; i++){ \
188: GMimeParam *param = g_mime_param_list_get_parameter_at(params, i); \
189: action \
1.128 moko 190: }}
191:
192: #else
193:
1.131 moko 194: #define G_MIME_CTYPE_PARAMS(action) { \
195: const GMimeParam *param=g_mime_content_type_get_params(type); \
196: while(param) { \
197: action \
198: param=g_mime_param_next(param); \
1.128 moko 199: }}
200:
1.131 moko 201: #define g_mime_init() g_mime_init(0)
202:
1.129 moko 203: #define g_mime_parser_construct_message(msg,p) g_mime_parser_construct_message(msg)
1.128 moko 204:
205: #endif
1.99 moko 206:
207: static char *readStream(GMimeStream* gstream, size_t &length){
208: length=MAX_STRING;
209: char *result=(char*)pa_malloc_atomic(length+1);
210: char *ptr=result;
211:
212: while(true) {
213: size_t current_size=ptr-result;
214: ssize_t todo_size=length-current_size;
215: ssize_t received_size=g_mime_stream_read (gstream, ptr, todo_size);
216:
217: if(received_size<0)
1.133 moko 218: throw Exception(PARSER_RUNTIME, 0, "mail content stream read error");
1.99 moko 219: if(received_size==0)
220: break;
221: if(received_size==todo_size) {
222: length=length*2;
223: result=(char *)pa_realloc(result, length+1);
224: ptr=result+current_size+received_size;
225: } else {
226: ptr+=received_size;
227: }
228: }
229:
230: length=ptr-result;
231: result[length]='\0';
232: return result;
233: }
234:
235: static void MimePart2body(GMimeObject *parent, GMimeObject *part, gpointer data) {
1.45 paf 236: MimePart2body_info& info=*static_cast<MimePart2body_info *>(data);
1.1 paf 237:
1.99 moko 238: // skipping message/partial & frames
1.101 moko 239: if (GMIME_IS_MESSAGE_PARTIAL (part) || GMIME_IS_MULTIPART (part))
1.99 moko 240: return;
241:
242: if (GMimeContentType *type=g_mime_object_get_content_type(part)) {
243: PartType partType=P_FILE;
244:
1.107 moko 245: if (GMIME_IS_MESSAGE_PART(part)){
1.99 moko 246: partType=P_MESSAGE;
1.107 moko 247: } else {
248: const char *disposition=g_mime_object_get_disposition(part);
249: if(!disposition || strcmp(disposition, GMIME_DISPOSITION_ATTACHMENT)){
250: if(g_mime_content_type_is_type(type, "text", "plain"))
251: partType=P_TEXT;
252: else if(g_mime_content_type_is_type(type, "text", "html"))
253: partType=P_HTML;
254: }
255: }
1.99 moko 256:
1.1 paf 257: // partName
1.99 moko 258: int partNumber=++info.partCounts[partType];
259: const char *partName=part_name_begins[partType];
1.1 paf 260:
1.99 moko 261: char partNameNumbered[MAX_STRING];
1.150 moko 262: pa_snprintf(partNameNumbered, MAX_STRING, "%s%d", partName, partNumber);
1.1 paf 263:
1.99 moko 264: // $.partN[
265: VHash* vpartHash(new VHash);
266: if(partNumber==1)
267: putReceived(*info.body, partName, vpartHash);
268: putReceived(*info.body, partNameNumbered, vpartHash);
269:
270: HashStringValue& partHash=vpartHash->hash();
271:
272: // $.raw[
1.140 moko 273: Field2received_info f2r_info(partHash);
274: g_mime_header_list_foreach(part->headers, MimeHeaderField2received, &f2r_info);
1.99 moko 275:
276: // $.content-type[
277: VHash* vcontent_type(new VHash);
278: putReceived(partHash, "content-type", vcontent_type);
279:
280: // $.value[text/plain]
281: char value[MAX_STRING];
1.150 moko 282: pa_snprintf(value, MAX_STRING, "%s/%s", type->type ? type->type : "x-unknown", type->subtype ? type->subtype : "x-unknown");
1.99 moko 283: putReceived(vcontent_type->hash(), VALUE_NAME, value);
284:
1.128 moko 285: // $.charset[windows-1251] && co
286: G_MIME_CTYPE_PARAMS(
1.107 moko 287: putReceived(vcontent_type->hash(), g_mime_param_get_name(param), transcode(g_mime_param_get_value(param)), true /*capitalizeName*/);
1.128 moko 288: );
1.99 moko 289:
290: if (GMIME_IS_MESSAGE_PART (part)) {
1.102 moko 291: /* message/rfc822, $.raw[] will be overwitten */
1.99 moko 292: GMimeMessage *message = g_mime_message_part_get_message ((GMimeMessagePart *) part);
293: parse(*info.r, message, partHash);
1.1 paf 294: } else {
1.101 moko 295: GMimePart *gpart = (GMimePart *)part;
296:
297: putReceived(partHash, "description", g_mime_part_get_content_description(gpart));
298: putReceived(partHash, "content-id", g_mime_part_get_content_id(gpart));
299: putReceived(partHash, "content-md5", g_mime_part_get_content_md5(gpart));
300: putReceived(partHash, "content-location", g_mime_part_get_content_location(gpart));
301:
1.1 paf 302: // $.value[string|file]
1.103 moko 303: if(GMimeDataWrapper* gcontent=g_mime_part_get_content_object(gpart)){
304: GMimeStream* gstream=g_mime_stream_filter_new(g_mime_data_wrapper_get_stream(gcontent));
1.151 moko 305: Temp_gobject_ref gstream_ref(gstream);
1.103 moko 306:
1.151 moko 307: add_filter(gstream, g_mime_filter_basic_new(g_mime_part_get_content_encoding(gpart), false));
1.103 moko 308:
309: size_t length;
1.99 moko 310:
1.103 moko 311: if(partType==P_FILE) {
312: char *content=readStream(gstream, length);
1.107 moko 313: const char* content_filename=transcode(g_mime_part_get_filename(gpart));
1.103 moko 314: VFile* vfile(new VFile);
315: vfile->set_binary(true/*tainted*/, content, length, new String(content_filename), content_filename ? new VString(info.r->mime_type_of(content_filename)) : 0);
316: putReceived(partHash, VALUE_NAME, vfile);
317: } else {
318: // P_TEXT, P_HTML
319: if(Value *charset=vcontent_type->hash().get("Charset"))
1.151 moko 320: add_filter(gstream, g_mime_filter_charset_new(charset->get_string()->cstr(), source_charset->NAME_CSTR()));
1.103 moko 321:
322: char *content=readStream(gstream, length);
323: putReceived(partHash, VALUE_NAME,new VString(*new String(content)));
324: }
1.1 paf 325: }
326: }
327: }
328: }
329:
1.99 moko 330: static void parse(Request& r, GMimeMessage *message, HashStringValue& received) {
1.1 paf 331: try {
332: // firstly user-defined strings go
333: // user headers
334: {
335: // $.raw[
1.140 moko 336: Field2received_info f2r_info(received);
337: g_mime_header_list_foreach(g_mime_object_get_header_list(GMIME_OBJECT(message)), MimeHeaderField2received, &f2r_info);
1.99 moko 338: }
339:
340: // secondly standard headers
341: putReceived(received, "message-id", g_mime_message_get_message_id(message));
1.107 moko 342:
1.128 moko 343: #if GMIME_MAJOR_VERSION > 2
344: const char *msg_from=internet_address_list_to_string(g_mime_message_get_addresses (message, GMIME_ADDRESS_TYPE_FROM), NULL, false);
345: const char *msg_to=internet_address_list_to_string(g_mime_message_get_addresses (message, GMIME_ADDRESS_TYPE_TO), NULL, false);
346: const char *msg_cc=internet_address_list_to_string(g_mime_message_get_addresses (message, GMIME_ADDRESS_TYPE_CC), NULL, false);
347: const char *msg_reply_to=internet_address_list_to_string(g_mime_message_get_addresses (message, GMIME_ADDRESS_TYPE_REPLY_TO), NULL, false);
348:
349: GDateTime *gdate = g_mime_message_get_date(message);
350: time_t date = gdate ? g_date_time_to_unix(gdate) : 0;
351: #else
352: const char *msg_from=g_mime_message_get_sender(message);
1.107 moko 353: const char *msg_to=internet_address_list_to_string(g_mime_message_get_recipients(message, GMIME_RECIPIENT_TYPE_TO), false);
1.128 moko 354: const char *msg_cc=internet_address_list_to_string(g_mime_message_get_recipients(message, GMIME_RECIPIENT_TYPE_CC), false);
355: const char *msg_reply_to=g_mime_message_get_reply_to(message);
356:
357: time_t date;
358: g_mime_message_get_date(message, &date, 0);
359: #endif
360: putReceived(received, "from", transcode(msg_from));
1.107 moko 361: putReceived(received, "to", transcode(msg_to));
362: putReceived(received, "cc", transcode(msg_cc));
1.128 moko 363: putReceived(received, "reply-to", transcode(msg_reply_to));
1.107 moko 364: putReceived(received, "subject", transcode(g_mime_message_get_subject(message)));
365:
1.151 moko 366: // allocated for the caller, putReceived has made the copies
367: #if GMIME_MAJOR_VERSION > 2
368: g_free((void *)msg_from);
369: g_free((void *)msg_reply_to);
370: #endif
371: g_free((void *)msg_to);
372: g_free((void *)msg_cc);
373:
1.113 moko 374: // .date(time_t in UTC)
1.114 moko 375: putReceived(received, "date", date);
1.1 paf 376:
377: // .body[part/parts
1.55 paf 378: MimePart2body_info info={&r, &received, {0}};
1.99 moko 379: g_mime_message_foreach(message, MimePart2body, &info);
1.1 paf 380:
1.48 paf 381: } catch(const Exception& e) {
1.125 moko 382: putReceived(received, VALUE_NAME, "<exception occurred while parsing message>");
1.99 moko 383: putReceived(received, EXCEPTION_VALUE, e.comment());
1.1 paf 384: } catch(...) {
1.125 moko 385: putReceived(received, VALUE_NAME, "<exception occurred while parsing message>");
1.1 paf 386: }
387: }
388:
1.152 ! moko 389: /// must be called before any gmime object is created
! 390: static void gmime_init() {
! 391: SYNCHRONIZED; // the first initialization is not thread safe, the next ones do nothing. Never shut down: the next message needs it
! 392: g_mime_init();
! 393: }
! 394:
1.151 moko 395: /// the message of the stream into the hash, the same for the incoming one and the one in memory. The reference to the @a source stays with the caller
396: static void parse_stream(Request& r, GMimeStream *source, HashStringValue& received) {
397: source_charset=&r.charsets.source();
398: // create stream with CRLF filter
399: GMimeStream *stream = g_mime_stream_filter_new(source);
400: Temp_gobject_ref stream_ref(stream);
401: add_filter(stream, g_mime_filter_crlf_new(false, false));
402: GMimeParser *parser = g_mime_parser_new_with_stream(stream);
403: Temp_gobject_ref parser_ref(parser);
404: try {
405: // parse the message
406: if(GMimeMessage *message=g_mime_parser_construct_message(parser, NULL)){
407: Temp_gobject_ref message_ref(message);
408: parse(r, message, received);
409: }
410: } catch(const Exception& e) {
411: putReceived(received, VALUE_NAME, "<exception occurred while parsing message>");
412: putReceived(received, EXCEPTION_VALUE, e.comment());
413: }
414: }
415:
1.99 moko 416: void VMail::fill_received(Request& r) {
1.45 paf 417: if(r.request_info.mail_received) {
1.152 ! moko 418: gmime_init();
1.131 moko 419: #if GMIME_MAJOR_VERSION > 2
1.151 moko 420: GMimeStream *source = g_mime_stream_pipe_new(STDIN_FILENO);
1.131 moko 421: #else
1.151 moko 422: GMimeStream *source = g_mime_stream_fs_new(STDIN_FILENO);
1.131 moko 423: #endif
1.151 moko 424: // not released: it would close stdin
425: parse_stream(r, source, vreceived.hash());
1.1 paf 426: }
427: }
428:
1.151 moko 429: VHash& VMail::parse_message(Request& r, const char* message, size_t length) {
430: VHash& result=*new VHash;
1.152 ! moko 431: gmime_init();
1.151 moko 432: GMimeStream *source = g_mime_stream_mem_new_with_buffer(message, length);
433: Temp_gobject_ref source_ref(source);
434: parse_stream(r, source, result.hash());
435: return result;
436: }
437:
1.99 moko 438: #else // WITH_MAILRECEIVE
439: void VMail::fill_received(Request&){}
440: #endif // WITH_MAILRECEIVE
441:
1.9 paf 442: typedef int (*string_contains_char_which_check)(int);
1.99 moko 443:
1.45 paf 444: static bool string_contains_char_which(const char* string, string_contains_char_which_check check) {
1.9 paf 445: while(char c=*string++) {
1.62 paf 446: if(check((unsigned char)c))
1.9 paf 447: return true;
448: }
449: return false;
450: }
1.99 moko 451:
1.32 paf 452: static char *trimBoth(char *s) {
453: // sanity check
454: if(!s)
455: return 0;
456:
457: // trim head whitespace
1.62 paf 458: while(*s && isspace((unsigned char)*s))
1.32 paf 459: s++;
460: // trim tail whitespace
461: char *tail=s+strlen(s);
462: if(tail>s) {
463: do {
464: --tail;
1.62 paf 465: if(isspace((unsigned char)*tail))
1.32 paf 466: *tail=0;
467: } while(tail>s);
468: }
469: // return it
470: return s;
471: }
1.99 moko 472:
1.45 paf 473: static void extractEmail(String& result, char *email) {
1.32 paf 474: email=trimBoth(email);
1.45 paf 475: result.append_help_length(email, 0, String::L_TAINTED);
1.9 paf 476:
477: /*
478: http://www.faqs.org/rfcs/rfc822.html
479:
480: addr-spec = local-part "@" domain ; global address
481:
482: local-part = word *("." word) ; uninterpreted case-preserved
483: word = atom / quoted-string
484:
485: domain = sub-domain *("." sub-domain)
486: sub-domain = domain-ref / domain-literal
487: domain-ref = atom ; symbolic reference
488:
1.92 misha 489: domain-literal << ignoring for now
1.9 paf 490: quoted-string in word << ignoring for now
491:
492: atom = 1*<any CHAR except specials, SPACE and CTLs> << the ONLY to check
493:
494: specials = "(" / ")" / "<" / ">" / "@" ; Must be in quoted-
1.92 misha 495: / "," / ";" / ":" / "\" / <"> ; string, to use
496: / "." / "[" / "]" ; within a word.
1.9 paf 497:
498: */
1.45 paf 499: const char* exception_type="email.format";
1.9 paf 500: if(strpbrk(email, "()<>,;:\\\"[]"/*specials minus @ and . */))
1.126 moko 501: throw Exception(exception_type, &result, "email contains bad characters (specials)");
1.9 paf 502: if(string_contains_char_which(email, (string_contains_char_which_check)isspace))
1.126 moko 503: throw Exception(exception_type, &result, "email contains bad characters (whitespace)");
1.9 paf 504: if(string_contains_char_which(email, (string_contains_char_which_check)iscntrl))
1.126 moko 505: throw Exception(exception_type, &result, "email contains bad characters (control)");
1.16 paf 506: if(result.is_empty())
1.126 moko 507: throw Exception(exception_type, 0, "email is empty");
1.39 paf 508: }
509:
1.45 paf 510: static const String& extractEmails(const String& string) {
511: char *emails=string.cstrm();
512: String& result=*new String;
1.39 paf 513: while(char *email=lsplit(&emails, ',')) {
514: rsplit(email, '>');
515: if(char *in_brackets=lsplit(email, '<'))
516: email=in_brackets;
517: if(!result.is_empty())
518: result<<",";
1.45 paf 519: extractEmail(result, email);
1.39 paf 520: }
1.9 paf 521:
522: return result;
523: }
1.45 paf 524:
525: #ifndef DOXYGEN
526: struct Store_message_element_info {
527: Request_charsets& charsets;
528: String& header;
529: const String* & from;
1.60 paf 530: bool extract_to; String* & to;
1.45 paf 531: bool mime_version_specified;
1.143 moko 532: Array<Value*>* parts[P_TYPES_COUNT];
1.45 paf 533: int parts_count;
534: bool backward_compatibility;
535: Value* content_type;
1.66 paf 536: bool had_content_disposition;
1.45 paf 537:
1.126 moko 538: Store_message_element_info(Request_charsets& acharsets, String& aheader, const String* & afrom, bool aextract_to, String* & ato):
1.45 paf 539: charsets(acharsets),
540: header(aheader),
541: from(afrom),
1.60 paf 542: extract_to(aextract_to), to(ato),
1.45 paf 543: mime_version_specified(false),
544: parts_count(0),
1.66 paf 545: backward_compatibility(false), content_type(0),
1.133 moko 546: had_content_disposition(false)
547: {
548: for(int pt=0; pt<P_TYPES_COUNT; pt++)
1.143 moko 549: parts[pt]=new Array<Value*>(1);
1.45 paf 550: }
551: };
552: #endif
1.99 moko 553:
1.126 moko 554: size_t mail_header_utf8_substring(const char *mail, size_t sub_length, size_t length){
555: int error_offset;
556: if(int error_code=pa_pcre_valid_utf((unsigned char *)mail, sub_length, &error_offset)){
557: if(error_code<PCRE_UTF8_ERR6){ // Missing X byte at the end of the string errors
558: sub_length+=error_code; // adding X bytes
559: return sub_length < length ? sub_length : length;
560: }
561: }
562:
563: return sub_length;
564: }
565:
566: static void store_message_element(HashStringValue::key_type raw_element_name, HashStringValue::value_type element_value, Store_message_element_info *info) {
567: const String& low_element_name=String(raw_element_name, String::L_TAINTED).change_case(info->charsets.source(), String::CC_LOWER);
1.1 paf 568:
569: // exclude internals
1.52 paf 570: if(low_element_name==MAIL_OPTIONS_NAME
571: || low_element_name==CHARSET_NAME
1.5 paf 572: || low_element_name==VALUE_NAME
573: || low_element_name==RAW_NAME
1.146 moko 574: || low_element_name==ELEMENTS_NAME
1.64 paf 575: || low_element_name==FORMAT_NAME
1.76 misha 576: || low_element_name==NAME_NAME
1.94 misha 577: || low_element_name==CID_NAME
578: || low_element_name==MAIL_DEBUG_NAME)
1.1 paf 579: return;
580:
581: // grep parts
582: for(int pt=0; pt<P_TYPES_COUNT; pt++) {
1.45 paf 583: if(low_element_name.starts_with(part_name_begins[pt])) {
1.29 paf 584: // check that $.message# '#' is digit
1.45 paf 585: size_t start_len=strlen(part_name_begins[pt]);
586: if(low_element_name.length()>start_len) {
587: const char* at_num=low_element_name.mid(start_len, start_len+1).cstr();
1.63 paf 588: if(!isdigit((unsigned char)*at_num))
1.29 paf 589: continue;
590: }
1.45 paf 591: *info->parts[pt]+=element_value;
592: info->parts_count++;
1.1 paf 593: return;
594: }
595: }
596:
1.10 paf 597: // fetch some special headers
1.45 paf 598: if(low_element_name=="from")
599: info->from=&extractEmails(element_value->as_string());
1.90 misha 600: if(low_element_name==CONTENT_DISPOSITION)
1.66 paf 601: info->had_content_disposition=true;
1.60 paf 602: if(info->extract_to) { // defined only when SMTP used, see mail.C [collecting info for RCPT to-s]
1.39 paf 603: bool is_to=low_element_name=="to" ;
604: bool is_cc=low_element_name=="cc" ;
605: bool is_bcc=low_element_name=="bcc" ;
606: if(is_to||is_cc||is_bcc) {
1.45 paf 607: if(!info->to)
608: info->to=new String;
1.39 paf 609: else
1.45 paf 610: *info->to << ",";
611: *info->to << extractEmails(element_value->as_string());
1.39 paf 612: }
613:
614: if(is_bcc) // blinding it
1.45 paf 615: return;
1.39 paf 616: }
1.37 paf 617: if(low_element_name=="mime-version")
1.45 paf 618: info->mime_version_specified=true;
1.1 paf 619:
1.45 paf 620: // has content type?
621: if(low_element_name==CONTENT_TYPE_NAME) {
622: info->content_type=element_value;
623: if(info->backward_compatibility)
624: return;
1.39 paf 625: }
1.1 paf 626:
1.45 paf 627: // preparing header line
1.123 moko 628: const String& source_line=attributed_meaning_to_string(*element_value, String::L_AS_IS);
629:
1.66 paf 630: if(source_line.is_empty())
631: return; // we don't need empty headers here [used in clearing content-disposition]
632:
1.45 paf 633: const char* source_line_cstr=source_line.cstr();
1.126 moko 634: String::C mail=Charset::transcode(String::C(source_line_cstr, source_line.length()), info->charsets.source(), info->charsets.mail());
1.92 misha 635:
1.45 paf 636: String& mail_line=*new String;
1.126 moko 637: if(low_element_name=="to" || low_element_name=="cc" || low_element_name=="bcc")
1.73 paf 638: {
1.144 moko 639: // never wrap address lines, mailer cannot handle wrapped properly
1.73 paf 640: mail_line.append_strdup(mail.str, mail.length, String::L_MAIL_HEADER);
641: } else {
642: while(mail.length) {
1.126 moko 643: bool too_long=mail.length > MAX_CHARS_IN_HEADER_LINE;
644: size_t length=too_long ? info->charsets.mail().isUTF8() ? mail_header_utf8_substring(mail.str, MAX_CHARS_IN_HEADER_LINE, mail.length) : MAX_CHARS_IN_HEADER_LINE : mail.length;
1.73 paf 645:
646: mail_line.append_strdup(mail.str, length, String::L_MAIL_HEADER);
1.126 moko 647:
1.73 paf 648: mail.length-=length;
1.126 moko 649: mail.str+=length;
1.73 paf 650:
651: if(too_long)
652: mail_line << "\n "; // break header and continue it on next line
1.126 moko 653: }
1.73 paf 654: }
1.45 paf 655:
656: // append header line
657: info->header
1.91 misha 658: << capitalize(raw_element_name.cstr())
1.96 misha 659: << ": " << mail_line.untaint_cstr(String::L_AS_IS, 0, &info->charsets)
1.45 paf 660: << "\n";
661: }
662:
663: static const String& file_value_to_string(Request& r, Value* send_value) {
1.64 paf 664: String& result=*new String;
665:
1.45 paf 666: VFile* vfile;
667: const String* file_name=0;
668: Value* vformat=0;
1.76 misha 669: Value* vcid=0;
1.66 paf 670: const String* dummy_from;
671: String* dummy_to;
1.95 misha 672: Store_message_element_info info(r.charsets, result, dummy_from, false, dummy_to);
673:
1.120 moko 674: HashStringValue *send_hash=send_value->get_hash();
1.142 moko 675: if(send_hash && !dynamic_cast<VFile*>(send_value)) { // hash
1.74 paf 676: send_hash->for_each<Store_message_element_info*>(store_message_element, &info);
1.64 paf 677:
1.1 paf 678: // $.value
1.45 paf 679: if(Value* value=send_hash->get(value_name))
1.139 moko 680: vfile=value->as_vfile();
1.1 paf 681: else
1.120 moko 682: throw Exception(PARSER_RUNTIME, 0, "file part has no $value");
1.1 paf 683:
684: // $.format
1.45 paf 685: vformat=send_hash->get(format_name);
1.1 paf 686:
1.76 misha 687: // $.content-id
688: vcid=send_hash->get(cid_name);
689:
1.6 paf 690: // $.name
1.45 paf 691: if(Value* vfile_name=send_hash->get(name_name)) // $name specified
1.1 paf 692: file_name=&vfile_name->as_string();
1.28 paf 693: } else // must be VFile then
1.139 moko 694: vfile=send_value->as_vfile();
1.28 paf 695:
696: if(!file_name)
1.45 paf 697: file_name=&vfile->fields().get(name_name)->as_string();
1.28 paf 698:
1.95 misha 699: const char* file_name_cstr;
700: const char* quoted_file_name_cstr;
701: {
702: Request_charsets charsets(r.charsets.source(), r.charsets.mail()/*uri!*/, r.charsets.mail());
1.97 misha 703: file_name_cstr=file_name->untaint_and_transcode_cstr(String::L_FILE_SPEC, &charsets);
1.95 misha 704: quoted_file_name_cstr=String(file_name_cstr).taint_cstr(String::L_MAIL_HEADER, 0, &charsets);
705: }
1.1 paf 706:
1.95 misha 707: // Content-Type: application/octet-stream
708: result
709: << HTTP_CONTENT_TYPE_CAPITALIZED ": "
710: << r.mime_type_of(file_name_cstr)
711: << "; name=\""
712: << quoted_file_name_cstr
713: << "\"\n";
1.66 paf 714:
1.95 misha 715: if(!info.had_content_disposition) // $.Content-Disposition wasn't specified by user
1.79 misha 716: result
1.91 misha 717: << CONTENT_DISPOSITION_CAPITALIZED ": "
1.79 misha 718: << ( vcid ? CONTENT_DISPOSITION_INLINE : CONTENT_DISPOSITION_ATTACHMENT )
719: << "; "
1.95 misha 720: << CONTENT_DISPOSITION_FILENAME_NAME"=\"" << quoted_file_name_cstr << "\"\n";
1.1 paf 721:
1.79 misha 722: if(vcid)
1.93 misha 723: result
724: << "Content-Id: <"
725: << vcid->as_string()
726: << ">\n"; // @todo: value must be escaped as %hh
1.79 misha 727:
1.45 paf 728: const String* type=vformat?&vformat->as_string():0;
1.93 misha 729: if(!type/*default*/ || *type=="base64") {
730: result << CONTENT_TRANSFER_ENCODING_CAPITALIZED ": base64\n\n";
731: result << pa_base64_encode(vfile->value_ptr(), vfile->value_size());
1.75 paf 732: } else {
1.93 misha 733: if(*type=="uue") {
734: result << CONTENT_TRANSFER_ENCODING_CAPITALIZED ": x-uuencode\n\n";
1.95 misha 735: result << pa_uuencode((const unsigned char*)vfile->value_ptr(), vfile->value_size(), file_name_cstr);
736: } else
1.133 moko 737: throw Exception(PARSER_RUNTIME, type, "unknown attachment encode format");
1.75 paf 738: }
1.95 misha 739:
1.1 paf 740: return result;
741: }
742:
1.133 moko 743: static const String& text_value_to_string(Request& r, PartType pt, Value* send_value, Store_message_element_info& info) {
1.45 paf 744: String& result=*new String;
1.1 paf 745:
1.45 paf 746: Value* text_value;
1.81 misha 747: Value* content_transfer_encoding=0;
1.45 paf 748: if(HashStringValue* send_hash=send_value->get_hash()) {
1.1 paf 749: // $.USER-HEADERS
1.92 misha 750: info.content_type=0;
751: info.backward_compatibility=false; // reset
1.74 paf 752: send_hash->for_each<Store_message_element_info*>(store_message_element, &info);
1.1 paf 753: // $.value
1.45 paf 754: text_value=send_hash->get(value_name);
1.1 paf 755: if(!text_value)
1.133 moko 756: throw Exception(PARSER_RUNTIME, 0, "%s part has no $" VALUE_NAME, part_name_begins[pt]);
1.81 misha 757: content_transfer_encoding=send_hash->get(content_transfer_encoding_name);
1.1 paf 758: } else
1.45 paf 759: text_value=send_value;
1.1 paf 760:
1.45 paf 761: if(!info.content_type) {
762: result
1.91 misha 763: << HTTP_CONTENT_TYPE_CAPITALIZED ": text/" << (pt==P_TEXT?"plain":"html")
1.45 paf 764: << "; charset=" << info.charsets.mail().NAME()
765: << "\n";
1.1 paf 766: }
1.81 misha 767: if(!content_transfer_encoding)
1.91 misha 768: result << CONTENT_TRANSFER_ENCODING_CAPITALIZED << ": 8bit\n";
1.1 paf 769:
770: // header|body separator
771: result << "\n";
772:
773: // body
1.45 paf 774: const String* body;
1.122 moko 775: String::Language body_lang=String::L_AS_IS;
776:
1.1 paf 777: switch(pt) {
778: case P_TEXT:
1.92 misha 779: {
780: body=&text_value->as_string();
781: break;
782: }
1.122 moko 783: case P_HTML:
1.1 paf 784: {
1.122 moko 785: body_lang=String::Language(String::L_HTML | String::L_OPTIMIZE_BIT);
1.55 paf 786: if(text_value->get_junction())
1.41 paf 787: body=&r.process_to_string(*text_value);
1.92 misha 788: else
1.122 moko 789: throw Exception(PARSER_RUNTIME, 0, "html part value must be code");
1.1 paf 790: break;
791: }
1.53 paf 792: default:
1.122 moko 793: throw Exception(0, 0, "unhandled part type #%d", pt);
1.41 paf 794: }
1.122 moko 795:
1.41 paf 796: if(body) {
1.69 paf 797: Request_charsets charsets(r.charsets.source(), r.charsets.mail()/*uri!*/, r.charsets.mail());
1.122 moko 798: const char* body_cstr=body->untaint_and_transcode_cstr(body_lang, &charsets);
1.95 misha 799: result.append_know_length(body_cstr, strlen(body_cstr), String::L_CLEAN);
1.1 paf 800: }
801:
802: return result;
1.111 moko 803: }
1.1 paf 804:
805: /// @todo files and messages in order (file, file2, ...)
1.134 moko 806: const String& VMail::message_hash_to_string(Request& r, HashStringValue* message_hash, const String* & from, bool extract_to, String* & to) {
1.34 paf 807:
1.1 paf 808: if(!message_hash)
1.133 moko 809: throw Exception(PARSER_RUNTIME, 0, "message must be hash");
1.1 paf 810:
1.45 paf 811: String& result=*new String;
1.1 paf 812:
1.45 paf 813: if(Value* vrecodecharset_name=message_hash->get(charset_name))
1.121 moko 814: r.charsets.set_mail(pa_charsets.get(vrecodecharset_name->as_string()));
1.1 paf 815: else
1.45 paf 816: r.charsets.set_mail(r.charsets.source());
817: // no big deal that we leave it set. they wont miss this point which would reset it
1.1 paf 818:
1.133 moko 819: Store_message_element_info info(r.charsets, result, from, extract_to, to);
820:
1.1 paf 821: {
1.133 moko 822: // for backward compatibilyty $.body+$.content-type -> $.text[$.value[] $.content-type[]]
1.45 paf 823:
824: Value* body=message_hash->get("body");
825: if(body) {
1.147 moko 826: message_hash->remove(String::Body("body"));
1.45 paf 827: info.backward_compatibility=true;
1.133 moko 828: }
1.74 paf 829: message_hash->for_each<Store_message_element_info*>(store_message_element, &info);
1.45 paf 830:
831: if(body) {
832: VHash& text_part=*new VHash();
833: HashStringValue& hash=text_part.hash();
834: hash.put(value_name, body);
835: if(info.content_type)
836: hash.put(content_type_name, info.content_type);
837:
838: *info.parts[P_TEXT]+=&text_part;
839: info.parts_count++;
840: }
841:
1.37 paf 842: if(!info.mime_version_specified)
843: result << "MIME-Version: 1.0\n"; // MIME-Version: default
1.1 paf 844: }
845:
1.45 paf 846: int textCount=info.parts[P_TEXT]->count();
1.1 paf 847: if(textCount>1)
1.136 moko 848: throw Exception(PARSER_RUNTIME, 0, "multiple text parts are not supported, use file part");
1.45 paf 849: int htmlCount=info.parts[P_HTML]->count();
1.1 paf 850: if(htmlCount>1)
1.136 moko 851: throw Exception(PARSER_RUNTIME, 0, "multiple html parts are not supported, use file part");
1.1 paf 852:
853: bool multipart=info.parts_count>1;
854: bool alternative=textCount && htmlCount;
855: // header
856: char *boundary=0;
857: if(multipart) {
1.118 moko 858: boundary=get_uuid_boundary();
1.76 misha 859:
860: bool is_inline = false;
861: {
1.143 moko 862: Array<Value*>& files=*info.parts[P_FILE];
1.76 misha 863: for(size_t i=0; i<files.count(); i++) {
1.82 misha 864: HashStringValue* file;
865: if((file=files.get(i)->get_hash()) && file->get(cid_name)){
1.76 misha 866: is_inline = true;
867: break;
1.77 misha 868: }
1.76 misha 869: }
870: }
1.133 moko 871:
1.91 misha 872: result << HTTP_CONTENT_TYPE_CAPITALIZED ": " << ( is_inline ? HTTP_CONTENT_TYPE_MULTIPART_RELATED : HTTP_CONTENT_TYPE_MULTIPART_MIXED ) << ";";
1.76 misha 873:
1.1 paf 874: // multi-part
1.133 moko 875: result << " boundary=\"" << boundary << "\"\n\nThis is a multi-part message in MIME format.";
1.1 paf 876: }
877:
878: // alternative or not
879: {
880: if(alternative) {
1.45 paf 881: result << "\n\n--" << boundary << "\n" // intermediate boundary
1.91 misha 882: HTTP_CONTENT_TYPE_CAPITALIZED ": multipart/alternative; boundary=\"ALT" << boundary << "\"\n";
1.1 paf 883: }
884: for(int i=0; i<2; i++) {
885: PartType pt=i==0?P_TEXT:P_HTML;
1.45 paf 886: if(info.parts[pt]->count()) {
1.1 paf 887: if(alternative)
888: result << "\n\n--ALT" << boundary << "\n"; // intermediate boundary
889: else if(boundary)
890: result << "\n\n--" << boundary << "\n"; // intermediate boundary
1.45 paf 891: result << text_value_to_string(r, pt, info.parts[pt]->get(0), info);
1.1 paf 892: }
893: }
894: if(alternative)
895: result << "\n\n--ALT" << boundary << "--\n";
896: }
897:
898: // messages
899: {
1.143 moko 900: Array<Value*>& messages=*info.parts[P_MESSAGE];
1.45 paf 901: for(size_t i=0; i<messages.count(); i++) {
1.1 paf 902: if(boundary)
903: result << "\n\n--" << boundary << "\n"; // intermediate boundary
904:
1.45 paf 905: const String* dummy_from;
906: String* dummy_to;
1.134 moko 907: result << message_hash_to_string(r, messages.get(i)->get_hash(), dummy_from, false, dummy_to);
1.1 paf 908: }
909: }
910:
1.132 moko 911: // files go last
912: {
1.143 moko 913: Array<Value*>& files=*info.parts[P_FILE];
1.132 moko 914: for(size_t i=0; i<files.count(); i++) {
915: if(boundary)
916: result << "\n\n--" << boundary << "\n"; // intermediate boundary
917: result << file_value_to_string(r, files.get(i));
918: }
919: }
920:
1.1 paf 921: // tailer
922: if(boundary)
923: result << "\n\n--" << boundary << "--\n"; // finish boundary
924:
925: // return
926: return result;
927: }
928:
929:
1.88 misha 930: Value* VMail::get_element(const String& aname) {
1.1 paf 931: // $fields
1.3 paf 932: #ifdef WITH_MAILRECEIVE
1.1 paf 933: if(aname==MAIL_RECEIVED_ELEMENT_NAME)
1.48 paf 934: return &vreceived;
1.1 paf 935: #endif
936:
1.110 misha 937: // $method
1.88 misha 938: if(Value* result=VStateless_class::get_element(aname))
1.1 paf 939: return result;
940:
1.109 moko 941: return bark("%s field not found", &aname);
1.1 paf 942: }
E-mail: