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