]> diplodocus.org Git - nmh/blob - uip/mhstoresbr.c
5d995492c217000e47bf718c99c75a6287897357
[nmh] / uip / mhstoresbr.c
1 /* mhstoresbr.c -- routines to save/store the contents of MIME messages
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include "h/mh.h"
9 #include "sbr/path.h"
10 #include "sbr/error.h"
11 #include <fcntl.h>
12 #include "h/md5.h"
13 #include "h/mts.h"
14 #include "h/tws.h"
15 #include "h/fmt_scan.h"
16 #include "h/mime.h"
17 #include "h/mhparse.h"
18 #include "h/utils.h"
19 #include "mhmisc.h"
20 #include "mhshowsbr.h"
21 #include "sbr/m_maildir.h"
22 #include "sbr/m_mktemp.h"
23
24 enum clobber_policy_t {
25 NMH_CLOBBER_ALWAYS = 0,
26 NMH_CLOBBER_AUTO,
27 NMH_CLOBBER_SUFFIX,
28 NMH_CLOBBER_ASK,
29 NMH_CLOBBER_NEVER
30 };
31
32 static enum clobber_policy_t clobber_policy (const char *) PURE;
33
34 struct mhstoreinfo {
35 CT *cts; /* Top-level list of contents to store. */
36 char *cwd; /* cached current directory */
37 int autosw; /* -auto enabled */
38 int verbosw; /* -verbose enabled */
39 int files_not_clobbered; /* output flag indicating that store failed
40 in order to not clobber an existing file */
41
42 /* The following must never be touched by a caller: they are for
43 internal use by the mhstoresbr functions. */
44 char *dir; /* directory in which to store contents */
45 enum clobber_policy_t clobber_policy; /* -clobber selection */
46 };
47
48 static bool use_param_as_filename(const char *p);
49
50 mhstoreinfo_t
51 mhstoreinfo_create (CT *ct, char *pwd, const char *csw, int asw, int vsw)
52 {
53 mhstoreinfo_t info;
54
55 NEW(info);
56 info->cts = ct;
57 info->cwd = pwd;
58 info->autosw = asw;
59 info->verbosw = vsw;
60 info->files_not_clobbered = 0;
61 info->dir = NULL;
62 info->clobber_policy = clobber_policy (csw);
63
64 return info;
65 }
66
67 void
68 mhstoreinfo_free (mhstoreinfo_t info)
69 {
70 free (info->cwd);
71 free (info->dir);
72 free (info);
73 }
74
75 int
76 mhstoreinfo_files_not_clobbered (const mhstoreinfo_t info)
77 {
78 return info->files_not_clobbered;
79 }
80
81
82 /*
83 * Type for a compare function for qsort. This keeps
84 * the compiler happy.
85 */
86 typedef int (*qsort_comp) (const void *, const void *);
87
88
89 /*
90 * static prototypes
91 */
92 static void store_single_message (CT, mhstoreinfo_t);
93 static int store_switch (CT, mhstoreinfo_t);
94 static int store_generic (CT, mhstoreinfo_t);
95 static int store_application (CT, mhstoreinfo_t);
96 static int store_multi (CT, mhstoreinfo_t);
97 static int store_partial (CT, mhstoreinfo_t);
98 static int store_external (CT, mhstoreinfo_t);
99 static int ct_compar (CT *, CT *);
100 static int store_content (CT, CT, mhstoreinfo_t);
101 static int output_content_file (CT, int);
102 static int output_content_folder (char *, char *);
103 static int parse_format_string (CT, char *, char *, int, char *);
104 static void get_storeproc (CT);
105 static int copy_some_headers (FILE *, CT);
106 static char *clobber_check (char *, mhstoreinfo_t);
107
108 /*
109 * Main entry point to store content
110 * from a collection of messages.
111 */
112
113 void
114 store_all_messages (mhstoreinfo_t info)
115 {
116 CT ct, *ctp;
117 char *cp;
118
119 /*
120 * Check for the directory in which to
121 * store any contents.
122 */
123 if ((cp = context_find (nmhstorage)) && *cp)
124 info->dir = mh_xstrdup(cp);
125 else
126 info->dir = getcpy (info->cwd);
127
128 for (ctp = info->cts; *ctp; ctp++) {
129 ct = *ctp;
130 store_single_message (ct, info);
131 }
132
133 flush_errors ();
134 }
135
136
137 /*
138 * Entry point to store the content
139 * in a (single) message
140 */
141
142 static void
143 store_single_message (CT ct, mhstoreinfo_t info)
144 {
145 if (type_ok (ct, 1)) {
146 umask (ct->c_umask);
147 store_switch (ct, info);
148 if (ct->c_fp) {
149 fclose (ct->c_fp);
150 ct->c_fp = NULL;
151 }
152 if (ct->c_ceclosefnx)
153 (*ct->c_ceclosefnx) (ct);
154 }
155 }
156
157
158 /*
159 * Switching routine to store different content types
160 */
161
162 static int
163 store_switch (CT ct, mhstoreinfo_t info)
164 {
165 switch (ct->c_type) {
166 case CT_MULTIPART:
167 return store_multi (ct, info);
168
169 case CT_MESSAGE:
170 switch (ct->c_subtype) {
171 case MESSAGE_PARTIAL:
172 return store_partial (ct, info);
173
174 case MESSAGE_EXTERNAL:
175 return store_external (ct, info);
176
177 case MESSAGE_RFC822:
178 default:
179 return store_generic (ct, info);
180 }
181
182 case CT_APPLICATION:
183 default:
184 return store_application (ct, info);
185
186 case CT_TEXT:
187 case CT_AUDIO:
188 case CT_IMAGE:
189 case CT_VIDEO:
190 return store_generic (ct, info);
191 }
192
193 return OK; /* NOT REACHED */
194 }
195
196
197 /*
198 * Generic routine to store a MIME content.
199 * (audio, video, image, text, message/rfc822)
200 */
201
202 static int
203 store_generic (CT ct, mhstoreinfo_t info)
204 {
205 /*
206 * Check if the content specifies a filename.
207 * Don't bother with this for type "message"
208 * (only "message/rfc822" will use store_generic).
209 */
210 if (info->autosw && ct->c_type != CT_MESSAGE)
211 get_storeproc (ct);
212
213 return store_content (ct, NULL, info);
214 }
215
216
217 /*
218 * Store content of type "application"
219 */
220
221 static int
222 store_application (CT ct, mhstoreinfo_t info)
223 {
224 CI ci = &ct->c_ctinfo;
225
226 /* Check if the content specifies a filename */
227 if (info->autosw)
228 get_storeproc (ct);
229
230 /*
231 * If storeproc is not defined, and the content is type
232 * "application/octet-stream", we also check for various
233 * attribute/value pairs which specify if this a tar file.
234 */
235 if (!ct->c_storeproc && ct->c_subtype == APPLICATION_OCTETS) {
236 bool tarP = false;
237 bool zP = false;
238 bool gzP = false;
239 char *cp;
240
241 if ((cp = get_param(ci->ci_first_pm, "type", ' ', 1))) {
242 if (strcasecmp (cp, "tar") == 0)
243 tarP = true;
244 }
245
246 /* check for "conversions=compress" attribute */
247 if ((cp = get_param(ci->ci_first_pm, "conversions", ' ', 1)) ||
248 (cp = get_param(ci->ci_first_pm, "x-conversions", ' ', 1))) {
249 if (strcasecmp (cp, "compress") == 0 ||
250 strcasecmp (cp, "x-compress") == 0) {
251 zP = true;
252 }
253 if (strcasecmp (cp, "gzip") == 0 ||
254 strcasecmp (cp, "x-gzip") == 0) {
255 gzP = true;
256 }
257 }
258
259 if (tarP) {
260 ct->c_showproc = add (zP ? "%euncompress | tar tvf -"
261 : (gzP ? "%egzip -dc | tar tvf -"
262 : "%etar tvf -"), NULL);
263 if (!ct->c_storeproc) {
264 if (info->autosw) {
265 ct->c_storeproc = add (zP ? "| uncompress | tar xvpf -"
266 : (gzP ? "| gzip -dc | tar xvpf -"
267 : "| tar xvpf -"), NULL);
268 ct->c_umask = 0022;
269 } else {
270 ct->c_storeproc= add (zP ? "%m%P.tar.Z"
271 : (gzP ? "%m%P.tar.gz"
272 : "%m%P.tar"), NULL);
273 }
274 }
275 }
276 }
277
278 return store_content (ct, NULL, info);
279 }
280
281
282 /*
283 * Store the content of a multipart message
284 */
285
286 static int
287 store_multi (CT ct, mhstoreinfo_t info)
288 {
289 int result;
290 struct multipart *m = (struct multipart *) ct->c_ctparams;
291 struct part *part;
292
293 result = NOTOK;
294 for (part = m->mp_parts; part; part = part->mp_next) {
295 CT p = part->mp_part;
296
297 if (part_ok (p) && type_ok (p, 1)) {
298 if (ct->c_storage) {
299 /* Support mhstore -outfile. The MIME parser doesn't
300 load c_storage, so we know that p->c_storage is
301 NULL here. */
302 p->c_storage = mh_xstrdup(ct->c_storage);
303 }
304 result = store_switch (p, info);
305
306 if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
307 break;
308 }
309 }
310
311 return result;
312 }
313
314
315 /*
316 * Reassemble and store the contents of a collection
317 * of messages of type "message/partial".
318 */
319
320 static int
321 store_partial (CT ct, mhstoreinfo_t info)
322 {
323 int cur, hi, i;
324 CT p, *ctp, *ctq;
325 CT *base;
326 struct partial *pm, *qm;
327
328 qm = (struct partial *) ct->c_ctparams;
329 if (qm->pm_stored)
330 return OK;
331
332 hi = i = 0;
333 for (ctp = info->cts; *ctp; ctp++) {
334 p = *ctp;
335 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
336 pm = (struct partial *) p->c_ctparams;
337 if (!pm->pm_stored
338 && strcmp (qm->pm_partid, pm->pm_partid) == 0) {
339 pm->pm_marked = pm->pm_partno;
340 if (pm->pm_maxno)
341 hi = pm->pm_maxno;
342 pm->pm_stored = 1;
343 i++;
344 }
345 else
346 pm->pm_marked = 0;
347 }
348 }
349
350 if (hi == 0) {
351 inform("missing (at least) last part of multipart message");
352 return NOTOK;
353 }
354
355 base = mh_xcalloc(i + 1, sizeof *base);
356 ctq = base;
357 for (ctp = info->cts; *ctp; ctp++) {
358 p = *ctp;
359 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
360 pm = (struct partial *) p->c_ctparams;
361 if (pm->pm_marked)
362 *ctq++ = p;
363 }
364 }
365 *ctq = NULL;
366
367 if (i > 1)
368 qsort(base, i, sizeof(*base), (qsort_comp) ct_compar);
369
370 cur = 1;
371 for (ctq = base; *ctq; ctq++) {
372 p = *ctq;
373 pm = (struct partial *) p->c_ctparams;
374 if (pm->pm_marked == cur) {
375 cur++;
376 continue;
377 }
378
379 if (pm->pm_marked == cur - 1) {
380 inform("duplicate part %d of %d part multipart message, continuing...",
381 pm->pm_marked, hi);
382 continue;
383 }
384
385 missing_part:
386 inform("missing %spart %d of %d part multipart message",
387 cur != hi ? "(at least) " : "", cur, hi);
388 goto losing;
389 }
390 if (hi != --cur) {
391 cur = hi;
392 goto missing_part;
393 }
394
395 /*
396 * Now cycle through the sorted list of messages of type
397 * "message/partial" and save/append them to a file.
398 */
399
400 ctq = base;
401 ct = *ctq++;
402 if (store_content (ct, NULL, info) == NOTOK) {
403 losing:
404 free(base);
405 return NOTOK;
406 }
407
408 for (; *ctq; ctq++) {
409 p = *ctq;
410 if (store_content (p, ct, info) == NOTOK)
411 goto losing;
412 }
413
414 free(base);
415 return OK;
416 }
417
418
419 /*
420 * Store content from a message of type "message/external".
421 */
422
423 static int
424 store_external (CT ct, mhstoreinfo_t info)
425 {
426 int result = NOTOK;
427 struct exbody *e = (struct exbody *) ct->c_ctparams;
428 CT p = e->eb_content;
429
430 if (!type_ok (p, 1))
431 return OK;
432
433 /*
434 * Check if the parameters for the external body
435 * specified a filename.
436 */
437 if (info->autosw) {
438 char *cp;
439
440 if ((cp = e->eb_name) && use_param_as_filename(cp)) {
441 if (!ct->c_storeproc)
442 ct->c_storeproc = mh_xstrdup(cp);
443 if (!p->c_storeproc)
444 p->c_storeproc = mh_xstrdup(cp);
445 }
446 }
447
448 /*
449 * Since we will let the Content structure for the
450 * external body substitute for the current content,
451 * we temporarily change its partno (number inside
452 * multipart), so everything looks right.
453 */
454 p->c_partno = ct->c_partno;
455
456 /* we probably need to check if content is really there */
457 if (ct->c_storage) {
458 /* Support mhstore -outfile. The MIME parser doesn't load
459 c_storage, so we know that p->c_storage is NULL here. */
460 p->c_storage = mh_xstrdup(ct->c_storage);
461 }
462 result = store_switch (p, info);
463
464 p->c_partno = NULL;
465 return result;
466 }
467
468
469 /*
470 * Compare the numbering from two different
471 * message/partials (needed for sorting).
472 */
473
474 static int
475 ct_compar (CT *a, CT *b)
476 {
477 struct partial *am = (struct partial *) ((*a)->c_ctparams);
478 struct partial *bm = (struct partial *) ((*b)->c_ctparams);
479
480 return am->pm_marked - bm->pm_marked;
481 }
482
483
484 /*
485 * Store contents of a message or message part to
486 * a folder, a file, the standard output, or pass
487 * the contents to a command.
488 *
489 * If the current content to be saved is a followup part
490 * to a collection of messages of type "message/partial",
491 * then field "p" is a pointer to the Content structure
492 * to the first message/partial in the group.
493 */
494
495 static int
496 store_content (CT ct, CT p, mhstoreinfo_t info)
497 {
498 bool appending = false;
499 int msgnum = 0;
500 bool is_partial = false;
501 bool first_partial = false;
502 bool last_partial = false;
503 char *cp, buffer[BUFSIZ];
504
505 /*
506 * Do special processing for messages of
507 * type "message/partial".
508 *
509 * We first check if this content is of type
510 * "message/partial". If it is, then we need to check
511 * whether it is the first and/or last in the group.
512 *
513 * Then if "p" is a valid pointer, it points to the Content
514 * structure of the first partial in the group. So we copy
515 * the file name and/or folder name from that message. In
516 * this case, we also note that we will be appending.
517 */
518 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
519 struct partial *pm = (struct partial *) ct->c_ctparams;
520
521 /* Yep, it's a message/partial */
522 is_partial = true;
523
524 /* But is it the first and/or last in the collection? */
525 if (pm->pm_partno == 1)
526 first_partial = true;
527 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
528 last_partial = true;
529
530 /*
531 * If "p" is a valid pointer, then it points to the
532 * Content structure for the first message in the group.
533 * So we just copy the filename or foldername information
534 * from the previous iteration of this function.
535 */
536 if (p) {
537 appending = true;
538 if (! ct->c_storage) {
539 ct->c_storage = mh_xstrdup(FENDNULL(p->c_storage));
540
541 /* record the folder name */
542 if (p->c_folder) {
543 ct->c_folder = mh_xstrdup(p->c_folder);
544 }
545 }
546 goto got_filename;
547 }
548 }
549
550 /*
551 * Get storage formatting string.
552 *
553 * 1) If we have storeproc defined, then use that
554 * 2) Else check for a mhn-store-<type>/<subtype> entry
555 * 3) Else check for a mhn-store-<type> entry
556 * 4) Else if content is "message", use "+" (current folder)
557 * 5) Else use string "%m%P.%s".
558 */
559 if ((cp = ct->c_storeproc) == NULL || *cp == '\0') {
560 CI ci = &ct->c_ctinfo;
561
562 cp = context_find_by_type ("store", ci->ci_type, ci->ci_subtype);
563 if (cp == NULL) {
564 cp = ct->c_type == CT_MESSAGE ? "+" : "%m%P.%s";
565 }
566 }
567
568 if (! ct->c_storage) {
569 /*
570 * Check the beginning of storage formatting string
571 * to see if we are saving content to a folder.
572 */
573 if (*cp == '+' || *cp == '@') {
574 char *tmpfilenam, *folder;
575
576 /* Store content in temporary file for now */
577 if ((tmpfilenam = m_mktemp(invo_name, NULL, NULL)) == NULL) {
578 die("unable to create temporary file in %s",
579 get_temp_dir());
580 }
581 ct->c_storage = mh_xstrdup(tmpfilenam);
582
583 /* Get the folder name */
584 if (cp[1])
585 folder = pluspath (cp);
586 else
587 folder = getfolder (1);
588
589 /* Check if folder exists */
590 create_folder(m_mailpath(folder), 0, exit);
591
592 /* Record the folder name */
593 ct->c_folder = mh_xstrdup(folder);
594
595 if (cp[1])
596 free (folder);
597
598 goto got_filename;
599 }
600
601 /*
602 * Parse and expand the storage formatting string
603 * in `cp' into `buffer'.
604 */
605 parse_format_string (ct, cp, buffer, sizeof(buffer), info->dir);
606
607 /*
608 * If formatting begins with '|' or '!', then pass
609 * content to standard input of a command and return.
610 */
611 if (buffer[0] == '|' || buffer[0] == '!')
612 return show_content_aux (ct, 0, buffer + 1, info->dir, NULL);
613
614 /* record the filename */
615 if ((ct->c_storage = clobber_check (mh_xstrdup(buffer), info)) ==
616 NULL) {
617 return NOTOK;
618 }
619 } else {
620 /* The output filename was explicitly specified, so use it. */
621 if ((ct->c_storage = clobber_check (ct->c_storage, info)) ==
622 NULL) {
623 return NOTOK;
624 }
625 }
626
627 got_filename:
628 /* flush the output stream */
629 fflush (stdout);
630
631 /* Now save or append the content to a file */
632 if (output_content_file (ct, appending) == NOTOK)
633 return NOTOK;
634
635 /*
636 * If necessary, link the file into a folder and remove
637 * the temporary file. If this message is a partial,
638 * then only do this if it is the last one in the group.
639 */
640 if (ct->c_folder && (!is_partial || last_partial)) {
641 msgnum = output_content_folder (ct->c_folder, ct->c_storage);
642 (void) m_unlink (ct->c_storage);
643 if (msgnum == NOTOK)
644 return NOTOK;
645 }
646
647 if (info->verbosw) {
648 /*
649 * Now print out the name/number of the message
650 * that we are storing.
651 */
652 if (is_partial) {
653 if (first_partial)
654 fprintf (stderr, "reassembling partials ");
655 if (last_partial)
656 fputs(ct->c_file, stderr);
657 else
658 fprintf (stderr, "%s,", ct->c_file);
659 } else {
660 fprintf (stderr, "storing message %s", ct->c_file);
661 if (ct->c_partno)
662 fprintf (stderr, " part %s", ct->c_partno);
663 }
664
665 /*
666 * Unless we are in the "middle" of group of message/partials,
667 * we now print the name of the file, folder, and/or message
668 * to which we are storing the content.
669 */
670 if (!is_partial || last_partial) {
671 if (ct->c_folder) {
672 fprintf (stderr, " to folder %s as message %d\n", ct->c_folder,
673 msgnum);
674 } else if (!strcmp(ct->c_storage, "-")) {
675 fprintf (stderr, " to stdout\n");
676 } else {
677 int cwdlen = strlen (info->cwd);
678
679 fprintf (stderr, " as file %s\n",
680 !has_prefix(ct->c_storage, info->cwd)
681 || ct->c_storage[cwdlen] != '/'
682 ? ct->c_storage : ct->c_storage + cwdlen + 1);
683 }
684 }
685 }
686
687 return OK;
688 }
689
690
691 /*
692 * Output content to a file
693 */
694
695 static int
696 output_content_file (CT ct, int appending)
697 {
698 int filterstate;
699 char *file, buffer[BUFSIZ];
700 long pos, last;
701 FILE *fp;
702
703 /*
704 * If the pathname is absolute, make sure
705 * all the relevant directories exist.
706 */
707 if (strchr(ct->c_storage, '/')
708 && make_intermediates (ct->c_storage) == NOTOK)
709 return NOTOK;
710
711 if (ct->c_encoding != CE_7BIT) {
712 int cc, fd;
713
714 if (!ct->c_ceopenfnx) {
715 inform("don't know how to decode part %s of message %s",
716 ct->c_partno, ct->c_file);
717 return NOTOK;
718 }
719
720 file = appending || !strcmp (ct->c_storage, "-") ? NULL
721 : ct->c_storage;
722 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
723 return NOTOK;
724 if (!strcmp (file, ct->c_storage)) {
725 (*ct->c_ceclosefnx) (ct);
726 return OK;
727 }
728
729 /*
730 * Send to standard output
731 */
732 if (!strcmp (ct->c_storage, "-")) {
733 int gd;
734
735 if ((gd = dup (fileno (stdout))) == NOTOK) {
736 advise ("stdout", "unable to dup");
737 losing:
738 (*ct->c_ceclosefnx) (ct);
739 return NOTOK;
740 }
741 if ((fp = fdopen (gd, appending ? "a" : "w")) == NULL) {
742 advise ("stdout", "unable to fdopen (%d, \"%s\") from", gd,
743 appending ? "a" : "w");
744 close (gd);
745 goto losing;
746 }
747 } else {
748 /*
749 * Open output file
750 */
751 if ((fp = fopen (ct->c_storage, appending ? "a" : "w")) == NULL) {
752 advise (ct->c_storage, "unable to fopen for %s",
753 appending ? "appending" : "writing");
754 goto losing;
755 }
756 }
757
758 /*
759 * Filter the header fields of the initial enclosing
760 * message/partial into the file.
761 */
762 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
763 struct partial *pm = (struct partial *) ct->c_ctparams;
764
765 if (pm->pm_partno == 1)
766 copy_some_headers (fp, ct);
767 }
768
769 for (;;) {
770 switch (cc = read (fd, buffer, sizeof(buffer))) {
771 case NOTOK:
772 advise (file, "error reading content from");
773 break;
774
775 case OK:
776 break;
777
778 default:
779 if ((int) fwrite (buffer, sizeof(*buffer), cc, fp) < cc) {
780 advise ("output_content_file", "fwrite");
781 }
782 continue;
783 }
784 break;
785 }
786
787 (*ct->c_ceclosefnx) (ct);
788
789 if (cc != NOTOK && fflush (fp))
790 advise (ct->c_storage, "error writing to");
791
792 fclose (fp);
793
794 return cc == NOTOK ? NOTOK : OK;
795 }
796
797 if (!ct->c_fp && (ct->c_fp = fopen (ct->c_file, "r")) == NULL) {
798 advise (ct->c_file, "unable to open for reading");
799 return NOTOK;
800 }
801
802 pos = ct->c_begin;
803 last = ct->c_end;
804 fseek (ct->c_fp, pos, SEEK_SET);
805
806 if (!strcmp (ct->c_storage, "-")) {
807 int gd;
808
809 if ((gd = dup (fileno (stdout))) == NOTOK) {
810 advise ("stdout", "unable to dup");
811 return NOTOK;
812 }
813 if ((fp = fdopen (gd, appending ? "a" : "w")) == NULL) {
814 advise ("stdout", "unable to fdopen (%d, \"%s\") from", gd,
815 appending ? "a" : "w");
816 close (gd);
817 return NOTOK;
818 }
819 } else {
820 if ((fp = fopen (ct->c_storage, appending ? "a" : "w")) == NULL) {
821 advise (ct->c_storage, "unable to fopen for %s",
822 appending ? "appending" : "writing");
823 return NOTOK;
824 }
825 }
826
827 /*
828 * Copy a few of the header fields of the initial
829 * enclosing message/partial into the file.
830 */
831 filterstate = 0;
832 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
833 struct partial *pm = (struct partial *) ct->c_ctparams;
834
835 if (pm->pm_partno == 1) {
836 copy_some_headers (fp, ct);
837 filterstate = 1;
838 }
839 }
840
841 while (fgets (buffer, sizeof buffer, ct->c_fp)) {
842 if ((pos += strlen (buffer)) > last) {
843 int diff;
844
845 diff = strlen (buffer) - (pos - last);
846 if (diff >= 0)
847 buffer[diff] = '\0';
848 }
849 /*
850 * If this is the first content of a group of
851 * message/partial contents, then we only copy a few
852 * of the header fields of the enclosed message.
853 */
854 if (filterstate) {
855 switch (buffer[0]) {
856 case ' ':
857 case '\t':
858 if (filterstate < 0)
859 buffer[0] = 0;
860 break;
861
862 case '\n':
863 filterstate = 0;
864 break;
865
866 default:
867 if (!uprf (buffer, XXX_FIELD_PRF)
868 && !uprf (buffer, VRSN_FIELD)
869 && !uprf (buffer, "Subject:")
870 && !uprf (buffer, "Encrypted:")
871 && !uprf (buffer, "Message-ID:")) {
872 filterstate = -1;
873 buffer[0] = 0;
874 break;
875 }
876 filterstate = 1;
877 break;
878 }
879 }
880 fputs (buffer, fp);
881 if (pos >= last)
882 break;
883 }
884
885 if (fflush (fp))
886 advise (ct->c_storage, "error writing to");
887
888 fclose (fp);
889 fclose (ct->c_fp);
890 ct->c_fp = NULL;
891 return OK;
892 }
893
894
895 /*
896 * Add a file to a folder.
897 *
898 * Return the new message number of the file
899 * when added to the folder. Return -1, if
900 * there is an error.
901 */
902
903 static int
904 output_content_folder (char *folder, char *filename)
905 {
906 int msgnum;
907 struct msgs *mp;
908
909 /* Read the folder. */
910 if (!(mp = folder_read(folder, 0))) {
911 inform("unable to read folder %s", folder);
912 return NOTOK;
913 }
914 /* Link file into folder */
915 msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
916
917 /* free folder structure */
918 folder_free (mp);
919
920 /*
921 * Return msgnum. We are relying on the fact that
922 * msgnum will be -1, if folder_addmsg() had an error.
923 */
924 return msgnum;
925 }
926
927
928 /*
929 * Parse and expand the storage formatting string
930 * pointed to by "cp" into "buffer".
931 */
932
933 static int
934 parse_format_string (CT ct, char *cp, char *buffer, int buflen, char *dir)
935 {
936 int len;
937 char *bp;
938 CI ci = &ct->c_ctinfo;
939
940 /*
941 * If storage string is "-", just copy it, and
942 * return (send content to standard output).
943 */
944 if (cp[0] == '-' && cp[1] == '\0') {
945 strncpy (buffer, cp, buflen);
946 return 0;
947 }
948
949 bp = buffer;
950 bp[0] = '\0';
951
952 /*
953 * If formatting string is a pathname that doesn't
954 * begin with '/', then preface the path with the
955 * appropriate directory.
956 */
957 if (*cp != '/' && *cp != '|' && *cp != '!') {
958 if (!strcmp(dir, "/"))
959 dir = ""; /* Don't start with "//". */
960 snprintf (bp, buflen, "%s/", dir);
961 len = strlen (bp);
962 bp += len;
963 buflen -= len;
964 }
965
966 for (; *cp; cp++) {
967
968 /* We are processing a storage escape */
969 if (*cp == '%') {
970 switch (*++cp) {
971 case 'a':
972 /*
973 * Insert parameters from Content-Type.
974 * This is only valid for '|' commands.
975 */
976 if (buffer[0] != '|' && buffer[0] != '!') {
977 *bp++ = *--cp;
978 *bp = '\0';
979 buflen--;
980 continue;
981 }
982 {
983 PM pm;
984 char *s = "";
985
986 for (pm = ci->ci_first_pm; pm; pm = pm->pm_next) {
987 snprintf (bp, buflen, "%s%s=\"%s\"", s,
988 pm->pm_name, get_param_value(pm, '?'));
989 len = strlen (bp);
990 bp += len;
991 buflen -= len;
992 s = " ";
993 }
994 }
995 break;
996
997 case 'm':
998 /* insert message number */
999 snprintf (bp, buflen, "%s", r1bindex (ct->c_file, '/'));
1000 break;
1001
1002 case 'P':
1003 /* insert part number with leading dot */
1004 if (ct->c_partno)
1005 snprintf (bp, buflen, ".%s", ct->c_partno);
1006 break;
1007
1008 case 'p':
1009 /* insert part number without leading dot */
1010 if (ct->c_partno)
1011 strncpy (bp, ct->c_partno, buflen);
1012 break;
1013
1014 case 't':
1015 /* insert content type */
1016 strncpy (bp, ci->ci_type, buflen);
1017 break;
1018
1019 case 's':
1020 /* insert content subtype */
1021 strncpy (bp, ci->ci_subtype, buflen);
1022 break;
1023
1024 case '%':
1025 /* insert the character % */
1026 goto raw;
1027
1028 default:
1029 *bp++ = *--cp;
1030 *bp = '\0';
1031 buflen--;
1032 continue;
1033 }
1034
1035 /* Advance bp and decrement buflen */
1036 len = strlen (bp);
1037 bp += len;
1038 buflen -= len;
1039
1040 } else {
1041 raw:
1042 *bp++ = *cp;
1043 *bp = '\0';
1044 buflen--;
1045 }
1046 }
1047
1048 return 0;
1049 }
1050
1051
1052 /*
1053 * Check if the content specifies a filename
1054 * in its MIME parameters.
1055 */
1056
1057 static void
1058 get_storeproc (CT ct)
1059 {
1060 char *cp;
1061 CI ci;
1062
1063 /*
1064 * If the storeproc has already been defined,
1065 * we just return (for instance, if this content
1066 * is part of a "message/external".
1067 */
1068 if (ct->c_storeproc)
1069 return;
1070
1071 /*
1072 * If there's a Content-Disposition header and it has a filename,
1073 * use that (RFC-2183).
1074 */
1075 if (ct->c_dispo) {
1076 if ((cp = get_param(ct->c_dispo_first, "filename", '_', 0)) &&
1077 use_param_as_filename(cp)) {
1078 ct->c_storeproc = mh_xstrdup(cp);
1079 free(cp);
1080 return;
1081 }
1082 free(cp);
1083 }
1084
1085 /*
1086 * Check the attribute/value pairs, for the attribute "name".
1087 * If found, do a few sanity checks and copy the value into
1088 * the storeproc.
1089 */
1090 ci = &ct->c_ctinfo;
1091 if ((cp = get_param(ci->ci_first_pm, "name", '_', 0)) &&
1092 use_param_as_filename(cp)) {
1093 ct->c_storeproc = mh_xstrdup(cp);
1094
1095 }
1096 free(cp);
1097 }
1098
1099
1100 /*
1101 * Copy some of the header fields of the initial message/partial
1102 * message into the header of the reassembled message.
1103 */
1104
1105 static int
1106 copy_some_headers (FILE *out, CT ct)
1107 {
1108 HF hp;
1109
1110 hp = ct->c_first_hf; /* start at first header field */
1111
1112 while (hp) {
1113 /*
1114 * A few of the header fields of the enclosing
1115 * messages are not copied.
1116 */
1117 if (!uprf (hp->name, XXX_FIELD_PRF)
1118 && strcasecmp (hp->name, VRSN_FIELD)
1119 && strcasecmp (hp->name, "Subject")
1120 && strcasecmp (hp->name, "Encrypted")
1121 && strcasecmp (hp->name, "Message-ID"))
1122 fprintf (out, "%s:%s", hp->name, hp->value);
1123 hp = hp->next; /* next header field */
1124 }
1125
1126 return OK;
1127 }
1128
1129 /******************************************************************************/
1130 /* -clobber support */
1131
1132 static enum clobber_policy_t
1133 clobber_policy (const char *value)
1134 {
1135 if (value == NULL || ! strcasecmp (value, "always")) {
1136 return NMH_CLOBBER_ALWAYS;
1137 }
1138 if (! strcasecmp (value, "auto")) {
1139 return NMH_CLOBBER_AUTO;
1140 }
1141 if (! strcasecmp (value, "suffix")) {
1142 return NMH_CLOBBER_SUFFIX;
1143 }
1144 if (! strcasecmp (value, "ask")) {
1145 return NMH_CLOBBER_ASK;
1146 }
1147 if (! strcasecmp (value, "never")) {
1148 return NMH_CLOBBER_NEVER;
1149 }
1150
1151 die("invalid argument, %s, to clobber", value);
1152 }
1153
1154
1155 static char *
1156 next_version (char *file, enum clobber_policy_t clobber_policy)
1157 {
1158 const size_t max_versions = 1000000;
1159 /* 8 = log max_versions + one for - or . + one for null terminator */
1160 const size_t buflen = strlen (file) + 8;
1161 char *buffer = mh_xmalloc (buflen);
1162 size_t version;
1163
1164 char *extension = NULL;
1165 if (clobber_policy == NMH_CLOBBER_AUTO &&
1166 ((extension = strrchr (file, '.')) != NULL)) {
1167 *extension++ = '\0';
1168 }
1169
1170 for (version = 1; version < max_versions; ++version) {
1171 int fd;
1172
1173 switch (clobber_policy) {
1174 case NMH_CLOBBER_AUTO: {
1175 snprintf (buffer, buflen, "%s-%ld%s%s", file, (long) version,
1176 extension == NULL ? "" : ".",
1177 extension == NULL ? "" : extension);
1178 break;
1179 }
1180
1181 case NMH_CLOBBER_SUFFIX:
1182 snprintf (buffer, buflen, "%s.%ld", file, (long) version);
1183 break;
1184
1185 default:
1186 /* Should never get here. */
1187 inform("will not overwrite %s, invalid clobber policy", buffer);
1188 free (buffer);
1189 return NULL;
1190 }
1191
1192 /* Actually (try to) create the file here to avoid a race
1193 condition on file naming + creation. This won't solve the
1194 problem with old NFS that doesn't support O_EXCL, though.
1195 Let the umask strip off permissions from 0666 as desired.
1196 That's what fopen () would do if it was creating the file. */
1197 if ((fd = open (buffer, O_CREAT | O_EXCL,
1198 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
1199 S_IROTH | S_IWOTH)) >= 0) {
1200 close (fd);
1201 break;
1202 }
1203 }
1204
1205 free (file);
1206
1207 if (version >= max_versions) {
1208 inform("will not overwrite %s, too many versions", buffer);
1209 free (buffer);
1210 buffer = NULL;
1211 }
1212
1213 return buffer;
1214 }
1215
1216
1217 static char *
1218 clobber_check (char *original_file, mhstoreinfo_t info)
1219 {
1220 /* clobber policy return value
1221 * -------------- ------------
1222 * -always original_file
1223 * -auto original_file-<digits>.extension
1224 * -suffix original_file.<digits>
1225 * -ask original_file, 0, or another filename/path
1226 * -never 0
1227 */
1228
1229 char *file;
1230 char *cwd = NULL;
1231 bool check_again;
1232
1233 if (! strcmp (original_file, "-")) {
1234 return original_file;
1235 }
1236
1237 if (info->clobber_policy == NMH_CLOBBER_ASK) {
1238 /* Save cwd for possible use in loop below. */
1239 char *slash;
1240
1241 cwd = mh_xstrdup(original_file);
1242 slash = strrchr (cwd, '/');
1243
1244 if (slash) {
1245 *slash = '\0';
1246 } else {
1247 /* original_file isn't a full path, which should only happen if
1248 it is -. */
1249 free (cwd);
1250 cwd = NULL;
1251 }
1252 }
1253
1254 do {
1255 struct stat st;
1256
1257 file = original_file;
1258 check_again = false;
1259
1260 switch (info->clobber_policy) {
1261 case NMH_CLOBBER_ALWAYS:
1262 break;
1263
1264 case NMH_CLOBBER_SUFFIX:
1265 case NMH_CLOBBER_AUTO:
1266 if (stat (file, &st) == OK) {
1267 if ((file = next_version (original_file, info->clobber_policy)) ==
1268 NULL) {
1269 ++info->files_not_clobbered;
1270 }
1271 }
1272 break;
1273
1274 case NMH_CLOBBER_ASK:
1275 if (stat (file, &st) == OK) {
1276 enum answers { NMH_YES, NMH_NO, NMH_RENAME };
1277 static struct swit answer[4] = {
1278 { "yes", 0, NMH_YES },
1279 { "no", 0, NMH_NO },
1280 { "rename", 0, NMH_RENAME },
1281 { NULL, 0, 0 } };
1282 char **ans;
1283
1284 if (isatty (fileno (stdin))) {
1285 char *prompt =
1286 concat ("Overwrite \"", file, "\" [y/n/rename]? ", NULL);
1287 ans = read_switch_multiword (prompt, answer);
1288 free (prompt);
1289 } else {
1290 /* Overwrite, that's what nmh used to do. And warn. */
1291 inform("-clobber ask but no tty, so overwrite %s", file);
1292 break;
1293 }
1294
1295 switch ((enum answers) smatch (*ans, answer)) {
1296 case NMH_YES:
1297 break;
1298 case NMH_NO:
1299 free (file);
1300 file = NULL;
1301 ++info->files_not_clobbered;
1302 break;
1303 case NMH_RENAME: {
1304 char buf[PATH_MAX];
1305 fputs("Enter filename or full path of the new file: ", stdout);
1306 if (fgets (buf, sizeof buf, stdin) == NULL ||
1307 buf[0] == '\0') {
1308 file = NULL;
1309 ++info->files_not_clobbered;
1310 } else {
1311 trim_suffix_c(buf, '\n');
1312 }
1313
1314 free (file);
1315
1316 if (buf[0] == '/') {
1317 /* Full path, use it. */
1318 file = mh_xstrdup(buf);
1319 } else {
1320 /* Relative path. */
1321 file = cwd ? concat (cwd, "/", buf, NULL) : mh_xstrdup(buf);
1322 }
1323
1324 check_again = true;
1325 break;
1326 }
1327 }
1328 }
1329 break;
1330
1331 case NMH_CLOBBER_NEVER:
1332 if (stat (file, &st) == OK) {
1333 /* Keep count of files that would have been clobbered,
1334 and return that as process exit status. */
1335 inform("will not overwrite %s with -clobber never", file);
1336 free (file);
1337 file = NULL;
1338 ++info->files_not_clobbered;
1339 }
1340 break;
1341 }
1342
1343 original_file = file;
1344 } while (check_again);
1345
1346 free (cwd);
1347
1348 return file;
1349 }
1350
1351 static bool
1352 use_param_as_filename(const char *p)
1353 {
1354 /* Preserve result of original test that considered an empty string
1355 * OK. */
1356 return !*p || (!strchr("/.|!", *p) && !strchr(p, '%'));
1357 }
1358
1359 /* -clobber support */
1360 /******************************************************************************/