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