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

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

E-mail: