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