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