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