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