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