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