]> diplodocus.org Git - nmh/blob - uip/mhfixmsg.c
c237ea872057f5c31769be51eee77e46f6341e76
[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 void freects_done (int) NORETURN;
75
76 /*
77 * static prototypes
78 */
79 typedef struct fix_transformations {
80 int fixboundary;
81 int fixcompositecte;
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_composite_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 CT build_multipart_alt (CT, CT, int, int);
112 static int boundary_in_content (FILE **, char *, const char *);
113 static void transfer_noncontent_headers (CT, CT);
114 static int set_ct_type (CT, int type, int subtype, int encoding);
115 static int decode_text_parts (CT, int, const char *, int *);
116 static int should_decode(const char *, const char *, const char *);
117 static int content_encoding (CT, const char **);
118 static int strip_crs (CT, int *);
119 static int convert_charsets (CT, char *, int *);
120 static int fix_always (CT, int *);
121 static int fix_filename_param (char *, char *, PM *, PM *);
122 static int fix_filename_encoding (CT);
123 static int write_content (CT, const char *, char *, int, int);
124 static void set_text_ctparams(CT, char *, int);
125 static int remove_file (const char *);
126 static void report (char *, char *, char *, char *, ...);
127 static void pipeser (int);
128
129
130 int
131 main (int argc, char **argv) {
132 int msgnum;
133 char *cp, *file = NULL, *folder = NULL;
134 char *maildir, buf[100], *outfile = NULL;
135 char **argp, **arguments;
136 struct msgs_array msgs = { 0, 0, NULL };
137 struct msgs *mp = NULL;
138 CT *ctp;
139 FILE *fp;
140 int using_stdin = 0;
141 int chgflag = 1;
142 int status = OK;
143 fix_transformations fx;
144 fx.reformat = fx.fixcompositecte = fx.fixboundary = 1;
145 fx.fixtypes = NULL;
146 fx.replacetextplain = 0;
147 fx.decodetext = CE_8BIT;
148 fx.decodetypes = "text,application/ics"; /* Default, per man page. */
149 fx.lf_line_endings = 0;
150 fx.textcharset = NULL;
151
152 if (nmh_init(argv[0], 1)) { return 1; }
153
154 done = freects_done;
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 if (! (cts = (CT *) mh_xcalloc ((size_t) 2, sizeof *cts))) {
359 adios (NULL, "out of memory");
360 }
361 ctp = cts;
362
363 if ((ct = parse_mime (file))) {
364 set_text_ctparams(ct, fx.decodetypes, fx.lf_line_endings);
365 *ctp++ = ct;
366 } else {
367 advise (NULL, "unable to parse message from file %s", file);
368 status = NOTOK;
369
370 /* If there's an outfile, pass the input message unchanged, so the message won't
371 get dropped from a pipeline. */
372 if (outfile) {
373 /* Something went wrong. Output might be expected, such as if this were run
374 as a filter. Just copy the input to the output. */
375 if (copy_input_to_output (file, outfile) != OK) {
376 advise (NULL, "unable to copy message to %s, it might be lost\n", outfile);
377 }
378 }
379 }
380 } else {
381 /*
382 * message(s) are coming from a folder
383 */
384 CT ct;
385
386 if (! msgs.size) {
387 app_msgarg(&msgs, "cur");
388 }
389 if (! folder) {
390 folder = getfolder (1);
391 }
392 maildir = m_maildir (folder);
393
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 if (! (cts =
416 (CT *) mh_xcalloc ((size_t) (mp->numsel + 1), sizeof *cts))) {
417 adios (NULL, "out of memory");
418 }
419 ctp = cts;
420
421 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
422 if (is_selected(mp, msgnum)) {
423 char *msgnam;
424
425 msgnam = m_name (msgnum);
426 if ((ct = parse_mime (msgnam))) {
427 set_text_ctparams(ct, fx.decodetypes, fx.lf_line_endings);
428 *ctp++ = ct;
429 } else {
430 advise (NULL, "unable to parse message %s", msgnam);
431 status = NOTOK;
432
433 /* If there's an outfile, pass the input message unchanged, so the message won't
434 get dropped from a pipeline. */
435 if (outfile) {
436 /* Something went wrong. Output might be expected, such as if this were run
437 as a filter. Just copy the input to the output. */
438 const char *input_filename = path (msgnam, TFILE);
439
440 if (copy_input_to_output (input_filename, outfile) != OK) {
441 advise (NULL, "unable to copy message to %s, it might be lost\n", outfile);
442 }
443 }
444 }
445 }
446 }
447
448 if (chgflag) {
449 seq_setcur (mp, mp->hghsel); /* update current message */
450 }
451 seq_save (mp); /* synchronize sequences */
452 context_replace (pfolder, folder);/* update current folder */
453 context_save (); /* save the context file */
454 }
455
456 if (*cts) {
457 for (ctp = cts; *ctp; ++ctp) {
458 status += mhfixmsgsbr (ctp, &fx, outfile);
459
460 if (using_stdin) {
461 (void) m_unlink (file);
462
463 if (! outfile) {
464 /* Just calling m_backup() unlinks the backup file. */
465 (void) m_backup (file);
466 }
467 }
468 }
469 } else {
470 status = 1;
471 }
472
473 if (fx.fixtypes != NULL) { svector_free (fx.fixtypes); }
474 free (outfile);
475 free (file);
476 free (folder);
477 free (arguments);
478
479 /* done is freects_done, which will clean up all of cts. */
480 done (status);
481 return NOTOK;
482 }
483
484
485 /*
486 * Apply transformations to one message.
487 */
488 int
489 mhfixmsgsbr (CT *ctp, const fix_transformations *fx, char *outfile) {
490 /* Store input filename in case one of the transformations, i.e.,
491 fix_boundary(), rewrites to a tmp file. */
492 char *input_filename = add ((*ctp)->c_file, NULL);
493 int modify_inplace = 0;
494 int message_mods = 0;
495 int status = OK;
496
497 if (outfile == NULL) {
498 modify_inplace = 1;
499
500 if ((*ctp)->c_file) {
501 char *tempfile;
502 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, NULL)) == NULL) {
503 adios (NULL, "unable to create temporary file in %s",
504 get_temp_dir());
505 }
506 outfile = add (tempfile, NULL);
507 } else {
508 adios (NULL, "missing both input and output filenames\n");
509 }
510 }
511
512 reverse_alternative_parts (*ctp);
513 status = fix_always (*ctp, &message_mods);
514 if (status == OK && fx->fixboundary) {
515 status = fix_boundary (ctp, &message_mods);
516 }
517 if (status == OK && fx->fixtypes != NULL) {
518 status = fix_types (*ctp, fx->fixtypes, &message_mods);
519 }
520 if (status == OK && fx->fixcompositecte) {
521 status = fix_composite_cte (*ctp, &message_mods);
522 }
523 if (status == OK && fx->reformat) {
524 status =
525 ensure_text_plain (ctp, NULL, &message_mods, fx->replacetextplain);
526 }
527 if (status == OK && fx->decodetext) {
528 status = decode_text_parts (*ctp, fx->decodetext, fx->decodetypes,
529 &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 of composite,, e.g., message or multipart, part.
1061 * According to RFC 2045 Sec. 6.4, it must be 7bit, 8bit, or binary. Set it to
1062 * 8 bit.
1063 */
1064 static int
1065 fix_composite_cte (CT ct, int *message_mods) {
1066 int status = OK;
1067
1068 if (ct->c_type == CT_MESSAGE || ct->c_type == CT_MULTIPART) {
1069 if (ct->c_encoding != CE_7BIT && ct->c_encoding != CE_8BIT &&
1070 ct->c_encoding != CE_BINARY) {
1071 HF hf;
1072
1073 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1074 char *name = hf->name;
1075 for (; *name && isspace ((unsigned char) *name); ++name) {
1076 continue;
1077 }
1078
1079 if (! strncasecmp (name, ENCODING_FIELD,
1080 strlen (ENCODING_FIELD))) {
1081 char *prefix = "Nmh-REPLACED-INVALID-";
1082 HF h = mh_xmalloc (sizeof *h);
1083
1084 h->name = add (hf->name, NULL);
1085 h->hf_encoding = hf->hf_encoding;
1086 h->next = hf->next;
1087 hf->next = h;
1088
1089 /* Retain old header but prefix its name. */
1090 free (hf->name);
1091 hf->name = concat (prefix, h->name, NULL);
1092
1093 ++*message_mods;
1094 if (verbosw) {
1095 char *encoding = cpytrim (hf->value);
1096 report (NULL, ct->c_partno, ct->c_file,
1097 "replace Content-Transfer-Encoding of %s "
1098 "with 8 bit", encoding);
1099 free (encoding);
1100 }
1101
1102 h->value = add (" 8bit\n", NULL);
1103
1104 /* Don't need to warn for multiple C-T-E header
1105 fields, parse_mime() already does that. But
1106 if there are any, fix them all as necessary. */
1107 hf = h;
1108 }
1109 }
1110
1111 set_ce (ct, CE_8BIT);
1112 }
1113
1114 if (ct->c_type == CT_MULTIPART) {
1115 struct multipart *m;
1116 struct part *part;
1117
1118 m = (struct multipart *) ct->c_ctparams;
1119 for (part = m->mp_parts; part; part = part->mp_next) {
1120 if (fix_composite_cte (part->mp_part, message_mods) != OK) {
1121 status = NOTOK;
1122 break;
1123 }
1124 }
1125 }
1126 }
1127
1128 return status;
1129 }
1130
1131
1132 /*
1133 * Set content encoding.
1134 */
1135 static int
1136 set_ce (CT ct, int encoding) {
1137 const char *ce = ce_str (encoding);
1138 const struct str2init *ctinit = get_ce_method (ce);
1139
1140 if (ctinit) {
1141 char *cte = concat (" ", ce, "\n", NULL);
1142 int found_cte = 0;
1143 HF hf;
1144 /* Decoded contents might be in ct->c_cefile.ce_file, if the
1145 caller is decode_text_parts (). Save because we'll
1146 overwrite below. */
1147 struct cefile decoded_content_info = ct->c_cefile;
1148
1149 ct->c_encoding = encoding;
1150
1151 ct->c_ctinitfnx = ctinit->si_init;
1152 /* This will assign ct->c_cefile with an all-0 struct, which
1153 is what we want. */
1154 (*ctinit->si_init) (ct);
1155 /* After returning, the caller should set
1156 ct->c_cefile.ce_file to the name of the file containing
1157 the contents. */
1158
1159 /* Restore the cefile. */
1160 ct->c_cefile = decoded_content_info;
1161
1162 /* Update/add Content-Transfer-Encoding header field. */
1163 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1164 if (! strcasecmp (ENCODING_FIELD, hf->name)) {
1165 found_cte = 1;
1166 free (hf->value);
1167 hf->value = cte;
1168 }
1169 }
1170 if (! found_cte) {
1171 add_header (ct, add (ENCODING_FIELD, NULL), cte);
1172 }
1173
1174 /* Update c_celine. It's used only by mhlist -debug. */
1175 free (ct->c_celine);
1176 ct->c_celine = add (cte, NULL);
1177
1178 return OK;
1179 } else {
1180 return NOTOK;
1181 }
1182 }
1183
1184
1185 /*
1186 * Make sure each text part has a corresponding text/plain part.
1187 */
1188 static int
1189 ensure_text_plain (CT *ct, CT parent, int *message_mods, int replacetextplain) {
1190 int status = OK;
1191
1192 switch ((*ct)->c_type) {
1193 case CT_TEXT: {
1194 /* Nothing to do for text/plain. */
1195 if ((*ct)->c_subtype == TEXT_PLAIN) { return OK; }
1196
1197 if (parent && parent->c_type == CT_MULTIPART &&
1198 parent->c_subtype == MULTI_ALTERNATE) {
1199 int new_subpart_number = 1;
1200 int has_text_plain =
1201 find_textplain_sibling (parent, replacetextplain,
1202 &new_subpart_number);
1203
1204 if (! has_text_plain) {
1205 /* Parent is a multipart/alternative. Insert a new
1206 text/plain subpart. */
1207 const int inserted =
1208 insert_new_text_plain_part (*ct, new_subpart_number,
1209 parent);
1210 if (inserted) {
1211 ++*message_mods;
1212 if (verbosw) {
1213 report (NULL, parent->c_partno, parent->c_file,
1214 "insert text/plain part");
1215 }
1216 } else {
1217 status = NOTOK;
1218 }
1219 }
1220 } else if (parent && parent->c_type == CT_MULTIPART &&
1221 parent->c_subtype == MULTI_RELATED) {
1222 char *type_subtype =
1223 concat ((*ct)->c_ctinfo.ci_type, "/",
1224 (*ct)->c_ctinfo.ci_subtype, NULL);
1225 const char *parent_type =
1226 get_param (parent->c_ctinfo.ci_first_pm, "type", '?', 1);
1227 int new_subpart_number = 1;
1228 int has_text_plain = 0;
1229
1230 /* Have to do string comparison on the subtype because we
1231 don't enumerate all of them in c_subtype values.
1232 parent_type will be NULL if the multipart/related part
1233 doesn't have a type parameter. The type parameter must
1234 be specified according to RFC 2387 Sec. 3.1 but not all
1235 messages comply. */
1236 if (parent_type && strcasecmp (type_subtype, parent_type) == 0) {
1237 /* The type of this part matches the root type of the
1238 parent multipart/related. Look to see if there's
1239 text/plain sibling. */
1240 has_text_plain =
1241 find_textplain_sibling (parent, replacetextplain,
1242 &new_subpart_number);
1243 }
1244
1245 free (type_subtype);
1246
1247 if (! has_text_plain) {
1248 struct multipart *mp = (struct multipart *) parent->c_ctparams;
1249 struct part *part;
1250 int siblings = 0;
1251
1252 for (part = mp->mp_parts; part; part = part->mp_next) {
1253 if (*ct != part->mp_part) {
1254 ++siblings;
1255 }
1256 }
1257
1258 if (siblings) {
1259 /* Parent is a multipart/related. Insert a new
1260 text/plain subpart in a new multipart/alternative. */
1261 if (insert_into_new_mp_alt (ct, message_mods)) {
1262 /* Not an error if text/plain couldn't be added. */
1263 }
1264 } else {
1265 /* There are no siblings, so insert a new text/plain
1266 subpart, and change the parent type from
1267 multipart/related to multipart/alternative. */
1268 const int inserted =
1269 insert_new_text_plain_part (*ct, new_subpart_number,
1270 parent);
1271
1272 if (inserted) {
1273 HF hf;
1274
1275 parent->c_subtype = MULTI_ALTERNATE;
1276 parent->c_ctinfo.ci_subtype = getcpy ("alternative");
1277 if (! replace_substring (&parent->c_ctline, "/related",
1278 "/alternative")) {
1279 advise (NULL,
1280 "did not find multipart/related in %s",
1281 parent->c_ctline);
1282 }
1283
1284 /* Update Content-Type header field. */
1285 for (hf = parent->c_first_hf; hf; hf = hf->next) {
1286 if (! strcasecmp (TYPE_FIELD, hf->name)) {
1287 if (replace_substring (&hf->value, "/related",
1288 "/alternative")) {
1289 ++*message_mods;
1290 if (verbosw) {
1291 report (NULL, parent->c_partno,
1292 parent->c_file,
1293 "insert text/plain part");
1294 }
1295
1296 /* Remove, e.g., type="text/html" from
1297 multipart/alternative. */
1298 remove_parameter (hf->value, "type");
1299 break;
1300 } else {
1301 advise (NULL, "did not find multipart/"
1302 "related in header %s",
1303 hf->value);
1304 }
1305 }
1306 }
1307 } else {
1308 /* Not an error if text/plain couldn't be inserted. */
1309 }
1310 }
1311 }
1312 } else {
1313 if (insert_into_new_mp_alt (ct, message_mods)) {
1314 status = NOTOK;
1315 }
1316 }
1317 break;
1318 }
1319
1320 case CT_MULTIPART: {
1321 struct multipart *mp = (struct multipart *) (*ct)->c_ctparams;
1322 struct part *part;
1323
1324 for (part = mp->mp_parts; status == OK && part; part = part->mp_next) {
1325 if ((*ct)->c_type == CT_MULTIPART) {
1326 status = ensure_text_plain (&part->mp_part, *ct, message_mods,
1327 replacetextplain);
1328 }
1329 }
1330 break;
1331 }
1332
1333 case CT_MESSAGE:
1334 if ((*ct)->c_subtype == MESSAGE_EXTERNAL) {
1335 struct exbody *e = (struct exbody *) (*ct)->c_ctparams;
1336
1337 status = ensure_text_plain (&e->eb_content, *ct, message_mods,
1338 replacetextplain);
1339 }
1340 break;
1341 }
1342
1343 return status;
1344 }
1345
1346
1347 /*
1348 * See if there is a sibling text/plain, and return its subpart number.
1349 */
1350 static int
1351 find_textplain_sibling (CT parent, int replacetextplain,
1352 int *new_subpart_number) {
1353 struct multipart *mp = (struct multipart *) parent->c_ctparams;
1354 struct part *part, *prev;
1355 int has_text_plain = 0;
1356
1357 for (prev = part = mp->mp_parts; part; part = part->mp_next) {
1358 ++*new_subpart_number;
1359 if (part->mp_part->c_type == CT_TEXT &&
1360 part->mp_part->c_subtype == TEXT_PLAIN) {
1361 if (replacetextplain) {
1362 struct part *old_part;
1363 if (part == mp->mp_parts) {
1364 old_part = mp->mp_parts;
1365 mp->mp_parts = part->mp_next;
1366 } else {
1367 old_part = prev->mp_next;
1368 prev->mp_next = part->mp_next;
1369 }
1370 if (verbosw) {
1371 report (NULL, parent->c_partno, parent->c_file,
1372 "remove text/plain part %s",
1373 old_part->mp_part->c_partno);
1374 }
1375 free_content (old_part->mp_part);
1376 free (old_part);
1377 } else {
1378 has_text_plain = 1;
1379 }
1380 break;
1381 }
1382 prev = part;
1383 }
1384
1385 return has_text_plain;
1386 }
1387
1388
1389 /*
1390 * Insert a new text/plain part.
1391 */
1392 static int
1393 insert_new_text_plain_part (CT ct, int new_subpart_number, CT parent) {
1394 struct multipart *mp = (struct multipart *) parent->c_ctparams;
1395 struct part *new_part = mh_xmalloc (sizeof *new_part);
1396
1397 if ((new_part->mp_part = build_text_plain_part (ct))) {
1398 char buffer[16];
1399 snprintf (buffer, sizeof buffer, "%d", new_subpart_number);
1400
1401 new_part->mp_next = mp->mp_parts;
1402 mp->mp_parts = new_part;
1403 new_part->mp_part->c_partno =
1404 concat (parent->c_partno ? parent->c_partno : "1", ".",
1405 buffer, NULL);
1406
1407 return 1;
1408 } else {
1409 free_content (new_part->mp_part);
1410 free (new_part);
1411
1412 return 0;
1413 }
1414 }
1415
1416
1417 /*
1418 * Create a text/plain part to go along with non-plain sibling part.
1419 */
1420 static CT
1421 build_text_plain_part (CT encoded_part) {
1422 CT tp_part = divide_part (encoded_part);
1423 char *tmp_plain_file = NULL;
1424
1425 if (decode_part (tp_part) == OK) {
1426 /* Now, tp_part->c_cefile.ce_file is the name of the tmp file that
1427 contains the decoded contents. And the decoding function, such
1428 as openQuoted, will have set ...->ce_unlink to 1 so that it will
1429 be unlinked by free_content (). */
1430 char *tempfile;
1431
1432 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, NULL)) == NULL) {
1433 advise (NULL, "unable to create temporary file in %s",
1434 get_temp_dir());
1435 } else {
1436 tmp_plain_file = add (tempfile, NULL);
1437 if (reformat_part (tp_part, tmp_plain_file,
1438 tp_part->c_ctinfo.ci_type,
1439 tp_part->c_ctinfo.ci_subtype,
1440 tp_part->c_type) == OK) {
1441 return tp_part;
1442 }
1443 }
1444 }
1445
1446 free_content (tp_part);
1447 if (tmp_plain_file) { (void) m_unlink (tmp_plain_file); }
1448 free (tmp_plain_file);
1449
1450 return NULL;
1451 }
1452
1453
1454 /*
1455 * Slip new text/plain part into a new multipart/alternative.
1456 */
1457 static int
1458 insert_into_new_mp_alt (CT *ct, int *message_mods) {
1459 CT tp_part = build_text_plain_part (*ct);
1460 int status = OK;
1461
1462 if (tp_part) {
1463 CT mp_alt = build_multipart_alt (*ct, tp_part, CT_MULTIPART,
1464 MULTI_ALTERNATE);
1465 if (mp_alt) {
1466 struct multipart *mp = (struct multipart *) mp_alt->c_ctparams;
1467
1468 if (mp && mp->mp_parts) {
1469 mp->mp_parts->mp_part = tp_part;
1470 /* Make the new multipart/alternative the parent. */
1471 *ct = mp_alt;
1472
1473 ++*message_mods;
1474 if (verbosw) {
1475 report (NULL, (*ct)->c_partno, (*ct)->c_file,
1476 "insert text/plain part");
1477 }
1478 } else {
1479 free_content (tp_part);
1480 free_content (mp_alt);
1481 status = NOTOK;
1482 }
1483 } else {
1484 status = NOTOK;
1485 }
1486 } else {
1487 /* Not an error if text/plain couldn't be built. */
1488 }
1489
1490 return status;
1491 }
1492
1493
1494 /*
1495 * Clone a MIME part.
1496 */
1497 static CT
1498 divide_part (CT ct) {
1499 CT new_part;
1500
1501 if ((new_part = (CT) mh_xcalloc (1, sizeof *new_part)) == NULL)
1502 adios (NULL, "out of memory");
1503
1504 /* Just copy over what is needed for decoding. c_vrsn and
1505 c_celine aren't necessary. */
1506 new_part->c_file = add (ct->c_file, NULL);
1507 new_part->c_begin = ct->c_begin;
1508 new_part->c_end = ct->c_end;
1509 copy_ctinfo (&new_part->c_ctinfo, &ct->c_ctinfo);
1510 new_part->c_type = ct->c_type;
1511 new_part->c_cefile = ct->c_cefile;
1512 new_part->c_encoding = ct->c_encoding;
1513 new_part->c_ctinitfnx = ct->c_ctinitfnx;
1514 new_part->c_ceopenfnx = ct->c_ceopenfnx;
1515 new_part->c_ceclosefnx = ct->c_ceclosefnx;
1516 new_part->c_cesizefnx = ct->c_cesizefnx;
1517
1518 /* c_ctline is used by reformat__part(), so it can preserve
1519 anything after the type/subtype. */
1520 new_part->c_ctline = add (ct->c_ctline, NULL);
1521
1522 return new_part;
1523 }
1524
1525
1526 /*
1527 * Copy the content info from one part to another.
1528 */
1529 static void
1530 copy_ctinfo (CI dest, CI src) {
1531 PM s_pm, d_pm;
1532
1533 dest->ci_type = src->ci_type ? add (src->ci_type, NULL) : NULL;
1534 dest->ci_subtype = src->ci_subtype ? add (src->ci_subtype, NULL) : NULL;
1535
1536 for (s_pm = src->ci_first_pm; s_pm; s_pm = s_pm->pm_next) {
1537 d_pm = add_param(&dest->ci_first_pm, &dest->ci_last_pm, s_pm->pm_name,
1538 s_pm->pm_value, 0);
1539 if (s_pm->pm_charset) {
1540 d_pm->pm_charset = getcpy(s_pm->pm_charset);
1541 }
1542 if (s_pm->pm_lang) {
1543 d_pm->pm_lang = getcpy(s_pm->pm_lang);
1544 }
1545 }
1546
1547 dest->ci_comment = src->ci_comment ? add (src->ci_comment, NULL) : NULL;
1548 dest->ci_magic = src->ci_magic ? add (src->ci_magic, NULL) : NULL;
1549 }
1550
1551
1552 /*
1553 * Decode content.
1554 */
1555 static int
1556 decode_part (CT ct) {
1557 char *tmp_decoded;
1558 int status;
1559 char *tempfile;
1560
1561 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, NULL)) == NULL) {
1562 adios (NULL, "unable to create temporary file in %s", get_temp_dir());
1563 }
1564 tmp_decoded = add (tempfile, NULL);
1565 /* The following call will load ct->c_cefile.ce_file with the tmp
1566 filename of the decoded content. tmp_decoded will contain the
1567 encoded output, get rid of that. */
1568 status = output_message (ct, tmp_decoded);
1569 (void) m_unlink (tmp_decoded);
1570 free (tmp_decoded);
1571
1572 return status;
1573 }
1574
1575
1576 /*
1577 * Reformat content as plain text.
1578 * Some of the arguments aren't really needed now, but maybe will
1579 * be in the future for other than text types.
1580 */
1581 static int
1582 reformat_part (CT ct, char *file, char *type, char *subtype, int c_type) {
1583 int output_subtype, output_encoding;
1584 const char *reason = NULL;
1585 char *cp, *cf;
1586 int status;
1587
1588 /* Hacky: this redirects the output from whatever command is used
1589 to show the part to a file. So, the user can't have any output
1590 redirection in that command.
1591 Could show_multi() in mhshowsbr.c avoid this? */
1592
1593 /* Check for invo_name-format-type/subtype. */
1594 if ((cf = context_find_by_type ("format", type, subtype)) == NULL) {
1595 if (verbosw) {
1596 advise (NULL, "Don't know how to convert %s, there is no "
1597 "%s-format-%s/%s profile entry",
1598 ct->c_file, invo_name, type, subtype);
1599 }
1600 return NOTOK;
1601 } else {
1602 if (strchr (cf, '>')) {
1603 advise (NULL, "'>' prohibited in \"%s\",\nplease fix your "
1604 "%s-format-%s/%s profile entry", cf, invo_name, type,
1605 subtype ? subtype : "");
1606
1607 return NOTOK;
1608 }
1609 }
1610
1611 cp = concat (cf, " >", file, NULL);
1612 status = show_content_aux (ct, 0, cp, NULL, NULL);
1613 free (cp);
1614
1615 /* Unlink decoded content tmp file and free its filename to avoid
1616 leaks. The file stream should already have been closed. */
1617 if (ct->c_cefile.ce_unlink) {
1618 (void) m_unlink (ct->c_cefile.ce_file);
1619 free (ct->c_cefile.ce_file);
1620 ct->c_cefile.ce_file = NULL;
1621 ct->c_cefile.ce_unlink = 0;
1622 }
1623
1624 if (c_type == CT_TEXT) {
1625 output_subtype = TEXT_PLAIN;
1626 } else {
1627 /* Set subtype to 0, which is always an UNKNOWN subtype. */
1628 output_subtype = 0;
1629 }
1630
1631 output_encoding = content_encoding (ct, &reason);
1632 if (set_ct_type (ct, c_type, output_subtype, output_encoding) == OK) {
1633 ct->c_cefile.ce_file = file;
1634 ct->c_cefile.ce_unlink = 1;
1635 } else {
1636 ct->c_cefile.ce_unlink = 0;
1637 status = NOTOK;
1638 }
1639
1640 return status;
1641 }
1642
1643
1644 /*
1645 * Fill in a multipart/alternative part.
1646 */
1647 static CT
1648 build_multipart_alt (CT first_alt, CT new_part, int type, int subtype) {
1649 char *boundary_prefix = "----=_nmh-multipart";
1650 char *boundary = concat (boundary_prefix, first_alt->c_partno, NULL);
1651 char *boundary_indicator = "; boundary=";
1652 char *typename, *subtypename, *name;
1653 CT ct;
1654 struct part *p;
1655 struct multipart *m;
1656 const struct str2init *ctinit;
1657
1658 if ((ct = (CT) mh_xcalloc (1, sizeof *ct)) == NULL)
1659 adios (NULL, "out of memory");
1660
1661 /* Set up the multipart/alternative part. These fields of *ct were
1662 initialized to 0 by mh_xcalloc():
1663 c_fp, c_unlink, c_begin, c_end,
1664 c_vrsn, c_ctline, c_celine,
1665 c_id, c_descr, c_dispo, c_partno,
1666 c_ctinfo.ci_comment, c_ctinfo.ci_magic,
1667 c_cefile, c_encoding,
1668 c_digested, c_digest[16], c_ctexbody,
1669 c_ctinitfnx, c_ceopenfnx, c_ceclosefnx, c_cesizefnx,
1670 c_umask, c_rfc934,
1671 c_showproc, c_termproc, c_storeproc, c_storage, c_folder
1672 */
1673
1674 ct->c_file = add (first_alt->c_file, NULL);
1675 ct->c_type = type;
1676 ct->c_subtype = subtype;
1677
1678 ctinit = get_ct_init (ct->c_type);
1679
1680 typename = ct_type_str (type);
1681 subtypename = ct_subtype_str (type, subtype);
1682
1683 {
1684 int serial = 0;
1685 int found_boundary = 1;
1686
1687 while (found_boundary && serial < 1000000) {
1688 found_boundary = 0;
1689
1690 /* Ensure that the boundary doesn't appear in the decoded
1691 content. */
1692 if (new_part->c_cefile.ce_file) {
1693 if ((found_boundary =
1694 boundary_in_content (&new_part->c_cefile.ce_fp,
1695 new_part->c_cefile.ce_file,
1696 boundary)) == -1) {
1697 free (ct);
1698 return NULL;
1699 }
1700 }
1701
1702 /* Ensure that the boundary doesn't appear in the encoded
1703 content. */
1704 if (! found_boundary && new_part->c_file) {
1705 if ((found_boundary = boundary_in_content (&new_part->c_fp,
1706 new_part->c_file,
1707 boundary)) == -1) {
1708 free (ct);
1709 return NULL;
1710 }
1711 }
1712
1713 if (found_boundary) {
1714 /* Try a slightly different boundary. */
1715 char buffer2[16];
1716
1717 free (boundary);
1718 ++serial;
1719 snprintf (buffer2, sizeof buffer2, "%d", serial);
1720 boundary =
1721 concat (boundary_prefix,
1722 first_alt->c_partno ? first_alt->c_partno : "",
1723 "-", buffer2, NULL);
1724 }
1725 }
1726
1727 if (found_boundary) {
1728 advise (NULL, "giving up trying to find a unique boundary");
1729 free (ct);
1730 return NULL;
1731 }
1732 }
1733
1734 name = concat (" ", typename, "/", subtypename, boundary_indicator, "\"",
1735 boundary, "\"", NULL);
1736
1737 /* Load c_first_hf and c_last_hf. */
1738 transfer_noncontent_headers (first_alt, ct);
1739 add_header (ct, add (TYPE_FIELD, NULL), concat (name, "\n", NULL));
1740 free (name);
1741
1742 /* Load c_partno. */
1743 if (first_alt->c_partno) {
1744 ct->c_partno = add (first_alt->c_partno, NULL);
1745 free (first_alt->c_partno);
1746 first_alt->c_partno = concat (ct->c_partno, ".1", NULL);
1747 new_part->c_partno = concat (ct->c_partno, ".2", NULL);
1748 } else {
1749 first_alt->c_partno = add ("1", NULL);
1750 new_part->c_partno = add ("2", NULL);
1751 }
1752
1753 if (ctinit) {
1754 ct->c_ctinfo.ci_type = add (typename, NULL);
1755 ct->c_ctinfo.ci_subtype = add (subtypename, NULL);
1756 }
1757
1758 add_param(&ct->c_ctinfo.ci_first_pm, &ct->c_ctinfo.ci_last_pm,
1759 "boundary", boundary, 0);
1760
1761 p = (struct part *) mh_xmalloc (sizeof *p);
1762 p->mp_next = (struct part *) mh_xmalloc (sizeof *p->mp_next);
1763 p->mp_next->mp_next = NULL;
1764 p->mp_next->mp_part = first_alt;
1765
1766 if ((m = (struct multipart *) mh_xcalloc (1, sizeof (struct multipart))) ==
1767 NULL)
1768 adios (NULL, "out of memory");
1769 m->mp_start = concat (boundary, "\n", NULL);
1770 m->mp_stop = concat (boundary, "--\n", NULL);
1771 m->mp_parts = p;
1772 ct->c_ctparams = m;
1773
1774 free (boundary);
1775
1776 return ct;
1777 }
1778
1779
1780 /*
1781 * Check that the boundary does not appear in the content.
1782 */
1783 static int
1784 boundary_in_content (FILE **fp, char *file, const char *boundary) {
1785 char buffer[BUFSIZ];
1786 size_t bytes_read;
1787 int found_boundary = 0;
1788
1789 /* free_content() will close *fp if we fopen it here. */
1790 if (! *fp && (*fp = fopen (file, "r")) == NULL) {
1791 advise (file, "unable to open %s for reading", file);
1792 return NOTOK;
1793 }
1794
1795 fseeko (*fp, 0L, SEEK_SET);
1796 while ((bytes_read = fread (buffer, 1, sizeof buffer, *fp)) > 0) {
1797 if (find_str (buffer, bytes_read, boundary)) {
1798 found_boundary = 1;
1799 break;
1800 }
1801 }
1802
1803 return found_boundary;
1804 }
1805
1806
1807 /*
1808 * Remove all non-Content headers.
1809 */
1810 static void
1811 transfer_noncontent_headers (CT old, CT new) {
1812 HF hp, hp_prev;
1813
1814 hp_prev = hp = old->c_first_hf;
1815 while (hp) {
1816 HF next = hp->next;
1817
1818 if (strncasecmp (XXX_FIELD_PRF, hp->name, strlen (XXX_FIELD_PRF))) {
1819 if (hp == old->c_last_hf) {
1820 if (hp == old->c_first_hf) {
1821 old->c_last_hf = old->c_first_hf = NULL;
1822 } else {
1823 hp_prev->next = NULL;
1824 old->c_last_hf = hp_prev;
1825 }
1826 } else {
1827 if (hp == old->c_first_hf) {
1828 old->c_first_hf = next;
1829 } else {
1830 hp_prev->next = next;
1831 }
1832 }
1833
1834 /* Put node hp in the new CT. */
1835 if (new->c_first_hf == NULL) {
1836 new->c_first_hf = hp;
1837 } else {
1838 new->c_last_hf->next = hp;
1839 }
1840 new->c_last_hf = hp;
1841 } else {
1842 /* A Content- header, leave in old. */
1843 hp_prev = hp;
1844 }
1845
1846 hp = next;
1847 }
1848 }
1849
1850
1851 /*
1852 * Set content type.
1853 */
1854 static int
1855 set_ct_type (CT ct, int type, int subtype, int encoding) {
1856 char *typename = ct_type_str (type);
1857 char *subtypename = ct_subtype_str (type, subtype);
1858 /* E.g, " text/plain" */
1859 char *type_subtypename = concat (" ", typename, "/", subtypename, NULL);
1860 /* E.g, " text/plain\n" */
1861 char *name_plus_nl = concat (type_subtypename, "\n", NULL);
1862 int found_content_type = 0;
1863 HF hf;
1864 const char *cp = NULL;
1865 char *ctline;
1866 int status;
1867
1868 /* Update/add Content-Type header field. */
1869 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1870 if (! strcasecmp (TYPE_FIELD, hf->name)) {
1871 found_content_type = 1;
1872 free (hf->value);
1873 hf->value = (cp = strchr (ct->c_ctline, ';'))
1874 ? concat (type_subtypename, cp, "\n", NULL)
1875 : add (name_plus_nl, NULL);
1876 }
1877 }
1878 if (! found_content_type) {
1879 add_header (ct, add (TYPE_FIELD, NULL),
1880 (cp = strchr (ct->c_ctline, ';'))
1881 ? concat (type_subtypename, cp, "\n", NULL)
1882 : add (name_plus_nl, NULL));
1883 }
1884
1885 /* Some of these might not be used, but set them anyway. */
1886 ctline = cp
1887 ? concat (type_subtypename, cp, NULL)
1888 : concat (type_subtypename, NULL);
1889 free (ct->c_ctline);
1890 ct->c_ctline = ctline;
1891 /* Leave other ctinfo members as they were. */
1892 free (ct->c_ctinfo.ci_type);
1893 ct->c_ctinfo.ci_type = add (typename, NULL);
1894 free (ct->c_ctinfo.ci_subtype);
1895 ct->c_ctinfo.ci_subtype = add (subtypename, NULL);
1896 ct->c_type = type;
1897 ct->c_subtype = subtype;
1898
1899 free (name_plus_nl);
1900 free (type_subtypename);
1901
1902 status = set_ce (ct, encoding);
1903
1904 return status;
1905 }
1906
1907
1908 /*
1909 * It's not necessary to update the charset parameter of a Content-Type
1910 * header for a text part. According to RFC 2045 Sec. 6.4, the body
1911 * (content) was originally in the specified charset, "and will be in
1912 * that character set again after decoding."
1913 */
1914 static int
1915 decode_text_parts (CT ct, int encoding, const char *decodetypes,
1916 int *message_mods) {
1917 int status = OK;
1918 int lf_line_endings = 0;
1919
1920 switch (ct->c_type) {
1921 case CT_MULTIPART: {
1922 struct multipart *m = (struct multipart *) ct->c_ctparams;
1923 struct part *part;
1924
1925 /* Should check to see if the body for this part is encoded?
1926 For now, it gets passed along as-is by InitMultiPart(). */
1927 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
1928 status = decode_text_parts (part->mp_part, encoding, decodetypes,
1929 message_mods);
1930 }
1931 break;
1932 }
1933
1934 case CT_MESSAGE:
1935 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1936 struct exbody *e = (struct exbody *) ct->c_ctparams;
1937
1938 status = decode_text_parts (e->eb_content, encoding, decodetypes,
1939 message_mods);
1940 }
1941 break;
1942
1943 default:
1944 if (! should_decode(decodetypes, ct->c_ctinfo.ci_type, ct->c_ctinfo.ci_subtype)) {
1945 break;
1946 }
1947
1948 lf_line_endings =
1949 ct->c_ctparams && ((struct text *) ct->c_ctparams)->lf_line_endings;
1950
1951 switch (ct->c_encoding) {
1952 case CE_BASE64:
1953 case CE_QUOTED: {
1954 int ct_encoding;
1955
1956 if (decode_part (ct) == OK && ct->c_cefile.ce_file) {
1957 const char *reason = NULL;
1958
1959 if ((ct_encoding = content_encoding (ct, &reason)) == CE_BINARY
1960 && encoding != CE_BINARY) {
1961 /* The decoding isn't acceptable so discard it.
1962 Leave status as OK to allow other transformations. */
1963 if (verbosw) {
1964 report (NULL, ct->c_partno, ct->c_file,
1965 "will not decode%s because it is binary (%s)",
1966 ct->c_partno ? ""
1967 : ct->c_ctline ? ct->c_ctline
1968 : "",
1969 reason);
1970 }
1971 (void) m_unlink (ct->c_cefile.ce_file);
1972 free (ct->c_cefile.ce_file);
1973 ct->c_cefile.ce_file = NULL;
1974 } else if (ct->c_encoding == CE_QUOTED &&
1975 ct_encoding == CE_8BIT && encoding == CE_7BIT) {
1976 /* The decoding isn't acceptable so discard it.
1977 Leave status as OK to allow other transformations. */
1978 if (verbosw) {
1979 report (NULL, ct->c_partno, ct->c_file,
1980 "will not decode%s because it is 8bit",
1981 ct->c_partno ? ""
1982 : ct->c_ctline ? ct->c_ctline
1983 : "");
1984 }
1985 (void) m_unlink (ct->c_cefile.ce_file);
1986 free (ct->c_cefile.ce_file);
1987 ct->c_cefile.ce_file = NULL;
1988 } else {
1989 int enc;
1990
1991 if (ct_encoding == CE_BINARY) {
1992 enc = CE_BINARY;
1993 } else if (ct_encoding == CE_8BIT && encoding == CE_7BIT) {
1994 enc = CE_QUOTED;
1995 } else {
1996 enc = ct_encoding;
1997 }
1998 if (set_ce (ct, enc) == OK) {
1999 ++*message_mods;
2000 if (verbosw) {
2001 report (NULL, ct->c_partno, ct->c_file, "decode%s",
2002 ct->c_ctline ? ct->c_ctline : "");
2003 }
2004 if (lf_line_endings) {
2005 strip_crs (ct, message_mods);
2006 }
2007 } else {
2008 status = NOTOK;
2009 }
2010 }
2011 } else {
2012 status = NOTOK;
2013 }
2014 break;
2015 }
2016 case CE_8BIT:
2017 case CE_7BIT:
2018 if (lf_line_endings) {
2019 strip_crs (ct, message_mods);
2020 }
2021 break;
2022 default:
2023 break;
2024 }
2025
2026 break;
2027 }
2028
2029 return status;
2030 }
2031
2032
2033 /*
2034 * Determine if the part with type[/subtype] should be decoded, according to
2035 * decodetypes (which came from the -decodetypes switch).
2036 */
2037 static int
2038 should_decode(const char *decodetypes, const char *type, const char *subtype) {
2039 /* Quick search for matching type[/subtype] in decodetypes: bracket
2040 decodetypes with commas, then search for ,type, and ,type/subtype, in
2041 it. */
2042
2043 int found_match = 0;
2044 char *delimited_decodetypes = concat(",", decodetypes, ",", NULL);
2045 char *delimited_type = concat(",", type, ",", NULL);
2046
2047 if (nmh_strcasestr(delimited_decodetypes, delimited_type)) {
2048 found_match = 1;
2049 } else if (subtype != NULL) {
2050 char *delimited_type_subtype =
2051 concat(",", type, "/", subtype, ",", NULL);
2052
2053 if (nmh_strcasestr(delimited_decodetypes, delimited_type_subtype)) {
2054 found_match = 1;
2055 }
2056 free(delimited_type_subtype);
2057 }
2058
2059 free(delimited_type);
2060 free(delimited_decodetypes);
2061
2062 return found_match;
2063 }
2064
2065
2066 /*
2067 * See if the decoded content is 7bit, 8bit, or binary. It's binary
2068 * if it has any NUL characters, a CR not followed by a LF, or lines
2069 * greater than 998 characters in length. If binary, reason is set
2070 * to a string explaining why.
2071 */
2072 static int
2073 content_encoding (CT ct, const char **reason) {
2074 CE ce = &ct->c_cefile;
2075 int encoding = CE_7BIT;
2076
2077 if (ce->ce_file) {
2078 size_t line_len = 0;
2079 char buffer[BUFSIZ];
2080 size_t inbytes;
2081
2082 if (! ce->ce_fp && (ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
2083 advise (ce->ce_file, "unable to open for reading");
2084 return CE_UNKNOWN;
2085 }
2086
2087 fseeko (ce->ce_fp, 0L, SEEK_SET);
2088 while (encoding != CE_BINARY &&
2089 (inbytes = fread (buffer, 1, sizeof buffer, ce->ce_fp)) > 0) {
2090 char *cp;
2091 size_t i;
2092 int last_char_was_cr = 0;
2093
2094 for (i = 0, cp = buffer; i < inbytes; ++i, ++cp) {
2095 if (*cp == '\0' || ++line_len > 998 ||
2096 (*cp != '\n' && last_char_was_cr)) {
2097 encoding = CE_BINARY;
2098 if (*cp == '\0') {
2099 *reason = "null character";
2100 } else if (line_len > 998) {
2101 *reason = "line length > 998";
2102 } else if (*cp != '\n' && last_char_was_cr) {
2103 *reason = "CR not followed by LF";
2104 } else {
2105 /* Should not reach this. */
2106 *reason = "";
2107 }
2108 break;
2109 } else if (*cp == '\n') {
2110 line_len = 0;
2111 } else if (! isascii ((unsigned char) *cp)) {
2112 encoding = CE_8BIT;
2113 }
2114
2115 last_char_was_cr = *cp == '\r' ? 1 : 0;
2116 }
2117 }
2118
2119 fclose (ce->ce_fp);
2120 ce->ce_fp = NULL;
2121 } /* else should never happen */
2122
2123 return encoding;
2124 }
2125
2126
2127 /*
2128 * Strip carriage returns from content.
2129 */
2130 static int
2131 strip_crs (CT ct, int *message_mods) {
2132 char *charset = content_charset (ct);
2133 int status = OK;
2134
2135 /* Only strip carriage returns if content is ASCII or another
2136 charset that has the same readily recognizable CR followed by a
2137 LF. We can include UTF-8 here because if the high-order bit of
2138 a UTF-8 byte is 0, then it must be a single-byte ASCII
2139 character. */
2140 if (! strcasecmp (charset, "US-ASCII") ||
2141 ! strcasecmp (charset, "UTF-8") ||
2142 ! strncasecmp (charset, "ISO-8859-", 9) ||
2143 ! strncasecmp (charset, "WINDOWS-12", 10)) {
2144 char **file = NULL;
2145 FILE **fp = NULL;
2146 size_t begin;
2147 size_t end;
2148 int has_crs = 0;
2149 int opened_input_file = 0;
2150
2151 if (ct->c_cefile.ce_file) {
2152 file = &ct->c_cefile.ce_file;
2153 fp = &ct->c_cefile.ce_fp;
2154 begin = end = 0;
2155 } else if (ct->c_file) {
2156 file = &ct->c_file;
2157 fp = &ct->c_fp;
2158 begin = (size_t) ct->c_begin;
2159 end = (size_t) ct->c_end;
2160 } /* else don't know where the content is */
2161
2162 if (file && *file && fp) {
2163 if (! *fp) {
2164 if ((*fp = fopen (*file, "r")) == NULL) {
2165 advise (*file, "unable to open for reading");
2166 status = NOTOK;
2167 } else {
2168 opened_input_file = 1;
2169 }
2170 }
2171 }
2172
2173 if (fp && *fp) {
2174 char buffer[BUFSIZ];
2175 size_t bytes_read;
2176 size_t bytes_to_read =
2177 end > 0 && end > begin ? end - begin : sizeof buffer;
2178
2179 fseeko (*fp, begin, SEEK_SET);
2180 while ((bytes_read = fread (buffer, 1,
2181 min (bytes_to_read, sizeof buffer),
2182 *fp)) > 0) {
2183 /* Look for CR followed by a LF. This is supposed to
2184 be text so there should be LF's. If not, don't
2185 modify the content. */
2186 char *cp;
2187 size_t i;
2188 int last_char_was_cr = 0;
2189
2190 if (end > 0) { bytes_to_read -= bytes_read; }
2191
2192 for (i = 0, cp = buffer; i < bytes_read; ++i, ++cp) {
2193 if (*cp == '\n' && last_char_was_cr) {
2194 has_crs = 1;
2195 break;
2196 }
2197
2198 last_char_was_cr = *cp == '\r' ? 1 : 0;
2199 }
2200 }
2201
2202 if (has_crs) {
2203 int fd;
2204 char *stripped_content_file;
2205 char *tempfile = m_mktemp2 (NULL, invo_name, &fd, NULL);
2206
2207 if (tempfile == NULL) {
2208 adios (NULL, "unable to create temporary file in %s",
2209 get_temp_dir());
2210 }
2211 stripped_content_file = add (tempfile, NULL);
2212
2213 /* Strip each CR before a LF from the content. */
2214 fseeko (*fp, begin, SEEK_SET);
2215 while ((bytes_read = fread (buffer, 1, sizeof buffer, *fp)) >
2216 0) {
2217 char *cp;
2218 size_t i;
2219 int last_char_was_cr = 0;
2220
2221 for (i = 0, cp = buffer; i < bytes_read; ++i, ++cp) {
2222 if (*cp == '\r') {
2223 last_char_was_cr = 1;
2224 } else if (last_char_was_cr) {
2225 if (*cp != '\n') {
2226 if (write (fd, "\r", 1) < 0) {
2227 advise (tempfile, "CR write");
2228 }
2229 }
2230 if (write (fd, cp, 1) < 0) {
2231 advise (tempfile, "write");
2232 }
2233 last_char_was_cr = 0;
2234 } else {
2235 if (write (fd, cp, 1) < 0) {
2236 advise (tempfile, "write");
2237 }
2238 last_char_was_cr = 0;
2239 }
2240 }
2241 }
2242
2243 if (close (fd)) {
2244 admonish (NULL, "unable to write temporary file %s",
2245 stripped_content_file);
2246 (void) m_unlink (stripped_content_file);
2247 status = NOTOK;
2248 } else {
2249 /* Replace the decoded file with the converted one. */
2250 if (ct->c_cefile.ce_file) {
2251 if (ct->c_cefile.ce_unlink) {
2252 (void) m_unlink (ct->c_cefile.ce_file);
2253 }
2254 free (ct->c_cefile.ce_file);
2255 }
2256 ct->c_cefile.ce_file = stripped_content_file;
2257 ct->c_cefile.ce_unlink = 1;
2258
2259 ++*message_mods;
2260 if (verbosw) {
2261 report (NULL, ct->c_partno,
2262 begin == 0 && end == 0 ? "" : *file,
2263 "stripped CRs");
2264 }
2265 }
2266 }
2267
2268 if (opened_input_file) {
2269 fclose (*fp);
2270 *fp = NULL;
2271 }
2272 }
2273 }
2274
2275 free (charset);
2276
2277 return status;
2278 }
2279
2280
2281 /*
2282 * Convert character set of each part.
2283 */
2284 static int
2285 convert_charsets (CT ct, char *dest_charset, int *message_mods) {
2286 int status = OK;
2287
2288 switch (ct->c_type) {
2289 case CT_TEXT:
2290 if (ct->c_subtype == TEXT_PLAIN) {
2291 status = convert_charset (ct, dest_charset, message_mods);
2292 if (status == OK) {
2293 if (verbosw) {
2294 char *ct_charset = content_charset (ct);
2295
2296 report (NULL, ct->c_partno, ct->c_file,
2297 "convert %s to %s", ct_charset, dest_charset);
2298 free (ct_charset);
2299 }
2300 } else {
2301 char *ct_charset = content_charset (ct);
2302
2303 report ("iconv", ct->c_partno, ct->c_file,
2304 "failed to convert %s to %s", ct_charset, dest_charset);
2305 free (ct_charset);
2306 }
2307 }
2308 break;
2309
2310 case CT_MULTIPART: {
2311 struct multipart *m = (struct multipart *) ct->c_ctparams;
2312 struct part *part;
2313
2314 /* Should check to see if the body for this part is encoded?
2315 For now, it gets passed along as-is by InitMultiPart(). */
2316 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
2317 status =
2318 convert_charsets (part->mp_part, dest_charset, message_mods);
2319 }
2320 break;
2321 }
2322
2323 case CT_MESSAGE:
2324 if (ct->c_subtype == MESSAGE_EXTERNAL) {
2325 struct exbody *e = (struct exbody *) ct->c_ctparams;
2326
2327 status =
2328 convert_charsets (e->eb_content, dest_charset, message_mods);
2329 }
2330 break;
2331
2332 default:
2333 break;
2334 }
2335
2336 return status;
2337 }
2338
2339
2340 /*
2341 * Fix various problems that aren't handled elsewhere. These
2342 * are fixed unconditionally: there are no switches to disable
2343 * them. Currently, "problems" are these:
2344 * 1) remove extraneous semicolon at the end of a header parameter list
2345 * 2) replace RFC 2047 encoding with RFC 2231 encoding of name and
2346 * filename parameters in Content-Type and Content-Disposition
2347 * headers, respectively.
2348 */
2349 static int
2350 fix_always (CT ct, int *message_mods) {
2351 int status = OK;
2352
2353 switch (ct->c_type) {
2354 case CT_MULTIPART: {
2355 struct multipart *m = (struct multipart *) ct->c_ctparams;
2356 struct part *part;
2357
2358 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
2359 status = fix_always (part->mp_part, message_mods);
2360 }
2361 break;
2362 }
2363
2364 case CT_MESSAGE:
2365 if (ct->c_subtype == MESSAGE_EXTERNAL) {
2366 struct exbody *e = (struct exbody *) ct->c_ctparams;
2367
2368 status = fix_always (e->eb_content, message_mods);
2369 }
2370 break;
2371
2372 default: {
2373 HF hf;
2374
2375 if (ct->c_first_hf) {
2376 fix_filename_encoding (ct);
2377 }
2378
2379 for (hf = ct->c_first_hf; hf; hf = hf->next) {
2380 size_t len = strlen (hf->value);
2381
2382 if (strcasecmp (hf->name, TYPE_FIELD) != 0 &&
2383 strcasecmp (hf->name, DISPO_FIELD) != 0) {
2384 /* Only do this for Content-Type and
2385 Content-Disposition fields because those are the
2386 only headers that parse_mime() warns about. */
2387 continue;
2388 }
2389
2390 /* whitespace following a trailing ';' will be nuked as well */
2391 if (hf->value[len - 1] == '\n') {
2392 while (isspace((unsigned char)(hf->value[len - 2]))) {
2393 if (len-- == 0) { break; }
2394 }
2395 }
2396
2397 if (hf->value[len - 2] == ';') {
2398 /* Remove trailing ';' from parameter value. */
2399 hf->value[len - 2] = '\n';
2400 hf->value[len - 1] = '\0';
2401
2402 /* Also, if Content-Type parameter, remove trailing ';'
2403 from ct->c_ctline. This probably isn't necessary
2404 but can't hurt. */
2405 if (strcasecmp(hf->name, TYPE_FIELD) == 0 && ct->c_ctline) {
2406 size_t l = strlen(ct->c_ctline) - 1;
2407 while (isspace((unsigned char)(ct->c_ctline[l])) ||
2408 ct->c_ctline[l] == ';') {
2409 ct->c_ctline[l--] = '\0';
2410 if (l == 0) { break; }
2411 }
2412 }
2413
2414 ++*message_mods;
2415 if (verbosw) {
2416 report (NULL, ct->c_partno, ct->c_file,
2417 "remove trailing ; from %s parameter value",
2418 hf->name);
2419 }
2420 }
2421 }
2422 }}
2423
2424 return status;
2425 }
2426
2427
2428 /*
2429 * Factor out common code for loops in fix_filename_encoding().
2430 */
2431 static int
2432 fix_filename_param (char *name, char *value, PM *first_pm, PM *last_pm) {
2433 size_t value_len;
2434 int fixed = 0;
2435
2436 if (((value_len = strlen (value)) > 0) &&
2437 strncmp (value, "=?", 2) == 0 &&
2438 strncmp (&value[value_len - 2], "?=", 2) == 0) {
2439 /* Looks like an RFC 2047 encoded parameter. */
2440 char decoded[PATH_MAX + 1];
2441
2442 if (decode_rfc2047 (value, decoded, sizeof decoded)) {
2443 /* Encode using RFC 2231. */
2444 replace_param (first_pm, last_pm, name, decoded, 0);
2445 fixed = 1;
2446 } else {
2447 advise (NULL, "failed to decode %s parameter %s", name, value);
2448 }
2449 }
2450
2451 return fixed;
2452 }
2453
2454
2455 /*
2456 * Replace RFC 2047 encoding with RFC 2231 encoding of name and
2457 * filename parameters in Content-Type and Content-Disposition
2458 * headers, respectively.
2459 */
2460 static int
2461 fix_filename_encoding (CT ct) {
2462 PM pm;
2463 HF hf;
2464 int fixed = 0;
2465
2466 for (pm = ct->c_ctinfo.ci_first_pm; pm; pm = pm->pm_next) {
2467 if (pm->pm_name && pm->pm_value &&
2468 strcasecmp (pm->pm_name, "name") == 0) {
2469 fixed = fix_filename_param (pm->pm_name, pm->pm_value,
2470 &ct->c_ctinfo.ci_first_pm,
2471 &ct->c_ctinfo.ci_last_pm);
2472 }
2473 }
2474
2475 for (pm = ct->c_dispo_first; pm; pm = pm->pm_next) {
2476 if (pm->pm_name && pm->pm_value &&
2477 strcasecmp (pm->pm_name, "filename") == 0) {
2478 fixed = fix_filename_param (pm->pm_name, pm->pm_value,
2479 &ct->c_dispo_first,
2480 &ct->c_dispo_last);
2481 }
2482 }
2483
2484 /* Fix hf values to correspond. */
2485 for (hf = ct->c_first_hf; fixed && hf; hf = hf->next) {
2486 enum { OTHER, TYPE_HEADER, DISPO_HEADER } field = OTHER;
2487
2488 if (strcasecmp (hf->name, TYPE_FIELD) == 0) {
2489 field = TYPE_HEADER;
2490 } else if (strcasecmp (hf->name, DISPO_FIELD) == 0) {
2491 field = DISPO_HEADER;
2492 }
2493
2494 if (field != OTHER) {
2495 const char *const semicolon_loc = strchr (hf->value, ';');
2496
2497 if (semicolon_loc) {
2498 const size_t len =
2499 strlen (hf->name) + 1 + semicolon_loc - hf->value;
2500 const char *const params =
2501 output_params (len,
2502 field == TYPE_HEADER
2503 ? ct->c_ctinfo.ci_first_pm
2504 : ct->c_dispo_first,
2505 NULL, 0);
2506 const char *const new_params = concat (params, "\n", NULL);
2507
2508 replace_substring (&hf->value, semicolon_loc, new_params);
2509 free ((char *) new_params);
2510 free ((char *) params);
2511 } else {
2512 advise (NULL, "did not find semicolon in %s:%s\n",
2513 hf->name, hf->value);
2514 }
2515 }
2516 }
2517
2518 return OK;
2519 }
2520
2521
2522 /*
2523 * Output content in input file to output file.
2524 */
2525 static int
2526 write_content (CT ct, const char *input_filename, char *outfile, int modify_inplace,
2527 int message_mods) {
2528 int status = OK;
2529
2530 if (modify_inplace) {
2531 if (message_mods > 0) {
2532 if ((status = output_message (ct, outfile)) == OK) {
2533 char *infile = input_filename
2534 ? add (input_filename, NULL)
2535 : add (ct->c_file ? ct->c_file : "-", NULL);
2536
2537 if (remove_file (infile) == OK) {
2538 if (rename (outfile, infile)) {
2539 /* Rename didn't work, possibly because of an
2540 attempt to rename across filesystems. Try
2541 brute force copy. */
2542 int old = open (outfile, O_RDONLY);
2543 int new =
2544 open (infile, O_WRONLY | O_CREAT, m_gmprot ());
2545 int i = -1;
2546
2547 if (old != -1 && new != -1) {
2548 char buffer[BUFSIZ];
2549
2550 while ((i = read (old, buffer, sizeof buffer)) >
2551 0) {
2552 if (write (new, buffer, i) != i) {
2553 i = -1;
2554 break;
2555 }
2556 }
2557 }
2558 if (new != -1) { close (new); }
2559 if (old != -1) { close (old); }
2560 (void) m_unlink (outfile);
2561
2562 if (i < 0) {
2563 /* The -file argument processing used path() to
2564 expand filename to absolute path. */
2565 int file = ct->c_file && ct->c_file[0] == '/';
2566
2567 admonish (NULL, "unable to rename %s %s to %s",
2568 file ? "file" : "message", outfile,
2569 infile);
2570 status = NOTOK;
2571 }
2572 }
2573 } else {
2574 admonish (NULL, "unable to remove input file %s, "
2575 "not modifying it", infile);
2576 (void) m_unlink (outfile);
2577 status = NOTOK;
2578 }
2579
2580 free (infile);
2581 } else {
2582 status = NOTOK;
2583 }
2584 } else {
2585 /* No modifications and didn't need the tmp outfile. */
2586 (void) m_unlink (outfile);
2587 }
2588 } else {
2589 /* Output is going to some file. Produce it whether or not
2590 there were modifications. */
2591 status = output_message (ct, outfile);
2592 }
2593
2594 flush_errors ();
2595 return status;
2596 }
2597
2598
2599 /*
2600 * parse_mime() does not set lf_line_endings in struct text, so use this
2601 * function to do it. It touches the parts the decodetypes identifies.
2602 */
2603 static void
2604 set_text_ctparams(CT ct, char *decodetypes, int lf_line_endings) {
2605 switch (ct->c_type) {
2606 case CT_MULTIPART: {
2607 struct multipart *m = (struct multipart *) ct->c_ctparams;
2608 struct part *part;
2609
2610 for (part = m->mp_parts; part; part = part->mp_next) {
2611 set_text_ctparams(part->mp_part, decodetypes, lf_line_endings);
2612 }
2613 break;
2614 }
2615
2616 case CT_MESSAGE:
2617 if (ct->c_subtype == MESSAGE_EXTERNAL) {
2618 struct exbody *e = (struct exbody *) ct->c_ctparams;
2619
2620 set_text_ctparams(e->eb_content, decodetypes, lf_line_endings);
2621 }
2622 break;
2623
2624 default:
2625 if (should_decode(decodetypes, ct->c_ctinfo.ci_type, ct->c_ctinfo.ci_subtype)) {
2626 if (ct->c_ctparams == NULL) {
2627 if ((ct->c_ctparams = (struct text *) mh_xcalloc (1, sizeof (struct text))) == NULL) {
2628 adios (NULL, "out of memory");
2629 }
2630 }
2631 ((struct text *) ct->c_ctparams)->lf_line_endings = lf_line_endings;
2632 }
2633 }
2634 }
2635
2636
2637 /*
2638 * If "rmmproc" is defined, call that to remove the file. Otherwise,
2639 * use the standard MH backup file.
2640 */
2641 static int
2642 remove_file (const char *file) {
2643 if (rmmproc) {
2644 char *rmm_command = concat (rmmproc, " ", file, NULL);
2645 int status = system (rmm_command);
2646
2647 free (rmm_command);
2648 return WIFEXITED (status) ? WEXITSTATUS (status) : NOTOK;
2649 } else {
2650 /* This is OK for a non-message file, it still uses the
2651 BACKUP_PREFIX form. The backup file will be in the same
2652 directory as file. */
2653 return rename (file, m_backup (file));
2654 }
2655 }
2656
2657
2658 /*
2659 * Output formatted message to user.
2660 */
2661 static void
2662 report (char *what, char *partno, char *filename, char *message, ...) {
2663 va_list args;
2664 char *fmt;
2665
2666 if (verbosw) {
2667 va_start (args, message);
2668 fmt = concat (filename, partno ? " part " : ", ",
2669 partno ? partno : "", partno ? ", " : "", message, NULL);
2670
2671 advertise (what, NULL, fmt, args);
2672
2673 free (fmt);
2674 va_end (args);
2675 }
2676 }
2677
2678
2679 static void
2680 pipeser (int i)
2681 {
2682 if (i == SIGQUIT) {
2683 fflush (stdout);
2684 fprintf (stderr, "\n");
2685 fflush (stderr);
2686 }
2687
2688 done (1);
2689 /* NOTREACHED */
2690 }