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