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