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