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