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