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