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