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