]> diplodocus.org Git - nmh/blob - uip/mhbuildsbr.c
Don't `else' after return. Simplify control flow.
[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 = mh_xstrdup(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 = mh_xstrdup(filename);
281 }
282 } else {
283 NEW0(convert);
284 convert->filename = mh_xstrdup(filename);
285 convert->type = mh_xstrdup(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 = mh_xstrdup(argstring);
321 }
322 } else {
323 NEW0(convert);
324 convert->type = mh_xstrdup(type);
325 convert->argstring = mh_xstrdup(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 * If using EAI, force 8-bit charset.
565 */
566 if (header_encoding == CE_8BIT) {
567 set_charset (ct, 1);
568 }
569
570 /*
571 * Scan the contents. Choose a transfer encoding, and
572 * check if prefix for multipart boundary clashes with
573 * any of the contents.
574 */
575 while (scan_content (ct, maxunencoded) == NOTOK) {
576 if (*cp < 'z') {
577 (*cp)++;
578 } else {
579 if (*++cp == 0)
580 adios (NULL, "giving up trying to find a unique delimiter string");
581 else
582 (*cp)++;
583 }
584 }
585
586 /* Build the rest of the header field structures */
587 if (! dist)
588 build_headers (ct, header_encoding);
589
590 return ct;
591 }
592
593
594 /*
595 * Set up structures for placing unencoded
596 * content when building parts.
597 */
598
599 static int
600 init_decoded_content (CT ct, const char *filename)
601 {
602 ct->c_ceopenfnx = open7Bit; /* since unencoded */
603 ct->c_ceclosefnx = close_encoding;
604 ct->c_cesizefnx = NULL; /* since unencoded */
605 ct->c_encoding = CE_7BIT; /* Seems like a reasonable default */
606 ct->c_file = add(filename, NULL);
607
608 return OK;
609 }
610
611
612 static char *
613 fgetstr (char *s, int n, FILE *stream)
614 {
615 char *cp, *ep;
616 int o_n = n;
617
618 while(1) {
619 for (ep = (cp = s) + o_n; cp < ep; ) {
620 int i;
621
622 if (!fgets (cp, n, stream))
623 return (cp != s ? s : NULL);
624
625 if (cp == s && *cp != '#')
626 return s;
627
628 cp += (i = strlen (cp)) - 1;
629 if (i <= 1 || *cp-- != '\n' || *cp != '\\')
630 break;
631 *cp = '\0';
632 n -= (i - 2);
633 }
634
635 if (strcmp(s, "#on\n") == 0) {
636 directive_onoff(1);
637 } else if (strcmp(s, "#off\n") == 0) {
638 directive_onoff(0);
639 } else if (strcmp(s, "#pop\n") == 0) {
640 directive_pop();
641 } else {
642 break;
643 }
644 }
645
646 return s;
647 }
648
649
650 /*
651 * Parse the composition draft for text and directives.
652 * Do initial setup of Content structure.
653 */
654
655 static int
656 user_content (FILE *in, char *buf, CT *ctp, const char *infilename)
657 {
658 int extrnal, vrsn;
659 char *cp, **ap;
660 char buffer[BUFSIZ];
661 struct multipart *m;
662 struct part **pp;
663 struct stat st;
664 struct str2init *s2i;
665 CI ci;
666 CT ct;
667 CE ce;
668
669 if (buf[0] == '\n' || (do_direct() && strcmp (buf, "#\n") == 0)) {
670 *ctp = NULL;
671 return OK;
672 }
673
674 /* allocate basic Content structure */
675 NEW0(ct);
676 *ctp = ct;
677
678 /* allocate basic structure for handling decoded content */
679 init_decoded_content (ct, infilename);
680 ce = &ct->c_cefile;
681
682 ci = &ct->c_ctinfo;
683 set_id (ct, 0);
684
685 /*
686 * Handle inline text. Check if line
687 * is one of the following forms:
688 *
689 * 1) doesn't begin with '#' (implicit directive)
690 * 2) begins with "##" (implicit directive)
691 * 3) begins with "#<"
692 */
693 if (!do_direct() || buf[0] != '#' || buf[1] == '#' || buf[1] == '<') {
694 int headers;
695 int inlineD;
696 long pos;
697 char content[BUFSIZ];
698 FILE *out;
699 char *cp;
700
701 if ((cp = m_mktemp2(NULL, invo_name, NULL, &out)) == NULL) {
702 adios("mhbuildsbr", "unable to create temporary file in %s",
703 get_temp_dir());
704 }
705
706 /* use a temp file to collect the plain text lines */
707 ce->ce_file = add (cp, NULL);
708 ce->ce_unlink = 1;
709
710 if (do_direct() && (buf[0] == '#' && buf[1] == '<')) {
711 strncpy (content, buf + 2, sizeof(content));
712 inlineD = 1;
713 goto rock_and_roll;
714 } else {
715 inlineD = 0;
716 }
717
718 /* the directive is implicit */
719 strncpy (content, "text/plain", sizeof(content));
720 headers = 0;
721 strncpy (buffer, (!do_direct() || buf[0] != '#') ? buf : buf + 1, sizeof(buffer));
722 for (;;) {
723 int i;
724
725 if (headers >= 0 && do_direct() && uprf (buffer, DESCR_FIELD)
726 && buffer[i = strlen (DESCR_FIELD)] == ':') {
727 headers = 1;
728
729 again_descr:
730 ct->c_descr = add (buffer + i + 1, ct->c_descr);
731 if (!fgetstr (buffer, sizeof(buffer) - 1, in))
732 adios (NULL, "end-of-file after %s: field in plaintext", DESCR_FIELD);
733 switch (buffer[0]) {
734 case ' ':
735 case '\t':
736 i = -1;
737 goto again_descr;
738
739 case '#':
740 adios (NULL, "#-directive after %s: field in plaintext", DESCR_FIELD);
741 /* NOTREACHED */
742
743 default:
744 break;
745 }
746 }
747
748 if (headers >= 0 && do_direct() && uprf (buffer, DISPO_FIELD)
749 && buffer[i = strlen (DISPO_FIELD)] == ':') {
750 headers = 1;
751
752 again_dispo:
753 ct->c_dispo = add (buffer + i + 1, ct->c_dispo);
754 if (!fgetstr (buffer, sizeof(buffer) - 1, in))
755 adios (NULL, "end-of-file after %s: field in plaintext", DISPO_FIELD);
756 switch (buffer[0]) {
757 case ' ':
758 case '\t':
759 i = -1;
760 goto again_dispo;
761
762 case '#':
763 adios (NULL, "#-directive after %s: field in plaintext", DISPO_FIELD);
764 /* NOTREACHED */
765
766 default:
767 break;
768 }
769 }
770
771 if (headers != 1 || buffer[0] != '\n')
772 fputs (buffer, out);
773
774 rock_and_roll:
775 headers = -1;
776 pos = ftell (in);
777 if ((cp = fgetstr (buffer, sizeof(buffer) - 1, in)) == NULL)
778 break;
779 if (do_direct() && buffer[0] == '#') {
780 char *bp;
781
782 if (buffer[1] != '#')
783 break;
784 for (cp = (bp = buffer) + 1; *cp; cp++)
785 *bp++ = *cp;
786 *bp = '\0';
787 }
788 }
789
790 if (listsw)
791 ct->c_end = ftell (out);
792 fclose (out);
793
794 /* parse content type */
795 if (get_ctinfo (content, ct, inlineD) == NOTOK)
796 done (1);
797
798 for (s2i = str2cts; s2i->si_key; s2i++)
799 if (!strcasecmp (ci->ci_type, s2i->si_key))
800 break;
801 if (!s2i->si_key && !uprf (ci->ci_type, "X-"))
802 s2i++;
803
804 /*
805 * check type specified (possibly implicitly)
806 */
807 switch (ct->c_type = s2i->si_val) {
808 case CT_MESSAGE:
809 if (!strcasecmp (ci->ci_subtype, "rfc822")) {
810 ct->c_encoding = CE_7BIT;
811 goto call_init;
812 }
813 /* else fall... */
814 case CT_MULTIPART:
815 adios (NULL, "it doesn't make sense to define an in-line %s content",
816 ct->c_type == CT_MESSAGE ? "message" : "multipart");
817 /* NOTREACHED */
818
819 default:
820 call_init:
821 if ((ct->c_ctinitfnx = s2i->si_init))
822 (*ct->c_ctinitfnx) (ct);
823 break;
824 }
825
826 if (cp)
827 fseek (in, pos, SEEK_SET);
828 return OK;
829 }
830
831 /*
832 * If we've reached this point, the next line
833 * must be some type of explicit directive.
834 */
835
836 /* check if directive is external-type */
837 extrnal = (buf[1] == '@');
838
839 /* parse directive */
840 if (get_ctinfo (buf + (extrnal ? 2 : 1), ct, 1) == NOTOK)
841 done (1);
842
843 /* check directive against the list of MIME types */
844 for (s2i = str2cts; s2i->si_key; s2i++)
845 if (!strcasecmp (ci->ci_type, s2i->si_key))
846 break;
847
848 /*
849 * Check if the directive specified a valid type.
850 * This will happen if it was one of the following forms:
851 *
852 * #type/subtype (or)
853 * #@type/subtype
854 */
855 if (s2i->si_key) {
856 if (!ci->ci_subtype)
857 adios (NULL, "missing subtype in \"#%s\"", ci->ci_type);
858
859 switch (ct->c_type = s2i->si_val) {
860 case CT_MULTIPART:
861 adios (NULL, "use \"#begin ... #end\" instead of \"#%s/%s\"",
862 ci->ci_type, ci->ci_subtype);
863 /* NOTREACHED */
864
865 case CT_MESSAGE:
866 if (!strcasecmp (ci->ci_subtype, "partial"))
867 adios (NULL, "sorry, \"#%s/%s\" isn't supported",
868 ci->ci_type, ci->ci_subtype);
869 if (!strcasecmp (ci->ci_subtype, "external-body"))
870 adios (NULL, "use \"#@type/subtype ... [] ...\" instead of \"#%s/%s\"",
871 ci->ci_type, ci->ci_subtype);
872 use_forw:
873 adios (NULL,
874 "use \"#forw [+folder] [msgs]\" instead of \"#%s/%s\"",
875 ci->ci_type, ci->ci_subtype);
876 /* NOTREACHED */
877
878 default:
879 if ((ct->c_ctinitfnx = s2i->si_init))
880 (*ct->c_ctinitfnx) (ct);
881 break;
882 }
883
884 /*
885 * #@type/subtype (external types directive)
886 */
887 if (extrnal) {
888 struct exbody *e;
889 CT p;
890
891 if (!ci->ci_magic)
892 adios (NULL, "need external information for \"#@%s/%s\"",
893 ci->ci_type, ci->ci_subtype);
894 p = ct;
895
896 snprintf (buffer, sizeof(buffer), "message/external-body; %s", ci->ci_magic);
897 free (ci->ci_magic);
898 ci->ci_magic = NULL;
899
900 /*
901 * Since we are using the current Content structure to
902 * hold information about the type of the external
903 * reference, we need to create another Content structure
904 * for the message/external-body to wrap it in.
905 */
906 NEW0(ct);
907 init_decoded_content(ct, infilename);
908 *ctp = ct;
909 if (get_ctinfo (buffer, ct, 0) == NOTOK)
910 done (1);
911 ct->c_type = CT_MESSAGE;
912 ct->c_subtype = MESSAGE_EXTERNAL;
913
914 NEW0(e);
915 ct->c_ctparams = (void *) e;
916
917 e->eb_parent = ct;
918 e->eb_content = p;
919 p->c_ctexbody = e;
920
921 if (params_external (ct, 1) == NOTOK)
922 done (1);
923
924 return OK;
925 }
926
927 /* Handle [file] argument */
928 if (ci->ci_magic) {
929 /* check if specifies command to execute */
930 if (*ci->ci_magic == '|' || *ci->ci_magic == '!') {
931 for (cp = ci->ci_magic + 1; isspace ((unsigned char) *cp); cp++)
932 continue;
933 if (!*cp)
934 adios (NULL, "empty pipe command for #%s directive", ci->ci_type);
935 cp = add (cp, NULL);
936 free (ci->ci_magic);
937 ci->ci_magic = cp;
938 } else {
939 /* record filename of decoded contents */
940 ce->ce_file = ci->ci_magic;
941 if (access (ce->ce_file, R_OK) == NOTOK)
942 adios ("reading", "unable to access %s for", ce->ce_file);
943 if (listsw && stat (ce->ce_file, &st) != NOTOK)
944 ct->c_end = (long) st.st_size;
945 ci->ci_magic = NULL;
946 }
947 return OK;
948 }
949
950 /*
951 * No [file] argument, so check profile for
952 * method to compose content.
953 */
954 cp = context_find_by_type ("compose", ci->ci_type, ci->ci_subtype);
955 if (cp == NULL) {
956 content_error (NULL, ct, "don't know how to compose content");
957 done (1);
958 }
959 ci->ci_magic = add (cp, NULL);
960 return OK;
961 }
962
963 if (extrnal)
964 adios (NULL, "external definition not allowed for \"#%s\"", ci->ci_type);
965
966 /*
967 * Message directive
968 * #forw [+folder] [msgs]
969 */
970 if (!strcasecmp (ci->ci_type, "forw")) {
971 int msgnum;
972 char *folder, *arguments[MAXARGS];
973 struct msgs *mp;
974
975 if (ci->ci_magic) {
976 ap = brkstring (ci->ci_magic, " ", "\n");
977 copyip (ap, arguments, MAXARGS);
978 } else {
979 arguments[0] = "cur";
980 arguments[1] = NULL;
981 }
982 folder = NULL;
983
984 /* search the arguments for a folder name */
985 for (ap = arguments; *ap; ap++) {
986 cp = *ap;
987 if (*cp == '+' || *cp == '@') {
988 if (folder)
989 adios (NULL, "only one folder per #forw directive");
990 else
991 folder = pluspath (cp);
992 }
993 }
994
995 /* else, use the current folder */
996 if (!folder)
997 folder = add (getfolder (1), NULL);
998
999 if (!(mp = folder_read (folder, 0)))
1000 adios (NULL, "unable to read folder %s", folder);
1001 for (ap = arguments; *ap; ap++) {
1002 cp = *ap;
1003 if (*cp != '+' && *cp != '@')
1004 if (!m_convert (mp, cp))
1005 done (1);
1006 }
1007 free (folder);
1008 free_ctinfo (ct);
1009
1010 /*
1011 * If there is more than one message to include, make this
1012 * a content of type "multipart/digest" and insert each message
1013 * as a subpart. If there is only one message, then make this
1014 * a content of type "message/rfc822".
1015 */
1016 if (mp->numsel > 1) {
1017 /* we are forwarding multiple messages */
1018 if (get_ctinfo ("multipart/digest", ct, 0) == NOTOK)
1019 done (1);
1020 ct->c_type = CT_MULTIPART;
1021 ct->c_subtype = MULTI_DIGEST;
1022
1023 NEW0(m);
1024 ct->c_ctparams = (void *) m;
1025 pp = &m->mp_parts;
1026
1027 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1028 if (is_selected(mp, msgnum)) {
1029 struct part *part;
1030 CT p;
1031 CE pe;
1032
1033 NEW0(p);
1034 init_decoded_content (p, infilename);
1035 pe = &p->c_cefile;
1036 if (get_ctinfo ("message/rfc822", p, 0) == NOTOK)
1037 done (1);
1038 p->c_type = CT_MESSAGE;
1039 p->c_subtype = MESSAGE_RFC822;
1040
1041 snprintf (buffer, sizeof(buffer), "%s/%d", mp->foldpath, msgnum);
1042 pe->ce_file = add (buffer, NULL);
1043 if (listsw && stat (pe->ce_file, &st) != NOTOK)
1044 p->c_end = (long) st.st_size;
1045
1046 NEW0(part);
1047 *pp = part;
1048 pp = &part->mp_next;
1049 part->mp_part = p;
1050 }
1051 }
1052 } else {
1053 /* we are forwarding one message */
1054 if (get_ctinfo ("message/rfc822", ct, 0) == NOTOK)
1055 done (1);
1056 ct->c_type = CT_MESSAGE;
1057 ct->c_subtype = MESSAGE_RFC822;
1058
1059 msgnum = mp->lowsel;
1060 snprintf (buffer, sizeof(buffer), "%s/%d", mp->foldpath, msgnum);
1061 ce->ce_file = add (buffer, NULL);
1062 if (listsw && stat (ce->ce_file, &st) != NOTOK)
1063 ct->c_end = (long) st.st_size;
1064 }
1065
1066 folder_free (mp); /* free folder/message structure */
1067 return OK;
1068 }
1069
1070 /*
1071 * #end
1072 */
1073 if (!strcasecmp (ci->ci_type, "end")) {
1074 free_content (ct);
1075 *ctp = NULL;
1076 return DONE;
1077 }
1078
1079 /*
1080 * #begin [ alternative | parallel ]
1081 */
1082 if (!strcasecmp (ci->ci_type, "begin")) {
1083 if (!ci->ci_magic) {
1084 vrsn = MULTI_MIXED;
1085 cp = SubMultiPart[vrsn - 1].kv_key;
1086 } else if (!strcasecmp (ci->ci_magic, "alternative")) {
1087 vrsn = MULTI_ALTERNATE;
1088 cp = SubMultiPart[vrsn - 1].kv_key;
1089 } else if (!strcasecmp (ci->ci_magic, "parallel")) {
1090 vrsn = MULTI_PARALLEL;
1091 cp = SubMultiPart[vrsn - 1].kv_key;
1092 } else if (uprf (ci->ci_magic, "digest")) {
1093 goto use_forw;
1094 } else {
1095 vrsn = MULTI_UNKNOWN;
1096 cp = ci->ci_magic;
1097 }
1098
1099 free_ctinfo (ct);
1100 snprintf (buffer, sizeof(buffer), "multipart/%s", cp);
1101 if (get_ctinfo (buffer, ct, 0) == NOTOK)
1102 done (1);
1103 ct->c_type = CT_MULTIPART;
1104 ct->c_subtype = vrsn;
1105
1106 NEW0(m);
1107 ct->c_ctparams = (void *) m;
1108
1109 pp = &m->mp_parts;
1110 while (fgetstr (buffer, sizeof(buffer) - 1, in)) {
1111 struct part *part;
1112 CT p;
1113
1114 if (user_content (in, buffer, &p, infilename) == DONE) {
1115 if (!m->mp_parts)
1116 adios (NULL, "empty \"#begin ... #end\" sequence");
1117 return OK;
1118 }
1119 if (!p)
1120 continue;
1121
1122 NEW0(part);
1123 *pp = part;
1124 pp = &part->mp_next;
1125 part->mp_part = p;
1126 }
1127 admonish (NULL, "premature end-of-file, missing #end");
1128 return OK;
1129 }
1130
1131 /*
1132 * Unknown directive
1133 */
1134 adios (NULL, "unknown directive \"#%s\"", ci->ci_type);
1135 return NOTOK; /* NOT REACHED */
1136 }
1137
1138
1139 static void
1140 set_id (CT ct, int top)
1141 {
1142 char contentid[BUFSIZ];
1143 static int partno;
1144 static time_t clock = 0;
1145 static char *msgfmt;
1146
1147 if (clock == 0) {
1148 time (&clock);
1149 snprintf (contentid, sizeof(contentid), "%s\n", message_id (clock, 1));
1150 partno = 0;
1151 msgfmt = mh_xstrdup(contentid);
1152 }
1153 snprintf (contentid, sizeof(contentid), msgfmt, top ? 0 : ++partno);
1154 ct->c_id = mh_xstrdup(contentid);
1155 }
1156
1157
1158 /*
1159 * Fill out, or expand the various contents in the composition
1160 * draft. Read-in any necessary files. Parse and execute any
1161 * commands specified by profile composition strings.
1162 */
1163
1164 static int
1165 compose_content (CT ct, int verbose)
1166 {
1167 CE ce = &ct->c_cefile;
1168
1169 switch (ct->c_type) {
1170 case CT_MULTIPART:
1171 {
1172 int partnum;
1173 char *pp;
1174 char partnam[BUFSIZ];
1175 struct multipart *m = (struct multipart *) ct->c_ctparams;
1176 struct part *part;
1177
1178 if (ct->c_partno) {
1179 snprintf (partnam, sizeof(partnam), "%s.", ct->c_partno);
1180 pp = partnam + strlen (partnam);
1181 } else {
1182 pp = partnam;
1183 }
1184
1185 /* first, we call compose_content on all the subparts */
1186 for (part = m->mp_parts, partnum = 1; part; part = part->mp_next, partnum++) {
1187 CT p = part->mp_part;
1188
1189 sprintf (pp, "%d", partnum);
1190 p->c_partno = add (partnam, NULL);
1191 if (compose_content (p, verbose) == NOTOK)
1192 return NOTOK;
1193 }
1194
1195 /*
1196 * If the -rfc934mode switch is given, then check all
1197 * the subparts of a multipart/digest. If they are all
1198 * message/rfc822, then mark this content and all
1199 * subparts with the rfc934 compatibility mode flag.
1200 */
1201 if (rfc934sw && ct->c_subtype == MULTI_DIGEST) {
1202 int is934 = 1;
1203
1204 for (part = m->mp_parts; part; part = part->mp_next) {
1205 CT p = part->mp_part;
1206
1207 if (p->c_subtype != MESSAGE_RFC822) {
1208 is934 = 0;
1209 break;
1210 }
1211 }
1212 ct->c_rfc934 = is934;
1213 for (part = m->mp_parts; part; part = part->mp_next) {
1214 CT p = part->mp_part;
1215
1216 if ((p->c_rfc934 = is934))
1217 p->c_end++;
1218 }
1219 }
1220
1221 if (listsw) {
1222 ct->c_end = (partnum = strlen (prefix) + 2) + 2;
1223 if (ct->c_rfc934)
1224 ct->c_end += 1;
1225
1226 for (part = m->mp_parts; part; part = part->mp_next)
1227 ct->c_end += part->mp_part->c_end + partnum;
1228 }
1229 }
1230 break;
1231
1232 case CT_MESSAGE:
1233 /* Nothing to do for type message */
1234 break;
1235
1236 /*
1237 * Discrete types (text/application/audio/image/video)
1238 */
1239 default:
1240 if (!ce->ce_file) {
1241 pid_t child_id;
1242 int i, xstdout, len, buflen;
1243 char *bp, *cp;
1244 char *vec[4], buffer[BUFSIZ];
1245 FILE *out;
1246 CI ci = &ct->c_ctinfo;
1247 char *tfile = NULL;
1248
1249 if (!(cp = ci->ci_magic))
1250 adios (NULL, "internal error(5)");
1251
1252 if ((tfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
1253 adios("mhbuildsbr", "unable to create temporary file in %s",
1254 get_temp_dir());
1255 }
1256 ce->ce_file = add (tfile, NULL);
1257 ce->ce_unlink = 1;
1258
1259 xstdout = 0;
1260
1261 /* Get buffer ready to go */
1262 bp = buffer;
1263 bp[0] = '\0';
1264 buflen = sizeof(buffer);
1265
1266 /*
1267 * Parse composition string into buffer
1268 */
1269 for ( ; *cp; cp++) {
1270 if (*cp == '%') {
1271 switch (*++cp) {
1272 case 'a':
1273 {
1274 /* insert parameters from directive */
1275 char *s = "";
1276 PM pm;
1277
1278 for (pm = ci->ci_first_pm; pm; pm = pm->pm_next) {
1279 snprintf (bp, buflen, "%s%s=\"%s\"", s,
1280 pm->pm_name, get_param_value(pm, '?'));
1281 len = strlen (bp);
1282 bp += len;
1283 buflen -= len;
1284 s = " ";
1285 }
1286 }
1287 break;
1288
1289 case 'F':
1290 /* %f, and stdout is not-redirected */
1291 xstdout = 1;
1292 /* and fall... */
1293
1294 case 'f':
1295 /*
1296 * insert temporary filename where
1297 * content should be written
1298 */
1299 snprintf (bp, buflen, "%s", ce->ce_file);
1300 break;
1301
1302 case 's':
1303 /* insert content subtype */
1304 strncpy (bp, ci->ci_subtype, buflen);
1305 break;
1306
1307 case '%':
1308 /* insert character % */
1309 goto raw;
1310
1311 default:
1312 *bp++ = *--cp;
1313 *bp = '\0';
1314 buflen--;
1315 continue;
1316 }
1317 len = strlen (bp);
1318 bp += len;
1319 buflen -= len;
1320 } else {
1321 raw:
1322 *bp++ = *cp;
1323 *bp = '\0';
1324 buflen--;
1325 }
1326 }
1327
1328 if (verbose)
1329 printf ("composing content %s/%s from command\n\t%s\n",
1330 ci->ci_type, ci->ci_subtype, buffer);
1331
1332 fflush (stdout); /* not sure if need for -noverbose */
1333
1334 vec[0] = "/bin/sh";
1335 vec[1] = "-c";
1336 vec[2] = buffer;
1337 vec[3] = NULL;
1338
1339 if ((out = fopen (ce->ce_file, "w")) == NULL)
1340 adios (ce->ce_file, "unable to open for writing");
1341
1342 for (i = 0; (child_id = fork()) == NOTOK && i > 5; i++)
1343 sleep (5);
1344 switch (child_id) {
1345 case NOTOK:
1346 adios ("fork", "unable to fork");
1347 /* NOTREACHED */
1348
1349 case OK:
1350 if (!xstdout)
1351 dup2 (fileno (out), 1);
1352 close (fileno (out));
1353 execvp ("/bin/sh", vec);
1354 fprintf (stderr, "unable to exec ");
1355 perror ("/bin/sh");
1356 _exit (-1);
1357 /* NOTREACHED */
1358
1359 default:
1360 fclose (out);
1361 if (pidXwait(child_id, NULL))
1362 done (1);
1363 break;
1364 }
1365 }
1366
1367 /* Check size of file */
1368 if (listsw && ct->c_end == 0L) {
1369 struct stat st;
1370
1371 if (stat (ce->ce_file, &st) != NOTOK)
1372 ct->c_end = (long) st.st_size;
1373 }
1374 break;
1375 }
1376
1377 return OK;
1378 }
1379
1380
1381 /*
1382 * Scan the content.
1383 *
1384 * 1) choose a transfer encoding.
1385 * 2) check for clashes with multipart boundary string.
1386 * 3) for text content, figure out which character set is being used.
1387 *
1388 * If there is a clash with one of the contents and the multipart boundary,
1389 * this function will exit with NOTOK. This will cause the scanning process
1390 * to be repeated with a different multipart boundary. It is possible
1391 * (although highly unlikely) that this scan will be repeated multiple times.
1392 */
1393
1394 static int
1395 scan_content (CT ct, size_t maxunencoded)
1396 {
1397 int prefix_len;
1398 int check8bit = 0, contains8bit = 0; /* check if contains 8bit data */
1399 int checknul = 0, containsnul = 0; /* check if contains NULs */
1400 int checklinelen = 0, linelen = 0; /* check for long lines */
1401 int checkllinelen = 0; /* check for extra-long lines */
1402 int checkboundary = 0, boundaryclash = 0; /* check if clashes with multipart boundary */
1403 int checklinespace = 0, linespace = 0; /* check if any line ends with space */
1404 char *cp = NULL;
1405 char *bufp = NULL;
1406 size_t buflen;
1407 ssize_t gotlen;
1408 struct text *t = NULL;
1409 FILE *in = NULL;
1410 CE ce = &ct->c_cefile;
1411
1412 /*
1413 * handle multipart by scanning all subparts
1414 * and then checking their encoding.
1415 */
1416 if (ct->c_type == CT_MULTIPART) {
1417 struct multipart *m = (struct multipart *) ct->c_ctparams;
1418 struct part *part;
1419
1420 /* initially mark the domain of enclosing multipart as 7bit */
1421 ct->c_encoding = CE_7BIT;
1422
1423 for (part = m->mp_parts; part; part = part->mp_next) {
1424 CT p = part->mp_part;
1425
1426 if (scan_content (p, maxunencoded) == NOTOK) /* choose encoding for subpart */
1427 return NOTOK;
1428
1429 /* if necessary, enlarge encoding for enclosing multipart */
1430 if (p->c_encoding == CE_BINARY)
1431 ct->c_encoding = CE_BINARY;
1432 if (p->c_encoding == CE_8BIT && ct->c_encoding != CE_BINARY)
1433 ct->c_encoding = CE_8BIT;
1434 }
1435
1436 return OK;
1437 }
1438
1439 /*
1440 * Decide what to check while scanning this content. Note that
1441 * for text content we always check for 8bit characters if the
1442 * charset is unspecified, because that controls whether or not the
1443 * character set is us-ascii or retrieved from the locale. And
1444 * we check even if the charset is specified, to allow setting
1445 * the proper Content-Transfer-Encoding.
1446 */
1447
1448 if (ct->c_type == CT_TEXT) {
1449 t = (struct text *) ct->c_ctparams;
1450 if (t->tx_charset == CHARSET_UNSPECIFIED) {
1451 checknul = 1;
1452 }
1453 check8bit = 1;
1454 }
1455
1456 switch (ct->c_reqencoding) {
1457 case CE_8BIT:
1458 checkllinelen = 1;
1459 checkboundary = 1;
1460 break;
1461 case CE_QUOTED:
1462 checkboundary = 1;
1463 break;
1464 case CE_BASE64:
1465 break;
1466 case CE_UNKNOWN:
1467 /* Use the default rules based on content-type */
1468 switch (ct->c_type) {
1469 case CT_TEXT:
1470 checkboundary = 1;
1471 checklinelen = 1;
1472 if (ct->c_subtype == TEXT_PLAIN) {
1473 checklinespace = 0;
1474 } else {
1475 checklinespace = 1;
1476 }
1477 break;
1478
1479 case CT_APPLICATION:
1480 check8bit = 1;
1481 checknul = 1;
1482 checklinelen = 1;
1483 checklinespace = 1;
1484 checkboundary = 1;
1485 break;
1486
1487 case CT_MESSAGE:
1488 checklinelen = 0;
1489 checklinespace = 0;
1490
1491 /* don't check anything for message/external */
1492 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1493 checkboundary = 0;
1494 check8bit = 0;
1495 } else {
1496 checkboundary = 1;
1497 check8bit = 1;
1498 }
1499 break;
1500
1501 case CT_AUDIO:
1502 case CT_IMAGE:
1503 case CT_VIDEO:
1504 /*
1505 * Don't check anything for these types,
1506 * since we are forcing use of base64, unless
1507 * the content-type was specified by a mhbuild directive.
1508 */
1509 check8bit = 0;
1510 checklinelen = 0;
1511 checklinespace = 0;
1512 checkboundary = 0;
1513 break;
1514 }
1515 }
1516
1517 /*
1518 * Scan the unencoded content
1519 */
1520 if (check8bit || checklinelen || checklinespace || checkboundary ||
1521 checkllinelen || checknul) {
1522 if ((in = fopen (ce->ce_file, "r")) == NULL)
1523 adios (ce->ce_file, "unable to open for reading");
1524 prefix_len = strlen (prefix);
1525
1526 while ((gotlen = getline(&bufp, &buflen, in)) != -1) {
1527 /*
1528 * Check for 8bit and NUL data.
1529 */
1530 for (cp = bufp; (check8bit || checknul) &&
1531 cp < bufp + gotlen; cp++) {
1532 if (!isascii ((unsigned char) *cp)) {
1533 contains8bit = 1;
1534 check8bit = 0; /* no need to keep checking */
1535 }
1536 if (!*cp) {
1537 containsnul = 1;
1538 checknul = 0; /* no need to keep checking */
1539 }
1540 }
1541
1542 /*
1543 * Check line length.
1544 */
1545 if (checklinelen && ((size_t)gotlen > maxunencoded + 1)) {
1546 linelen = 1;
1547 checklinelen = 0; /* no need to keep checking */
1548 }
1549
1550 /*
1551 * RFC 5322 specifies that a message cannot contain a line
1552 * greater than 998 characters (excluding the CRLF). If we
1553 * get one of those lines and linelen is NOT set, then abort.
1554 */
1555
1556 if (checkllinelen && !linelen &&
1557 (gotlen > MAXLONGLINE + 1)) {
1558 adios(NULL, "Line in content exceeds maximum line limit (%d)",
1559 MAXLONGLINE);
1560 }
1561
1562 /*
1563 * Check if line ends with a space.
1564 */
1565 if (checklinespace && (cp = bufp + gotlen - 2) > bufp &&
1566 isspace ((unsigned char) *cp)) {
1567 linespace = 1;
1568 checklinespace = 0; /* no need to keep checking */
1569 }
1570
1571 /*
1572 * Check if content contains a line that clashes
1573 * with our standard boundary for multipart messages.
1574 */
1575 if (checkboundary && bufp[0] == '-' && bufp[1] == '-') {
1576 for (cp = bufp + gotlen - 1; cp >= bufp; cp--)
1577 if (!isspace ((unsigned char) *cp))
1578 break;
1579 *++cp = '\0';
1580 if (!strncmp(bufp + 2, prefix, prefix_len) &&
1581 isdigit((unsigned char) bufp[2 + prefix_len])) {
1582 boundaryclash = 1;
1583 checkboundary = 0; /* no need to keep checking */
1584 }
1585 }
1586 }
1587 fclose (in);
1588 free(bufp);
1589 }
1590
1591 /*
1592 * If the content is text and didn't specify a character set,
1593 * we need to figure out which one was used.
1594 */
1595 set_charset (ct, contains8bit);
1596
1597 /*
1598 * Decide which transfer encoding to use.
1599 */
1600
1601 if (ct->c_reqencoding != CE_UNKNOWN)
1602 ct->c_encoding = ct->c_reqencoding;
1603 else {
1604 int wants_q_p = (containsnul || linelen || linespace || checksw);
1605
1606 switch (ct->c_type) {
1607 case CT_TEXT:
1608 if (wants_q_p)
1609 ct->c_encoding = CE_QUOTED;
1610 else if (contains8bit)
1611 ct->c_encoding = CE_8BIT;
1612 else
1613 ct->c_encoding = CE_7BIT;
1614
1615 break;
1616
1617 case CT_APPLICATION:
1618 /* For application type, use base64, except when postscript */
1619 if (wants_q_p || contains8bit) {
1620 if (ct->c_subtype == APPLICATION_POSTSCRIPT)
1621 ct->c_encoding = CE_QUOTED; /* historical */
1622 else
1623 ct->c_encoding = CE_BASE64;
1624 } else {
1625 ct->c_encoding = CE_7BIT;
1626 }
1627 break;
1628
1629 case CT_MESSAGE:
1630 ct->c_encoding = contains8bit ? CE_8BIT : CE_7BIT;
1631 break;
1632
1633 case CT_AUDIO:
1634 case CT_IMAGE:
1635 case CT_VIDEO:
1636 /* For audio, image, and video contents, just use base64 */
1637 ct->c_encoding = CE_BASE64;
1638 break;
1639 }
1640 }
1641
1642 return (boundaryclash ? NOTOK : OK);
1643 }
1644
1645
1646 /*
1647 * Scan the content structures, and build header
1648 * fields that will need to be output into the
1649 * message.
1650 */
1651
1652 static int
1653 build_headers (CT ct, int header_encoding)
1654 {
1655 int cc, mailbody, extbody, len;
1656 char *np, *vp, buffer[BUFSIZ];
1657 CI ci = &ct->c_ctinfo;
1658
1659 /*
1660 * If message is type multipart, then add the multipart
1661 * boundary to the list of attribute/value pairs.
1662 */
1663 if (ct->c_type == CT_MULTIPART) {
1664 static int level = 0; /* store nesting level */
1665
1666 snprintf (buffer, sizeof(buffer), "%s%d", prefix, level++);
1667 add_param(&ci->ci_first_pm, &ci->ci_last_pm, "boundary", buffer, 0);
1668 }
1669
1670 /*
1671 * Skip the output of Content-Type, parameters, content
1672 * description and disposition, and Content-ID if the
1673 * content is of type "message" and the rfc934 compatibility
1674 * flag is set (which means we are inside multipart/digest
1675 * and the switch -rfc934mode was given).
1676 */
1677 if (ct->c_type == CT_MESSAGE && ct->c_rfc934)
1678 goto skip_headers;
1679
1680 /*
1681 * output the content type and subtype
1682 */
1683 np = add (TYPE_FIELD, NULL);
1684 vp = concat (" ", ci->ci_type, "/", ci->ci_subtype, NULL);
1685
1686 /* keep track of length of line */
1687 len = strlen (TYPE_FIELD) + strlen (ci->ci_type)
1688 + strlen (ci->ci_subtype) + 3;
1689
1690 extbody = ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_EXTERNAL;
1691 mailbody = extbody && ((struct exbody *) ct->c_ctparams)->eb_body;
1692
1693 /*
1694 * Append the attribute/value pairs to
1695 * the end of the Content-Type line.
1696 */
1697
1698 if (ci->ci_first_pm) {
1699 char *s = output_params(len, ci->ci_first_pm, &len, mailbody);
1700
1701 if (!s)
1702 adios(NULL, "Internal error: failed outputting Content-Type "
1703 "parameters");
1704
1705 vp = add (s, vp);
1706 free(s);
1707 }
1708
1709 /*
1710 * Append any RFC-822 comment to the end of
1711 * the Content-Type line.
1712 */
1713 if (ci->ci_comment) {
1714 snprintf (buffer, sizeof(buffer), "(%s)", ci->ci_comment);
1715 if (len + 1 + (cc = 2 + strlen (ci->ci_comment)) >= CPERLIN) {
1716 vp = add ("\n\t", vp);
1717 len = 8;
1718 } else {
1719 vp = add (" ", vp);
1720 len++;
1721 }
1722 vp = add (buffer, vp);
1723 len += cc;
1724 }
1725 vp = add ("\n", vp);
1726 add_header (ct, np, vp);
1727
1728 /*
1729 * output the Content-ID, unless disabled by -nocontentid
1730 */
1731 if (contentidsw && ct->c_id) {
1732 np = add (ID_FIELD, NULL);
1733 vp = concat (" ", ct->c_id, NULL);
1734 add_header (ct, np, vp);
1735 }
1736 /*
1737 * output the Content-Description
1738 */
1739 if (ct->c_descr) {
1740 np = add (DESCR_FIELD, NULL);
1741 vp = concat (" ", ct->c_descr, NULL);
1742 if (header_encoding != CE_8BIT) {
1743 if (encode_rfc2047(DESCR_FIELD, &vp, header_encoding, NULL)) {
1744 adios(NULL, "Unable to encode %s header", DESCR_FIELD);
1745 }
1746 }
1747 add_header (ct, np, vp);
1748 }
1749
1750 /*
1751 * output the Content-Disposition. If it's NULL but c_dispo_type is
1752 * set, then we need to build it.
1753 */
1754 if (ct->c_dispo) {
1755 np = add (DISPO_FIELD, NULL);
1756 vp = concat (" ", ct->c_dispo, NULL);
1757 add_header (ct, np, vp);
1758 } else if (ct->c_dispo_type) {
1759 vp = concat (" ", ct->c_dispo_type, NULL);
1760 len = strlen(DISPO_FIELD) + strlen(vp) + 1;
1761 np = output_params(len, ct->c_dispo_first, NULL, 0);
1762 vp = add(np, vp);
1763 vp = add("\n", vp);
1764 if (np)
1765 free(np);
1766 add_header (ct, mh_xstrdup(DISPO_FIELD), vp);
1767 }
1768
1769 skip_headers:
1770 /*
1771 * If this is the internal content structure for a
1772 * "message/external", then we are done with the
1773 * headers (since it has no body).
1774 */
1775 if (ct->c_ctexbody)
1776 return OK;
1777
1778 /*
1779 * output the Content-MD5
1780 */
1781 if (checksw) {
1782 np = add (MD5_FIELD, NULL);
1783 vp = calculate_digest (ct, (ct->c_encoding == CE_QUOTED) ? 1 : 0);
1784 add_header (ct, np, vp);
1785 }
1786
1787 /*
1788 * output the Content-Transfer-Encoding
1789 * If using EAI and message body is 7-bit, force 8-bit C-T-E.
1790 */
1791 if (header_encoding == CE_8BIT && ct->c_encoding == CE_7BIT) {
1792 ct->c_encoding = CE_8BIT;
1793 }
1794
1795 switch (ct->c_encoding) {
1796 case CE_7BIT:
1797 /* Nothing to output */
1798 break;
1799
1800 case CE_8BIT:
1801 np = add (ENCODING_FIELD, NULL);
1802 vp = concat (" ", "8bit", "\n", NULL);
1803 add_header (ct, np, vp);
1804 break;
1805
1806 case CE_QUOTED:
1807 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1808 adios (NULL, "internal error, invalid encoding");
1809
1810 np = add (ENCODING_FIELD, NULL);
1811 vp = concat (" ", "quoted-printable", "\n", NULL);
1812 add_header (ct, np, vp);
1813 break;
1814
1815 case CE_BASE64:
1816 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1817 adios (NULL, "internal error, invalid encoding");
1818
1819 np = add (ENCODING_FIELD, NULL);
1820 vp = concat (" ", "base64", "\n", NULL);
1821 add_header (ct, np, vp);
1822 break;
1823
1824 case CE_BINARY:
1825 if (ct->c_type == CT_MESSAGE)
1826 adios (NULL, "internal error, invalid encoding");
1827
1828 np = add (ENCODING_FIELD, NULL);
1829 vp = concat (" ", "binary", "\n", NULL);
1830 add_header (ct, np, vp);
1831 break;
1832
1833 default:
1834 adios (NULL, "unknown transfer encoding in content");
1835 break;
1836 }
1837
1838 /*
1839 * Additional content specific header processing
1840 */
1841 switch (ct->c_type) {
1842 case CT_MULTIPART:
1843 {
1844 struct multipart *m;
1845 struct part *part;
1846
1847 m = (struct multipart *) ct->c_ctparams;
1848 for (part = m->mp_parts; part; part = part->mp_next) {
1849 CT p;
1850
1851 p = part->mp_part;
1852 build_headers (p, header_encoding);
1853 }
1854 }
1855 break;
1856
1857 case CT_MESSAGE:
1858 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1859 struct exbody *e;
1860
1861 e = (struct exbody *) ct->c_ctparams;
1862 build_headers (e->eb_content, header_encoding);
1863 }
1864 break;
1865
1866 default:
1867 /* Nothing to do */
1868 break;
1869 }
1870
1871 return OK;
1872 }
1873
1874
1875 static char nib2b64[0x40+1] =
1876 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1877
1878 static char *
1879 calculate_digest (CT ct, int asciiP)
1880 {
1881 int cc;
1882 char *vp, *op;
1883 unsigned char *dp;
1884 unsigned char digest[16];
1885 unsigned char outbuf[25];
1886 MD5_CTX mdContext;
1887 CE ce = &ct->c_cefile;
1888 char *infilename = ce->ce_file ? ce->ce_file : ct->c_file;
1889 FILE *in;
1890
1891 /* open content */
1892 if ((in = fopen (infilename, "r")) == NULL)
1893 adios (infilename, "unable to open for reading");
1894
1895 /* Initialize md5 context */
1896 MD5Init (&mdContext);
1897
1898 /* calculate md5 message digest */
1899 if (asciiP) {
1900 char *bufp = NULL;
1901 size_t buflen;
1902 ssize_t gotlen;
1903 while ((gotlen = getline(&bufp, &buflen, in)) != -1) {
1904 char c, *cp;
1905
1906 cp = bufp + gotlen - 1;
1907 if ((c = *cp) == '\n')
1908 gotlen--;
1909
1910 MD5Update (&mdContext, (unsigned char *) bufp,
1911 (unsigned int) gotlen);
1912
1913 if (c == '\n')
1914 MD5Update (&mdContext, (unsigned char *) "\r\n", 2);
1915 }
1916 } else {
1917 char buffer[BUFSIZ];
1918 while ((cc = fread (buffer, sizeof(*buffer), sizeof(buffer), in)) > 0)
1919 MD5Update (&mdContext, (unsigned char *) buffer, (unsigned int) cc);
1920 }
1921
1922 /* md5 finalization. Write digest and zero md5 context */
1923 MD5Final (digest, &mdContext);
1924
1925 /* close content */
1926 fclose (in);
1927
1928 /* print debugging info */
1929 if (debugsw) {
1930 unsigned char *ep;
1931
1932 fprintf (stderr, "MD5 digest=");
1933 for (ep = (dp = digest) + sizeof(digest) / sizeof(digest[0]);
1934 dp < ep; dp++)
1935 fprintf (stderr, "%02x", *dp & 0xff);
1936 fprintf (stderr, "\n");
1937 }
1938
1939 /* encode the digest using base64 */
1940 for (dp = digest, op = (char *) outbuf,
1941 cc = sizeof(digest) / sizeof(digest[0]);
1942 cc > 0; cc -= 3, op += 4) {
1943 unsigned long bits;
1944 char *bp;
1945
1946 bits = (*dp++ & 0xff) << 16;
1947 if (cc > 1) {
1948 bits |= (*dp++ & 0xff) << 8;
1949 if (cc > 2)
1950 bits |= *dp++ & 0xff;
1951 }
1952
1953 for (bp = op + 4; bp > op; bits >>= 6)
1954 *--bp = nib2b64[bits & 0x3f];
1955 if (cc < 3) {
1956 *(op + 3) = '=';
1957 if (cc < 2)
1958 *(op + 2) = '=';
1959 }
1960 }
1961
1962 /* null terminate string */
1963 outbuf[24] = '\0';
1964
1965 /* now make copy and return string */
1966 vp = concat (" ", outbuf, "\n", NULL);
1967 return vp;
1968 }
1969
1970 /*
1971 * Set things up for the content structure for file "filename" that
1972 * we want to attach
1973 */
1974
1975 static void
1976 setup_attach_content(CT ct, char *filename)
1977 {
1978 char *type, *simplename = r1bindex(filename, '/');
1979 struct str2init *s2i;
1980 PM pm;
1981
1982 if (! (type = mime_type(filename))) {
1983 adios(NULL, "Unable to determine MIME type of \"%s\"", filename);
1984 }
1985
1986 /*
1987 * Parse the Content-Type. get_ctinfo() parses MIME parameters, but
1988 * since we're just feeding it a MIME type we have to add those ourself.
1989 * Map that to a valid content-type label and call any initialization
1990 * function.
1991 */
1992
1993 if (get_ctinfo(type, ct, 0) == NOTOK)
1994 done(1);
1995
1996 free(type);
1997
1998 for (s2i = str2cts; s2i->si_key; s2i++)
1999 if (strcasecmp(ct->c_ctinfo.ci_type, s2i->si_key) == 0)
2000 break;
2001 if (!s2i->si_key && !uprf(ct->c_ctinfo.ci_type, "X-"))
2002 s2i++;
2003
2004 /*
2005 * Make sure the type isn't incompatible with what we can handle
2006 */
2007
2008 switch (ct->c_type = s2i->si_val) {
2009 case CT_MULTIPART:
2010 adios (NULL, "multipart types must be specified by mhbuild directives");
2011 /* NOTREACHED */
2012
2013 case CT_MESSAGE:
2014 if (strcasecmp(ct->c_ctinfo.ci_subtype, "partial") == 0)
2015 adios(NULL, "Sorry, %s/%s isn't supported", ct->c_ctinfo.ci_type,
2016 ct->c_ctinfo.ci_subtype);
2017 if (strcasecmp(ct->c_ctinfo.ci_subtype, "external-body") == 0)
2018 adios(NULL, "external-body messages must be specified "
2019 "by mhbuild directives");
2020 /* Fall through */
2021
2022 default:
2023 /*
2024 * This sets the subtype, if it's significant
2025 */
2026 if ((ct->c_ctinitfnx = s2i->si_init))
2027 (*ct->c_ctinitfnx)(ct);
2028 break;
2029 }
2030
2031 /*
2032 * Feed in a few attributes; specifically, the name attribute, the
2033 * content-description, and the content-disposition.
2034 */
2035
2036 for (pm = ct->c_ctinfo.ci_first_pm; pm; pm = pm->pm_next) {
2037 if (strcasecmp(pm->pm_name, "name") == 0) {
2038 if (pm->pm_value)
2039 free(pm->pm_value);
2040 pm->pm_value = mh_xstrdup(simplename);
2041 break;
2042 }
2043 }
2044
2045 if (pm == NULL)
2046 add_param(&ct->c_ctinfo.ci_first_pm, &ct->c_ctinfo.ci_last_pm,
2047 "name", simplename, 0);
2048
2049 ct->c_descr = mh_xstrdup(simplename);
2050 ct->c_descr = add("\n", ct->c_descr);
2051 ct->c_cefile.ce_file = mh_xstrdup(filename);
2052
2053 set_disposition (ct);
2054
2055 add_param(&ct->c_dispo_first, &ct->c_dispo_last, "filename", simplename, 0);
2056 }
2057
2058 /*
2059 * If disposition type hasn't already been set in ct:
2060 * Look for mhbuild-disposition-<type>/<subtype> entry
2061 * that specifies Content-Disposition type. Only
2062 * 'attachment' and 'inline' are allowed. Default to
2063 * 'attachment'.
2064 */
2065 void
2066 set_disposition (CT ct) {
2067 if (ct->c_dispo_type == NULL) {
2068 char *cp = context_find_by_type ("disposition", ct->c_ctinfo.ci_type,
2069 ct->c_ctinfo.ci_subtype);
2070
2071 if (cp && strcasecmp (cp, "attachment") &&
2072 strcasecmp (cp, "inline")) {
2073 admonish (NULL, "configuration problem: %s-disposition-%s%s%s "
2074 "specifies '%s' but only 'attachment' and 'inline' are "
2075 "allowed", invo_name,
2076 ct->c_ctinfo.ci_type,
2077 ct->c_ctinfo.ci_subtype ? "/" : "",
2078 ct->c_ctinfo.ci_subtype ? ct->c_ctinfo.ci_subtype : "",
2079 cp);
2080 }
2081
2082 if (!cp)
2083 cp = "attachment";
2084 ct->c_dispo_type = mh_xstrdup(cp);
2085 }
2086 }
2087
2088 /*
2089 * Set text content charset if it was unspecified. contains8bit
2090 * selctions:
2091 * 0: content does not contain 8-bit characters
2092 * 1: content contains 8-bit characters
2093 * -1: ignore content and use user's locale to determine charset
2094 */
2095 void
2096 set_charset (CT ct, int contains8bit) {
2097 if (ct->c_type == CT_TEXT) {
2098 struct text *t;
2099
2100 if (ct->c_ctparams == NULL) {
2101 NEW0(t);
2102 ct->c_ctparams = t;
2103 t->tx_charset = CHARSET_UNSPECIFIED;
2104 } else {
2105 t = (struct text *) ct->c_ctparams;
2106 }
2107
2108 if (t->tx_charset == CHARSET_UNSPECIFIED) {
2109 CI ci = &ct->c_ctinfo;
2110 char *eightbitcharset = write_charset_8bit();
2111 char *charset = contains8bit ? eightbitcharset : "us-ascii";
2112
2113 if (contains8bit == 1 &&
2114 strcasecmp (eightbitcharset, "US-ASCII") == 0) {
2115 adios (NULL, "Text content contains 8 bit characters, but "
2116 "character set is US-ASCII");
2117 }
2118
2119 add_param (&ci->ci_first_pm, &ci->ci_last_pm, "charset", charset,
2120 0);
2121
2122 t->tx_charset = CHARSET_SPECIFIED;
2123 }
2124 }
2125 }
2126
2127
2128 /*
2129 * Look at all of the replied-to message parts and expand any that
2130 * are matched by a pseudoheader. Except don't descend into
2131 * message parts.
2132 */
2133 void
2134 expand_pseudoheaders (CT ct, struct multipart *m, const char *infile,
2135 const convert_list *convert_head) {
2136 /* text_plain_ct is used to concatenate all of the text/plain
2137 replies into one part, instead of having each one in a separate
2138 part. */
2139 CT text_plain_ct = NULL;
2140
2141 switch (ct->c_type) {
2142 case CT_MULTIPART: {
2143 struct multipart *mp = (struct multipart *) ct->c_ctparams;
2144 struct part *part;
2145
2146 if (ct->c_subtype == MULTI_ALTERNATE) {
2147 int matched = 0;
2148
2149 /* The parts are in descending priority order (defined by
2150 RFC 2046 Sec. 5.1.4) because they were reversed by
2151 parse_mime (). So, stop looking for matches with
2152 immediate subparts after the first match of an
2153 alternative. */
2154 for (part = mp->mp_parts; ! matched && part; part = part->mp_next) {
2155 char *type_subtype =
2156 concat (part->mp_part->c_ctinfo.ci_type, "/",
2157 part->mp_part->c_ctinfo.ci_subtype, NULL);
2158
2159 if (part->mp_part->c_type == CT_MULTIPART) {
2160 expand_pseudoheaders (part->mp_part, m, infile,
2161 convert_head);
2162 } else {
2163 const convert_list *c;
2164
2165 for (c = convert_head; c; c = c->next) {
2166 if (! strcasecmp (type_subtype, c->type)) {
2167 expand_pseudoheader (part->mp_part, &text_plain_ct,
2168 m, infile,
2169 c->type, c->argstring);
2170 matched = 1;
2171 break;
2172 }
2173 }
2174 }
2175 free (type_subtype);
2176 }
2177 } else {
2178 for (part = mp->mp_parts; part; part = part->mp_next) {
2179 expand_pseudoheaders (part->mp_part, m, infile, convert_head);
2180 }
2181 }
2182 break;
2183 }
2184
2185 default: {
2186 char *type_subtype =
2187 concat (ct->c_ctinfo.ci_type, "/", ct->c_ctinfo.ci_subtype,
2188 NULL);
2189 const convert_list *c;
2190
2191 for (c = convert_head; c; c = c->next) {
2192 if (! strcasecmp (type_subtype, c->type)) {
2193 expand_pseudoheader (ct, &text_plain_ct, m, infile, c->type,
2194 c->argstring);
2195 break;
2196 }
2197 }
2198 free (type_subtype);
2199 break;
2200 }
2201 }
2202 }
2203
2204
2205 /*
2206 * Expand a single pseudoheader. It's for the specified type.
2207 */
2208 void
2209 expand_pseudoheader (CT ct, CT *text_plain_ct, struct multipart *m,
2210 const char *infile, const char *type,
2211 const char *argstring) {
2212 char *reply_file;
2213 FILE *reply_fp = NULL;
2214 char *convert, *type_p, *subtype_p;
2215 char *convert_command;
2216 char *charset = NULL;
2217 char *cp;
2218 struct str2init *s2i;
2219 CT reply_ct;
2220 struct part *part;
2221 int eightbit = 0;
2222 int status;
2223
2224 type_p = getcpy (type);
2225 if ((subtype_p = strchr (type_p, '/'))) {
2226 *subtype_p++ = '\0';
2227 convert = context_find_by_type ("convert", type_p, subtype_p);
2228 } else {
2229 free (type_p);
2230 type_p = concat ("mhbuild-convert-", type, NULL);
2231 convert = context_find (type_p);
2232 }
2233 free (type_p);
2234
2235 if (! (convert)) {
2236 /* No mhbuild-convert- entry in mhn.defaults or profile
2237 for type. */
2238 return;
2239 }
2240 /* reply_file is used to pass the output of the convert. */
2241 reply_file = getcpy (m_mktemp2 (NULL, invo_name, NULL, NULL));
2242 convert_command =
2243 concat (convert, " ", argstring ? argstring : "", " >", reply_file,
2244 NULL);
2245
2246 /* Convert here . . . */
2247 ct->c_storeproc = mh_xstrdup(convert_command);
2248 ct->c_umask = ~m_gmprot ();
2249
2250 if ((status = show_content_aux (ct, 0, convert_command, NULL, NULL)) !=
2251 OK) {
2252 admonish (NULL, "store of %s content failed", type);
2253 }
2254 free (convert_command);
2255
2256 /* Fill out the the new ct, reply_ct. */
2257 NEW0(reply_ct);
2258 init_decoded_content (reply_ct, infile);
2259
2260 if (extract_headers (reply_ct, reply_file, &reply_fp) == NOTOK) {
2261 free (reply_file);
2262 admonish (NULL,
2263 "failed to extract headers from convert output in %s",
2264 reply_file);
2265 return;
2266 }
2267
2268 /* For text content only, see if it is 8-bit text. */
2269 if (reply_ct->c_type == CT_TEXT) {
2270 int fd;
2271
2272 if ((fd = open (reply_file, O_RDONLY)) == NOTOK ||
2273 scan_input (fd, &eightbit) == NOTOK) {
2274 free (reply_file);
2275 admonish (NULL, "failed to read %s", reply_file);
2276 return;
2277 } else {
2278 (void) close (fd);
2279 }
2280 }
2281
2282 /* This sets reply_ct->c_ctparams, and reply_ct->c_termproc if the
2283 charset can't be handled natively. */
2284 for (s2i = str2cts; s2i->si_key; s2i++) {
2285 if (strcasecmp(reply_ct->c_ctinfo.ci_type, s2i->si_key) == 0) {
2286 break;
2287 }
2288 }
2289
2290 if ((reply_ct->c_ctinitfnx = s2i->si_init)) {
2291 (*reply_ct->c_ctinitfnx)(reply_ct);
2292 }
2293
2294 if ((cp =
2295 get_param (reply_ct->c_ctinfo.ci_first_pm, "charset", '?', 1))) {
2296 /* The reply Content-Type had the charset. */
2297 charset = cp;
2298 } else {
2299 set_charset (reply_ct, -1);
2300 charset = get_param (reply_ct->c_ctinfo.ci_first_pm, "charset", '?', 1);
2301 if (reply_ct->c_reqencoding == CE_UNKNOWN &&
2302 reply_ct->c_type == CT_TEXT) {
2303 /* Assume that 8bit is sufficient (for text). In other words,
2304 don't allow it to be encoded as quoted printable if lines
2305 are too long. This also sidesteps the check for whether
2306 it needs to be encoded as binary; instead, it relies on
2307 the applicable mhbuild-convert-text directive to ensure
2308 that the resultant text is not binary. */
2309 reply_ct->c_reqencoding = eightbit ? CE_8BIT : CE_7BIT;
2310 }
2311 }
2312
2313 /* Concatenate text/plain parts. */
2314 if (reply_ct->c_type == CT_TEXT &&
2315 reply_ct->c_subtype == TEXT_PLAIN) {
2316 if (! *text_plain_ct && m->mp_parts && m->mp_parts->mp_part &&
2317 m->mp_parts->mp_part->c_type == CT_TEXT &&
2318 m->mp_parts->mp_part->c_subtype == TEXT_PLAIN) {
2319 *text_plain_ct = m->mp_parts->mp_part;
2320 /* Make sure that the charset is set in the text/plain
2321 part. */
2322 set_charset (*text_plain_ct, -1);
2323 if ((*text_plain_ct)->c_reqencoding == CE_UNKNOWN) {
2324 /* Assume that 8bit is sufficient (for text). In other words,
2325 don't allow it to be encoded as quoted printable if lines
2326 are too long. This also sidesteps the check for whether
2327 it needs to be encoded as binary; instead, it relies on
2328 the applicable mhbuild-convert-text directive to ensure
2329 that the resultant text is not binary. */
2330 (*text_plain_ct)->c_reqencoding =
2331 eightbit ? CE_8BIT : CE_7BIT;
2332 }
2333 }
2334
2335 if (*text_plain_ct) {
2336 /* Only concatenate if the charsets are identical. */
2337 char *text_plain_ct_charset =
2338 get_param ((*text_plain_ct)->c_ctinfo.ci_first_pm, "charset",
2339 '?', 1);
2340
2341 if (strcasecmp (text_plain_ct_charset, charset) == 0) {
2342 /* Append this text/plain reply to the first one.
2343 If there's a problem anywhere along the way,
2344 instead attach it is a separate part. */
2345 int text_plain_reply =
2346 open ((*text_plain_ct)->c_cefile.ce_file,
2347 O_WRONLY | O_APPEND);
2348 int addl_reply = open (reply_file, O_RDONLY);
2349
2350 if (text_plain_reply != NOTOK && addl_reply != NOTOK) {
2351 /* Insert blank line before each addl part. */
2352 /* It would be nice not to do this for the first one. */
2353 if (write (text_plain_reply, "\n", 1) == 1) {
2354 /* Copy the text from the new reply and
2355 then free its Content struct. */
2356 cpydata (addl_reply, text_plain_reply,
2357 (*text_plain_ct)->c_cefile.ce_file,
2358 reply_file);
2359 if (close (text_plain_reply) == OK &&
2360 close (addl_reply) == OK) {
2361 /* If appended text needed 8-bit but first text didn't,
2362 propagate the 8-bit indication. */
2363 if ((*text_plain_ct)->c_reqencoding == CE_7BIT &&
2364 reply_ct->c_reqencoding == CE_8BIT) {
2365 (*text_plain_ct)->c_reqencoding = CE_8BIT;
2366 }
2367
2368 if (reply_fp) { fclose (reply_fp); }
2369 free (reply_file);
2370 free_content (reply_ct);
2371 return;
2372 }
2373 }
2374 }
2375 }
2376 } else {
2377 *text_plain_ct = reply_ct;
2378 }
2379 }
2380
2381 reply_ct->c_cefile.ce_file = reply_file;
2382 reply_ct->c_cefile.ce_fp = reply_fp;
2383 reply_ct->c_cefile.ce_unlink = 1;
2384
2385 /* Attach the new part to the parent multipart/mixed, "m". */
2386 NEW0(part);
2387 part->mp_part = reply_ct;
2388 if (m->mp_parts) {
2389 struct part *p;
2390
2391 for (p = m->mp_parts; p && p->mp_next; p = p->mp_next) { continue; }
2392 p->mp_next = part;
2393 } else {
2394 m->mp_parts = part;
2395 }
2396 }
2397
2398
2399 /* Extract any Content-Type header from beginning of convert output. */
2400 int
2401 extract_headers (CT ct, char *reply_file, FILE **reply_fp) {
2402 char *buffer = NULL, *cp, *end_of_header;
2403 int found_header = 0;
2404 struct stat statbuf;
2405
2406 /* Read the convert reply from the file to memory. */
2407 if (stat (reply_file, &statbuf) == NOTOK) {
2408 admonish (reply_file, "failed to stat");
2409 goto failed_to_extract_ct;
2410 }
2411
2412 buffer = mh_xmalloc (statbuf.st_size + 1);
2413
2414 if ((*reply_fp = fopen (reply_file, "r+")) == NULL ||
2415 fread (buffer, 1, (size_t) statbuf.st_size, *reply_fp) <
2416 (size_t) statbuf.st_size) {
2417 admonish (reply_file, "failed to read");
2418 goto failed_to_extract_ct;
2419 }
2420 buffer[statbuf.st_size] = '\0';
2421
2422 /* Look for a header in the convert reply. */
2423 if (strncasecmp (buffer, TYPE_FIELD, strlen (TYPE_FIELD)) == 0 &&
2424 buffer[strlen (TYPE_FIELD)] == ':') {
2425 if ((end_of_header = strstr (buffer, "\r\n\r\n"))) {
2426 end_of_header += 2;
2427 found_header = 1;
2428 } else if ((end_of_header = strstr (buffer, "\n\n"))) {
2429 ++end_of_header;
2430 found_header = 1;
2431 }
2432 }
2433
2434 if (found_header) {
2435 CT tmp_ct;
2436 char *tmp_file;
2437 FILE *tmp_f;
2438 size_t n;
2439
2440 /* Truncate buffer to just the C-T. */
2441 *end_of_header = '\0';
2442 n = strlen (buffer);
2443
2444 if (get_ctinfo (buffer + 14, ct, 0) != OK) {
2445 admonish (NULL, "unable to get content info for reply");
2446 goto failed_to_extract_ct;
2447 }
2448
2449 /* Hack. Use parse_mime() to detect the type/subtype of the
2450 reply, which we'll use below. */
2451 tmp_file = getcpy (m_mktemp2 (NULL, invo_name, NULL, NULL));
2452 if ((tmp_f = fopen (tmp_file, "w")) &&
2453 fwrite (buffer, 1, n, tmp_f) == n) {
2454 fclose (tmp_f);
2455 } else {
2456 goto failed_to_extract_ct;
2457 }
2458 tmp_ct = parse_mime (tmp_file);
2459
2460 if (tmp_ct) {
2461 /* The type and subtype were detected from the reply
2462 using parse_mime() above. */
2463 ct->c_type = tmp_ct->c_type;
2464 ct->c_subtype = tmp_ct->c_subtype;
2465 free_content (tmp_ct);
2466 }
2467
2468 free (tmp_file);
2469
2470 /* Rewrite the content without the header. */
2471 cp = end_of_header + 1;
2472 rewind (*reply_fp);
2473
2474 if (fwrite (cp, 1, statbuf.st_size - (cp - buffer), *reply_fp) <
2475 (size_t) (statbuf.st_size - (cp - buffer))) {
2476 admonish (reply_file, "failed to write");
2477 goto failed_to_extract_ct;
2478 }
2479
2480 if (ftruncate (fileno (*reply_fp), statbuf.st_size - (cp - buffer)) !=
2481 0) {
2482 advise (reply_file, "ftruncate");
2483 goto failed_to_extract_ct;
2484 }
2485 } else {
2486 /* No header section, assume the reply is text/plain. */
2487 ct->c_type = CT_TEXT;
2488 ct->c_subtype = TEXT_PLAIN;
2489 if (get_ctinfo ("text/plain", ct, 0) == NOTOK) {
2490 /* This never should fail, but just in case. */
2491 adios (NULL, "unable to get content info for reply");
2492 }
2493 }
2494
2495 /* free_encoding() will close reply_fp, which is passed through
2496 ct->c_cefile.ce_fp. */
2497 free (buffer);
2498 return OK;
2499
2500 failed_to_extract_ct:
2501 if (*reply_fp) { fclose (*reply_fp); }
2502 free (buffer);
2503 return NOTOK;
2504 }