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