Annotation of parser3/src/types/pa_vmail.C, revision 1.107

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

E-mail: