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)) {
356 /* abort if draft has Mime-Version header field */
357 if (!mh_strcasecmp(f.name, VRSN_FIELD)) {
358 adios(EX_CONFIG, NULL, "draft shouldn't contain %s: field", VRSN_FIELD);
362 ** abort if draft has Content-Transfer-Encoding
365 if (!mh_strcasecmp(f.name, ENCODING_FIELD)) {
366 adios(EX_CONFIG, NULL, "draft shouldn't contain %s: field", ENCODING_FIELD);
369 /* ignore any Content-Type fields in the header */
370 if (!mh_strcasecmp(f.name, TYPE_FIELD)) {
374 /* add the header data to the list */
375 add_header(ct, mh_xstrdup(f.name), mh_xstrdup(f.value));
380 fseek(in, (long) (-strlen(f.value)), SEEK_CUR);
384 adios(EX_CONFIG, NULL, "draft has empty body -- no directives!");
390 adios(EX_CONFIG, NULL, "message format error in component #%d",
394 adios(EX_SOFTWARE, NULL, "getfld() returned %d", state);
400 ** Iterate through the list of headers and call the function to
401 ** MIME-ify them if required.
403 for (hp = ct->c_first_hf; hp != NULL; hp = hp->next) {
404 if (encode_rfc2047(hp->name, &hp->value, NULL)) {
405 adios(EX_DATAERR, NULL, "Unable to encode header \"%s\"", hp->name);
410 ** Now add the MIME-Version header field
411 ** to the list of header fields.
413 np = mh_xstrdup(VRSN_FIELD);
414 vp = concat(" ", VRSN_VALUE, "\n", NULL);
415 add_header(ct, np, vp);
418 ** We initially assume we will find multiple contents in the
419 ** draft. So create a multipart/mixed content to hold everything.
420 ** We can remove this later, if it is not needed.
422 if (get_ctinfo("multipart/mixed", ct, 0) == NOTOK) {
425 ct->c_type = CT_MULTIPART;
426 ct->c_subtype = MULTI_MIXED;
427 ct->c_file = mh_xstrdup(infile);
429 m = (struct multipart *) mh_xcalloc(1, sizeof(*m));
430 ct->c_ctparams = (void *) m;
434 ** read and parse the composition file
435 ** and the directives it contains.
437 while (fgetstr(buf, sizeof(buf) - 1, in)) {
441 if (user_content(in, infile, buf, &p) == DONE) {
442 admonish(NULL, "ignoring spurious #end");
448 part = mh_xcalloc(1, sizeof(*part));
455 ** close the composition draft since
456 ** it's not needed any longer.
460 /* check if any contents were found */
462 adios(EX_OSERR, NULL, "no content directives found");
465 ** If only one content was found, then remove and
466 ** free the outer multipart content.
468 if (!m->mp_parts->mp_next) {
471 p = m->mp_parts->mp_part;
472 m->mp_parts->mp_part = NULL;
474 /* move header fields */
475 p->c_first_hf = ct->c_first_hf;
476 p->c_last_hf = ct->c_last_hf;
477 ct->c_first_hf = NULL;
478 ct->c_last_hf = NULL;
487 ** Fill out, or expand directives. Parse and execute
488 ** commands specified by profile composition strings.
492 if ((cp = strchr(prefix, 'a')) == NULL)
493 adios(EX_SOFTWARE, NULL, "internal error(4)");
496 ** Scan the contents. Choose a transfer encoding, and
497 ** check if prefix for multipart boundary clashes with
498 ** any of the contents.
500 while (scan_content(ct) == NOTOK) {
505 adios(EX_SOFTWARE, NULL, "giving up trying to find a unique delimiter string");
511 /* Build the rest of the header field structures */
519 ** Set up structures for placing unencoded
520 ** content when building parts.
524 init_decoded_content(CT ct)
528 ce = mh_xcalloc(1, sizeof(*ce));
531 ct->c_ceopenfnx = open7Bit; /* since unencoded */
532 ct->c_ceclosefnx = close_encoding;
533 ct->c_cesizefnx = NULL; /* since unencoded */
540 fgetstr(char *s, int n, FILE *stream)
544 for (ep = (cp = s) + n; cp < ep; ) {
547 if (!fgets(cp, n, stream))
548 return (cp != s ? s : NULL);
549 if (cp == s && *cp != '#')
552 cp += (i = strlen(cp)) - 1;
553 if (i <= 1 || *cp-- != '\n' || *cp != '\\')
564 ** Parse the composition draft for text and directives.
565 ** Do initial setup of Content structure.
569 user_content(FILE *in, char *file, char *buf, CT *ctp)
577 struct str2init *s2i;
582 if (buf[0] == '\n' || strcmp(buf, "#\n") == 0) {
587 /* allocate basic Content structure */
588 ct = mh_xcalloc(1, sizeof(*ct));
591 /* allocate basic structure for handling decoded content */
592 init_decoded_content(ct);
599 ** Handle inline text. Check if line
600 ** is one of the following forms:
602 ** 1) doesn't begin with '#' (implicit directive)
603 ** 2) begins with "##" (implicit directive)
604 ** 3) begins with "#<"
606 if (buf[0] != '#' || buf[1] == '#' || buf[1] == '<') {
610 char content[BUFSIZ];
614 cp = m_mktemp2(NULL, invo_name, NULL, &out);
616 adios(EX_CANTCREAT, "mhbuild", "unable to create temporary file");
618 /* use a temp file to collect the plain text lines */
619 ce->ce_file = mh_xstrdup(cp);
622 if (buf[0] == '#' && buf[1] == '<') {
623 strncpy(content, buf + 2, sizeof(content));
630 /* the directive is implicit */
631 strncpy(content, "text/plain", sizeof(content));
633 strncpy(buffer, buf[0] != '#' ? buf : buf + 1, sizeof(buffer));
637 if (headers >= 0 && uprf(buffer, DESCR_FIELD) &&
638 buffer[i=strlen(DESCR_FIELD)] == ':') {
642 ct->c_descr = add(buffer + i + 1, ct->c_descr);
643 if (!fgetstr(buffer, sizeof(buffer) - 1, in))
644 adios(EX_DATAERR, NULL, "end-of-file after %s: field in plaintext", DESCR_FIELD);
652 adios(EX_DATAERR, NULL, "#-directive after %s: field in plaintext", DESCR_FIELD);
660 if (headers >= 0 && uprf(buffer, DISPO_FIELD)
661 && buffer[i = strlen(DISPO_FIELD)] == ':') {
665 ct->c_dispo = add(buffer + i + 1, ct->c_dispo);
666 if (!fgetstr(buffer, sizeof(buffer) - 1, in))
667 adios(EX_DATAERR, NULL, "end-of-file after %s: field in plaintext", DISPO_FIELD);
675 adios(EX_DATAERR, NULL, "#-directive after %s: field in plaintext", DISPO_FIELD);
683 if (headers != 1 || buffer[0] != '\n')
689 if ((cp = fgetstr(buffer, sizeof(buffer) - 1, in))
692 if (buffer[0] == '#') {
695 if (buffer[1] != '#')
697 for (cp = (bp = buffer) + 1; *cp; cp++)
705 /* parse content type */
706 if (get_ctinfo(content, ct, inlineD) == NOTOK)
709 for (s2i = str2cts; s2i->si_key; s2i++)
710 if (!mh_strcasecmp(ci->ci_type, s2i->si_key))
712 if (!s2i->si_key && !uprf(ci->ci_type, "X-"))
716 ** check type specified (possibly implicitly)
718 switch (ct->c_type = s2i->si_val) {
720 if (!mh_strcasecmp(ci->ci_subtype, "rfc822")) {
721 ct->c_encoding = CE_7BIT;
726 adios(EX_DATAERR, NULL, "it doesn't make sense to define an in-line %s content",
727 ct->c_type == CT_MESSAGE ? "message" :
733 if ((ct->c_ctinitfnx = s2i->si_init))
734 (*ct->c_ctinitfnx) (ct);
739 fseek(in, pos, SEEK_SET);
744 ** If we've reached this point, the next line
745 ** must be some type of explicit directive.
749 adios(EX_DATAERR, NULL, "The #@ directive i.e. message/external-body "
750 "is not supported anymore.");
753 /* parse directive */
754 if (get_ctinfo(buf+1, ct, 1) == NOTOK)
757 /* check directive against the list of MIME types */
758 for (s2i = str2cts; s2i->si_key; s2i++)
759 if (!mh_strcasecmp(ci->ci_type, s2i->si_key))
763 ** Check if the directive specified a valid type.
764 ** This will happen if it was one of the following forms:
770 adios(EX_DATAERR, NULL, "missing subtype in \"#%s\"", ci->ci_type);
772 switch (ct->c_type = s2i->si_val) {
774 adios(EX_DATAERR, NULL, "use \"#begin ... #end\" instead of \"#%s/%s\"", ci->ci_type, ci->ci_subtype);
778 if (!mh_strcasecmp(ci->ci_subtype, "partial") ||
779 !mh_strcasecmp(ci->ci_subtype,
781 adios(EX_DATAERR, NULL, "sorry, \"#%s/%s\" isn't supported", ci->ci_type, ci->ci_subtype);
784 admonish(NULL, "use \"#forw [+folder] [msgs]\" instead of \"#%s/%s\"", ci->ci_type, ci->ci_subtype);
788 if ((ct->c_ctinitfnx = s2i->si_init))
789 (*ct->c_ctinitfnx) (ct);
793 /* Handle [file] argument */
795 /* check if specifies command to execute */
796 if (*ci->ci_magic == '|' || *ci->ci_magic == '!') {
797 for (cp = ci->ci_magic + 1; isspace(*cp); cp++)
800 adios(EX_DATAERR, NULL, "empty pipe command for #%s directive", ci->ci_type);
802 mh_free0(&(ci->ci_magic));
805 /* record filename of decoded contents */
806 ce->ce_file = ci->ci_magic;
807 if (access(ce->ce_file, R_OK) == NOTOK)
808 adios(EX_IOERR, "reading", "unable to access %s for", ce->ce_file);
815 ** No [file] argument, so check profile for
816 ** method to compose content.
818 snprintf(buffer, sizeof(buffer), "%s-compose-%s/%s",
819 invo_name, ci->ci_type, ci->ci_subtype);
820 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
821 snprintf(buffer, sizeof(buffer), "%s-compose-%s",
822 invo_name, ci->ci_type);
823 if ((cp = context_find(buffer)) == NULL ||
825 content_error(NULL, ct, "don't know how to compose content");
829 ci->ci_magic = mh_xstrdup(cp);
835 ** #forw [+folder] [msgs]
837 if (!mh_strcasecmp(ci->ci_type, "forw")) {
839 char *folder, *arguments[MAXARGS];
845 ap = brkstring(ci->ci_magic, " ", "\n");
846 for (i=0; ap[i] && i<MAXARGS-1; i++) {
847 arguments[i] = ap[i];
852 arguments[0] = seq_cur;
857 /* search the arguments for a folder name */
858 for (ap = arguments; *ap; ap++) {
860 if (*cp == '+' || *cp == '@') {
862 adios(EX_USAGE, NULL, "only one folder per #forw directive");
864 folder = mh_xstrdup(expandfol(cp));
868 /* else, use the current folder */
870 folder = mh_xstrdup(getcurfol());
872 if (!(mp = folder_read(folder)))
873 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
874 for (ap = arguments; *ap; ap++) {
876 if (*cp != '+' && *cp != '@')
877 if (!m_convert(mp, cp))
884 ** If there is more than one message to include, make this
885 ** a content of type "multipart/digest" and insert each message
886 ** as a subpart. If there is only one message, then make this
887 ** a content of type "message/rfc822".
889 if (mp->numsel > 1) {
890 /* we are forwarding multiple messages */
891 if (get_ctinfo("multipart/digest", ct, 0) == NOTOK)
893 ct->c_type = CT_MULTIPART;
894 ct->c_subtype = MULTI_DIGEST;
896 m = mh_xcalloc(1, sizeof(*m));
897 ct->c_ctparams = (void *) m;
900 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
901 if (is_selected(mp, msgnum)) {
906 p = mh_xcalloc(1, sizeof(*p));
907 init_decoded_content(p);
909 if (get_ctinfo("message/rfc822", p, 0)
912 p->c_type = CT_MESSAGE;
913 p->c_subtype = MESSAGE_RFC822;
915 snprintf(buffer, sizeof(buffer),
916 "%s/%d", mp->foldpath,
918 pe->ce_file = mh_xstrdup(buffer);
920 part = mh_xcalloc(1, sizeof(*part));
927 /* we are forwarding one message */
928 if (get_ctinfo("message/rfc822", ct, 0) == NOTOK)
930 ct->c_type = CT_MESSAGE;
931 ct->c_subtype = MESSAGE_RFC822;
934 snprintf(buffer, sizeof(buffer), "%s/%d",
935 mp->foldpath, msgnum);
936 ce->ce_file = mh_xstrdup(buffer);
939 folder_free(mp); /* free folder/message structure */
946 if (!mh_strcasecmp(ci->ci_type, "end")) {
953 ** #begin [ alternative | parallel ]
955 if (!mh_strcasecmp(ci->ci_type, "begin")) {
958 cp = SubMultiPart[vrsn - 1].kv_key;
959 } else if (!mh_strcasecmp(ci->ci_magic, "alternative")) {
960 vrsn = MULTI_ALTERNATE;
961 cp = SubMultiPart[vrsn - 1].kv_key;
962 } else if (!mh_strcasecmp(ci->ci_magic, "parallel")) {
963 vrsn = MULTI_PARALLEL;
964 cp = SubMultiPart[vrsn - 1].kv_key;
965 } else if (uprf(ci->ci_magic, "digest")) {
968 vrsn = MULTI_UNKNOWN;
973 snprintf(buffer, sizeof(buffer), "multipart/%s", cp);
974 if (get_ctinfo(buffer, ct, 0) == NOTOK)
976 ct->c_type = CT_MULTIPART;
977 ct->c_subtype = vrsn;
979 m = mh_xcalloc(1, sizeof(*m));
980 ct->c_ctparams = (void *) m;
983 while (fgetstr(buffer, sizeof(buffer) - 1, in)) {
987 if (user_content(in, file, buffer, &p) == DONE) {
989 adios(EX_DATAERR, NULL, "empty \"#begin ... #end\" sequence");
995 part = mh_xcalloc(1, sizeof(*part));
1000 admonish(NULL, "premature end-of-file, missing #end");
1005 ** Unknown directive
1007 adios(EX_DATAERR, NULL, "unknown directive \"#%s\"", ci->ci_type);
1008 return NOTOK; /* NOT REACHED */
1013 set_id(CT ct, int top)
1017 static time_t clock = 0;
1018 static char *msgfmt;
1022 snprintf(msgid, sizeof(msgid), "<%d.%ld.%%d@%s>\n",
1023 (int) getpid(), (long) clock, LocalName());
1025 msgfmt = mh_xstrdup(msgid);
1027 snprintf(msgid, sizeof(msgid), msgfmt, top ? 0 : ++partno);
1028 ct->c_id = mh_xstrdup(msgid);
1033 ** Fill out, or expand the various contents in the composition
1034 ** draft. Read-in any necessary files. Parse and execute any
1035 ** commands specified by profile composition strings.
1039 compose_content(CT ct)
1041 CE ce = ct->c_cefile;
1043 switch (ct->c_type) {
1048 char partnam[BUFSIZ];
1049 struct multipart *m = (struct multipart *) ct->c_ctparams;
1053 snprintf(partnam, sizeof(partnam), "%s.",
1055 pp = partnam + strlen(partnam);
1060 /* first, we call compose_content on all the subparts */
1061 for (part = m->mp_parts, partnum = 1; part;
1062 part = part->mp_next, partnum++) {
1063 CT p = part->mp_part;
1065 sprintf(pp, "%d", partnum);
1066 p->c_partno = mh_xstrdup(partnam);
1067 if (compose_content(p) == NOTOK)
1074 /* Nothing to do for type message */
1078 ** Discrete types (text/application/audio/image/video)
1083 int xstdout, len, buflen;
1084 char *bp, **ap, *cp;
1085 char *vec[4], buffer[BUFSIZ];
1087 CI ci = &ct->c_ctinfo;
1090 if (!(cp = ci->ci_magic))
1091 adios(EX_SOFTWARE, NULL, "internal error(5)");
1093 tfile = m_mktemp2(NULL, invo_name, NULL, NULL);
1094 if (tfile == NULL) {
1095 adios(EX_CANTCREAT, "mhbuild", "unable to create temporary file");
1097 ce->ce_file = mh_xstrdup(tfile);
1102 /* Get buffer ready to go */
1105 buflen = sizeof(buffer);
1108 ** Parse composition string into buffer
1110 for ( ; *cp; cp++) {
1116 ** insert parameters from
1122 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++) {
1123 snprintf(bp, buflen, "%s%s=\"%s\"", s, *ap, *ep);
1133 /* %f, and stdout is not-redirected */
1139 ** insert temporary filename
1140 ** where content should be
1143 snprintf(bp, buflen, "%s", ce->ce_file);
1147 /* insert content subtype */
1148 strncpy(bp, ci->ci_subtype, buflen);
1152 /* insert character % */
1173 printf("composing content %s/%s from command\n\t%s\n", ci->ci_type, ci->ci_subtype, buffer);
1175 fflush(stdout); /* not sure if need for -noverbose */
1182 if ((out = fopen(ce->ce_file, "w")) == NULL)
1183 adios(EX_IOERR, ce->ce_file, "unable to open for writing");
1185 switch (child_id = fork()) {
1187 adios(EX_OSERR, "fork", "unable to fork");
1192 dup2(fileno(out), 1);
1194 execvp("/bin/sh", vec);
1195 fprintf(stderr, "unable to exec ");
1202 if (pidXwait(child_id, NULL))
1215 ** Scan the content.
1217 ** 1) choose a transfer encoding.
1218 ** 2) check for clashes with multipart boundary string.
1219 ** 3) for text content, figure out which character set is being used.
1221 ** If there is a clash with one of the contents and the multipart boundary,
1222 ** this function will exit with NOTOK. This will cause the scanning process
1223 ** to be repeated with a different multipart boundary. It is possible
1224 ** (although highly unlikely) that this scan will be repeated multiple times.
1231 int check8bit = 0, contains8bit = 0;
1232 int checklinelen = 0, linelen = 0;
1233 int checkboundary = 0, boundaryclash = 0;
1234 int checklinespace = 0, linespace = 0; /* trailing whitespace */
1235 unsigned char *cp = NULL, buffer[BUFSIZ];
1236 struct text *t = NULL;
1238 CE ce = ct->c_cefile;
1241 ** handle multipart by scanning all subparts
1242 ** and then checking their encoding.
1244 if (ct->c_type == CT_MULTIPART) {
1245 struct multipart *m = (struct multipart *) ct->c_ctparams;
1248 /* initially mark the domain of enclosing multipart as 7bit */
1249 ct->c_encoding = CE_7BIT;
1251 for (part = m->mp_parts; part; part = part->mp_next) {
1252 CT p = part->mp_part;
1254 if (scan_content(p) == NOTOK) {
1255 /* choose encoding for subpart */
1260 ** if necessary, enlarge encoding for enclosing
1263 if (p->c_encoding == CE_BINARY)
1264 ct->c_encoding = CE_BINARY;
1265 if (p->c_encoding == CE_8BIT &&
1266 ct->c_encoding != CE_BINARY)
1267 ct->c_encoding = CE_8BIT;
1274 ** Decide what to check while scanning this content.
1276 switch (ct->c_type) {
1291 case CT_APPLICATION:
1303 ** Scan the unencoded content
1305 if (check8bit || checklinelen || checklinespace || checkboundary) {
1306 if ((in = fopen(ce->ce_file, "r")) == NULL)
1307 adios(EX_IOERR, ce->ce_file, "unable to open for reading");
1308 len = strlen(prefix);
1310 while (fgets(buffer, sizeof(buffer) - 1, in)) {
1312 for (cp = buffer; *cp; cp++) {
1313 if (!isascii(*cp)) {
1315 /* no need to keep checking */
1321 if (checklinelen && (strlen(buffer) > CPERLIN + 1)) {
1323 checklinelen = 0; /* no need to keep checking */
1326 if (checklinespace &&
1327 (cp = buffer + strlen(buffer) - 2) >
1328 buffer && isspace(*cp)) {
1330 /* no need to keep checking */
1335 ** Check if content contains a line that clashes
1336 ** with our standard boundary for multipart messages.
1338 if (checkboundary && buffer[0] == '-' &&
1340 for (cp = buffer + strlen(buffer) - 1;
1345 if (strncmp(buffer + 2, prefix, len)==0 &&
1346 isdigit(buffer[2 + len])) {
1348 /* no need to keep checking */
1357 ** Decide which transfer encoding to use.
1359 switch (ct->c_type) {
1362 ** If the text content didn't specify a character
1363 ** set, we need to figure out which one was used.
1365 t = (struct text *) ct->c_ctparams;
1366 if (t->tx_charset == CHARSET_UNSPECIFIED) {
1367 CI ci = &ct->c_ctinfo;
1370 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++)
1374 t->tx_charset = CHARSET_UNKNOWN;
1375 *ap = concat("charset=", write_charset_8bit(),
1378 t->tx_charset = CHARSET_USASCII;
1379 *ap = mh_xstrdup("charset=us-ascii");
1382 cp = strchr(*ap++, '=');
1388 if (contains8bit || linelen || linespace)
1389 ct->c_encoding = CE_QUOTED;
1391 ct->c_encoding = CE_7BIT;
1395 ct->c_encoding = CE_7BIT;
1398 case CT_APPLICATION:
1403 ** Forcing use of base64, because these types likely
1404 ** contain binary data and NUL bytes. Don't care about
1405 ** files that would be clean.
1407 ct->c_encoding = CE_BASE64;
1411 return (boundaryclash ? NOTOK : OK);
1416 ** Scan the content structures, and build header
1417 ** fields that will need to be output into the
1422 build_headers(CT ct)
1426 char *np, *vp, buffer[BUFSIZ];
1427 CI ci = &ct->c_ctinfo;
1430 ** If message is type multipart, then add the multipart
1431 ** boundary to the list of attribute/value pairs.
1433 if (ct->c_type == CT_MULTIPART) {
1435 static int level = 0; /* store nesting level */
1439 snprintf(buffer, sizeof(buffer), "boundary=%s%d",
1441 cp = strchr(*ap++ = mh_xstrdup(buffer), '=');
1448 ** output the content type and subtype
1450 np = mh_xstrdup(TYPE_FIELD);
1451 vp = concat(" ", ci->ci_type, "/", ci->ci_subtype, NULL);
1453 /* keep track of length of line */
1454 len = strlen(TYPE_FIELD) + strlen(ci->ci_type) +
1455 strlen(ci->ci_subtype) + 3;
1458 ** Append the attribute/value pairs to
1459 ** the end of the Content-Type line.
1461 for (ap = ci->ci_attrs, ep = ci->ci_values; *ap; ap++, ep++) {
1465 snprintf(buffer, sizeof(buffer), "%s=\"%s\"", *ap, *ep);
1466 if (len + 1 + (cc = strlen(buffer)) >= CPERLIN) {
1467 vp = add("\n\t", vp);
1473 vp = add(buffer, vp);
1478 ** Append any RFC-822 comment to the end of
1479 ** the Content-Type line.
1481 if (ci->ci_comment) {
1482 snprintf(buffer, sizeof(buffer), "(%s)", ci->ci_comment);
1483 if (len + 1 + (cc = 2 + strlen(ci->ci_comment)) >= CPERLIN) {
1484 vp = add("\n\t", vp);
1490 vp = add(buffer, vp);
1494 add_header(ct, np, vp);
1497 ** output the Content-ID
1500 np = mh_xstrdup(ID_FIELD);
1501 vp = concat(" ", ct->c_id, NULL);
1502 add_header(ct, np, vp);
1506 ** output the Content-Description
1509 np = mh_xstrdup(DESCR_FIELD);
1510 vp = concat(" ", ct->c_descr, NULL);
1511 if (encode_rfc2047(DESCR_FIELD, &vp, NULL)) {
1512 adios(EX_DATAERR, NULL, "Unable to encode %s header", DESCR_FIELD);
1514 add_header(ct, np, vp);
1518 ** output the Content-Disposition
1521 np = mh_xstrdup(DISPO_FIELD);
1522 vp = concat(" ", ct->c_dispo, NULL);
1523 add_header(ct, np, vp);
1527 ** output the Content-Transfer-Encoding
1529 switch (ct->c_encoding) {
1531 /* Nothing to output */
1535 if (ct->c_type == CT_MESSAGE)
1536 adios(EX_DATAERR, NULL, "internal error, invalid encoding");
1538 np = mh_xstrdup(ENCODING_FIELD);
1539 vp = concat(" ", "8bit", "\n", NULL);
1540 add_header(ct, np, vp);
1544 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1545 adios(EX_DATAERR, NULL, "internal error, invalid encoding");
1547 np = mh_xstrdup(ENCODING_FIELD);
1548 vp = concat(" ", "quoted-printable", "\n", NULL);
1549 add_header(ct, np, vp);
1553 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART)
1554 adios(EX_DATAERR, NULL, "internal error, invalid encoding");
1556 np = mh_xstrdup(ENCODING_FIELD);
1557 vp = concat(" ", "base64", "\n", NULL);
1558 add_header(ct, np, vp);
1562 if (ct->c_type == CT_MESSAGE)
1563 adios(EX_DATAERR, NULL, "internal error, invalid encoding");
1565 np = mh_xstrdup(ENCODING_FIELD);
1566 vp = concat(" ", "binary", "\n", NULL);
1567 add_header(ct, np, vp);
1571 adios(EX_DATAERR, NULL, "unknown transfer encoding in content");
1576 ** Additional content specific header processing
1578 switch (ct->c_type) {
1581 struct multipart *m;
1584 m = (struct multipart *) ct->c_ctparams;
1585 for (part = m->mp_parts; part; part = part->mp_next) {