]> diplodocus.org Git - nmh/blob - uip/mhbuildsbr.c
Add test for -maxunencoded.
[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/signals.h>
21 #include <h/md5.h>
22 #include <h/mts.h>
23 #include <h/tws.h>
24 #include <h/mime.h>
25 #include <h/mhparse.h>
26 #include <h/utils.h>
27
28 #ifdef HAVE_SYS_TIME_H
29 # include <sys/time.h>
30 #endif
31 #include <time.h>
32
33
34 extern int debugsw;
35 extern int verbosw;
36
37 extern int listsw;
38 extern int rfc934sw;
39 extern int contentidsw;
40
41 /* cache policies */
42 extern int rcachesw; /* mhcachesbr.c */
43 extern int wcachesw; /* mhcachesbr.c */
44
45 pid_t xpid = 0;
46
47 static char prefix[] = "----- =_aaaaaaaaaa";
48
49 struct attach_list {
50 char *filename;
51 struct attach_list *next;
52 };
53
54 /*
55 * Maximum size of URL token in message/external-body
56 */
57
58 #define MAXURLTOKEN 40
59
60
61 /* mhmisc.c */
62 void content_error (char *, CT, char *, ...);
63
64 /* mhcachesbr.c */
65 int find_cache (CT, int, int *, char *, char *, int);
66
67 /* mhfree.c */
68 void free_ctinfo (CT);
69 void free_encoding (CT, int);
70
71 /*
72 * static prototypes
73 */
74 static int init_decoded_content (CT);
75 static void setup_attach_content(CT, char *);
76 static char *fgetstr (char *, int, FILE *);
77 static int user_content (FILE *, char *, CT *);
78 static void set_id (CT, int);
79 static int compose_content (CT);
80 static int scan_content (CT, size_t);
81 static int build_headers (CT);
82 static char *calculate_digest (CT, int);
83
84
85 static unsigned char directives_stack[32];
86 static unsigned int directives_index;
87
88 static int do_direct(void)
89 {
90 return directives_stack[directives_index];
91 }
92
93 static void directive_onoff(int onoff)
94 {
95 if (directives_index >= sizeof(directives_stack) - 1) {
96 fprintf(stderr, "mhbuild: #on/off overflow, continuing\n");
97 return;
98 }
99 directives_stack[++directives_index] = onoff;
100 }
101
102 static void directive_init(int onoff)
103 {
104 directives_index = 0;
105 directives_stack[0] = onoff;
106 }
107
108 static void directive_pop(void)
109 {
110 if (directives_index > 0)
111 directives_index--;
112 else
113 fprintf(stderr, "mhbuild: #pop underflow, continuing\n");
114 }
115
116 /*
117 * Main routine for translating composition file
118 * into valid MIME message. It translates the draft
119 * into a content structure (actually a tree of content
120 * structures). This message then can be manipulated
121 * in various ways, including being output via
122 * output_message().
123 */
124
125 CT
126 build_mime (char *infile, int autobuild, int dist, int directives,
127 int header_encoding, size_t maxunencoded)
128 {
129 int compnum, state;
130 char buf[BUFSIZ], name[NAMESZ];
131 char *cp, *np, *vp;
132 struct multipart *m;
133 struct part **pp;
134 CT ct;
135 FILE *in;
136 HF hp;
137 m_getfld_state_t gstate = 0;
138 struct attach_list *attach_head = NULL, *attach_tail = NULL, *at_entry;
139
140 directive_init(directives);
141
142 umask (~m_gmprot ());
143
144 /* open the composition draft */
145 if ((in = fopen (infile, "r")) == NULL)
146 adios (infile, "unable to open for reading");
147
148 /*
149 * Allocate space for primary (outside) content
150 */
151 if ((ct = (CT) calloc (1, sizeof(*ct))) == NULL)
152 adios (NULL, "out of memory");
153
154 /*
155 * Allocate structure for handling decoded content
156 * for this part. We don't really need this, but
157 * allocate it to remain consistent.
158 */
159 init_decoded_content (ct);
160
161 /*
162 * Parse some of the header fields in the composition
163 * draft into the linked list of header fields for
164 * the new MIME message.
165 */
166 m_getfld_track_filepos (&gstate, in);
167 for (compnum = 1;;) {
168 int bufsz = sizeof buf;
169 switch (state = m_getfld (&gstate, name, buf, &bufsz, in)) {
170 case FLD:
171 case FLDPLUS:
172 compnum++;
173
174 /* abort if draft has Mime-Version or C-T-E header field */
175 if (strcasecmp (name, VRSN_FIELD) == 0 ||
176 strcasecmp (name, ENCODING_FIELD) == 0) {
177 if (autobuild) {
178 fclose(in);
179 return NULL;
180 } else {
181 adios (NULL, "draft shouldn't contain %s: field", name);
182 }
183 }
184
185 /* ignore any Content-Type fields in the header */
186 if (!strcasecmp (name, TYPE_FIELD)) {
187 while (state == FLDPLUS) {
188 bufsz = sizeof buf;
189 state = m_getfld (&gstate, name, buf, &bufsz, in);
190 }
191 goto finish_field;
192 }
193
194 /* get copies of the buffers */
195 np = add (name, NULL);
196 vp = add (buf, NULL);
197
198 /* if necessary, get rest of field */
199 while (state == FLDPLUS) {
200 bufsz = sizeof buf;
201 state = m_getfld (&gstate, name, buf, &bufsz, in);
202 vp = add (buf, vp); /* add to previous value */
203 }
204
205 /*
206 * Now add the header data to the list, unless it's an attach
207 * header; in that case, add it to our attach list
208 */
209
210 if (strcasecmp(ATTACH_FIELD, np) == 0) {
211 struct attach_list *entry;
212 char *s = vp, *e = vp + strlen(vp) - 1;
213 free(np);
214
215 /*
216 * Make sure we can find the start of this filename.
217 * If it's blank, we skip completely. Otherwise, strip
218 * off any leading spaces and trailing newlines.
219 */
220
221 while (isspace((unsigned char) *s))
222 s++;
223
224 while (e > s && *e == '\n')
225 *e-- = '\0';
226
227 if (*s == '\0') {
228 free(vp);
229 goto finish_field;
230 }
231
232 entry = mh_xmalloc(sizeof(*entry));
233 entry->filename = getcpy(s);
234 entry->next = NULL;
235 free(vp);
236
237 if (attach_tail) {
238 attach_tail->next = entry;
239 attach_tail = entry;
240 } else {
241 attach_head = attach_tail = entry;
242 }
243 } else {
244 add_header (ct, np, vp);
245 }
246
247 finish_field:
248 /* if this wasn't the last header field, then continue */
249 continue;
250
251 case BODY:
252 fseek (in, (long) (-strlen (buf)), SEEK_CUR);
253 /* fall through */
254 case FILEEOF:
255 break;
256
257 case LENERR:
258 case FMTERR:
259 adios (NULL, "message format error in component #%d", compnum);
260
261 default:
262 adios (NULL, "getfld() returned %d", state);
263 }
264 break;
265 }
266 m_getfld_state_destroy (&gstate);
267
268 /*
269 * Iterate through the list of headers and call the function to MIME-ify
270 * them if required.
271 */
272
273 for (hp = ct->c_first_hf; hp != NULL; hp = hp->next) {
274 if (encode_rfc2047(hp->name, &hp->value, header_encoding, NULL)) {
275 adios(NULL, "Unable to encode header \"%s\"", hp->name);
276 }
277 }
278
279 /*
280 * Now add the MIME-Version header field
281 * to the list of header fields.
282 */
283
284 if (! dist) {
285 np = add (VRSN_FIELD, NULL);
286 vp = concat (" ", VRSN_VALUE, "\n", NULL);
287 add_header (ct, np, vp);
288 }
289
290 /*
291 * We initally assume we will find multiple contents in the
292 * draft. So create a multipart/mixed content to hold everything.
293 * We can remove this later, if it is not needed.
294 */
295 if (get_ctinfo ("multipart/mixed", ct, 0) == NOTOK)
296 done (1);
297 ct->c_type = CT_MULTIPART;
298 ct->c_subtype = MULTI_MIXED;
299 ct->c_file = add (infile, NULL);
300
301 if ((m = (struct multipart *) calloc (1, sizeof(*m))) == NULL)
302 adios (NULL, "out of memory");
303 ct->c_ctparams = (void *) m;
304 pp = &m->mp_parts;
305
306 /*
307 * read and parse the composition file
308 * and the directives it contains.
309 */
310 while (fgetstr (buf, sizeof(buf) - 1, in)) {
311 struct part *part;
312 CT p;
313
314 if (user_content (in, buf, &p) == DONE) {
315 admonish (NULL, "ignoring spurious #end");
316 continue;
317 }
318 if (!p)
319 continue;
320
321 if ((part = (struct part *) calloc (1, sizeof(*part))) == NULL)
322 adios (NULL, "out of memory");
323 *pp = part;
324 pp = &part->mp_next;
325 part->mp_part = p;
326 }
327
328 /*
329 * Add any Attach headers to the list of MIME parts at the end of the
330 * message.
331 */
332
333 for (at_entry = attach_head; at_entry; ) {
334 struct attach_list *at_prev = at_entry;
335 struct part *part;
336 CT p;
337
338 if (access(at_entry->filename, R_OK) != 0) {
339 adios("reading", "Unable to open %s for", at_entry->filename);
340 }
341
342 if ((p = (CT) calloc (1, sizeof(*p))) == NULL)
343 adios(NULL, "out of memory");
344
345 init_decoded_content(p);
346
347 /*
348 * Initialize our content structure based on the filename,
349 * and fill in all of the relevant fields. Also place MIME
350 * parameters in the attributes array.
351 */
352
353 setup_attach_content(p, at_entry->filename);
354
355 if ((part = (struct part *) calloc (1, sizeof(*part))) == NULL)
356 adios (NULL, "out of memory");
357 *pp = part;
358 pp = &part->mp_next;
359 part->mp_part = p;
360
361 at_entry = at_entry->next;
362 free(at_prev->filename);
363 free(at_prev);
364 }
365
366 /*
367 * To allow for empty message bodies, if we've found NO content at all
368 * yet cook up an empty text/plain part.
369 */
370
371 if (!m->mp_parts) {
372 CT p;
373 struct part *part;
374 struct text *t;
375
376 if ((p = (CT) calloc (1, sizeof(*p))) == NULL)
377 adios(NULL, "out of memory");
378
379 init_decoded_content(p);
380
381 if (get_ctinfo ("text/plain", p, 0) == NOTOK)
382 done (1);
383
384 p->c_type = CT_TEXT;
385 p->c_subtype = TEXT_PLAIN;
386 p->c_encoding = CE_7BIT;
387 p->c_file = getcpy(infile);
388 /*
389 * Sigh. ce_file contains the "decoded" contents of this part.
390 * So this seems like the best option available since we're going
391 * to call scan_content() on this.
392 */
393 p->c_cefile.ce_file = getcpy("/dev/null");
394 p->c_begin = ftell(in);
395 p->c_end = ftell(in);
396
397 if ((t = (struct text *) calloc (1, sizeof (*t))) == NULL)
398 adios (NULL, "out of memory");
399
400 t->tx_charset = CHARSET_SPECIFIED;
401 p->c_ctparams = t;
402
403 if ((part = (struct part *) calloc (1, sizeof(*part))) == NULL)
404 adios (NULL, "out of memory");
405 *pp = part;
406 pp = &part->mp_next;
407 part->mp_part = p;
408 }
409
410 /*
411 * close the composition draft since
412 * it's not needed any longer.
413 */
414 fclose (in);
415
416 /*
417 * If only one content was found, then remove and
418 * free the outer multipart content.
419 */
420 if (!m->mp_parts->mp_next) {
421 CT p;
422
423 p = m->mp_parts->mp_part;
424 m->mp_parts->mp_part = NULL;
425
426 /* move header fields */
427 p->c_first_hf = ct->c_first_hf;
428 p->c_last_hf = ct->c_last_hf;
429 ct->c_first_hf = NULL;
430 ct->c_last_hf = NULL;
431
432 free_content (ct);
433 ct = p;
434 } else {
435 set_id (ct, 1);
436 }
437
438 /*
439 * Fill out, or expand directives. Parse and execute
440 * commands specified by profile composition strings.
441 */
442 compose_content (ct);
443
444 if ((cp = strchr(prefix, 'a')) == NULL)
445 adios (NULL, "internal error(4)");
446
447 /*
448 * Scan the contents. Choose a transfer encoding, and
449 * check if prefix for multipart boundary clashes with
450 * any of the contents.
451 */
452 while (scan_content (ct, maxunencoded) == NOTOK) {
453 if (*cp < 'z') {
454 (*cp)++;
455 } else {
456 if (*++cp == 0)
457 adios (NULL, "giving up trying to find a unique delimiter string");
458 else
459 (*cp)++;
460 }
461 }
462
463 /* Build the rest of the header field structures */
464 if (! dist)
465 build_headers (ct);
466
467 return ct;
468 }
469
470
471 /*
472 * Set up structures for placing unencoded
473 * content when building parts.
474 */
475
476 static int
477 init_decoded_content (CT ct)
478 {
479 ct->c_ceopenfnx = open7Bit; /* since unencoded */
480 ct->c_ceclosefnx = close_encoding;
481 ct->c_cesizefnx = NULL; /* since unencoded */
482
483 return OK;
484 }
485
486
487 static char *
488 fgetstr (char *s, int n, FILE *stream)
489 {
490 char *cp, *ep;
491 int o_n = n;
492
493 while(1) {
494 for (ep = (cp = s) + o_n; cp < ep; ) {
495 int i;
496
497 if (!fgets (cp, n, stream))
498 return (cp != s ? s : NULL);
499
500 if (cp == s && *cp != '#')
501 return s;
502
503 cp += (i = strlen (cp)) - 1;
504 if (i <= 1 || *cp-- != '\n' || *cp != '\\')
505 break;
506 *cp = '\0';
507 n -= (i - 2);
508 }
509
510 if (strcmp(s, "#on\n") == 0) {
511 directive_onoff(1);
512 } else if (strcmp(s, "#off\n") == 0) {
513 directive_onoff(0);
514 } else if (strcmp(s, "#pop\n") == 0) {
515 directive_pop();
516 } else {
517 break;
518 }
519 }
520
521 return s;
522 }
523
524
525 /*
526 * Parse the composition draft for text and directives.
527 * Do initial setup of Content structure.
528 */
529
530 static int
531 user_content (FILE *in, char *buf, CT *ctp)
532 {
533 int extrnal, vrsn;
534 char *cp, **ap;
535 char buffer[BUFSIZ];
536 struct multipart *m;
537 struct part **pp;
538 struct stat st;
539 struct str2init *s2i;
540 CI ci;
541 CT ct;
542 CE ce;
543
544 if (buf[0] == '\n' || (do_direct() && strcmp (buf, "#\n") == 0)) {
545 *ctp = NULL;
546 return OK;
547 }
548
549 /* allocate basic Content structure */
550 if ((ct = (CT) calloc (1, sizeof(*ct))) == NULL)
551 adios (NULL, "out of memory");
552 *ctp = ct;
553
554 /* allocate basic structure for handling decoded content */
555 init_decoded_content (ct);
556 ce = &ct->c_cefile;
557
558 ci = &ct->c_ctinfo;
559 set_id (ct, 0);
560
561 /*
562 * Handle inline text. Check if line
563 * is one of the following forms:
564 *
565 * 1) doesn't begin with '#' (implicit directive)
566 * 2) begins with "##" (implicit directive)
567 * 3) begins with "#<"
568 */
569 if (!do_direct() || buf[0] != '#' || buf[1] == '#' || buf[1] == '<') {
570 int headers;
571 int inlineD;
572 long pos;
573 char content[BUFSIZ];
574 FILE *out;
575 char *cp;
576
577 if ((cp = m_mktemp2(NULL, invo_name, NULL, &out)) == NULL) {
578 adios("mhbuildsbr", "unable to create temporary file in %s",
579 get_temp_dir());
580 }
581
582 /* use a temp file to collect the plain text lines */
583 ce->ce_file = add (cp, NULL);
584 ce->ce_unlink = 1;
585
586 if (do_direct() && (buf[0] == '#' && buf[1] == '<')) {
587 strncpy (content, buf + 2, sizeof(content));
588 inlineD = 1;
589 goto rock_and_roll;
590 } else {
591 inlineD = 0;
592 }
593
594 /* the directive is implicit */
595 strncpy (content, "text/plain", sizeof(content));
596 headers = 0;
597 strncpy (buffer, (!do_direct() || buf[0] != '#') ? buf : buf + 1, sizeof(buffer));
598 for (;;) {
599 int i;
600
601 if (headers >= 0 && do_direct() && uprf (buffer, DESCR_FIELD)
602 && buffer[i = strlen (DESCR_FIELD)] == ':') {
603 headers = 1;
604
605 again_descr:
606 ct->c_descr = add (buffer + i + 1, ct->c_descr);
607 if (!fgetstr (buffer, sizeof(buffer) - 1, in))
608 adios (NULL, "end-of-file after %s: field in plaintext", DESCR_FIELD);
609 switch (buffer[0]) {
610 case ' ':
611 case '\t':
612 i = -1;
613 goto again_descr;
614
615 case '#':
616 adios (NULL, "#-directive after %s: field in plaintext", DESCR_FIELD);
617 /* NOTREACHED */
618
619 default:
620 break;
621 }
622 }
623
624 if (headers >= 0 && do_direct() && uprf (buffer, DISPO_FIELD)
625 && buffer[i = strlen (DISPO_FIELD)] == ':') {
626 headers = 1;
627
628 again_dispo:
629 ct->c_dispo = add (buffer + i + 1, ct->c_dispo);
630 if (!fgetstr (buffer, sizeof(buffer) - 1, in))
631 adios (NULL, "end-of-file after %s: field in plaintext", DISPO_FIELD);
632 switch (buffer[0]) {
633 case ' ':
634 case '\t':
635 i = -1;
636 goto again_dispo;
637
638 case '#':
639 adios (NULL, "#-directive after %s: field in plaintext", DISPO_FIELD);
640 /* NOTREACHED */
641
642 default:
643 break;
644 }
645 }
646
647 if (headers != 1 || buffer[0] != '\n')
648 fputs (buffer, out);
649
650 rock_and_roll:
651 headers = -1;
652 pos = ftell (in);
653 if ((cp = fgetstr (buffer, sizeof(buffer) - 1, in)) == NULL)
654 break;
655 if (do_direct() && buffer[0] == '#') {
656 char *bp;
657
658 if (buffer[1] != '#')
659 break;
660 for (cp = (bp = buffer) + 1; *cp; cp++)
661 *bp++ = *cp;
662 *bp = '\0';
663 }
664 }
665
666 if (listsw)
667 ct->c_end = ftell (out);
668 fclose (out);
669
670 /* parse content type */
671 if (get_ctinfo (content, ct, inlineD) == NOTOK)
672 done (1);
673
674 for (s2i = str2cts; s2i->si_key; s2i++)
675 if (!strcasecmp (ci->ci_type, s2i->si_key))
676 break;
677 if (!s2i->si_key && !uprf (ci->ci_type, "X-"))
678 s2i++;
679
680 /*
681 * check type specified (possibly implicitly)
682 */
683 switch (ct->c_type = s2i->si_val) {
684 case CT_MESSAGE:
685 if (!strcasecmp (ci->ci_subtype, "rfc822")) {
686 ct->c_encoding = CE_7BIT;
687 goto call_init;
688 }
689 /* else fall... */
690 case CT_MULTIPART:
691 adios (NULL, "it doesn't make sense to define an in-line %s content",
692 ct->c_type == CT_MESSAGE ? "message" : "multipart");
693 /* NOTREACHED */
694
695 default:
696 call_init:
697 if ((ct->c_ctinitfnx = s2i->si_init))
698 (*ct->c_ctinitfnx) (ct);
699 break;
700 }
701
702 if (cp)
703 fseek (in, pos, SEEK_SET);
704 return OK;
705 }
706
707 /*
708 * If we've reached this point, the next line
709 * must be some type of explicit directive.
710 */
711
712 /* check if directive is external-type */
713 extrnal = (buf[1] == '@');
714
715 /* parse directive */
716 if (get_ctinfo (buf + (extrnal ? 2 : 1), ct, 1) == NOTOK)
717 done (1);
718
719 /* check directive against the list of MIME types */
720 for (s2i = str2cts; s2i->si_key; s2i++)
721 if (!strcasecmp (ci->ci_type, s2i->si_key))
722 break;
723
724 /*
725 * Check if the directive specified a valid type.
726 * This will happen if it was one of the following forms:
727 *
728 * #type/subtype (or)
729 * #@type/subtype
730 */
731 if (s2i->si_key) {
732 if (!ci->ci_subtype)
733 adios (NULL, "missing subtype in \"#%s\"", ci->ci_type);
734
735 switch (ct->c_type = s2i->si_val) {
736 case CT_MULTIPART:
737 adios (NULL, "use \"#begin ... #end\" instead of \"#%s/%s\"",
738 ci->ci_type, ci->ci_subtype);
739 /* NOTREACHED */
740
741 case CT_MESSAGE:
742 if (!strcasecmp (ci->ci_subtype, "partial"))
743 adios (NULL, "sorry, \"#%s/%s\" isn't supported",
744 ci->ci_type, ci->ci_subtype);
745 if (!strcasecmp (ci->ci_subtype, "external-body"))
746 adios (NULL, "use \"#@type/subtype ... [] ...\" instead of \"#%s/%s\"",
747 ci->ci_type, ci->ci_subtype);
748 use_forw:
749 adios (NULL,
750 "use \"#forw [+folder] [msgs]\" instead of \"#%s/%s\"",
751 ci->ci_type, ci->ci_subtype);
752 /* NOTREACHED */
753
754 default:
755 if ((ct->c_ctinitfnx = s2i->si_init))
756 (*ct->c_ctinitfnx) (ct);
757 break;
758 }
759
760 /*
761 * #@type/subtype (external types directive)
762 */
763 if (extrnal) {
764 struct exbody *e;
765 CT p;
766
767 if (!ci->ci_magic)
768 adios (NULL, "need external information for \"#@%s/%s\"",
769 ci->ci_type, ci->ci_subtype);
770 p = ct;
771
772 snprintf (buffer, sizeof(buffer), "message/external-body; %s", ci->ci_magic);
773 free (ci->ci_magic);
774 ci->ci_magic = NULL;
775
776 /*
777 * Since we are using the current Content structure to
778 * hold information about the type of the external
779 * reference, we need to create another Content structure
780 * for the message/external-body to wrap it in.
781 */
782 if ((ct = (CT) calloc (1, sizeof(*ct))) == NULL)
783 adios (NULL, "out of memory");
784 *ctp = ct;
785 ci = &ct->c_ctinfo;
786 if (get_ctinfo (buffer, ct, 0) == NOTOK)
787 done (1);
788 ct->c_type = CT_MESSAGE;
789 ct->c_subtype = MESSAGE_EXTERNAL;
790
791 if ((e = (struct exbody *) calloc (1, sizeof(*e))) == NULL)
792 adios (NULL, "out of memory");
793 ct->c_ctparams = (void *) e;
794
795 e->eb_parent = ct;
796 e->eb_content = p;
797 p->c_ctexbody = e;
798
799 if (params_external (ct, 1) == NOTOK)
800 done (1);
801
802 return OK;
803 }
804
805 /* Handle [file] argument */
806 if (ci->ci_magic) {
807 /* check if specifies command to execute */
808 if (*ci->ci_magic == '|' || *ci->ci_magic == '!') {
809 for (cp = ci->ci_magic + 1; isspace ((unsigned char) *cp); cp++)
810 continue;
811 if (!*cp)
812 adios (NULL, "empty pipe command for #%s directive", ci->ci_type);
813 cp = add (cp, NULL);
814 free (ci->ci_magic);
815 ci->ci_magic = cp;
816 } else {
817 /* record filename of decoded contents */
818 ce->ce_file = ci->ci_magic;
819 if (access (ce->ce_file, R_OK) == NOTOK)
820 adios ("reading", "unable to access %s for", ce->ce_file);
821 if (listsw && stat (ce->ce_file, &st) != NOTOK)
822 ct->c_end = (long) st.st_size;
823 ci->ci_magic = NULL;
824 }
825 return OK;
826 }
827
828 /*
829 * No [file] argument, so check profile for
830 * method to compose content.
831 */
832 snprintf (buffer, sizeof(buffer), "%s-compose-%s/%s",
833 invo_name, ci->ci_type, ci->ci_subtype);
834 if ((cp = context_find (buffer)) == NULL || *cp == '\0') {
835 snprintf (buffer, sizeof(buffer), "%s-compose-%s", invo_name, ci->ci_type);
836 if ((cp = context_find (buffer)) == NULL || *cp == '\0') {
837 content_error (NULL, ct, "don't know how to compose content");
838 done (1);
839 }
840 }
841 ci->ci_magic = add (cp, NULL);
842 return OK;
843 }
844
845 if (extrnal)
846 adios (NULL, "external definition not allowed for \"#%s\"", ci->ci_type);
847
848 /*
849 * Message directive
850 * #forw [+folder] [msgs]
851 */
852 if (!strcasecmp (ci->ci_type, "forw")) {
853 int msgnum;
854 char *folder, *arguments[MAXARGS];
855 struct msgs *mp;
856
857 if (ci->ci_magic) {
858 ap = brkstring (ci->ci_magic, " ", "\n");
859 copyip (ap, arguments, MAXARGS);
860 } else {
861 arguments[0] = "cur";
862 arguments[1] = NULL;
863 }
864 folder = NULL;
865
866 /* search the arguments for a folder name */
867 for (ap = arguments; *ap; ap++) {
868 cp = *ap;
869 if (*cp == '+' || *cp == '@') {
870 if (folder)
871 adios (NULL, "only one folder per #forw directive");
872 else
873 folder = pluspath (cp);
874 }
875 }
876
877 /* else, use the current folder */
878 if (!folder)
879 folder = add (getfolder (1), NULL);
880
881 if (!(mp = folder_read (folder, 0)))
882 adios (NULL, "unable to read folder %s", folder);
883 for (ap = arguments; *ap; ap++) {
884 cp = *ap;
885 if (*cp != '+' && *cp != '@')
886 if (!m_convert (mp, cp))
887 done (1);
888 }
889 free (folder);
890 free_ctinfo (ct);
891
892 /*
893 * If there is more than one message to include, make this
894 * a content of type "multipart/digest" and insert each message
895 * as a subpart. If there is only one message, then make this
896 * a content of type "message/rfc822".
897 */
898 if (mp->numsel > 1) {
899 /* we are forwarding multiple messages */
900 if (get_ctinfo ("multipart/digest", ct, 0) == NOTOK)
901 done (1);
902 ct->c_type = CT_MULTIPART;
903 ct->c_subtype = MULTI_DIGEST;
904
905 if ((m = (struct multipart *) calloc (1, sizeof(*m))) == NULL)
906 adios (NULL, "out of memory");
907 ct->c_ctparams = (void *) m;
908 pp = &m->mp_parts;
909
910 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
911 if (is_selected(mp, msgnum)) {
912 struct part *part;
913 CT p;
914 CE pe;
915
916 if ((p = (CT) calloc (1, sizeof(*p))) == NULL)
917 adios (NULL, "out of memory");
918 init_decoded_content (p);
919 pe = &p->c_cefile;
920 if (get_ctinfo ("message/rfc822", p, 0) == NOTOK)
921 done (1);
922 p->c_type = CT_MESSAGE;
923 p->c_subtype = MESSAGE_RFC822;
924
925 snprintf (buffer, sizeof(buffer), "%s/%d", mp->foldpath, msgnum);
926 pe->ce_file = add (buffer, NULL);
927 if (listsw && stat (pe->ce_file, &st) != NOTOK)
928 p->c_end = (long) st.st_size;
929
930 if ((part = (struct part *) calloc (1, sizeof(*part))) == NULL)
931 adios (NULL, "out of memory");
932 *pp = part;
933 pp = &part->mp_next;
934 part->mp_part = p;
935 }
936 }
937 } else {
938 /* we are forwarding one message */
939 if (get_ctinfo ("message/rfc822", ct, 0) == NOTOK)
940 done (1);
941 ct->c_type = CT_MESSAGE;
942 ct->c_subtype = MESSAGE_RFC822;
943
944 msgnum = mp->lowsel;
945 snprintf (buffer, sizeof(buffer), "%s/%d", mp->foldpath, msgnum);
946 ce->ce_file = add (buffer, NULL);
947 if (listsw && stat (ce->ce_file, &st) != NOTOK)
948 ct->c_end = (long) st.st_size;
949 }
950
951 folder_free (mp); /* free folder/message structure */
952 return OK;
953 }
954
955 /*
956 * #end
957 */
958 if (!strcasecmp (ci->ci_type, "end")) {
959 free_content (ct);
960 *ctp = NULL;
961 return DONE;
962 }
963
964 /*
965 * #begin [ alternative | parallel ]
966 */
967 if (!strcasecmp (ci->ci_type, "begin")) {
968 if (!ci->ci_magic) {
969 vrsn = MULTI_MIXED;
970 cp = SubMultiPart[vrsn - 1].kv_key;
971 } else if (!strcasecmp (ci->ci_magic, "alternative")) {
972 vrsn = MULTI_ALTERNATE;
973 cp = SubMultiPart[vrsn - 1].kv_key;
974 } else if (!strcasecmp (ci->ci_magic, "parallel")) {
975 vrsn = MULTI_PARALLEL;
976 cp = SubMultiPart[vrsn - 1].kv_key;
977 } else if (uprf (ci->ci_magic, "digest")) {
978 goto use_forw;
979 } else {
980 vrsn = MULTI_UNKNOWN;
981 cp = ci->ci_magic;
982 }
983
984 free_ctinfo (ct);
985 snprintf (buffer, sizeof(buffer), "multipart/%s", cp);
986 if (get_ctinfo (buffer, ct, 0) == NOTOK)
987 done (1);
988 ct->c_type = CT_MULTIPART;
989 ct->c_subtype = vrsn;
990
991 if ((m = (struct multipart *) calloc (1, sizeof(*m))) == NULL)
992 adios (NULL, "out of memory");
993 ct->c_ctparams = (void *) m;
994
995 pp = &m->mp_parts;
996 while (fgetstr (buffer, sizeof(buffer) - 1, in)) {
997 struct part *part;
998 CT p;
999
1000 if (user_content (in, buffer, &p) == DONE) {
1001 if (!m->mp_parts)
1002 adios (NULL, "empty \"#begin ... #end\" sequence");
1003 return OK;
1004 }
1005 if (!p)
1006 continue;
1007
1008 if ((part = (struct part *) calloc (1, sizeof(*part))) == NULL)
1009 adios (NULL, "out of memory");
1010 *pp = part;
1011 pp = &part->mp_next;
1012 part->mp_part = p;
1013 }
1014 admonish (NULL, "premature end-of-file, missing #end");
1015 return OK;
1016 }
1017
1018 /*
1019 * Unknown directive
1020 */
1021 adios (NULL, "unknown directive \"#%s\"", ci->ci_type);
1022 return NOTOK; /* NOT REACHED */
1023 }
1024
1025
1026 static void
1027 set_id (CT ct, int top)
1028 {
1029 char contentid[BUFSIZ];
1030 static int partno;
1031 static time_t clock = 0;
1032 static char *msgfmt;
1033
1034 if (clock == 0) {
1035 time (&clock);
1036 snprintf (contentid, sizeof(contentid), "%s\n", message_id (clock, 1));
1037 partno = 0;
1038 msgfmt = getcpy(contentid);
1039 }
1040 snprintf (contentid, sizeof(contentid), msgfmt, top ? 0 : ++partno);
1041 ct->c_id = getcpy (contentid);
1042 }
1043
1044
1045 /*
1046 * Fill out, or expand the various contents in the composition
1047 * draft. Read-in any necessary files. Parse and execute any
1048 * commands specified by profile composition strings.
1049 */
1050
1051 static int
1052 compose_content (CT ct)
1053 {
1054 CE ce = &ct->c_cefile;
1055
1056 switch (ct->c_type) {
1057 case CT_MULTIPART:
1058 {
1059 int partnum;
1060 char *pp;
1061 char partnam[BUFSIZ];
1062 struct multipart *m = (struct multipart *) ct->c_ctparams;
1063 struct part *part;
1064
1065 if (ct->c_partno) {
1066 snprintf (partnam, sizeof(partnam), "%s.", ct->c_partno);
1067 pp = partnam + strlen (partnam);
1068 } else {
1069 pp = partnam;
1070 }
1071
1072 /* first, we call compose_content on all the subparts */
1073 for (part = m->mp_parts, partnum = 1; part; part = part->mp_next, partnum++) {
1074 CT p = part->mp_part;
1075
1076 sprintf (pp, "%d", partnum);
1077 p->c_partno = add (partnam, NULL);
1078 if (compose_content (p) == NOTOK)
1079 return NOTOK;
1080 }
1081
1082 /*
1083 * If the -rfc934mode switch is given, then check all
1084 * the subparts of a multipart/digest. If they are all
1085 * message/rfc822, then mark this content and all
1086 * subparts with the rfc934 compatibility mode flag.
1087 */
1088 if (rfc934sw && ct->c_subtype == MULTI_DIGEST) {
1089 int is934 = 1;
1090
1091 for (part = m->mp_parts; part; part = part->mp_next) {
1092 CT p = part->mp_part;
1093
1094 if (p->c_subtype != MESSAGE_RFC822) {
1095 is934 = 0;
1096 break;
1097 }
1098 }
1099 ct->c_rfc934 = is934;
1100 for (part = m->mp_parts; part; part = part->mp_next) {
1101 CT p = part->mp_part;
1102
1103 if ((p->c_rfc934 = is934))
1104 p->c_end++;
1105 }
1106 }
1107
1108 if (listsw) {
1109 ct->c_end = (partnum = strlen (prefix) + 2) + 2;
1110 if (ct->c_rfc934)
1111 ct->c_end += 1;
1112
1113 for (part = m->mp_parts; part; part = part->mp_next)
1114 ct->c_end += part->mp_part->c_end + partnum;
1115 }
1116 }
1117 break;
1118
1119 case CT_MESSAGE:
1120 /* Nothing to do for type message */
1121 break;
1122
1123 /*
1124 * Discrete types (text/application/audio/image/video)
1125 */
1126 default:
1127 if (!ce->ce_file) {
1128 pid_t child_id;
1129 int i, xstdout, len, buflen;
1130 char *bp, **ap, *cp;
1131 char *vec[4], buffer[BUFSIZ];
1132 FILE *out;
1133 CI ci = &ct->c_ctinfo;
1134 char *tfile = NULL;
1135
1136 if (!(cp = ci->ci_magic))
1137 adios (NULL, "internal error(5)");
1138
1139 if ((tfile = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
1140 adios("mhbuildsbr", "unable to create temporary file in %s",
1141 get_temp_dir());
1142 }
1143 ce->ce_file = add (tfile, NULL);
1144 ce->ce_unlink = 1;
1145
1146 xstdout = 0;
1147
1148 /* Get buffer ready to go */
1149 bp = buffer;
1150 bp[0] = '\0';
1151 buflen = sizeof(buffer);
1152
1153 /*
1154 * Parse composition string into buffer
1155 */
1156 for ( ; *cp; cp++) {
1157 if (*cp == '%') {
1158 switch (*++cp) {
1159 case 'a':
1160 {
1161 /* insert parameters from directive */
1162 char **ep;
1163 char *s = "";
1164
1165 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++) {
1166 snprintf (bp, buflen, "%s%s=\"%s\"", s, *ap, *ep);
1167 len = strlen (bp);
1168 bp += len;
1169 buflen -= len;
1170 s = " ";
1171 }
1172 }
1173 break;
1174
1175 case 'F':
1176 /* %f, and stdout is not-redirected */
1177 xstdout = 1;
1178 /* and fall... */
1179
1180 case 'f':
1181 /*
1182 * insert temporary filename where
1183 * content should be written
1184 */
1185 snprintf (bp, buflen, "%s", ce->ce_file);
1186 break;
1187
1188 case 's':
1189 /* insert content subtype */
1190 strncpy (bp, ci->ci_subtype, buflen);
1191 break;
1192
1193 case '%':
1194 /* insert character % */
1195 goto raw;
1196
1197 default:
1198 *bp++ = *--cp;
1199 *bp = '\0';
1200 buflen--;
1201 continue;
1202 }
1203 len = strlen (bp);
1204 bp += len;
1205 buflen -= len;
1206 } else {
1207 raw:
1208 *bp++ = *cp;
1209 *bp = '\0';
1210 buflen--;
1211 }
1212 }
1213
1214 if (verbosw)
1215 printf ("composing content %s/%s from command\n\t%s\n",
1216 ci->ci_type, ci->ci_subtype, buffer);
1217
1218 fflush (stdout); /* not sure if need for -noverbose */
1219
1220 vec[0] = "/bin/sh";
1221 vec[1] = "-c";
1222 vec[2] = buffer;
1223 vec[3] = NULL;
1224
1225 if ((out = fopen (ce->ce_file, "w")) == NULL)
1226 adios (ce->ce_file, "unable to open for writing");
1227
1228 for (i = 0; (child_id = fork()) == NOTOK && i > 5; i++)
1229 sleep (5);
1230 switch (child_id) {
1231 case NOTOK:
1232 adios ("fork", "unable to fork");
1233 /* NOTREACHED */
1234
1235 case OK:
1236 if (!xstdout)
1237 dup2 (fileno (out), 1);
1238 close (fileno (out));
1239 execvp ("/bin/sh", vec);
1240 fprintf (stderr, "unable to exec ");
1241 perror ("/bin/sh");
1242 _exit (-1);
1243 /* NOTREACHED */
1244
1245 default:
1246 fclose (out);
1247 if (pidXwait(child_id, NULL))
1248 done (1);
1249 break;
1250 }
1251 }
1252
1253 /* Check size of file */
1254 if (listsw && ct->c_end == 0L) {
1255 struct stat st;
1256
1257 if (stat (ce->ce_file, &st) != NOTOK)
1258 ct->c_end = (long) st.st_size;
1259 }
1260 break;
1261 }
1262
1263 return OK;
1264 }
1265
1266
1267 /*
1268 * Scan the content.
1269 *
1270 * 1) choose a transfer encoding.
1271 * 2) check for clashes with multipart boundary string.
1272 * 3) for text content, figure out which character set is being used.
1273 *
1274 * If there is a clash with one of the contents and the multipart boundary,
1275 * this function will exit with NOTOK. This will cause the scanning process
1276 * to be repeated with a different multipart boundary. It is possible
1277 * (although highly unlikely) that this scan will be repeated multiple times.
1278 */
1279
1280 static int
1281 scan_content (CT ct, size_t maxunencoded)
1282 {
1283 int len;
1284 int check8bit = 0, contains8bit = 0; /* check if contains 8bit data */
1285 int checklinelen = 0, linelen = 0; /* check for long lines */
1286 int checkllinelen = 0; /* check for extra-long lines */
1287 int checkboundary = 0, boundaryclash = 0; /* check if clashes with multipart boundary */
1288 int checklinespace = 0, linespace = 0; /* check if any line ends with space */
1289 char *cp = NULL, buffer[BUFSIZ];
1290 struct text *t = NULL;
1291 FILE *in = NULL;
1292 CE ce = &ct->c_cefile;
1293
1294 /*
1295 * handle multipart by scanning all subparts
1296 * and then checking their encoding.
1297 */
1298 if (ct->c_type == CT_MULTIPART) {
1299 struct multipart *m = (struct multipart *) ct->c_ctparams;
1300 struct part *part;
1301
1302 /* initially mark the domain of enclosing multipart as 7bit */
1303 ct->c_encoding = CE_7BIT;
1304
1305 for (part = m->mp_parts; part; part = part->mp_next) {
1306 CT p = part->mp_part;
1307
1308 if (scan_content (p, maxunencoded) == NOTOK) /* choose encoding for subpart */
1309 return NOTOK;
1310
1311 /* if necessary, enlarge encoding for enclosing multipart */
1312 if (p->c_encoding == CE_BINARY)
1313 ct->c_encoding = CE_BINARY;
1314 if (p->c_encoding == CE_8BIT && ct->c_encoding != CE_BINARY)
1315 ct->c_encoding = CE_8BIT;
1316 }
1317
1318 return OK;
1319 }
1320
1321 /*
1322 * Decide what to check while scanning this content. Note that
1323 * for text content we always check for 8bit characters if the
1324 * charset is unspecified, because that controls whether or not the
1325 * character set is us-ascii or retrieved from the locale.
1326 */
1327
1328 if (ct->c_type == CT_TEXT) {
1329 t = (struct text *) ct->c_ctparams;
1330 if (t->tx_charset == CHARSET_UNSPECIFIED)
1331 check8bit = 1;
1332 }
1333
1334 switch (ct->c_reqencoding) {
1335 case CE_8BIT:
1336 checkllinelen = 1;
1337 checkboundary = 1;
1338 break;
1339 case CE_QUOTED:
1340 checkboundary = 1;
1341 break;
1342 case CE_BASE64:
1343 break;
1344 case CE_UNKNOWN:
1345 /* Use the default rules based on content-type */
1346 switch (ct->c_type) {
1347 case CT_TEXT:
1348 checkboundary = 1;
1349 checklinelen = 1;
1350 if (ct->c_subtype == TEXT_PLAIN) {
1351 checklinespace = 0;
1352 } else {
1353 checklinespace = 1;
1354 }
1355 break;
1356
1357 case CT_APPLICATION:
1358 check8bit = 1;
1359 checklinelen = 1;
1360 checklinespace = 1;
1361 checkboundary = 1;
1362 break;
1363
1364 case CT_MESSAGE:
1365 check8bit = 0;
1366 checklinelen = 0;
1367 checklinespace = 0;
1368
1369 /* don't check anything for message/external */
1370 if (ct->c_subtype == MESSAGE_EXTERNAL)
1371 checkboundary = 0;
1372 else
1373 checkboundary = 1;
1374 break;
1375
1376 case CT_AUDIO:
1377 case CT_IMAGE:
1378 case CT_VIDEO:
1379 /*
1380 * Don't check anything for these types,
1381 * since we are forcing use of base64, unless
1382 * the content-type was specified by a mhbuild directive.
1383 */
1384 check8bit = 0;
1385 checklinelen = 0;
1386 checklinespace = 0;
1387 checkboundary = 0;
1388 break;
1389 }
1390 }
1391
1392 /*
1393 * Scan the unencoded content
1394 */
1395 if (check8bit || checklinelen || checklinespace || checkboundary ||
1396 checkllinelen) {
1397 if ((in = fopen (ce->ce_file, "r")) == NULL)
1398 adios (ce->ce_file, "unable to open for reading");
1399 len = strlen (prefix);
1400
1401 while (fgets (buffer, sizeof(buffer) - 1, in)) {
1402 /*
1403 * Check for 8bit data.
1404 */
1405 if (check8bit) {
1406 for (cp = buffer; *cp; cp++) {
1407 if (!isascii ((unsigned char) *cp)) {
1408 contains8bit = 1;
1409 check8bit = 0; /* no need to keep checking */
1410 }
1411 }
1412 }
1413
1414 /*
1415 * Check line length.
1416 */
1417 if (checklinelen && (strlen (buffer) > maxunencoded + 1)) {
1418 linelen = 1;
1419 checklinelen = 0; /* no need to keep checking */
1420 }
1421
1422 /*
1423 * RFC 5322 specifies that a message cannot contain a line
1424 * greater than 998 characters (excluding the CRLF). If we
1425 * get one of those lines and linelen is NOT set, then abort.
1426 */
1427
1428 if (checkllinelen && !linelen &&
1429 (strlen(buffer) > MAXLONGLINE + 1)) {
1430 adios(NULL, "Line in content exceeds maximum line limit (%d)",
1431 MAXLONGLINE);
1432 }
1433
1434 /*
1435 * Check if line ends with a space.
1436 */
1437 if (checklinespace && (cp = buffer + strlen (buffer) - 2) > buffer && isspace ((unsigned char) *cp)) {
1438 linespace = 1;
1439 checklinespace = 0; /* no need to keep checking */
1440 }
1441
1442 /*
1443 * Check if content contains a line that clashes
1444 * with our standard boundary for multipart messages.
1445 */
1446 if (checkboundary && buffer[0] == '-' && buffer[1] == '-') {
1447 for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1448 if (!isspace ((unsigned char) *cp))
1449 break;
1450 *++cp = '\0';
1451 if (!strncmp(buffer + 2, prefix, len) && isdigit((unsigned char) buffer[2 + len])) {
1452 boundaryclash = 1;
1453 checkboundary = 0; /* no need to keep checking */
1454 }
1455 }
1456 }
1457 fclose (in);
1458 }
1459
1460 /*
1461 * If the content is text and didn't specify a character set,
1462 * we need to figure out which one was used.
1463 */
1464
1465 if (ct->c_type == CT_TEXT) {
1466 t = (struct text *) ct->c_ctparams;
1467 if (t->tx_charset == CHARSET_UNSPECIFIED) {
1468 CI ci = &ct->c_ctinfo;
1469 char **ap, **ep;
1470
1471 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++)
1472 continue;
1473
1474 if (contains8bit) {
1475 *ap = concat ("charset=", write_charset_8bit(), NULL);
1476 } else {
1477 *ap = add ("charset=us-ascii", NULL);
1478 }
1479 t->tx_charset = CHARSET_SPECIFIED;
1480
1481 cp = strchr(*ap++, '=');
1482 *ap = NULL;
1483 *cp++ = '\0';
1484 *ep = cp;
1485 }
1486 }
1487
1488 /*
1489 * Decide which transfer encoding to use.
1490 */
1491
1492 if (ct->c_reqencoding != CE_UNKNOWN)
1493 ct->c_encoding = ct->c_reqencoding;
1494 else
1495 switch (ct->c_type) {
1496 case CT_TEXT:
1497 if (contains8bit && !linelen && !linespace && !checksw)
1498 ct->c_encoding = CE_8BIT;
1499 else if (contains8bit || linelen || linespace || checksw)
1500 ct->c_encoding = CE_QUOTED;
1501 else
1502 ct->c_encoding = CE_7BIT;
1503 break;
1504
1505 case CT_APPLICATION:
1506 /* For application type, use base64, except when postscript */
1507 if (contains8bit || linelen || linespace || checksw)
1508 ct->c_encoding = (ct->c_subtype == APPLICATION_POSTSCRIPT)
1509 ? CE_QUOTED : CE_BASE64;
1510 else
1511 ct->c_encoding = CE_7BIT;
1512 break;
1513
1514 case CT_MESSAGE:
1515 ct->c_encoding = CE_7BIT;
1516 break;
1517
1518 case CT_AUDIO:
1519 case CT_IMAGE:
1520 case CT_VIDEO:
1521 /* For audio, image, and video contents, just use base64 */
1522 ct->c_encoding = CE_BASE64;
1523 break;
1524 }
1525
1526 return (boundaryclash ? NOTOK : OK);
1527 }
1528
1529
1530 /*
1531 * Scan the content structures, and build header
1532 * fields that will need to be output into the
1533 * message.
1534 */
1535
1536 static int
1537 build_headers (CT ct)
1538 {
1539 int cc, mailbody, extbody, len;
1540 char **ap, **ep;
1541 char *np, *vp, buffer[BUFSIZ];
1542 CI ci = &ct->c_ctinfo;
1543
1544 /*
1545 * If message is type multipart, then add the multipart
1546 * boundary to the list of attribute/value pairs.
1547 */
1548 if (ct->c_type == CT_MULTIPART) {
1549 char *cp;
1550 static int level = 0; /* store nesting level */
1551
1552 ap = ci->ci_attrs;
1553 ep = ci->ci_values;
1554 snprintf (buffer, sizeof(buffer), "boundary=%s%d", prefix, level++);
1555 cp = strchr(*ap++ = add (buffer, NULL), '=');
1556 *ap = NULL;
1557 *cp++ = '\0';
1558 *ep = cp;
1559 }
1560
1561 /*
1562 * Skip the output of Content-Type, parameters, content
1563 * description and disposition, and Content-ID if the
1564 * content is of type "message" and the rfc934 compatibility
1565 * flag is set (which means we are inside multipart/digest
1566 * and the switch -rfc934mode was given).
1567 */
1568 if (ct->c_type == CT_MESSAGE && ct->c_rfc934)
1569 goto skip_headers;
1570
1571 /*
1572 * output the content type and subtype
1573 */
1574 np = add (TYPE_FIELD, NULL);
1575 vp = concat (" ", ci->ci_type, "/", ci->ci_subtype, NULL);
1576
1577 /* keep track of length of line */
1578 len = strlen (TYPE_FIELD) + strlen (ci->ci_type)
1579 + strlen (ci->ci_subtype) + 3;
1580
1581 extbody = ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_EXTERNAL;
1582 mailbody = extbody && ((struct exbody *) ct->c_ctparams)->eb_body;
1583
1584 /*
1585 * Append the attribute/value pairs to
1586 * the end of the Content-Type line.
1587 */
1588 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++) {
1589 if (mailbody && !strcasecmp (*ap, "body"))
1590 continue;
1591
1592 vp = add (";", vp);
1593 len++;
1594
1595 /*
1596 * According to RFC 2017, if we have a URL longer than 40 characters
1597 * we have to break it across multiple lines
1598 */
1599
1600 if (extbody && strcasecmp (*ap, "url") == 0) {
1601 char *value = *ep;
1602
1603 /* 7 here refers to " url=\"\"" */
1604 if (len + 1 + (cc = (min(MAXURLTOKEN, strlen(value)) + 7)) >=
1605 CPERLIN) {
1606 vp = add ("\n\t", vp);
1607 len = 8;
1608 } else {
1609 vp = add (" ", vp);
1610 len++;
1611 }
1612
1613 vp = add ("url=\"", vp);
1614 len += 5;
1615
1616 while (strlen(value) > MAXURLTOKEN) {
1617 strncpy(buffer, value, MAXURLTOKEN);
1618 buffer[MAXURLTOKEN] = '\0';
1619 vp = add (buffer, vp);
1620 vp = add ("\n\t", vp);
1621 value += MAXURLTOKEN;
1622 len = 8;
1623 }
1624
1625 vp = add (value, vp);
1626 vp = add ("\"", vp);
1627 len += strlen(value) + 1;
1628 continue;
1629 }
1630
1631 snprintf (buffer, sizeof(buffer), "%s=\"%s\"", *ap, *ep);
1632 if (len + 1 + (cc = strlen (buffer)) >= CPERLIN) {
1633 vp = add ("\n\t", vp);
1634 len = 8;
1635 } else {
1636 vp = add (" ", vp);
1637 len++;
1638 }
1639 vp = add (buffer, vp);
1640 len += cc;
1641 }
1642
1643 /*
1644 * Append any RFC-822 comment to the end of
1645 * the Content-Type line.
1646 */
1647 if (ci->ci_comment) {
1648 snprintf (buffer, sizeof(buffer), "(%s)", ci->ci_comment);
1649 if (len + 1 + (cc = 2 + strlen (ci->ci_comment)) >= CPERLIN) {
1650 vp = add ("\n\t", vp);
1651 len = 8;
1652 } else {
1653 vp = add (" ", vp);
1654 len++;
1655 }
1656 vp = add (buffer, vp);
1657 len += cc;
1658 }
1659 vp = add ("\n", vp);
1660 add_header (ct, np, vp);
1661
1662 /*
1663 * output the Content-ID, unless disabled by -nocontentid
1664 */
1665 if (contentidsw && ct->c_id) {
1666 np = add (ID_FIELD, NULL);
1667 vp = concat (" ", ct->c_id, NULL);
1668 add_header (ct, np, vp);
1669 }
1670
1671 /*
1672 * output the Content-Description
1673 */
1674 if (ct->c_descr) {
1675 np = add (DESCR_FIELD, NULL);
1676 vp = concat (" ", ct->c_descr, NULL);
1677 add_header (ct, np, vp);
1678 }
1679
1680 /*
1681 * output the Content-Disposition
1682 */
1683 if (ct->c_dispo) {
1684 np = add (DISPO_FIELD, NULL);
1685 vp = concat (" ", ct->c_dispo, NULL);
1686 add_header (ct, np, vp);
1687 }
1688
1689 skip_headers:
1690 /*
1691 * If this is the internal content structure for a
1692 * "message/external", then we are done with the
1693 * headers (since it has no body).
1694 */
1695 if (ct->c_ctexbody)
1696 return OK;
1697
1698 /*
1699 * output the Content-MD5
1700 */
1701 if (checksw) {
1702 np = add (MD5_FIELD, NULL);
1703 vp = calculate_digest (ct, (ct->c_encoding == CE_QUOTED) ? 1 : 0);
1704 add_header (ct, np, vp);
1705 }
1706
1707 /*
1708 * output the Content-Transfer-Encoding
1709 */
1710 switch (ct->c_encoding) {
1711 case CE_7BIT:
1712 /* Nothing to output */
1713 break;
1714
1715 case CE_8BIT:
1716 if (ct->c_type == CT_MESSAGE)
1717 adios (NULL, "internal error, invalid encoding");
1718
1719 np = add (ENCODING_FIELD, NULL);
1720 vp = concat (" ", "8bit", "\n", NULL);
1721 add_header (ct, np, vp);
1722 break;
1723
1724 case CE_QUOTED:
1725 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1726 adios (NULL, "internal error, invalid encoding");
1727
1728 np = add (ENCODING_FIELD, NULL);
1729 vp = concat (" ", "quoted-printable", "\n", NULL);
1730 add_header (ct, np, vp);
1731 break;
1732
1733 case CE_BASE64:
1734 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1735 adios (NULL, "internal error, invalid encoding");
1736
1737 np = add (ENCODING_FIELD, NULL);
1738 vp = concat (" ", "base64", "\n", NULL);
1739 add_header (ct, np, vp);
1740 break;
1741
1742 case CE_BINARY:
1743 if (ct->c_type == CT_MESSAGE)
1744 adios (NULL, "internal error, invalid encoding");
1745
1746 np = add (ENCODING_FIELD, NULL);
1747 vp = concat (" ", "binary", "\n", NULL);
1748 add_header (ct, np, vp);
1749 break;
1750
1751 default:
1752 adios (NULL, "unknown transfer encoding in content");
1753 break;
1754 }
1755
1756 /*
1757 * Additional content specific header processing
1758 */
1759 switch (ct->c_type) {
1760 case CT_MULTIPART:
1761 {
1762 struct multipart *m;
1763 struct part *part;
1764
1765 m = (struct multipart *) ct->c_ctparams;
1766 for (part = m->mp_parts; part; part = part->mp_next) {
1767 CT p;
1768
1769 p = part->mp_part;
1770 build_headers (p);
1771 }
1772 }
1773 break;
1774
1775 case CT_MESSAGE:
1776 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1777 struct exbody *e;
1778
1779 e = (struct exbody *) ct->c_ctparams;
1780 build_headers (e->eb_content);
1781 }
1782 break;
1783
1784 default:
1785 /* Nothing to do */
1786 break;
1787 }
1788
1789 return OK;
1790 }
1791
1792
1793 static char nib2b64[0x40+1] =
1794 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1795
1796 static char *
1797 calculate_digest (CT ct, int asciiP)
1798 {
1799 int cc;
1800 char buffer[BUFSIZ], *vp, *op;
1801 unsigned char *dp;
1802 unsigned char digest[16];
1803 unsigned char outbuf[25];
1804 MD5_CTX mdContext;
1805 CE ce = &ct->c_cefile;
1806 char *infilename = ce->ce_file ? ce->ce_file : ct->c_file;
1807 FILE *in;
1808
1809 /* open content */
1810 if ((in = fopen (infilename, "r")) == NULL)
1811 adios (infilename, "unable to open for reading");
1812
1813 /* Initialize md5 context */
1814 MD5Init (&mdContext);
1815
1816 /* calculate md5 message digest */
1817 if (asciiP) {
1818 while (fgets (buffer, sizeof(buffer) - 1, in)) {
1819 char c, *cp;
1820
1821 cp = buffer + strlen (buffer) - 1;
1822 if ((c = *cp) == '\n')
1823 *cp = '\0';
1824
1825 MD5Update (&mdContext, (unsigned char *) buffer,
1826 (unsigned int) strlen (buffer));
1827
1828 if (c == '\n')
1829 MD5Update (&mdContext, (unsigned char *) "\r\n", 2);
1830 }
1831 } else {
1832 while ((cc = fread (buffer, sizeof(*buffer), sizeof(buffer), in)) > 0)
1833 MD5Update (&mdContext, (unsigned char *) buffer, (unsigned int) cc);
1834 }
1835
1836 /* md5 finalization. Write digest and zero md5 context */
1837 MD5Final (digest, &mdContext);
1838
1839 /* close content */
1840 fclose (in);
1841
1842 /* print debugging info */
1843 if (debugsw) {
1844 unsigned char *ep;
1845
1846 fprintf (stderr, "MD5 digest=");
1847 for (ep = (dp = digest) + sizeof(digest) / sizeof(digest[0]);
1848 dp < ep; dp++)
1849 fprintf (stderr, "%02x", *dp & 0xff);
1850 fprintf (stderr, "\n");
1851 }
1852
1853 /* encode the digest using base64 */
1854 for (dp = digest, op = (char *) outbuf,
1855 cc = sizeof(digest) / sizeof(digest[0]);
1856 cc > 0; cc -= 3, op += 4) {
1857 unsigned long bits;
1858 char *bp;
1859
1860 bits = (*dp++ & 0xff) << 16;
1861 if (cc > 1) {
1862 bits |= (*dp++ & 0xff) << 8;
1863 if (cc > 2)
1864 bits |= *dp++ & 0xff;
1865 }
1866
1867 for (bp = op + 4; bp > op; bits >>= 6)
1868 *--bp = nib2b64[bits & 0x3f];
1869 if (cc < 3) {
1870 *(op + 3) = '=';
1871 if (cc < 2)
1872 *(op + 2) = '=';
1873 }
1874 }
1875
1876 /* null terminate string */
1877 outbuf[24] = '\0';
1878
1879 /* now make copy and return string */
1880 vp = concat (" ", outbuf, "\n", NULL);
1881 return vp;
1882 }
1883
1884 /*
1885 * Set things up for the content structure for file "filename" that
1886 * we want to attach
1887 */
1888
1889 static void
1890 setup_attach_content(CT ct, char *filename)
1891 {
1892 char *type, **ap, **ep, *simplename = r1bindex(filename, '/');
1893 struct str2init *s2i;
1894
1895 if (! (type = mime_type(filename))) {
1896 adios(NULL, "Unable to determine MIME type of \"%s\"", filename);
1897 }
1898
1899 /*
1900 * Parse the Content-Type. get_ctinfo() parses MIME parameters, but
1901 * since we're just feeding it a MIME type we have to add those ourself.
1902 * Map that to a valid content-type label and call any initialization
1903 * function.
1904 */
1905
1906 if (get_ctinfo(type, ct, 0) == NOTOK)
1907 done(1);
1908
1909 free(type);
1910
1911 for (s2i = str2cts; s2i->si_key; s2i++)
1912 if (strcasecmp(ct->c_ctinfo.ci_type, s2i->si_key) == 0)
1913 break;
1914 if (!s2i->si_key && !uprf(ct->c_ctinfo.ci_type, "X-"))
1915 s2i++;
1916
1917 /*
1918 * Make sure the type isn't incompatible with what we can handle
1919 */
1920
1921 switch (ct->c_type = s2i->si_val) {
1922 case CT_MULTIPART:
1923 adios (NULL, "multipart types must be specified by mhbuild directives");
1924 /* NOTREACHED */
1925
1926 case CT_MESSAGE:
1927 if (strcasecmp(ct->c_ctinfo.ci_subtype, "partial") == 0)
1928 adios(NULL, "Sorry, %s/%s isn't supported", ct->c_ctinfo.ci_type,
1929 ct->c_ctinfo.ci_subtype);
1930 if (strcasecmp(ct->c_ctinfo.ci_subtype, "external-body") == 0)
1931 adios(NULL, "external-body messages must be specified "
1932 "by mhbuild directives");
1933 /* Fall through */
1934
1935 default:
1936 /*
1937 * This sets the subtype, if it's significant
1938 */
1939 if ((ct->c_ctinitfnx = s2i->si_init))
1940 (*ct->c_ctinitfnx)(ct);
1941 break;
1942 }
1943
1944 /*
1945 * Feed in a few attributes; specifically, the name attribute, the
1946 * content-description, and the content-disposition.
1947 */
1948
1949 for (ap = ct->c_ctinfo.ci_attrs, ep = ct->c_ctinfo.ci_values; *ap;
1950 ap++, ep++) {
1951 if (strcasecmp(*ap, "name") == 0) {
1952 if (*ep)
1953 free(*ep);
1954 *ep = getcpy(simplename);
1955 break;
1956 }
1957 }
1958
1959 if (*ap == NULL) {
1960 *ap = getcpy("name");
1961 *ep = getcpy(simplename);
1962 }
1963
1964 ct->c_descr = getcpy(simplename);
1965 ct->c_descr = add("\n", ct->c_descr);
1966 ct->c_cefile.ce_file = getcpy(filename);
1967
1968 /*
1969 * If it's a text/calendar, we need to make sure it's an inline,
1970 * otherwise it won't work with some calendar programs. Otherwise
1971 * assume attachment
1972 */
1973
1974 if (strcasecmp(ct->c_ctinfo.ci_type, "text") == 0 &&
1975 strcasecmp(ct->c_ctinfo.ci_subtype, "calendar") == 0) {
1976 ct->c_dispo = getcpy("inline; filename=\"");
1977 } else {
1978 ct->c_dispo = getcpy("attachment; filename=\"");
1979 }
1980
1981 ct->c_dispo = add(simplename, ct->c_dispo);
1982 ct->c_dispo = add("\"\n", ct->c_dispo);
1983 }