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