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