remove unnecessary casts
[mmh] / uip / mhstore.c
1 /*
2 ** mhstore.c -- store the contents of MIME messages
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <fcntl.h>
11 #include <h/signals.h>
12 #include <errno.h>
13 #include <signal.h>
14 #include <h/tws.h>
15 #include <h/mime.h>
16 #include <h/mhparse.h>
17 #include <h/utils.h>
18 #include <unistd.h>
19 #include <sys/stat.h>
20 #include <locale.h>
21 #include <sysexits.h>
22
23 static struct swit switches[] = {
24 #define AUTOSW  0
25         { "auto", 0 },
26 #define NAUTOSW  1
27         { "noauto", 2 },
28 #define FILESW  2  /* interface from show */
29         { "file file", 0 },
30 #define PARTSW  3
31         { "part number", 0 },
32 #define TYPESW  4
33         { "type content", 0 },
34 #define VERSIONSW  5
35         { "Version", 0 },
36 #define HELPSW  6
37         { "help", 0 },
38 #define DEBUGSW  7
39         { "debug", -5 },
40         { NULL, 0 }
41 };
42
43
44 /* mhparse.c */
45 extern char *tmp;  /* directory to place temp files */
46
47 /* mhmisc.c */
48 extern int npart;
49 extern int ntype;
50 extern char *parts[NPARTS + 1];
51 extern char *types[NTYPES + 1];
52 extern int userrs;
53
54 int debugsw = 0;
55
56 #define quitser pipeser
57
58 /* mhparse.c */
59 CT parse_mime(char *);
60
61 /* mhmisc.c */
62 int part_ok(CT, int);
63 int type_ok(CT, int);
64 void set_endian(void);
65 void flush_errors(void);
66
67 /* mhfree.c */
68 void free_content(CT);
69 extern CT *cts;  /* The list of top-level contents to display */
70 void freects_done();
71
72 /*
73 ** static prototypes
74 */
75 static void pipeser(int);
76
77 int autosw = 1;
78
79 /*
80 ** Cache of current directory.  This must be
81 ** set before these routines are called.
82 */
83 char *cwd;
84
85 /*
86 ** The directory in which to store the contents.
87 */
88 static char *dir;
89
90 /*
91 ** Type for a compare function for qsort.  This keeps
92 ** the compiler happy.
93 */
94 typedef int (*qsort_comp) (const void *, const void *);
95
96
97 /* mhmisc.c */
98 int part_ok(CT, int);
99 int type_ok(CT, int);
100 int make_intermediates(char *);
101 void flush_errors(void);
102
103 /* mhshowsbr.c */
104 int show_content_aux(CT, int, char *, char *);
105
106 /*
107 ** static prototypes
108 */
109 static void store_single_message(CT);
110 static int store_switch(CT);
111 static int store_generic(CT);
112 static int store_multi(CT);
113 static int store_partial(CT);
114 static int store_external(CT);
115 static int ct_compar(CT *, CT *);
116 static int store_content(CT, CT);
117 static int output_content_file(CT, int);
118 static int output_content_folder(char *, char *);
119 static int parse_format_string(CT, char *, char *, int, char *);
120 static int copy_some_headers(FILE *, CT);
121 static void store_all_messages(CT *);
122
123
124 int
125 main(int argc, char **argv)
126 {
127         int msgnum;
128         char *cp, *file = NULL, *folder = NULL;
129         char *maildir, buf[100], **argp;
130         char **arguments;
131         struct msgs_array msgs = { 0, 0, NULL };
132         struct msgs *mp = NULL;
133         CT ct, *ctp;
134         FILE *fp;
135
136         if (atexit(freects_done) != 0) {
137                 adios(EX_OSERR, NULL, "atexit failed");
138         }
139
140         setlocale(LC_ALL, "");
141         invo_name = mhbasename(argv[0]);
142
143         /* read user profile/context */
144         context_read();
145
146         arguments = getarguments(invo_name, argc, argv, 1);
147         argp = arguments;
148
149         /*
150         ** Parse arguments
151         */
152         while ((cp = *argp++)) {
153                 if (*cp == '-') {
154                         switch (smatch(++cp, switches)) {
155                         case AMBIGSW:
156                                 ambigsw(cp, switches);
157                                 exit(EX_USAGE);
158                         case UNKWNSW:
159                                 adios(EX_USAGE, NULL, "-%s unknown", cp);
160
161                         case HELPSW:
162                                 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
163                                 print_help(buf, switches, 1);
164                                 exit(argc == 2 ? EX_OK : EX_USAGE);
165                         case VERSIONSW:
166                                 print_version(invo_name);
167                                 exit(argc == 2 ? EX_OK : EX_USAGE);
168
169                         case AUTOSW:
170                                 autosw++;
171                                 continue;
172                         case NAUTOSW:
173                                 autosw = 0;
174                                 continue;
175
176                         case PARTSW:
177                                 if (!(cp = *argp++) || *cp == '-')
178                                         adios(EX_USAGE, NULL, "missing argument to %s",
179                                                         argp[-2]);
180                                 if (npart >= NPARTS)
181                                         adios(EX_USAGE, NULL, "too many parts (starting with %s), %d max", cp, NPARTS);
182                                 parts[npart++] = cp;
183                                 continue;
184
185                         case TYPESW:
186                                 if (!(cp = *argp++) || *cp == '-')
187                                         adios(EX_USAGE, NULL, "missing argument to %s",
188                                                         argp[-2]);
189                                 if (ntype >= NTYPES)
190                                         adios(EX_USAGE, NULL, "too many types (starting with %s), %d max", cp, NTYPES);
191                                 types[ntype++] = cp;
192                                 continue;
193
194                         case FILESW:
195                                 if (!(cp = *argp++) || (*cp == '-' && cp[1]))
196                                         adios(EX_USAGE, NULL, "missing argument to %s",
197                                                         argp[-2]);
198                                 file = *cp == '-' ? cp : getcpy(expanddir(cp));
199                                 continue;
200
201                         case DEBUGSW:
202                                 debugsw = 1;
203                                 continue;
204                         }
205                 }
206                 if (*cp == '+' || *cp == '@') {
207                         if (folder)
208                                 adios(EX_USAGE, NULL, "only one folder at a time!");
209                         else
210                                 folder = getcpy(expandfol(cp));
211                 } else
212                         app_msgarg(&msgs, cp);
213         }
214
215         /* null terminate the list of acceptable parts/types */
216         parts[npart] = NULL;
217         types[ntype] = NULL;
218
219         set_endian();
220
221         /*
222         ** Check if we've specified an additional profile
223         */
224         if ((cp = getenv("MHSTORE"))) {
225                 if ((fp = fopen(cp, "r"))) {
226                         readconfig((struct node **) 0, fp, cp, 0);
227                         fclose(fp);
228                 } else {
229                         admonish("", "unable to read $MHSTORE profile (%s)",
230                                         cp);
231                 }
232         }
233
234         /*
235         ** Read the standard profile setup
236         */
237         if ((fp = fopen(cp = etcpath("mhn.defaults"), "r"))) {
238                 readconfig((struct node **) 0, fp, cp, 0);
239                 fclose(fp);
240         }
241
242         /*
243         ** Cache the current directory before we do any chdirs()'s.
244         */
245         cwd = getcpy(pwd());
246
247         /*
248         ** Check for storage directory.  If specified,
249         ** then store temporary files there.  Else we
250         ** store them in standard nmh directory.
251         */
252         if ((cp = context_find(nmhstorage)) && *cp)
253                 tmp = concat(cp, "/", invo_name, NULL);
254         else
255                 tmp = getcpy(toabsdir(invo_name));
256
257         if (file && msgs.size)
258                 adios(EX_USAGE, NULL, "cannot specify msg and file at same time!");
259
260         /*
261         ** check if message is coming from file
262         */
263         if (file) {
264                 cts = mh_xcalloc(2, sizeof(*cts));
265                 ctp = cts;
266
267                 if ((ct = parse_mime(file)))
268                         *ctp++ = ct;
269         } else {
270                 /*
271                 ** message(s) are coming from a folder
272                 */
273                 if (!msgs.size)
274                         app_msgarg(&msgs, seq_cur);
275                 if (!folder)
276                         folder = getcurfol();
277                 maildir = toabsdir(folder);
278
279                 if (chdir(maildir) == NOTOK)
280                         adios(EX_OSERR, maildir, "unable to change directory to");
281
282                 /* read folder and create message structure */
283                 if (!(mp = folder_read(folder)))
284                         adios(EX_IOERR, NULL, "unable to read folder %s", folder);
285
286                 /* check for empty folder */
287                 if (mp->nummsg == 0)
288                         adios(EX_DATAERR, NULL, "no messages in %s", folder);
289
290                 /* parse all the message ranges/sequences and set SELECTED */
291                 for (msgnum = 0; msgnum < msgs.size; msgnum++)
292                         if (!m_convert(mp, msgs.msgs[msgnum]))
293                                 exit(EX_USAGE);
294                 seq_setprev(mp);  /* set the previous-sequence */
295
296                 cts = mh_xcalloc(mp->numsel + 1, sizeof(*cts));
297                 ctp = cts;
298
299                 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
300                         if (is_selected(mp, msgnum)) {
301                                 char *msgnam;
302
303                                 msgnam = m_name(msgnum);
304                                 if ((ct = parse_mime(msgnam)))
305                                         *ctp++ = ct;
306                         }
307                 }
308         }
309
310         if (!*cts)
311                 exit(EX_SOFTWARE);
312
313         userrs = 1;
314         SIGNAL(SIGQUIT, quitser);
315         SIGNAL(SIGPIPE, pipeser);
316
317         /*
318         ** Get the associated umask for the relevant contents.
319         */
320         for (ctp = cts; *ctp; ctp++) {
321                 struct stat st;
322
323                 ct = *ctp;
324                 if (type_ok(ct, 1) && !ct->c_umask) {
325                         if (stat(ct->c_file, &st) != NOTOK)
326                                 ct->c_umask = ~(st.st_mode & 0777);
327                         else
328                                 ct->c_umask = ~m_gmprot();
329                 }
330         }
331
332         /*
333         ** Store the message content
334         */
335         store_all_messages(cts);
336
337         /* Now free all the structures for the content */
338         for (ctp = cts; *ctp; ctp++)
339                 free_content(*ctp);
340
341         free((char *) cts);
342         cts = NULL;
343
344         /* If reading from a folder, do some updating */
345         if (mp) {
346                 context_replace(curfolder, folder); /* update current folder */
347                 seq_setcur(mp, mp->hghsel);  /* update current message */
348                 seq_save(mp);  /* synchronize sequences  */
349                 context_save();  /* save the context file  */
350         }
351
352         return 0;
353 }
354
355
356 static void
357 pipeser(int i)
358 {
359         if (i == SIGQUIT) {
360                 unlink("core");
361                 fflush(stdout);
362                 fprintf(stderr, "\n");
363                 fflush(stderr);
364                 exit(EX_TEMPFAIL);
365         }
366
367         exit(EX_IOERR);
368         /* NOTREACHED */
369 }
370
371
372 /*
373 ** Main entry point to store content from a collection of messages.
374 */
375 static void
376 store_all_messages(CT *cts)
377 {
378         CT ct, *ctp;
379         char *cp;
380
381         /*
382         ** Check for the directory in which to
383         ** store any contents.
384         */
385         if ((cp = context_find(nmhstorage)) && *cp)
386                 dir = getcpy(cp);
387         else
388                 dir = getcpy(cwd);
389
390         for (ctp = cts; *ctp; ctp++) {
391                 ct = *ctp;
392                 store_single_message(ct);
393         }
394
395         flush_errors();
396 }
397
398
399 /*
400 ** Entry point to store the content
401 ** in a (single) message
402 */
403
404 static void
405 store_single_message(CT ct)
406 {
407         if (type_ok(ct, 1)) {
408                 umask(ct->c_umask);
409                 store_switch(ct);
410                 if (ct->c_fp) {
411                         fclose(ct->c_fp);
412                         ct->c_fp = NULL;
413                 }
414                 if (ct->c_ceclosefnx)
415                         (*ct->c_ceclosefnx) (ct);
416         }
417 }
418
419
420 /*
421 ** Switching routine to store different content types
422 */
423
424 static int
425 store_switch(CT ct)
426 {
427         switch (ct->c_type) {
428         case CT_MULTIPART:
429                 return store_multi(ct);
430                 break;
431
432         case CT_MESSAGE:
433                 switch (ct->c_subtype) {
434                 case MESSAGE_PARTIAL:
435                         return store_partial(ct);
436                         break;
437
438                 case MESSAGE_EXTERNAL:
439                         return store_external(ct);
440
441                 case MESSAGE_RFC822:
442                 default:
443                         return store_generic(ct);
444                         break;
445                 }
446                 break;
447
448         case CT_APPLICATION:
449         case CT_TEXT:
450         case CT_AUDIO:
451         case CT_IMAGE:
452         case CT_VIDEO:
453                 return store_generic(ct);
454                 break;
455
456         default:
457                 adios(EX_DATAERR, NULL, "unknown content type %d", ct->c_type);
458                 break;
459         }
460
461         return OK;  /* NOT REACHED */
462 }
463
464
465 /*
466 ** Generic routine to store a MIME content.
467 ** (application, audio, video, image, text, message/rfc922)
468 */
469 static int
470 store_generic(CT ct)
471 {
472         char **ap, **vp, *cp;
473         CI ci = &ct->c_ctinfo;
474
475         /*
476         ** Check if the content specifies a filename in its MIME parameters.
477         ** Don't bother with this for type "message"
478         ** (only the "message" subtype "rfc822" will use store_generic).
479         */
480         if (autosw && ct->c_type != CT_MESSAGE) {
481                 /*
482                 ** Check the attribute/value pairs, for the attribute "name".
483                 ** If found, take the basename, do a few sanity checks and
484                 ** copy the value into c_storeproc.
485                 */
486                 for (ap = ci->ci_attrs, vp = ci->ci_values; *ap; ap++,vp++) {
487                         if (mh_strcasecmp(*ap, "name")!=0) {
488                                 continue;
489                         }
490                         cp = mhbasename(*vp);
491                         if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
492                                         !strchr(cp, '%')) {
493                                 /* filename looks good: use it */
494                                 ct->c_storeproc = getcpy(cp);
495                         }
496                         break;
497                 }
498         }
499
500         return store_content(ct, NULL);
501 }
502
503
504 /*
505 ** Store the content of a multipart message
506 */
507
508 static int
509 store_multi(CT ct)
510 {
511         int result;
512         struct multipart *m = (struct multipart *) ct->c_ctparams;
513         struct part *part;
514
515         result = NOTOK;
516         for (part = m->mp_parts; part; part = part->mp_next) {
517                 CT  p = part->mp_part;
518
519                 if (part_ok(p, 1) && type_ok(p, 1)) {
520                         result = store_switch(p);
521                         if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
522                                 break;
523                 }
524         }
525
526         return result;
527 }
528
529
530 /*
531 ** Reassemble and store the contents of a collection
532 ** of messages of type "message/partial".
533 */
534
535 static int
536 store_partial(CT ct)
537 {
538         int cur, hi, i;
539         CT p, *ctp, *ctq;
540         CT *base;
541         struct partial *pm, *qm;
542
543         qm = (struct partial *) ct->c_ctparams;
544         if (qm->pm_stored)
545                 return OK;
546
547         hi = i = 0;
548         for (ctp = cts; *ctp; ctp++) {
549                 p = *ctp;
550                 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
551                         pm = (struct partial *) p->c_ctparams;
552                         if (!pm->pm_stored &&
553                                         strcmp(qm->pm_partid, pm->pm_partid)
554                                         == 0) {
555                                 pm->pm_marked = pm->pm_partno;
556                                 if (pm->pm_maxno)
557                                         hi = pm->pm_maxno;
558                                 pm->pm_stored = 1;
559                                 i++;
560                         } else
561                                 pm->pm_marked = 0;
562                 }
563         }
564
565         if (hi == 0) {
566                 advise(NULL, "missing (at least) last part of multipart message");
567                 return NOTOK;
568         }
569
570         base = mh_xcalloc(i + 1, sizeof(*base));
571
572         ctq = base;
573         for (ctp = cts; *ctp; ctp++) {
574                 p = *ctp;
575                 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
576                         pm = (struct partial *) p->c_ctparams;
577                         if (pm->pm_marked)
578                                 *ctq++ = p;
579                 }
580         }
581         *ctq = NULL;
582
583         if (i > 1)
584                 qsort((char *) base, i, sizeof(*base), (qsort_comp) ct_compar);
585
586         cur = 1;
587         for (ctq = base; *ctq; ctq++) {
588                 p = *ctq;
589                 pm = (struct partial *) p->c_ctparams;
590                 if (pm->pm_marked != cur) {
591                         if (pm->pm_marked == cur - 1) {
592                                 admonish(NULL, "duplicate part %d of %d part multipart message", pm->pm_marked, hi);
593                                 continue;
594                         }
595
596 missing_part:
597                         advise (NULL, "missing %spart %d of %d part multipart message", cur != hi ? "(at least) " : "", cur, hi);
598                         goto losing;
599                 } else
600                         cur++;
601         }
602         if (hi != --cur) {
603                 cur = hi;
604                 goto missing_part;
605         }
606
607         /*
608         ** Now cycle through the sorted list of messages of type
609         ** "message/partial" and save/append them to a file.
610         */
611
612         ctq = base;
613         ct = *ctq++;
614         if (store_content(ct, NULL) == NOTOK) {
615 losing:
616                 free((char *) base);
617                 return NOTOK;
618         }
619
620         for (; *ctq; ctq++) {
621                 p = *ctq;
622                 if (store_content(p, ct) == NOTOK)
623                         goto losing;
624         }
625
626         free((char *) base);
627         return OK;
628 }
629
630
631 /*
632 ** Show how to retrieve content of type "message/external".
633 */
634 static int
635 store_external(CT ct)
636 {
637         char **ap, **ep;
638         char *msg;
639         FILE *fp;
640         char buf[BUFSIZ];
641
642         msg = add("You need to fetch the contents yourself:", NULL);
643         ap = ct->c_ctinfo.ci_attrs;
644         ep = ct->c_ctinfo.ci_values;
645         for (; *ap; ap++, ep++) {
646                 msg = add(concat("\n\t", *ap, ": ", *ep, NULL), msg);
647         }
648         if (!(fp = fopen(ct->c_file, "r"))) {
649                 adios(EX_IOERR, ct->c_file, "unable to open");
650         }
651         fseek(fp, ct->c_begin, SEEK_SET);
652         while (!feof(fp) && ftell(fp) < ct->c_end) {
653                 if (!fgets(buf, sizeof buf, fp)) {
654                         adios(EX_IOERR, ct->c_file, "unable to read");
655                 }
656                 *strchr(buf, '\n') = '\0';
657                 msg = add(concat("\n\t", buf, NULL), msg);
658         }
659         fclose(fp);
660         advise(NULL, msg);
661         return OK;
662 }
663
664
665 /*
666 ** Compare the numbering from two different
667 ** message/partials (needed for sorting).
668 */
669
670 static int
671 ct_compar(CT *a, CT *b)
672 {
673         struct partial *am = (struct partial *) ((*a)->c_ctparams);
674         struct partial *bm = (struct partial *) ((*b)->c_ctparams);
675
676         return (am->pm_marked - bm->pm_marked);
677 }
678
679
680 /*
681 ** Store contents of a message or message part to
682 ** a folder, a file, the standard output, or pass
683 ** the contents to a command.
684 **
685 ** If the current content to be saved is a followup part
686 ** to a collection of messages of type "message/partial",
687 ** then field "p" is a pointer to the Content structure
688 ** to the first message/partial in the group.
689 */
690
691 static int
692 store_content(CT ct, CT p)
693 {
694         int appending = 0, msgnum = 0;
695         int is_partial = 0, first_partial = 0;
696         int last_partial = 0;
697         char *cp, buffer[BUFSIZ];
698
699         /*
700         ** Do special processing for messages of
701         ** type "message/partial".
702         **
703         ** We first check if this content is of type
704         ** "message/partial".  If it is, then we need to check
705         ** whether it is the first and/or last in the group.
706         **
707         ** Then if "p" is a valid pointer, it points to the Content
708         ** structure of the first partial in the group.  So we copy
709         ** the file name and/or folder name from that message.  In
710         ** this case, we also note that we will be appending.
711         */
712         if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
713                 struct partial *pm = (struct partial *) ct->c_ctparams;
714
715                 /* Yep, it's a message/partial */
716                 is_partial = 1;
717
718                 /* But is it the first and/or last in the collection? */
719                 if (pm->pm_partno == 1)
720                         first_partial = 1;
721                 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
722                         last_partial = 1;
723
724                 /*
725                 ** If "p" is a valid pointer, then it points to the
726                 ** Content structure for the first message in the group.
727                 ** So we just copy the filename or foldername information
728                 ** from the previous iteration of this function.
729                 */
730                 if (p) {
731                         appending = 1;
732                         ct->c_storage = getcpy(p->c_storage);
733
734                         /* record the folder name */
735                         if (p->c_folder) {
736                                 ct->c_folder = getcpy(p->c_folder);
737                         }
738                         goto got_filename;
739                 }
740         }
741
742         /*
743         ** Get storage formatting string.
744         **
745         ** 1) If we have storeproc defined, then use that
746         ** 2) Else check for a mhstore-store-<type>/<subtype> entry
747         ** 3) Else check for a mhstore-store-<type> entry
748         ** 4) Else if content is "message", use "+" (current folder)
749         ** 5) Else use string "%m%P.%s".
750         */
751         if (!(cp = ct->c_storeproc) || !*cp) {
752                 CI ci = &ct->c_ctinfo;
753
754                 snprintf(buffer, sizeof(buffer), "%s-store-%s/%s",
755                                 invo_name, ci->ci_type, ci->ci_subtype);
756                 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
757                         snprintf(buffer, sizeof(buffer), "%s-store-%s",
758                                         invo_name, ci->ci_type);
759                         if ((cp = context_find(buffer)) == NULL ||
760                                         *cp == '\0') {
761                                 cp = ct->c_type == CT_MESSAGE ?
762                                                 "+" : "%m%P.%s";
763                         }
764                 }
765         }
766
767         /*
768         ** Check the beginning of storage formatting string
769         ** to see if we are saving content to a folder.
770         */
771         if (*cp == '+' || *cp == '@') {
772                 char *tmpfilenam, *folder;
773
774                 /* Store content in temporary file for now */
775                 tmpfilenam = m_mktemp(invo_name, NULL, NULL);
776                 ct->c_storage = getcpy(tmpfilenam);
777
778                 /* Get the folder name */
779                 if (cp[1])
780                         folder = getcpy(expandfol(cp));
781                 else
782                         folder = getcurfol();
783
784                 /* Check if folder exists */
785                 create_folder(toabsdir(folder), 0, exit);
786
787                 /* Record the folder name */
788                 ct->c_folder = getcpy(folder);
789
790                 if (cp[1])
791                         free(folder);
792
793                 goto got_filename;
794         }
795
796         /*
797         ** Parse and expand the storage formatting string
798         ** in `cp' into `buffer'.
799         */
800         parse_format_string(ct, cp, buffer, sizeof(buffer), dir);
801
802         /*
803         ** If formatting begins with '|' or '!', then pass
804         ** content to standard input of a command and return.
805         */
806         if (buffer[0] == '|' || buffer[0] == '!')
807                 return show_content_aux(ct, 0, buffer + 1, dir);
808
809         /* record the filename */
810         ct->c_storage = getcpy(buffer);
811
812 got_filename:
813         /* flush the output stream */
814         fflush(stdout);
815
816         /* Now save or append the content to a file */
817         if (output_content_file(ct, appending) == NOTOK)
818                 return NOTOK;
819
820         /*
821         ** If necessary, link the file into a folder and remove
822         ** the temporary file.  If this message is a partial,
823         ** then only do this if it is the last one in the group.
824         */
825         if (ct->c_folder && (!is_partial || last_partial)) {
826                 msgnum = output_content_folder(ct->c_folder, ct->c_storage);
827                 unlink(ct->c_storage);
828                 if (msgnum == NOTOK)
829                         return NOTOK;
830         }
831
832         /*
833         ** Now print out the name/number of the message
834         ** that we are storing.
835         */
836         if (is_partial) {
837                 if (first_partial)
838                         fprintf(stderr, "reassembling partials ");
839                 if (last_partial)
840                         fprintf(stderr, "%s", ct->c_file);
841                 else
842                         fprintf(stderr, "%s,", ct->c_file);
843         } else {
844                 fprintf(stderr, "storing message %s", ct->c_file);
845                 if (ct->c_partno)
846                         fprintf(stderr, " part %s", ct->c_partno);
847         }
848
849         /*
850         ** Unless we are in the "middle" of group of message/partials,
851         ** we now print the name of the file, folder, and/or message
852         ** to which we are storing the content.
853         */
854         if (!is_partial || last_partial) {
855                 if (ct->c_folder) {
856                         fprintf(stderr, " to folder %s as message %d\n",
857                                         ct->c_folder, msgnum);
858                 } else if (strcmp(ct->c_storage, "-")==0) {
859                         fprintf(stderr, " to stdout\n");
860                 } else {
861                         int cwdlen;
862
863                         cwdlen = strlen(cwd);
864                         fprintf(stderr, " as file %s\n",
865                                         strncmp(ct->c_storage, cwd,
866                                         cwdlen)!=0 ||
867                                         ct->c_storage[cwdlen] != '/' ?
868                                         ct->c_storage :
869                                         ct->c_storage + cwdlen + 1);
870                 }
871         }
872
873         return OK;
874 }
875
876
877 /*
878 ** Output content to a file
879 */
880
881 static int
882 output_content_file(CT ct, int appending)
883 {
884         int filterstate;
885         char *file, buffer[BUFSIZ];
886         long pos, last;
887         FILE *fp;
888
889         /*
890         ** If the pathname contains directories, make sure
891         ** all of them exist.
892         */
893         if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
894                         == NOTOK)
895                 return NOTOK;
896
897         if (ct->c_encoding != CE_7BIT) {
898                 int cc, fd;
899
900                 if (!ct->c_ceopenfnx) {
901                         advise(NULL, "don't know how to decode part %s of message %s", ct->c_partno, ct->c_file);
902                         return NOTOK;
903                 }
904
905                 file = appending || strcmp(ct->c_storage, "-")==0 ?
906                                 NULL : ct->c_storage;
907                 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
908                         return NOTOK;
909                 if (strcmp(file, ct->c_storage)==0) {
910                         (*ct->c_ceclosefnx) (ct);
911                         return OK;
912                 }
913
914                 /*
915                 ** Send to standard output
916                 */
917                 if (strcmp(ct->c_storage, "-")==0) {
918                         int gd;
919
920                         if ((gd = dup(fileno(stdout))) == NOTOK) {
921                                 advise("stdout", "unable to dup");
922 losing:
923                                 (*ct->c_ceclosefnx) (ct);
924                                 return NOTOK;
925                         }
926                         if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
927                                 advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
928                                 close(gd);
929                                 goto losing;
930                         }
931                 } else {
932                         /*
933                         ** Open output file
934                         */
935                         if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
936                                         == NULL) {
937                                 advise(ct->c_storage, "unable to fopen for %s",
938                                                 appending ?
939                                                 "appending" : "writing");
940                                 goto losing;
941                         }
942                 }
943
944                 /*
945                 ** Filter the header fields of the initial enclosing
946                 ** message/partial into the file.
947                 */
948                 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
949                         struct partial *pm = (struct partial *) ct->c_ctparams;
950
951                         if (pm->pm_partno == 1)
952                                 copy_some_headers(fp, ct);
953                 }
954
955                 for (;;) {
956                         switch (cc = read(fd, buffer, sizeof(buffer))) {
957                         case NOTOK:
958                                 advise(file, "error reading content from");
959                                 break;
960
961                         case OK:
962                                 break;
963
964                         default:
965                                 fwrite(buffer, sizeof(*buffer), cc, fp);
966                                 continue;
967                         }
968                         break;
969                 }
970
971                 (*ct->c_ceclosefnx) (ct);
972
973                 if (cc != NOTOK && fflush(fp))
974                         advise(ct->c_storage, "error writing to");
975
976                 fclose(fp);
977
978                 return (cc != NOTOK ? OK : NOTOK);
979         }
980
981         if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
982                 advise(ct->c_file, "unable to open for reading");
983                 return NOTOK;
984         }
985
986         pos = ct->c_begin;
987         last = ct->c_end;
988         fseek(ct->c_fp, pos, SEEK_SET);
989
990         if (strcmp(ct->c_storage, "-")==0) {
991                 int gd;
992
993                 if ((gd = dup(fileno(stdout))) == NOTOK) {
994                         advise("stdout", "unable to dup");
995                         return NOTOK;
996                 }
997                 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
998                         advise("stdout", "unable to fdopen (%d, \"%s\") from",
999                                         gd, appending ? "a" : "w");
1000                         close(gd);
1001                         return NOTOK;
1002                 }
1003         } else {
1004                 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
1005                                 == NULL) {
1006                         advise(ct->c_storage, "unable to fopen for %s",
1007                                         appending ? "appending" : "writing");
1008                         return NOTOK;
1009                 }
1010         }
1011
1012         /*
1013         ** Copy a few of the header fields of the initial
1014         ** enclosing message/partial into the file.
1015         */
1016         filterstate = 0;
1017         if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
1018                 struct partial *pm = (struct partial *) ct->c_ctparams;
1019
1020                 if (pm->pm_partno == 1) {
1021                         copy_some_headers(fp, ct);
1022                         filterstate = 1;
1023                 }
1024         }
1025
1026         while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
1027                 if ((pos += strlen(buffer)) > last) {
1028                         int diff;
1029
1030                         diff = strlen(buffer) - (pos - last);
1031                         if (diff >= 0)
1032                                 buffer[diff] = '\0';
1033                 }
1034                 /*
1035                 ** If this is the first content of a group of
1036                 ** message/partial contents, then we only copy a few
1037                 ** of the header fields of the enclosed message.
1038                 */
1039                 if (filterstate) {
1040                         switch (buffer[0]) {
1041                         case ' ':
1042                         case '\t':
1043                                 if (filterstate < 0)
1044                                         buffer[0] = 0;
1045                                 break;
1046
1047                         case '\n':
1048                                 filterstate = 0;
1049                                 break;
1050
1051                         default:
1052                                 if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
1053                                         filterstate = -1;
1054                                         buffer[0] = 0;
1055                                         break;
1056                                 }
1057                                 filterstate = 1;
1058                                 break;
1059                         }
1060                 }
1061                 fputs(buffer, fp);
1062                 if (pos >= last)
1063                         break;
1064         }
1065
1066         if (fflush(fp))
1067                 advise(ct->c_storage, "error writing to");
1068
1069         fclose(fp);
1070         fclose(ct->c_fp);
1071         ct->c_fp = NULL;
1072         return OK;
1073 }
1074
1075
1076 /*
1077 ** Add a file to a folder.
1078 **
1079 ** Return the new message number of the file
1080 ** when added to the folder.  Return -1, if
1081 ** there is an error.
1082 */
1083
1084 static int
1085 output_content_folder(char *folder, char *filename)
1086 {
1087         int msgnum;
1088         struct msgs *mp;
1089
1090         /* Read the folder. */
1091         if ((mp = folder_read(folder))) {
1092                 /* Link file into folder */
1093                 msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
1094         } else {
1095                 advise(NULL, "unable to read folder %s", folder);
1096                 return NOTOK;
1097         }
1098
1099         /* free folder structure */
1100         folder_free(mp);
1101
1102         /*
1103         ** Return msgnum.  We are relying on the fact that
1104         ** msgnum will be -1, if folder_addmsg() had an error.
1105         */
1106         return msgnum;
1107 }
1108
1109
1110 /*
1111 ** Parse and expand the storage formatting string
1112 ** pointed to by "cp" into "buffer".
1113 */
1114
1115 static int
1116 parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
1117 {
1118         int len;
1119         char *bp;
1120         CI ci = &ct->c_ctinfo;
1121
1122         /*
1123         ** If storage string is "-", just copy it, and
1124         ** return (send content to standard output).
1125         */
1126         if (cp[0] == '-' && cp[1] == '\0') {
1127                 strncpy(buffer, cp, buflen);
1128                 return 0;
1129         }
1130
1131         bp = buffer;
1132         bp[0] = '\0';
1133
1134         /*
1135         ** If formatting string is a pathname that doesn't
1136         ** begin with '/', then preface the path with the
1137         ** appropriate directory.
1138         */
1139         if (*cp != '/' && *cp != '|' && *cp != '!') {
1140                 snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
1141                 len = strlen(bp);
1142                 bp += len;
1143                 buflen -= len;
1144         }
1145
1146         for (; *cp; cp++) {
1147
1148                 /* We are processing a storage escape */
1149                 if (*cp == '%') {
1150                         switch (*++cp) {
1151                         case 'a':
1152                                 /*
1153                                 ** Insert parameters from Content-Type.
1154                                 ** This is only valid for '|' commands.
1155                                 */
1156                                 if (buffer[0] != '|' && buffer[0] != '!') {
1157                                         *bp++ = *--cp;
1158                                         *bp = '\0';
1159                                         buflen--;
1160                                         continue;
1161                                 } else {
1162                                         char **ap, **ep;
1163                                         char *s = "";
1164
1165                                         for (ap=ci->ci_attrs, ep=ci->ci_values;
1166                                                          *ap; ap++, ep++) {
1167                                                 snprintf(bp, buflen,
1168                                                                 "%s%s=\"%s\"",
1169                                                                 s, *ap, *ep);
1170                                                 len = strlen(bp);
1171                                                 bp += len;
1172                                                 buflen -= len;
1173                                                 s = " ";
1174                                         }
1175                                 }
1176                                 break;
1177
1178                         case 'm':
1179                                 /* insert message number */
1180                                 snprintf(bp, buflen, "%s",
1181                                                 mhbasename(ct->c_file));
1182                                 break;
1183
1184                         case 'P':
1185                                 /* insert part number with leading dot */
1186                                 if (ct->c_partno)
1187                                         snprintf(bp, buflen, ".%s",
1188                                                         ct->c_partno);
1189                                 break;
1190
1191                         case 'p':
1192                                 /* insert part number withouth leading dot */
1193                                 if (ct->c_partno)
1194                                         strncpy(bp, ct->c_partno, buflen);
1195                                 break;
1196
1197                         case 't':
1198                                 /* insert content type */
1199                                 strncpy(bp, ci->ci_type, buflen);
1200                                 break;
1201
1202                         case 's':
1203                                 /* insert content subtype */
1204                                 strncpy(bp, ci->ci_subtype, buflen);
1205                                 break;
1206
1207                         case '%':
1208                                 /* insert the character % */
1209                                 goto raw;
1210
1211                         default:
1212                                 *bp++ = *--cp;
1213                                 *bp = '\0';
1214                                 buflen--;
1215                                 continue;
1216                         }
1217
1218                         /* Advance bp and decrement buflen */
1219                         len = strlen(bp);
1220                         bp += len;
1221                         buflen -= len;
1222
1223                 } else {
1224 raw:
1225                         *bp++ = *cp;
1226                         *bp = '\0';
1227                         buflen--;
1228                 }
1229         }
1230
1231         return 0;
1232 }
1233
1234
1235 /*
1236 ** Copy some of the header fields of the initial message/partial
1237 ** message into the header of the reassembled message.
1238 */
1239
1240 static int
1241 copy_some_headers(FILE *out, CT ct)
1242 {
1243         HF hp;
1244
1245         hp = ct->c_first_hf;  /* start at first header field */
1246
1247         while (hp) {
1248                 /*
1249                 ** A few of the header fields of the enclosing
1250                 ** messages are not copied.
1251                 */
1252                 if (!uprf(hp->name, XXX_FIELD_PRF) &&
1253                                 mh_strcasecmp(hp->name, VRSN_FIELD) &&
1254                                 mh_strcasecmp(hp->name, "Subject") &&
1255                                 mh_strcasecmp(hp->name, "Message-ID"))
1256                         fprintf(out, "%s:%s", hp->name, hp->value);
1257                 hp = hp->next;  /* next header field */
1258         }
1259
1260         return OK;
1261 }