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