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