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