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