]> diplodocus.org Git - nmh/blob - uip/mhfixmsg.c
d69039748d81bcd2705e6ceb0d95103d2b062caf
[nmh] / uip / mhfixmsg.c
1 /*
2 * mhfixmsg.c -- rewrite a message with various tranformations
3 *
4 * This code is Copyright (c) 2002 and 2013, by the authors of nmh.
5 * See the COPYRIGHT file in the root directory of the nmh
6 * distribution for complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <h/mime.h>
11 #include <h/mhparse.h>
12 #include <h/utils.h>
13 #include <h/signals.h>
14 #include <signal.h>
15 #include <sys/stat.h>
16 #include <fcntl.h>
17 #ifdef HAVE_ICONV
18 # include <iconv.h>
19 #endif
20
21 #define MHFIXMSG_SWITCHES \
22 X("decodetext 8bit|7bit", 0, DECODETEXTSW) \
23 X("nodecodetext", 0, NDECODETEXTSW) \
24 X("textcodeset", 0, TEXTCODESETSW) \
25 X("notextcodeset", 0, NTEXTCODESETSW) \
26 X("reformat", 0, REFORMATSW) \
27 X("noreformat", 0, NREFORMATSW) \
28 X("fixboundary", 0, FIXBOUNDARYSW) \
29 X("nofixboundary", 0, NFIXBOUNDARYSW) \
30 X("fixcte", 0, FIXCTESW) \
31 X("nofixcte", 0, NFIXCTESW) \
32 X("file file", 0, FILESW) \
33 X("outfile file", 0, OUTFILESW) \
34 X("verbose", 0, VERBSW) \
35 X("noverbose", 0, NVERBSW) \
36 X("version", 0, VERSIONSW) \
37 X("help", 0, HELPSW) \
38
39 #define X(sw, minchars, id) id,
40 DEFINE_SWITCH_ENUM(MHFIXMSG);
41 #undef X
42
43 #define X(sw, minchars, id) { sw, minchars, id },
44 DEFINE_SWITCH_ARRAY(MHFIXMSG, switches);
45 #undef X
46
47
48 int verbosw;
49 int debugsw; /* Needed by mhparse.c. */
50
51 #define quitser pipeser
52
53 /* mhparse.c */
54 extern char *tmp; /* directory to place tmp files */
55 extern int skip_mp_cte_check; /* flag to InitMultiPart */
56 extern int suppress_bogus_mp_content_warning; /* flag to InitMultiPart */
57 extern int bogus_mp_content; /* flag from InitMultiPart */
58 CT parse_mime (char *);
59 void reverse_parts (CT);
60
61 /* mhoutsbr.c */
62 int output_message (CT, char *);
63
64 /* mhshowsbr.c */
65 int show_content_aux (CT, int, int, char *, char *);
66
67 /* mhmisc.c */
68 void flush_errors (void);
69
70 /* mhfree.c */
71 extern CT *cts;
72 void freects_done (int) NORETURN;
73
74 /*
75 * static prototypes
76 */
77 typedef struct fix_transformations {
78 int fixboundary;
79 int fixcte;
80 int reformat;
81 int decodetext;
82 char *textcodeset;
83 } fix_transformations;
84
85 int mhfixmsgsbr (CT *, const fix_transformations *, char *);
86 static void reverse_alternative_parts (CT);
87 static int fix_boundary (CT *, int *);
88 static int get_multipart_boundary (CT, char **);
89 static int replace_boundary (CT, char *, const char *);
90 static char *update_attr (char *, const char *, const char *e);
91 static int fix_multipart_cte (CT, int *);
92 static int set_ce (CT, int);
93 static int ensure_text_plain (CT *, CT, int *);
94 static CT build_text_plain_part (CT);
95 static CT divide_part (CT);
96 static void copy_ctinfo (CI, CI);
97 static int decode_part (CT);
98 static int reformat_part (CT, char *, char *, char *, int);
99 static int charset_encoding (CT);
100 static CT build_multipart_alt (CT, CT, int, int);
101 static int boundary_in_content (FILE **, char *, const char *);
102 static void transfer_noncontent_headers (CT, CT);
103 static int set_ct_type (CT, int type, int subtype, int encoding);
104 static int decode_text_parts (CT, int, int *);
105 static int content_encoding (CT);
106 static int convert_codesets (CT, char *, int *);
107 static int convert_codeset (CT, char *, int *);
108 static int write_content (CT, char *, char *, int, int);
109 static int remove_file (char *);
110 static void report (char *, char *, char *, ...);
111 static char *upcase (char *);
112 static void pipeser (int);
113
114
115 int
116 main (int argc, char **argv) {
117 int msgnum;
118 char *cp, *file = NULL, *folder = NULL;
119 char *maildir, buf[100], *outfile = NULL;
120 char **argp, **arguments;
121 struct msgs_array msgs = { 0, 0, NULL };
122 struct msgs *mp = NULL;
123 CT *ctp;
124 FILE *fp;
125 int using_stdin = 0;
126 int status = OK;
127 fix_transformations fx;
128 fx.reformat = fx.fixcte = fx.fixboundary = 1;
129 fx.decodetext = CE_8BIT;
130 fx.textcodeset = NULL;
131
132 done = freects_done;
133
134 #ifdef LOCALE
135 setlocale(LC_ALL, "");
136 #endif
137 invo_name = r1bindex (argv[0], '/');
138
139 /* read user profile/context */
140 context_read();
141
142 arguments = getarguments (invo_name, argc, argv, 1);
143 argp = arguments;
144
145 /*
146 * Parse arguments
147 */
148 while ((cp = *argp++)) {
149 if (*cp == '-') {
150 switch (smatch (++cp, switches)) {
151 case AMBIGSW:
152 ambigsw (cp, switches);
153 done (1);
154 case UNKWNSW:
155 adios (NULL, "-%s unknown", cp);
156
157 case HELPSW:
158 snprintf (buf, sizeof buf, "%s [+folder] [msgs] [switches]",
159 invo_name);
160 print_help (buf, switches, 1);
161 done (0);
162 case VERSIONSW:
163 print_version(invo_name);
164 done (0);
165
166 case DECODETEXTSW:
167 if (! (cp = *argp++) || *cp == '-')
168 adios (NULL, "missing argument to %s", argp[-2]);
169 if (! strcasecmp (cp, "8bit")) {
170 fx.decodetext = CE_8BIT;
171 } else if (! strcasecmp (cp, "7bit")) {
172 fx.decodetext = CE_7BIT;
173 } else {
174 adios (NULL, "invalid argument to %s", argp[-2]);
175 }
176 continue;
177 case NDECODETEXTSW:
178 fx.decodetext = 0;
179 continue;
180 case TEXTCODESETSW:
181 if (! (cp = *argp++) || (*cp == '-' && cp[1]))
182 adios (NULL, "missing argument to %s", argp[-2]);
183 fx.textcodeset = cp;
184 continue;
185 case NTEXTCODESETSW:
186 fx.textcodeset = 0;
187 continue;
188 case FIXBOUNDARYSW:
189 fx.fixboundary = 1;
190 continue;
191 case NFIXBOUNDARYSW:
192 fx.fixboundary = 0;
193 continue;
194 case FIXCTESW:
195 fx.fixcte = 1;
196 continue;
197 case NFIXCTESW:
198 fx.fixcte = 0;
199 continue;
200 case REFORMATSW:
201 fx.reformat = 1;
202 continue;
203 case NREFORMATSW:
204 fx.reformat = 0;
205 continue;
206
207 case FILESW:
208 if (! (cp = *argp++) || (*cp == '-' && cp[1]))
209 adios (NULL, "missing argument to %s", argp[-2]);
210 file = *cp == '-' ? add (cp, NULL) : path (cp, TFILE);
211 continue;
212
213 case OUTFILESW:
214 if (! (cp = *argp++) || (*cp == '-' && cp[1]))
215 adios (NULL, "missing argument to %s", argp[-2]);
216 outfile = *cp == '-' ? add (cp, NULL) : path (cp, TFILE);
217 continue;
218
219 case VERBSW:
220 verbosw = 1;
221 continue;
222 case NVERBSW:
223 verbosw = 0;
224 continue;
225 }
226 }
227 if (*cp == '+' || *cp == '@') {
228 if (folder)
229 adios (NULL, "only one folder at a time!");
230 else
231 folder = pluspath (cp);
232 } else
233 app_msgarg(&msgs, cp);
234 }
235
236 SIGNAL (SIGQUIT, quitser);
237 SIGNAL (SIGPIPE, pipeser);
238
239 /*
240 * Read the standard profile setup
241 */
242 if ((fp = fopen (cp = etcpath ("mhn.defaults"), "r"))) {
243 readconfig ((struct node **) 0, fp, cp, 0);
244 fclose (fp);
245 }
246
247 /*
248 * Check for storage directory. If specified,
249 * then store temporary files there. Else we
250 * store them in standard nmh directory.
251 */
252 if ((cp = context_find (nmhstorage)) && *cp)
253 tmp = concat (cp, "/", invo_name, NULL);
254 else
255 tmp = add (m_maildir (invo_name), NULL);
256
257 suppress_bogus_mp_content_warning = skip_mp_cte_check = 1;
258
259 if (! context_find ("path"))
260 free (path ("./", TFOLDER));
261
262 if (file && msgs.size)
263 adios (NULL, "cannot specify msg and file at same time!");
264
265 /*
266 * check if message is coming from file
267 */
268 if (file) {
269 /* If file is stdin, create a tmp file name before parse_mime()
270 has a chance, because it might put in on a different
271 filesystem than the output file. Instead, put it in the
272 user's preferred tmp directory. */
273 CT ct;
274
275 if (! strcmp ("-", file)) {
276 int fd;
277 char *cp;
278
279 using_stdin = 1;
280
281 if ((cp = m_mktemp2 (tmp, invo_name, &fd, NULL)) == NULL) {
282 adios (NULL, "unable to create temporary file");
283 } else {
284 free (file);
285 file = add (cp, NULL);
286 chmod (file, 0600);
287 cpydata (STDIN_FILENO, fd, "-", file);
288 }
289
290 if (close (fd)) {
291 unlink (file);
292 adios (NULL, "failed to write temporary file");
293 }
294 }
295
296 if (! (cts = (CT *) calloc ((size_t) 2, sizeof *cts)))
297 adios (NULL, "out of memory");
298 ctp = cts;
299
300 if ((ct = parse_mime (file)))
301 *ctp++ = ct;
302 } else {
303 /*
304 * message(s) are coming from a folder
305 */
306 CT ct;
307
308 if (! msgs.size)
309 app_msgarg(&msgs, "cur");
310 if (! folder)
311 folder = getfolder (1);
312 maildir = m_maildir (folder);
313
314 if (chdir (maildir) == NOTOK)
315 adios (maildir, "unable to change directory to");
316
317 /* read folder and create message structure */
318 if (! (mp = folder_read (folder)))
319 adios (NULL, "unable to read folder %s", folder);
320
321 /* check for empty folder */
322 if (mp->nummsg == 0)
323 adios (NULL, "no messages in %s", folder);
324
325 /* parse all the message ranges/sequences and set SELECTED */
326 for (msgnum = 0; msgnum < msgs.size; msgnum++)
327 if (! m_convert (mp, msgs.msgs[msgnum]))
328 done (1);
329 seq_setprev (mp); /* set the previous-sequence */
330
331 if (! (cts = (CT *) calloc ((size_t) (mp->numsel + 1), sizeof *cts)))
332 adios (NULL, "out of memory");
333 ctp = cts;
334
335 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
336 if (is_selected(mp, msgnum)) {
337 char *msgnam;
338
339 msgnam = m_name (msgnum);
340 if ((ct = parse_mime (msgnam)))
341 *ctp++ = ct;
342 }
343 }
344
345 /*
346 * This is a hack. If we are using an external rmmproc,
347 * then save the current folder to the context file,
348 * so the external rmmproc will remove files from the correct
349 * directory. This should be moved to folder_delmsgs().
350 */
351 if (rmmproc) {
352 context_replace (pfolder, folder);/* update current folder */
353 seq_setcur (mp, mp->hghsel); /* update current message */
354 seq_save (mp); /* synchronize sequences */
355 context_save (); /* save the context file */
356 fflush (stdout);
357 }
358 }
359
360 if (*cts) {
361 for (ctp = cts; *ctp; ++ctp) {
362 status += mhfixmsgsbr (ctp, &fx, outfile);
363
364 if (using_stdin) {
365 unlink (file);
366
367 if (! outfile) {
368 /* Just calling m_backup() unlinks the backup file. */
369 (void) m_backup (file);
370 }
371 }
372 }
373 } else {
374 status = 1;
375 }
376
377 free (outfile);
378 free (tmp);
379 free (file);
380
381 /* done is freects_done, which will clean up all of cts. */
382 done (status);
383 return NOTOK;
384 }
385
386
387 int
388 mhfixmsgsbr (CT *ctp, const fix_transformations *fx, char *outfile) {
389 /* Store input filename in case one of the transformations, i.e.,
390 fix_boundary(), rewrites to a tmp file. */
391 char *input_filename = add ((*ctp)->c_file, NULL);
392 int modify_inplace = 0;
393 int message_mods = 0;
394 int status = OK;
395
396 if (outfile == NULL) {
397 modify_inplace = 1;
398
399 if ((*ctp)->c_file) {
400 outfile = add (m_mktemp2 (tmp, invo_name, NULL, NULL), NULL);
401 } else {
402 adios (NULL, "missing both input and output filenames\n");
403 }
404 }
405
406 reverse_alternative_parts (*ctp);
407 if (status == OK && fx->fixboundary) {
408 status = fix_boundary (ctp, &message_mods);
409 }
410 if (status == OK && fx->fixcte) {
411 status = fix_multipart_cte (*ctp, &message_mods);
412 }
413 if (status == OK && fx->reformat) {
414 status = ensure_text_plain (ctp, NULL, &message_mods);
415 }
416 if (status == OK && fx->decodetext) {
417 status = decode_text_parts (*ctp, fx->decodetext, &message_mods);
418 }
419 if (status == OK && fx->textcodeset != NULL) {
420 status = convert_codesets (*ctp, fx->textcodeset, &message_mods);
421 }
422
423 if (! (*ctp)->c_umask) {
424 /* Set the umask for the contents file. This currently
425 isn't used but just in case it is in the future. */
426 struct stat st;
427
428 if (stat ((*ctp)->c_file, &st) != NOTOK) {
429 (*ctp)->c_umask = ~(st.st_mode & 0777);
430 } else {
431 (*ctp)->c_umask = ~m_gmprot();
432 }
433 }
434
435 /*
436 * Write the content to a file
437 */
438 if (status == OK) {
439 status = write_content (*ctp, input_filename, outfile, modify_inplace,
440 message_mods);
441 } else if (! modify_inplace) {
442 /* Something went wrong. Output might be expected, such
443 as if this were run as a filter. Just copy the input
444 to the output. */
445 int in = open (input_filename, O_RDONLY);
446 int out = strcmp (outfile, "-")
447 ? open (outfile, O_WRONLY | O_CREAT, m_gmprot ())
448 : STDOUT_FILENO;
449
450 if (in != -1 && out != -1) {
451 cpydata (in, out, input_filename, outfile);
452 } else {
453 status = NOTOK;
454 }
455
456 close (out);
457 close (in);
458 }
459
460 if (modify_inplace) {
461 free (outfile);
462 outfile = NULL;
463 }
464
465 free (input_filename);
466
467 return status;
468 }
469
470
471 /* parse_mime() arranges alternates in reverse (priority) order, so
472 reverse them back. This will put a text/plain part at the front of
473 a multipart/alternative part, for example, where it belongs. */
474 static void
475 reverse_alternative_parts (CT ct) {
476 if (ct->c_type == CT_MULTIPART) {
477 struct multipart *m = (struct multipart *) ct->c_ctparams;
478 struct part *part;
479
480 if (ct->c_subtype == MULTI_ALTERNATE) {
481 reverse_parts (ct);
482 }
483
484 /* And call recursively on each part of a multipart. */
485 for (part = m->mp_parts; part; part = part->mp_next) {
486 reverse_alternative_parts (part->mp_part);
487 }
488 }
489 }
490
491
492 static int
493 fix_boundary (CT *ct, int *message_mods) {
494 struct multipart *mp;
495 int status = OK;
496
497 if (bogus_mp_content) {
498 mp = (struct multipart *) (*ct)->c_ctparams;
499
500 /*
501 * 1) Get boundary at end of part.
502 * 2) Get boundary at beginning of part and compare to the end-of-part
503 * boundary.
504 * 3) Write out contents of ct to tmp file, replacing boundary in
505 * header with boundary from part. Set c_unlink to 1.
506 * 4) Free ct.
507 * 5) Call parse_mime() on the tmp file, replacing ct.
508 */
509
510 if (mp && mp->mp_start) {
511 char *part_boundary;
512
513 if (get_multipart_boundary (*ct, &part_boundary) == OK) {
514 char *fixed;
515
516 if ((fixed = m_mktemp2 (tmp, invo_name, NULL, &(*ct)->c_fp))) {
517 if (replace_boundary (*ct, fixed, part_boundary) == OK) {
518 char *filename = add ((*ct)->c_file, NULL);
519
520 free_content (*ct);
521 *ct = parse_mime (fixed);
522 (*ct)->c_unlink = 1;
523
524 ++*message_mods;
525 if (verbosw) {
526 report (NULL, filename, "fix multipart boundary");
527 }
528 free (filename);
529 } else {
530 advise (NULL, "unable to replace broken boundary");
531 status = NOTOK;
532 }
533 } else {
534 advise (NULL, "unable to create temporary file");
535 status = NOTOK;
536 }
537
538 free (part_boundary);
539 }
540 }
541 }
542
543 return status;
544 }
545
546
547 static int
548 get_multipart_boundary (CT ct, char **part_boundary) {
549 char buffer[BUFSIZ];
550 char *end_boundary = NULL;
551 off_t begin = (off_t) ct->c_end > (off_t) (ct->c_begin + sizeof buffer)
552 ? (off_t) (ct->c_end - sizeof buffer)
553 : (off_t) ct->c_begin;
554 size_t bytes_read;
555 int status = OK;
556
557 /* This will fail if the boundary spans fread() calls. BUFSIZ should
558 be big enough, even if it's just 1024, to make that unlikely. */
559
560 /* free_content() will close ct->c_fp. */
561 if (! ct->c_fp && (ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
562 advise (ct->c_file, "unable to open for reading");
563 return NOTOK;
564 }
565
566 /* Get boundary at end of multipart. */
567 while (begin >= (off_t) ct->c_begin) {
568 fseeko (ct->c_fp, begin, SEEK_SET);
569 while ((bytes_read = fread (buffer, 1, sizeof buffer, ct->c_fp)) > 0) {
570 char *end = buffer + bytes_read - 1;
571 char *cp;
572
573 if ((cp = rfind_str (buffer, bytes_read, "--"))) {
574 /* Trim off trailing "--" and anything beyond. */
575 *cp-- = '\0';
576 if ((end = rfind_str (buffer, cp - buffer, "\n"))) {
577 if (strlen (end) > 3 && *end++ == '\n' &&
578 *end++ == '-' && *end++ == '-') {
579 end_boundary = add (end, NULL);
580 break;
581 }
582 }
583 }
584 }
585
586 if (! end_boundary && begin > (off_t) (ct->c_begin + sizeof buffer)) {
587 begin -= sizeof buffer;
588 } else {
589 break;
590 }
591 }
592
593 /* Get boundary at beginning of multipart. */
594 if (end_boundary) {
595 fseeko (ct->c_fp, ct->c_begin, SEEK_SET);
596 while ((bytes_read = fread (buffer, 1, sizeof buffer, ct->c_fp)) > 0) {
597 if (bytes_read >= strlen (end_boundary)) {
598 char *cp = find_str (buffer, bytes_read, end_boundary);
599
600 if (cp && cp - buffer >= 2 && *--cp == '-' &&
601 *--cp == '-' && (cp > buffer && *--cp == '\n')) {
602 break;
603 }
604 /* Else the start and end boundaries didn't match, or
605 the start boundary doesn't begin with "\n--" (or
606 "--" if at the beginning of buffer). Keep trying. */
607 } else {
608 status = NOTOK;
609 }
610 }
611 }
612
613 if (status == OK) {
614 *part_boundary = end_boundary;
615 } else {
616 *part_boundary = NULL;
617 free (end_boundary);
618 }
619
620 return status;
621 }
622
623
624 /* Open and copy ct->c_file to file, replacing the multipart boundary. */
625 static int
626 replace_boundary (CT ct, char *file, const char *boundary) {
627 FILE *fpin, *fpout;
628 int compnum, state;
629 char buf[BUFSIZ], name[NAMESZ];
630 char *np, *vp;
631 m_getfld_state_t gstate = 0;
632 int status = OK;
633
634 if (ct->c_file == NULL) {
635 advise (NULL, "missing input filename");
636 return NOTOK;
637 }
638
639 if ((fpin = fopen (ct->c_file, "r")) == NULL) {
640 advise (ct->c_file, "unable to open for reading");
641 return NOTOK;
642 }
643
644 if ((fpout = fopen (file, "w")) == NULL) {
645 fclose (fpin);
646 advise (file, "unable to open for writing");
647 return NOTOK;
648 }
649
650 for (compnum = 1;;) {
651 int bufsz = (int) sizeof buf;
652
653 switch (state = m_getfld (&gstate, name, buf, &bufsz, fpin)) {
654 case FLD:
655 case FLDPLUS:
656 compnum++;
657
658 /* get copies of the buffers */
659 np = add (name, NULL);
660 vp = add (buf, NULL);
661
662 /* if necessary, get rest of field */
663 while (state == FLDPLUS) {
664 bufsz = sizeof buf;
665 state = m_getfld (&gstate, name, buf, &bufsz, fpin);
666 vp = add (buf, vp); /* add to previous value */
667 }
668
669 if (strcasecmp (TYPE_FIELD, np)) {
670 fprintf (fpout, "%s:%s", np, vp);
671 } else {
672 char *new_boundary = update_attr (vp, "boundary=", boundary);
673
674 fprintf (fpout, "%s:%s\n", np, new_boundary);
675 free (new_boundary);
676 }
677
678 free (vp);
679 free (np);
680
681 continue;
682
683 case BODY:
684 fputs ("\n", fpout);
685 /* buf will have a terminating NULL, skip it. */
686 fwrite (buf, 1, bufsz-1, fpout);
687 continue;
688
689 case FILEEOF:
690 break;
691
692 case LENERR:
693 case FMTERR:
694 advise (NULL, "message format error in component #%d", compnum);
695 status = NOTOK;
696 break;
697
698 default:
699 advise (NULL, "getfld() returned %d", state);
700 status = NOTOK;
701 break;
702 }
703
704 break;
705 }
706
707 m_getfld_state_destroy (&gstate);
708 fclose (fpout);
709 fclose (fpin);
710
711 return status;
712 }
713
714
715 /* Change the value of a name=value pair in a header field body.
716 If the name isn't there, append them. In any case, a new
717 string will be allocated and must be free'd by the caller.
718 Trims any trailing newlines. */
719 static char *
720 update_attr (char *body, const char *name, const char *value) {
721 char *bp = nmh_strcasestr (body, name);
722 char *new_body;
723
724 if (bp) {
725 char *other_attrs = strchr (bp, ';');
726
727 *(bp + strlen (name)) = '\0';
728 new_body = concat (body, "\"", value, "\"", NULL);
729
730 if (other_attrs) {
731 char *cp;
732
733 /* Trim any trailing newlines. */
734 for (cp = &other_attrs[strlen (other_attrs) - 1];
735 cp > other_attrs && *cp == '\n';
736 *cp-- = '\0') continue;
737 new_body = add (other_attrs, new_body);
738 }
739 } else {
740 char *cp;
741
742 /* Append name/value pair, after first removing a final newline
743 and (extraneous) semicolon. */
744 if (*(cp = &body[strlen (body) - 1]) == '\n') *cp = '\0';
745 if (*(cp = &body[strlen (body) - 1]) == ';') *cp = '\0';
746 new_body = concat (body, "; ", name, "\"", value, "\"", NULL);
747 }
748
749 return new_body;
750 }
751
752
753 static int
754 fix_multipart_cte (CT ct, int *message_mods) {
755 int status = OK;
756
757 if (ct->c_type == CT_MULTIPART) {
758 struct multipart *m;
759 struct part *part;
760
761 if (ct->c_encoding != CE_7BIT && ct->c_encoding != CE_8BIT &&
762 ct->c_encoding != CE_BINARY) {
763 HF hf;
764
765 for (hf = ct->c_first_hf; hf; hf = hf->next) {
766 char *name = hf->name;
767 for (; *name && isspace ((unsigned char) *name); ++name) {
768 continue;
769 }
770
771 if (! strncasecmp (name, ENCODING_FIELD,
772 strlen (ENCODING_FIELD))) {
773 char *prefix = "Nmh-REPLACED-INVALID-";
774 HF h = mh_xmalloc (sizeof *h);
775
776 h->name = add (hf->name, NULL);
777 h->hf_encoding = hf->hf_encoding;
778 h->next = hf->next;
779 hf->next = h;
780
781 /* Retain old header but prefix its name. */
782 free (hf->name);
783 hf->name = concat (prefix, h->name, NULL);
784
785 ++*message_mods;
786 if (verbosw) {
787 char *encoding = cpytrim (hf->value);
788 report (ct->c_partno, ct->c_file,
789 "replace Content-Transfer-Encoding of %s "
790 "with 8 bit", encoding);
791 free (encoding);
792 }
793
794 h->value = add (" 8bit\n", NULL);
795
796 /* Don't need to warn for multiple C-T-E header
797 fields, parse_mime() already does that. But
798 if there are any, fix them all as necessary. */
799 hf = h;
800 }
801 }
802
803 set_ce (ct, CE_8BIT);
804 }
805
806 m = (struct multipart *) ct->c_ctparams;
807 for (part = m->mp_parts; part; part = part->mp_next) {
808 if (fix_multipart_cte (part->mp_part, message_mods) != OK) {
809 status = NOTOK;
810 break;
811 }
812 }
813 }
814
815 return status;
816 }
817
818
819 static int
820 set_ce (CT ct, int encoding) {
821 const char *ce = ce_str (encoding);
822 const struct str2init *ctinit = get_ce_method (ce);
823
824 if (ctinit) {
825 char *cte = concat (" ", ce, "\n", NULL);
826 int found_cte = 0;
827 HF hf;
828 /* Decoded contents might be in ct->c_cefile.ce_file, if the
829 caller is decode_text_parts (). Save because we'll
830 overwrite below. */
831 struct cefile decoded_content_info = ct->c_cefile;
832
833 ct->c_encoding = encoding;
834
835 ct->c_ctinitfnx = ctinit->si_init;
836 /* This will assign ct->c_cefile with an all-0 struct, which
837 is what we want. */
838 (*ctinit->si_init) (ct);
839 /* After returning, the caller should set
840 ct->c_cefile.ce_file to the name of the file containing
841 the contents. */
842
843 /* Restore the cefile. */
844 ct->c_cefile = decoded_content_info;
845
846 /* Update/add Content-Transfer-Encoding header field. */
847 for (hf = ct->c_first_hf; hf; hf = hf->next) {
848 if (! strcasecmp (ENCODING_FIELD, hf->name)) {
849 found_cte = 1;
850 free (hf->value);
851 hf->value = cte;
852 }
853 }
854 if (! found_cte) {
855 add_header (ct, add (ENCODING_FIELD, NULL), cte);
856 }
857
858 /* Update c_celine. It's used only by mhlist -debug. */
859 free (ct->c_celine);
860 ct->c_celine = add (cte, NULL);
861
862 return OK;
863 } else {
864 return NOTOK;
865 }
866 }
867
868
869 /* Make sure each text part has a corresponding text/plain part. */
870 static int
871 ensure_text_plain (CT *ct, CT parent, int *message_mods) {
872 int status = OK;
873
874 switch ((*ct)->c_type) {
875 case CT_TEXT: {
876 int has_text_plain = 0;
877
878 /* Nothing to do for text/plain. */
879 if ((*ct)->c_subtype == TEXT_PLAIN) return OK;
880
881 if (parent && parent->c_type == CT_MULTIPART &&
882 parent->c_subtype == MULTI_ALTERNATE) {
883 struct multipart *mp = (struct multipart *) parent->c_ctparams;
884 struct part *part;
885 int new_subpart_number = 1;
886
887 /* See if there is a sibling text/plain. */
888 for (part = mp->mp_parts; part; part = part->mp_next) {
889 ++new_subpart_number;
890 if (part->mp_part->c_type == CT_TEXT &&
891 part->mp_part->c_subtype == TEXT_PLAIN) {
892 has_text_plain = 1;
893 break;
894 }
895 }
896
897 if (! has_text_plain) {
898 /* Parent is a multipart/alternative. Insert a new
899 text/plain subpart. */
900 struct part *new_part = mh_xmalloc (sizeof *new_part);
901
902 if ((new_part->mp_part = build_text_plain_part (*ct))) {
903 char buffer[16];
904 snprintf (buffer, sizeof buffer, "%d", new_subpart_number);
905
906 new_part->mp_next = mp->mp_parts;
907 mp->mp_parts = new_part;
908 new_part->mp_part->c_partno =
909 concat (parent->c_partno ? parent->c_partno : "1", ".",
910 buffer, NULL);
911
912 ++*message_mods;
913 if (verbosw) {
914 report (parent->c_partno, parent->c_file,
915 "insert text/plain part");
916 }
917 } else {
918 free_content (new_part->mp_part);
919 free (new_part);
920 status = NOTOK;
921 }
922 }
923 } else {
924 /* Slip new text/plain part into a new multipart/alternative. */
925 CT tp_part = build_text_plain_part (*ct);
926 CT mp_alt = build_multipart_alt (*ct, tp_part, CT_MULTIPART,
927 MULTI_ALTERNATE);
928 struct multipart *mp = (struct multipart *) mp_alt->c_ctparams;
929
930 if (mp && mp->mp_parts && (mp->mp_parts->mp_part = tp_part)) {
931 /* Make the new multipart/alternative the parent. */
932 *ct = mp_alt;
933
934 ++*message_mods;
935 if (verbosw) {
936 report ((*ct)->c_partno, (*ct)->c_file,
937 "insert text/plain part");
938 }
939 } else {
940 free_content (tp_part);
941
942 /* Undo enough of what build_multipart_alt() did so
943 that free_content() can be called on mp_alt. */
944 mp->mp_parts->mp_part = NULL;
945 mp->mp_parts->mp_next->mp_part = NULL;
946 free_content (mp_alt);
947 status = NOTOK;
948 }
949 }
950 break;
951 }
952
953 case CT_MULTIPART: {
954 struct multipart *mp = (struct multipart *) (*ct)->c_ctparams;
955 struct part *part;
956
957 for (part = mp->mp_parts; status == OK && part; part = part->mp_next) {
958 if ((*ct)->c_type == CT_MULTIPART) {
959 status = ensure_text_plain (&part->mp_part, *ct, message_mods);
960 }
961 }
962 break;
963 }
964
965 case CT_MESSAGE:
966 if ((*ct)->c_subtype == MESSAGE_EXTERNAL) {
967 struct exbody *e;
968
969 e = (struct exbody *) (*ct)->c_ctparams;
970 status = ensure_text_plain (&e->eb_content, *ct, message_mods);
971 }
972 break;
973 }
974
975 return status;
976 }
977
978
979 static CT
980 build_text_plain_part (CT encoded_part) {
981 CT tp_part = divide_part (encoded_part);
982 char *tmp_plain_file = NULL;
983
984 if (decode_part (tp_part) == OK) {
985 /* Now, tp_part->c_cefile.ce_file is the name of the tmp file that
986 contains the decoded contents. And the decoding function, such
987 as openQuoted, will have set ...->ce_unlink to 1 so that it will
988 be unlinked by free_content (). */
989 tmp_plain_file = add (m_mktemp2 (tmp, invo_name, NULL, NULL), NULL);
990 if (reformat_part (tp_part, tmp_plain_file,
991 tp_part->c_ctinfo.ci_type,
992 tp_part->c_ctinfo.ci_subtype,
993 tp_part->c_type) == OK) {
994 return tp_part;
995 }
996 }
997
998 free_content (tp_part);
999 unlink (tmp_plain_file);
1000 free (tmp_plain_file);
1001
1002 return NULL;
1003 }
1004
1005
1006 static CT
1007 divide_part (CT ct) {
1008 CT new_part;
1009
1010 if ((new_part = (CT) calloc (1, sizeof *new_part)) == NULL)
1011 adios (NULL, "out of memory");
1012
1013 /* Just copy over what is needed for decoding. c_vrsn and
1014 c_celine aren't necessary. */
1015 new_part->c_file = add (ct->c_file, NULL);
1016 new_part->c_begin = ct->c_begin;
1017 new_part->c_end = ct->c_end;
1018 copy_ctinfo (&new_part->c_ctinfo, &ct->c_ctinfo);
1019 new_part->c_type = ct->c_type;
1020 new_part->c_cefile = ct->c_cefile;
1021 new_part->c_encoding = ct->c_encoding;
1022 new_part->c_ctinitfnx = ct->c_ctinitfnx;
1023 new_part->c_ceopenfnx = ct->c_ceopenfnx;
1024 new_part->c_ceclosefnx = ct->c_ceclosefnx;
1025 new_part->c_cesizefnx = ct->c_cesizefnx;
1026
1027 /* c_ctline is used by reformat__part(), so it can preserve
1028 anything after the type/subtype. */
1029 new_part->c_ctline = add (ct->c_ctline, NULL);
1030
1031 return new_part;
1032 }
1033
1034
1035 static void
1036 copy_ctinfo (CI dest, CI src) {
1037 char **s_ap, **d_ap, **s_vp, **d_vp;
1038
1039 dest->ci_type = src->ci_type ? add (src->ci_type, NULL) : NULL;
1040 dest->ci_subtype = src->ci_subtype ? add (src->ci_subtype, NULL) : NULL;
1041
1042 for (s_ap = src->ci_attrs, d_ap = dest->ci_attrs,
1043 s_vp = src->ci_values, d_vp = dest->ci_values;
1044 *s_ap;
1045 ++s_ap, ++d_ap, ++s_vp, ++d_vp) {
1046 *d_ap = add (*s_ap, NULL);
1047 *d_vp = *s_vp;
1048 }
1049 *d_ap = NULL;
1050
1051 dest->ci_comment = src->ci_comment ? add (src->ci_comment, NULL) : NULL;
1052 dest->ci_magic = src->ci_magic ? add (src->ci_magic, NULL) : NULL;
1053 }
1054
1055
1056 static int
1057 decode_part (CT ct) {
1058 char *tmp_decoded;
1059 int status;
1060
1061 tmp_decoded = add (m_mktemp2 (tmp, invo_name, NULL, NULL), NULL);
1062 /* The following call will load ct->c_cefile.ce_file with the tmp
1063 filename of the decoded content. tmp_decoded will contain the
1064 encoded output, get rid of that. */
1065 status = output_message (ct, tmp_decoded);
1066 unlink (tmp_decoded);
1067 free (tmp_decoded);
1068
1069 return status;
1070 }
1071
1072
1073 /* Some of the arguments aren't really needed now, but maybe will
1074 be in the future for other than text types. */
1075 static int
1076 reformat_part (CT ct, char *file, char *type, char *subtype, int c_type) {
1077 int output_subtype, output_encoding;
1078 char *cp, *cf;
1079 int status;
1080
1081 /* Hacky: this redirects the output from whatever command is used
1082 to show the part to a file. So, the user can't have any output
1083 redirection in that command.
1084 Could show_multi() in mhshowsbr.c avoid this? */
1085
1086 /* Check for invo_name-format-type/subtype. */
1087 cp = concat (invo_name, "-format-", type, "/", subtype, NULL);
1088 if ((cf = context_find (cp)) && *cf != '\0') {
1089 if (strchr (cf, '>')) {
1090 free (cp);
1091 advise (NULL, "'>' prohibited in \"%s\",\nplease fix your "
1092 "%s-format-%s/%s profile entry", cf, invo_name, type,
1093 subtype);
1094 return NOTOK;
1095 }
1096 } else {
1097 free (cp);
1098
1099 /* Check for invo_name-format-type. */
1100 cp = concat (invo_name, "-format-", type, NULL);
1101 if (! (cf = context_find (cp)) || *cf == '\0') {
1102 free (cp);
1103 if (verbosw) {
1104 advise (NULL, "Don't know how to convert %s, there is no "
1105 "%s-format-%s/%s profile entry",
1106 ct->c_file, invo_name, type, subtype);
1107 }
1108 return NOTOK;
1109 }
1110
1111 if (strchr (cf, '>')) {
1112 free (cp);
1113 advise (NULL, "'>' prohibited in \"%s\"", cf);
1114 return NOTOK;
1115 }
1116 }
1117 free (cp);
1118
1119 cp = concat (cf, " >", file, NULL);
1120 status = show_content_aux (ct, 1, 0, cp, NULL);
1121 free (cp);
1122
1123 /* Unlink decoded content tmp file and free its filename to avoid
1124 leaks. The file stream should already have been closed. */
1125 if (ct->c_cefile.ce_unlink) {
1126 unlink (ct->c_cefile.ce_file);
1127 free (ct->c_cefile.ce_file);
1128 ct->c_cefile.ce_file = NULL;
1129 ct->c_cefile.ce_unlink = 0;
1130 }
1131
1132 if (c_type == CT_TEXT) {
1133 output_subtype = TEXT_PLAIN;
1134 } else {
1135 /* Set subtype to 0, which is always an UNKNOWN subtype. */
1136 output_subtype = 0;
1137 }
1138 output_encoding = charset_encoding (ct);
1139
1140 if (set_ct_type (ct, c_type, output_subtype, output_encoding) == OK) {
1141 ct->c_cefile.ce_file = file;
1142 ct->c_cefile.ce_unlink = 1;
1143 } else {
1144 ct->c_cefile.ce_unlink = 0;
1145 status = NOTOK;
1146 }
1147
1148 return status;
1149 }
1150
1151
1152 /* Identifies 7bit or 8bit content based on charset, if specified. */
1153 static int
1154 charset_encoding (CT ct) {
1155 int encoding = CE_8BIT;
1156 CI ctinfo = &ct->c_ctinfo;
1157 char **ap, **vp;
1158
1159 for (ap = ctinfo->ci_attrs, vp = ctinfo->ci_values; *ap; ++ap, ++vp) {
1160 if (! strcasecmp (*ap, "charset")) {
1161 /* norm_charmap() is case sensitive. */
1162 char *ch = upcase (*vp);
1163
1164 if (! strcmp (norm_charmap (ch), "US-ASCII")) encoding = CE_7BIT;
1165 free (ch);
1166 break;
1167 }
1168 }
1169
1170 return encoding;
1171 }
1172
1173
1174 static CT
1175 build_multipart_alt (CT first_alt, CT new_part, int type, int subtype) {
1176 char *boundary_prefix = "----=_nmh-multipart";
1177 char *boundary = concat (boundary_prefix, first_alt->c_partno, NULL);
1178 char *boundary_indicator = "; boundary=";
1179 char *typename, *subtypename, *name;
1180 CT ct;
1181 struct part *p;
1182 struct multipart *m;
1183 char *cp;
1184 const struct str2init *ctinit;
1185
1186 if ((ct = (CT) calloc (1, sizeof *ct)) == NULL)
1187 adios (NULL, "out of memory");
1188
1189 /* Set up the multipart/alternative part. These fields of *ct were
1190 initialized to 0 by calloc():
1191 c_fp, c_unlink, c_begin, c_end,
1192 c_vrsn, c_ctline, c_celine,
1193 c_id, c_descr, c_dispo, c_partno,
1194 c_ctinfo.ci_comment, c_ctinfo.ci_magic,
1195 c_cefile, c_encoding,
1196 c_digested, c_digest[16], c_ctexbody,
1197 c_ctinitfnx, c_ceopenfnx, c_ceclosefnx, c_cesizefnx,
1198 c_umask, c_pid, c_rfc934,
1199 c_showproc, c_termproc, c_storeproc, c_storage, c_folder
1200 */
1201
1202 ct->c_file = add (first_alt->c_file, NULL);
1203 ct->c_type = type;
1204 ct->c_subtype = subtype;
1205
1206 ctinit = get_ct_init (ct->c_type);
1207
1208 typename = ct_type_str (type);
1209 subtypename = ct_subtype_str (type, subtype);
1210
1211 {
1212 int serial = 0;
1213 int found_boundary = 1;
1214
1215 while (found_boundary && serial < 1000000) {
1216 found_boundary = 0;
1217
1218 /* Ensure that the boundary doesn't appear in the decoded
1219 content. */
1220 if (new_part->c_cefile.ce_file) {
1221 if ((found_boundary =
1222 boundary_in_content (&new_part->c_cefile.ce_fp,
1223 new_part->c_cefile.ce_file,
1224 boundary)) == -1) {
1225 return NULL;
1226 }
1227 }
1228
1229 /* Ensure that the boundary doesn't appear in the encoded
1230 content. */
1231 if (! found_boundary && new_part->c_file) {
1232 if ((found_boundary = boundary_in_content (&new_part->c_fp,
1233 new_part->c_file,
1234 boundary)) == -1) {
1235 return NULL;
1236 }
1237 }
1238
1239 if (found_boundary) {
1240 /* Try a slightly different boundary. */
1241 char buffer2[16];
1242
1243 free (boundary);
1244 ++serial;
1245 snprintf (buffer2, sizeof buffer2, "%d", serial);
1246 boundary =
1247 concat (boundary_prefix,
1248 first_alt->c_partno ? first_alt->c_partno : "",
1249 "-", buffer2, NULL);
1250 }
1251 }
1252
1253 if (found_boundary) {
1254 advise (NULL, "giving up trying to find a unique boundary");
1255 return NULL;
1256 }
1257 }
1258
1259 name = concat (" ", typename, "/", subtypename, boundary_indicator, "\"",
1260 boundary, "\"", NULL);
1261
1262 /* Load c_first_hf and c_last_hf. */
1263 transfer_noncontent_headers (first_alt, ct);
1264 add_header (ct, add (TYPE_FIELD, NULL), concat (name, "\n", NULL));
1265 free (name);
1266
1267 /* Load c_partno. */
1268 if (first_alt->c_partno) {
1269 ct->c_partno = add (first_alt->c_partno, NULL);
1270 free (first_alt->c_partno);
1271 first_alt->c_partno = concat (ct->c_partno, ".1", NULL);
1272 new_part->c_partno = concat (ct->c_partno, ".2", NULL);
1273 } else {
1274 first_alt->c_partno = add ("1", NULL);
1275 new_part->c_partno = add ("2", NULL);
1276 }
1277
1278 if (ctinit) {
1279 ct->c_ctinfo.ci_type = add (typename, NULL);
1280 ct->c_ctinfo.ci_subtype = add (subtypename, NULL);
1281 }
1282
1283 name = concat (" ", typename, "/", subtypename, boundary_indicator,
1284 boundary, NULL);
1285 if ((cp = strstr (name, boundary_indicator))) {
1286 ct->c_ctinfo.ci_attrs[0] = name;
1287 ct->c_ctinfo.ci_attrs[1] = NULL;
1288 /* ci_values don't get free'd, so point into ci_attrs. */
1289 ct->c_ctinfo.ci_values[0] = cp + strlen (boundary_indicator);
1290 }
1291
1292 p = (struct part *) mh_xmalloc (sizeof *p);
1293 p->mp_next = (struct part *) mh_xmalloc (sizeof *p->mp_next);
1294 p->mp_next->mp_next = NULL;
1295 p->mp_next->mp_part = first_alt;
1296
1297 if ((m = (struct multipart *) calloc (1, sizeof (struct multipart))) ==
1298 NULL)
1299 adios (NULL, "out of memory");
1300 m->mp_start = concat (boundary, "\n", NULL);
1301 m->mp_stop = concat (boundary, "--\n", NULL);
1302 m->mp_parts = p;
1303 ct->c_ctparams = (void *) m;
1304
1305 free (boundary);
1306
1307 return ct;
1308 }
1309
1310
1311 /* Check that the boundary does not appear in the content. */
1312 static int
1313 boundary_in_content (FILE **fp, char *file, const char *boundary) {
1314 char buffer[BUFSIZ];
1315 size_t bytes_read;
1316 int found_boundary = 0;
1317
1318 /* free_content() will close *fp if we fopen it here. */
1319 if (! *fp && (*fp = fopen (file, "r")) == NULL) {
1320 advise (file, "unable to open %s for reading", file);
1321 return NOTOK;
1322 }
1323
1324 fseeko (*fp, 0L, SEEK_SET);
1325 while ((bytes_read = fread (buffer, 1, sizeof buffer, *fp)) > 0) {
1326 if (find_str (buffer, bytes_read, boundary)) {
1327 found_boundary = 1;
1328 break;
1329 }
1330 }
1331
1332 return found_boundary;
1333 }
1334
1335
1336 /* Remove all non-Content headers. */
1337 static void
1338 transfer_noncontent_headers (CT old, CT new) {
1339 HF hp, hp_prev;
1340
1341 hp_prev = hp = old->c_first_hf;
1342 while (hp) {
1343 HF next = hp->next;
1344
1345 if (strncasecmp (XXX_FIELD_PRF, hp->name, strlen (XXX_FIELD_PRF))) {
1346 if (hp == old->c_last_hf) {
1347 if (hp == old->c_first_hf) {
1348 old->c_last_hf = old->c_first_hf = NULL;
1349 } else {
1350 hp_prev->next = NULL;
1351 old->c_last_hf = hp_prev;
1352 }
1353 } else {
1354 if (hp == old->c_first_hf) {
1355 old->c_first_hf = next;
1356 } else {
1357 hp_prev->next = next;
1358 }
1359 }
1360
1361 /* Put node hp in the new CT. */
1362 if (new->c_first_hf == NULL) {
1363 new->c_first_hf = hp;
1364 } else {
1365 new->c_last_hf->next = hp;
1366 }
1367 new->c_last_hf = hp;
1368 } else {
1369 /* A Content- header, leave in old. */
1370 hp_prev = hp;
1371 }
1372
1373 hp = next;
1374 }
1375 }
1376
1377
1378 static int
1379 set_ct_type (CT ct, int type, int subtype, int encoding) {
1380 char *typename = ct_type_str (type);
1381 char *subtypename = ct_subtype_str (type, subtype);
1382 /* E.g, " text/plain" */
1383 char *type_subtypename = concat (" ", typename, "/", subtypename, NULL);
1384 /* E.g, " text/plain\n" */
1385 char *name_plus_nl = concat (type_subtypename, "\n", NULL);
1386 int found_content_type = 0;
1387 HF hf;
1388 const char *cp = NULL;
1389 char *ctline;
1390 int status;
1391
1392 /* Update/add Content-Type header field. */
1393 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1394 if (! strcasecmp (TYPE_FIELD, hf->name)) {
1395 found_content_type = 1;
1396 free (hf->value);
1397 hf->value = (cp = strchr (ct->c_ctline, ';'))
1398 ? concat (type_subtypename, cp, "\n", NULL)
1399 : add (name_plus_nl, NULL);
1400 }
1401 }
1402 if (! found_content_type) {
1403 add_header (ct, add (TYPE_FIELD, NULL),
1404 (cp = strchr (ct->c_ctline, ';'))
1405 ? concat (type_subtypename, cp, "\n", NULL)
1406 : add (name_plus_nl, NULL));
1407 }
1408
1409 /* Some of these might not be used, but set them anyway. */
1410 ctline = cp
1411 ? concat (type_subtypename, cp, NULL)
1412 : concat (type_subtypename, NULL);
1413 free (ct->c_ctline);
1414 ct->c_ctline = ctline;
1415 /* Leave other ctinfo members as they were. */
1416 free (ct->c_ctinfo.ci_type);
1417 ct->c_ctinfo.ci_type = add (typename, NULL);
1418 free (ct->c_ctinfo.ci_subtype);
1419 ct->c_ctinfo.ci_subtype = add (subtypename, NULL);
1420 ct->c_type = type;
1421 ct->c_subtype = subtype;
1422
1423 free (name_plus_nl);
1424 free (type_subtypename);
1425
1426 status = set_ce (ct, encoding);
1427
1428 return status;
1429 }
1430
1431
1432 static int
1433 decode_text_parts (CT ct, int encoding, int *message_mods) {
1434 int status = OK;
1435
1436 switch (ct->c_type) {
1437 case CT_TEXT:
1438 switch (ct->c_encoding) {
1439 case CE_BASE64:
1440 case CE_QUOTED: {
1441 int ct_encoding;
1442
1443 if (decode_part (ct) == OK && ct->c_cefile.ce_file) {
1444 if ((ct_encoding = content_encoding (ct)) == CE_BINARY &&
1445 encoding != CE_BINARY) {
1446 if (verbosw) {
1447 report (ct->c_partno, ct->c_file,
1448 "will not decode%s because it is binary",
1449 ct->c_partno ? ""
1450 : ct->c_ctline ? ct->c_ctline
1451 : "");
1452 }
1453 unlink (ct->c_cefile.ce_file);
1454 free (ct->c_cefile.ce_file);
1455 ct->c_cefile.ce_file = NULL;
1456 } else if (ct_encoding == CE_8BIT && encoding == CE_7BIT) {
1457 if (verbosw) {
1458 report (ct->c_partno, ct->c_file,
1459 "will not decode%s because it is 8bit",
1460 ct->c_partno ? ""
1461 : ct->c_ctline ? ct->c_ctline
1462 : "");
1463 }
1464 unlink (ct->c_cefile.ce_file);
1465 free (ct->c_cefile.ce_file);
1466 ct->c_cefile.ce_file = NULL;
1467 } else {
1468 int enc = ct_encoding == CE_BINARY
1469 ? CE_BINARY
1470 : charset_encoding (ct);
1471 if (set_ce (ct, enc) == OK) {
1472 ++*message_mods;
1473 if (verbosw) {
1474 report (ct->c_partno, ct->c_file, "decode%s",
1475 ct->c_ctline ? ct->c_ctline : "");
1476 }
1477 } else {
1478 status = NOTOK;
1479 }
1480 }
1481 } else {
1482 status = NOTOK;
1483 }
1484 break;
1485 }
1486 default:
1487 break;
1488 }
1489 break;
1490
1491 case CT_MULTIPART: {
1492 struct multipart *m = (struct multipart *) ct->c_ctparams;
1493 struct part *part;
1494
1495 /* Should check to see if the body for this part is encoded?
1496 For now, it gets passed along as-is by InitMultiPart(). */
1497 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
1498 status = decode_text_parts (part->mp_part, encoding, message_mods);
1499 }
1500 break;
1501 }
1502
1503 case CT_MESSAGE:
1504 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1505 struct exbody *e;
1506
1507 e = (struct exbody *) ct->c_ctparams;
1508 status = decode_text_parts (e->eb_content, encoding, message_mods);
1509 }
1510 break;
1511
1512 default:
1513 break;
1514 }
1515
1516 return status;
1517 }
1518
1519
1520 /* See if the decoded content is 7bit, 8bit, or binary. It's binary
1521 if it has any NUL characters, a CR not followed by a LF, or lines
1522 greater than 998 characters in length. */
1523 static int
1524 content_encoding (CT ct) {
1525 CE ce = &ct->c_cefile;
1526 int encoding = CE_7BIT;
1527
1528 if (ce->ce_file) {
1529 char buffer[BUFSIZ];
1530 size_t inbytes;
1531
1532 if (! ce->ce_fp && (ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
1533 advise (ce->ce_file, "unable to open for reading");
1534 return CE_UNKNOWN;
1535 }
1536
1537 fseeko (ce->ce_fp, 0L, SEEK_SET);
1538 while (encoding != CE_BINARY &&
1539 (inbytes = fread (buffer, 1, sizeof buffer, ce->ce_fp)) > 0) {
1540 char *cp;
1541 size_t i;
1542 size_t line_len = 0;
1543 int last_char_was_cr = 0;
1544
1545 for (i = 0, cp = buffer; i < inbytes; ++i, ++cp) {
1546 if (*cp == '\0' || ++line_len > 998 ||
1547 (*cp != '\n' && last_char_was_cr)) {
1548 encoding = CE_BINARY;
1549 break;
1550 } else if (*cp == '\n') {
1551 line_len = 0;
1552 } else if (! isascii ((unsigned char) *cp)) {
1553 encoding = CE_8BIT;
1554 }
1555
1556 last_char_was_cr = *cp == '\r' ? 1 : 0;
1557 }
1558 }
1559
1560 fclose (ce->ce_fp);
1561 ce->ce_fp = NULL;
1562 } /* else should never happen */
1563
1564 return encoding;
1565 }
1566
1567
1568 static int
1569 convert_codesets (CT ct, char *dest_codeset, int *message_mods) {
1570 int status = OK;
1571
1572 switch (ct->c_type) {
1573 case CT_TEXT:
1574 if (ct->c_subtype == TEXT_PLAIN) {
1575 status = convert_codeset (ct, dest_codeset, message_mods);
1576 }
1577 break;
1578
1579 case CT_MULTIPART: {
1580 struct multipart *m = (struct multipart *) ct->c_ctparams;
1581 struct part *part;
1582
1583 /* Should check to see if the body for this part is encoded?
1584 For now, it gets passed along as-is by InitMultiPart(). */
1585 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
1586 status =
1587 convert_codesets (part->mp_part, dest_codeset, message_mods);
1588 }
1589 break;
1590 }
1591
1592 case CT_MESSAGE:
1593 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1594 struct exbody *e;
1595
1596 e = (struct exbody *) ct->c_ctparams;
1597 status =
1598 convert_codesets (e->eb_content, dest_codeset, message_mods);
1599 }
1600 break;
1601
1602 default:
1603 break;
1604 }
1605
1606 return status;
1607 }
1608
1609
1610 static int
1611 convert_codeset (CT ct, char *dest_codeset, int *message_mods) {
1612 const char *const charset = "charset";
1613 char **src_codeset = NULL;
1614 char *default_codeset = NULL;
1615 CI ctinfo = &ct->c_ctinfo;
1616 char **ap, **vp;
1617 int status = OK;
1618
1619 for (ap = ctinfo->ci_attrs, vp = ctinfo->ci_values; *ap; ++ap, ++vp) {
1620 if (! strcasecmp (*ap, charset)) {
1621 src_codeset = vp;
1622 break;
1623 }
1624 }
1625 /* RFC 2045, Sec. 5.2: default to us-ascii. */
1626 if (src_codeset == NULL) src_codeset = &default_codeset;
1627 if (*src_codeset == NULL) *src_codeset = "US-ASCII";
1628
1629 if (strcmp (norm_charmap (*src_codeset), norm_charmap (dest_codeset))) {
1630 #ifdef HAVE_ICONV
1631 iconv_t conv_desc = NULL;
1632 char *dest;
1633 int fd = -1;
1634 char **file = NULL;
1635 FILE **fp = NULL;
1636 long begin;
1637 long end;
1638 int opened_input_file = 0;
1639 char src_buffer[BUFSIZ];
1640 HF hf;
1641
1642 if ((conv_desc = iconv_open (dest_codeset, *src_codeset)) ==
1643 (iconv_t) -1) {
1644 advise (NULL, "Can't convert %s to %s", *src_codeset, dest_codeset);
1645 return -1;
1646 }
1647
1648 dest = add (m_mktemp2 (tmp, invo_name, &fd, NULL), NULL);
1649
1650 if (ct->c_cefile.ce_file) {
1651 file = &ct->c_cefile.ce_file;
1652 fp = &ct->c_cefile.ce_fp;
1653 begin = 0;
1654 end = -1;
1655 } else if (ct->c_file) {
1656 file = &ct->c_file;
1657 fp = &ct->c_fp;
1658 begin = ct->c_begin;
1659 end = ct->c_end;
1660 } /* else no input file: shouldn't happen */
1661
1662 if (file && *file && fp) {
1663 if (! *fp) {
1664 if ((*fp = fopen (*file, "r")) == NULL) {
1665 advise (*file, "unable to open for reading");
1666 status = NOTOK;
1667 } else {
1668 opened_input_file = 1;
1669 }
1670 }
1671 }
1672
1673 if (fp && *fp) {
1674 size_t inbytes;
1675 size_t max = end > 0 ? (size_t) (end-begin) : sizeof src_buffer;
1676
1677 fseeko (*fp, begin, SEEK_SET);
1678 while (status == OK && max > 0 &&
1679 (inbytes = fread (src_buffer, 1, max, *fp)) > 0) {
1680 char dest_buffer[BUFSIZ];
1681 char *ib = src_buffer, *ob = dest_buffer;
1682 size_t outbytes = sizeof dest_buffer;
1683 size_t outbytes_before = outbytes;
1684
1685 if (end > 0) max -= inbytes;
1686
1687 if (iconv (conv_desc, &ib, &inbytes, &ob, &outbytes) ==
1688 (size_t) -1) {
1689 status = NOTOK;
1690 break;
1691 } else {
1692 write (fd, dest_buffer, outbytes_before - outbytes);
1693 }
1694 }
1695
1696 if (opened_input_file) {
1697 fclose (*fp);
1698 *fp = NULL;
1699 }
1700 }
1701
1702 iconv_close (conv_desc);
1703 close (fd);
1704
1705 if (status == OK) {
1706 /* Replace the decoded file with the converted one. */
1707 if (ct->c_cefile.ce_file) {
1708 if (ct->c_cefile.ce_unlink) {
1709 unlink (ct->c_cefile.ce_file);
1710 }
1711 free (ct->c_cefile.ce_file);
1712 }
1713 ct->c_cefile.ce_file = dest;
1714 ct->c_cefile.ce_unlink = 1;
1715
1716 ++*message_mods;
1717 if (verbosw) {
1718 report (ct->c_partno, ct->c_file, "convert %s to %s",
1719 *src_codeset, dest_codeset);
1720 }
1721
1722 /* Update ci_attrs. */
1723 *src_codeset = dest_codeset;
1724
1725 /* Update ct->c_ctline. */
1726 if (ct->c_ctline) {
1727 char *ctline =
1728 update_attr (ct->c_ctline, "charset=", dest_codeset);
1729
1730 free (ct->c_ctline);
1731 ct->c_ctline = ctline;
1732 } /* else no CT line, which is odd */
1733
1734 /* Update Content-Type header field. */
1735 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1736 if (! strcasecmp (TYPE_FIELD, hf->name)) {
1737 char *ctline_less_newline =
1738 update_attr (hf->value, "charset=", dest_codeset);
1739 char *ctline = concat (ctline_less_newline, "\n", NULL);
1740 free (ctline_less_newline);
1741
1742 free (hf->value);
1743 hf->value = ctline;
1744 break;
1745 }
1746 }
1747 } else {
1748 unlink (dest);
1749 }
1750 #else /* ! HAVE_ICONV */
1751 NMH_UNUSED (message_mods);
1752
1753 advise (NULL, "Can't convert %s to %s without iconv", *src_codeset,
1754 dest_codeset);
1755 status = NOTOK;
1756 #endif /* ! HAVE_ICONV */
1757 }
1758
1759 return status;
1760 }
1761
1762
1763 static int
1764 write_content (CT ct, char *input_filename, char *outfile, int modify_inplace,
1765 int message_mods) {
1766 int status = OK;
1767
1768 if (modify_inplace) {
1769 if (message_mods > 0) {
1770 if ((status = output_message (ct, outfile)) == OK) {
1771 char *infile = input_filename
1772 ? add (input_filename, NULL)
1773 : add (ct->c_file ? ct->c_file : "-", NULL);
1774
1775 if (remove_file (infile) == OK) {
1776 if (rename (outfile, infile)) {
1777 /* The -file argument processing used path() to
1778 expand filename to absolute path. */
1779 int file = ct->c_file && ct->c_file[0] == '/';
1780
1781 admonish (NULL, "unable to rename %s %s to %s",
1782 file ? "file" : "message", outfile, infile);
1783 unlink (outfile);
1784 status = NOTOK;
1785 }
1786 } else {
1787 admonish (NULL, "unable to remove input file %s, "
1788 "not modifying it", infile);
1789 unlink (outfile);
1790 status = NOTOK;
1791 }
1792
1793 free (infile);
1794 }
1795 } else {
1796 /* No modifications and didn't need the tmp outfile. */
1797 unlink (outfile);
1798 }
1799 } else {
1800 /* Output is going to some file. Produce it whether or not
1801 there were modifications. */
1802 status = output_message (ct, outfile);
1803 }
1804
1805 flush_errors ();
1806 return status;
1807 }
1808
1809
1810 /*
1811 * If "rmmproc" is defined, call that to remove the file. Otherwise,
1812 * use the standard MH backup file.
1813 */
1814 static int
1815 remove_file (char *file) {
1816 if (rmmproc) {
1817 char *rmm_command = concat (rmmproc, " ", file, NULL);
1818 int status = system (rmm_command);
1819
1820 free (rmm_command);
1821 return WIFEXITED (status) ? WEXITSTATUS (status) : NOTOK;
1822 } else {
1823 /* This is OK for a non-message file, it still uses the
1824 BACKUP_PREFIX form. The backup file will be in the same
1825 directory as file. */
1826 return rename (file, m_backup (file));
1827 }
1828 }
1829
1830
1831 static void
1832 report (char *partno, char *filename, char *message, ...) {
1833 va_list args;
1834 char *fmt;
1835
1836 if (verbosw) {
1837 va_start (args, message);
1838 fmt = concat (filename, partno ? " part " : ", ",
1839 partno ? partno : "", partno ? ", " : "", message, NULL);
1840
1841 advertise (NULL, NULL, fmt, args);
1842
1843 free (fmt);
1844 va_end (args);
1845 }
1846 }
1847
1848
1849 static char *
1850 upcase (char *str) {
1851 char *up = cpytrim (str);
1852 char *cp;
1853
1854 for (cp = up; *cp; ++cp) *cp = toupper ((unsigned char) *cp);
1855
1856 return up;
1857 }
1858
1859
1860 static void
1861 pipeser (int i)
1862 {
1863 if (i == SIGQUIT) {
1864 fflush (stdout);
1865 fprintf (stderr, "\n");
1866 fflush (stderr);
1867 }
1868
1869 done (1);
1870 /* NOTREACHED */
1871 }