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