]> diplodocus.org Git - nmh/blob - uip/mhfixmsg.c
ffe97acdb7e6b4d421dfa71983c61d2c4d8ae4f7
[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("textcharset", 0, TEXTCHARSETSW) \
20 X("notextcharset", 0, NTEXTCHARSETSW) \
21 X("reformat", 0, REFORMATSW) \
22 X("noreformat", 0, NREFORMATSW) \
23 X("replacetextplain", 0, REPLACETEXTPLAINSW) \
24 X("noreplacetextplain", 0, NREPLACETEXTPLAINSW) \
25 X("fixboundary", 0, FIXBOUNDARYSW) \
26 X("nofixboundary", 0, NFIXBOUNDARYSW) \
27 X("fixcte", 0, FIXCTESW) \
28 X("nofixcte", 0, NFIXCTESW) \
29 X("file file", 0, FILESW) \
30 X("outfile file", 0, OUTFILESW) \
31 X("rmmproc program", 0, RPROCSW) \
32 X("normmproc", 0, NRPRCSW) \
33 X("changecur", 0, CHGSW) \
34 X("nochangecur", 0, NCHGSW) \
35 X("verbose", 0, VERBSW) \
36 X("noverbose", 0, NVERBSW) \
37 X("version", 0, VERSIONSW) \
38 X("help", 0, HELPSW) \
39
40 #define X(sw, minchars, id) id,
41 DEFINE_SWITCH_ENUM(MHFIXMSG);
42 #undef X
43
44 #define X(sw, minchars, id) { sw, minchars, id },
45 DEFINE_SWITCH_ARRAY(MHFIXMSG, switches);
46 #undef X
47
48
49 int verbosw;
50 int debugsw; /* Needed by mhparse.c. */
51
52 #define quitser pipeser
53
54 /* mhparse.c */
55 extern int skip_mp_cte_check; /* flag to InitMultiPart */
56 extern int suppress_bogus_mp_content_warning; /* flag to InitMultiPart */
57 extern int bogus_mp_content; /* flag from InitMultiPart */
58
59 /* mhoutsbr.c */
60 int output_message (CT, char *);
61
62 /* mhmisc.c */
63 void flush_errors (void);
64
65 /* mhfree.c */
66 extern CT *cts;
67 void freects_done (int) NORETURN;
68
69 /*
70 * static prototypes
71 */
72 typedef struct fix_transformations {
73 int fixboundary;
74 int fixcte;
75 int reformat;
76 int replacetextplain;
77 int decodetext;
78 char *textcharset;
79 } fix_transformations;
80
81 int mhfixmsgsbr (CT *, const fix_transformations *, char *);
82 static int fix_boundary (CT *, int *);
83 static int get_multipart_boundary (CT, char **);
84 static int replace_boundary (CT, char *, char *);
85 static int fix_multipart_cte (CT, int *);
86 static int set_ce (CT, int);
87 static int ensure_text_plain (CT *, CT, int *, int);
88 static CT build_text_plain_part (CT);
89 static CT divide_part (CT);
90 static void copy_ctinfo (CI, CI);
91 static int decode_part (CT);
92 static int reformat_part (CT, char *, char *, char *, int);
93 static int charset_encoding (CT);
94 static CT build_multipart_alt (CT, CT, int, int);
95 static int boundary_in_content (FILE **, char *, const char *);
96 static void transfer_noncontent_headers (CT, CT);
97 static int set_ct_type (CT, int type, int subtype, int encoding);
98 static int decode_text_parts (CT, int, int *);
99 static int content_encoding (CT, const char **);
100 static int strip_crs (CT, int *);
101 static int convert_charsets (CT, char *, int *);
102 static int write_content (CT, char *, char *, int, int);
103 static int remove_file (char *);
104 static void report (char *, char *, char *, char *, ...);
105 static void pipeser (int);
106
107
108 int
109 main (int argc, char **argv) {
110 int msgnum;
111 char *cp, *file = NULL, *folder = NULL;
112 char *maildir, buf[100], *outfile = NULL;
113 char **argp, **arguments;
114 struct msgs_array msgs = { 0, 0, NULL };
115 struct msgs *mp = NULL;
116 CT *ctp;
117 FILE *fp;
118 int using_stdin = 0;
119 int chgflag = 1;
120 int status = OK;
121 fix_transformations fx;
122 fx.reformat = fx.fixcte = fx.fixboundary = 1;
123 fx.replacetextplain = 0;
124 fx.decodetext = CE_8BIT;
125 fx.textcharset = NULL;
126
127 if (nmh_init(argv[0], 1)) { return 1; }
128
129 done = freects_done;
130
131 arguments = getarguments (invo_name, argc, argv, 1);
132 argp = arguments;
133
134 /*
135 * Parse arguments
136 */
137 while ((cp = *argp++)) {
138 if (*cp == '-') {
139 switch (smatch (++cp, switches)) {
140 case AMBIGSW:
141 ambigsw (cp, switches);
142 done (1);
143 case UNKWNSW:
144 adios (NULL, "-%s unknown", cp);
145
146 case HELPSW:
147 snprintf (buf, sizeof buf, "%s [+folder] [msgs] [switches]",
148 invo_name);
149 print_help (buf, switches, 1);
150 done (0);
151 case VERSIONSW:
152 print_version(invo_name);
153 done (0);
154
155 case DECODETEXTSW:
156 if (! (cp = *argp++) || *cp == '-')
157 adios (NULL, "missing argument to %s", argp[-2]);
158 if (! strcasecmp (cp, "8bit")) {
159 fx.decodetext = CE_8BIT;
160 } else if (! strcasecmp (cp, "7bit")) {
161 fx.decodetext = CE_7BIT;
162 } else {
163 adios (NULL, "invalid argument to %s", argp[-2]);
164 }
165 continue;
166 case NDECODETEXTSW:
167 fx.decodetext = 0;
168 continue;
169 case TEXTCHARSETSW:
170 if (! (cp = *argp++) || (*cp == '-' && cp[1]))
171 adios (NULL, "missing argument to %s", argp[-2]);
172 fx.textcharset = cp;
173 continue;
174 case NTEXTCHARSETSW:
175 fx.textcharset = 0;
176 continue;
177 case FIXBOUNDARYSW:
178 fx.fixboundary = 1;
179 continue;
180 case NFIXBOUNDARYSW:
181 fx.fixboundary = 0;
182 continue;
183 case FIXCTESW:
184 fx.fixcte = 1;
185 continue;
186 case NFIXCTESW:
187 fx.fixcte = 0;
188 continue;
189 case REFORMATSW:
190 fx.reformat = 1;
191 continue;
192 case NREFORMATSW:
193 fx.reformat = 0;
194 continue;
195 case REPLACETEXTPLAINSW:
196 fx.replacetextplain = 1;
197 continue;
198 case NREPLACETEXTPLAINSW:
199 fx.replacetextplain = 0;
200 continue;
201 case FILESW:
202 if (! (cp = *argp++) || (*cp == '-' && cp[1]))
203 adios (NULL, "missing argument to %s", argp[-2]);
204 file = *cp == '-' ? add (cp, NULL) : path (cp, TFILE);
205 continue;
206 case OUTFILESW:
207 if (! (cp = *argp++) || (*cp == '-' && cp[1]))
208 adios (NULL, "missing argument to %s", argp[-2]);
209 outfile = *cp == '-' ? add (cp, NULL) : path (cp, TFILE);
210 continue;
211 case RPROCSW:
212 if (!(rmmproc = *argp++) || *rmmproc == '-')
213 adios (NULL, "missing argument to %s", argp[-2]);
214 continue;
215 case NRPRCSW:
216 rmmproc = NULL;
217 continue;
218 case CHGSW:
219 chgflag = 1;
220 continue;
221 case NCHGSW:
222 chgflag = 0;
223 continue;
224 case VERBSW:
225 verbosw = 1;
226 continue;
227 case NVERBSW:
228 verbosw = 0;
229 continue;
230 }
231 }
232 if (*cp == '+' || *cp == '@') {
233 if (folder)
234 adios (NULL, "only one folder at a time!");
235 else
236 folder = pluspath (cp);
237 } else {
238 if (*cp == '/') {
239 /* Interpret a full path as a filename, not a message. */
240 file = add (cp, NULL);
241 } else {
242 app_msgarg (&msgs, cp);
243 }
244 }
245 }
246
247 SIGNAL (SIGQUIT, quitser);
248 SIGNAL (SIGPIPE, pipeser);
249
250 /*
251 * Read the standard profile setup
252 */
253 if ((fp = fopen (cp = etcpath ("mhn.defaults"), "r"))) {
254 readconfig ((struct node **) 0, fp, cp, 0);
255 fclose (fp);
256 }
257
258 suppress_bogus_mp_content_warning = skip_mp_cte_check = 1;
259
260 if (! context_find ("path"))
261 free (path ("./", TFOLDER));
262
263 if (file && msgs.size)
264 adios (NULL, "cannot specify msg and file at same time!");
265
266 /*
267 * check if message is coming from file
268 */
269 if (file) {
270 /* If file is stdin, create a tmp file name before parse_mime()
271 has a chance, because it might put in on a different
272 filesystem than the output file. Instead, put it in the
273 user's preferred tmp directory. */
274 CT ct;
275
276 if (! strcmp ("-", file)) {
277 int fd;
278 char *cp;
279
280 using_stdin = 1;
281
282 if ((cp = m_mktemp2 (NULL, invo_name, &fd, NULL)) == NULL) {
283 adios (NULL, "unable to create temporary file in %s",
284 get_temp_dir());
285 } else {
286 free (file);
287 file = add (cp, NULL);
288 cpydata (STDIN_FILENO, fd, "-", file);
289 }
290
291 if (close (fd)) {
292 (void) m_unlink (file);
293 adios (NULL, "failed to write temporary file");
294 }
295 }
296
297 if (! (cts = (CT *) mh_xcalloc ((size_t) 2, sizeof *cts))) {
298 adios (NULL, "out of memory");
299 }
300 ctp = cts;
301
302 if ((ct = parse_mime (file))) { *ctp++ = ct; }
303 } else {
304 /*
305 * message(s) are coming from a folder
306 */
307 CT ct;
308
309 if (! msgs.size)
310 app_msgarg(&msgs, "cur");
311 if (! folder)
312 folder = getfolder (1);
313 maildir = m_maildir (folder);
314
315 if (chdir (maildir) == NOTOK)
316 adios (maildir, "unable to change directory to");
317
318 /* read folder and create message structure */
319 if (! (mp = folder_read (folder, 1)))
320 adios (NULL, "unable to read folder %s", folder);
321
322 /* check for empty folder */
323 if (mp->nummsg == 0)
324 adios (NULL, "no messages in %s", folder);
325
326 /* parse all the message ranges/sequences and set SELECTED */
327 for (msgnum = 0; msgnum < msgs.size; msgnum++)
328 if (! m_convert (mp, msgs.msgs[msgnum]))
329 done (1);
330 seq_setprev (mp); /* set the previous-sequence */
331
332 if (! (cts =
333 (CT *) mh_xcalloc ((size_t) (mp->numsel + 1), sizeof *cts))) {
334 adios (NULL, "out of memory");
335 }
336 ctp = cts;
337
338 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
339 if (is_selected(mp, msgnum)) {
340 char *msgnam;
341
342 msgnam = m_name (msgnum);
343 if ((ct = parse_mime (msgnam))) { *ctp++ = ct; }
344 }
345 }
346
347 if (chgflag) {
348 seq_setcur (mp, mp->hghsel); /* update current message */
349 }
350 seq_save (mp); /* synchronize sequences */
351 context_replace (pfolder, folder);/* update current folder */
352 context_save (); /* save the context file */
353 }
354
355 if (*cts) {
356 for (ctp = cts; *ctp; ++ctp) {
357 status += mhfixmsgsbr (ctp, &fx, outfile);
358
359 if (using_stdin) {
360 (void) m_unlink (file);
361
362 if (! outfile) {
363 /* Just calling m_backup() unlinks the backup file. */
364 (void) m_backup (file);
365 }
366 }
367 }
368 } else {
369 status = 1;
370 }
371
372 free (outfile);
373 free (file);
374
375 /* done is freects_done, which will clean up all of cts. */
376 done (status);
377 return NOTOK;
378 }
379
380
381 int
382 mhfixmsgsbr (CT *ctp, const fix_transformations *fx, char *outfile) {
383 /* Store input filename in case one of the transformations, i.e.,
384 fix_boundary(), rewrites to a tmp file. */
385 char *input_filename = add ((*ctp)->c_file, NULL);
386 int modify_inplace = 0;
387 int message_mods = 0;
388 int status = OK;
389
390 if (outfile == NULL) {
391 modify_inplace = 1;
392
393 if ((*ctp)->c_file) {
394 char *tempfile;
395 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, NULL)) == NULL) {
396 adios (NULL, "unable to create temporary file in %s",
397 get_temp_dir());
398 }
399 outfile = add (tempfile, NULL);
400 } else {
401 adios (NULL, "missing both input and output filenames\n");
402 }
403 }
404
405 reverse_alternative_parts (*ctp);
406 if (status == OK && fx->fixboundary) {
407 status = fix_boundary (ctp, &message_mods);
408 }
409 if (status == OK && fx->fixcte) {
410 status = fix_multipart_cte (*ctp, &message_mods);
411 }
412 if (status == OK && fx->reformat) {
413 status =
414 ensure_text_plain (ctp, NULL, &message_mods, fx->replacetextplain);
415 }
416 if (status == OK && fx->decodetext) {
417 status = decode_text_parts (*ctp, fx->decodetext, &message_mods);
418 }
419 if (status == OK && fx->textcharset != NULL) {
420 status = convert_charsets (*ctp, fx->textcharset, &message_mods);
421 }
422
423 if (! (*ctp)->c_umask) {
424 /* Set the umask for the contents file. This currently
425 isn't used but just in case it is in the future. */
426 struct stat st;
427
428 if (stat ((*ctp)->c_file, &st) != NOTOK) {
429 (*ctp)->c_umask = ~(st.st_mode & 0777);
430 } else {
431 (*ctp)->c_umask = ~m_gmprot();
432 }
433 }
434
435 /*
436 * Write the content to a file
437 */
438 if (status == OK) {
439 status = write_content (*ctp, input_filename, outfile, modify_inplace,
440 message_mods);
441 } else if (! modify_inplace) {
442 /* Something went wrong. Output might be expected, such
443 as if this were run as a filter. Just copy the input
444 to the output. */
445 int in = open (input_filename, O_RDONLY);
446 int out = strcmp (outfile, "-")
447 ? open (outfile, O_WRONLY | O_CREAT, m_gmprot ())
448 : STDOUT_FILENO;
449
450 if (in != -1 && out != -1) {
451 cpydata (in, out, input_filename, outfile);
452 } else {
453 status = NOTOK;
454 }
455
456 close (out);
457 close (in);
458 }
459
460 if (modify_inplace) {
461 if (status != OK) { (void) m_unlink (outfile); }
462 free (outfile);
463 outfile = NULL;
464 }
465
466 free (input_filename);
467
468 return status;
469 }
470
471
472 static int
473 fix_boundary (CT *ct, int *message_mods) {
474 struct multipart *mp;
475 int status = OK;
476
477 if (bogus_mp_content) {
478 mp = (struct multipart *) (*ct)->c_ctparams;
479
480 /*
481 * 1) Get boundary at end of part.
482 * 2) Get boundary at beginning of part and compare to the end-of-part
483 * boundary.
484 * 3) Write out contents of ct to tmp file, replacing boundary in
485 * header with boundary from part. Set c_unlink to 1.
486 * 4) Free ct.
487 * 5) Call parse_mime() on the tmp file, replacing ct.
488 */
489
490 if (mp && mp->mp_start) {
491 char *part_boundary;
492
493 if (get_multipart_boundary (*ct, &part_boundary) == OK) {
494 char *fixed;
495
496 if ((fixed = m_mktemp2 (NULL, invo_name, NULL, &(*ct)->c_fp))) {
497 if (replace_boundary (*ct, fixed, part_boundary) == OK) {
498 char *filename = add ((*ct)->c_file, NULL);
499 CT fixed_ct;
500
501 free_content (*ct);
502 if ((fixed_ct = parse_mime (fixed))) {
503 *ct = fixed_ct;
504 (*ct)->c_unlink = 1;
505
506 ++*message_mods;
507 if (verbosw) {
508 report (NULL, NULL, filename,
509 "fix multipart boundary");
510 }
511 } else {
512 advise (NULL, "unable to parse fixed part");
513 status = NOTOK;
514 }
515 free (filename);
516 } else {
517 advise (NULL, "unable to replace broken boundary");
518 status = NOTOK;
519 }
520 } else {
521 advise (NULL, "unable to create temporary file in %s",
522 get_temp_dir());
523 status = NOTOK;
524 }
525
526 free (part_boundary);
527 }
528 }
529 }
530
531 return status;
532 }
533
534
535 static int
536 get_multipart_boundary (CT ct, char **part_boundary) {
537 char buffer[BUFSIZ];
538 char *end_boundary = NULL;
539 off_t begin = (off_t) ct->c_end > (off_t) (ct->c_begin + sizeof buffer)
540 ? (off_t) (ct->c_end - sizeof buffer)
541 : (off_t) ct->c_begin;
542 size_t bytes_read;
543 int status = OK;
544
545 /* This will fail if the boundary spans fread() calls. BUFSIZ should
546 be big enough, even if it's just 1024, to make that unlikely. */
547
548 /* free_content() will close ct->c_fp. */
549 if (! ct->c_fp && (ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
550 advise (ct->c_file, "unable to open for reading");
551 return NOTOK;
552 }
553
554 /* Get boundary at end of multipart. */
555 while (begin >= (off_t) ct->c_begin) {
556 fseeko (ct->c_fp, begin, SEEK_SET);
557 while ((bytes_read = fread (buffer, 1, sizeof buffer, ct->c_fp)) > 0) {
558 char *cp = rfind_str (buffer, bytes_read, "--");
559
560 if (cp) {
561 char *end;
562
563 /* Trim off trailing "--" and anything beyond. */
564 *cp-- = '\0';
565 if ((end = rfind_str (buffer, cp - buffer, "\n"))) {
566 if (strlen (end) > 3 && *end++ == '\n' &&
567 *end++ == '-' && *end++ == '-') {
568 end_boundary = add (end, NULL);
569 break;
570 }
571 }
572 }
573 }
574
575 if (! end_boundary && begin > (off_t) (ct->c_begin + sizeof buffer)) {
576 begin -= sizeof buffer;
577 } else {
578 break;
579 }
580 }
581
582 /* Get boundary at beginning of multipart. */
583 if (end_boundary) {
584 fseeko (ct->c_fp, ct->c_begin, SEEK_SET);
585 while ((bytes_read = fread (buffer, 1, sizeof buffer, ct->c_fp)) > 0) {
586 if (bytes_read >= strlen (end_boundary)) {
587 char *cp = find_str (buffer, bytes_read, end_boundary);
588
589 if (cp && cp - buffer >= 2 && *--cp == '-' &&
590 *--cp == '-' && (cp > buffer && *--cp == '\n')) {
591 status = OK;
592 break;
593 }
594 } else {
595 /* The start and end boundaries didn't match, or the
596 start boundary doesn't begin with "\n--" (or "--"
597 if at the beginning of buffer). Keep trying. */
598 status = NOTOK;
599 }
600 }
601 } else {
602 status = NOTOK;
603 }
604
605 if (status == OK) {
606 *part_boundary = end_boundary;
607 } else {
608 *part_boundary = NULL;
609 free (end_boundary);
610 }
611
612 return status;
613 }
614
615
616 /* Open and copy ct->c_file to file, replacing the multipart boundary. */
617 static int
618 replace_boundary (CT ct, char *file, char *boundary) {
619 FILE *fpin, *fpout;
620 int compnum, state;
621 char buf[BUFSIZ], name[NAMESZ];
622 char *np, *vp;
623 m_getfld_state_t gstate = 0;
624 int status = OK;
625
626 if (ct->c_file == NULL) {
627 advise (NULL, "missing input filename");
628 return NOTOK;
629 }
630
631 if ((fpin = fopen (ct->c_file, "r")) == NULL) {
632 advise (ct->c_file, "unable to open for reading");
633 return NOTOK;
634 }
635
636 if ((fpout = fopen (file, "w")) == NULL) {
637 fclose (fpin);
638 advise (file, "unable to open for writing");
639 return NOTOK;
640 }
641
642 for (compnum = 1;;) {
643 int bufsz = (int) sizeof buf;
644
645 switch (state = m_getfld (&gstate, name, buf, &bufsz, fpin)) {
646 case FLD:
647 case FLDPLUS:
648 compnum++;
649
650 /* get copies of the buffers */
651 np = add (name, NULL);
652 vp = add (buf, NULL);
653
654 /* if necessary, get rest of field */
655 while (state == FLDPLUS) {
656 bufsz = sizeof buf;
657 state = m_getfld (&gstate, name, buf, &bufsz, fpin);
658 vp = add (buf, vp); /* add to previous value */
659 }
660
661 if (strcasecmp (TYPE_FIELD, np)) {
662 fprintf (fpout, "%s:%s", np, vp);
663 } else {
664 char *new_ctline, *new_params;
665
666 replace_param(&ct->c_ctinfo.ci_first_pm,
667 &ct->c_ctinfo.ci_last_pm, "boundary",
668 boundary, 0);
669
670 new_ctline = concat(" ", ct->c_ctinfo.ci_type, "/",
671 ct->c_ctinfo.ci_subtype, NULL);
672 new_params = output_params(strlen(TYPE_FIELD) +
673 strlen(new_ctline) + 1,
674 ct->c_ctinfo.ci_first_pm, NULL, 0);
675 fprintf (fpout, "%s:%s%s\n", np, new_ctline,
676 new_params ? new_params : "");
677 free(new_ctline);
678 if (new_params)
679 free(new_params);
680 }
681
682 free (vp);
683 free (np);
684
685 continue;
686
687 case BODY:
688 fputs ("\n", fpout);
689 /* buf will have a terminating NULL, skip it. */
690 if ((int) fwrite (buf, 1, bufsz-1, fpout) < bufsz-1) {
691 advise (file, "fwrite");
692 }
693 continue;
694
695 case FILEEOF:
696 break;
697
698 case LENERR:
699 case FMTERR:
700 advise (NULL, "message format error in component #%d", compnum);
701 status = NOTOK;
702 break;
703
704 default:
705 advise (NULL, "getfld() returned %d", state);
706 status = NOTOK;
707 break;
708 }
709
710 break;
711 }
712
713 m_getfld_state_destroy (&gstate);
714 fclose (fpout);
715 fclose (fpin);
716
717 return status;
718 }
719
720
721 static int
722 fix_multipart_cte (CT ct, int *message_mods) {
723 int status = OK;
724
725 if (ct->c_type == CT_MULTIPART) {
726 struct multipart *m;
727 struct part *part;
728
729 if (ct->c_encoding != CE_7BIT && ct->c_encoding != CE_8BIT &&
730 ct->c_encoding != CE_BINARY) {
731 HF hf;
732
733 for (hf = ct->c_first_hf; hf; hf = hf->next) {
734 char *name = hf->name;
735 for (; *name && isspace ((unsigned char) *name); ++name) {
736 continue;
737 }
738
739 if (! strncasecmp (name, ENCODING_FIELD,
740 strlen (ENCODING_FIELD))) {
741 char *prefix = "Nmh-REPLACED-INVALID-";
742 HF h = mh_xmalloc (sizeof *h);
743
744 h->name = add (hf->name, NULL);
745 h->hf_encoding = hf->hf_encoding;
746 h->next = hf->next;
747 hf->next = h;
748
749 /* Retain old header but prefix its name. */
750 free (hf->name);
751 hf->name = concat (prefix, h->name, NULL);
752
753 ++*message_mods;
754 if (verbosw) {
755 char *encoding = cpytrim (hf->value);
756 report (NULL, ct->c_partno, ct->c_file,
757 "replace Content-Transfer-Encoding of %s "
758 "with 8 bit", encoding);
759 free (encoding);
760 }
761
762 h->value = add (" 8bit\n", NULL);
763
764 /* Don't need to warn for multiple C-T-E header
765 fields, parse_mime() already does that. But
766 if there are any, fix them all as necessary. */
767 hf = h;
768 }
769 }
770
771 set_ce (ct, CE_8BIT);
772 }
773
774 m = (struct multipart *) ct->c_ctparams;
775 for (part = m->mp_parts; part; part = part->mp_next) {
776 if (fix_multipart_cte (part->mp_part, message_mods) != OK) {
777 status = NOTOK;
778 break;
779 }
780 }
781 }
782
783 return status;
784 }
785
786
787 static int
788 set_ce (CT ct, int encoding) {
789 const char *ce = ce_str (encoding);
790 const struct str2init *ctinit = get_ce_method (ce);
791
792 if (ctinit) {
793 char *cte = concat (" ", ce, "\n", NULL);
794 int found_cte = 0;
795 HF hf;
796 /* Decoded contents might be in ct->c_cefile.ce_file, if the
797 caller is decode_text_parts (). Save because we'll
798 overwrite below. */
799 struct cefile decoded_content_info = ct->c_cefile;
800
801 ct->c_encoding = encoding;
802
803 ct->c_ctinitfnx = ctinit->si_init;
804 /* This will assign ct->c_cefile with an all-0 struct, which
805 is what we want. */
806 (*ctinit->si_init) (ct);
807 /* After returning, the caller should set
808 ct->c_cefile.ce_file to the name of the file containing
809 the contents. */
810
811 /* Restore the cefile. */
812 ct->c_cefile = decoded_content_info;
813
814 /* Update/add Content-Transfer-Encoding header field. */
815 for (hf = ct->c_first_hf; hf; hf = hf->next) {
816 if (! strcasecmp (ENCODING_FIELD, hf->name)) {
817 found_cte = 1;
818 free (hf->value);
819 hf->value = cte;
820 }
821 }
822 if (! found_cte) {
823 add_header (ct, add (ENCODING_FIELD, NULL), cte);
824 }
825
826 /* Update c_celine. It's used only by mhlist -debug. */
827 free (ct->c_celine);
828 ct->c_celine = add (cte, NULL);
829
830 return OK;
831 } else {
832 return NOTOK;
833 }
834 }
835
836
837 /* Make sure each text part has a corresponding text/plain part. */
838 static int
839 ensure_text_plain (CT *ct, CT parent, int *message_mods, int replacetextplain) {
840 int status = OK;
841
842 switch ((*ct)->c_type) {
843 case CT_TEXT: {
844 int has_text_plain = 0;
845
846 /* Nothing to do for text/plain. */
847 if ((*ct)->c_subtype == TEXT_PLAIN) { return OK; }
848
849 if (parent && parent->c_type == CT_MULTIPART &&
850 parent->c_subtype == MULTI_ALTERNATE) {
851 struct multipart *mp = (struct multipart *) parent->c_ctparams;
852 struct part *part, *prev;
853 int new_subpart_number = 1;
854
855 /* See if there is a sibling text/plain. */
856 for (prev = part = mp->mp_parts; part; part = part->mp_next) {
857 ++new_subpart_number;
858 if (part->mp_part->c_type == CT_TEXT &&
859 part->mp_part->c_subtype == TEXT_PLAIN) {
860 if (replacetextplain) {
861 struct part *old_part;
862 if (part == mp->mp_parts) {
863 old_part = mp->mp_parts;
864 mp->mp_parts = part->mp_next;
865 } else {
866 old_part = prev->mp_next;
867 prev->mp_next = part->mp_next;
868 }
869 if (verbosw) {
870 report (NULL, parent->c_partno, parent->c_file,
871 "remove text/plain part %s",
872 old_part->mp_part->c_partno);
873 }
874 free_content (old_part->mp_part);
875 free (old_part);
876 } else {
877 has_text_plain = 1;
878 }
879 break;
880 }
881 prev = part;
882 }
883
884 if (! has_text_plain) {
885 /* Parent is a multipart/alternative. Insert a new
886 text/plain subpart. */
887 struct part *new_part = mh_xmalloc (sizeof *new_part);
888
889 if ((new_part->mp_part = build_text_plain_part (*ct))) {
890 char buffer[16];
891 snprintf (buffer, sizeof buffer, "%d", new_subpart_number);
892
893 new_part->mp_next = mp->mp_parts;
894 mp->mp_parts = new_part;
895 new_part->mp_part->c_partno =
896 concat (parent->c_partno ? parent->c_partno : "1", ".",
897 buffer, NULL);
898
899 ++*message_mods;
900 if (verbosw) {
901 report (NULL, parent->c_partno, parent->c_file,
902 "insert text/plain part");
903 }
904 } else {
905 free_content (new_part->mp_part);
906 free (new_part);
907 status = NOTOK;
908 }
909 }
910 } else {
911 /* Slip new text/plain part into a new multipart/alternative. */
912 CT tp_part = build_text_plain_part (*ct);
913
914 if (tp_part) {
915 CT mp_alt = build_multipart_alt (*ct, tp_part, CT_MULTIPART,
916 MULTI_ALTERNATE);
917 if (mp_alt) {
918 struct multipart *mp =
919 (struct multipart *) mp_alt->c_ctparams;
920
921 if (mp && mp->mp_parts) {
922 mp->mp_parts->mp_part = tp_part;
923 /* Make the new multipart/alternative the parent. */
924 *ct = mp_alt;
925
926 ++*message_mods;
927 if (verbosw) {
928 report (NULL, (*ct)->c_partno, (*ct)->c_file,
929 "insert text/plain part");
930 }
931 } else {
932 free_content (tp_part);
933 free_content (mp_alt);
934 status = NOTOK;
935 }
936 } else {
937 status = NOTOK;
938 }
939 } else {
940 status = NOTOK;
941 }
942 }
943 break;
944 }
945
946 case CT_MULTIPART: {
947 struct multipart *mp = (struct multipart *) (*ct)->c_ctparams;
948 struct part *part;
949
950 for (part = mp->mp_parts; status == OK && part; part = part->mp_next) {
951 if ((*ct)->c_type == CT_MULTIPART) {
952 status = ensure_text_plain (&part->mp_part, *ct, message_mods,
953 replacetextplain);
954 }
955 }
956 break;
957 }
958
959 case CT_MESSAGE:
960 if ((*ct)->c_subtype == MESSAGE_EXTERNAL) {
961 struct exbody *e = (struct exbody *) (*ct)->c_ctparams;
962
963 status = ensure_text_plain (&e->eb_content, *ct, message_mods,
964 replacetextplain);
965 }
966 break;
967 }
968
969 return status;
970 }
971
972
973 static CT
974 build_text_plain_part (CT encoded_part) {
975 CT tp_part = divide_part (encoded_part);
976 char *tmp_plain_file = NULL;
977
978 if (decode_part (tp_part) == OK) {
979 /* Now, tp_part->c_cefile.ce_file is the name of the tmp file that
980 contains the decoded contents. And the decoding function, such
981 as openQuoted, will have set ...->ce_unlink to 1 so that it will
982 be unlinked by free_content (). */
983 char *tempfile;
984
985 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, NULL)) == NULL) {
986 advise (NULL, "unable to create temporary file in %s",
987 get_temp_dir());
988 }
989 tmp_plain_file = add (tempfile, NULL);
990 if (reformat_part (tp_part, tmp_plain_file,
991 tp_part->c_ctinfo.ci_type,
992 tp_part->c_ctinfo.ci_subtype,
993 tp_part->c_type) == OK) {
994 return tp_part;
995 }
996 }
997
998 free_content (tp_part);
999 (void) m_unlink (tmp_plain_file);
1000 free (tmp_plain_file);
1001
1002 return NULL;
1003 }
1004
1005
1006 static CT
1007 divide_part (CT ct) {
1008 CT new_part;
1009
1010 if ((new_part = (CT) mh_xcalloc (1, sizeof *new_part)) == NULL)
1011 adios (NULL, "out of memory");
1012
1013 /* Just copy over what is needed for decoding. c_vrsn and
1014 c_celine aren't necessary. */
1015 new_part->c_file = add (ct->c_file, NULL);
1016 new_part->c_begin = ct->c_begin;
1017 new_part->c_end = ct->c_end;
1018 copy_ctinfo (&new_part->c_ctinfo, &ct->c_ctinfo);
1019 new_part->c_type = ct->c_type;
1020 new_part->c_cefile = ct->c_cefile;
1021 new_part->c_encoding = ct->c_encoding;
1022 new_part->c_ctinitfnx = ct->c_ctinitfnx;
1023 new_part->c_ceopenfnx = ct->c_ceopenfnx;
1024 new_part->c_ceclosefnx = ct->c_ceclosefnx;
1025 new_part->c_cesizefnx = ct->c_cesizefnx;
1026
1027 /* c_ctline is used by reformat__part(), so it can preserve
1028 anything after the type/subtype. */
1029 new_part->c_ctline = add (ct->c_ctline, NULL);
1030
1031 return new_part;
1032 }
1033
1034
1035 static void
1036 copy_ctinfo (CI dest, CI src) {
1037 PM s_pm, d_pm;
1038
1039 dest->ci_type = src->ci_type ? add (src->ci_type, NULL) : NULL;
1040 dest->ci_subtype = src->ci_subtype ? add (src->ci_subtype, NULL) : NULL;
1041
1042 for (s_pm = src->ci_first_pm; s_pm; s_pm = s_pm->pm_next) {
1043 d_pm = add_param(&dest->ci_first_pm, &dest->ci_last_pm, s_pm->pm_name,
1044 s_pm->pm_value, 0);
1045 if (s_pm->pm_charset)
1046 d_pm->pm_charset = getcpy(s_pm->pm_charset);
1047 if (s_pm->pm_lang)
1048 d_pm->pm_lang = getcpy(s_pm->pm_lang);
1049 }
1050
1051 dest->ci_comment = src->ci_comment ? add (src->ci_comment, NULL) : NULL;
1052 dest->ci_magic = src->ci_magic ? add (src->ci_magic, NULL) : NULL;
1053 }
1054
1055
1056 static int
1057 decode_part (CT ct) {
1058 char *tmp_decoded;
1059 int status;
1060 char *tempfile;
1061
1062 if ((tempfile = m_mktemp2 (NULL, invo_name, NULL, NULL)) == NULL) {
1063 adios (NULL, "unable to create temporary file in %s", get_temp_dir());
1064 }
1065 tmp_decoded = add (tempfile, NULL);
1066 /* The following call will load ct->c_cefile.ce_file with the tmp
1067 filename of the decoded content. tmp_decoded will contain the
1068 encoded output, get rid of that. */
1069 status = output_message (ct, tmp_decoded);
1070 (void) m_unlink (tmp_decoded);
1071 free (tmp_decoded);
1072
1073 return status;
1074 }
1075
1076
1077 /* Some of the arguments aren't really needed now, but maybe will
1078 be in the future for other than text types. */
1079 static int
1080 reformat_part (CT ct, char *file, char *type, char *subtype, int c_type) {
1081 int output_subtype, output_encoding;
1082 char *cp, *cf;
1083 int status;
1084
1085 /* Hacky: this redirects the output from whatever command is used
1086 to show the part to a file. So, the user can't have any output
1087 redirection in that command.
1088 Could show_multi() in mhshowsbr.c avoid this? */
1089
1090 /* Check for invo_name-format-type/subtype. */
1091 if ((cf = context_find_by_type ("format", type, subtype)) == NULL) {
1092 if (verbosw) {
1093 advise (NULL, "Don't know how to convert %s, there is no "
1094 "%s-format-%s/%s profile entry",
1095 ct->c_file, invo_name, type, subtype);
1096 }
1097 return NOTOK;
1098 } else {
1099 if (strchr (cf, '>')) {
1100 advise (NULL, "'>' prohibited in \"%s\",\nplease fix your "
1101 "%s-format-%s/%s profile entry", cf, invo_name, type,
1102 subtype ? subtype : "");
1103
1104 return NOTOK;
1105 }
1106 }
1107
1108 cp = concat (cf, " >", file, NULL);
1109 status = show_content_aux (ct, 0, cp, NULL, NULL);
1110 free (cp);
1111
1112 /* Unlink decoded content tmp file and free its filename to avoid
1113 leaks. The file stream should already have been closed. */
1114 if (ct->c_cefile.ce_unlink) {
1115 (void) m_unlink (ct->c_cefile.ce_file);
1116 free (ct->c_cefile.ce_file);
1117 ct->c_cefile.ce_file = NULL;
1118 ct->c_cefile.ce_unlink = 0;
1119 }
1120
1121 if (c_type == CT_TEXT) {
1122 output_subtype = TEXT_PLAIN;
1123 } else {
1124 /* Set subtype to 0, which is always an UNKNOWN subtype. */
1125 output_subtype = 0;
1126 }
1127 output_encoding = charset_encoding (ct);
1128
1129 if (set_ct_type (ct, c_type, output_subtype, output_encoding) == OK) {
1130 ct->c_cefile.ce_file = file;
1131 ct->c_cefile.ce_unlink = 1;
1132 } else {
1133 ct->c_cefile.ce_unlink = 0;
1134 status = NOTOK;
1135 }
1136
1137 return status;
1138 }
1139
1140
1141 /* Identifies 7bit or 8bit content based on charset. */
1142 static int
1143 charset_encoding (CT ct) {
1144 char *ct_charset = content_charset (ct);
1145 int encoding = strcasecmp (ct_charset, "US-ASCII") ? CE_8BIT : CE_7BIT;
1146
1147 free (ct_charset);
1148
1149 return encoding;
1150 }
1151
1152
1153 static CT
1154 build_multipart_alt (CT first_alt, CT new_part, int type, int subtype) {
1155 char *boundary_prefix = "----=_nmh-multipart";
1156 char *boundary = concat (boundary_prefix, first_alt->c_partno, NULL);
1157 char *boundary_indicator = "; boundary=";
1158 char *typename, *subtypename, *name;
1159 CT ct;
1160 struct part *p;
1161 struct multipart *m;
1162 const struct str2init *ctinit;
1163
1164 if ((ct = (CT) mh_xcalloc (1, sizeof *ct)) == NULL)
1165 adios (NULL, "out of memory");
1166
1167 /* Set up the multipart/alternative part. These fields of *ct were
1168 initialized to 0 by mh_xcalloc():
1169 c_fp, c_unlink, c_begin, c_end,
1170 c_vrsn, c_ctline, c_celine,
1171 c_id, c_descr, c_dispo, c_partno,
1172 c_ctinfo.ci_comment, c_ctinfo.ci_magic,
1173 c_cefile, c_encoding,
1174 c_digested, c_digest[16], c_ctexbody,
1175 c_ctinitfnx, c_ceopenfnx, c_ceclosefnx, c_cesizefnx,
1176 c_umask, c_rfc934,
1177 c_showproc, c_termproc, c_storeproc, c_storage, c_folder
1178 */
1179
1180 ct->c_file = add (first_alt->c_file, NULL);
1181 ct->c_type = type;
1182 ct->c_subtype = subtype;
1183
1184 ctinit = get_ct_init (ct->c_type);
1185
1186 typename = ct_type_str (type);
1187 subtypename = ct_subtype_str (type, subtype);
1188
1189 {
1190 int serial = 0;
1191 int found_boundary = 1;
1192
1193 while (found_boundary && serial < 1000000) {
1194 found_boundary = 0;
1195
1196 /* Ensure that the boundary doesn't appear in the decoded
1197 content. */
1198 if (new_part->c_cefile.ce_file) {
1199 if ((found_boundary =
1200 boundary_in_content (&new_part->c_cefile.ce_fp,
1201 new_part->c_cefile.ce_file,
1202 boundary)) == -1) {
1203 free (ct);
1204 return NULL;
1205 }
1206 }
1207
1208 /* Ensure that the boundary doesn't appear in the encoded
1209 content. */
1210 if (! found_boundary && new_part->c_file) {
1211 if ((found_boundary = boundary_in_content (&new_part->c_fp,
1212 new_part->c_file,
1213 boundary)) == -1) {
1214 free (ct);
1215 return NULL;
1216 }
1217 }
1218
1219 if (found_boundary) {
1220 /* Try a slightly different boundary. */
1221 char buffer2[16];
1222
1223 free (boundary);
1224 ++serial;
1225 snprintf (buffer2, sizeof buffer2, "%d", serial);
1226 boundary =
1227 concat (boundary_prefix,
1228 first_alt->c_partno ? first_alt->c_partno : "",
1229 "-", buffer2, NULL);
1230 }
1231 }
1232
1233 if (found_boundary) {
1234 advise (NULL, "giving up trying to find a unique boundary");
1235 free (ct);
1236 return NULL;
1237 }
1238 }
1239
1240 name = concat (" ", typename, "/", subtypename, boundary_indicator, "\"",
1241 boundary, "\"", NULL);
1242
1243 /* Load c_first_hf and c_last_hf. */
1244 transfer_noncontent_headers (first_alt, ct);
1245 add_header (ct, add (TYPE_FIELD, NULL), concat (name, "\n", NULL));
1246 free (name);
1247
1248 /* Load c_partno. */
1249 if (first_alt->c_partno) {
1250 ct->c_partno = add (first_alt->c_partno, NULL);
1251 free (first_alt->c_partno);
1252 first_alt->c_partno = concat (ct->c_partno, ".1", NULL);
1253 new_part->c_partno = concat (ct->c_partno, ".2", NULL);
1254 } else {
1255 first_alt->c_partno = add ("1", NULL);
1256 new_part->c_partno = add ("2", NULL);
1257 }
1258
1259 if (ctinit) {
1260 ct->c_ctinfo.ci_type = add (typename, NULL);
1261 ct->c_ctinfo.ci_subtype = add (subtypename, NULL);
1262 }
1263
1264 add_param(&ct->c_ctinfo.ci_first_pm, &ct->c_ctinfo.ci_last_pm,
1265 "boundary", boundary, 0);
1266
1267 p = (struct part *) mh_xmalloc (sizeof *p);
1268 p->mp_next = (struct part *) mh_xmalloc (sizeof *p->mp_next);
1269 p->mp_next->mp_next = NULL;
1270 p->mp_next->mp_part = first_alt;
1271
1272 if ((m = (struct multipart *) mh_xcalloc (1, sizeof (struct multipart))) ==
1273 NULL)
1274 adios (NULL, "out of memory");
1275 m->mp_start = concat (boundary, "\n", NULL);
1276 m->mp_stop = concat (boundary, "--\n", NULL);
1277 m->mp_parts = p;
1278 ct->c_ctparams = m;
1279
1280 free (boundary);
1281
1282 return ct;
1283 }
1284
1285
1286 /* Check that the boundary does not appear in the content. */
1287 static int
1288 boundary_in_content (FILE **fp, char *file, const char *boundary) {
1289 char buffer[BUFSIZ];
1290 size_t bytes_read;
1291 int found_boundary = 0;
1292
1293 /* free_content() will close *fp if we fopen it here. */
1294 if (! *fp && (*fp = fopen (file, "r")) == NULL) {
1295 advise (file, "unable to open %s for reading", file);
1296 return NOTOK;
1297 }
1298
1299 fseeko (*fp, 0L, SEEK_SET);
1300 while ((bytes_read = fread (buffer, 1, sizeof buffer, *fp)) > 0) {
1301 if (find_str (buffer, bytes_read, boundary)) {
1302 found_boundary = 1;
1303 break;
1304 }
1305 }
1306
1307 return found_boundary;
1308 }
1309
1310
1311 /* Remove all non-Content headers. */
1312 static void
1313 transfer_noncontent_headers (CT old, CT new) {
1314 HF hp, hp_prev;
1315
1316 hp_prev = hp = old->c_first_hf;
1317 while (hp) {
1318 HF next = hp->next;
1319
1320 if (strncasecmp (XXX_FIELD_PRF, hp->name, strlen (XXX_FIELD_PRF))) {
1321 if (hp == old->c_last_hf) {
1322 if (hp == old->c_first_hf) {
1323 old->c_last_hf = old->c_first_hf = NULL;
1324 } else {
1325 hp_prev->next = NULL;
1326 old->c_last_hf = hp_prev;
1327 }
1328 } else {
1329 if (hp == old->c_first_hf) {
1330 old->c_first_hf = next;
1331 } else {
1332 hp_prev->next = next;
1333 }
1334 }
1335
1336 /* Put node hp in the new CT. */
1337 if (new->c_first_hf == NULL) {
1338 new->c_first_hf = hp;
1339 } else {
1340 new->c_last_hf->next = hp;
1341 }
1342 new->c_last_hf = hp;
1343 } else {
1344 /* A Content- header, leave in old. */
1345 hp_prev = hp;
1346 }
1347
1348 hp = next;
1349 }
1350 }
1351
1352
1353 static int
1354 set_ct_type (CT ct, int type, int subtype, int encoding) {
1355 char *typename = ct_type_str (type);
1356 char *subtypename = ct_subtype_str (type, subtype);
1357 /* E.g, " text/plain" */
1358 char *type_subtypename = concat (" ", typename, "/", subtypename, NULL);
1359 /* E.g, " text/plain\n" */
1360 char *name_plus_nl = concat (type_subtypename, "\n", NULL);
1361 int found_content_type = 0;
1362 HF hf;
1363 const char *cp = NULL;
1364 char *ctline;
1365 int status;
1366
1367 /* Update/add Content-Type header field. */
1368 for (hf = ct->c_first_hf; hf; hf = hf->next) {
1369 if (! strcasecmp (TYPE_FIELD, hf->name)) {
1370 found_content_type = 1;
1371 free (hf->value);
1372 hf->value = (cp = strchr (ct->c_ctline, ';'))
1373 ? concat (type_subtypename, cp, "\n", NULL)
1374 : add (name_plus_nl, NULL);
1375 }
1376 }
1377 if (! found_content_type) {
1378 add_header (ct, add (TYPE_FIELD, NULL),
1379 (cp = strchr (ct->c_ctline, ';'))
1380 ? concat (type_subtypename, cp, "\n", NULL)
1381 : add (name_plus_nl, NULL));
1382 }
1383
1384 /* Some of these might not be used, but set them anyway. */
1385 ctline = cp
1386 ? concat (type_subtypename, cp, NULL)
1387 : concat (type_subtypename, NULL);
1388 free (ct->c_ctline);
1389 ct->c_ctline = ctline;
1390 /* Leave other ctinfo members as they were. */
1391 free (ct->c_ctinfo.ci_type);
1392 ct->c_ctinfo.ci_type = add (typename, NULL);
1393 free (ct->c_ctinfo.ci_subtype);
1394 ct->c_ctinfo.ci_subtype = add (subtypename, NULL);
1395 ct->c_type = type;
1396 ct->c_subtype = subtype;
1397
1398 free (name_plus_nl);
1399 free (type_subtypename);
1400
1401 status = set_ce (ct, encoding);
1402
1403 return status;
1404 }
1405
1406
1407 static int
1408 decode_text_parts (CT ct, int encoding, int *message_mods) {
1409 int status = OK;
1410
1411 switch (ct->c_type) {
1412 case CT_TEXT:
1413 switch (ct->c_encoding) {
1414 case CE_BASE64:
1415 case CE_QUOTED: {
1416 int ct_encoding;
1417
1418 if (decode_part (ct) == OK && ct->c_cefile.ce_file) {
1419 const char *reason = NULL;
1420
1421 if ((ct_encoding = content_encoding (ct, &reason)) == CE_BINARY
1422 && encoding != CE_BINARY) {
1423 /* The decoding isn't acceptable so discard it.
1424 Leave status as OK to allow other transformations. */
1425 if (verbosw) {
1426 report (NULL, ct->c_partno, ct->c_file,
1427 "will not decode%s because it is binary (%s)",
1428 ct->c_partno ? ""
1429 : ct->c_ctline ? ct->c_ctline
1430 : "",
1431 reason);
1432 }
1433 (void) m_unlink (ct->c_cefile.ce_file);
1434 free (ct->c_cefile.ce_file);
1435 ct->c_cefile.ce_file = NULL;
1436 } else if (ct->c_encoding == CE_QUOTED &&
1437 ct_encoding == CE_8BIT && encoding == CE_7BIT) {
1438 /* The decoding isn't acceptable so discard it.
1439 Leave status as OK to allow other transformations. */
1440 if (verbosw) {
1441 report (NULL, ct->c_partno, ct->c_file,
1442 "will not decode%s because it is 8bit",
1443 ct->c_partno ? ""
1444 : ct->c_ctline ? ct->c_ctline
1445 : "");
1446 }
1447 (void) m_unlink (ct->c_cefile.ce_file);
1448 free (ct->c_cefile.ce_file);
1449 ct->c_cefile.ce_file = NULL;
1450 } else {
1451 int enc;
1452 if (ct_encoding == CE_BINARY)
1453 enc = CE_BINARY;
1454 else if (ct_encoding == CE_8BIT && encoding == CE_7BIT)
1455 enc = CE_QUOTED;
1456 else
1457 enc = charset_encoding (ct);
1458 if (set_ce (ct, enc) == OK) {
1459 ++*message_mods;
1460 if (verbosw) {
1461 report (NULL, ct->c_partno, ct->c_file, "decode%s",
1462 ct->c_ctline ? ct->c_ctline : "");
1463 }
1464 strip_crs (ct, message_mods);
1465 } else {
1466 status = NOTOK;
1467 }
1468 }
1469 } else {
1470 status = NOTOK;
1471 }
1472 break;
1473 }
1474 case CE_8BIT:
1475 case CE_7BIT:
1476 strip_crs (ct, message_mods);
1477 break;
1478 default:
1479 break;
1480 }
1481
1482 break;
1483
1484 case CT_MULTIPART: {
1485 struct multipart *m = (struct multipart *) ct->c_ctparams;
1486 struct part *part;
1487
1488 /* Should check to see if the body for this part is encoded?
1489 For now, it gets passed along as-is by InitMultiPart(). */
1490 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
1491 status = decode_text_parts (part->mp_part, encoding, message_mods);
1492 }
1493 break;
1494 }
1495
1496 case CT_MESSAGE:
1497 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1498 struct exbody *e = (struct exbody *) ct->c_ctparams;
1499
1500 status = decode_text_parts (e->eb_content, encoding, message_mods);
1501 }
1502 break;
1503
1504 default:
1505 break;
1506 }
1507
1508 return status;
1509 }
1510
1511
1512 /* See if the decoded content is 7bit, 8bit, or binary. It's binary
1513 if it has any NUL characters, a CR not followed by a LF, or lines
1514 greater than 998 characters in length. If binary, reason is set
1515 to a string explaining why. */
1516 static int
1517 content_encoding (CT ct, const char **reason) {
1518 CE ce = &ct->c_cefile;
1519 int encoding = CE_7BIT;
1520
1521 if (ce->ce_file) {
1522 size_t line_len = 0;
1523 char buffer[BUFSIZ];
1524 size_t inbytes;
1525
1526 if (! ce->ce_fp && (ce->ce_fp = fopen (ce->ce_file, "r")) == NULL) {
1527 advise (ce->ce_file, "unable to open for reading");
1528 return CE_UNKNOWN;
1529 }
1530
1531 fseeko (ce->ce_fp, 0L, SEEK_SET);
1532 while (encoding != CE_BINARY &&
1533 (inbytes = fread (buffer, 1, sizeof buffer, ce->ce_fp)) > 0) {
1534 char *cp;
1535 size_t i;
1536 int last_char_was_cr = 0;
1537
1538 for (i = 0, cp = buffer; i < inbytes; ++i, ++cp) {
1539 if (*cp == '\0' || ++line_len > 998 ||
1540 (*cp != '\n' && last_char_was_cr)) {
1541 encoding = CE_BINARY;
1542 if (*cp == '\0') {
1543 *reason = "null character";
1544 } else if (line_len > 998) {
1545 *reason = "line length > 998";
1546 } else if (*cp != '\n' && last_char_was_cr) {
1547 *reason = "CR not followed by LF";
1548 } else {
1549 /* Should not reach this. */
1550 *reason = "";
1551 }
1552 break;
1553 } else if (*cp == '\n') {
1554 line_len = 0;
1555 } else if (! isascii ((unsigned char) *cp)) {
1556 encoding = CE_8BIT;
1557 }
1558
1559 last_char_was_cr = *cp == '\r' ? 1 : 0;
1560 }
1561 }
1562
1563 fclose (ce->ce_fp);
1564 ce->ce_fp = NULL;
1565 } /* else should never happen */
1566
1567 return encoding;
1568 }
1569
1570
1571 static int
1572 strip_crs (CT ct, int *message_mods) {
1573 char *charset = content_charset (ct);
1574 int status = OK;
1575
1576 /* Only strip carriage returns if content is ASCII or another
1577 charset that has the same readily recognizable CR followed by a
1578 LF. We can include UTF-8 here because if the high-order bit of
1579 a UTF-8 byte is 0, then it must be a single-byte ASCII
1580 character. */
1581 if (! strcasecmp (charset, "US-ASCII") ||
1582 ! strcasecmp (charset, "UTF-8") ||
1583 ! strncasecmp (charset, "ISO-8859-", 9) ||
1584 ! strncasecmp (charset, "WINDOWS-12", 10)) {
1585 char **file = NULL;
1586 FILE **fp = NULL;
1587 size_t begin;
1588 size_t end;
1589 int has_crs = 0;
1590 int opened_input_file = 0;
1591
1592 if (ct->c_cefile.ce_file) {
1593 file = &ct->c_cefile.ce_file;
1594 fp = &ct->c_cefile.ce_fp;
1595 begin = end = 0;
1596 } else if (ct->c_file) {
1597 file = &ct->c_file;
1598 fp = &ct->c_fp;
1599 begin = (size_t) ct->c_begin;
1600 end = (size_t) ct->c_end;
1601 } /* else don't know where the content is */
1602
1603 if (file && *file && fp) {
1604 if (! *fp) {
1605 if ((*fp = fopen (*file, "r")) == NULL) {
1606 advise (*file, "unable to open for reading");
1607 status = NOTOK;
1608 } else {
1609 opened_input_file = 1;
1610 }
1611 }
1612 }
1613
1614 if (fp && *fp) {
1615 char buffer[BUFSIZ];
1616 size_t bytes_read;
1617 size_t bytes_to_read =
1618 end > 0 && end > begin ? end - begin : sizeof buffer;
1619
1620 fseeko (*fp, begin, SEEK_SET);
1621 while ((bytes_read = fread (buffer, 1,
1622 min (bytes_to_read, sizeof buffer),
1623 *fp)) > 0) {
1624 /* Look for CR followed by a LF. This is supposed to
1625 be text so there should be LF's. If not, don't
1626 modify the content. */
1627 char *cp;
1628 size_t i;
1629 int last_char_was_cr = 0;
1630
1631 if (end > 0) { bytes_to_read -= bytes_read; }
1632
1633 for (i = 0, cp = buffer; i < bytes_read; ++i, ++cp) {
1634 if (*cp == '\n' && last_char_was_cr) {
1635 has_crs = 1;
1636 break;
1637 }
1638
1639 last_char_was_cr = *cp == '\r' ? 1 : 0;
1640 }
1641 }
1642
1643 if (has_crs) {
1644 int fd;
1645 char *stripped_content_file;
1646 char *tempfile = m_mktemp2 (NULL, invo_name, &fd, NULL);
1647
1648 if (tempfile == NULL) {
1649 adios (NULL, "unable to create temporary file in %s",
1650 get_temp_dir());
1651 }
1652 stripped_content_file = add (tempfile, NULL);
1653
1654 /* Strip each CR before a LF from the content. */
1655 fseeko (*fp, begin, SEEK_SET);
1656 while ((bytes_read = fread (buffer, 1, sizeof buffer, *fp)) >
1657 0) {
1658 char *cp;
1659 size_t i;
1660 int last_char_was_cr = 0;
1661
1662 for (i = 0, cp = buffer; i < bytes_read; ++i, ++cp) {
1663 if (*cp == '\r') {
1664 last_char_was_cr = 1;
1665 } else if (last_char_was_cr) {
1666 if (*cp != '\n') {
1667 if (write (fd, "\r", 1) < 0) {
1668 advise (tempfile, "CR write");
1669 }
1670 }
1671 if (write (fd, cp, 1) < 0) {
1672 advise (tempfile, "write");
1673 }
1674 last_char_was_cr = 0;
1675 } else {
1676 if (write (fd, cp, 1) < 0) {
1677 advise (tempfile, "write");
1678 }
1679 last_char_was_cr = 0;
1680 }
1681 }
1682 }
1683
1684 if (close (fd)) {
1685 admonish (NULL, "unable to write temporary file %s",
1686 stripped_content_file);
1687 (void) m_unlink (stripped_content_file);
1688 status = NOTOK;
1689 } else {
1690 /* Replace the decoded file with the converted one. */
1691 if (ct->c_cefile.ce_file) {
1692 if (ct->c_cefile.ce_unlink) {
1693 (void) m_unlink (ct->c_cefile.ce_file);
1694 }
1695 free (ct->c_cefile.ce_file);
1696 }
1697 ct->c_cefile.ce_file = stripped_content_file;
1698 ct->c_cefile.ce_unlink = 1;
1699
1700 ++*message_mods;
1701 if (verbosw) {
1702 report (NULL, ct->c_partno,
1703 begin == 0 && end == 0 ? "" : *file,
1704 "stripped CRs");
1705 }
1706 }
1707 }
1708
1709 if (opened_input_file) {
1710 fclose (*fp);
1711 *fp = NULL;
1712 }
1713 }
1714 }
1715
1716 free (charset);
1717
1718 return status;
1719 }
1720
1721
1722 static int
1723 convert_charsets (CT ct, char *dest_charset, int *message_mods) {
1724 int status = OK;
1725
1726 switch (ct->c_type) {
1727 case CT_TEXT:
1728 if (ct->c_subtype == TEXT_PLAIN) {
1729 status = convert_charset (ct, dest_charset, message_mods);
1730 if (status == OK) {
1731 if (verbosw) {
1732 char *ct_charset = content_charset (ct);
1733
1734 report (NULL, ct->c_partno, ct->c_file,
1735 "convert %s to %s", ct_charset, dest_charset);
1736 free (ct_charset);
1737 }
1738 } else {
1739 char *ct_charset = content_charset (ct);
1740
1741 report ("iconv", ct->c_partno, ct->c_file,
1742 "failed to convert %s to %s", ct_charset, dest_charset);
1743 free (ct_charset);
1744 }
1745 }
1746 break;
1747
1748 case CT_MULTIPART: {
1749 struct multipart *m = (struct multipart *) ct->c_ctparams;
1750 struct part *part;
1751
1752 /* Should check to see if the body for this part is encoded?
1753 For now, it gets passed along as-is by InitMultiPart(). */
1754 for (part = m->mp_parts; status == OK && part; part = part->mp_next) {
1755 status =
1756 convert_charsets (part->mp_part, dest_charset, message_mods);
1757 }
1758 break;
1759 }
1760
1761 case CT_MESSAGE:
1762 if (ct->c_subtype == MESSAGE_EXTERNAL) {
1763 struct exbody *e = (struct exbody *) ct->c_ctparams;
1764
1765 status =
1766 convert_charsets (e->eb_content, dest_charset, message_mods);
1767 }
1768 break;
1769
1770 default:
1771 break;
1772 }
1773
1774 return status;
1775 }
1776
1777
1778 static int
1779 write_content (CT ct, char *input_filename, char *outfile, int modify_inplace,
1780 int message_mods) {
1781 int status = OK;
1782
1783 if (modify_inplace) {
1784 if (message_mods > 0) {
1785 if ((status = output_message (ct, outfile)) == OK) {
1786 char *infile = input_filename
1787 ? add (input_filename, NULL)
1788 : add (ct->c_file ? ct->c_file : "-", NULL);
1789
1790 if (remove_file (infile) == OK) {
1791 if (rename (outfile, infile)) {
1792 /* Rename didn't work, possibly because of an
1793 attempt to rename across filesystems. Try
1794 brute force copy. */
1795 int old = open (outfile, O_RDONLY);
1796 int new =
1797 open (infile, O_WRONLY | O_CREAT, m_gmprot ());
1798 int i = -1;
1799
1800 if (old != -1 && new != -1) {
1801 char buffer[BUFSIZ];
1802
1803 while ((i = read (old, buffer, sizeof buffer)) >
1804 0) {
1805 if (write (new, buffer, i) != i) {
1806 i = -1;
1807 break;
1808 }
1809 }
1810 }
1811 if (new != -1) { close (new); }
1812 if (old != -1) { close (old); }
1813 (void) m_unlink (outfile);
1814
1815 if (i < 0) {
1816 /* The -file argument processing used path() to
1817 expand filename to absolute path. */
1818 int file = ct->c_file && ct->c_file[0] == '/';
1819
1820 admonish (NULL, "unable to rename %s %s to %s",
1821 file ? "file" : "message", outfile,
1822 infile);
1823 status = NOTOK;
1824 }
1825 }
1826 } else {
1827 admonish (NULL, "unable to remove input file %s, "
1828 "not modifying it", infile);
1829 (void) m_unlink (outfile);
1830 status = NOTOK;
1831 }
1832
1833 free (infile);
1834 } else {
1835 status = NOTOK;
1836 }
1837 } else {
1838 /* No modifications and didn't need the tmp outfile. */
1839 (void) m_unlink (outfile);
1840 }
1841 } else {
1842 /* Output is going to some file. Produce it whether or not
1843 there were modifications. */
1844 status = output_message (ct, outfile);
1845 }
1846
1847 flush_errors ();
1848 return status;
1849 }
1850
1851
1852 /*
1853 * If "rmmproc" is defined, call that to remove the file. Otherwise,
1854 * use the standard MH backup file.
1855 */
1856 static int
1857 remove_file (char *file) {
1858 if (rmmproc) {
1859 char *rmm_command = concat (rmmproc, " ", file, NULL);
1860 int status = system (rmm_command);
1861
1862 free (rmm_command);
1863 return WIFEXITED (status) ? WEXITSTATUS (status) : NOTOK;
1864 } else {
1865 /* This is OK for a non-message file, it still uses the
1866 BACKUP_PREFIX form. The backup file will be in the same
1867 directory as file. */
1868 return rename (file, m_backup (file));
1869 }
1870 }
1871
1872
1873 static void
1874 report (char *what, char *partno, char *filename, char *message, ...) {
1875 va_list args;
1876 char *fmt;
1877
1878 if (verbosw) {
1879 va_start (args, message);
1880 fmt = concat (filename, partno ? " part " : ", ",
1881 partno ? partno : "", partno ? ", " : "", message, NULL);
1882
1883 advertise (what, NULL, fmt, args);
1884
1885 free (fmt);
1886 va_end (args);
1887 }
1888 }
1889
1890
1891 static void
1892 pipeser (int i)
1893 {
1894 if (i == SIGQUIT) {
1895 fflush (stdout);
1896 fprintf (stderr, "\n");
1897 fflush (stderr);
1898 }
1899
1900 done (1);
1901 /* NOTREACHED */
1902 }