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