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