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