Add GNU LGPL headers to all .c .C and .h files
[oweals/cde.git] / cde / programs / dtmail / libDtMail / RFC / MIMEBodyPart.C
1 /*
2  * CDE - Common Desktop Environment
3  *
4  * Copyright (c) 1993-2012, The Open Group. All rights reserved.
5  *
6  * These libraries and programs are free software; you can
7  * redistribute them and/or modify them under the terms of the GNU
8  * Lesser General Public License as published by the Free Software
9  * Foundation; either version 2 of the License, or (at your option)
10  * any later version.
11  *
12  * These libraries and programs are distributed in the hope that
13  * they will be useful, but WITHOUT ANY WARRANTY; without even the
14  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15  * PURPOSE. See the GNU Lesser General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with these librararies and programs; if not, write
20  * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
21  * Floor, Boston, MA 02110-1301 USA
22  */
23 /*
24  *+SNOTICE
25  *
26  *
27  *      $TOG: MIMEBodyPart.C /main/11 1998/04/06 13:27:03 mgreess $
28  *
29  *      RESTRICTED CONFIDENTIAL INFORMATION:
30  *      
31  *      The information in this document is subject to special
32  *      restrictions in a confidential disclosure agreement bertween
33  *      HP, IBM, Sun, USL, SCO and Univel.  Do not distribute this
34  *      document outside HP, IBM, Sun, USL, SCO, or Univel wihtout
35  *      Sun's specific written approval.  This documment and all copies
36  *      and derivative works thereof must be returned or destroyed at
37  *      Sun's request.
38  *
39  *      Copyright 1993 Sun Microsystems, Inc.  All rights reserved.
40  *
41  *+ENOTICE
42  */
43
44 #include <EUSCompat.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <ctype.h>
49
50 #include <Dt/Dts.h>
51
52 #include <DtMail/DtMail.hh>
53 #include "RFCImpl.hh"
54 #include "RFCMIME.hh"
55 #include <DtMail/Threads.hh>
56 #include "md5.h"
57
58 // For CHARSET
59 #include <locale.h>
60 #include <DtHelp/LocaleXlate.h>
61 #include "str_utils.h"
62
63 MIMEBodyPart::MIMEBodyPart(DtMailEnv & error,
64                          DtMail::Message * parent,
65                          const char * start,
66                          const int len,
67                          RFCEnvelope * body_env)
68 : RFCBodyPart(error, parent, start, len, body_env)
69 {
70     // A single part message. We are done for now.
71     //
72     error.clear();
73     return;
74 }
75
76 MIMEBodyPart::MIMEBodyPart(DtMailEnv & error,
77                            DtMail::Message * parent,
78                            const char * start,
79                            const char ** end,
80                            const char * boundary)
81 : RFCBodyPart(error, parent, start, 0, NULL)
82 {
83     error.clear();
84
85     // We are sitting at the start of a boundary. We need to get
86     // past the boundary to do the real processing.
87     //
88     const char * body_end;
89     for (body_end = _body_text; body_end <= *end && *body_end != '\n'; body_end++) {
90         continue;
91     }
92     body_end += 1;
93
94     if (body_end > *end) {
95         // Don't know. Give up!
96         *end = body_end;
97         _body_len = *end - start + 1;
98
99         // Need a bogus envelope for other uses.
100         //
101         _body_env = new RFCEnvelope(error, parent, NULL, 0);
102         return;
103     }
104
105     const char * env_start = body_end;
106     _my_env = DTM_TRUE;
107     if (isTerm(env_start)) {
108         _body_env = new RFCEnvelope(error, parent, env_start, 0);
109     }
110     else {
111         // Find the blank line where the envelope ends.
112         //
113         for (; body_end <= *end; body_end++) {
114             if (*body_end == '\n') {
115                 int blank_only = 1;
116                 for (const char * blank = body_end + 1;
117                      blank <= *end && *blank != '\n'; blank++) {
118                     if (!isspace((unsigned char)*blank)) {
119                         blank_only = 0;
120                         break;
121                     }
122                 }
123                 if (blank_only) {
124                     break;
125                 }
126             }
127         }
128         _body_env = new RFCEnvelope(error,
129                                     parent,
130                                     env_start,
131                                     body_end - env_start + 1);
132         body_end += 1;
133     }
134
135     // Chew everything up to the next new line, which should be only
136     // a CRLF.
137     //
138     for (;body_end <= *end && *body_end != '\n'; body_end++) {
139         continue;
140     }
141     body_end += 1;
142
143     _body_text = body_end; // This is where the body really starts.
144
145     // Now we need to find the end of the body. MIME doesn't have
146     // any predefined length fields so we have to use the boundaries.
147     //
148     int bndry_len = strlen(boundary);
149     for (;body_end <= *end; body_end++) {
150         if (*body_end == '\n' &&
151             *(body_end + 1) == '-' &&
152             *(body_end + 2) == '-' &&
153             strncmp(body_end + 3, boundary, bndry_len) == 0) {
154             break;
155         }
156     }
157
158     if (*(body_end - 1) == '\r') {
159         body_end -= 1;
160     }
161     _body_len = body_end - _body_text + 1;
162
163     // MIME says the CRLF preceding a boundary belongs to the boundary.
164     // We will pull it off here rather than do it on entry to this
165     // method for the next message.
166     for (;body_end <= *end && *body_end != '\n'; body_end++) {
167         continue;
168     }
169     body_end += 1;
170
171     // Computing the end here is a little different. If the boundary
172     // ends with a "--" as well, then we are at the real end of
173     // the message.
174     //
175     const char * bndry_end = body_end + 2 + strlen(boundary);
176     if (*bndry_end == '-' && *(bndry_end + 1) == '-') {
177         *end = *end + 1;
178     }
179     else {
180         *end = body_end;
181     }
182
183     return;
184 }
185
186 MIMEBodyPart::~MIMEBodyPart(void)
187 {
188 }
189
190 #ifdef DEAD_WOOD
191 DtMailChecksumState
192 MIMEBodyPart::checksum(DtMailEnv & error)
193 {
194     error.clear();
195
196     // Look for the Content-MD5 header. If it is not present, then
197     // the state is unknown and we can punt.
198     //
199     DtMailEnv my_error;
200     DtMailValueSeq value;
201     _body_env->getHeader(my_error, "Content-MD5", DTM_FALSE, value);
202     if (my_error.isSet()) {
203         return(DtMailCheckUnknown);
204     }
205
206
207     if (_body_type == NULL) {
208         getDtType(error);
209         if (error.isSet()) {
210             return(DtMailCheckUnknown);
211         }
212     }
213
214     char stored_digest[32];
215     int stored_size = 0;
216     RFCMIME::readBase64(stored_digest, stored_size,
217                         *(value[0]), strlen(*(value[0])));
218     if (stored_size != 16) {
219         // The MD5 sum must be 16 bytes, or we have a bad checksum.
220         //
221         return(DtMailCheckBad);
222     }
223
224     // See if we call this text. We need to handle md5 checksums
225     // different for text. They must be computed with CRLF line
226     // termination.
227     //
228     char * text_type = DtDtsDataTypeToAttributeValue(_body_type,
229                                                      DtDTS_DA_IS_TEXT,
230                                                      NULL);
231
232     unsigned char digest[16];
233     if (text_type && strcasecmp(text_type, "true") == 0) {
234         RFCMIME::md5PlainText(_body, _body_decoded_len, digest);
235     }
236     else {
237         MD5_CTX context;
238         MD5Init(&context);
239         MD5Update(&context, (unsigned char *)_body, _body_decoded_len);
240         MD5Final(digest, &context);
241     }
242
243     free(text_type);
244
245     if (memcmp(digest, stored_digest, sizeof(digest)) == 0) {
246         return(DtMailCheckGood);
247     }
248     else {
249         return(DtMailCheckBad);
250     }
251 }
252 #endif /* DEAD_WOOD */
253
254 static int
255 countTypes(char ** types)
256 {
257     int count;
258     for (count = 0; *types; types++, count++) {
259         continue;
260     }
261
262     return(count);
263 }
264
265 void
266 MIMEBodyPart::getContentType(DtMailEnv &error, char **mime_type)
267 {
268     DtMailValueSeq value;
269
270     if (mime_type)
271       *mime_type = (char *)0;
272
273     if (_body_env)
274       _body_env->getHeader(error, "Content-Type", DTM_FALSE, value);
275
276     if (_body_env && !error.isSet())
277     {
278         // Handle "Content-Type: text" problem with /usr/lib/mail.local
279         if (strcasecmp(*(value[0]), "text")==0)
280           *mime_type = strdup("text/plain");
281         else
282           *mime_type = strdup(*(value[0]));
283     }
284     else
285     {
286         error.clear();
287         *mime_type = strdup("text/plain");
288     }
289 }
290
291 void
292 MIMEBodyPart::getDtType(DtMailEnv & error)
293 {
294     MutexLock lock_scope(_obj_mutex);
295     MutexLock dt_lib_lock(_DtMutex);
296
297 //    error.clear();
298
299     char * end;
300     char * mime_type;
301     DtMailValueSeq value;
302
303     if (_body_env) {
304         _body_env->getHeader(error, "Content-Type", DTM_FALSE, value);
305     }
306
307     if (_body_env && !error.isSet()) {
308         // Handle "Content-Type: text" problem with /usr/lib/mail.local
309         //
310         if (strcasecmp(*(value[0]), "text")==0)
311           mime_type = strdup("text/plain");
312         else
313           mime_type = strdup(*(value[0]));
314     }
315     else {
316         error.clear();
317         mime_type = strdup("text/plain");
318     }
319
320     for (end = mime_type; *end; end++) {
321         if (*end == ';' || isspace((unsigned char)*end)) {
322             break;
323         }
324         if (isupper(*end)) {
325             *end = tolower(*end);
326         }
327     }
328     *end = 0;
329
330     char ** types = DtDtsFindAttribute(DtDTS_DA_MIME_TYPE, mime_type);
331
332     // We must have an exact 1:1 mapping between the mime type and the
333     // CDE type to use this inverse mapping. If we have no hits then we
334     // dont have any thing to use. If we have several hits, then we have
335     // no idea which type is the correct type.
336     //
337     if (NULL != types) {
338         if (countTypes(types) == 1) {
339             // We will use the first name. It may be wrong, but
340             // it is the best we can do at this point.
341             //
342             _body_type = strdup(types[0]);
343             DtDtsFreeDataTypeNames(types);
344             free(mime_type);
345             return;
346         }
347         DtDtsFreeDataTypeNames(types);
348     }
349
350     // We need the bits so we can type the buffer and get
351     // a type for the object. This is where things can get
352     // very slow for the user.
353     //
354     loadBody(error);
355     if (error.isSet()) {
356         return;
357     }
358
359     int istext = (strcasecmp(mime_type, "text/plain") == 0);
360     char * name = getNameHeaderVal(error);
361     char * type = DtDtsBufferToDataType(_body, _body_decoded_len, name);
362
363     // We have written a name pattern for text parts that will match
364     // the name "text" as a TEXT part.  If the first attempt to get the
365     // data type fails and we have a MIMETYPE of text/plain, then we try
366     // again using the name "text".
367     //
368     if ( (0 == strcasecmp(mime_type, "text/plain")) &&
369          (NULL == type || 0 == strcasecmp(type, "DATA")) )
370     {
371         if (type)
372           DtDtsFreeDataType(type);
373         type = DtDtsBufferToDataType(_body, _body_decoded_len, "text");
374     }
375
376     if (NULL != type)
377       _body_type = strdup(type);
378     else
379       _body_type = strdup("UNKNOWN");
380
381     if (error.isSet())
382       error.clear();
383     if (type)
384       DtDtsFreeDataType(type);
385     if (mime_type)
386       free(mime_type);
387     if (name)
388       free(name);
389 }
390
391 void
392 MIMEBodyPart::loadBody(DtMailEnv & error)
393 {
394 // For CHARSET
395         char *cs = NULL, *to_cs = NULL, *from_cs = NULL;
396
397 // There is no reason to clear the error object because it is assumed 
398 // that whoever instantiated it, cleared it.
399 //  error.clear();
400   
401   if (_body) {
402     return;
403   }
404
405   // If there is any encoding done to the body, reverse it
406   //
407   DtMailValueSeq value;
408   if (_body_env) {
409     _body_env->getHeader(error, "Content-Transfer-Encoding",
410                          DTM_FALSE, value);
411   }
412   
413   if (_body_env && !error.isSet()) {
414     const char * enc = *(value[0]);
415     if (strcasecmp(enc, "base64") == 0) {
416       // Decoded bodies will always be smaller than
417       // encoded bodies.
418       //_body = (char *)malloc(_body_len); 
419
420       _body = (char *)malloc(_body_len+1);
421       int size = _body_decoded_len = 0;
422       _must_free_body = DTM_TRUE;
423       RFCMIME::readBase64(_body, size, _body_text, _body_len);
424       _body_decoded_len = size;
425
426       // Changed this temporarily until after release. We really should not
427       // be null terminating these buffers.
428       (_body)[_body_decoded_len] = 0;
429     }
430     else if (strcasecmp(enc, "quoted-printable") == 0) {
431       _body = (char *)malloc(_body_len + 20);
432       _must_free_body = DTM_TRUE;
433       int size = _body_decoded_len = 0;
434       RFCMIME::readQPrint(_body, size, _body_text, _body_len);
435       _body_decoded_len = size;
436
437       // Changed this temporarily until after release. We really should not
438       // be null terminating these buffers.
439       (_body)[_body_decoded_len] = 0;
440     }
441     else {
442     // Default case is no transfer encoding applies (7bit==8bit==binary)
443     _body = (char *)_body_text;
444     _must_free_body = DTM_FALSE;
445     _body_decoded_len = _body_len;
446     }
447   }
448   else {
449     // Default case is no transfer encoding applies.
450     error.clear(); 
451     _body = (char *)_body_text;
452     _must_free_body = DTM_FALSE;
453     _body_decoded_len = _body_len;
454    }
455
456 // For CHARSET
457         // Get charset from content-type field
458         char *ret = NULL;
459         value.clear();
460         _body_env->getHeader(error, "Content-Type", DTM_FALSE, value);
461         if (error.isNotSet()) {
462        cs = csFromContentType(value);
463        if ( cs == NULL ) {
464               // Random allocation for cs
465                   cs = (char *)calloc(128, sizeof(char));
466                   DtXlateOpToStdLocale(DtLCX_OPER_SETLOCALE,
467                          setlocale(LC_CTYPE, NULL),
468                          NULL,
469                          NULL,
470                          &ret);
471                   strcpy(cs, "DEFAULT");
472                   strcat(cs, ".");
473                   strcat(cs, ret);
474            }
475         } else {    // No Content-Type
476            // We'll be flexible here.  If Content-Type header is missing, we'll
477            // still try to convert from the locale specific default codeset.
478            error.clear();
479            // Random allocation for cs
480            cs = (char *)calloc(128, sizeof(char));
481            DtXlateOpToStdLocale(DtLCX_OPER_SETLOCALE,
482                  setlocale(LC_CTYPE, NULL),
483                  NULL,
484                  NULL,
485                  &ret);
486            strcpy(cs, "DEFAULT");
487            strcat(cs, ".");
488            strcat(cs, ret);
489         }
490
491         // Handle ISO-2022-INT, RFC approved, or private encoding names
492         if ( strcasecmp(cs, "ISO-2022-INT-1") == 0 ) {
493            // Need to obtain charset from encoding
494         }  // RFC approved and private names are not treated differently.
495
496         // Get iconv name from charset - this is the "from" name.
497     from_cs = NULL;
498     from_cs = csToConvName(cs);
499
500         // Get current locale's iconv name - this is the "to" name.
501         to_cs = NULL;
502         to_cs = locToConvName();
503
504     if ( from_cs && to_cs ) {
505           if ( strcasecmp(from_cs, to_cs) != 0 ) {
506           unsigned long tmp_len = (unsigned long) _body_decoded_len;
507           if (csConvert(&_body, tmp_len, (int)_must_free_body, from_cs, to_cs)) {
508                 _must_free_body = DTM_TRUE;
509                 _body_decoded_len = (int) tmp_len;
510           }
511           }
512         }
513         if ( cs )
514         free ( cs );
515         if ( from_cs )
516             free( from_cs );
517         if ( to_cs )
518             free ( to_cs );
519         if ( ret )
520             free( ret );
521         
522 // End of For CHARSET
523
524     // Clear the error condition before proceeding.  This is done
525     // because functions that take a DtMailEnv object as a parameter
526     // expect it to be cleared.  (Already cleared above)
527     // error.clear();  
528
529   // If the body is text/enriched, convert it to text/plain
530   // At some point the front end should be able to handle this via
531   // data typing and do an 'intelligent' conversion, in which
532   // case this code can be removed
533   //
534
535   value.clear();
536   if (_body_env) {
537     _body_env->getHeader(error, "Content-Type", DTM_FALSE, value);
538   }
539
540   if (_body_env && !error.isSet() &&
541       ((strncasecmp(*(value[0]), "text/enriched", 13) == 0)
542        || (strncasecmp(*(value[0]), "text/richtext", 13) == 0))) {
543     char *new_body = (char *)malloc((unsigned)(_body_len*2));
544     int size = 0;
545     RFCMIME::readTextEnriched(new_body, size, _body, _body_decoded_len);
546     new_body = (char *)realloc(new_body, size+2);
547     if (_must_free_body == DTM_TRUE)
548       free(_body);
549     _must_free_body = DTM_TRUE;
550     _body_decoded_len = size;
551     _body = new_body;
552     // Changed this temporarily until after release. We really should not
553     // be null terminating these buffers.
554     (_body)[_body_decoded_len] = 0;
555   }
556   error.clear();
557   return;
558 }
559
560 // NOTES ON HANDLING OF "FILE NAMES" FOR BODY PARTS IN MIME COMPLIANT ENTITIES:
561 // (see full description in evaluation for bug 1189035)
562 // 
563 // The ability to provide a "file name" for a body part in a MIME compliant
564 // entity is partially addressed in RFC 1341 [MIME: Multipurpose Internet Mail
565 // Extentions] and RFC 1521 [which obsoleted RFC 1341].
566 // 
567 // RFC 1341 proposed a solution to the file name problem (Content-Type:
568 // type; name=name); RFC 1521 subsequently depreciated this solution in
569 // favor of a to-be-defined future specification of "Content-Disposition".
570 // 
571 // In essence there is an anticipation that "Content-Disposition" will
572 // be defined in a future RFC such that the notion of a "file name" may
573 // be given to a body part of a MIME compliant entity.
574 // 
575 // OpenWindows mailtool currently recognizes "Content-Description" on MIME
576 // compliant entities and uses that information as the "file name" for
577 // an attachment (as per a loose interpretation of RFC 1521).
578 // 
579 // CDE DtMail currently sends out and recognizes "X-Content-Name" on MIME
580 // compliant entities and uses that information as the "file name" for an
581 // attachment. This is essentially a non-standard header field as per RFC
582 // 1521:
583 // 
584 //     "X-" fields may be created for experimental or private purposes, 
585 //     with the recognition that the information they contain may be 
586 //     lost at some gateways.
587 // 
588 // Since OpenWindows mailtool does not understand "X-Content-Name", any
589 // body part in e-mail originating from CDE DtMail does not appear to 
590 // have a file name when read by mailtool.
591 // 
592 // Given these facts:
593 // 
594 //     . OpenWindows mailtool cannot be changed until at least the Solaris
595 //       2.5 release (if at all).
596 // 
597 //     . OpenWindows mailtool is recognizing a valid MIME header field 
598 //       which is essentially "free form" in nature.
599 // 
600 //     . CDE DtMail is currently using an experimental or private field 
601 //       which is not part of the standard and is not guaranteed to survive
602 //       transport across gateways.
603 // 
604 //     . There is no officially proscribed method for providing the "file
605 //       name" of a body part in a MIME compliant entity in RFC 1521.
606 // 
607 // The reasonable approach to take to solve this problem is:
608 // 
609 // 1. Have DtMail use "Content-Description" to transmit the "file name"
610 //    for a body part - this achieves compatibility with mailtool.
611 // 
612 // 2. Have DtMail also continue to use "X-Content-Name" to transmit the
613 //    "file name" - this maintains compatibility with previous versions
614 //    of DtMail which only recognize this header.
615 // 
616 // 3. Have Dtmail recognize both "Content-Description" and "X-Content-Name"
617 //    as specifying the "file name" for a body part. In the case that both
618 //    fields are present, "Content-Description" takes precedence over
619 //    "X-Content-Name".
620 // 
621 // 4. When "Content-Disposition" is properly defined and included as part
622 //    of an updated MIME specification, revisit this issue.
623 //
624 // 
625 // So, since dtmail currently *ignores* the "Content-Description" field,
626 // we overload the "getNameHeaderVal" function to use "Content-Description"
627 // first, then the older unofficial experimental "X-Content-Name". If
628 // and when Content-Disposition takes hold, it will have to override
629 // Content-Description when both are present.
630 //
631
632 //
633 // March 25, 1997
634 // The Content-Disposition field has been designated as the primary 
635 // header field for transmitting file names.  See RFC 1806.  Therefore
636 // the algorithm has bee updated as follows.
637 //
638 // 1. DtMail checks the following headers for the "filename" for a body part:
639 //      o The "filename" parameter of the "Content-Disposition" header field.
640 //      o The contents of the "Content-Description" header field.
641 //      o The "name" parameter of the "Content-Type" header field.
642 //      o The contents of the "Content-Name" header field.
643 //      o The contents of the "X-Content-Name" header field.
644 //
645 // 2. DtMail uses the following fields to specify the "filename" for a body
646 //    part in outgoing mail:
647 //      o The "filename" parameter of the "Content-Disposition" header field.
648 //      o The contents of the "Content-Description" header field.
649 //
650
651 char *
652 MIMEBodyPart::getDescription(DtMailEnv &)
653 {
654   // Dont have this return anything without checking
655   // ramifications with getNameHeaderValue
656
657 // No need to clear error object here because we assume it has already
658 // been cleared by the caller and nothing has touched it in this method.
659 //    error.clear();
660
661     return(NULL);
662 }
663
664 char *
665 MIMEBodyPart::getNameHeaderVal(DtMailEnv & error)
666 {
667     DtMailValueSeq value;
668
669     if (_body_env == NULL) {
670         // No need to clear the error object...it is unchanged from the 
671         // state we received it in.
672         //error.clear();
673         return(NULL);
674     }
675
676     // The current standard seems to be to use the "Content-Disposition"
677     // header as the primary mechanism for transmitting file names.
678     //
679     _body_env->getHeader(error, "Content-Disposition", DTM_FALSE, value);
680     if (error.isNotSet()) {
681         char *param = parameterValue(value, "filename", DTM_FALSE);
682         if (NULL != param)
683             return strdup(param);
684     }
685     error.clear();
686
687     // In keeping with the current undefined nature of
688     // file names for body parts in RFC 1521, and to be
689     // compatible with OpenWindows mailtool, the first
690     // overriding "name" comes from "Content-Description"
691     //
692     _body_env->getHeader(error, "Content-Description", DTM_FALSE, value);
693     if (error.isNotSet()) {
694         return(strdup(*(value[0])));
695     }
696     error.clear();
697
698     // For backward compatibility with older mail agents, check the "Name"
699     // parameter in the "Content-Type" header.
700     //
701     _body_env->getHeader(error, "Content-Type", DTM_FALSE, value);
702     if (error.isNotSet()) {
703         char *param = parameterValue(value, "name", DTM_FALSE);
704         if (NULL != param)
705             return strdup(param);
706     }
707     error.clear();
708
709     // Next we remain compatible with previous versions
710     // of DtMail that used "X-Content-Name" instead of
711     // "Content-Description" for the file name of a
712     // body part (1-27-95)
713     //
714     _body_env->getHeader(error, "X-Content-Name",
715                          DTM_FALSE, value);
716     if (error.isNotSet()) {
717         return(strdup(*(value[0])));
718     }
719     error.clear();
720
721     // This code was in dtmail on 1-27-95 and even though
722     // that version of dtmail did not send out "Content-Name"
723     // (which is not part of RFC 1341 or 1521) it doesnt
724     // hurt to recognize it if its the only header there.
725     //
726     _body_env->getHeader(error, "Content-Name",
727                          DTM_FALSE, value);
728     if (error.isNotSet()) {
729         return(strdup(*(value[0])));
730     }
731     error.clear(); // NULL is the real error here.
732
733     // No name for this body part
734     //
735     return(NULL);
736 }
737
738 char *
739 MIMEBodyPart::getName(DtMailEnv & error)
740 {
741     char * h_name = getNameHeaderVal(error);
742     // don't care about the error returned by getNameHeaderVal()
743     error.clear();
744     if (h_name) {
745         return(h_name);
746     }
747
748     if (!_body_type) {
749         getDtType(error);
750         if (error.isSet()) {
751             error.clear();
752             return(strdup("Attachment"));
753         }
754     }
755
756     char * pat = DtDtsDataTypeToAttributeValue(_body_type,
757                                                "NAME_TEMPLATE",
758                                                NULL);
759
760     if (pat) {
761         int max_len = strlen(pat) + 20;
762         char * name = (char*) malloc((size_t) max_len);
763         sprintf(name, pat, "Attachment");
764         DtDtsFreeAttributeValue(pat);
765         return(name);
766     }
767
768     return(strdup("Attachment"));
769 }
770
771 void
772 MIMEBodyPart::setName(DtMailEnv & error, const char * name)
773 {
774     if (_body_env) {
775         _body_env->setHeader(error, "X-Content-Name", DTM_TRUE, name);
776     }
777 }
778
779 unsigned long
780 MIMEBodyPart::getLength(DtMailEnv & error)
781 {
782     MutexLock lock_scope(_obj_mutex);
783
784     loadBody(error);
785     if (error.isSet()) {
786         // propogate the error back to the caller.
787         return (0);
788     }
789
790     // We have to treat external bodies differently. The headers on these
791     // parts contain useful information to the client.
792     //
793     const char * mime_type;
794     DtMailValueSeq value;
795
796     if (_body_env) {
797         _body_env->getHeader(error, "Content-Type", DTM_FALSE, value);
798     }
799
800     if (_body_env && !error.isSet()) {
801         mime_type = *(value[0]);
802     }
803     else {
804         // only need to clear the error object if getHeader returned 
805         // an error condition.  We don't want to propogate the error
806         // back up the calling sequence.
807         error.clear();
808         mime_type = "text/plain";
809     }
810
811     unsigned long len;
812
813     if (strncasecmp(mime_type, "message/external-body", 21) == 0) {
814         const char * contents = _body_start;
815         for (;contents < (_body_text + _body_len); contents++) {
816             if (*contents == '\n') {
817                 break;
818             }
819         }
820         contents += 1;
821
822         len = _body_len + (_body_text - contents);
823     }
824     else {
825         len = _body_decoded_len;
826     }
827
828     return(len);
829 }
830
831 int
832 MIMEBodyPart::rfcSize(const char *, DtMailBoolean &)
833 {
834     return(0);
835 }
836
837 char *
838 MIMEBodyPart::writeBodyParts(char * buf)
839 {
840   return(buf);
841 }
842
843 const void *
844 MIMEBodyPart::getBody(DtMailEnv & error)
845 {
846 // No need to clear the error here, should be cleared by the object
847 // that instantiated it.
848 //    error.clear();
849
850     if (!_body) {
851         loadBody(error);
852         // loadBody currently (version 1.31) clears the error before
853         // returning, so the following check is not needed.  We'll
854         // leave it alone on the chance that loadBody() will someday
855         // return an error condition.
856         if (error.isSet()) {
857             return(NULL);
858         }
859     }
860
861     // We have to treat external bodies differently. The headers on these
862     // parts contain useful information to the client.
863     //
864     const char * mime_type;
865     DtMailValueSeq value;
866
867     if (_body_env) {
868         _body_env->getHeader(error, "Content-Type", DTM_FALSE, value);
869     }
870
871     if (_body_env && !error.isSet()) {
872       // Handle "Content-Type: text" problem with /usr/lib/mail.local
873       //
874       if (strcasecmp(*(value[0]), "text")==0)
875         mime_type = "text/plain";
876       else
877         mime_type = *(value[0]);
878     }
879     else {
880         error.clear();
881         mime_type = "text/plain";
882     }
883
884     const char * contents;
885
886     if (strncasecmp(mime_type, "message/external-body", 21) == 0) {
887         contents = _body_start;
888         for (;contents < (_body_text + _body_len); contents++) {
889             if (*contents == '\n') {
890                 break;
891             }
892         }
893         contents += 1;
894     }
895     else {
896         contents = _body;
897     }
898
899     return(contents);
900 }
901
902 // For CHARSET
903
904 // Given the Content-Type field, extract the charset value.
905 // Returns one of the following:
906 // 1) charset value,
907 //    Caller MUST FREE this return value.
908 // 2) NULL if charset is not specified but Content-Type specifies
909 //    text/plain data.  If this routine returns NULL, that means
910 //    charset is not specified but the data is text/plain.  Therefore,
911 //    (as in the case of MIMEBodyPart::loadBody) caller
912 //    will call csToConvName("DEFAULT.<locale>") and csToConvName will return
913 //    a default iconv conversion name for the current locale.
914 //    This is the case because some (old) mailers do not set the charset value
915 //    but encodes the message in a "popular" codeset.  The default conversion
916 //    name for a particular locale assumes the "popular" codeset used.
917 // 3) non NULL but invalid charset value if Content-Type does not specify
918 //    text/plain data.  Caller MUST FREE this return value.
919 char *
920 MIMEBodyPart::csFromContentType(DtMailValueSeq &value)
921 {
922    char *cs_str = NULL;
923    char *val_ptr = NULL;
924    int quoted = 0;
925
926    // value[0] should be valid else error would have occurred before
927    // this routine ever gets called.  And value index is 0 because
928    // previous value stored should have been removed.
929    const char *val = *(value[0]);
930
931    // Check to see if Content-Type field specifies text/plain data.
932    // If so, look for charset value
933    // else, returns value in Content-Type field
934    if ( strstr(val, "text") == NULL ) {
935       if ( strstr(val, "TEXT") == NULL ) {
936                 cs_str = strdup(val);
937                 return cs_str;
938       }
939    } 
940    // Get charset value
941    val_ptr = strstr(val, "charset=");
942    if ( val_ptr == NULL ) {
943           val_ptr = strstr(val, "CHARSET=");
944    }
945    if ( val_ptr == NULL ) {
946           return NULL;
947    }
948    val_ptr = val_ptr+8;
949
950    // Check if charset value is quoted
951    if ( val_ptr[0] == '"' ) {
952           val_ptr++;
953           quoted = 1;
954    }
955    if ( quoted ) {
956           cs_str = strdup(strtok(val_ptr, "\""));
957    } else {
958           cs_str = (char *)calloc(strlen(val_ptr)+1, sizeof(char));
959       sscanf(val_ptr, "%s", cs_str);
960    }
961
962    return cs_str;
963 }
964 // End of For CHARSET
965
966
967 char *
968 MIMEBodyPart::parameterValue(
969                         DtMailValueSeq &value,
970                         const char * parameter,
971                         DtMailBoolean isCaseSensitive)
972 {
973     char *lasts=NULL;
974     char *ptok, *vtok;
975     char *parm, *val;
976     int rtn = 0;
977
978     val = strdup(*(value[0]));
979     vtok = strrchr(val, ';');
980     while (NULL != vtok)
981     {
982         *vtok = '\0';
983         vtok++;
984
985         while(isspace(*vtok))
986           vtok++;
987
988         if (isCaseSensitive)
989           rtn = strncmp(vtok, parameter, sizeof(parameter));
990         else
991           rtn = strncasecmp(vtok, parameter, sizeof(parameter));
992
993         if (0 == rtn)
994         {
995             ptok = strrchr(vtok, '=');
996             if (NULL == ptok)
997             {
998                 free(val);
999                 return NULL;
1000             }
1001
1002             ptok++;
1003             if (*ptok == '"' )
1004             {
1005                 ptok++;
1006                 parm = strdup(strtok(ptok, (const char *) "\""));
1007             }
1008             else
1009               parm = strdup(ptok);
1010             
1011             free(val);
1012             return parm;
1013         }
1014
1015         vtok = strrchr(val, ';');
1016     }
1017
1018     free(val);
1019     return NULL;
1020 }