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