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