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