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