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