]> diplodocus.org Git - nmh/blob - uip/mhbuildsbr.c
Add -D_FORTIFY_SOURCE=2 to CPPFLAGS instead of AM_CPPFLAGS.
[nmh] / uip / mhbuildsbr.c
1 /* mhbuildsbr.c -- routines to expand/translate MIME composition files
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 /*
9 * This code was originally part of mhn.c. I split it into
10 * a separate program (mhbuild.c) and then later split it
11 * again (mhbuildsbr.c). But the code still has some of
12 * the mhn.c code in it. This program needs additional
13 * streamlining and removal of unneeded code.
14 */
15
16 #include <h/mh.h>
17 #include <fcntl.h>
18 #include <h/md5.h>
19 #include <h/mts.h>
20 #include <h/tws.h>
21 #include <h/fmt_scan.h>
22 #include <h/mime.h>
23 #include <h/mhparse.h>
24 #include <h/utils.h>
25 #include "../sbr/m_mktemp.h"
26 #include "../sbr/message_id.h"
27 #include "../sbr/mime_type.h"
28 #include "mhfree.h"
29 #include "mhshowsbr.h"
30
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #include <time.h>
35
36
37 extern int debugsw;
38
39 extern int listsw;
40 extern int rfc934sw;
41 extern int contentidsw;
42
43 static char prefix[] = "----- =_aaaaaaaaaa";
44
45 struct attach_list {
46 char *filename;
47 struct attach_list *next;
48 };
49
50 typedef struct convert_list {
51 char *type;
52 char *filename;
53 char *argstring;
54 struct convert_list *next;
55 } convert_list;
56
57
58 /* mhmisc.c */
59 void content_error (char *, CT, char *, ...);
60
61 /* mhcachesbr.c */
62 int find_cache (CT, int, int *, char *, char *, int);
63
64 /*
65 * static prototypes
66 */
67 static int init_decoded_content (CT, const char *);
68 static void setup_attach_content(CT, char *);
69 static void set_disposition (CT);
70 static void set_charset (CT, int);
71 static void expand_pseudoheaders (CT, struct multipart *, const char *,
72 const convert_list *);
73 static void expand_pseudoheader (CT, CT *, struct multipart *, const char *,
74 const char *, const char *);
75 static char *fgetstr (char *, int, FILE *);
76 static int user_content (FILE *, char *, CT *, const char *infilename);
77 static void set_id (CT, int);
78 static int compose_content (CT, int);
79 static int scan_content (CT, size_t);
80 static int build_headers (CT, int);
81 static char *calculate_digest (CT, int);
82 static int extract_headers (CT, char *, FILE **);
83
84
85 static unsigned char directives_stack[32];
86 static unsigned int directives_index;
87
88 static int do_direct(void)
89 {
90 return directives_stack[directives_index];
91 }
92
93 static void directive_onoff(int onoff)
94 {
95 if (directives_index >= sizeof(directives_stack) - 1) {
96 fprintf(stderr, "mhbuild: #on/off overflow, continuing\n");
97 return;
98 }
99 directives_stack[++directives_index] = onoff;
100 }
101
102 static void directive_init(int onoff)
103 {
104 directives_index = 0;
105 directives_stack[0] = onoff;
106 }
107
108 static void directive_pop(void)
109 {
110 if (directives_index > 0)
111 directives_index--;
112 else
113 fprintf(stderr, "mhbuild: #pop underflow, continuing\n");
114 }
115
116 /*
117 * Main routine for translating composition file
118 * into valid MIME message. It translates the draft
119 * into a content structure (actually a tree of content
120 * structures). This message then can be manipulated
121 * in various ways, including being output via
122 * output_message().
123 */
124
125 CT
126 build_mime (char *infile, int autobuild, int dist, int directives,
127 int header_encoding, size_t maxunencoded, int verbose)
128 {
129 int compnum, state;
130 char buf[NMH_BUFSIZ], name[NAMESZ];
131 char *cp, *np, *vp;
132 struct multipart *m;
133 struct part **pp;
134 CT ct;
135 FILE *in;
136 HF hp;
137 m_getfld_state_t gstate;
138 struct attach_list *attach_head = NULL, *attach_tail = NULL, *at_entry;
139 convert_list *convert_head = NULL, *convert_tail = NULL, *convert;
140
141 directive_init(directives);
142
143 umask (~m_gmprot ());
144
145 /* open the composition draft */
146 if ((in = fopen (infile, "r")) == NULL)
147 adios (infile, "unable to open for reading");
148
149 /*
150 * Allocate space for primary (outside) content
151 */
152 NEW0(ct);
153
154 /*
155 * Allocate structure for handling decoded content
156 * for this part. We don't really need this, but
157 * allocate it to remain consistent.
158 */
159 init_decoded_content (ct, infile);
160
161 /*
162 * Parse some of the header fields in the composition
163 * draft into the linked list of header fields for
164 * the new MIME message.
165 */
166 gstate = m_getfld_state_init(in);
167 m_getfld_track_filepos2(&gstate);
168 for (compnum = 1;;) {
169 int bufsz = sizeof buf;
170 switch (state = m_getfld2(&gstate, name, buf, &bufsz)) {
171 case FLD:
172 case FLDPLUS:
173 compnum++;
174
175 /* abort if draft has Mime-Version or C-T-E header field */
176 if (strcasecmp (name, VRSN_FIELD) == 0 ||
177 strcasecmp (name, ENCODING_FIELD) == 0) {
178 if (autobuild) {
179 fclose(in);
180 free (ct);
181 return NULL;
182 }
183 adios (NULL, "draft shouldn't contain %s: field", name);
184 }
185
186 /* ignore any Content-Type fields in the header */
187 if (!strcasecmp (name, TYPE_FIELD)) {
188 while (state == FLDPLUS) {
189 bufsz = sizeof buf;
190 state = m_getfld2(&gstate, name, buf, &bufsz);
191 }
192 goto finish_field;
193 }
194
195 /* get copies of the buffers */
196 np = mh_xstrdup(name);
197 vp = mh_xstrdup(buf);
198
199 /* if necessary, get rest of field */
200 while (state == FLDPLUS) {
201 bufsz = sizeof buf;
202 state = m_getfld2(&gstate, name, buf, &bufsz);
203 vp = add (buf, vp); /* add to previous value */
204 }
205
206 /*
207 * Now add the header data to the list, unless it's an attach
208 * header; in that case, add it to our attach list
209 */
210
211 if (strcasecmp(ATTACH_FIELD, np) == 0 ||
212 strcasecmp(ATTACH_FIELD_ALT, np) == 0) {
213 struct attach_list *entry;
214 char *s = vp, *e = vp + strlen(vp) - 1;
215 free(np);
216
217 /*
218 * Make sure we can find the start of this filename.
219 * If it's blank, we skip completely. Otherwise, strip
220 * off any leading spaces and trailing newlines.
221 */
222
223 while (isspace((unsigned char) *s))
224 s++;
225
226 while (e > s && *e == '\n')
227 *e-- = '\0';
228
229 if (*s == '\0') {
230 free(vp);
231 goto finish_field;
232 }
233
234 NEW(entry);
235 entry->filename = mh_xstrdup(s);
236 entry->next = NULL;
237 free(vp);
238
239 if (attach_tail) {
240 attach_tail->next = entry;
241 attach_tail = entry;
242 } else {
243 attach_head = attach_tail = entry;
244 }
245 } else if (strncasecmp(MHBUILD_FILE_PSEUDOHEADER, np,
246 strlen (MHBUILD_FILE_PSEUDOHEADER)) == 0) {
247 /* E.g.,
248 * Nmh-mhbuild-file-text/calendar: /home/user/Mail/inbox/9
249 */
250 char *type = np + strlen (MHBUILD_FILE_PSEUDOHEADER);
251 char *filename = vp;
252
253 /* vp should begin with a space because m_getfld2()
254 includes the space after the colon in buf. */
255 while (isspace((unsigned char) *filename)) { ++filename; }
256 /* Trim trailing newline and any other whitespace. */
257 rtrim (filename);
258
259 for (convert = convert_head; convert; convert = convert->next) {
260 if (strcasecmp (convert->type, type) == 0) { break; }
261 }
262 if (convert) {
263 if (convert->filename &&
264 strcasecmp (convert->filename, filename)) {
265 adios (NULL, "Multiple %s headers with different files"
266 " not allowed", type);
267 } else {
268 convert->filename = mh_xstrdup(filename);
269 }
270 } else {
271 NEW0(convert);
272 convert->filename = mh_xstrdup(filename);
273 convert->type = mh_xstrdup(type);
274
275 if (convert_tail) {
276 convert_tail->next = convert;
277 } else {
278 convert_head = convert;
279 }
280 convert_tail = convert;
281 }
282
283 free (vp);
284 free (np);
285 } else if (strncasecmp(MHBUILD_ARGS_PSEUDOHEADER, np,
286 strlen (MHBUILD_ARGS_PSEUDOHEADER)) == 0) {
287 /* E.g.,
288 * Nmh-mhbuild-args-text/calendar: -reply accept
289 */
290 char *type = np + strlen (MHBUILD_ARGS_PSEUDOHEADER);
291 char *argstring = vp;
292
293 /* vp should begin with a space because m_getfld2()
294 includes the space after the colon in buf. */
295 while (isspace((unsigned char) *argstring)) { ++argstring; }
296 /* Trim trailing newline and any other whitespace. */
297 rtrim (argstring);
298
299 for (convert = convert_head; convert; convert = convert->next) {
300 if (strcasecmp (convert->type, type) == 0) { break; }
301 }
302 if (convert) {
303 if (convert->argstring &&
304 strcasecmp (convert->argstring, argstring)) {
305 adios (NULL, "Multiple %s headers with different "
306 "argstrings not allowed", type);
307 } else {
308 convert->argstring = mh_xstrdup(argstring);
309 }
310 } else {
311 NEW0(convert);
312 convert->type = mh_xstrdup(type);
313 convert->argstring = mh_xstrdup(argstring);
314
315 if (convert_tail) {
316 convert_tail->next = convert;
317 } else {
318 convert_head = convert;
319 }
320 convert_tail = convert;
321 }
322
323 free (vp);
324 free (np);
325 } else {
326 add_header (ct, np, vp);
327 }
328
329 finish_field:
330 /* if this wasn't the last header field, then continue */
331 continue;
332
333 case BODY:
334 fseek (in, (long) (-strlen (buf)), SEEK_CUR);
335 break;
336 case FILEEOF:
337 break;
338
339 case LENERR:
340 case FMTERR:
341 adios (NULL, "message format error in component #%d", compnum);
342
343 default:
344 adios (NULL, "getfld() returned %d", state);
345 }
346 break;
347 }
348 m_getfld_state_destroy (&gstate);
349
350 if (header_encoding != CE_8BIT) {
351 /*
352 * Iterate through the list of headers and call the function to MIME-ify
353 * them if required.
354 */
355
356 for (hp = ct->c_first_hf; hp != NULL; hp = hp->next) {
357 if (encode_rfc2047(hp->name, &hp->value, header_encoding, NULL)) {
358 adios(NULL, "Unable to encode header \"%s\"", hp->name);
359 }
360 }
361 }
362
363 /*
364 * Now add the MIME-Version header field
365 * to the list of header fields.
366 */
367
368 if (! dist) {
369 np = mh_xstrdup(VRSN_FIELD);
370 vp = concat (" ", VRSN_VALUE, "\n", NULL);
371 add_header (ct, np, vp);
372 }
373
374 /*
375 * We initially assume we will find multiple contents in the
376 * draft. So create a multipart/mixed content to hold everything.
377 * We can remove this later, if it is not needed.
378 */
379 if (get_ctinfo ("multipart/mixed", ct, 0) == NOTOK)
380 done (1);
381 ct->c_type = CT_MULTIPART;
382 ct->c_subtype = MULTI_MIXED;
383
384 NEW0(m);
385 ct->c_ctparams = (void *) m;
386 pp = &m->mp_parts;
387
388 /*
389 * read and parse the composition file
390 * and the directives it contains.
391 */
392 while (fgetstr (buf, sizeof(buf) - 1, in)) {
393 struct part *part;
394 CT p;
395
396 if (user_content (in, buf, &p, infile) == DONE) {
397 inform("ignoring spurious #end, continuing...");
398 continue;
399 }
400 if (!p)
401 continue;
402
403 NEW0(part);
404 *pp = part;
405 pp = &part->mp_next;
406 part->mp_part = p;
407 }
408
409 /*
410 * Add any Attach headers to the list of MIME parts at the end of the
411 * message.
412 */
413
414 for (at_entry = attach_head; at_entry; ) {
415 struct attach_list *at_prev = at_entry;
416 struct part *part;
417 CT p;
418
419 if (access(at_entry->filename, R_OK) != 0) {
420 adios("reading", "Unable to open %s for", at_entry->filename);
421 }
422
423 NEW0(p);
424 init_decoded_content(p, infile);
425
426 /*
427 * Initialize our content structure based on the filename,
428 * and fill in all of the relevant fields. Also place MIME
429 * parameters in the attributes array.
430 */
431
432 setup_attach_content(p, at_entry->filename);
433
434 NEW0(part);
435 *pp = part;
436 pp = &part->mp_next;
437 part->mp_part = p;
438
439 at_entry = at_entry->next;
440 free(at_prev->filename);
441 free(at_prev);
442 }
443
444 /*
445 * Handle the mhbuild pseudoheaders, which deal with specific
446 * content types.
447 */
448 if (convert_head) {
449 CT *ctp;
450 convert_list *next;
451
452 done = freects_done;
453
454 /* In case there are multiple calls that land here, prevent leak. */
455 for (ctp = cts; ctp && *ctp; ++ctp) { free_content (*ctp); }
456 free (cts);
457
458 /* Extract the type part (as a CT) from filename. */
459 cts = mh_xcalloc(2, sizeof *cts);
460 if (! (cts[0] = parse_mime (convert_head->filename))) {
461 adios (NULL, "failed to parse %s", convert_head->filename);
462 }
463
464 expand_pseudoheaders (cts[0], m, infile, convert_head);
465
466 /* Free the convert list. */
467 for (convert = convert_head; convert; convert = next) {
468 next = convert->next;
469 free (convert->type);
470 free (convert->filename);
471 free (convert->argstring);
472 free (convert);
473 }
474 convert_head = NULL;
475 }
476
477 /*
478 * To allow for empty message bodies, if we've found NO content at all
479 * yet cook up an empty text/plain part.
480 */
481
482 if (!m->mp_parts) {
483 CT p;
484 struct part *part;
485 struct text *t;
486
487 NEW0(p);
488 init_decoded_content(p, infile);
489
490 if (get_ctinfo ("text/plain", p, 0) == NOTOK)
491 done (1);
492
493 p->c_type = CT_TEXT;
494 p->c_subtype = TEXT_PLAIN;
495 p->c_encoding = CE_7BIT;
496 /*
497 * Sigh. ce_file contains the "decoded" contents of this part.
498 * So this seems like the best option available since we're going
499 * to call scan_content() on this.
500 */
501 p->c_cefile.ce_file = mh_xstrdup("/dev/null");
502 p->c_begin = ftell(in);
503 p->c_end = ftell(in);
504
505 NEW0(t);
506 t->tx_charset = CHARSET_SPECIFIED;
507 p->c_ctparams = t;
508
509 NEW0(part);
510 *pp = part;
511 part->mp_part = p;
512 }
513
514 /*
515 * close the composition draft since
516 * it's not needed any longer.
517 */
518 fclose (in);
519
520 /*
521 * If only one content was found, then remove and
522 * free the outer multipart content.
523 */
524 if (!m->mp_parts->mp_next) {
525 CT p;
526
527 p = m->mp_parts->mp_part;
528 m->mp_parts->mp_part = NULL;
529
530 /* move header fields */
531 p->c_first_hf = ct->c_first_hf;
532 p->c_last_hf = ct->c_last_hf;
533 ct->c_first_hf = NULL;
534 ct->c_last_hf = NULL;
535
536 free_content (ct);
537 ct = p;
538 } else {
539 set_id (ct, 1);
540 }
541
542 /*
543 * Fill out, or expand directives. Parse and execute
544 * commands specified by profile composition strings.
545 */
546 compose_content (ct, verbose);
547
548 if ((cp = strchr(prefix, 'a')) == NULL)
549 adios (NULL, "internal error(4)");
550
551 /*
552 * If using EAI, force 8-bit charset.
553 */
554 if (header_encoding == CE_8BIT) {
555 set_charset (ct, 1);
556 }
557
558 /*
559 * Scan the contents. Choose a transfer encoding, and
560 * check if prefix for multipart boundary clashes with
561 * any of the contents.
562 */
563 while (scan_content (ct, maxunencoded) == NOTOK) {
564 if (*cp < 'z') {
565 (*cp)++;
566 } else {
567 if (*++cp == 0)
568 adios (NULL, "giving up trying to find a unique delimiter string");
569 else
570 (*cp)++;
571 }
572 }
573
574 /* Build the rest of the header field structures */
575 if (! dist)
576 build_headers (ct, header_encoding);
577
578 return ct;
579 }
580
581
582 /*
583 * Set up structures for placing unencoded
584 * content when building parts.
585 */
586
587 static int
588 init_decoded_content (CT ct, const char *filename)
589 {
590 ct->c_ceopenfnx = open7Bit; /* since unencoded */
591 ct->c_ceclosefnx = close_encoding;
592 ct->c_cesizefnx = NULL; /* since unencoded */
593 ct->c_encoding = CE_7BIT; /* Seems like a reasonable default */
594 ct->c_file = add(filename, NULL);
595
596 return OK;
597 }
598
599
600 static char *
601 fgetstr (char *s, int n, FILE *stream)
602 {
603 char *cp, *ep;
604
605 ep = s + n;
606 while(1) {
607 for (cp = s; cp < ep;) {
608 int len;
609
610 if (!fgets (cp, n, stream))
611 return cp == s ? NULL : s; /* "\\\nEOF" ignored. */
612
613 if (! do_direct() || (cp == s && *cp != '#'))
614 return s; /* Plaintext line. */
615
616 len = strlen(cp);
617 if (len <= 1)
618 break; /* Can't contain "\\\n". */
619 cp += len - 1; /* Just before NUL. */
620 if (*cp-- != '\n' || *cp != '\\')
621 break;
622 *cp = '\0'; /* Erase the trailing "\\\n". */
623 n -= (len - 2);
624 }
625
626 if (strcmp(s, "#on\n") == 0) {
627 directive_onoff(1);
628 } else if (strcmp(s, "#off\n") == 0) {
629 directive_onoff(0);
630 } else if (strcmp(s, "#pop\n") == 0) {
631 directive_pop();
632 } else {
633 return s;
634 }
635 }
636 }
637
638
639 /*
640 * Parse the composition draft for text and directives.
641 * Do initial setup of Content structure.
642 */
643
644 static int
645 user_content (FILE *in, char *buf, CT *ctp, const char *infilename)
646 {
647 int extrnal, vrsn;
648 char *cp, **ap;
649 char buffer[NMH_BUFSIZ];
650 struct multipart *m;
651 struct part **pp;
652 struct stat st;
653 struct str2init *s2i;
654 CI ci;
655 CT ct;
656 CE ce;
657
658 if (buf[0] == '\n' || (do_direct() && strcmp (buf, "#\n") == 0)) {
659 *ctp = NULL;
660 return OK;
661 }
662
663 /* allocate basic Content structure */
664 NEW0(ct);
665 *ctp = ct;
666
667 /* allocate basic structure for handling decoded content */
668 init_decoded_content (ct, infilename);
669 ce = &ct->c_cefile;
670
671 ci = &ct->c_ctinfo;
672 set_id (ct, 0);
673
674 /*
675 * Handle inline text. Check if line
676 * is one of the following forms:
677 *
678 * 1) doesn't begin with '#' (implicit directive)
679 * 2) begins with "##" (implicit directive)
680 * 3) begins with "#<"
681 */
682 if (!do_direct() || buf[0] != '#' || buf[1] == '#' || buf[1] == '<') {
683 int headers;
684 int inlineD;
685 long pos;
686 char content[BUFSIZ];
687 FILE *out;
688 char *cp;
689
690 if ((cp = m_mktemp2(NULL, invo_name, NULL, &out)) == NULL) {
691 adios("mhbuildsbr", "unable to create temporary file in %s",
692 get_temp_dir());
693 }
694
695 /* use a temp file to collect the plain text lines */
696 ce->ce_file = mh_xstrdup(cp);
697 ce->ce_unlink = 1;
698
699 if (do_direct() && (buf[0] == '#' && buf[1] == '<')) {
700 strncpy (content, buf + 2, sizeof(content));
701 inlineD = 1;
702 goto rock_and_roll;
703 }
704 inlineD = 0;
705
706 /* the directive is implicit */
707 strncpy (content, "text/plain", sizeof(content));
708 headers = 0;
709 strncpy (buffer, (!do_direct() || buf[0] != '#') ? buf : buf + 1, sizeof(buffer));
710 for (;;) {
711 int i;
712
713 if (headers >= 0 && do_direct() && uprf (buffer, DESCR_FIELD)
714 && buffer[i = strlen (DESCR_FIELD)] == ':') {
715 headers = 1;
716
717 again_descr:
718 ct->c_descr = add (buffer + i + 1, ct->c_descr);
719 if (!fgetstr (buffer, sizeof(buffer) - 1, in))
720 adios (NULL, "end-of-file after %s: field in plaintext", DESCR_FIELD);
721 switch (buffer[0]) {
722 case ' ':
723 case '\t':
724 i = -1;
725 goto again_descr;
726
727 case '#':
728 adios (NULL, "#-directive after %s: field in plaintext", DESCR_FIELD);
729 /* NOTREACHED */
730
731 default:
732 break;
733 }
734 }
735
736 if (headers >= 0 && do_direct() && uprf (buffer, DISPO_FIELD)
737 && buffer[i = strlen (DISPO_FIELD)] == ':') {
738 headers = 1;
739
740 again_dispo:
741 ct->c_dispo = add (buffer + i + 1, ct->c_dispo);
742 if (!fgetstr (buffer, sizeof(buffer) - 1, in))
743 adios (NULL, "end-of-file after %s: field in plaintext", DISPO_FIELD);
744 switch (buffer[0]) {
745 case ' ':
746 case '\t':
747 i = -1;
748 goto again_dispo;
749
750 case '#':
751 adios (NULL, "#-directive after %s: field in plaintext", DISPO_FIELD);
752 /* NOTREACHED */
753
754 default:
755 break;
756 }
757 }
758
759 if (headers != 1 || buffer[0] != '\n')
760 fputs (buffer, out);
761
762 rock_and_roll:
763 headers = -1;
764 pos = ftell (in);
765 if ((cp = fgetstr (buffer, sizeof(buffer) - 1, in)) == NULL)
766 break;
767 if (do_direct() && buffer[0] == '#') {
768 char *bp;
769
770 if (buffer[1] != '#')
771 break;
772 for (cp = (bp = buffer) + 1; *cp; cp++)
773 *bp++ = *cp;
774 *bp = '\0';
775 }
776 }
777
778 if (listsw)
779 ct->c_end = ftell (out);
780 fclose (out);
781
782 /* parse content type */
783 if (get_ctinfo (content, ct, inlineD) == NOTOK)
784 done (1);
785
786 for (s2i = str2cts; s2i->si_key; s2i++)
787 if (!strcasecmp (ci->ci_type, s2i->si_key))
788 break;
789 if (!s2i->si_key && !uprf (ci->ci_type, "X-"))
790 s2i++;
791
792 /*
793 * check type specified (possibly implicitly)
794 */
795 switch (ct->c_type = s2i->si_val) {
796 case CT_MESSAGE:
797 if (!strcasecmp (ci->ci_subtype, "rfc822")) {
798 ct->c_encoding = CE_7BIT;
799 goto call_init;
800 }
801 /* FALLTHRU */
802 case CT_MULTIPART:
803 adios (NULL, "it doesn't make sense to define an in-line %s content",
804 ct->c_type == CT_MESSAGE ? "message" : "multipart");
805 /* NOTREACHED */
806
807 default:
808 call_init:
809 if ((ct->c_ctinitfnx = s2i->si_init))
810 (*ct->c_ctinitfnx) (ct);
811 break;
812 }
813
814 if (cp)
815 fseek (in, pos, SEEK_SET);
816 return OK;
817 }
818
819 /*
820 * If we've reached this point, the next line
821 * must be some type of explicit directive.
822 */
823
824 /* check if directive is external-type */
825 extrnal = (buf[1] == '@');
826
827 /* parse directive */
828 if (get_ctinfo (buf + (extrnal ? 2 : 1), ct, 1) == NOTOK)
829 done (1);
830
831 /* check directive against the list of MIME types */
832 for (s2i = str2cts; s2i->si_key; s2i++)
833 if (!strcasecmp (ci->ci_type, s2i->si_key))
834 break;
835
836 /*
837 * Check if the directive specified a valid type.
838 * This will happen if it was one of the following forms:
839 *
840 * #type/subtype (or)
841 * #@type/subtype
842 */
843 if (s2i->si_key) {
844 if (!ci->ci_subtype)
845 adios (NULL, "missing subtype in \"#%s\"", ci->ci_type);
846
847 switch (ct->c_type = s2i->si_val) {
848 case CT_MULTIPART:
849 adios (NULL, "use \"#begin ... #end\" instead of \"#%s/%s\"",
850 ci->ci_type, ci->ci_subtype);
851 /* NOTREACHED */
852
853 case CT_MESSAGE:
854 if (!strcasecmp (ci->ci_subtype, "partial"))
855 adios (NULL, "sorry, \"#%s/%s\" isn't supported",
856 ci->ci_type, ci->ci_subtype);
857 if (!strcasecmp (ci->ci_subtype, "external-body"))
858 adios (NULL, "use \"#@type/subtype ... [] ...\" instead of \"#%s/%s\"",
859 ci->ci_type, ci->ci_subtype);
860 use_forw:
861 adios (NULL,
862 "use \"#forw [+folder] [msgs]\" instead of \"#%s/%s\"",
863 ci->ci_type, ci->ci_subtype);
864 /* NOTREACHED */
865
866 default:
867 if ((ct->c_ctinitfnx = s2i->si_init))
868 (*ct->c_ctinitfnx) (ct);
869 break;
870 }
871
872 /*
873 * #@type/subtype (external types directive)
874 */
875 if (extrnal) {
876 struct exbody *e;
877 CT p;
878
879 if (!ci->ci_magic)
880 adios (NULL, "need external information for \"#@%s/%s\"",
881 ci->ci_type, ci->ci_subtype);
882 p = ct;
883
884 snprintf (buffer, sizeof(buffer), "message/external-body; %s", ci->ci_magic);
885 free (ci->ci_magic);
886 ci->ci_magic = NULL;
887
888 /*
889 * Since we are using the current Content structure to
890 * hold information about the type of the external
891 * reference, we need to create another Content structure
892 * for the message/external-body to wrap it in.
893 */
894 NEW0(ct);
895 init_decoded_content(ct, infilename);
896 *ctp = ct;
897 if (get_ctinfo (buffer, ct, 0) == NOTOK)
898 done (1);
899 ct->c_type = CT_MESSAGE;
900 ct->c_subtype = MESSAGE_EXTERNAL;
901
902 NEW0(e);
903 ct->c_ctparams = (void *) e;
904
905 e->eb_parent = ct;
906 e->eb_content = p;
907 p->c_ctexbody = e;
908
909 if (params_external (ct, 1) == NOTOK)
910 done (1);
911
912 return OK;
913 }
914
915 /* Handle [file] argument */
916 if (ci->ci_magic) {
917 /* check if specifies command to execute */
918 if (*ci->ci_magic == '|' || *ci->ci_magic == '!') {
919 for (cp = ci->ci_magic + 1; isspace ((unsigned char) *cp); cp++)
920 continue;
921 if (!*cp)
922 adios (NULL, "empty pipe command for #%s directive", ci->ci_type);
923 cp = mh_xstrdup(cp);
924 free (ci->ci_magic);
925 ci->ci_magic = cp;
926 } else {
927 /* record filename of decoded contents */
928 ce->ce_file = ci->ci_magic;
929 if (access (ce->ce_file, R_OK) == NOTOK)
930 adios ("reading", "unable to access %s for", ce->ce_file);
931 if (listsw && stat (ce->ce_file, &st) != NOTOK)
932 ct->c_end = (long) st.st_size;
933 ci->ci_magic = NULL;
934 }
935 return OK;
936 }
937
938 /*
939 * No [file] argument, so check profile for
940 * method to compose content.
941 */
942 cp = context_find_by_type ("compose", ci->ci_type, ci->ci_subtype);
943 if (cp == NULL) {
944 content_error (NULL, ct, "don't know how to compose content");
945 done (1);
946 }
947 ci->ci_magic = mh_xstrdup(cp);
948 return OK;
949 }
950
951 if (extrnal)
952 adios (NULL, "external definition not allowed for \"#%s\"", ci->ci_type);
953
954 /*
955 * Message directive
956 * #forw [+folder] [msgs]
957 */
958 if (!strcasecmp (ci->ci_type, "forw")) {
959 int msgnum;
960 char *folder, *arguments[MAXARGS];
961 struct msgs *mp;
962
963 if (ci->ci_magic) {
964 ap = brkstring (ci->ci_magic, " ", "\n");
965 copyip (ap, arguments, MAXARGS);
966 } else {
967 arguments[0] = "cur";
968 arguments[1] = NULL;
969 }
970 folder = NULL;
971
972 /* search the arguments for a folder name */
973 for (ap = arguments; *ap; ap++) {
974 cp = *ap;
975 if (*cp == '+' || *cp == '@') {
976 if (folder)
977 adios (NULL, "only one folder per #forw directive");
978 else
979 folder = pluspath (cp);
980 }
981 }
982
983 /* else, use the current folder */
984 if (!folder)
985 folder = mh_xstrdup(getfolder(1));
986
987 if (!(mp = folder_read (folder, 0)))
988 adios (NULL, "unable to read folder %s", folder);
989 for (ap = arguments; *ap; ap++) {
990 cp = *ap;
991 if (*cp != '+' && *cp != '@')
992 if (!m_convert (mp, cp))
993 done (1);
994 }
995 free (folder);
996 free_ctinfo (ct);
997
998 /*
999 * If there is more than one message to include, make this
1000 * a content of type "multipart/digest" and insert each message
1001 * as a subpart. If there is only one message, then make this
1002 * a content of type "message/rfc822".
1003 */
1004 if (mp->numsel > 1) {
1005 /* we are forwarding multiple messages */
1006 if (get_ctinfo ("multipart/digest", ct, 0) == NOTOK)
1007 done (1);
1008 ct->c_type = CT_MULTIPART;
1009 ct->c_subtype = MULTI_DIGEST;
1010
1011 NEW0(m);
1012 ct->c_ctparams = (void *) m;
1013 pp = &m->mp_parts;
1014
1015 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1016 if (is_selected(mp, msgnum)) {
1017 struct part *part;
1018 CT p;
1019 CE pe;
1020
1021 NEW0(p);
1022 init_decoded_content (p, infilename);
1023 pe = &p->c_cefile;
1024 if (get_ctinfo ("message/rfc822", p, 0) == NOTOK)
1025 done (1);
1026 p->c_type = CT_MESSAGE;
1027 p->c_subtype = MESSAGE_RFC822;
1028
1029 snprintf (buffer, sizeof(buffer), "%s/%d", mp->foldpath, msgnum);
1030 pe->ce_file = mh_xstrdup(buffer);
1031 if (listsw && stat (pe->ce_file, &st) != NOTOK)
1032 p->c_end = (long) st.st_size;
1033
1034 NEW0(part);
1035 *pp = part;
1036 pp = &part->mp_next;
1037 part->mp_part = p;
1038 }
1039 }
1040 } else {
1041 /* we are forwarding one message */
1042 if (get_ctinfo ("message/rfc822", ct, 0) == NOTOK)
1043 done (1);
1044 ct->c_type = CT_MESSAGE;
1045 ct->c_subtype = MESSAGE_RFC822;
1046
1047 msgnum = mp->lowsel;
1048 snprintf (buffer, sizeof(buffer), "%s/%d", mp->foldpath, msgnum);
1049 ce->ce_file = mh_xstrdup(buffer);
1050 if (listsw && stat (ce->ce_file, &st) != NOTOK)
1051 ct->c_end = (long) st.st_size;
1052 }
1053
1054 folder_free (mp); /* free folder/message structure */
1055 return OK;
1056 }
1057
1058 /*
1059 * #end
1060 */
1061 if (!strcasecmp (ci->ci_type, "end")) {
1062 free_content (ct);
1063 *ctp = NULL;
1064 return DONE;
1065 }
1066
1067 /*
1068 * #begin [ alternative | parallel ]
1069 */
1070 if (!strcasecmp (ci->ci_type, "begin")) {
1071 if (!ci->ci_magic) {
1072 vrsn = MULTI_MIXED;
1073 cp = SubMultiPart[vrsn - 1].kv_key;
1074 } else if (!strcasecmp (ci->ci_magic, "alternative")) {
1075 vrsn = MULTI_ALTERNATE;
1076 cp = SubMultiPart[vrsn - 1].kv_key;
1077 } else if (!strcasecmp (ci->ci_magic, "parallel")) {
1078 vrsn = MULTI_PARALLEL;
1079 cp = SubMultiPart[vrsn - 1].kv_key;
1080 } else if (uprf (ci->ci_magic, "digest")) {
1081 goto use_forw;
1082 } else {
1083 vrsn = MULTI_UNKNOWN;
1084 cp = ci->ci_magic;
1085 }
1086
1087 free_ctinfo (ct);
1088 snprintf (buffer, sizeof(buffer), "multipart/%s", cp);
1089 if (get_ctinfo (buffer, ct, 0) == NOTOK)
1090 done (1);
1091 ct->c_type = CT_MULTIPART;
1092 ct->c_subtype = vrsn;
1093
1094 NEW0(m);
1095 ct->c_ctparams = (void *) m;
1096
1097 pp = &m->mp_parts;
1098 while (fgetstr (buffer, sizeof(buffer) - 1, in)) {
1099 struct part *part;
1100 CT p;
1101
1102 if (user_content (in, buffer, &p, infilename) == DONE) {
1103 if (!m->mp_parts)
1104 adios (NULL, "empty \"#begin ... #end\" sequence");
1105 return OK;
1106 }
1107 if (!p)
1108 continue;
1109
1110 NEW0(part);
1111 *pp = part;
1112 pp = &part->mp_next;
1113 part->mp_part = p;
1114 }
1115 inform("premature end-of-file, missing #end, continuing...");
1116 return OK;
1117 }
1118
1119 /*
1120 * Unknown directive
1121 */
1122 adios (NULL, "unknown directive \"#%s\"", ci->ci_type);
1123 return NOTOK; /* NOT REACHED */
1124 }
1125
1126
1127 static void
1128 set_id (CT ct, int top)
1129 {
1130 char contentid[BUFSIZ];
1131 static int partno;
1132 static time_t clock = 0;
1133 static char *msgfmt;
1134
1135 if (clock == 0) {
1136 time (&clock);
1137 snprintf (contentid, sizeof(contentid), "%s\n", message_id (clock, 1));
1138 partno = 0;
1139 msgfmt = mh_xstrdup(contentid);
1140 }
1141 snprintf (contentid, sizeof(contentid), msgfmt, top ? 0 : ++partno);
1142 ct->c_id = mh_xstrdup(contentid);
1143 }
1144
1145
1146 /*
1147 * Fill out, or expand the various contents in the composition
1148 * draft. Read-in any necessary files. Parse and execute any
1149 * commands specified by profile composition strings.
1150 */
1151
1152 static int
1153 compose_content (CT ct, int verbose)
1154 {
1155 CE ce = &ct->c_cefile;
1156
1157 switch (ct->c_type) {
1158 case CT_MULTIPART:
1159 {
1160 int partnum;
1161 char *pp;
1162 char partnam[BUFSIZ];
1163 struct multipart *m = (struct multipart *) ct->c_ctparams;
1164 struct part *part;
1165
1166 if (ct->c_partno) {
1167 snprintf (partnam, sizeof(partnam), "%s.", ct->c_partno);
1168 pp = partnam + strlen (partnam);
1169 } else {
1170 pp = partnam;
1171 }
1172
1173 /* first, we call compose_content on all the subparts */
1174 for (part = m->mp_parts, partnum = 1; part; part = part->mp_next, partnum++) {
1175 CT p = part->mp_part;
1176
1177 sprintf (pp, "%d", partnum);
1178 p->c_partno = mh_xstrdup(partnam);
1179 if (compose_content (p, verbose) == NOTOK)
1180 return NOTOK;
1181 }
1182
1183 /*
1184 * If the -rfc934mode switch is given, then check all
1185 * the subparts of a multipart/digest. If they are all
1186 * message/rfc822, then mark this content and all
1187 * subparts with the rfc934 compatibility mode flag.
1188 */
1189 if (rfc934sw && ct->c_subtype == MULTI_DIGEST) {
1190 int is934 = 1;
1191
1192 for (part = m->mp_parts; part; part = part->mp_next) {
1193 CT p = part->mp_part;
1194
1195 if (p->c_subtype != MESSAGE_RFC822) {
1196 is934 = 0;
1197 break;
1198 }
1199 }
1200 ct->c_rfc934 = is934;
1201 for (part = m->mp_parts; part; part = part->mp_next) {
1202 CT p = part->mp_part;
1203
1204 if ((p->c_rfc934 = is934))
1205 p->c_end++;
1206 }
1207 }
1208
1209 if (listsw) {
1210 ct->c_end = (partnum = strlen (prefix) + 2) + 2;
1211 if (ct->c_rfc934)
1212 ct->c_end++;
1213
1214 for (part = m->mp_parts; part; part = part->mp_next)
1215 ct->c_end += part->mp_part->c_end + partnum;
1216 }
1217 }
1218 break;
1219
1220 case CT_MESSAGE:
1221 /* Nothing to do for type message */
1222 break;
1223
1224 /*
1225 * Discrete types (text/application/audio/image/video)
1226 */
1227 default:
1228 if (!ce->ce_file) {
1229 pid_t child_id;
1230 int i, xstdout, len, buflen;
1231 char *bp, *cp;
1232 char *vec[4], buffer[BUFSIZ];
1233 FILE *out;
1234 CI ci = &ct->c_ctinfo;
1235 char *tfile = NULL;
1236
1237 if (!(cp = ci->ci_magic))
1238 adios (NULL, "internal error(5)");
1239
1240 if ((tfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
1241 adios("mhbuildsbr", "unable to create temporary file in %s",
1242 get_temp_dir());
1243 }
1244 ce->ce_file = mh_xstrdup(tfile);
1245 ce->ce_unlink = 1;
1246
1247 xstdout = 0;
1248
1249 /* Get buffer ready to go */
1250 bp = buffer;
1251 bp[0] = '\0';
1252 buflen = sizeof(buffer);
1253
1254 /*
1255 * Parse composition string into buffer
1256 */
1257 for ( ; *cp; cp++) {
1258 if (*cp == '%') {
1259 switch (*++cp) {
1260 case 'a':
1261 {
1262 /* insert parameters from directive */
1263 char *s = "";
1264 PM pm;
1265
1266 for (pm = ci->ci_first_pm; pm; pm = pm->pm_next) {
1267 snprintf (bp, buflen, "%s%s=\"%s\"", s,
1268 pm->pm_name, get_param_value(pm, '?'));
1269 len = strlen (bp);
1270 bp += len;
1271 buflen -= len;
1272 s = " ";
1273 }
1274 }
1275 break;
1276
1277 case 'F':
1278 /* %f, and stdout is not-redirected */
1279 xstdout = 1;
1280 /* FALLTHRU */
1281
1282 case 'f':
1283 /*
1284 * insert temporary filename where
1285 * content should be written
1286 */
1287 snprintf (bp, buflen, "%s", ce->ce_file);
1288 break;
1289
1290 case 's':
1291 /* insert content subtype */
1292 strncpy (bp, ci->ci_subtype, buflen);
1293 break;
1294
1295 case '%':
1296 /* insert character % */
1297 goto raw;
1298
1299 default:
1300 *bp++ = *--cp;
1301 *bp = '\0';
1302 buflen--;
1303 continue;
1304 }
1305 len = strlen (bp);
1306 bp += len;
1307 buflen -= len;
1308 } else {
1309 raw:
1310 *bp++ = *cp;
1311 *bp = '\0';
1312 buflen--;
1313 }
1314 }
1315
1316 if (verbose)
1317 printf ("composing content %s/%s from command\n\t%s\n",
1318 ci->ci_type, ci->ci_subtype, buffer);
1319
1320 fflush (stdout); /* not sure if need for -noverbose */
1321
1322 vec[0] = "/bin/sh";
1323 vec[1] = "-c";
1324 vec[2] = buffer;
1325 vec[3] = NULL;
1326
1327 if ((out = fopen (ce->ce_file, "w")) == NULL)
1328 adios (ce->ce_file, "unable to open for writing");
1329
1330 for (i = 0; (child_id = fork()) == NOTOK && i > 5; i++)
1331 sleep (5);
1332 switch (child_id) {
1333 case NOTOK:
1334 adios ("fork", "unable to fork");
1335 /* NOTREACHED */
1336
1337 case OK:
1338 if (!xstdout)
1339 dup2 (fileno (out), 1);
1340 close (fileno (out));
1341 execvp ("/bin/sh", vec);
1342 fprintf (stderr, "unable to exec ");
1343 perror ("/bin/sh");
1344 _exit (-1);
1345 /* NOTREACHED */
1346
1347 default:
1348 fclose (out);
1349 if (pidXwait(child_id, NULL))
1350 done (1);
1351 break;
1352 }
1353 }
1354
1355 /* Check size of file */
1356 if (listsw && ct->c_end == 0L) {
1357 struct stat st;
1358
1359 if (stat (ce->ce_file, &st) != NOTOK)
1360 ct->c_end = (long) st.st_size;
1361 }
1362 break;
1363 }
1364
1365 return OK;
1366 }
1367
1368
1369 /*
1370 * Scan the content.
1371 *
1372 * 1) choose a transfer encoding.
1373 * 2) check for clashes with multipart boundary string.
1374 * 3) for text content, figure out which character set is being used.
1375 *
1376 * If there is a clash with one of the contents and the multipart boundary,
1377 * this function will exit with NOTOK. This will cause the scanning process
1378 * to be repeated with a different multipart boundary. It is possible
1379 * (although highly unlikely) that this scan will be repeated multiple times.
1380 */
1381
1382 static int
1383 scan_content (CT ct, size_t maxunencoded)
1384 {
1385 int prefix_len;
1386 int check8bit = 0, contains8bit = 0; /* check if contains 8bit data */
1387 int checknul = 0, containsnul = 0; /* check if contains NULs */
1388 int checklinelen = 0, linelen = 0; /* check for long lines */
1389 int checkllinelen = 0; /* check for extra-long lines */
1390 int checkboundary = 0, boundaryclash = 0; /* check if clashes with multipart boundary */
1391 int checklinespace = 0, linespace = 0; /* check if any line ends with space */
1392 char *cp = NULL;
1393 char *bufp = NULL;
1394 size_t buflen;
1395 ssize_t gotlen;
1396 struct text *t = NULL;
1397 FILE *in = NULL;
1398 CE ce = &ct->c_cefile;
1399
1400 /*
1401 * handle multipart by scanning all subparts
1402 * and then checking their encoding.
1403 */
1404 if (ct->c_type == CT_MULTIPART) {
1405 struct multipart *m = (struct multipart *) ct->c_ctparams;
1406 struct part *part;
1407
1408 /* initially mark the domain of enclosing multipart as 7bit */
1409 ct->c_encoding = CE_7BIT;
1410
1411 for (part = m->mp_parts; part; part = part->mp_next) {
1412 CT p = part->mp_part;
1413
1414 if (scan_content (p, maxunencoded) == NOTOK) /* choose encoding for subpart */
1415 return NOTOK;
1416
1417 /* if necessary, enlarge encoding for enclosing multipart */
1418 if (p->c_encoding == CE_BINARY)
1419 ct->c_encoding = CE_BINARY;
1420 if (p->c_encoding == CE_8BIT && ct->c_encoding != CE_BINARY)
1421 ct->c_encoding = CE_8BIT;
1422 }
1423
1424 return OK;
1425 }
1426
1427 /*
1428 * Decide what to check while scanning this content. Note that
1429 * for text content we always check for 8bit characters if the
1430 * charset is unspecified, because that controls whether or not the
1431 * character set is us-ascii or retrieved from the locale. And
1432 * we check even if the charset is specified, to allow setting
1433 * the proper Content-Transfer-Encoding.
1434 */
1435
1436 if (ct->c_type == CT_TEXT) {
1437 t = (struct text *) ct->c_ctparams;
1438 if (t->tx_charset == CHARSET_UNSPECIFIED) {
1439 checknul = 1;
1440 }
1441 check8bit = 1;
1442 }
1443
1444 switch (ct->c_reqencoding) {
1445 case CE_8BIT:
1446 checkllinelen = 1;
1447 checkboundary = 1;
1448 break;
1449 case CE_QUOTED:
1450 checkboundary = 1;
1451 break;
1452 case CE_BASE64:
1453 break;
1454 case CE_UNKNOWN:
1455 /* Use the default rules based on content-type */
1456 switch (ct->c_type) {
1457 case CT_TEXT:
1458 checkboundary = 1;
1459 checklinelen = 1;
1460 if (ct->c_subtype == TEXT_PLAIN) {
1461 checklinespace = 0;
1462 } else {
1463 checklinespace = 1;
1464 }
1465 break;
1466
1467 case CT_APPLICATION:
1468 check8bit = 1;
1469 checknul = 1;
1470 checklinelen = 1;
1471 checklinespace = 1;
1472 checkboundary = 1;
1473 break;
1474
1475 case CT_MESSAGE:
1476 checklinelen = 0;
1477 checklinespace = 0;
1478
1479 /* don't check anything for message/external */
1480 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1481 checkboundary = 0;
1482 check8bit = 0;
1483 } else {
1484 checkboundary = 1;
1485 check8bit = 1;
1486 }
1487 break;
1488
1489 case CT_AUDIO:
1490 case CT_IMAGE:
1491 case CT_VIDEO:
1492 /*
1493 * Don't check anything for these types,
1494 * since we are forcing use of base64, unless
1495 * the content-type was specified by a mhbuild directive.
1496 */
1497 check8bit = 0;
1498 checklinelen = 0;
1499 checklinespace = 0;
1500 checkboundary = 0;
1501 break;
1502 }
1503 }
1504
1505 /*
1506 * Scan the unencoded content
1507 */
1508 if (check8bit || checklinelen || checklinespace || checkboundary ||
1509 checkllinelen || checknul) {
1510 if ((in = fopen (ce->ce_file, "r")) == NULL)
1511 adios (ce->ce_file, "unable to open for reading");
1512 prefix_len = strlen (prefix);
1513
1514 while ((gotlen = getline(&bufp, &buflen, in)) != -1) {
1515 /*
1516 * Check for 8bit and NUL data.
1517 */
1518 for (cp = bufp; (check8bit || checknul) &&
1519 cp < bufp + gotlen; cp++) {
1520 if (!isascii ((unsigned char) *cp)) {
1521 contains8bit = 1;
1522 check8bit = 0; /* no need to keep checking */
1523 }
1524 if (!*cp) {
1525 containsnul = 1;
1526 checknul = 0; /* no need to keep checking */
1527 }
1528 }
1529
1530 /*
1531 * Check line length.
1532 */
1533 if (checklinelen && ((size_t)gotlen > maxunencoded + 1)) {
1534 linelen = 1;
1535 checklinelen = 0; /* no need to keep checking */
1536 }
1537
1538 /*
1539 * RFC 5322 specifies that a message cannot contain a line
1540 * greater than 998 characters (excluding the CRLF). If we
1541 * get one of those lines and linelen is NOT set, then abort.
1542 */
1543
1544 if (checkllinelen && !linelen &&
1545 (gotlen > MAXLONGLINE + 1)) {
1546 adios(NULL, "Line in content exceeds maximum line limit (%d)",
1547 MAXLONGLINE);
1548 }
1549
1550 /*
1551 * Check if line ends with a space.
1552 */
1553 if (checklinespace && (cp = bufp + gotlen - 2) > bufp &&
1554 isspace ((unsigned char) *cp)) {
1555 linespace = 1;
1556 checklinespace = 0; /* no need to keep checking */
1557 }
1558
1559 /*
1560 * Check if content contains a line that clashes
1561 * with our standard boundary for multipart messages.
1562 */
1563 if (checkboundary && bufp[0] == '-' && bufp[1] == '-') {
1564 for (cp = bufp + gotlen - 1; cp >= bufp; cp--)
1565 if (!isspace ((unsigned char) *cp))
1566 break;
1567 *++cp = '\0';
1568 if (!strncmp(bufp + 2, prefix, prefix_len) &&
1569 isdigit((unsigned char) bufp[2 + prefix_len])) {
1570 boundaryclash = 1;
1571 checkboundary = 0; /* no need to keep checking */
1572 }
1573 }
1574 }
1575 fclose (in);
1576 free(bufp);
1577 }
1578
1579 /*
1580 * If the content is text and didn't specify a character set,
1581 * we need to figure out which one was used.
1582 */
1583 set_charset (ct, contains8bit);
1584
1585 /*
1586 * Decide which transfer encoding to use.
1587 */
1588
1589 if (ct->c_reqencoding != CE_UNKNOWN)
1590 ct->c_encoding = ct->c_reqencoding;
1591 else {
1592 int wants_q_p = (containsnul || linelen || linespace || checksw);
1593
1594 switch (ct->c_type) {
1595 case CT_TEXT:
1596 if (wants_q_p)
1597 ct->c_encoding = CE_QUOTED;
1598 else if (contains8bit)
1599 ct->c_encoding = CE_8BIT;
1600 else
1601 ct->c_encoding = CE_7BIT;
1602
1603 break;
1604
1605 case CT_APPLICATION:
1606 /* For application type, use base64, except when postscript */
1607 if (wants_q_p || contains8bit) {
1608 if (ct->c_subtype == APPLICATION_POSTSCRIPT)
1609 ct->c_encoding = CE_QUOTED; /* historical */
1610 else
1611 ct->c_encoding = CE_BASE64;
1612 } else {
1613 ct->c_encoding = CE_7BIT;
1614 }
1615 break;
1616
1617 case CT_MESSAGE:
1618 ct->c_encoding = contains8bit ? CE_8BIT : CE_7BIT;
1619 break;
1620
1621 case CT_AUDIO:
1622 case CT_IMAGE:
1623 case CT_VIDEO:
1624 /* For audio, image, and video contents, just use base64 */
1625 ct->c_encoding = CE_BASE64;
1626 break;
1627 }
1628 }
1629
1630 return (boundaryclash ? NOTOK : OK);
1631 }
1632
1633
1634 /*
1635 * Scan the content structures, and build header
1636 * fields that will need to be output into the
1637 * message.
1638 */
1639
1640 static int
1641 build_headers (CT ct, int header_encoding)
1642 {
1643 int cc, mailbody, extbody, len;
1644 char *np, *vp, buffer[BUFSIZ];
1645 CI ci = &ct->c_ctinfo;
1646
1647 /*
1648 * If message is type multipart, then add the multipart
1649 * boundary to the list of attribute/value pairs.
1650 */
1651 if (ct->c_type == CT_MULTIPART) {
1652 static int level = 0; /* store nesting level */
1653
1654 snprintf (buffer, sizeof(buffer), "%s%d", prefix, level++);
1655 add_param(&ci->ci_first_pm, &ci->ci_last_pm, "boundary", buffer, 0);
1656 }
1657
1658 /*
1659 * Skip the output of Content-Type, parameters, content
1660 * description and disposition, and Content-ID if the
1661 * content is of type "message" and the rfc934 compatibility
1662 * flag is set (which means we are inside multipart/digest
1663 * and the switch -rfc934mode was given).
1664 */
1665 if (ct->c_type == CT_MESSAGE && ct->c_rfc934)
1666 goto skip_headers;
1667
1668 /*
1669 * output the content type and subtype
1670 */
1671 np = mh_xstrdup(TYPE_FIELD);
1672 vp = concat (" ", ci->ci_type, "/", ci->ci_subtype, NULL);
1673
1674 /* keep track of length of line */
1675 len = strlen (TYPE_FIELD) + strlen (ci->ci_type)
1676 + strlen (ci->ci_subtype) + 3;
1677
1678 extbody = ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_EXTERNAL;
1679 mailbody = extbody && ((struct exbody *) ct->c_ctparams)->eb_body;
1680
1681 /*
1682 * Append the attribute/value pairs to
1683 * the end of the Content-Type line.
1684 */
1685
1686 if (ci->ci_first_pm) {
1687 char *s = output_params(len, ci->ci_first_pm, &len, mailbody);
1688
1689 if (!s)
1690 adios(NULL, "Internal error: failed outputting Content-Type "
1691 "parameters");
1692
1693 vp = add (s, vp);
1694 free(s);
1695 }
1696
1697 /*
1698 * Append any RFC-822 comment to the end of
1699 * the Content-Type line.
1700 */
1701 if (ci->ci_comment) {
1702 snprintf (buffer, sizeof(buffer), "(%s)", ci->ci_comment);
1703 if (len + 1 + (cc = 2 + strlen (ci->ci_comment)) >= CPERLIN) {
1704 vp = add ("\n\t", vp);
1705 len = 8;
1706 } else {
1707 vp = add (" ", vp);
1708 len++;
1709 }
1710 vp = add (buffer, vp);
1711 len += cc;
1712 }
1713 vp = add ("\n", vp);
1714 add_header (ct, np, vp);
1715
1716 /*
1717 * output the Content-ID, unless disabled by -nocontentid. Note that
1718 * RFC 2045 always requires a Content-ID header for message/external-body
1719 * entities.
1720 */
1721 if ((contentidsw || ct->c_ctexbody) && ct->c_id) {
1722 np = mh_xstrdup(ID_FIELD);
1723 vp = concat (" ", ct->c_id, NULL);
1724 add_header (ct, np, vp);
1725 }
1726 /*
1727 * output the Content-Description
1728 */
1729 if (ct->c_descr) {
1730 np = mh_xstrdup(DESCR_FIELD);
1731 vp = concat (" ", ct->c_descr, NULL);
1732 if (header_encoding != CE_8BIT) {
1733 if (encode_rfc2047(DESCR_FIELD, &vp, header_encoding, NULL)) {
1734 adios(NULL, "Unable to encode %s header", DESCR_FIELD);
1735 }
1736 }
1737 add_header (ct, np, vp);
1738 }
1739
1740 /*
1741 * output the Content-Disposition. If it's NULL but c_dispo_type is
1742 * set, then we need to build it.
1743 */
1744 if (ct->c_dispo) {
1745 np = mh_xstrdup(DISPO_FIELD);
1746 vp = concat (" ", ct->c_dispo, NULL);
1747 add_header (ct, np, vp);
1748 } else if (ct->c_dispo_type) {
1749 vp = concat (" ", ct->c_dispo_type, NULL);
1750 len = strlen(DISPO_FIELD) + strlen(vp) + 1;
1751 np = output_params(len, ct->c_dispo_first, NULL, 0);
1752 vp = add(np, vp);
1753 vp = add("\n", vp);
1754 mh_xfree(np);
1755 add_header (ct, mh_xstrdup(DISPO_FIELD), vp);
1756 }
1757
1758 skip_headers:
1759 /*
1760 * If this is the internal content structure for a
1761 * "message/external", then we are done with the
1762 * headers (since it has no body).
1763 */
1764 if (ct->c_ctexbody)
1765 return OK;
1766
1767 /*
1768 * output the Content-MD5
1769 */
1770 if (checksw) {
1771 np = mh_xstrdup(MD5_FIELD);
1772 vp = calculate_digest (ct, ct->c_encoding == CE_QUOTED);
1773 add_header (ct, np, vp);
1774 }
1775
1776 /*
1777 * output the Content-Transfer-Encoding
1778 * If using EAI and message body is 7-bit, force 8-bit C-T-E.
1779 */
1780 if (header_encoding == CE_8BIT && ct->c_encoding == CE_7BIT) {
1781 ct->c_encoding = CE_8BIT;
1782 }
1783
1784 switch (ct->c_encoding) {
1785 case CE_7BIT:
1786 /* Nothing to output */
1787 break;
1788
1789 case CE_8BIT:
1790 np = mh_xstrdup(ENCODING_FIELD);
1791 vp = concat (" ", "8bit", "\n", NULL);
1792 add_header (ct, np, vp);
1793 break;
1794
1795 case CE_QUOTED:
1796 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1797 adios (NULL, "internal error, invalid encoding");
1798
1799 np = mh_xstrdup(ENCODING_FIELD);
1800 vp = concat (" ", "quoted-printable", "\n", NULL);
1801 add_header (ct, np, vp);
1802 break;
1803
1804 case CE_BASE64:
1805 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1806 adios (NULL, "internal error, invalid encoding");
1807
1808 np = mh_xstrdup(ENCODING_FIELD);
1809 vp = concat (" ", "base64", "\n", NULL);
1810 add_header (ct, np, vp);
1811 break;
1812
1813 case CE_BINARY:
1814 if (ct->c_type == CT_MESSAGE)
1815 adios (NULL, "internal error, invalid encoding");
1816
1817 np = mh_xstrdup(ENCODING_FIELD);
1818 vp = concat (" ", "binary", "\n", NULL);
1819 add_header (ct, np, vp);
1820 break;
1821
1822 default:
1823 adios (NULL, "unknown transfer encoding in content");
1824 break;
1825 }
1826
1827 /*
1828 * Additional content specific header processing
1829 */
1830 switch (ct->c_type) {
1831 case CT_MULTIPART:
1832 {
1833 struct multipart *m;
1834 struct part *part;
1835
1836 m = (struct multipart *) ct->c_ctparams;
1837 for (part = m->mp_parts; part; part = part->mp_next) {
1838 CT p;
1839
1840 p = part->mp_part;
1841 build_headers (p, header_encoding);
1842 }
1843 }
1844 break;
1845
1846 case CT_MESSAGE:
1847 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1848 struct exbody *e;
1849
1850 e = (struct exbody *) ct->c_ctparams;
1851 build_headers (e->eb_content, header_encoding);
1852 }
1853 break;
1854
1855 default:
1856 /* Nothing to do */
1857 break;
1858 }
1859
1860 return OK;
1861 }
1862
1863
1864 static char nib2b64[0x40+1] =
1865 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1866
1867 static char *
1868 calculate_digest (CT ct, int asciiP)
1869 {
1870 int cc;
1871 char *vp, *op;
1872 unsigned char *dp;
1873 unsigned char digest[16];
1874 unsigned char outbuf[25];
1875 MD5_CTX mdContext;
1876 CE ce = &ct->c_cefile;
1877 char *infilename = ce->ce_file ? ce->ce_file : ct->c_file;
1878 FILE *in;
1879
1880 /* open content */
1881 if ((in = fopen (infilename, "r")) == NULL)
1882 adios (infilename, "unable to open for reading");
1883
1884 /* Initialize md5 context */
1885 MD5Init (&mdContext);
1886
1887 /* calculate md5 message digest */
1888 if (asciiP) {
1889 char *bufp = NULL;
1890 size_t buflen;
1891 ssize_t gotlen;
1892 while ((gotlen = getline(&bufp, &buflen, in)) != -1) {
1893 char c, *cp;
1894
1895 cp = bufp + gotlen - 1;
1896 if ((c = *cp) == '\n')
1897 gotlen--;
1898
1899 MD5Update (&mdContext, (unsigned char *) bufp,
1900 (unsigned int) gotlen);
1901
1902 if (c == '\n')
1903 MD5Update (&mdContext, (unsigned char *) "\r\n", 2);
1904 }
1905 } else {
1906 char buffer[BUFSIZ];
1907 while ((cc = fread (buffer, sizeof(*buffer), sizeof(buffer), in)) > 0)
1908 MD5Update (&mdContext, (unsigned char *) buffer, (unsigned int) cc);
1909 }
1910
1911 /* md5 finalization. Write digest and zero md5 context */
1912 MD5Final (digest, &mdContext);
1913
1914 /* close content */
1915 fclose (in);
1916
1917 /* print debugging info */
1918 if (debugsw) {
1919 unsigned char *ep;
1920
1921 fprintf (stderr, "MD5 digest=");
1922 for (ep = (dp = digest) + sizeof digest;
1923 dp < ep; dp++)
1924 fprintf (stderr, "%02x", *dp & 0xff);
1925 fprintf (stderr, "\n");
1926 }
1927
1928 /* encode the digest using base64 */
1929 for (dp = digest, op = (char *) outbuf,
1930 cc = sizeof digest;
1931 cc > 0; cc -= 3, op += 4) {
1932 unsigned long bits;
1933 char *bp;
1934
1935 bits = (*dp++ & 0xff) << 16;
1936 if (cc > 1) {
1937 bits |= (*dp++ & 0xff) << 8;
1938 if (cc > 2)
1939 bits |= *dp++ & 0xff;
1940 }
1941
1942 for (bp = op + 4; bp > op; bits >>= 6)
1943 *--bp = nib2b64[bits & 0x3f];
1944 if (cc < 3) {
1945 *(op + 3) = '=';
1946 if (cc < 2)
1947 *(op + 2) = '=';
1948 }
1949 }
1950
1951 /* null terminate string */
1952 outbuf[24] = '\0';
1953
1954 /* now make copy and return string */
1955 vp = concat (" ", outbuf, "\n", NULL);
1956 return vp;
1957 }
1958
1959 /*
1960 * Set things up for the content structure for file "filename" that
1961 * we want to attach
1962 */
1963
1964 static void
1965 setup_attach_content(CT ct, char *filename)
1966 {
1967 char *type, *simplename = r1bindex(filename, '/');
1968 struct str2init *s2i;
1969 PM pm;
1970
1971 if (! (type = mime_type(filename))) {
1972 adios(NULL, "Unable to determine MIME type of \"%s\"", filename);
1973 }
1974
1975 /*
1976 * Parse the Content-Type. get_ctinfo() parses MIME parameters, but
1977 * since we're just feeding it a MIME type we have to add those ourselves.
1978 * Map that to a valid content-type label and call any initialization
1979 * function.
1980 */
1981
1982 if (get_ctinfo(type, ct, 0) == NOTOK)
1983 done(1);
1984
1985 free(type);
1986
1987 for (s2i = str2cts; s2i->si_key; s2i++)
1988 if (strcasecmp(ct->c_ctinfo.ci_type, s2i->si_key) == 0)
1989 break;
1990 if (!s2i->si_key && !uprf(ct->c_ctinfo.ci_type, "X-"))
1991 s2i++;
1992
1993 /*
1994 * Make sure the type isn't incompatible with what we can handle
1995 */
1996
1997 switch (ct->c_type = s2i->si_val) {
1998 case CT_MULTIPART:
1999 adios (NULL, "multipart types must be specified by mhbuild directives");
2000 /* NOTREACHED */
2001
2002 case CT_MESSAGE:
2003 if (strcasecmp(ct->c_ctinfo.ci_subtype, "partial") == 0)
2004 adios(NULL, "Sorry, %s/%s isn't supported", ct->c_ctinfo.ci_type,
2005 ct->c_ctinfo.ci_subtype);
2006 if (strcasecmp(ct->c_ctinfo.ci_subtype, "external-body") == 0)
2007 adios(NULL, "external-body messages must be specified "
2008 "by mhbuild directives");
2009 /* FALLTHRU */
2010
2011 default:
2012 /*
2013 * This sets the subtype, if it's significant
2014 */
2015 if ((ct->c_ctinitfnx = s2i->si_init))
2016 (*ct->c_ctinitfnx)(ct);
2017 break;
2018 }
2019
2020 /*
2021 * Feed in a few attributes; specifically, the name attribute, the
2022 * content-description, and the content-disposition.
2023 */
2024
2025 for (pm = ct->c_ctinfo.ci_first_pm; pm; pm = pm->pm_next) {
2026 if (strcasecmp(pm->pm_name, "name") == 0) {
2027 mh_xfree(pm->pm_value);
2028 pm->pm_value = mh_xstrdup(simplename);
2029 break;
2030 }
2031 }
2032
2033 if (pm == NULL)
2034 add_param(&ct->c_ctinfo.ci_first_pm, &ct->c_ctinfo.ci_last_pm,
2035 "name", simplename, 0);
2036
2037 ct->c_descr = mh_xstrdup(simplename);
2038 ct->c_descr = add("\n", ct->c_descr);
2039 ct->c_cefile.ce_file = mh_xstrdup(filename);
2040
2041 set_disposition (ct);
2042
2043 add_param(&ct->c_dispo_first, &ct->c_dispo_last, "filename", simplename, 0);
2044 }
2045
2046 /*
2047 * If disposition type hasn't already been set in ct:
2048 * Look for mhbuild-disposition-<type>/<subtype> entry
2049 * that specifies Content-Disposition type. Only
2050 * 'attachment' and 'inline' are allowed. Default to
2051 * 'attachment'.
2052 */
2053 void
2054 set_disposition (CT ct) {
2055 if (ct->c_dispo_type == NULL) {
2056 char *cp = context_find_by_type ("disposition", ct->c_ctinfo.ci_type,
2057 ct->c_ctinfo.ci_subtype);
2058
2059 if (cp && strcasecmp (cp, "attachment") &&
2060 strcasecmp (cp, "inline")) {
2061 inform("configuration problem: %s-disposition-%s%s%s specifies "
2062 "'%s' but only 'attachment' and 'inline' are allowed, "
2063 "continuing...", invo_name,
2064 ct->c_ctinfo.ci_type,
2065 ct->c_ctinfo.ci_subtype ? "/" : "",
2066 FENDNULL(ct->c_ctinfo.ci_subtype),
2067 cp);
2068 }
2069
2070 if (!cp)
2071 cp = "attachment";
2072 ct->c_dispo_type = mh_xstrdup(cp);
2073 }
2074 }
2075
2076 /*
2077 * Set text content charset if it was unspecified. contains8bit
2078 * selections:
2079 * 0: content does not contain 8-bit characters
2080 * 1: content contains 8-bit characters
2081 * -1: ignore content and use user's locale to determine charset
2082 */
2083 void
2084 set_charset (CT ct, int contains8bit) {
2085 if (ct->c_type == CT_TEXT) {
2086 struct text *t;
2087
2088 if (ct->c_ctparams == NULL) {
2089 NEW0(t);
2090 ct->c_ctparams = t;
2091 t->tx_charset = CHARSET_UNSPECIFIED;
2092 } else {
2093 t = (struct text *) ct->c_ctparams;
2094 }
2095
2096 if (t->tx_charset == CHARSET_UNSPECIFIED) {
2097 CI ci = &ct->c_ctinfo;
2098 char *eightbitcharset = write_charset_8bit();
2099 char *charset = contains8bit ? eightbitcharset : "us-ascii";
2100
2101 if (contains8bit == 1 &&
2102 strcasecmp (eightbitcharset, "US-ASCII") == 0) {
2103 adios (NULL, "Text content contains 8 bit characters, but "
2104 "character set is US-ASCII");
2105 }
2106
2107 add_param (&ci->ci_first_pm, &ci->ci_last_pm, "charset", charset,
2108 0);
2109
2110 t->tx_charset = CHARSET_SPECIFIED;
2111 }
2112 }
2113 }
2114
2115
2116 /*
2117 * Look at all of the replied-to message parts and expand any that
2118 * are matched by a pseudoheader. Except don't descend into
2119 * message parts.
2120 */
2121 void
2122 expand_pseudoheaders (CT ct, struct multipart *m, const char *infile,
2123 const convert_list *convert_head) {
2124 /* text_plain_ct is used to concatenate all of the text/plain
2125 replies into one part, instead of having each one in a separate
2126 part. */
2127 CT text_plain_ct = NULL;
2128
2129 switch (ct->c_type) {
2130 case CT_MULTIPART: {
2131 struct multipart *mp = (struct multipart *) ct->c_ctparams;
2132 struct part *part;
2133
2134 if (ct->c_subtype == MULTI_ALTERNATE) {
2135 int matched = 0;
2136
2137 /* The parts are in descending priority order (defined by
2138 RFC 2046 Sec. 5.1.4) because they were reversed by
2139 parse_mime (). So, stop looking for matches with
2140 immediate subparts after the first match of an
2141 alternative. */
2142 for (part = mp->mp_parts; ! matched && part; part = part->mp_next) {
2143 char *type_subtype =
2144 concat (part->mp_part->c_ctinfo.ci_type, "/",
2145 part->mp_part->c_ctinfo.ci_subtype, NULL);
2146
2147 if (part->mp_part->c_type == CT_MULTIPART) {
2148 expand_pseudoheaders (part->mp_part, m, infile,
2149 convert_head);
2150 } else {
2151 const convert_list *c;
2152
2153 for (c = convert_head; c; c = c->next) {
2154 if (! strcasecmp (type_subtype, c->type)) {
2155 expand_pseudoheader (part->mp_part, &text_plain_ct,
2156 m, infile,
2157 c->type, c->argstring);
2158 matched = 1;
2159 break;
2160 }
2161 }
2162 }
2163 free (type_subtype);
2164 }
2165 } else {
2166 for (part = mp->mp_parts; part; part = part->mp_next) {
2167 expand_pseudoheaders (part->mp_part, m, infile, convert_head);
2168 }
2169 }
2170 break;
2171 }
2172
2173 default: {
2174 char *type_subtype =
2175 concat (ct->c_ctinfo.ci_type, "/", ct->c_ctinfo.ci_subtype,
2176 NULL);
2177 const convert_list *c;
2178
2179 for (c = convert_head; c; c = c->next) {
2180 if (! strcasecmp (type_subtype, c->type)) {
2181 expand_pseudoheader (ct, &text_plain_ct, m, infile, c->type,
2182 c->argstring);
2183 break;
2184 }
2185 }
2186 free (type_subtype);
2187 break;
2188 }
2189 }
2190 }
2191
2192
2193 /*
2194 * Expand a single pseudoheader. It's for the specified type.
2195 */
2196 void
2197 expand_pseudoheader (CT ct, CT *text_plain_ct, struct multipart *m,
2198 const char *infile, const char *type,
2199 const char *argstring) {
2200 char *reply_file;
2201 FILE *reply_fp = NULL;
2202 char *convert, *type_p, *subtype_p;
2203 char *convert_command;
2204 char *charset = NULL;
2205 char *cp;
2206 struct str2init *s2i;
2207 CT reply_ct;
2208 struct part *part;
2209 int status;
2210
2211 type_p = getcpy (type);
2212 if ((subtype_p = strchr (type_p, '/'))) {
2213 *subtype_p++ = '\0';
2214 convert = context_find_by_type ("convert", type_p, subtype_p);
2215 } else {
2216 free (type_p);
2217 type_p = concat ("mhbuild-convert-", type, NULL);
2218 convert = context_find (type_p);
2219 }
2220 free (type_p);
2221
2222 if (! (convert)) {
2223 /* No mhbuild-convert- entry in mhn.defaults or profile for type. */
2224 return;
2225 }
2226 /* reply_file is used to pass the output of the convert. */
2227 reply_file = getcpy (m_mktemp2 (NULL, invo_name, NULL, NULL));
2228 convert_command =
2229 concat (convert, " ", FENDNULL(argstring), " >", reply_file, NULL);
2230
2231 /* Convert here . . . */
2232 ct->c_storeproc = mh_xstrdup(convert_command);
2233 ct->c_umask = ~m_gmprot ();
2234
2235 if ((status = show_content_aux (ct, 0, convert_command, NULL, NULL)) !=
2236 OK) {
2237 inform("store of %s content failed, continuing...", type);
2238 }
2239 free (convert_command);
2240
2241 /* Fill out the the new ct, reply_ct. */
2242 NEW0(reply_ct);
2243 init_decoded_content (reply_ct, infile);
2244
2245 if (extract_headers (reply_ct, reply_file, &reply_fp) == NOTOK) {
2246 free (reply_file);
2247 inform("failed to extract headers from convert output in %s, "
2248 "continuing...", reply_file);
2249 return;
2250 }
2251
2252 /* This sets reply_ct->c_ctparams, and reply_ct->c_termproc if the
2253 charset can't be handled natively. */
2254 for (s2i = str2cts; s2i->si_key; s2i++) {
2255 if (strcasecmp(reply_ct->c_ctinfo.ci_type, s2i->si_key) == 0) {
2256 break;
2257 }
2258 }
2259
2260 if ((reply_ct->c_ctinitfnx = s2i->si_init)) {
2261 (*reply_ct->c_ctinitfnx)(reply_ct);
2262 }
2263
2264 if ((cp = get_param (reply_ct->c_ctinfo.ci_first_pm, "charset", '?', 1))) {
2265 /* The reply Content-Type had the charset. */
2266 charset = cp;
2267 } else {
2268 set_charset (reply_ct, -1);
2269 charset = get_param (reply_ct->c_ctinfo.ci_first_pm, "charset", '?', 1);
2270 }
2271
2272 /* Concatenate text/plain parts. */
2273 if (reply_ct->c_type == CT_TEXT && reply_ct->c_subtype == TEXT_PLAIN) {
2274 if (! *text_plain_ct && m->mp_parts && m->mp_parts->mp_part &&
2275 m->mp_parts->mp_part->c_type == CT_TEXT &&
2276 m->mp_parts->mp_part->c_subtype == TEXT_PLAIN) {
2277 *text_plain_ct = m->mp_parts->mp_part;
2278 /* Make sure that the charset is set in the text/plain part. */
2279 set_charset (*text_plain_ct, -1);
2280 }
2281
2282 if (*text_plain_ct) {
2283 /* Only concatenate if the charsets are identical. */
2284 char *text_plain_ct_charset =
2285 get_param ((*text_plain_ct)->c_ctinfo.ci_first_pm, "charset",
2286 '?', 1);
2287
2288 if (strcasecmp (text_plain_ct_charset, charset) == 0) {
2289 /* Append this text/plain reply to the first one.
2290 If there's a problem anywhere along the way,
2291 instead attach it is a separate part. */
2292 int text_plain_reply =
2293 open ((*text_plain_ct)->c_cefile.ce_file,
2294 O_WRONLY | O_APPEND);
2295 int addl_reply = open (reply_file, O_RDONLY);
2296
2297 if (text_plain_reply != NOTOK && addl_reply != NOTOK) {
2298 /* Insert blank line before each addl part. */
2299 /* It would be nice not to do this for the first one. */
2300 if (write (text_plain_reply, "\n", 1) == 1) {
2301 /* Copy the text from the new reply and
2302 then free its Content struct. */
2303 cpydata (addl_reply, text_plain_reply,
2304 (*text_plain_ct)->c_cefile.ce_file,
2305 reply_file);
2306 if (close (text_plain_reply) == OK &&
2307 close (addl_reply) == OK) {
2308 /* If appended text needed 8-bit but first text didn't,
2309 propagate the 8-bit indication. */
2310 if ((*text_plain_ct)->c_reqencoding == CE_7BIT &&
2311 reply_ct->c_reqencoding == CE_8BIT) {
2312 (*text_plain_ct)->c_reqencoding = CE_8BIT;
2313 }
2314
2315 if (reply_fp) { fclose (reply_fp); }
2316 free (reply_file);
2317 free_content (reply_ct);
2318 return;
2319 }
2320 }
2321 }
2322 }
2323 } else {
2324 *text_plain_ct = reply_ct;
2325 }
2326 }
2327
2328 reply_ct->c_cefile.ce_file = reply_file;
2329 reply_ct->c_cefile.ce_fp = reply_fp;
2330 reply_ct->c_cefile.ce_unlink = 1;
2331
2332 /* Attach the new part to the parent multipart/mixed, "m". */
2333 NEW0(part);
2334 part->mp_part = reply_ct;
2335 if (m->mp_parts) {
2336 struct part *p;
2337
2338 for (p = m->mp_parts; p && p->mp_next; p = p->mp_next) { continue; }
2339 p->mp_next = part;
2340 } else {
2341 m->mp_parts = part;
2342 }
2343 }
2344
2345
2346 /* Extract any Content-Type header from beginning of convert output. */
2347 int
2348 extract_headers (CT ct, char *reply_file, FILE **reply_fp) {
2349 char *buffer = NULL, *cp, *end_of_header;
2350 int found_header = 0;
2351 struct stat statbuf;
2352
2353 /* Read the convert reply from the file to memory. */
2354 if (stat (reply_file, &statbuf) == NOTOK) {
2355 admonish (reply_file, "failed to stat");
2356 goto failed_to_extract_ct;
2357 }
2358
2359 buffer = mh_xmalloc (statbuf.st_size + 1);
2360
2361 if ((*reply_fp = fopen (reply_file, "r+")) == NULL ||
2362 fread (buffer, 1, (size_t) statbuf.st_size, *reply_fp) <
2363 (size_t) statbuf.st_size) {
2364 admonish (reply_file, "failed to read");
2365 goto failed_to_extract_ct;
2366 }
2367 buffer[statbuf.st_size] = '\0';
2368
2369 /* Look for a header in the convert reply. */
2370 if (strncasecmp (buffer, TYPE_FIELD, strlen (TYPE_FIELD)) == 0 &&
2371 buffer[strlen (TYPE_FIELD)] == ':') {
2372 if ((end_of_header = strstr (buffer, "\r\n\r\n"))) {
2373 end_of_header += 2;
2374 found_header = 1;
2375 } else if ((end_of_header = strstr (buffer, "\n\n"))) {
2376 ++end_of_header;
2377 found_header = 1;
2378 }
2379 }
2380
2381 if (found_header) {
2382 CT tmp_ct;
2383 char *tmp_file;
2384 FILE *tmp_f;
2385 size_t n;
2386
2387 /* Truncate buffer to just the C-T. */
2388 *end_of_header = '\0';
2389 n = strlen (buffer);
2390
2391 if (get_ctinfo (buffer + 14, ct, 0) != OK) {
2392 inform("unable to get content info for reply, continuing...");
2393 goto failed_to_extract_ct;
2394 }
2395
2396 /* Hack. Use parse_mime() to detect the type/subtype of the
2397 reply, which we'll use below. */
2398 tmp_file = getcpy (m_mktemp2 (NULL, invo_name, NULL, NULL));
2399 if ((tmp_f = fopen (tmp_file, "w")) &&
2400 fwrite (buffer, 1, n, tmp_f) == n) {
2401 fclose (tmp_f);
2402 } else {
2403 goto failed_to_extract_ct;
2404 }
2405 tmp_ct = parse_mime (tmp_file);
2406
2407 if (tmp_ct) {
2408 /* The type and subtype were detected from the reply
2409 using parse_mime() above. */
2410 ct->c_type = tmp_ct->c_type;
2411 ct->c_subtype = tmp_ct->c_subtype;
2412 free_content (tmp_ct);
2413 }
2414
2415 free (tmp_file);
2416
2417 /* Rewrite the content without the header. */
2418 cp = end_of_header + 1;
2419 rewind (*reply_fp);
2420
2421 if (fwrite (cp, 1, statbuf.st_size - (cp - buffer), *reply_fp) <
2422 (size_t) (statbuf.st_size - (cp - buffer))) {
2423 admonish (reply_file, "failed to write");
2424 goto failed_to_extract_ct;
2425 }
2426
2427 if (ftruncate (fileno (*reply_fp), statbuf.st_size - (cp - buffer)) !=
2428 0) {
2429 advise (reply_file, "ftruncate");
2430 goto failed_to_extract_ct;
2431 }
2432 } else {
2433 /* No header section, assume the reply is text/plain. */
2434 ct->c_type = CT_TEXT;
2435 ct->c_subtype = TEXT_PLAIN;
2436 if (get_ctinfo ("text/plain", ct, 0) == NOTOK) {
2437 /* This never should fail, but just in case. */
2438 adios (NULL, "unable to get content info for reply");
2439 }
2440 }
2441
2442 /* free_encoding() will close reply_fp, which is passed through
2443 ct->c_cefile.ce_fp. */
2444 free (buffer);
2445 return OK;
2446
2447 failed_to_extract_ct:
2448 if (*reply_fp) { fclose (*reply_fp); }
2449 free (buffer);
2450 return NOTOK;
2451 }