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