]> diplodocus.org Git - nmh/blob - uip/mhfixmsg.c
dd0d8a232d000809e5a5e01e8f85502695f03e0c
[nmh] / uip / mhfixmsg.c
1 /* mhfixmsg.c -- rewrite a message with various transformations
2 *
3 * This code is Copyright (c) 2002 and 2013, by the authors of nmh.
4 * See the COPYRIGHT file in the root directory of the nmh
5 * distribution for complete copyright information.
6 */
7
8 #include "h/mh.h"
9 #include "sbr/fmt_rfc2047.h"
10 #include "sbr/cpydata.h"
11 #include "sbr/trimcpy.h"
12 #include "sbr/m_convert.h"
13 #include "sbr/m_backup.h"
14 #include "sbr/getfolder.h"
15 #include "sbr/folder_read.h"
16 #include "sbr/context_save.h"
17 #include "sbr/context_replace.h"
18 #include "sbr/context_find.h"
19 #include "sbr/readconfig.h"
20 #include "sbr/ambigsw.h"
21 #include "sbr/path.h"
22 #include "sbr/print_version.h"
23 #include "sbr/print_help.h"
24 #include "sbr/error.h"
25 #include "h/fmt_scan.h"
26 #include "h/mime.h"
27 #include "h/mhparse.h"
28 #include "h/done.h"
29 #include "h/utils.h"
30 #include "h/signals.h"
31 #include "sbr/m_maildir.h"
32 #include "sbr/m_mktemp.h"
33 #include "sbr/mime_type.h"
34 #include "mhmisc.h"
35 #include "mhfree.h"
36 #include "mhoutsbr.h"
37 #include "mhshowsbr.h"
38 #include <fcntl.h>
39
40 #define MHFIXMSG_SWITCHES \
41 X("decodetext 8bit|7bit|binary", 0, DECODETEXTSW) \
42 X("nodecodetext", 0, NDECODETEXTSW) \
43 X("decodetypes", 0, DECODETYPESW) \
44 X("crlflinebreaks", 0, CRLFLINEBREAKSSW) \
45 X("nocrlflinebreaks", 0, NCRLFLINEBREAKSSW) \
46 X("textcharset", 0, TEXTCHARSETSW) \
47 X("notextcharset", 0, NTEXTCHARSETSW) \
48 X("reformat", 0, REFORMATSW) \
49 X("noreformat", 0, NREFORMATSW) \
50 X("replacetextplain", 0, REPLACETEXTPLAINSW) \
51 X("noreplacetextplain", 0, NREPLACETEXTPLAINSW) \
52 X("fixboundary", 0, FIXBOUNDARYSW) \
53 X("nofixboundary", 0, NFIXBOUNDARYSW) \
54 X("fixcte", 0, FIXCOMPOSITECTESW) \
55 X("nofixcte", 0, NFIXCOMPOSITECTESW) \
56 X("fixtype mimetype", 0, FIXTYPESW) \
57 X("file file", 0, FILESW) \
58 X("outfile file", 0, OUTFILESW) \
59 X("rmmproc program", 0, RPROCSW) \
60 X("normmproc", 0, NRPRCSW) \
61 X("changecur", 0, CHGSW) \
62 X("nochangecur", 0, NCHGSW) \
63 X("verbose", 0, VERBSW) \
64 X("noverbose", 0, NVERBSW) \
65 X("version", 0, VERSIONSW) \
66 X("help", 0, HELPSW) \
67
68 #define X(sw, minchars, id) id,
69 DEFINE_SWITCH_ENUM(MHFIXMSG);
70 #undef X
71
72 #define X(sw, minchars, id) { sw, minchars, id },
73 DEFINE_SWITCH_ARRAY(MHFIXMSG, switches);
74 #undef X
75
76
77 int verbosw;
78 int debugsw; /* Needed by mhparse.c. */
79
80 #define quitser pipeser
81
82 /*
83 * static prototypes
84 */
85 typedef struct fix_transformations {
86 int fixboundary;
87 int fixcompositecte;
88 svector_t fixtypes;
89 int reformat;
90 int replacetextplain;
91 int decodetext;
92 char *decodetypes;
93 /* Whether to use CRLF linebreaks, per RFC 2046 Sec. 4.1.1, par.1. */
94 int lf_line_endings;
95 char *textcharset;
96 } fix_transformations;
97
98 static int mhfixmsgsbr (CT *, char *, const fix_transformations *,
99 FILE **, char *, FILE **);
100 static int fix_boundary (CT *, int *);
101 static int copy_input_to_output (const char *, FILE *, const char *, FILE *);
102 static int get_multipart_boundary (CT, char **);
103 static int replace_boundary (CT, char *, char *);
104 static int fix_types (CT, svector_t, int *);
105 static char *replace_substring (char **, const char *, const char *);
106 static char *remove_parameter (char *, const char *);
107 static int fix_composite_cte (CT, int *);
108 static int set_ce (CT, int);
109 static int ensure_text_plain (CT *, CT, int *, int);
110 static int find_textplain_sibling (CT, int, int *);
111 static int insert_new_text_plain_part (CT, int, CT);
112 static CT build_text_plain_part (CT);
113 static int insert_into_new_mp_alt (CT *, int *);
114 static CT divide_part (CT);
115 static void copy_ctinfo (CI, CI);
116 static int decode_part (CT);
117 static int reformat_part (CT, char *, char *, char *, int);
118 static CT build_multipart_alt (CT, CT, int, int);
119 static int boundary_in_content (FILE **, char *, const char *);
120 static void transfer_noncontent_headers (CT, CT);
121 static int set_ct_type (CT, int type, int subtype, int encoding);
122 static int decode_text_parts (CT, int, const char *, int *);
123 static int should_decode(const char *, const char *, const char *);
124 static int content_encoding (CT, const char **);
125 static int strip_crs (CT, int *);
126 static void update_cte (CT);
127 static int least_restrictive_encoding (CT) PURE;
128 static int less_restrictive (int, int);
129 static int convert_charsets (CT, char *, int *);
130 static int fix_always (CT, int *);
131 static int fix_filename_param (char *, char *, PM *, PM *);
132 static int fix_filename_encoding (CT);
133 static int write_content (CT, const char *, char *, FILE *, int, int);
134 static void set_text_ctparams(CT, char *, int);
135 static int remove_file (const char *);
136 static void report (char *, char *, char *, char *, ...)
137 CHECK_PRINTF(4, 5);
138 static void pipeser (int);
139
140
141 int
142 main (int argc, char **argv)
143 {
144 int msgnum;
145 char *cp, *file = NULL, *folder = NULL;
146 char *maildir = NULL, buf[100], *outfile = NULL;
147 char **argp, **arguments;
148 struct msgs_array msgs = { 0, 0, NULL };
149 struct msgs *mp = NULL;
150 CT *ctp;
151 FILE *fp, *infp = NULL, *outfp = NULL;
152 bool using_stdin = false;
153 bool chgflag = true;
154 int status = OK;
155 fix_transformations fx;
156 fx.reformat = fx.fixcompositecte = fx.fixboundary = 1;
157 fx.fixtypes = NULL;
158 fx.replacetextplain = 0;
159 fx.decodetext = CE_8BIT;
160 fx.decodetypes = "text,application/ics"; /* Default, per man page. */
161 fx.lf_line_endings = 0;
162 fx.textcharset = NULL;
163
164 if (nmh_init(argv[0], true, false)) { return 1; }
165
166 arguments = getarguments (invo_name, argc, argv, 1);
167 argp = arguments;
168
169 /*
170 * Parse arguments
171 */
172 while ((cp = *argp++)) {
173 if (*cp == '-') {
174 switch (smatch (++cp, switches)) {
175 case AMBIGSW:
176 ambigsw (cp, switches);
177 done (1);
178 case UNKWNSW:
179 die("-%s unknown", cp);
180
181 case HELPSW:
182 snprintf (buf, sizeof buf, "%s [+folder] [msgs] [switches]",
183 invo_name);
184 print_help (buf, switches, 1);
185 done (0);
186 case VERSIONSW:
187 print_version(invo_name);
188 done (0);
189
190 case DECODETEXTSW:
191 if (! (cp = *argp++) || *cp == '-') {
192 die("missing argument to %s", argp[-2]);
193 }
194 if (! strcasecmp (cp, "8bit")) {
195 fx.decodetext = CE_8BIT;
196 } else if (! strcasecmp (cp, "7bit")) {
197 fx.decodetext = CE_7BIT;
198 } else if (! strcasecmp (cp, "binary")) {
199 fx.decodetext = CE_BINARY;
200 } else {
201 die("invalid argument to %s", argp[-2]);
202 }
203 continue;
204 case NDECODETEXTSW:
205 fx.decodetext = 0;
206 continue;
207 case DECODETYPESW:
208 if (! (cp = *argp++) || *cp == '-') {
209 die("missing argument to %s", argp[-2]);
210 }
211 fx.decodetypes = cp;
212 continue;
213 case CRLFLINEBREAKSSW:
214 fx.lf_line_endings = 0;
215 continue;
216 case NCRLFLINEBREAKSSW:
217 fx.lf_line_endings = 1;
218 continue;
219 case TEXTCHARSETSW:
220 if (! (cp = *argp++) || (*cp == '-' && cp[1])) {
221 die("missing argument to %s", argp[-2]);
222 }
223 fx.textcharset = cp;
224 continue;
225 case NTEXTCHARSETSW:
226 fx.textcharset = 0;
227 continue;
228 case FIXBOUNDARYSW:
229 fx.fixboundary = 1;
230 continue;
231 case NFIXBOUNDARYSW:
232 fx.fixboundary = 0;
233 continue;
234 case FIXCOMPOSITECTESW:
235 fx.fixcompositecte = 1;
236 continue;
237 case NFIXCOMPOSITECTESW:
238 fx.fixcompositecte = 0;
239 continue;
240 case FIXTYPESW:
241 if (! (cp = *argp++) || (*cp == '-' && cp[1])) {
242 die("missing argument to %s", argp[-2]);
243 }
244 if (! strncasecmp (cp, "multipart/", 10) ||
245 ! strncasecmp (cp, "message/", 8))
246 die("-fixtype %s not allowed", cp);
247 if (! strchr (cp, '/'))
248 die("-fixtype requires type/subtype");
249 if (fx.fixtypes == NULL) { fx.fixtypes = svector_create (10); }
250 svector_push_back (fx.fixtypes, cp);
251 continue;
252 case REFORMATSW:
253 fx.reformat = 1;
254 continue;
255 case NREFORMATSW:
256 fx.reformat = 0;
257 continue;
258 case REPLACETEXTPLAINSW:
259 fx.replacetextplain = 1;
260 continue;
261 case NREPLACETEXTPLAINSW:
262 fx.replacetextplain = 0;
263 continue;
264 case FILESW:
265 if (! (cp = *argp++) || (*cp == '-' && cp[1])) {
266 die("missing argument to %s", argp[-2]);
267 }
268 file = *cp == '-' ? mh_xstrdup (cp) : path (cp, TFILE);
269 continue;
270 case OUTFILESW:
271 if (! (cp = *argp++) || (*cp == '-' && cp[1])) {
272 die("missing argument to %s", argp[-2]);
273 }
274 outfile = *cp == '-' ? mh_xstrdup (cp) : path (cp, TFILE);
275 continue;
276 case RPROCSW:
277 if (!(rmmproc = *argp++) || *rmmproc == '-') {
278 die("missing argument to %s", argp[-2]);
279 }
280 continue;
281 case NRPRCSW:
282 rmmproc = NULL;
283 continue;
284 case CHGSW:
285 chgflag = true;
286 continue;
287 case NCHGSW:
288 chgflag = false;
289 continue;
290 case VERBSW:
291 verbosw = 1;
292 continue;
293 case NVERBSW:
294 verbosw = 0;
295 continue;
296 }
297 }
298 if (*cp == '+' || *cp == '@') {
299 if (folder)
300 die("only one folder at a time!");
301 folder = pluspath (cp);
302 } else {
303 if (*cp == '/') {
304 /* Interpret a full path as a filename, not a message. */
305 file = mh_xstrdup (cp);
306 } else {
307 app_msgarg (&msgs, cp);
308 }
309 }
310 }
311
312 SIGNAL (SIGQUIT, quitser);
313 SIGNAL (SIGPIPE, pipeser);
314
315 /*
316 * Read the standard profile setup
317 */
318 if ((fp = fopen (cp = etcpath ("mhn.defaults"), "r"))) {
319 readconfig(NULL, fp, cp, 0);
320 fclose (fp);
321 }
322
323 suppress_bogus_mp_content_warning = skip_mp_cte_check = true;
324 suppress_extraneous_trailing_semicolon_warning = true;
325
326 if (! context_find ("path")) {
327 free (path ("./", TFOLDER));
328 }
329
330 if (file && msgs.size) {
331 die("cannot specify msg and file at same time!");
332 }
333
334 if (outfile) {
335 /* Open the outfile now, so we don't have to risk opening it
336 after running out of fds. */
337 if (strcmp (outfile, "-") == 0) {
338 outfp = stdout;
339 } else if ((outfp = fopen (outfile, "w")) == NULL) {
340 adios (outfile, "unable to open for writing");
341 }
342 }
343
344 /*
345 * check if message is coming from file
346 */
347 if (file) {
348 /* If file is stdin, create a tmp file name before parse_mime()
349 has a chance, because it might put in on a different
350 filesystem than the output file. Instead, put it in the
351 user's preferred tmp directory. */
352 CT ct;
353
354 if (! strcmp ("-", file)) {
355 int fd;
356 char *cp;
357
358 using_stdin = true;
359
360 if ((cp = m_mktemp2 (NULL, invo_name, &fd, NULL)) == NULL) {
361 die("unable to create temporary file in %s",
362 get_temp_dir());
363 } else {
364 free (file);
365 file = mh_xstrdup (cp);
366 cpydata (STDIN_FILENO, fd, "-", file);
367 }
368
369 if (close (fd)) {
370 (void) m_unlink (file);
371 die("failed to write temporary file");
372 }
373 }
374
375 cts = mh_xcalloc(2, sizeof *cts);
376 ctp = cts;
377
378 if ((ct = parse_mime (file))) {
379 set_text_ctparams(ct, fx.decodetypes, fx.lf_line_endings);
380 *ctp++ = ct;
381 } else {
382 inform("unable to parse message from file %s", file);
383 status = NOTOK;
384
385 /* If there's an outfile, pass the input message unchanged, so the
386 message won't get dropped from a pipeline. */
387 if (outfile) {
388 /* Something went wrong. Output might be expected, such as if
389 this were run as a filter. Just copy the input to the
390 output. */
391 if ((infp = fopen (file, "r")) == NULL) {
392 adios (file, "unable to open for reading");
393 }
394
395 if (copy_input_to_output (file, infp, outfile, outfp) != OK) {
396 inform("unable to copy message to %s, "
397 "it might be lost\n", outfile);
398 }
399
400 fclose (infp);
401 infp = NULL;
402 }
403 }
404 } else {
405 /*
406 * message(s) are coming from a folder
407 */
408 CT ct;
409
410 if (! msgs.size) {
411 app_msgarg(&msgs, "cur");
412 }
413 if (! folder) {
414 folder = getfolder (1);
415 }
416 maildir = mh_xstrdup(m_maildir (folder));
417
418 /* chdir so that error messages, esp. from MIME parser, just
419 refer to the message and not its path. */
420 if (chdir (maildir) == NOTOK) {
421 adios (maildir, "unable to change directory to");
422 }
423
424 /* read folder and create message structure */
425 if (! (mp = folder_read (folder, 1))) {
426 die("unable to read folder %s", folder);
427 }
428
429 /* check for empty folder */
430 if (mp->nummsg == 0) {
431 die("no messages in %s", folder);
432 }
433
434 /* parse all the message ranges/sequences and set SELECTED */
435 for (msgnum = 0; msgnum < msgs.size; msgnum++)
436 if (! m_convert (mp, msgs.msgs[msgnum])) {
437 done (1);
438 }
439 seq_setprev (mp); /* set the previous-sequence */
440
441 cts = mh_xcalloc(mp->numsel + 1, sizeof *cts);
442 ctp = cts;
443
444 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
445 if (is_selected(mp, msgnum)) {
446 char *msgnam = m_name (msgnum);
447
448 if ((ct = parse_mime (msgnam))) {
449 set_text_ctparams(ct, fx.decodetypes, fx.lf_line_endings);
450 *ctp++ = ct;
451 } else {
452 inform("unable to parse message %s", msgnam);
453 status = NOTOK;
454
455 /* If there's an outfile, pass the input message
456 unchanged, so the message won't get dropped from a
457 pipeline. */
458 if (outfile) {
459 /* Something went wrong. Output might be expected,
460 such as if this were run as a filter. Just copy
461 the input to the output. */
462 /* Can't use path() here because 1) it might have been
463 called before and it caches the pwd, and 2) we call
464 chdir() after that. */
465 char *input_filename =
466 concat (maildir, "/", msgnam, NULL);
467
468 if ((infp = fopen (input_filename, "r")) == NULL) {
469 adios (input_filename,
470 "unable to open for reading");
471 }
472
473 if (copy_input_to_output (input_filename, infp,
474 outfile, outfp) != OK) {
475 inform("unable to copy message to %s, "
476 "it might be lost\n", outfile);
477 }
478
479 fclose (infp);
480 infp = NULL;
481 free (input_filename);
482 }
483 }
484 }
485 }
486
487 if (chgflag) {
488 seq_setcur (mp, mp->hghsel); /* update current message */
489 }
490 seq_save (mp); /* synchronize sequences */
491 context_replace (pfolder, folder);/* update current folder */
492 context_save (); /* save the context file */
493 }
494
495 if (*cts) {
496 for (ctp = cts; *ctp; ++ctp) {
497 status =
498 mhfixmsgsbr (ctp, maildir, &fx, &infp, outfile, &outfp) == OK
499 ? 0
500 : 1;
501 free_content (*ctp);
502
503 if (using_stdin) {
504 (void) m_unlink (file);
505
506 if (! outfile) {
507 /* Just calling m_backup() unlinks the backup file. */
508 (void) m_backup (file);
509 }
510 }
511 }
512 } else {
513 status = 1;
514 }
515
516 free(maildir);
517 free (cts);
518
519 if (fx.fixtypes != NULL) { svector_free (fx.fixtypes); }
520 if (infp) { fclose (infp); } /* even if stdin */
521 if (outfp) { fclose (outfp); } /* even if stdout */
522 free (outfile);
523 free (file);
524 free (folder);
525 free (arguments);
526
527 done (status == OK ? 0 : 1);
528 return NOTOK;
529 }
530
531
532 /*
533 * Apply transformations to one message.
534 */
535 static int
536 mhfixmsgsbr (CT *ctp, char *maildir, const fix_transformations *fx,
537 FILE **infp, char *outfile, FILE **outfp)
538 {
539 /* Store input filename in case one of the transformations, i.e.,
540 fix_boundary(), rewrites to a tmp file. */
541 char *input_filename = maildir
542 ? concat (maildir, "/", (*ctp)->c_file, NULL)
543 : mh_xstrdup ((*ctp)->c_file);
544 bool modify_inplace = false;
545 int message_mods = 0;
546 int status = OK;
547
548 /* Though the input file won't need to be opened if everything goes
549 well, do it here just in case there's a failure, and that failure is
550 running out of file descriptors. */
551 if ((*infp = fopen (input_filename, "r")) == NULL) {
552 adios (input_filename, "unable to open for reading");
553 }
554
555 if (outfile == NULL) {
556 modify_inplace = true;
557
558 if ((*ctp)->c_file) {
559 char *tempfile;
560 /* outfp will be closed by the caller */
561 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, outfp)) ==
562 NULL) {
563 die("unable to create temporary file in %s",
564 get_temp_dir());
565 }
566 outfile = mh_xstrdup (tempfile);
567 } else {
568 die("missing both input and output filenames\n");
569 }
570 } /* else *outfp was defined by caller */
571
572 reverse_alternative_parts (*ctp);
573 status = fix_always (*ctp, &message_mods);
574 if (status == OK && fx->fixboundary) {
575 status = fix_boundary (ctp, &message_mods);
576 }
577 if (status == OK && fx->fixtypes != NULL) {
578 status = fix_types (*ctp, fx->fixtypes, &message_mods);
579 }
580 if (status == OK && fx->fixcompositecte) {
581 status = fix_composite_cte (*ctp, &message_mods);
582 }
583 if (status == OK && fx->reformat) {
584 status =
585 ensure_text_plain (ctp, NULL, &message_mods, fx->replacetextplain);
586 }
587 if (status == OK && fx->decodetext) {
588 status = decode_text_parts (*ctp, fx->decodetext, fx->decodetypes,
589 &message_mods);
590 update_cte (*ctp);
591 }
592 if (status == OK && fx->textcharset != NULL) {
593 status = convert_charsets (*ctp, fx->textcharset, &message_mods);
594 }
595
596 if (status == OK && ! (*ctp)->c_umask) {
597 /* Set the umask for the contents file. This currently
598 isn't used but just in case it is in the future. */
599 struct stat st;
600
601 if (stat ((*ctp)->c_file, &st) != NOTOK) {
602 (*ctp)->c_umask = ~(st.st_mode & 0777);
603 } else {
604 (*ctp)->c_umask = ~m_gmprot();
605 }
606 }
607
608 /*
609 * Write the content to a file
610 */
611 if (status == OK) {
612 status = write_content (*ctp, input_filename, outfile, *outfp,
613 modify_inplace, message_mods);
614 } else if (! modify_inplace) {
615 /* Something went wrong. Output might be expected, such
616 as if this were run as a filter. Just copy the input
617 to the output. */
618 if (copy_input_to_output (input_filename, *infp, outfile,
619 *outfp) != OK) {
620 inform("unable to copy message to %s, it might be lost\n",
621 outfile);
622 }
623 }
624
625 if (modify_inplace) {
626 if (status != OK) { (void) m_unlink (outfile); }
627 free (outfile);
628 outfile = NULL;
629 }
630
631 fclose (*infp);
632 *infp = NULL;
633 free (input_filename);
634
635 return status;
636 }
637
638
639 /*
640 * Copy input message to output. Assumes not modifying in place, so this
641 * might be running as part of a pipeline.
642 */
643 static int
644 copy_input_to_output (const char *input_filename, FILE *infp,
645 const char *output_filename, FILE *outfp)
646 {
647 int in = fileno (infp);
648 int out = fileno (outfp);
649 int status = OK;
650
651 if (in != -1 && out != -1) {
652 cpydata (in, out, input_filename, output_filename);
653 } else {
654 status = NOTOK;
655 }
656
657 return status;
658 }
659
660
661 /*
662 * Fix mismatched outer level boundary.
663 */
664 static int
665 fix_boundary (CT *ct, int *message_mods)
666 {
667 struct multipart *mp;
668 int status = OK;
669
670 if (ct && (*ct)->c_type == CT_MULTIPART && bogus_mp_content) {
671 mp = (struct multipart *) (*ct)->c_ctparams;
672
673 /*
674 * 1) Get boundary at end of part.
675 * 2) Get boundary at beginning of part and compare to the end-of-part
676 * boundary.
677 * 3) Write out contents of ct to tmp file, replacing boundary in
678 * header with boundary from part. Set c_unlink to 1.
679 * 4) Free ct.
680 * 5) Call parse_mime() on the tmp file, replacing ct.
681 */
682
683 if (mp && mp->mp_start) {
684 char *part_boundary;
685
686 if (get_multipart_boundary (*ct, &part_boundary) == OK) {
687 char *fixed;
688
689 if ((fixed = m_mktemp2 (NULL, invo_name, NULL, &(*ct)->c_fp))) {
690 if (replace_boundary (*ct, fixed, part_boundary) == OK) {
691 char *filename = mh_xstrdup ((*ct)->c_file);
692 CT fixed_ct;
693
694 free_content (*ct);
695 if ((fixed_ct = parse_mime (fixed))) {
696 *ct = fixed_ct;
697 (*ct)->c_unlink = 1;
698
699 ++*message_mods;
700 if (verbosw) {
701 report (NULL, NULL, filename,
702 "fix multipart boundary");
703 }
704 } else {
705 *ct = NULL;
706 inform("unable to parse fixed part");
707 status = NOTOK;
708 }
709 free (filename);
710 } else {
711 inform("unable to replace broken boundary");
712 status = NOTOK;
713 }
714 } else {
715 inform("unable to create temporary file in %s",
716 get_temp_dir());
717 status = NOTOK;
718 }
719
720 free (part_boundary);
721 } else {
722 /* Couldn't fix the boundary. Report failure so that mhfixmsg
723 doesn't modify the message. */
724 status = NOTOK;
725 }
726 } else {
727 /* No multipart struct, even though the content type is
728 CT_MULTIPART. Report failure so that mhfixmsg doesn't modify
729 the message. */
730 status = NOTOK;
731 }
732 }
733
734 return status;
735 }
736
737
738 /*
739 * Find boundary at end of multipart.
740 */
741 static int
742 get_multipart_boundary (CT ct, char **part_boundary)
743 {
744 char buffer[NMH_BUFSIZ];
745 char *end_boundary = NULL;
746 off_t begin = (off_t) ct->c_end > (off_t) (ct->c_begin + sizeof buffer)
747 ? (off_t) (ct->c_end - sizeof buffer)
748 : (off_t) ct->c_begin;
749 size_t bytes_read;
750 int status = OK;
751
752 /* This will fail if the boundary spans fread() calls. NMH_BUFSIZ should
753 be big enough, even if it's just 1024, to make that unlikely. */
754
755 /* free_content() will close ct->c_fp if bogus MP boundary is fixed. */
756 if (! ct->c_fp && (ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
757 advise (ct->c_file, "unable to open for reading");
758 return NOTOK;
759 }
760
761 /* Get boundary at end of multipart. */
762 while (begin >= (off_t) ct->c_begin) {
763 fseeko (ct->c_fp, begin, SEEK_SET);
764 while ((bytes_read = fread (buffer, 1, sizeof buffer, ct->c_fp)) > 0) {
765 char *cp = rfind_str (buffer, bytes_read, "--");
766
767 if (cp) {
768 char *end;
769
770 /* Trim off trailing "--" and anything beyond. */
771 *cp-- = '\0';
772 if ((end = rfind_str (buffer, cp - buffer, "\n"))) {
773 if (strlen (end) > 3 && *end++ == '\n' &&
774 *end++ == '-' && *end++ == '-') {
775 end_boundary = mh_xstrdup (end);
776 break;
777 }
778 }
779 }
780 }
781
782 if (end_boundary || begin <= (off_t) (ct->c_begin + sizeof buffer))
783 break;
784 begin -= sizeof buffer;
785 }
786
787 /* Get boundary at beginning of multipart. */
788 if (end_boundary) {
789 fseeko (ct->c_fp, ct->c_begin, SEEK_SET);
790 while ((bytes_read = fread (buffer, 1, sizeof buffer, ct->c_fp)) > 0) {
791 if (bytes_read >= strlen (end_boundary)) {
792 char *cp = find_str (buffer, bytes_read, end_boundary);
793
794 if (cp && cp - buffer >= 2 && *--cp == '-' &&
795 *--cp == '-' && (cp > buffer && *--cp == '\n')) {
796 status = OK;
797 break;
798 }
799 } else {
800 /* The start and end boundaries didn't match, or the
801 start boundary doesn't begin with "\n--" (or "--"
802 if at the beginning of buffer). Keep trying. */
803 status = NOTOK;
804 }
805 }
806 } else {
807 status = NOTOK;
808 }
809
810 if (ct->c_fp) {
811 fclose (ct->c_fp);
812 ct->c_fp = NULL;
813 }
814
815 if (status == OK) {
816 *part_boundary = end_boundary;
817 } else {
818 *part_boundary = NULL;
819 free (end_boundary);
820 }
821
822 return status;
823 }
824
825
826 /*
827 * Open and copy ct->c_file to file, replacing the multipart boundary.
828 */
829 static int
830 replace_boundary (CT ct, char *file, char *boundary)
831 {
832 FILE *fpin, *fpout;
833 int compnum, state;
834 char buf[NMH_BUFSIZ], name[NAMESZ];
835 char *np, *vp;
836 m_getfld_state_t gstate;
837 int status = OK;
838
839 if (ct->c_file == NULL) {
840 inform("missing input filename");
841 return NOTOK;
842 }
843
844 if ((fpin = fopen (ct->c_file, "r")) == NULL) {
845 advise (ct->c_file, "unable to open for reading");
846 return NOTOK;
847 }
848
849 if ((fpout = fopen (file, "w")) == NULL) {
850 fclose (fpin);
851 advise (file, "unable to open for writing");
852 return NOTOK;
853 }
854
855 gstate = m_getfld_state_init(fpin);
856 for (compnum = 1;;) {
857 int bufsz = (int) sizeof buf;
858
859 switch (state = m_getfld2(&gstate, name, buf, &bufsz)) {
860 case FLD:
861 case FLDPLUS:
862 compnum++;
863
864 /* get copies of the buffers */
865 np = mh_xstrdup (name);
866 vp = mh_xstrdup (buf);
867
868 /* if necessary, get rest of field */
869 while (state == FLDPLUS) {
870 bufsz = sizeof buf;
871 state = m_getfld2(&gstate, name, buf, &bufsz);
872 vp = add (buf, vp); /* add to previous value */
873 }
874
875 if (strcasecmp (TYPE_FIELD, np)) {
876 fprintf (fpout, "%s:%s", np, vp);
877 } else {
878 char *new_ctline, *new_params;
879
880 replace_param(&ct->c_ctinfo.ci_first_pm,
881 &ct->c_ctinfo.ci_last_pm, "boundary",
882 boundary, 0);
883
884 new_ctline = concat(" ", ct->c_ctinfo.ci_type, "/",
885 ct->c_ctinfo.ci_subtype, NULL);
886 new_params = output_params(LEN(TYPE_FIELD) +
887 strlen(new_ctline) + 1,
888 ct->c_ctinfo.ci_first_pm, NULL, 0);
889 fprintf (fpout, "%s:%s%s\n", np, new_ctline,
890 FENDNULL(new_params));
891 free(new_ctline);
892 free(new_params);
893 }
894
895 free (vp);
896 free (np);
897
898 continue;
899
900 case BODY:
901 putc('\n', fpout);
902 /* buf will have a terminating NULL, skip it. */
903 if ((int) fwrite (buf, 1, bufsz-1, fpout) < bufsz-1) {
904 advise (file, "fwrite");
905 }
906 continue;
907
908 case FILEEOF:
909 break;
910
911 case LENERR:
912 case FMTERR:
913 inform("message format error in component #%d", compnum);
914 status = NOTOK;
915 break;
916
917 default:
918 inform("getfld() returned %d", state);
919 status = NOTOK;
920 break;
921 }
922
923 break;
924 }
925
926 m_getfld_state_destroy (&gstate);
927 fclose (fpout);
928 fclose (fpin);
929
930 return status;
931 }
932
933
934 /*
935 * Fix Content-Type header to reflect the content of its part.
936 */
937 static int
938 fix_types (CT ct, svector_t fixtypes, int *message_mods)
939 {
940 int status = OK;
941
942 switch (ct->c_type) {
943 case CT_MULTIPART: {
944 struct multipart *m = (struct multipart *) ct->c_ctparams;
945 struct part *part;
946
947 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
948 status = fix_types (part->mp_part, fixtypes, message_mods);
949 }
950 break;
951 }
952
953 case CT_MESSAGE:
954 if (ct->c_subtype == MESSAGE_EXTERNAL) {
955 struct exbody *e = (struct exbody *) ct->c_ctparams;
956
957 status = fix_types (e->eb_content, fixtypes, message_mods);
958 }
959 break;
960
961 default: {
962 char **typep, *type;
963
964 if (ct->c_ctinfo.ci_type && ct->c_ctinfo.ci_subtype) {
965 for (typep = svector_strs (fixtypes);
966 typep && (type = *typep);
967 ++typep) {
968 char *type_subtype =
969 concat (ct->c_ctinfo.ci_type, "/", ct->c_ctinfo.ci_subtype,
970 NULL);
971
972 if (! strcasecmp (type, type_subtype) &&
973 decode_part (ct) == OK &&
974 ct->c_cefile.ce_file != NULL) {
975 char *ct_type_subtype = mime_type (ct->c_cefile.ce_file);
976 char *cp;
977
978 if ((cp = strchr (ct_type_subtype, ';'))) {
979 /* Truncate to remove any parameter list from
980 mime_type () result. */
981 *cp = '\0';
982 }
983
984 if (strcasecmp (type, ct_type_subtype)) {
985 char *ct_type, *ct_subtype;
986 HF hf;
987
988 /* The Content-Type header does not match the
989 content, so update these struct Content
990 fields to match:
991 * c_type, c_subtype
992 * c_ctinfo.ci_type, c_ctinfo.ci_subtype
993 * c_ctline
994 */
995 /* Extract type and subtype from type/subtype. */
996 ct_type = mh_xstrdup(ct_type_subtype);
997 if ((cp = strchr (ct_type, '/'))) {
998 *cp = '\0';
999 ct_subtype = mh_xstrdup(++cp);
1000 } else {
1001 inform("missing / in MIME type of %s %s",
1002 ct->c_file, ct->c_partno);
1003 free (ct_type);
1004 return NOTOK;
1005 }
1006
1007 ct->c_type = ct_str_type (ct_type);
1008 ct->c_subtype = ct_str_subtype (ct->c_type, ct_subtype);
1009
1010 free (ct->c_ctinfo.ci_type);
1011 ct->c_ctinfo.ci_type = ct_type;
1012 free (ct->c_ctinfo.ci_subtype);
1013 ct->c_ctinfo.ci_subtype = ct_subtype;
1014 if (! replace_substring (&ct->c_ctline, type,
1015 ct_type_subtype)) {
1016 inform("did not find %s in %s",
1017 type, ct->c_ctline);
1018 }
1019
1020 /* Update Content-Type header field. */
1021 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1022 if (! strcasecmp (TYPE_FIELD, hf->name)) {
1023 if (replace_substring (&hf->value, type,
1024 ct_type_subtype)) {
1025 ++*message_mods;
1026 if (verbosw) {
1027 report (NULL, ct->c_partno, ct->c_file,
1028 "change Content-Type in header "
1029 "from %s to %s",
1030 type, ct_type_subtype);
1031 }
1032 break;
1033 }
1034 inform("did not find %s in %s", type, hf->value);
1035 }
1036 }
1037 }
1038 free (ct_type_subtype);
1039 }
1040 free (type_subtype);
1041 }
1042 }
1043 }}
1044
1045 return status;
1046 }
1047
1048
1049 /*
1050 * Replace a substring, allocating space to hold the new one.
1051 */
1052 char *
1053 replace_substring (char **str, const char *old, const char *new)
1054 {
1055 char *cp;
1056
1057 if ((cp = strstr (*str, old))) {
1058 char *remainder = cp + strlen (old);
1059 char *prefix, *new_str;
1060
1061 if (cp - *str) {
1062 prefix = mh_xstrdup(*str);
1063 *(prefix + (cp - *str)) = '\0';
1064 new_str = concat (prefix, new, remainder, NULL);
1065 free (prefix);
1066 } else {
1067 new_str = concat (new, remainder, NULL);
1068 }
1069
1070 free (*str);
1071
1072 return *str = new_str;
1073 }
1074
1075 return NULL;
1076 }
1077
1078
1079 /*
1080 * Remove a name=value parameter, given just its name, from a header value.
1081 */
1082 char *
1083 remove_parameter (char *str, const char *name)
1084 {
1085 /* It looks to me, based on the BNF in RFC 2045, than there can't
1086 be whitespace between the parameter name and the "=", or
1087 between the "=" and the parameter value. */
1088 char *param_name = concat (name, "=", NULL);
1089 char *cp;
1090
1091 if ((cp = strstr (str, param_name))) {
1092 char *start, *end;
1093 size_t count = 1;
1094
1095 /* Remove any leading spaces, before the parameter name. */
1096 for (start = cp;
1097 start > str && isspace ((unsigned char) *(start-1));
1098 --start) {
1099 continue;
1100 }
1101 /* Remove a leading semicolon. */
1102 if (start > str && *(start-1) == ';') { --start; }
1103
1104 end = cp + strlen (name) + 1;
1105 if (*end == '"') {
1106 /* Skip past the quoted value, and then the final quote. */
1107 for (++end ; *end && *end != '"'; ++end) { continue; }
1108 ++end;
1109 } else {
1110 /* Skip past the value. */
1111 for (++end ; *end && ! isspace ((unsigned char) *end); ++end) {}
1112 }
1113
1114 /* Count how many characters need to be moved. Include
1115 trailing null, which is accounted for by the
1116 initialization of count to 1. */
1117 for (cp = end; *cp; ++cp) { ++count; }
1118 (void) memmove (start, end, count);
1119 }
1120
1121 free (param_name);
1122
1123 return str;
1124 }
1125
1126
1127 /*
1128 * Fix Content-Transfer-Encoding of composite,, e.g., message or multipart, part.
1129 * According to RFC 2045 Sec. 6.4, it must be 7bit, 8bit, or binary. Set it to
1130 * 8 bit.
1131 */
1132 static int
1133 fix_composite_cte (CT ct, int *message_mods)
1134 {
1135 int status = OK;
1136
1137 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART) {
1138 if (ct->c_encoding != CE_7BIT && ct->c_encoding != CE_8BIT &&
1139 ct->c_encoding != CE_BINARY) {
1140 HF hf;
1141
1142 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1143 char *name = hf->name;
1144 for (; isspace((unsigned char)*name); ++name) {
1145 continue;
1146 }
1147
1148 if (! strncasecmp (name, ENCODING_FIELD,
1149 LEN(ENCODING_FIELD))) {
1150 char *prefix = "Nmh-REPLACED-INVALID-";
1151 HF h;
1152
1153 NEW(h);
1154 h->name = mh_xstrdup (hf->name);
1155 h->hf_encoding = hf->hf_encoding;
1156 h->next = hf->next;
1157 hf->next = h;
1158
1159 /* Retain old header but prefix its name. */
1160 free (hf->name);
1161 hf->name = concat (prefix, h->name, NULL);
1162
1163 ++*message_mods;
1164 if (verbosw) {
1165 char *encoding = cpytrim (hf->value);
1166 report (NULL, ct->c_partno, ct->c_file,
1167 "replace Content-Transfer-Encoding of %s "
1168 "with 8 bit", encoding);
1169 free (encoding);
1170 }
1171
1172 h->value = mh_xstrdup (" 8bit\n");
1173
1174 /* Don't need to warn for multiple C-T-E header
1175 fields, parse_mime() already does that. But
1176 if there are any, fix them all as necessary. */
1177 hf = h;
1178 }
1179 }
1180
1181 set_ce (ct, CE_8BIT);
1182 }
1183
1184 if (ct->c_type == CT_MULTIPART) {
1185 struct multipart *m;
1186 struct part *part;
1187
1188 m = (struct multipart *) ct->c_ctparams;
1189 for (part = m->mp_parts; part; part = part->mp_next) {
1190 if (fix_composite_cte (part->mp_part, message_mods) != OK) {
1191 status = NOTOK;
1192 break;
1193 }
1194 }
1195 }
1196 }
1197
1198 return status;
1199 }
1200
1201
1202 /*
1203 * Set content encoding.
1204 */
1205 static int
1206 set_ce (CT ct, int encoding)
1207 {
1208 const char *ce = ce_str (encoding);
1209 const struct str2init *ctinit = get_ce_method (ce);
1210
1211 if (ctinit) {
1212 char *cte = concat (" ", ce, "\n", NULL);
1213 bool found_cte = false;
1214 HF hf;
1215 /* Decoded contents might be in ct->c_cefile.ce_file, if the
1216 caller is decode_text_parts (). Save because we'll
1217 overwrite below. */
1218 struct cefile decoded_content_info = ct->c_cefile;
1219
1220 ct->c_encoding = encoding;
1221
1222 ct->c_ctinitfnx = ctinit->si_init;
1223 /* This will assign ct->c_cefile with an all-0 struct, which
1224 is what we want. */
1225 (*ctinit->si_init) (ct);
1226 /* After returning, the caller should set
1227 ct->c_cefile.ce_file to the name of the file containing
1228 the contents. */
1229
1230 if (ct->c_ceclosefnx) {
1231 (*ct->c_ceclosefnx) (ct);
1232 }
1233
1234 /* Restore the cefile. */
1235 ct->c_cefile = decoded_content_info;
1236
1237 /* Update/add Content-Transfer-Encoding header field. */
1238 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1239 if (! strcasecmp (ENCODING_FIELD, hf->name)) {
1240 found_cte = true;
1241 free (hf->value);
1242 hf->value = cte;
1243 }
1244 }
1245 if (! found_cte) {
1246 add_header (ct, mh_xstrdup (ENCODING_FIELD), cte);
1247 }
1248
1249 /* Update c_celine. It's used only by mhlist -debug. */
1250 free (ct->c_celine);
1251 ct->c_celine = mh_xstrdup (cte);
1252
1253 return OK;
1254 }
1255
1256 return NOTOK;
1257 }
1258
1259
1260 /*
1261 * Make sure each text part has a corresponding text/plain part.
1262 */
1263 static int
1264 ensure_text_plain (CT *ct, CT parent, int *message_mods, int replacetextplain)
1265 {
1266 int status = OK;
1267
1268 switch ((*ct)->c_type) {
1269 case CT_TEXT: {
1270 /* Nothing to do for text/plain. */
1271 if ((*ct)->c_subtype == TEXT_PLAIN) { return OK; }
1272
1273 if (parent && parent->c_type == CT_MULTIPART &&
1274 parent->c_subtype == MULTI_ALTERNATE) {
1275 int new_subpart_number = 1;
1276 int has_text_plain =
1277 find_textplain_sibling (parent, replacetextplain,
1278 &new_subpart_number);
1279
1280 if (! has_text_plain) {
1281 /* Parent is a multipart/alternative. Insert a new
1282 text/plain subpart. */
1283 const int inserted =
1284 insert_new_text_plain_part (*ct, new_subpart_number,
1285 parent);
1286 if (inserted) {
1287 ++*message_mods;
1288 if (verbosw) {
1289 report (NULL, parent->c_partno, parent->c_file,
1290 "insert text/plain part");
1291 }
1292 } else {
1293 status = NOTOK;
1294 }
1295 }
1296 } else if (parent && parent->c_type == CT_MULTIPART &&
1297 parent->c_subtype == MULTI_RELATED) {
1298 char *type_subtype =
1299 concat ((*ct)->c_ctinfo.ci_type, "/",
1300 (*ct)->c_ctinfo.ci_subtype, NULL);
1301 const char *parent_type =
1302 get_param (parent->c_ctinfo.ci_first_pm, "type", '?', 1);
1303 int new_subpart_number = 1;
1304 int has_text_plain = 0;
1305
1306 /* Have to do string comparison on the subtype because we
1307 don't enumerate all of them in c_subtype values.
1308 parent_type will be NULL if the multipart/related part
1309 doesn't have a type parameter. The type parameter must
1310 be specified according to RFC 2387 Sec. 3.1 but not all
1311 messages comply. */
1312 if (parent_type && strcasecmp (type_subtype, parent_type) == 0) {
1313 /* The type of this part matches the root type of the
1314 parent multipart/related. Look to see if there's
1315 text/plain sibling. */
1316 has_text_plain =
1317 find_textplain_sibling (parent, replacetextplain,
1318 &new_subpart_number);
1319 }
1320
1321 free (type_subtype);
1322
1323 if (! has_text_plain) {
1324 struct multipart *mp = (struct multipart *) parent->c_ctparams;
1325 struct part *part;
1326 int siblings = 0;
1327
1328 for (part = mp->mp_parts; part; part = part->mp_next) {
1329 if (*ct != part->mp_part) {
1330 ++siblings;
1331 }
1332 }
1333
1334 if (siblings) {
1335 /* Parent is a multipart/related. Insert a new
1336 text/plain subpart in a new multipart/alternative. */
1337 if (insert_into_new_mp_alt (ct, message_mods)) {
1338 /* Not an error if text/plain couldn't be added. */
1339 }
1340 } else {
1341 /* There are no siblings, so insert a new text/plain
1342 subpart, and change the parent type from
1343 multipart/related to multipart/alternative. */
1344 const int inserted =
1345 insert_new_text_plain_part (*ct, new_subpart_number,
1346 parent);
1347
1348 if (inserted) {
1349 HF hf;
1350
1351 parent->c_subtype = MULTI_ALTERNATE;
1352 free (parent->c_ctinfo.ci_subtype);
1353 parent->c_ctinfo.ci_subtype = mh_xstrdup("alternative");
1354 if (! replace_substring (&parent->c_ctline, "/related",
1355 "/alternative")) {
1356 inform("did not find multipart/related in %s",
1357 parent->c_ctline);
1358 }
1359
1360 /* Update Content-Type header field. */
1361 for (hf = parent->c_first_hf; hf; hf = hf->next) {
1362 if (! strcasecmp (TYPE_FIELD, hf->name)) {
1363 if (replace_substring (&hf->value, "/related",
1364 "/alternative")) {
1365 ++*message_mods;
1366 if (verbosw) {
1367 report (NULL, parent->c_partno,
1368 parent->c_file,
1369 "insert text/plain part");
1370 }
1371
1372 /* Remove, e.g., type="text/html" from
1373 multipart/alternative. */
1374 remove_parameter (hf->value, "type");
1375 break;
1376 }
1377 inform("did not find multipart/"
1378 "related in header %s", hf->value);
1379 }
1380 }
1381 } else {
1382 /* Not an error if text/plain couldn't be inserted. */
1383 }
1384 }
1385 }
1386 } else {
1387 if (insert_into_new_mp_alt (ct, message_mods)) {
1388 status = NOTOK;
1389 }
1390 }
1391 break;
1392 }
1393
1394 case CT_MULTIPART: {
1395 struct multipart *mp = (struct multipart *) (*ct)->c_ctparams;
1396 struct part *part;
1397
1398 for (part = mp->mp_parts; status == OK && part; part = part->mp_next) {
1399 if ((*ct)->c_type == CT_MULTIPART) {
1400 status = ensure_text_plain (&part->mp_part, *ct, message_mods,
1401 replacetextplain);
1402 }
1403 }
1404 break;
1405 }
1406
1407 case CT_MESSAGE:
1408 if ((*ct)->c_subtype == MESSAGE_EXTERNAL) {
1409 struct exbody *e = (struct exbody *) (*ct)->c_ctparams;
1410
1411 status = ensure_text_plain (&e->eb_content, *ct, message_mods,
1412 replacetextplain);
1413 }
1414 break;
1415 }
1416
1417 return status;
1418 }
1419
1420
1421 /*
1422 * See if there is a sibling text/plain, and return its subpart number.
1423 */
1424 static int
1425 find_textplain_sibling (CT parent, int replacetextplain,
1426 int *new_subpart_number)
1427 {
1428 struct multipart *mp = (struct multipart *) parent->c_ctparams;
1429 struct part *part, *prev;
1430 bool has_text_plain = false;
1431
1432 for (prev = part = mp->mp_parts; part; part = part->mp_next) {
1433 ++*new_subpart_number;
1434 if (part->mp_part->c_type == CT_TEXT &&
1435 part->mp_part->c_subtype == TEXT_PLAIN) {
1436 if (replacetextplain) {
1437 struct part *old_part;
1438 if (part == mp->mp_parts) {
1439 old_part = mp->mp_parts;
1440 mp->mp_parts = part->mp_next;
1441 } else {
1442 old_part = prev->mp_next;
1443 prev->mp_next = part->mp_next;
1444 }
1445 if (verbosw) {
1446 report (NULL, parent->c_partno, parent->c_file,
1447 "remove text/plain part %s",
1448 old_part->mp_part->c_partno);
1449 }
1450 free_content (old_part->mp_part);
1451 free (old_part);
1452 } else {
1453 has_text_plain = true;
1454 }
1455 break;
1456 }
1457 prev = part;
1458 }
1459
1460 return has_text_plain;
1461 }
1462
1463
1464 /*
1465 * Insert a new text/plain part.
1466 */
1467 static int
1468 insert_new_text_plain_part (CT ct, int new_subpart_number, CT parent)
1469 {
1470 struct multipart *mp = (struct multipart *) parent->c_ctparams;
1471 struct part *new_part;
1472
1473 NEW(new_part);
1474 if ((new_part->mp_part = build_text_plain_part (ct))) {
1475 char buffer[16];
1476 snprintf (buffer, sizeof buffer, "%d", new_subpart_number);
1477
1478 new_part->mp_next = mp->mp_parts;
1479 mp->mp_parts = new_part;
1480 new_part->mp_part->c_partno =
1481 concat (parent->c_partno ? parent->c_partno : "1", ".",
1482 buffer, NULL);
1483
1484 return 1;
1485 }
1486
1487 free_content (new_part->mp_part);
1488 free (new_part);
1489
1490 return 0;
1491 }
1492
1493
1494 /*
1495 * Create a text/plain part to go along with non-plain sibling part.
1496 */
1497 static CT
1498 build_text_plain_part (CT encoded_part)
1499 {
1500 CT tp_part = divide_part (encoded_part);
1501 char *tmp_plain_file = NULL;
1502
1503 if (decode_part (tp_part) == OK) {
1504 /* Now, tp_part->c_cefile.ce_file is the name of the tmp file that
1505 contains the decoded contents. And the decoding function, such
1506 as openQuoted, will have set ...->ce_unlink to 1 so that it will
1507 be unlinked by free_content (). */
1508 char *tempfile;
1509
1510 /* This m_mktemp2() call closes the temp file. */
1511 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, NULL)) == NULL) {
1512 inform("unable to create temporary file in %s",
1513 get_temp_dir());
1514 } else {
1515 tmp_plain_file = mh_xstrdup (tempfile);
1516 if (reformat_part (tp_part, tmp_plain_file,
1517 tp_part->c_ctinfo.ci_type,
1518 tp_part->c_ctinfo.ci_subtype,
1519 tp_part->c_type) == OK) {
1520 return tp_part;
1521 }
1522 }
1523 }
1524
1525 free_content (tp_part);
1526 if (tmp_plain_file) { (void) m_unlink (tmp_plain_file); }
1527 free (tmp_plain_file);
1528
1529 return NULL;
1530 }
1531
1532
1533 /*
1534 * Slip new text/plain part into a new multipart/alternative.
1535 */
1536 static int
1537 insert_into_new_mp_alt (CT *ct, int *message_mods)
1538 {
1539 CT tp_part = build_text_plain_part (*ct);
1540 int status = OK;
1541
1542 if (tp_part) {
1543 CT mp_alt = build_multipart_alt (*ct, tp_part, CT_MULTIPART,
1544 MULTI_ALTERNATE);
1545 if (mp_alt) {
1546 struct multipart *mp = (struct multipart *) mp_alt->c_ctparams;
1547
1548 if (mp && mp->mp_parts) {
1549 mp->mp_parts->mp_part = tp_part;
1550 /* Make the new multipart/alternative the parent. */
1551 *ct = mp_alt;
1552
1553 ++*message_mods;
1554 if (verbosw) {
1555 report (NULL, (*ct)->c_partno, (*ct)->c_file,
1556 "insert text/plain part");
1557 }
1558 } else {
1559 free_content (tp_part);
1560 free_content (mp_alt);
1561 status = NOTOK;
1562 }
1563 } else {
1564 status = NOTOK;
1565 }
1566 } else {
1567 /* Not an error if text/plain couldn't be built. */
1568 }
1569
1570 return status;
1571 }
1572
1573
1574 /*
1575 * Clone a MIME part.
1576 */
1577 static CT
1578 divide_part (CT ct)
1579 {
1580 CT new_part;
1581
1582 NEW0(new_part);
1583 /* Just copy over what is needed for decoding. c_vrsn and
1584 c_celine aren't necessary. */
1585 new_part->c_file = mh_xstrdup (ct->c_file);
1586 new_part->c_begin = ct->c_begin;
1587 new_part->c_end = ct->c_end;
1588 copy_ctinfo (&new_part->c_ctinfo, &ct->c_ctinfo);
1589 new_part->c_type = ct->c_type;
1590 new_part->c_cefile = ct->c_cefile;
1591 new_part->c_encoding = ct->c_encoding;
1592 new_part->c_ctinitfnx = ct->c_ctinitfnx;
1593 new_part->c_ceopenfnx = ct->c_ceopenfnx;
1594 new_part->c_ceclosefnx = ct->c_ceclosefnx;
1595 new_part->c_cesizefnx = ct->c_cesizefnx;
1596
1597 /* c_ctline is used by reformat__part(), so it can preserve
1598 anything after the type/subtype. */
1599 new_part->c_ctline = mh_xstrdup (ct->c_ctline);
1600
1601 return new_part;
1602 }
1603
1604
1605 /*
1606 * Copy the content info from one part to another.
1607 */
1608 static void
1609 copy_ctinfo (CI dest, CI src)
1610 {
1611 PM s_pm, d_pm;
1612
1613 dest->ci_type = src->ci_type ? mh_xstrdup (src->ci_type) : NULL;
1614 dest->ci_subtype = src->ci_subtype ? mh_xstrdup (src->ci_subtype) : NULL;
1615
1616 for (s_pm = src->ci_first_pm; s_pm; s_pm = s_pm->pm_next) {
1617 d_pm = add_param(&dest->ci_first_pm, &dest->ci_last_pm, s_pm->pm_name,
1618 s_pm->pm_value, 0);
1619 if (s_pm->pm_charset) {
1620 d_pm->pm_charset = mh_xstrdup(s_pm->pm_charset);
1621 }
1622 if (s_pm->pm_lang) {
1623 d_pm->pm_lang = mh_xstrdup(s_pm->pm_lang);
1624 }
1625 }
1626
1627 dest->ci_comment = src->ci_comment ? mh_xstrdup (src->ci_comment) : NULL;
1628 dest->ci_magic = src->ci_magic ? mh_xstrdup (src->ci_magic) : NULL;
1629 }
1630
1631
1632 /*
1633 * Decode content.
1634 */
1635 static int
1636 decode_part (CT ct)
1637 {
1638 char *tmp_decoded;
1639 int status;
1640 FILE *file;
1641 char *tempfile;
1642
1643 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, &file)) == NULL) {
1644 die("unable to create temporary file in %s", get_temp_dir());
1645 }
1646 tmp_decoded = mh_xstrdup (tempfile);
1647 /* The following call will load ct->c_cefile.ce_file with the tmp
1648 filename of the decoded content. tmp_decoded will contain the
1649 encoded output, get rid of that. */
1650 status = output_message_fp (ct, file, tmp_decoded);
1651 (void) m_unlink (tmp_decoded);
1652 free (tmp_decoded);
1653 if (fclose (file)) {
1654 inform("unable to close temporary file %s, continuing...", tempfile);
1655 }
1656
1657 return status;
1658 }
1659
1660
1661 /*
1662 * Reformat content as plain text.
1663 * Some of the arguments aren't really needed now, but maybe will
1664 * be in the future for other than text types.
1665 */
1666 static int
1667 reformat_part (CT ct, char *file, char *type, char *subtype, int c_type)
1668 {
1669 int output_subtype, output_encoding;
1670 const char *reason = NULL;
1671 char *cp, *cf;
1672 int status;
1673
1674 /* Hacky: this redirects the output from whatever command is used
1675 to show the part to a file. So, the user can't have any output
1676 redirection in that command.
1677 Could show_multi() in mhshowsbr.c avoid this? */
1678
1679 /* Check for invo_name-format-type/subtype. */
1680 if ((cf = context_find_by_type ("format", type, subtype)) == NULL) {
1681 if (verbosw) {
1682 inform("Don't know how to convert %s, there is no "
1683 "%s-format-%s/%s profile entry",
1684 ct->c_file, invo_name, type, subtype);
1685 }
1686 return NOTOK;
1687 }
1688 if (strchr (cf, '>')) {
1689 inform("'>' prohibited in \"%s\",\nplease fix your "
1690 "%s-format-%s/%s profile entry", cf, invo_name, type,
1691 FENDNULL(subtype));
1692
1693 return NOTOK;
1694 }
1695
1696 cp = concat (cf, " >", file, NULL);
1697 status = show_content_aux (ct, 0, cp, NULL, NULL);
1698 free (cp);
1699
1700 /* Unlink decoded content tmp file and free its filename to avoid
1701 leaks. The file stream should already have been closed. */
1702 if (ct->c_cefile.ce_unlink) {
1703 (void) m_unlink (ct->c_cefile.ce_file);
1704 free (ct->c_cefile.ce_file);
1705 ct->c_cefile.ce_file = NULL;
1706 ct->c_cefile.ce_unlink = 0;
1707 }
1708
1709 if (c_type == CT_TEXT) {
1710 output_subtype = TEXT_PLAIN;
1711 } else {
1712 /* Set subtype to 0, which is always an UNKNOWN subtype. */
1713 output_subtype = 0;
1714 }
1715
1716 output_encoding = content_encoding (ct, &reason);
1717 if (status == OK &&
1718 set_ct_type (ct, c_type, output_subtype, output_encoding) == OK) {
1719 ct->c_cefile.ce_file = file;
1720 ct->c_cefile.ce_unlink = 1;
1721 } else {
1722 ct->c_cefile.ce_unlink = 0;
1723 status = NOTOK;
1724 }
1725
1726 return status;
1727 }
1728
1729
1730 /*
1731 * Fill in a multipart/alternative part.
1732 */
1733 static CT
1734 build_multipart_alt (CT first_alt, CT new_part, int type, int subtype)
1735 {
1736 char *boundary_prefix = "----=_nmh-multipart";
1737 char *boundary = concat (boundary_prefix, first_alt->c_partno, NULL);
1738 char *boundary_indicator = "; boundary=";
1739 char *typename, *subtypename, *name;
1740 CT ct;
1741 struct part *p;
1742 struct multipart *m;
1743 const struct str2init *ctinit;
1744
1745 NEW0(ct);
1746
1747 /* Set up the multipart/alternative part. These fields of *ct were
1748 initialized to 0 by mh_xcalloc():
1749 c_fp, c_unlink, c_begin, c_end,
1750 c_vrsn, c_ctline, c_celine,
1751 c_id, c_descr, c_dispo, c_partno,
1752 c_ctinfo.ci_comment, c_ctinfo.ci_magic,
1753 c_cefile, c_encoding,
1754 c_digested, c_digest[16], c_ctexbody,
1755 c_ctinitfnx, c_ceopenfnx, c_ceclosefnx, c_cesizefnx,
1756 c_umask, c_rfc934,
1757 c_showproc, c_termproc, c_storeproc, c_storage, c_folder
1758 */
1759
1760 ct->c_file = mh_xstrdup (first_alt->c_file);
1761 ct->c_type = type;
1762 ct->c_subtype = subtype;
1763
1764 ctinit = get_ct_init (ct->c_type);
1765
1766 typename = ct_type_str (type);
1767 subtypename = ct_subtype_str (type, subtype);
1768
1769 {
1770 int serial = 0;
1771 int found_boundary = 1;
1772
1773 while (found_boundary && serial < 1000000) {
1774 found_boundary = 0;
1775
1776 /* Ensure that the boundary doesn't appear in the decoded
1777 content. */
1778 if (new_part->c_cefile.ce_file) {
1779 if ((found_boundary =
1780 boundary_in_content (&new_part->c_cefile.ce_fp,
1781 new_part->c_cefile.ce_file,
1782 boundary)) == NOTOK) {
1783 goto return_null;
1784 }
1785 }
1786
1787 /* Ensure that the boundary doesn't appear in the encoded
1788 content. */
1789 if (! found_boundary && new_part->c_file) {
1790 if ((found_boundary =
1791 boundary_in_content (&new_part->c_fp,
1792 new_part->c_file,
1793 boundary)) == NOTOK) {
1794 goto return_null;
1795 }
1796 }
1797
1798 if (found_boundary) {
1799 /* Try a slightly different boundary. */
1800 char buffer2[16];
1801
1802 free (boundary);
1803 ++serial;
1804 snprintf (buffer2, sizeof buffer2, "%d", serial);
1805 boundary =
1806 concat (boundary_prefix,
1807 FENDNULL(first_alt->c_partno),
1808 "-", buffer2, NULL);
1809 }
1810 }
1811
1812 if (found_boundary) {
1813 inform("giving up trying to find a unique boundary");
1814 goto return_null;
1815 }
1816 }
1817
1818 name = concat (" ", typename, "/", subtypename, boundary_indicator, "\"",
1819 boundary, "\"", NULL);
1820
1821 /* Load c_first_hf and c_last_hf. */
1822 transfer_noncontent_headers (first_alt, ct);
1823 add_header (ct, mh_xstrdup (TYPE_FIELD), concat (name, "\n", NULL));
1824 free (name);
1825
1826 /* Load c_partno. */
1827 if (first_alt->c_partno) {
1828 ct->c_partno = mh_xstrdup (first_alt->c_partno);
1829 free (first_alt->c_partno);
1830 first_alt->c_partno = concat (ct->c_partno, ".1", NULL);
1831 new_part->c_partno = concat (ct->c_partno, ".2", NULL);
1832 } else {
1833 first_alt->c_partno = mh_xstrdup ("1");
1834 new_part->c_partno = mh_xstrdup ("2");
1835 }
1836
1837 if (ctinit) {
1838 ct->c_ctinfo.ci_type = mh_xstrdup (typename);
1839 ct->c_ctinfo.ci_subtype = mh_xstrdup (subtypename);
1840 }
1841
1842 add_param(&ct->c_ctinfo.ci_first_pm, &ct->c_ctinfo.ci_last_pm,
1843 "boundary", boundary, 0);
1844
1845 NEW(p);
1846 NEW(p->mp_next);
1847 p->mp_next->mp_next = NULL;
1848 p->mp_next->mp_part = first_alt;
1849
1850 NEW0(m);
1851 m->mp_start = concat (boundary, "\n", NULL);
1852 m->mp_stop = concat (boundary, "--\n", NULL);
1853 m->mp_parts = p;
1854 ct->c_ctparams = m;
1855
1856 free (boundary);
1857
1858 return ct;
1859
1860 return_null:
1861 free_content(ct);
1862 free(boundary);
1863 return NULL;
1864 }
1865
1866
1867 /*
1868 * Check that the boundary does not appear in the content.
1869 */
1870 static int
1871 boundary_in_content (FILE **fp, char *file, const char *boundary)
1872 {
1873 char buffer[NMH_BUFSIZ];
1874 size_t bytes_read;
1875 bool found_boundary = false;
1876
1877 /* free_content() will close *fp if we fopen it here. */
1878 if (! *fp && (*fp = fopen (file, "r")) == NULL) {
1879 advise (file, "unable to open %s for reading", file);
1880 return NOTOK;
1881 }
1882
1883 fseeko (*fp, 0L, SEEK_SET);
1884 while ((bytes_read = fread (buffer, 1, sizeof buffer, *fp)) > 0) {
1885 if (find_str (buffer, bytes_read, boundary)) {
1886 found_boundary = true;
1887 break;
1888 }
1889 }
1890
1891 return found_boundary;
1892 }
1893
1894
1895 /*
1896 * Remove all non-Content headers.
1897 */
1898 static void
1899 transfer_noncontent_headers (CT old, CT new)
1900 {
1901 HF hp, hp_prev;
1902
1903 hp_prev = hp = old->c_first_hf;
1904 while (hp) {
1905 HF next = hp->next;
1906
1907 if (strncasecmp (XXX_FIELD_PRF, hp->name, LEN(XXX_FIELD_PRF))) {
1908 if (hp == old->c_last_hf) {
1909 if (hp == old->c_first_hf) {
1910 old->c_last_hf = old->c_first_hf = NULL;
1911 } else {
1912 hp_prev->next = NULL;
1913 old->c_last_hf = hp_prev;
1914 }
1915 } else {
1916 if (hp == old->c_first_hf) {
1917 old->c_first_hf = next;
1918 } else {
1919 hp_prev->next = next;
1920 }
1921 }
1922
1923 /* Put node hp in the new CT. */
1924 if (new->c_first_hf == NULL) {
1925 new->c_first_hf = hp;
1926 } else {
1927 new->c_last_hf->next = hp;
1928 }
1929 new->c_last_hf = hp;
1930 } else {
1931 /* A Content- header, leave in old. */
1932 hp_prev = hp;
1933 }
1934
1935 hp = next;
1936 }
1937 }
1938
1939
1940 /*
1941 * Set content type.
1942 */
1943 static int
1944 set_ct_type (CT ct, int type, int subtype, int encoding)
1945 {
1946 char *typename = ct_type_str (type);
1947 char *subtypename = ct_subtype_str (type, subtype);
1948 /* E.g, " text/plain" */
1949 char *type_subtypename = concat (" ", typename, "/", subtypename, NULL);
1950 /* E.g, " text/plain\n" */
1951 char *name_plus_nl = concat (type_subtypename, "\n", NULL);
1952 bool found_content_type = false;
1953 HF hf;
1954 const char *cp = NULL;
1955 char *ctline;
1956 int status;
1957
1958 /* Update/add Content-Type header field. */
1959 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1960 if (! strcasecmp (TYPE_FIELD, hf->name)) {
1961 found_content_type = true;
1962 free (hf->value);
1963 hf->value = (cp = strchr (ct->c_ctline, ';'))
1964 ? concat (type_subtypename, cp, "\n", NULL)
1965 : mh_xstrdup (name_plus_nl);
1966 }
1967 }
1968 if (! found_content_type) {
1969 add_header (ct, mh_xstrdup (TYPE_FIELD),
1970 (cp = strchr (ct->c_ctline, ';'))
1971 ? concat (type_subtypename, cp, "\n", NULL)
1972 : mh_xstrdup (name_plus_nl));
1973 }
1974
1975 /* Some of these might not be used, but set them anyway. */
1976 ctline = cp
1977 ? concat (type_subtypename, cp, NULL)
1978 : concat (type_subtypename, NULL);
1979 free (ct->c_ctline);
1980 ct->c_ctline = ctline;
1981 /* Leave other ctinfo members as they were. */
1982 free (ct->c_ctinfo.ci_type);
1983 ct->c_ctinfo.ci_type = mh_xstrdup (typename);
1984 free (ct->c_ctinfo.ci_subtype);
1985 ct->c_ctinfo.ci_subtype = mh_xstrdup (subtypename);
1986 ct->c_type = type;
1987 ct->c_subtype = subtype;
1988
1989 free (name_plus_nl);
1990 free (type_subtypename);
1991
1992 status = set_ce (ct, encoding);
1993
1994 return status;
1995 }
1996
1997
1998 /*
1999 * It's not necessary to update the charset parameter of a Content-Type
2000 * header for a text part. According to RFC 2045 Sec. 6.4, the body
2001 * (content) was originally in the specified charset, "and will be in
2002 * that character set again after decoding."
2003 */
2004 static int
2005 decode_text_parts (CT ct, int encoding, const char *decodetypes,
2006 int *message_mods)
2007 {
2008 int status = OK;
2009 int lf_line_endings = 0;
2010
2011 switch (ct->c_type) {
2012 case CT_MULTIPART: {
2013 struct multipart *m = (struct multipart *) ct->c_ctparams;
2014 struct part *part;
2015
2016 /* Should check to see if the body for this part is encoded?
2017 For now, it gets passed along as-is by InitMultiPart(). */
2018 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
2019 status = decode_text_parts (part->mp_part, encoding, decodetypes,
2020 message_mods);
2021 }
2022 break;
2023 }
2024
2025 case CT_MESSAGE:
2026 if (ct->c_subtype == MESSAGE_EXTERNAL) {
2027 struct exbody *e = (struct exbody *) ct->c_ctparams;
2028
2029 status = decode_text_parts (e->eb_content, encoding, decodetypes,
2030 message_mods);
2031 }
2032 break;
2033
2034 default:
2035 if (! should_decode(decodetypes, ct->c_ctinfo.ci_type, ct->c_ctinfo.ci_subtype)) {
2036 break;
2037 }
2038
2039 lf_line_endings =
2040 ct->c_ctparams && ((struct text *) ct->c_ctparams)->lf_line_endings;
2041
2042 switch (ct->c_encoding) {
2043 case CE_BASE64:
2044 case CE_QUOTED: {
2045 int ct_encoding;
2046
2047 if (decode_part (ct) == OK && ct->c_cefile.ce_file) {
2048 const char *reason = NULL;
2049
2050 if ((ct_encoding = content_encoding (ct, &reason)) == CE_BINARY
2051 && encoding != CE_BINARY) {
2052 /* The decoding isn't acceptable so discard it.
2053 Leave status as OK to allow other transformations. */
2054 if (verbosw) {
2055 report (NULL, ct->c_partno, ct->c_file,
2056 "will not decode%s because it is binary (%s)",
2057 ct->c_partno ? ""
2058 : (FENDNULL(ct->c_ctline)),
2059 reason);
2060 }
2061 (void) m_unlink (ct->c_cefile.ce_file);
2062 free (ct->c_cefile.ce_file);
2063 ct->c_cefile.ce_file = NULL;
2064 } else if (ct->c_encoding == CE_QUOTED &&
2065 ct_encoding == CE_8BIT && encoding == CE_7BIT) {
2066 /* The decoding isn't acceptable so discard it.
2067 Leave status as OK to allow other transformations. */
2068 if (verbosw) {
2069 report (NULL, ct->c_partno, ct->c_file,
2070 "will not decode%s because it is 8bit",
2071 ct->c_partno ? ""
2072 : (FENDNULL(ct->c_ctline)));
2073 }
2074 (void) m_unlink (ct->c_cefile.ce_file);
2075 free (ct->c_cefile.ce_file);
2076 ct->c_cefile.ce_file = NULL;
2077 } else {
2078 int enc;
2079
2080 if (ct_encoding == CE_BINARY) {
2081 enc = CE_BINARY;
2082 } else if (ct_encoding == CE_8BIT && encoding == CE_7BIT) {
2083 enc = CE_QUOTED;
2084 } else {
2085 enc = ct_encoding;
2086 }
2087 if (set_ce (ct, enc) == OK) {
2088 ++*message_mods;
2089 if (verbosw) {
2090 report (NULL, ct->c_partno, ct->c_file, "decode%s",
2091 FENDNULL(ct->c_ctline));
2092 }
2093 if (lf_line_endings) {
2094 strip_crs (ct, message_mods);
2095 }
2096 } else {
2097 status = NOTOK;
2098 }
2099 }
2100 } else {
2101 status = NOTOK;
2102 }
2103 break;
2104 }
2105 case CE_8BIT:
2106 case CE_7BIT:
2107 if (lf_line_endings) {
2108 strip_crs (ct, message_mods);
2109 }
2110 break;
2111 default:
2112 break;
2113 }
2114
2115 break;
2116 }
2117
2118 return status;
2119 }
2120
2121
2122 /*
2123 * Determine if the part with type[/subtype] should be decoded, according to
2124 * decodetypes (which came from the -decodetypes switch).
2125 */
2126 static int
2127 should_decode(const char *decodetypes, const char *type, const char *subtype)
2128 {
2129 /* Quick search for matching type[/subtype] in decodetypes: bracket
2130 decodetypes with commas, then search for ,type, and ,type/subtype, in
2131 it. */
2132
2133 bool found_match = false;
2134 char *delimited_decodetypes = concat(",", decodetypes, ",", NULL);
2135 char *delimited_type = concat(",", type, ",", NULL);
2136
2137 if (nmh_strcasestr(delimited_decodetypes, delimited_type)) {
2138 found_match = true;
2139 } else if (subtype != NULL) {
2140 char *delimited_type_subtype =
2141 concat(",", type, "/", subtype, ",", NULL);
2142
2143 if (nmh_strcasestr(delimited_decodetypes, delimited_type_subtype)) {
2144 found_match = true;
2145 }
2146 free(delimited_type_subtype);
2147 }
2148
2149 free(delimited_type);
2150 free(delimited_decodetypes);
2151
2152 return found_match;
2153 }
2154
2155
2156 /*
2157 * See if the decoded content is 7bit, 8bit, or binary. It's binary
2158 * if it has any NUL characters, a CR not followed by a LF, or lines
2159 * greater than 998 characters in length. If binary, reason is set
2160 * to a string explaining why.
2161 */
2162 static int
2163 content_encoding (CT ct, const char **reason)
2164 {
2165 CE ce = &ct->c_cefile;
2166 int encoding = CE_7BIT;
2167
2168 if (ce->ce_file) {
2169 size_t line_len = 0;
2170 char buffer[NMH_BUFSIZ];
2171 size_t inbytes;
2172
2173 if (! ce->ce_fp && (ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
2174 advise (ce->ce_file, "unable to open for reading");
2175 return CE_UNKNOWN;
2176 }
2177
2178 fseeko (ce->ce_fp, 0L, SEEK_SET);
2179 while (encoding != CE_BINARY &&
2180 (inbytes = fread (buffer, 1, sizeof buffer, ce->ce_fp)) > 0) {
2181 char *cp;
2182 size_t i;
2183 int last_char_was_cr = 0;
2184
2185 for (i = 0, cp = buffer; i < inbytes; ++i, ++cp) {
2186 if (*cp == '\0' || ++line_len > 998 ||
2187 (*cp != '\n' && last_char_was_cr)) {
2188 encoding = CE_BINARY;
2189 if (*cp == '\0') {
2190 *reason = "null character";
2191 } else if (line_len > 998) {
2192 *reason = "line length > 998";
2193 } else if (*cp != '\n' && last_char_was_cr) {
2194 *reason = "CR not followed by LF";
2195 } else {
2196 /* Should not reach this. */
2197 *reason = "";
2198 }
2199 break;
2200 }
2201 if (*cp == '\n') {
2202 line_len = 0;
2203 } else if (! isascii ((unsigned char) *cp)) {
2204 encoding = CE_8BIT;
2205 }
2206
2207 last_char_was_cr = *cp == '\r';
2208 }
2209 }
2210
2211 fclose (ce->ce_fp);
2212 ce->ce_fp = NULL;
2213 } /* else should never happen */
2214
2215 return encoding;
2216 }
2217
2218
2219 /*
2220 * Strip carriage returns from content.
2221 */
2222 static int
2223 strip_crs (CT ct, int *message_mods)
2224 {
2225 char *charset = content_charset (ct);
2226 int status = OK;
2227
2228 /* Only strip carriage returns if content is ASCII or another
2229 charset that has the same readily recognizable CR followed by a
2230 LF. We can include UTF-8 here because if the high-order bit of
2231 a UTF-8 byte is 0, then it must be a single-byte ASCII
2232 character. */
2233 if (! strcasecmp (charset, "US-ASCII") ||
2234 ! strcasecmp (charset, "UTF-8") ||
2235 ! strncasecmp (charset, "ISO-8859-", 9) ||
2236 ! strncasecmp (charset, "WINDOWS-12", 10)) {
2237 char **file = NULL;
2238 FILE **fp = NULL;
2239 size_t begin;
2240 size_t end;
2241 bool has_crs = false;
2242 bool opened_input_file = false;
2243
2244 if (ct->c_cefile.ce_file) {
2245 file = &ct->c_cefile.ce_file;
2246 fp = &ct->c_cefile.ce_fp;
2247 begin = end = 0;
2248 } else if (ct->c_file) {
2249 file = &ct->c_file;
2250 fp = &ct->c_fp;
2251 begin = (size_t) ct->c_begin;
2252 end = (size_t) ct->c_end;
2253 } /* else don't know where the content is */
2254
2255 if (file && *file && fp) {
2256 if (! *fp) {
2257 if ((*fp = fopen (*file, "r")) == NULL) {
2258 advise (*file, "unable to open for reading");
2259 status = NOTOK;
2260 } else {
2261 opened_input_file = true;
2262 }
2263 }
2264 }
2265
2266 if (fp && *fp) {
2267 char buffer[NMH_BUFSIZ];
2268 size_t bytes_read;
2269 size_t bytes_to_read =
2270 end > 0 && end > begin ? end - begin : sizeof buffer;
2271
2272 fseeko (*fp, begin, SEEK_SET);
2273 while ((bytes_read = fread (buffer, 1,
2274 min (bytes_to_read, sizeof buffer),
2275 *fp)) > 0) {
2276 /* Look for CR followed by a LF. This is supposed to
2277 be text so there should be LF's. If not, don't
2278 modify the content. */
2279 char *cp;
2280 size_t i;
2281 bool last_char_was_cr = false;
2282
2283 if (end > 0) { bytes_to_read -= bytes_read; }
2284
2285 for (i = 0, cp = buffer; i < bytes_read; ++i, ++cp) {
2286 if (*cp == '\n' && last_char_was_cr) {
2287 has_crs = true;
2288 break;
2289 }
2290
2291 last_char_was_cr = *cp == '\r';
2292 }
2293 }
2294
2295 if (has_crs) {
2296 int fd;
2297 char *stripped_content_file;
2298 char *tempfile = m_mktemp2 (NULL, invo_name, &fd, NULL);
2299
2300 if (tempfile == NULL) {
2301 die("unable to create temporary file in %s",
2302 get_temp_dir());
2303 }
2304 stripped_content_file = mh_xstrdup (tempfile);
2305
2306 /* Strip each CR before a LF from the content. */
2307 fseeko (*fp, begin, SEEK_SET);
2308 while ((bytes_read = fread (buffer, 1, sizeof buffer, *fp)) >
2309 0) {
2310 char *cp;
2311 size_t i;
2312 bool last_char_was_cr = false;
2313
2314 for (i = 0, cp = buffer; i < bytes_read; ++i, ++cp) {
2315 if (*cp == '\r') {
2316 last_char_was_cr = true;
2317 } else if (last_char_was_cr) {
2318 if (*cp != '\n') {
2319 if (write (fd, "\r", 1) < 0) {
2320 advise (tempfile, "CR write");
2321 }
2322 }
2323 if (write (fd, cp, 1) < 0) {
2324 advise (tempfile, "write");
2325 }
2326 last_char_was_cr = false;
2327 } else {
2328 if (write (fd, cp, 1) < 0) {
2329 advise (tempfile, "write");
2330 }
2331 last_char_was_cr = false;
2332 }
2333 }
2334 }
2335
2336 if (close (fd)) {
2337 inform("unable to write temporary file %s, continuing...",
2338 stripped_content_file);
2339 (void) m_unlink (stripped_content_file);
2340 free(stripped_content_file);
2341 status = NOTOK;
2342 } else {
2343 /* Replace the decoded file with the converted one. */
2344 if (ct->c_cefile.ce_file && ct->c_cefile.ce_unlink)
2345 (void) m_unlink (ct->c_cefile.ce_file);
2346
2347 free(ct->c_cefile.ce_file);
2348 ct->c_cefile.ce_file = stripped_content_file;
2349 ct->c_cefile.ce_unlink = 1;
2350
2351 ++*message_mods;
2352 if (verbosw) {
2353 report (NULL, ct->c_partno,
2354 begin == 0 && end == 0 ? "" : *file,
2355 "stripped CRs");
2356 }
2357 }
2358 }
2359
2360 if (opened_input_file) {
2361 fclose (*fp);
2362 *fp = NULL;
2363 }
2364 }
2365 }
2366
2367 free (charset);
2368
2369 return status;
2370 }
2371
2372
2373 /*
2374 * Add/update, if necessary, the message C-T-E, based on the least restrictive
2375 * of the part C-T-E's.
2376 */
2377 static void
2378 update_cte (CT ct)
2379 {
2380 const int least_restrictive_enc = least_restrictive_encoding (ct);
2381
2382 if (least_restrictive_enc != CE_UNKNOWN &&
2383 least_restrictive_enc != CE_7BIT) {
2384 char *cte = concat (" ", ce_str (least_restrictive_enc), "\n", NULL);
2385 HF hf;
2386 bool found_cte = false;
2387
2388 /* Update/add Content-Transfer-Encoding header field. */
2389 for (hf = ct->c_first_hf; hf; hf = hf->next) {
2390 if (! strcasecmp (ENCODING_FIELD, hf->name)) {
2391 found_cte = true;
2392 free (hf->value);
2393 hf->value = cte;
2394 }
2395 }
2396 if (! found_cte) {
2397 add_header (ct, mh_xstrdup (ENCODING_FIELD), cte);
2398 }
2399 }
2400 }
2401
2402
2403 /*
2404 * Find the least restrictive encoding (7bit, 8bit, binary) of the parts
2405 * within a message.
2406 */
2407 static int
2408 least_restrictive_encoding (CT ct)
2409 {
2410 int encoding = CE_UNKNOWN;
2411
2412 switch (ct->c_type) {
2413 case CT_MULTIPART: {
2414 struct multipart *m = (struct multipart *) ct->c_ctparams;
2415 struct part *part;
2416
2417 for (part = m->mp_parts; part; part = part->mp_next) {
2418 const int part_encoding =
2419 least_restrictive_encoding (part->mp_part);
2420
2421 if (less_restrictive (encoding, part_encoding)) {
2422 encoding = part_encoding;
2423 }
2424 }
2425 break;
2426 }
2427
2428 case CT_MESSAGE:
2429 if (ct->c_subtype == MESSAGE_EXTERNAL) {
2430 struct exbody *e = (struct exbody *) ct->c_ctparams;
2431 const int part_encoding =
2432 least_restrictive_encoding (e->eb_content);
2433
2434 if (less_restrictive (encoding, part_encoding)) {
2435 encoding = part_encoding;
2436 }
2437 }
2438 break;
2439
2440 default: {
2441 if (less_restrictive (encoding, ct->c_encoding)) {
2442 encoding = ct->c_encoding;
2443 }
2444 }}
2445
2446 return encoding;
2447 }
2448
2449
2450 /*
2451 * Return whether the second encoding is less restrictive than the first, where
2452 * "less restrictive" is in the sense used by RFC 2045 Secs. 6.1 and 6.4. So,
2453 * CE_BINARY is less restrictive than CE_8BIT and
2454 * CE_8BIT is less restrictive than CE_7BIT.
2455 */
2456 static int
2457 less_restrictive (int encoding, int second_encoding)
2458 {
2459 switch (second_encoding) {
2460 case CE_BINARY:
2461 return encoding != CE_BINARY;
2462 case CE_8BIT:
2463 return encoding != CE_BINARY && encoding != CE_8BIT;
2464 case CE_7BIT:
2465 return encoding != CE_BINARY && encoding != CE_8BIT &&
2466 encoding != CE_7BIT;
2467 default :
2468 return 0;
2469 }
2470 }
2471
2472
2473 /*
2474 * Convert character set of each part.
2475 */
2476 static int
2477 convert_charsets (CT ct, char *dest_charset, int *message_mods)
2478 {
2479 int status = OK;
2480
2481 switch (ct->c_type) {
2482 case CT_TEXT:
2483 if (ct->c_subtype == TEXT_PLAIN) {
2484 status = convert_charset (ct, dest_charset, message_mods);
2485 if (status == OK) {
2486 if (verbosw) {
2487 char *ct_charset = content_charset (ct);
2488
2489 report (NULL, ct->c_partno, ct->c_file,
2490 "convert %s to %s", ct_charset, dest_charset);
2491 free (ct_charset);
2492 }
2493 } else {
2494 char *ct_charset = content_charset (ct);
2495
2496 report ("iconv", ct->c_partno, ct->c_file,
2497 "failed to convert %s to %s", ct_charset, dest_charset);
2498 free (ct_charset);
2499 }
2500 }
2501 break;
2502
2503 case CT_MULTIPART: {
2504 struct multipart *m = (struct multipart *) ct->c_ctparams;
2505 struct part *part;
2506
2507 /* Should check to see if the body for this part is encoded?
2508 For now, it gets passed along as-is by InitMultiPart(). */
2509 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
2510 status =
2511 convert_charsets (part->mp_part, dest_charset, message_mods);
2512 }
2513 break;
2514 }
2515
2516 case CT_MESSAGE:
2517 if (ct->c_subtype == MESSAGE_EXTERNAL) {
2518 struct exbody *e = (struct exbody *) ct->c_ctparams;
2519
2520 status =
2521 convert_charsets (e->eb_content, dest_charset, message_mods);
2522 }
2523 break;
2524
2525 default:
2526 break;
2527 }
2528
2529 return status;
2530 }
2531
2532
2533 /*
2534 * Fix various problems that aren't handled elsewhere. These
2535 * are fixed unconditionally: there are no switches to disable
2536 * them. Currently, "problems" are these:
2537 * 1) remove extraneous semicolon at the end of a header parameter list
2538 * 2) replace RFC 2047 encoding with RFC 2231 encoding of name and
2539 * filename parameters in Content-Type and Content-Disposition
2540 * headers, respectively.
2541 */
2542 static int
2543 fix_always (CT ct, int *message_mods)
2544 {
2545 int status = OK;
2546
2547 switch (ct->c_type) {
2548 case CT_MULTIPART: {
2549 struct multipart *m = (struct multipart *) ct->c_ctparams;
2550 struct part *part;
2551
2552 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
2553 status = fix_always (part->mp_part, message_mods);
2554 }
2555 break;
2556 }
2557
2558 case CT_MESSAGE:
2559 if (ct->c_subtype == MESSAGE_EXTERNAL) {
2560 struct exbody *e = (struct exbody *) ct->c_ctparams;
2561
2562 status = fix_always (e->eb_content, message_mods);
2563 }
2564 break;
2565
2566 default: {
2567 HF hf;
2568
2569 if (ct->c_first_hf) {
2570 fix_filename_encoding (ct);
2571 }
2572
2573 for (hf = ct->c_first_hf; hf; hf = hf->next) {
2574 size_t len = strlen (hf->value);
2575
2576 if (strcasecmp (hf->name, TYPE_FIELD) != 0 &&
2577 strcasecmp (hf->name, DISPO_FIELD) != 0) {
2578 /* Only do this for Content-Type and
2579 Content-Disposition fields because those are the
2580 only headers that parse_mime() warns about. */
2581 continue;
2582 }
2583
2584 /* whitespace following a trailing ';' will be nuked as well */
2585 if (hf->value[len - 1] == '\n') {
2586 while (isspace((unsigned char)(hf->value[len - 2]))) {
2587 if (len-- == 0) { break; }
2588 }
2589 }
2590
2591 if (hf->value[len - 2] == ';') {
2592 /* Remove trailing ';' from parameter value. */
2593 hf->value[len - 2] = '\n';
2594 hf->value[len - 1] = '\0';
2595
2596 /* Also, if Content-Type parameter, remove trailing ';'
2597 from ct->c_ctline. This probably isn't necessary
2598 but can't hurt. */
2599 if (strcasecmp(hf->name, TYPE_FIELD) == 0 && ct->c_ctline) {
2600 size_t l = strlen(ct->c_ctline) - 1;
2601 while (isspace((unsigned char)(ct->c_ctline[l])) ||
2602 ct->c_ctline[l] == ';') {
2603 ct->c_ctline[l--] = '\0';
2604 if (l == 0) { break; }
2605 }
2606 }
2607
2608 ++*message_mods;
2609 if (verbosw) {
2610 report (NULL, ct->c_partno, ct->c_file,
2611 "remove trailing ; from %s parameter value",
2612 hf->name);
2613 }
2614 }
2615 }
2616 }}
2617
2618 return status;
2619 }
2620
2621
2622 /*
2623 * Factor out common code for loops in fix_filename_encoding().
2624 */
2625 static int
2626 fix_filename_param (char *name, char *value, PM *first_pm, PM *last_pm)
2627 {
2628 bool fixed = false;
2629
2630 if (has_prefix(value, "=?") && has_suffix(value, "?=")) {
2631 /* Looks like an RFC 2047 encoded parameter. */
2632 char decoded[PATH_MAX + 1];
2633
2634 if (decode_rfc2047 (value, decoded, sizeof decoded)) {
2635 /* Encode using RFC 2231. */
2636 replace_param (first_pm, last_pm, name, decoded, 0);
2637 fixed = true;
2638 } else {
2639 inform("failed to decode %s parameter %s", name, value);
2640 }
2641 }
2642
2643 return fixed;
2644 }
2645
2646
2647 /*
2648 * Replace RFC 2047 encoding with RFC 2231 encoding of name and
2649 * filename parameters in Content-Type and Content-Disposition
2650 * headers, respectively.
2651 */
2652 static int
2653 fix_filename_encoding (CT ct)
2654 {
2655 PM pm;
2656 HF hf;
2657 int fixed = 0;
2658
2659 for (pm = ct->c_ctinfo.ci_first_pm; pm; pm = pm->pm_next) {
2660 if (pm->pm_name && pm->pm_value &&
2661 strcasecmp (pm->pm_name, "name") == 0) {
2662 fixed = fix_filename_param (pm->pm_name, pm->pm_value,
2663 &ct->c_ctinfo.ci_first_pm,
2664 &ct->c_ctinfo.ci_last_pm);
2665 }
2666 }
2667
2668 for (pm = ct->c_dispo_first; pm; pm = pm->pm_next) {
2669 if (pm->pm_name && pm->pm_value &&
2670 strcasecmp (pm->pm_name, "filename") == 0) {
2671 fixed = fix_filename_param (pm->pm_name, pm->pm_value,
2672 &ct->c_dispo_first,
2673 &ct->c_dispo_last);
2674 }
2675 }
2676
2677 /* Fix hf values to correspond. */
2678 for (hf = ct->c_first_hf; fixed && hf; hf = hf->next) {
2679 enum { OTHER, TYPE_HEADER, DISPO_HEADER } field = OTHER;
2680
2681 if (strcasecmp (hf->name, TYPE_FIELD) == 0) {
2682 field = TYPE_HEADER;
2683 } else if (strcasecmp (hf->name, DISPO_FIELD) == 0) {
2684 field = DISPO_HEADER;
2685 }
2686
2687 if (field != OTHER) {
2688 const char *const semicolon_loc = strchr (hf->value, ';');
2689
2690 if (semicolon_loc) {
2691 const size_t len =
2692 strlen (hf->name) + 1 + semicolon_loc - hf->value;
2693 const char *const params =
2694 output_params (len,
2695 field == TYPE_HEADER
2696 ? ct->c_ctinfo.ci_first_pm
2697 : ct->c_dispo_first,
2698 NULL, 0);
2699 const char *const new_params = concat (params, "\n", NULL);
2700
2701 replace_substring (&hf->value, semicolon_loc, new_params);
2702 free((void *)new_params); /* Cast away const. Sigh. */
2703 free((void *)params);
2704 } else {
2705 inform("did not find semicolon in %s:%s\n",
2706 hf->name, hf->value);
2707 }
2708 }
2709 }
2710
2711 return OK;
2712 }
2713
2714
2715 /*
2716 * Output content in input file to output file.
2717 */
2718 static int
2719 write_content (CT ct, const char *input_filename, char *outfile, FILE *outfp,
2720 int modify_inplace, int message_mods)
2721 {
2722 int status = OK;
2723
2724 if (modify_inplace) {
2725 if (message_mods > 0) {
2726 if ((status = output_message_fp (ct, outfp, outfile)) == OK) {
2727 char *infile = input_filename
2728 ? mh_xstrdup (input_filename)
2729 : mh_xstrdup (ct->c_file ? ct->c_file : "-");
2730
2731 if (remove_file (infile) == OK) {
2732 if (rename (outfile, infile)) {
2733 /* Rename didn't work, possibly because of an
2734 attempt to rename across filesystems. Try
2735 brute force copy. */
2736 int old = open (outfile, O_RDONLY);
2737 int new =
2738 open (infile, O_WRONLY | O_CREAT, m_gmprot ());
2739 int i = -1;
2740
2741 if (old != -1 && new != -1) {
2742 char buffer[NMH_BUFSIZ];
2743
2744 while ((i = read (old, buffer, sizeof buffer)) >
2745 0) {
2746 if (write (new, buffer, i) != i) {
2747 i = -1;
2748 break;
2749 }
2750 }
2751 }
2752 if (new != -1) { close (new); }
2753 if (old != -1) { close (old); }
2754 (void) m_unlink (outfile);
2755
2756 if (i < 0) {
2757 /* The -file argument processing used path() to
2758 expand filename to absolute path. */
2759 int file = ct->c_file && ct->c_file[0] == '/';
2760
2761 inform("unable to rename %s %s to %s, continuing...",
2762 file ? "file" : "message", outfile,
2763 infile);
2764 status = NOTOK;
2765 }
2766 }
2767 } else {
2768 inform("unable to remove input file %s, "
2769 "not modifying it, continuing...", infile);
2770 (void) m_unlink (outfile);
2771 status = NOTOK;
2772 }
2773
2774 free (infile);
2775 } else {
2776 status = NOTOK;
2777 }
2778 } else {
2779 /* No modifications and didn't need the tmp outfile. */
2780 (void) m_unlink (outfile);
2781 }
2782 } else {
2783 /* Output is going to some file. Produce it whether or not
2784 there were modifications. */
2785 status = output_message_fp (ct, outfp, outfile);
2786 }
2787
2788 flush_errors ();
2789 return status;
2790 }
2791
2792
2793 /*
2794 * parse_mime() does not set lf_line_endings in struct text, so use this
2795 * function to do it. It touches the parts the decodetypes identifies.
2796 */
2797 static void
2798 set_text_ctparams(CT ct, char *decodetypes, int lf_line_endings)
2799 {
2800 switch (ct->c_type) {
2801 case CT_MULTIPART: {
2802 struct multipart *m = (struct multipart *) ct->c_ctparams;
2803 struct part *part;
2804
2805 for (part = m->mp_parts; part; part = part->mp_next) {
2806 set_text_ctparams(part->mp_part, decodetypes, lf_line_endings);
2807 }
2808 break;
2809 }
2810
2811 case CT_MESSAGE:
2812 if (ct->c_subtype == MESSAGE_EXTERNAL) {
2813 struct exbody *e = (struct exbody *) ct->c_ctparams;
2814
2815 set_text_ctparams(e->eb_content, decodetypes, lf_line_endings);
2816 }
2817 break;
2818
2819 default:
2820 if (should_decode(decodetypes, ct->c_ctinfo.ci_type, ct->c_ctinfo.ci_subtype)) {
2821 if (ct->c_ctparams == NULL) {
2822 ct->c_ctparams = mh_xcalloc(1, sizeof (struct text));
2823 }
2824 ((struct text *) ct->c_ctparams)->lf_line_endings = lf_line_endings;
2825 }
2826 }
2827 }
2828
2829
2830 /*
2831 * If "rmmproc" is defined, call that to remove the file. Otherwise,
2832 * use the standard MH backup file.
2833 */
2834 static int
2835 remove_file (const char *file)
2836 {
2837 if (rmmproc) {
2838 char *rmm_command = concat (rmmproc, " ", file, NULL);
2839 int status = system (rmm_command);
2840
2841 free (rmm_command);
2842 return WIFEXITED (status) ? WEXITSTATUS (status) : NOTOK;
2843 }
2844 /* This is OK for a non-message file, it still uses the
2845 BACKUP_PREFIX form. The backup file will be in the same
2846 directory as file. */
2847 return rename (file, m_backup (file));
2848 }
2849
2850
2851 /*
2852 * Output formatted message to user.
2853 */
2854 static void
2855 report (char *what, char *partno, char *filename, char *message, ...)
2856 {
2857 va_list args;
2858 char *fmt;
2859
2860 if (verbosw) {
2861 va_start (args, message);
2862 fmt = concat (filename, partno ? " part " : ", ",
2863 FENDNULL(partno), partno ? ", " : "", message, NULL);
2864
2865 advertise (what, NULL, fmt, args);
2866
2867 free (fmt);
2868 va_end (args);
2869 }
2870 }
2871
2872
2873 static void
2874 pipeser (int i)
2875 {
2876 if (i == SIGQUIT) {
2877 fflush (stdout);
2878 fprintf (stderr, "\n");
2879 fflush (stderr);
2880 }
2881
2882 done (1);
2883 /* NOTREACHED */
2884 }