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