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