2 ** mhbuild.c -- expand/translate MIME composition files
4 ** This code is Copyright (c) 2002, by the authors of nmh. See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
10 ** This code was originally part of mhn.c. I split it into
11 ** a separate program (mhbuild.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.
21 #include <h/mhparse.h>
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
34 static struct swit switches[] = {
48 char *version=VERSION;
51 ** Directory to place tmp files. This must
52 ** be set before these routines are called.
58 static char prefix[] = "----- =_aaaaaaaaaa";
66 int make_intermediates(char *);
67 void content_error(char *, CT, char *, ...);
70 void free_content(CT);
72 void free_encoding(CT, int);
77 static int init_decoded_content(CT);
78 static char *fgetstr(char *, int, FILE *);
79 static int user_content(FILE *, char *, char *, CT *);
80 static void set_id(CT, int);
81 static int compose_content(CT);
82 static int scan_content(CT);
83 static int build_headers(CT);
84 static CT build_mime(char *);
93 static char infile[BUFSIZ];
94 static int unlink_infile = 0;
96 static char outfile[BUFSIZ];
97 static int unlink_outfile = 0;
102 int output_message(CT, char *);
103 int output_message_fp(CT, FILE *, char*);
106 void set_endian(void);
109 void free_content(CT);
113 main(int argc, char **argv)
115 char *cp, buf[BUFSIZ];
116 char buffer[BUFSIZ], *compfile = NULL;
117 char **argp, **arguments;
122 if (atexit(unlink_done) != 0) {
123 adios(EX_OSERR, NULL, "atexit failed");
126 setlocale(LC_ALL, "");
127 invo_name = mhbasename(argv[0]);
129 /* read user profile/context */
132 arguments = getarguments(invo_name, argc, argv, 1);
135 while ((cp = *argp++)) {
136 if (cp[0] == '-' && cp[1] == '\0') {
138 adios(EX_USAGE, NULL, "cannot specify both standard input and a file");
141 verbosw = 0; /* turn off -verbose listings */
145 switch (smatch(++cp, switches)) {
147 ambigsw(cp, switches);
150 adios(EX_USAGE, NULL, "-%s unknown", cp);
153 snprintf(buf, sizeof(buf), "%s [switches] file", invo_name);
154 print_help(buf, switches, 1);
155 exit(argc == 2 ? EX_OK : EX_USAGE);
157 print_version(invo_name);
158 exit(argc == 2 ? EX_OK : EX_USAGE);
172 adios(EX_USAGE, NULL, "only one composition file allowed");
180 ** Check if we've specified an additional profile
182 if ((cp = getenv("MHBUILD"))) {
183 if ((fp = fopen(cp, "r"))) {
184 readconfig((struct node **) 0, fp, cp, 0);
187 admonish("", "unable to read $MHBUILD profile (%s)",
193 ** Read the standard profile setup
195 if ((fp = fopen(cp = etcpath("mhn.defaults"), "r"))) {
196 readconfig((struct node **) 0, fp, cp, 0);
201 ** Check for storage directory. If defined, we
202 ** will store temporary files there. Else we
203 ** store them in standard nmh directory.
205 if ((cp = context_find(nmhstorage)) && *cp)
206 tmp = concat(cp, "/", invo_name, NULL);
208 tmp = mh_xstrdup(toabsdir(invo_name));
210 /* Check if we have a file to process */
212 adios(EX_USAGE, NULL, "need to specify a %s composition file",
216 ** Process the composition file from standard input.
218 if (compfile[0] == '-' && compfile[1] == '\0') {
219 /* copy standard input to temporary file */
220 strncpy(infile, m_mktemp(invo_name, NULL, &fp),
222 while (fgets(buffer, BUFSIZ, stdin))
227 /* build the content structures for MIME message */
228 ct = build_mime(infile);
230 /* output MIME message to this temporary file */
231 strncpy(outfile, m_mktemp(invo_name, NULL, &fp_out),
235 /* output the message */
236 output_message_fp(ct, fp_out, outfile);
239 /* output the temp file to standard output */
240 if ((fp = fopen(outfile, "r")) == NULL)
241 adios(EX_IOERR, outfile, "unable to open");
242 while (fgets(buffer, BUFSIZ, fp))
243 fputs(buffer, stdout);
257 ** Process the composition file from a file.
260 /* build the content structures for MIME message */
261 ct = build_mime(compfile);
263 /* output MIME message to this temporary file */
264 strncpy(outfile, m_mktemp2(compfile, invo_name, NULL, &fp_out),
268 /* output the message */
269 output_message_fp(ct, fp_out, outfile);
272 /* Rename composition draft */
273 snprintf(buffer, sizeof(buffer), "%s.orig", compfile);
274 if (rename(compfile, buffer) == NOTOK) {
275 adios(EX_IOERR, buffer, "unable to rename draft %s to", compfile);
278 /* Rename output file to take its place */
279 if (rename(outfile, compfile) == NOTOK) {
280 advise(compfile, "unable to rename output %s to", outfile);
281 rename(buffer, compfile);
295 ** Check if we need to remove stray temporary files.
300 if (unlink_outfile) {
306 ** Main routine for translating composition file
307 ** into valid MIME message. It translates the draft
308 ** into a content structure (actually a tree of content
309 ** structures). This message then can be manipulated
310 ** in various ways, including being output via
314 build_mime(char *infile)
317 struct field f = {{0}};
329 /* open the composition draft */
330 if ((in = fopen(infile, "r")) == NULL) {
331 adios(EX_IOERR, infile, "unable to open for reading");
335 ** Allocate space for primary (outside) content
337 ct = mh_xcalloc(1, sizeof(*ct));
340 ** Allocate structure for handling decoded content
341 ** for this part. We don't really need this, but
342 ** allocate it to remain consistent.
344 init_decoded_content(ct);
347 ** Parse some of the header fields in the composition
348 ** draft into the linked list of header fields for
349 ** the new MIME message.
351 for (compnum = 1, state = FLD2;;) {
352 switch (state = m_getfld2(state, &f, in)) {
358 /* abort if draft has Mime-Version header field */
359 if (!mh_strcasecmp(f.name, VRSN_FIELD)) {
360 adios(EX_CONFIG, NULL, "draft shouldn't contain %s: field", VRSN_FIELD);
364 ** abort if draft has Content-Transfer-Encoding
367 if (!mh_strcasecmp(f.name, ENCODING_FIELD)) {
368 adios(EX_CONFIG, NULL, "draft shouldn't contain %s: field", ENCODING_FIELD);
371 /* ignore any Content-Type fields in the header */
372 if (!mh_strcasecmp(f.name, TYPE_FIELD)) {
376 /* add the header data to the list */
377 add_header(ct, mh_xstrdup(f.name), mh_xstrdup(f.value));
382 fseek(in, (long) (-strlen(f.value)), SEEK_CUR);
386 adios(EX_CONFIG, NULL, "draft has empty body -- no directives!");
391 adios(EX_CONFIG, NULL, "message format error in component #%d",
395 adios(EX_SOFTWARE, NULL, "getfld() returned %d", state);
401 ** Iterate through the list of headers and call the function to
402 ** MIME-ify them if required.
404 for (hp = ct->c_first_hf; hp != NULL; hp = hp->next) {
405 if (encode_rfc2047(hp->name, &hp->value, NULL)) {
406 adios(EX_DATAERR, NULL, "Unable to encode header \"%s\"", hp->name);
411 ** Now add the MIME-Version header field
412 ** to the list of header fields.
414 np = mh_xstrdup(VRSN_FIELD);
415 vp = concat(" ", VRSN_VALUE, "\n", NULL);
416 add_header(ct, np, vp);
419 ** We initially assume we will find multiple contents in the
420 ** draft. So create a multipart/mixed content to hold everything.
421 ** We can remove this later, if it is not needed.
423 if (get_ctinfo("multipart/mixed", ct, 0) == NOTOK) {
426 ct->c_type = CT_MULTIPART;
427 ct->c_subtype = MULTI_MIXED;
428 ct->c_file = mh_xstrdup(infile);
430 m = (struct multipart *) mh_xcalloc(1, sizeof(*m));
431 ct->c_ctparams = (void *) m;
435 ** read and parse the composition file
436 ** and the directives it contains.
438 while (fgetstr(buf, sizeof(buf) - 1, in)) {
442 if (user_content(in, infile, buf, &p) == DONE) {
443 admonish(NULL, "ignoring spurious #end");
449 part = mh_xcalloc(1, sizeof(*part));
456 ** close the composition draft since
457 ** it's not needed any longer.
461 /* check if any contents were found */
463 adios(EX_OSERR, NULL, "no content directives found");
466 ** If only one content was found, then remove and
467 ** free the outer multipart content.
469 if (!m->mp_parts->mp_next) {
472 p = m->mp_parts->mp_part;
473 m->mp_parts->mp_part = NULL;
475 /* move header fields */
476 p->c_first_hf = ct->c_first_hf;
477 p->c_last_hf = ct->c_last_hf;
478 ct->c_first_hf = NULL;
479 ct->c_last_hf = NULL;
488 ** Fill out, or expand directives. Parse and execute
489 ** commands specified by profile composition strings.
493 if ((cp = strchr(prefix, 'a')) == NULL)
494 adios(EX_SOFTWARE, NULL, "internal error(4)");
497 ** Scan the contents. Choose a transfer encoding, and
498 ** check if prefix for multipart boundary clashes with
499 ** any of the contents.
501 while (scan_content(ct) == NOTOK) {
506 adios(EX_SOFTWARE, NULL, "giving up trying to find a unique delimiter string");
512 /* Build the rest of the header field structures */
520 ** Set up structures for placing unencoded
521 ** content when building parts.
525 init_decoded_content(CT ct)
529 ce = mh_xcalloc(1, sizeof(*ce));
532 ct->c_ceopenfnx = open7Bit; /* since unencoded */
533 ct->c_ceclosefnx = close_encoding;
534 ct->c_cesizefnx = NULL; /* since unencoded */
541 fgetstr(char *s, int n, FILE *stream)
545 for (ep = (cp = s) + n; cp < ep; ) {
548 if (!fgets(cp, n, stream))
549 return (cp != s ? s : NULL);
550 if (cp == s && *cp != '#')
553 cp += (i = strlen(cp)) - 1;
554 if (i <= 1 || *cp-- != '\n' || *cp != '\\')
565 ** Parse the composition draft for text and directives.
566 ** Do initial setup of Content structure.
570 user_content(FILE *in, char *file, char *buf, CT *ctp)
578 struct str2init *s2i;
583 if (buf[0] == '\n' || strcmp(buf, "#\n") == 0) {
588 /* allocate basic Content structure */
589 ct = mh_xcalloc(1, sizeof(*ct));
592 /* allocate basic structure for handling decoded content */
593 init_decoded_content(ct);
600 ** Handle inline text. Check if line
601 ** is one of the following forms:
603 ** 1) doesn't begin with '#' (implicit directive)
604 ** 2) begins with "##" (implicit directive)
605 ** 3) begins with "#<"
607 if (buf[0] != '#' || buf[1] == '#' || buf[1] == '<') {
611 char content[BUFSIZ];
615 cp = m_mktemp2(NULL, invo_name, NULL, &out);
617 adios(EX_CANTCREAT, "mhbuild", "unable to create temporary file");
619 /* use a temp file to collect the plain text lines */
620 ce->ce_file = mh_xstrdup(cp);
623 if (buf[0] == '#' && buf[1] == '<') {
624 strncpy(content, buf + 2, sizeof(content));
631 /* the directive is implicit */
632 strncpy(content, "text/plain", sizeof(content));
634 strncpy(buffer, buf[0] != '#' ? buf : buf + 1, sizeof(buffer));
638 if (headers >= 0 && uprf(buffer, DESCR_FIELD) &&
639 buffer[i=strlen(DESCR_FIELD)] == ':') {
643 ct->c_descr = add(buffer + i + 1, ct->c_descr);
644 if (!fgetstr(buffer, sizeof(buffer) - 1, in))
645 adios(EX_DATAERR, NULL, "end-of-file after %s: field in plaintext", DESCR_FIELD);
653 adios(EX_DATAERR, NULL, "#-directive after %s: field in plaintext", DESCR_FIELD);
661 if (headers >= 0 && uprf(buffer, DISPO_FIELD)
662 && buffer[i = strlen(DISPO_FIELD)] == ':') {
666 ct->c_dispo = add(buffer + i + 1, ct->c_dispo);
667 if (!fgetstr(buffer, sizeof(buffer) - 1, in))
668 adios(EX_DATAERR, NULL, "end-of-file after %s: field in plaintext", DISPO_FIELD);
676 adios(EX_DATAERR, NULL, "#-directive after %s: field in plaintext", DISPO_FIELD);
684 if (headers != 1 || buffer[0] != '\n')
690 if ((cp = fgetstr(buffer, sizeof(buffer) - 1, in))
693 if (buffer[0] == '#') {
696 if (buffer[1] != '#')
698 for (cp = (bp = buffer) + 1; *cp; cp++)
706 /* parse content type */
707 if (get_ctinfo(content, ct, inlineD) == NOTOK)
710 for (s2i = str2cts; s2i->si_key; s2i++)
711 if (!mh_strcasecmp(ci->ci_type, s2i->si_key))
713 if (!s2i->si_key && !uprf(ci->ci_type, "X-"))
717 ** check type specified (possibly implicitly)
719 switch (ct->c_type = s2i->si_val) {
721 if (!mh_strcasecmp(ci->ci_subtype, "rfc822")) {
722 ct->c_encoding = CE_7BIT;
727 adios(EX_DATAERR, NULL, "it doesn't make sense to define an in-line %s content",
728 ct->c_type == CT_MESSAGE ? "message" :
734 if ((ct->c_ctinitfnx = s2i->si_init))
735 (*ct->c_ctinitfnx) (ct);
740 fseek(in, pos, SEEK_SET);
745 ** If we've reached this point, the next line
746 ** must be some type of explicit directive.
750 adios(EX_DATAERR, NULL, "The #@ directive i.e. message/external-body "
751 "is not supported anymore.");
754 /* parse directive */
755 if (get_ctinfo(buf+1, ct, 1) == NOTOK)
758 /* check directive against the list of MIME types */
759 for (s2i = str2cts; s2i->si_key; s2i++)
760 if (!mh_strcasecmp(ci->ci_type, s2i->si_key))
764 ** Check if the directive specified a valid type.
765 ** This will happen if it was one of the following forms:
771 adios(EX_DATAERR, NULL, "missing subtype in \"#%s\"", ci->ci_type);
773 switch (ct->c_type = s2i->si_val) {
775 adios(EX_DATAERR, NULL, "use \"#begin ... #end\" instead of \"#%s/%s\"", ci->ci_type, ci->ci_subtype);
779 if (!mh_strcasecmp(ci->ci_subtype, "partial") ||
780 !mh_strcasecmp(ci->ci_subtype,
782 adios(EX_DATAERR, NULL, "sorry, \"#%s/%s\" isn't supported", ci->ci_type, ci->ci_subtype);
785 admonish(NULL, "use \"#forw [+folder] [msgs]\" instead of \"#%s/%s\"", ci->ci_type, ci->ci_subtype);
789 if ((ct->c_ctinitfnx = s2i->si_init))
790 (*ct->c_ctinitfnx) (ct);
794 /* Handle [file] argument */
796 /* check if specifies command to execute */
797 if (*ci->ci_magic == '|' || *ci->ci_magic == '!') {
798 for (cp = ci->ci_magic + 1; isspace(*cp); cp++)
801 adios(EX_DATAERR, NULL, "empty pipe command for #%s directive", ci->ci_type);
803 mh_free0(&(ci->ci_magic));
806 /* record filename of decoded contents */
807 ce->ce_file = ci->ci_magic;
808 if (access(ce->ce_file, R_OK) == NOTOK)
809 adios(EX_IOERR, "reading", "unable to access %s for", ce->ce_file);
816 ** No [file] argument, so check profile for
817 ** method to compose content.
819 snprintf(buffer, sizeof(buffer), "%s-compose-%s/%s",
820 invo_name, ci->ci_type, ci->ci_subtype);
821 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
822 snprintf(buffer, sizeof(buffer), "%s-compose-%s",
823 invo_name, ci->ci_type);
824 if ((cp = context_find(buffer)) == NULL ||
826 content_error(NULL, ct, "don't know how to compose content");
830 ci->ci_magic = mh_xstrdup(cp);
836 ** #forw [+folder] [msgs]
838 if (!mh_strcasecmp(ci->ci_type, "forw")) {
840 char *folder, *arguments[MAXARGS];
846 ap = brkstring(ci->ci_magic, " ", "\n");
847 for (i=0; ap[i] && i<MAXARGS-1; i++) {
848 arguments[i] = ap[i];
853 arguments[0] = seq_cur;
858 /* search the arguments for a folder name */
859 for (ap = arguments; *ap; ap++) {
861 if (*cp == '+' || *cp == '@') {
863 adios(EX_USAGE, NULL, "only one folder per #forw directive");
865 folder = mh_xstrdup(expandfol(cp));
869 /* else, use the current folder */
871 folder = mh_xstrdup(getcurfol());
873 if (!(mp = folder_read(folder)))
874 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
875 for (ap = arguments; *ap; ap++) {
877 if (*cp != '+' && *cp != '@')
878 if (!m_convert(mp, cp))
885 ** If there is more than one message to include, make this
886 ** a content of type "multipart/digest" and insert each message
887 ** as a subpart. If there is only one message, then make this
888 ** a content of type "message/rfc822".
890 if (mp->numsel > 1) {
891 /* we are forwarding multiple messages */
892 if (get_ctinfo("multipart/digest", ct, 0) == NOTOK)
894 ct->c_type = CT_MULTIPART;
895 ct->c_subtype = MULTI_DIGEST;
897 m = mh_xcalloc(1, sizeof(*m));
898 ct->c_ctparams = (void *) m;
901 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
902 if (is_selected(mp, msgnum)) {
907 p = mh_xcalloc(1, sizeof(*p));
908 init_decoded_content(p);
910 if (get_ctinfo("message/rfc822", p, 0)
913 p->c_type = CT_MESSAGE;
914 p->c_subtype = MESSAGE_RFC822;
916 snprintf(buffer, sizeof(buffer),
917 "%s/%d", mp->foldpath,
919 pe->ce_file = mh_xstrdup(buffer);
921 part = mh_xcalloc(1, sizeof(*part));
928 /* we are forwarding one message */
929 if (get_ctinfo("message/rfc822", ct, 0) == NOTOK)
931 ct->c_type = CT_MESSAGE;
932 ct->c_subtype = MESSAGE_RFC822;
935 snprintf(buffer, sizeof(buffer), "%s/%d",
936 mp->foldpath, msgnum);
937 ce->ce_file = mh_xstrdup(buffer);
940 folder_free(mp); /* free folder/message structure */
947 if (!mh_strcasecmp(ci->ci_type, "end")) {
954 ** #begin [ alternative | parallel ]
956 if (!mh_strcasecmp(ci->ci_type, "begin")) {
959 cp = SubMultiPart[vrsn - 1].kv_key;
960 } else if (!mh_strcasecmp(ci->ci_magic, "alternative")) {
961 vrsn = MULTI_ALTERNATE;
962 cp = SubMultiPart[vrsn - 1].kv_key;
963 } else if (!mh_strcasecmp(ci->ci_magic, "parallel")) {
964 vrsn = MULTI_PARALLEL;
965 cp = SubMultiPart[vrsn - 1].kv_key;
966 } else if (uprf(ci->ci_magic, "digest")) {
969 vrsn = MULTI_UNKNOWN;
974 snprintf(buffer, sizeof(buffer), "multipart/%s", cp);
975 if (get_ctinfo(buffer, ct, 0) == NOTOK)
977 ct->c_type = CT_MULTIPART;
978 ct->c_subtype = vrsn;
980 m = mh_xcalloc(1, sizeof(*m));
981 ct->c_ctparams = (void *) m;
984 while (fgetstr(buffer, sizeof(buffer) - 1, in)) {
988 if (user_content(in, file, buffer, &p) == DONE) {
990 adios(EX_DATAERR, NULL, "empty \"#begin ... #end\" sequence");
996 part = mh_xcalloc(1, sizeof(*part));
1001 admonish(NULL, "premature end-of-file, missing #end");
1006 ** Unknown directive
1008 adios(EX_DATAERR, NULL, "unknown directive \"#%s\"", ci->ci_type);
1009 return NOTOK; /* NOT REACHED */
1014 set_id(CT ct, int top)
1018 static time_t clock = 0;
1019 static char *msgfmt;
1023 snprintf(msgid, sizeof(msgid), "<%d.%ld.%%d@%s>\n",
1024 (int) getpid(), (long) clock, LocalName());
1026 msgfmt = mh_xstrdup(msgid);
1028 snprintf(msgid, sizeof(msgid), msgfmt, top ? 0 : ++partno);
1029 ct->c_id = mh_xstrdup(msgid);
1034 ** Fill out, or expand the various contents in the composition
1035 ** draft. Read-in any necessary files. Parse and execute any
1036 ** commands specified by profile composition strings.
1040 compose_content(CT ct)
1042 CE ce = ct->c_cefile;
1044 switch (ct->c_type) {
1049 char partnam[BUFSIZ];
1050 struct multipart *m = (struct multipart *) ct->c_ctparams;
1054 snprintf(partnam, sizeof(partnam), "%s.",
1056 pp = partnam + strlen(partnam);
1061 /* first, we call compose_content on all the subparts */
1062 for (part = m->mp_parts, partnum = 1; part;
1063 part = part->mp_next, partnum++) {
1064 CT p = part->mp_part;
1066 sprintf(pp, "%d", partnum);
1067 p->c_partno = mh_xstrdup(partnam);
1068 if (compose_content(p) == NOTOK)
1075 /* Nothing to do for type message */
1079 ** Discrete types (text/application/audio/image/video)
1084 int xstdout, len, buflen;
1085 char *bp, **ap, *cp;
1086 char *vec[4], buffer[BUFSIZ];
1088 CI ci = &ct->c_ctinfo;
1091 if (!(cp = ci->ci_magic))
1092 adios(EX_SOFTWARE, NULL, "internal error(5)");
1094 tfile = m_mktemp2(NULL, invo_name, NULL, NULL);
1095 if (tfile == NULL) {
1096 adios(EX_CANTCREAT, "mhbuild", "unable to create temporary file");
1098 ce->ce_file = mh_xstrdup(tfile);
1103 /* Get buffer ready to go */
1106 buflen = sizeof(buffer);
1109 ** Parse composition string into buffer
1111 for ( ; *cp; cp++) {
1117 ** insert parameters from
1123 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++) {
1124 snprintf(bp, buflen, "%s%s=\"%s\"", s, *ap, *ep);
1134 /* %f, and stdout is not-redirected */
1140 ** insert temporary filename
1141 ** where content should be
1144 snprintf(bp, buflen, "%s", ce->ce_file);
1148 /* insert content subtype */
1149 strncpy(bp, ci->ci_subtype, buflen);
1153 /* insert character % */
1174 printf("composing content %s/%s from command\n\t%s\n", ci->ci_type, ci->ci_subtype, buffer);
1176 fflush(stdout); /* not sure if need for -noverbose */
1183 if ((out = fopen(ce->ce_file, "w")) == NULL)
1184 adios(EX_IOERR, ce->ce_file, "unable to open for writing");
1186 switch (child_id = fork()) {
1188 adios(EX_OSERR, "fork", "unable to fork");
1193 dup2(fileno(out), 1);
1195 execvp("/bin/sh", vec);
1196 fprintf(stderr, "unable to exec ");
1203 if (pidXwait(child_id, NULL))
1216 ** Scan the content.
1218 ** 1) choose a transfer encoding.
1219 ** 2) check for clashes with multipart boundary string.
1220 ** 3) for text content, figure out which character set is being used.
1222 ** If there is a clash with one of the contents and the multipart boundary,
1223 ** this function will exit with NOTOK. This will cause the scanning process
1224 ** to be repeated with a different multipart boundary. It is possible
1225 ** (although highly unlikely) that this scan will be repeated multiple times.
1232 int check8bit = 0, contains8bit = 0;
1233 int checklinelen = 0, linelen = 0;
1234 int checkboundary = 0, boundaryclash = 0;
1235 int checklinespace = 0, linespace = 0; /* trailing whitespace */
1236 unsigned char *cp = NULL, buffer[BUFSIZ];
1237 struct text *t = NULL;
1239 CE ce = ct->c_cefile;
1242 ** handle multipart by scanning all subparts
1243 ** and then checking their encoding.
1245 if (ct->c_type == CT_MULTIPART) {
1246 struct multipart *m = (struct multipart *) ct->c_ctparams;
1249 /* initially mark the domain of enclosing multipart as 7bit */
1250 ct->c_encoding = CE_7BIT;
1252 for (part = m->mp_parts; part; part = part->mp_next) {
1253 CT p = part->mp_part;
1255 if (scan_content(p) == NOTOK) {
1256 /* choose encoding for subpart */
1261 ** if necessary, enlarge encoding for enclosing
1264 if (p->c_encoding == CE_BINARY)
1265 ct->c_encoding = CE_BINARY;
1266 if (p->c_encoding == CE_8BIT &&
1267 ct->c_encoding != CE_BINARY)
1268 ct->c_encoding = CE_8BIT;
1275 ** Decide what to check while scanning this content.
1277 switch (ct->c_type) {
1292 case CT_APPLICATION:
1304 ** Scan the unencoded content
1306 if (check8bit || checklinelen || checklinespace || checkboundary) {
1307 if ((in = fopen(ce->ce_file, "r")) == NULL)
1308 adios(EX_IOERR, ce->ce_file, "unable to open for reading");
1309 len = strlen(prefix);
1311 while (fgets(buffer, sizeof(buffer) - 1, in)) {
1313 for (cp = buffer; *cp; cp++) {
1314 if (!isascii(*cp)) {
1316 /* no need to keep checking */
1322 if (checklinelen && (strlen(buffer) > CPERLIN + 1)) {
1324 checklinelen = 0; /* no need to keep checking */
1327 if (checklinespace &&
1328 (cp = buffer + strlen(buffer) - 2) >
1329 buffer && isspace(*cp)) {
1331 /* no need to keep checking */
1336 ** Check if content contains a line that clashes
1337 ** with our standard boundary for multipart messages.
1339 if (checkboundary && buffer[0] == '-' &&
1341 for (cp = buffer + strlen(buffer) - 1;
1346 if (strncmp(buffer + 2, prefix, len)==0 &&
1347 isdigit(buffer[2 + len])) {
1349 /* no need to keep checking */
1358 ** Decide which transfer encoding to use.
1360 switch (ct->c_type) {
1363 ** If the text content didn't specify a character
1364 ** set, we need to figure out which one was used.
1366 t = (struct text *) ct->c_ctparams;
1367 if (t->tx_charset == CHARSET_UNSPECIFIED) {
1368 CI ci = &ct->c_ctinfo;
1371 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++)
1375 t->tx_charset = CHARSET_UNKNOWN;
1376 *ap = concat("charset=", write_charset_8bit(),
1379 t->tx_charset = CHARSET_USASCII;
1380 *ap = mh_xstrdup("charset=us-ascii");
1383 cp = strchr(*ap++, '=');
1389 if (contains8bit || linelen || linespace)
1390 ct->c_encoding = CE_QUOTED;
1392 ct->c_encoding = CE_7BIT;
1396 ct->c_encoding = CE_7BIT;
1399 case CT_APPLICATION:
1404 ** Forcing use of base64, because these types likely
1405 ** contain binary data and NUL bytes. Don't care about
1406 ** files that would be clean.
1408 ct->c_encoding = CE_BASE64;
1412 return (boundaryclash ? NOTOK : OK);
1417 ** Scan the content structures, and build header
1418 ** fields that will need to be output into the
1423 build_headers(CT ct)
1427 char *np, *vp, buffer[BUFSIZ];
1428 CI ci = &ct->c_ctinfo;
1431 ** If message is type multipart, then add the multipart
1432 ** boundary to the list of attribute/value pairs.
1434 if (ct->c_type == CT_MULTIPART) {
1436 static int level = 0; /* store nesting level */
1440 snprintf(buffer, sizeof(buffer), "boundary=%s%d",
1442 cp = strchr(*ap++ = mh_xstrdup(buffer), '=');
1449 ** output the content type and subtype
1451 np = mh_xstrdup(TYPE_FIELD);
1452 vp = concat(" ", ci->ci_type, "/", ci->ci_subtype, NULL);
1454 /* keep track of length of line */
1455 len = strlen(TYPE_FIELD) + strlen(ci->ci_type) +
1456 strlen(ci->ci_subtype) + 3;
1459 ** Append the attribute/value pairs to
1460 ** the end of the Content-Type line.
1462 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++) {
1466 snprintf(buffer, sizeof(buffer), "%s=\"%s\"", *ap, *ep);
1467 if (len + 1 + (cc = strlen(buffer)) >= CPERLIN) {
1468 vp = add("\n\t", vp);
1474 vp = add(buffer, vp);
1479 ** Append any RFC-822 comment to the end of
1480 ** the Content-Type line.
1482 if (ci->ci_comment) {
1483 snprintf(buffer, sizeof(buffer), "(%s)", ci->ci_comment);
1484 if (len + 1 + (cc = 2 + strlen(ci->ci_comment)) >= CPERLIN) {
1485 vp = add("\n\t", vp);
1491 vp = add(buffer, vp);
1495 add_header(ct, np, vp);
1498 ** output the Content-ID
1501 np = mh_xstrdup(ID_FIELD);
1502 vp = concat(" ", ct->c_id, NULL);
1503 add_header(ct, np, vp);
1507 ** output the Content-Description
1510 np = mh_xstrdup(DESCR_FIELD);
1511 vp = concat(" ", ct->c_descr, NULL);
1512 if (encode_rfc2047(DESCR_FIELD, &vp, NULL)) {
1513 adios(EX_DATAERR, NULL, "Unable to encode %s header", DESCR_FIELD);
1515 add_header(ct, np, vp);
1519 ** output the Content-Disposition
1522 np = mh_xstrdup(DISPO_FIELD);
1523 vp = concat(" ", ct->c_dispo, NULL);
1524 add_header(ct, np, vp);
1528 ** output the Content-Transfer-Encoding
1530 switch (ct->c_encoding) {
1532 /* Nothing to output */
1536 if (ct->c_type == CT_MESSAGE)
1537 adios(EX_DATAERR, NULL, "internal error, invalid encoding");
1539 np = mh_xstrdup(ENCODING_FIELD);
1540 vp = concat(" ", "8bit", "\n", NULL);
1541 add_header(ct, np, vp);
1545 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1546 adios(EX_DATAERR, NULL, "internal error, invalid encoding");
1548 np = mh_xstrdup(ENCODING_FIELD);
1549 vp = concat(" ", "quoted-printable", "\n", NULL);
1550 add_header(ct, np, vp);
1554 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1555 adios(EX_DATAERR, NULL, "internal error, invalid encoding");
1557 np = mh_xstrdup(ENCODING_FIELD);
1558 vp = concat(" ", "base64", "\n", NULL);
1559 add_header(ct, np, vp);
1563 if (ct->c_type == CT_MESSAGE)
1564 adios(EX_DATAERR, NULL, "internal error, invalid encoding");
1566 np = mh_xstrdup(ENCODING_FIELD);
1567 vp = concat(" ", "binary", "\n", NULL);
1568 add_header(ct, np, vp);
1572 adios(EX_DATAERR, NULL, "unknown transfer encoding in content");
1577 ** Additional content specific header processing
1579 switch (ct->c_type) {
1582 struct multipart *m;
1585 m = (struct multipart *) ct->c_ctparams;
1586 for (part = m->mp_parts; part; part = part->mp_next) {