fae054fa1461075beb4b4ea7b2a5b5e3b886ba03
[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 = (CT *) mh_xcalloc((size_t) 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 = (CT *) mh_xcalloc((size_t) (mp->numsel + 1),
297                                 sizeof(*cts));
298                 ctp = cts;
299
300                 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
301                         if (is_selected(mp, msgnum)) {
302                                 char *msgnam;
303
304                                 msgnam = m_name(msgnum);
305                                 if ((ct = parse_mime(msgnam)))
306                                         *ctp++ = ct;
307                         }
308                 }
309         }
310
311         if (!*cts)
312                 exit(EX_SOFTWARE);
313
314         userrs = 1;
315         SIGNAL(SIGQUIT, quitser);
316         SIGNAL(SIGPIPE, pipeser);
317
318         /*
319         ** Get the associated umask for the relevant contents.
320         */
321         for (ctp = cts; *ctp; ctp++) {
322                 struct stat st;
323
324                 ct = *ctp;
325                 if (type_ok(ct, 1) && !ct->c_umask) {
326                         if (stat(ct->c_file, &st) != NOTOK)
327                                 ct->c_umask = ~(st.st_mode & 0777);
328                         else
329                                 ct->c_umask = ~m_gmprot();
330                 }
331         }
332
333         /*
334         ** Store the message content
335         */
336         store_all_messages(cts);
337
338         /* Now free all the structures for the content */
339         for (ctp = cts; *ctp; ctp++)
340                 free_content(*ctp);
341
342         free((char *) cts);
343         cts = NULL;
344
345         /* If reading from a folder, do some updating */
346         if (mp) {
347                 context_replace(curfolder, folder); /* update current folder */
348                 seq_setcur(mp, mp->hghsel);  /* update current message */
349                 seq_save(mp);  /* synchronize sequences  */
350                 context_save();  /* save the context file  */
351         }
352
353         return 0;
354 }
355
356
357 static void
358 pipeser(int i)
359 {
360         if (i == SIGQUIT) {
361                 unlink("core");
362                 fflush(stdout);
363                 fprintf(stderr, "\n");
364                 fflush(stderr);
365                 exit(EX_TEMPFAIL);
366         }
367
368         exit(EX_IOERR);
369         /* NOTREACHED */
370 }
371
372
373 /*
374 ** Main entry point to store content from a collection of messages.
375 */
376 static void
377 store_all_messages(CT *cts)
378 {
379         CT ct, *ctp;
380         char *cp;
381
382         /*
383         ** Check for the directory in which to
384         ** store any contents.
385         */
386         if ((cp = context_find(nmhstorage)) && *cp)
387                 dir = getcpy(cp);
388         else
389                 dir = getcpy(cwd);
390
391         for (ctp = cts; *ctp; ctp++) {
392                 ct = *ctp;
393                 store_single_message(ct);
394         }
395
396         flush_errors();
397 }
398
399
400 /*
401 ** Entry point to store the content
402 ** in a (single) message
403 */
404
405 static void
406 store_single_message(CT ct)
407 {
408         if (type_ok(ct, 1)) {
409                 umask(ct->c_umask);
410                 store_switch(ct);
411                 if (ct->c_fp) {
412                         fclose(ct->c_fp);
413                         ct->c_fp = NULL;
414                 }
415                 if (ct->c_ceclosefnx)
416                         (*ct->c_ceclosefnx) (ct);
417         }
418 }
419
420
421 /*
422 ** Switching routine to store different content types
423 */
424
425 static int
426 store_switch(CT ct)
427 {
428         switch (ct->c_type) {
429         case CT_MULTIPART:
430                 return store_multi(ct);
431                 break;
432
433         case CT_MESSAGE:
434                 switch (ct->c_subtype) {
435                 case MESSAGE_PARTIAL:
436                         return store_partial(ct);
437                         break;
438
439                 case MESSAGE_EXTERNAL:
440                         return store_external(ct);
441
442                 case MESSAGE_RFC822:
443                 default:
444                         return store_generic(ct);
445                         break;
446                 }
447                 break;
448
449         case CT_APPLICATION:
450         case CT_TEXT:
451         case CT_AUDIO:
452         case CT_IMAGE:
453         case CT_VIDEO:
454                 return store_generic(ct);
455                 break;
456
457         default:
458                 adios(EX_DATAERR, NULL, "unknown content type %d", ct->c_type);
459                 break;
460         }
461
462         return OK;  /* NOT REACHED */
463 }
464
465
466 /*
467 ** Generic routine to store a MIME content.
468 ** (application, audio, video, image, text, message/rfc922)
469 */
470 static int
471 store_generic(CT ct)
472 {
473         char **ap, **vp, *cp;
474         CI ci = &ct->c_ctinfo;
475
476         /*
477         ** Check if the content specifies a filename in its MIME parameters.
478         ** Don't bother with this for type "message"
479         ** (only the "message" subtype "rfc822" will use store_generic).
480         */
481         if (autosw && ct->c_type != CT_MESSAGE) {
482                 /*
483                 ** Check the attribute/value pairs, for the attribute "name".
484                 ** If found, take the basename, do a few sanity checks and
485                 ** copy the value into c_storeproc.
486                 */
487                 for (ap = ci->ci_attrs, vp = ci->ci_values; *ap; ap++,vp++) {
488                         if (mh_strcasecmp(*ap, "name")!=0) {
489                                 continue;
490                         }
491                         cp = mhbasename(*vp);
492                         if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
493                                         !strchr(cp, '%')) {
494                                 /* filename looks good: use it */
495                                 ct->c_storeproc = getcpy(cp);
496                         }
497                         break;
498                 }
499         }
500
501         return store_content(ct, NULL);
502 }
503
504
505 /*
506 ** Store the content of a multipart message
507 */
508
509 static int
510 store_multi(CT ct)
511 {
512         int result;
513         struct multipart *m = (struct multipart *) ct->c_ctparams;
514         struct part *part;
515
516         result = NOTOK;
517         for (part = m->mp_parts; part; part = part->mp_next) {
518                 CT  p = part->mp_part;
519
520                 if (part_ok(p, 1) && type_ok(p, 1)) {
521                         result = store_switch(p);
522                         if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
523                                 break;
524                 }
525         }
526
527         return result;
528 }
529
530
531 /*
532 ** Reassemble and store the contents of a collection
533 ** of messages of type "message/partial".
534 */
535
536 static int
537 store_partial(CT ct)
538 {
539         int cur, hi, i;
540         CT p, *ctp, *ctq;
541         CT *base;
542         struct partial *pm, *qm;
543
544         qm = (struct partial *) ct->c_ctparams;
545         if (qm->pm_stored)
546                 return OK;
547
548         hi = i = 0;
549         for (ctp = cts; *ctp; ctp++) {
550                 p = *ctp;
551                 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
552                         pm = (struct partial *) p->c_ctparams;
553                         if (!pm->pm_stored &&
554                                         strcmp(qm->pm_partid, pm->pm_partid)
555                                         == 0) {
556                                 pm->pm_marked = pm->pm_partno;
557                                 if (pm->pm_maxno)
558                                         hi = pm->pm_maxno;
559                                 pm->pm_stored = 1;
560                                 i++;
561                         } else
562                                 pm->pm_marked = 0;
563                 }
564         }
565
566         if (hi == 0) {
567                 advise(NULL, "missing (at least) last part of multipart message");
568                 return NOTOK;
569         }
570
571         base = (CT *) mh_xcalloc((size_t) (i + 1), sizeof(*base));
572
573         ctq = base;
574         for (ctp = cts; *ctp; ctp++) {
575                 p = *ctp;
576                 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
577                         pm = (struct partial *) p->c_ctparams;
578                         if (pm->pm_marked)
579                                 *ctq++ = p;
580                 }
581         }
582         *ctq = NULL;
583
584         if (i > 1)
585                 qsort((char *) base, i, sizeof(*base), (qsort_comp) ct_compar);
586
587         cur = 1;
588         for (ctq = base; *ctq; ctq++) {
589                 p = *ctq;
590                 pm = (struct partial *) p->c_ctparams;
591                 if (pm->pm_marked != cur) {
592                         if (pm->pm_marked == cur - 1) {
593                                 admonish(NULL, "duplicate part %d of %d part multipart message", pm->pm_marked, hi);
594                                 continue;
595                         }
596
597 missing_part:
598                         advise (NULL, "missing %spart %d of %d part multipart message", cur != hi ? "(at least) " : "", cur, hi);
599                         goto losing;
600                 } else
601                         cur++;
602         }
603         if (hi != --cur) {
604                 cur = hi;
605                 goto missing_part;
606         }
607
608         /*
609         ** Now cycle through the sorted list of messages of type
610         ** "message/partial" and save/append them to a file.
611         */
612
613         ctq = base;
614         ct = *ctq++;
615         if (store_content(ct, NULL) == NOTOK) {
616 losing:
617                 free((char *) base);
618                 return NOTOK;
619         }
620
621         for (; *ctq; ctq++) {
622                 p = *ctq;
623                 if (store_content(p, ct) == NOTOK)
624                         goto losing;
625         }
626
627         free((char *) base);
628         return OK;
629 }
630
631
632 /*
633 ** Show how to retrieve content of type "message/external".
634 */
635 static int
636 store_external(CT ct)
637 {
638         char **ap, **ep;
639         char *msg;
640         FILE *fp;
641         char buf[BUFSIZ];
642
643         msg = add("You need to fetch the contents yourself:", NULL);
644         ap = ct->c_ctinfo.ci_attrs;
645         ep = ct->c_ctinfo.ci_values;
646         for (; *ap; ap++, ep++) {
647                 msg = add(concat("\n\t", *ap, ": ", *ep, NULL), msg);
648         }
649         if (!(fp = fopen(ct->c_file, "r"))) {
650                 adios(EX_IOERR, ct->c_file, "unable to open");
651         }
652         fseek(fp, ct->c_begin, SEEK_SET);
653         while (!feof(fp) && ftell(fp) < ct->c_end) {
654                 if (!fgets(buf, sizeof buf, fp)) {
655                         adios(EX_IOERR, ct->c_file, "unable to read");
656                 }
657                 *strchr(buf, '\n') = '\0';
658                 msg = add(concat("\n\t", buf, NULL), msg);
659         }
660         fclose(fp);
661         advise(NULL, msg);
662         return OK;
663 }
664
665
666 /*
667 ** Compare the numbering from two different
668 ** message/partials (needed for sorting).
669 */
670
671 static int
672 ct_compar(CT *a, CT *b)
673 {
674         struct partial *am = (struct partial *) ((*a)->c_ctparams);
675         struct partial *bm = (struct partial *) ((*b)->c_ctparams);
676
677         return (am->pm_marked - bm->pm_marked);
678 }
679
680
681 /*
682 ** Store contents of a message or message part to
683 ** a folder, a file, the standard output, or pass
684 ** the contents to a command.
685 **
686 ** If the current content to be saved is a followup part
687 ** to a collection of messages of type "message/partial",
688 ** then field "p" is a pointer to the Content structure
689 ** to the first message/partial in the group.
690 */
691
692 static int
693 store_content(CT ct, CT p)
694 {
695         int appending = 0, msgnum = 0;
696         int is_partial = 0, first_partial = 0;
697         int last_partial = 0;
698         char *cp, buffer[BUFSIZ];
699
700         /*
701         ** Do special processing for messages of
702         ** type "message/partial".
703         **
704         ** We first check if this content is of type
705         ** "message/partial".  If it is, then we need to check
706         ** whether it is the first and/or last in the group.
707         **
708         ** Then if "p" is a valid pointer, it points to the Content
709         ** structure of the first partial in the group.  So we copy
710         ** the file name and/or folder name from that message.  In
711         ** this case, we also note that we will be appending.
712         */
713         if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
714                 struct partial *pm = (struct partial *) ct->c_ctparams;
715
716                 /* Yep, it's a message/partial */
717                 is_partial = 1;
718
719                 /* But is it the first and/or last in the collection? */
720                 if (pm->pm_partno == 1)
721                         first_partial = 1;
722                 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
723                         last_partial = 1;
724
725                 /*
726                 ** If "p" is a valid pointer, then it points to the
727                 ** Content structure for the first message in the group.
728                 ** So we just copy the filename or foldername information
729                 ** from the previous iteration of this function.
730                 */
731                 if (p) {
732                         appending = 1;
733                         ct->c_storage = getcpy(p->c_storage);
734
735                         /* record the folder name */
736                         if (p->c_folder) {
737                                 ct->c_folder = getcpy(p->c_folder);
738                         }
739                         goto got_filename;
740                 }
741         }
742
743         /*
744         ** Get storage formatting string.
745         **
746         ** 1) If we have storeproc defined, then use that
747         ** 2) Else check for a mhstore-store-<type>/<subtype> entry
748         ** 3) Else check for a mhstore-store-<type> entry
749         ** 4) Else if content is "message", use "+" (current folder)
750         ** 5) Else use string "%m%P.%s".
751         */
752         if (!(cp = ct->c_storeproc) || !*cp) {
753                 CI ci = &ct->c_ctinfo;
754
755                 snprintf(buffer, sizeof(buffer), "%s-store-%s/%s",
756                                 invo_name, ci->ci_type, ci->ci_subtype);
757                 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
758                         snprintf(buffer, sizeof(buffer), "%s-store-%s",
759                                         invo_name, ci->ci_type);
760                         if ((cp = context_find(buffer)) == NULL ||
761                                         *cp == '\0') {
762                                 cp = ct->c_type == CT_MESSAGE ?
763                                                 "+" : "%m%P.%s";
764                         }
765                 }
766         }
767
768         /*
769         ** Check the beginning of storage formatting string
770         ** to see if we are saving content to a folder.
771         */
772         if (*cp == '+' || *cp == '@') {
773                 char *tmpfilenam, *folder;
774
775                 /* Store content in temporary file for now */
776                 tmpfilenam = m_mktemp(invo_name, NULL, NULL);
777                 ct->c_storage = getcpy(tmpfilenam);
778
779                 /* Get the folder name */
780                 if (cp[1])
781                         folder = getcpy(expandfol(cp));
782                 else
783                         folder = getcurfol();
784
785                 /* Check if folder exists */
786                 create_folder(toabsdir(folder), 0, exit);
787
788                 /* Record the folder name */
789                 ct->c_folder = getcpy(folder);
790
791                 if (cp[1])
792                         free(folder);
793
794                 goto got_filename;
795         }
796
797         /*
798         ** Parse and expand the storage formatting string
799         ** in `cp' into `buffer'.
800         */
801         parse_format_string(ct, cp, buffer, sizeof(buffer), dir);
802
803         /*
804         ** If formatting begins with '|' or '!', then pass
805         ** content to standard input of a command and return.
806         */
807         if (buffer[0] == '|' || buffer[0] == '!')
808                 return show_content_aux(ct, 0, buffer + 1, dir);
809
810         /* record the filename */
811         ct->c_storage = getcpy(buffer);
812
813 got_filename:
814         /* flush the output stream */
815         fflush(stdout);
816
817         /* Now save or append the content to a file */
818         if (output_content_file(ct, appending) == NOTOK)
819                 return NOTOK;
820
821         /*
822         ** If necessary, link the file into a folder and remove
823         ** the temporary file.  If this message is a partial,
824         ** then only do this if it is the last one in the group.
825         */
826         if (ct->c_folder && (!is_partial || last_partial)) {
827                 msgnum = output_content_folder(ct->c_folder, ct->c_storage);
828                 unlink(ct->c_storage);
829                 if (msgnum == NOTOK)
830                         return NOTOK;
831         }
832
833         /*
834         ** Now print out the name/number of the message
835         ** that we are storing.
836         */
837         if (is_partial) {
838                 if (first_partial)
839                         fprintf(stderr, "reassembling partials ");
840                 if (last_partial)
841                         fprintf(stderr, "%s", ct->c_file);
842                 else
843                         fprintf(stderr, "%s,", ct->c_file);
844         } else {
845                 fprintf(stderr, "storing message %s", ct->c_file);
846                 if (ct->c_partno)
847                         fprintf(stderr, " part %s", ct->c_partno);
848         }
849
850         /*
851         ** Unless we are in the "middle" of group of message/partials,
852         ** we now print the name of the file, folder, and/or message
853         ** to which we are storing the content.
854         */
855         if (!is_partial || last_partial) {
856                 if (ct->c_folder) {
857                         fprintf(stderr, " to folder %s as message %d\n",
858                                         ct->c_folder, msgnum);
859                 } else if (strcmp(ct->c_storage, "-")==0) {
860                         fprintf(stderr, " to stdout\n");
861                 } else {
862                         int cwdlen;
863
864                         cwdlen = strlen(cwd);
865                         fprintf(stderr, " as file %s\n",
866                                         strncmp(ct->c_storage, cwd,
867                                         cwdlen)!=0 ||
868                                         ct->c_storage[cwdlen] != '/' ?
869                                         ct->c_storage :
870                                         ct->c_storage + cwdlen + 1);
871                 }
872         }
873
874         return OK;
875 }
876
877
878 /*
879 ** Output content to a file
880 */
881
882 static int
883 output_content_file(CT ct, int appending)
884 {
885         int filterstate;
886         char *file, buffer[BUFSIZ];
887         long pos, last;
888         FILE *fp;
889
890         /*
891         ** If the pathname contains directories, make sure
892         ** all of them exist.
893         */
894         if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
895                         == NOTOK)
896                 return NOTOK;
897
898         if (ct->c_encoding != CE_7BIT) {
899                 int cc, fd;
900
901                 if (!ct->c_ceopenfnx) {
902                         advise(NULL, "don't know how to decode part %s of message %s", ct->c_partno, ct->c_file);
903                         return NOTOK;
904                 }
905
906                 file = appending || strcmp(ct->c_storage, "-")==0 ?
907                                 NULL : ct->c_storage;
908                 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
909                         return NOTOK;
910                 if (strcmp(file, ct->c_storage)==0) {
911                         (*ct->c_ceclosefnx) (ct);
912                         return OK;
913                 }
914
915                 /*
916                 ** Send to standard output
917                 */
918                 if (strcmp(ct->c_storage, "-")==0) {
919                         int gd;
920
921                         if ((gd = dup(fileno(stdout))) == NOTOK) {
922                                 advise("stdout", "unable to dup");
923 losing:
924                                 (*ct->c_ceclosefnx) (ct);
925                                 return NOTOK;
926                         }
927                         if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
928                                 advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
929                                 close(gd);
930                                 goto losing;
931                         }
932                 } else {
933                         /*
934                         ** Open output file
935                         */
936                         if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
937                                         == NULL) {
938                                 advise(ct->c_storage, "unable to fopen for %s",
939                                                 appending ?
940                                                 "appending" : "writing");
941                                 goto losing;
942                         }
943                 }
944
945                 /*
946                 ** Filter the header fields of the initial enclosing
947                 ** message/partial into the file.
948                 */
949                 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
950                         struct partial *pm = (struct partial *) ct->c_ctparams;
951
952                         if (pm->pm_partno == 1)
953                                 copy_some_headers(fp, ct);
954                 }
955
956                 for (;;) {
957                         switch (cc = read(fd, buffer, sizeof(buffer))) {
958                         case NOTOK:
959                                 advise(file, "error reading content from");
960                                 break;
961
962                         case OK:
963                                 break;
964
965                         default:
966                                 fwrite(buffer, sizeof(*buffer), cc, fp);
967                                 continue;
968                         }
969                         break;
970                 }
971
972                 (*ct->c_ceclosefnx) (ct);
973
974                 if (cc != NOTOK && fflush(fp))
975                         advise(ct->c_storage, "error writing to");
976
977                 fclose(fp);
978
979                 return (cc != NOTOK ? OK : NOTOK);
980         }
981
982         if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
983                 advise(ct->c_file, "unable to open for reading");
984                 return NOTOK;
985         }
986
987         pos = ct->c_begin;
988         last = ct->c_end;
989         fseek(ct->c_fp, pos, SEEK_SET);
990
991         if (strcmp(ct->c_storage, "-")==0) {
992                 int gd;
993
994                 if ((gd = dup(fileno(stdout))) == NOTOK) {
995                         advise("stdout", "unable to dup");
996                         return NOTOK;
997                 }
998                 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
999                         advise("stdout", "unable to fdopen (%d, \"%s\") from",
1000                                         gd, appending ? "a" : "w");
1001                         close(gd);
1002                         return NOTOK;
1003                 }
1004         } else {
1005                 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
1006                                 == NULL) {
1007                         advise(ct->c_storage, "unable to fopen for %s",
1008                                         appending ? "appending" : "writing");
1009                         return NOTOK;
1010                 }
1011         }
1012
1013         /*
1014         ** Copy a few of the header fields of the initial
1015         ** enclosing message/partial into the file.
1016         */
1017         filterstate = 0;
1018         if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
1019                 struct partial *pm = (struct partial *) ct->c_ctparams;
1020
1021                 if (pm->pm_partno == 1) {
1022                         copy_some_headers(fp, ct);
1023                         filterstate = 1;
1024                 }
1025         }
1026
1027         while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
1028                 if ((pos += strlen(buffer)) > last) {
1029                         int diff;
1030
1031                         diff = strlen(buffer) - (pos - last);
1032                         if (diff >= 0)
1033                                 buffer[diff] = '\0';
1034                 }
1035                 /*
1036                 ** If this is the first content of a group of
1037                 ** message/partial contents, then we only copy a few
1038                 ** of the header fields of the enclosed message.
1039                 */
1040                 if (filterstate) {
1041                         switch (buffer[0]) {
1042                         case ' ':
1043                         case '\t':
1044                                 if (filterstate < 0)
1045                                         buffer[0] = 0;
1046                                 break;
1047
1048                         case '\n':
1049                                 filterstate = 0;
1050                                 break;
1051
1052                         default:
1053                                 if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
1054                                         filterstate = -1;
1055                                         buffer[0] = 0;
1056                                         break;
1057                                 }
1058                                 filterstate = 1;
1059                                 break;
1060                         }
1061                 }
1062                 fputs(buffer, fp);
1063                 if (pos >= last)
1064                         break;
1065         }
1066
1067         if (fflush(fp))
1068                 advise(ct->c_storage, "error writing to");
1069
1070         fclose(fp);
1071         fclose(ct->c_fp);
1072         ct->c_fp = NULL;
1073         return OK;
1074 }
1075
1076
1077 /*
1078 ** Add a file to a folder.
1079 **
1080 ** Return the new message number of the file
1081 ** when added to the folder.  Return -1, if
1082 ** there is an error.
1083 */
1084
1085 static int
1086 output_content_folder(char *folder, char *filename)
1087 {
1088         int msgnum;
1089         struct msgs *mp;
1090
1091         /* Read the folder. */
1092         if ((mp = folder_read(folder))) {
1093                 /* Link file into folder */
1094                 msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
1095         } else {
1096                 advise(NULL, "unable to read folder %s", folder);
1097                 return NOTOK;
1098         }
1099
1100         /* free folder structure */
1101         folder_free(mp);
1102
1103         /*
1104         ** Return msgnum.  We are relying on the fact that
1105         ** msgnum will be -1, if folder_addmsg() had an error.
1106         */
1107         return msgnum;
1108 }
1109
1110
1111 /*
1112 ** Parse and expand the storage formatting string
1113 ** pointed to by "cp" into "buffer".
1114 */
1115
1116 static int
1117 parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
1118 {
1119         int len;
1120         char *bp;
1121         CI ci = &ct->c_ctinfo;
1122
1123         /*
1124         ** If storage string is "-", just copy it, and
1125         ** return (send content to standard output).
1126         */
1127         if (cp[0] == '-' && cp[1] == '\0') {
1128                 strncpy(buffer, cp, buflen);
1129                 return 0;
1130         }
1131
1132         bp = buffer;
1133         bp[0] = '\0';
1134
1135         /*
1136         ** If formatting string is a pathname that doesn't
1137         ** begin with '/', then preface the path with the
1138         ** appropriate directory.
1139         */
1140         if (*cp != '/' && *cp != '|' && *cp != '!') {
1141                 snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
1142                 len = strlen(bp);
1143                 bp += len;
1144                 buflen -= len;
1145         }
1146
1147         for (; *cp; cp++) {
1148
1149                 /* We are processing a storage escape */
1150                 if (*cp == '%') {
1151                         switch (*++cp) {
1152                         case 'a':
1153                                 /*
1154                                 ** Insert parameters from Content-Type.
1155                                 ** This is only valid for '|' commands.
1156                                 */
1157                                 if (buffer[0] != '|' && buffer[0] != '!') {
1158                                         *bp++ = *--cp;
1159                                         *bp = '\0';
1160                                         buflen--;
1161                                         continue;
1162                                 } else {
1163                                         char **ap, **ep;
1164                                         char *s = "";
1165
1166                                         for (ap=ci->ci_attrs, ep=ci->ci_values;
1167                                                          *ap; ap++, ep++) {
1168                                                 snprintf(bp, buflen,
1169                                                                 "%s%s=\"%s\"",
1170                                                                 s, *ap, *ep);
1171                                                 len = strlen(bp);
1172                                                 bp += len;
1173                                                 buflen -= len;
1174                                                 s = " ";
1175                                         }
1176                                 }
1177                                 break;
1178
1179                         case 'm':
1180                                 /* insert message number */
1181                                 snprintf(bp, buflen, "%s",
1182                                                 mhbasename(ct->c_file));
1183                                 break;
1184
1185                         case 'P':
1186                                 /* insert part number with leading dot */
1187                                 if (ct->c_partno)
1188                                         snprintf(bp, buflen, ".%s",
1189                                                         ct->c_partno);
1190                                 break;
1191
1192                         case 'p':
1193                                 /* insert part number withouth leading dot */
1194                                 if (ct->c_partno)
1195                                         strncpy(bp, ct->c_partno, buflen);
1196                                 break;
1197
1198                         case 't':
1199                                 /* insert content type */
1200                                 strncpy(bp, ci->ci_type, buflen);
1201                                 break;
1202
1203                         case 's':
1204                                 /* insert content subtype */
1205                                 strncpy(bp, ci->ci_subtype, buflen);
1206                                 break;
1207
1208                         case '%':
1209                                 /* insert the character % */
1210                                 goto raw;
1211
1212                         default:
1213                                 *bp++ = *--cp;
1214                                 *bp = '\0';
1215                                 buflen--;
1216                                 continue;
1217                         }
1218
1219                         /* Advance bp and decrement buflen */
1220                         len = strlen(bp);
1221                         bp += len;
1222                         buflen -= len;
1223
1224                 } else {
1225 raw:
1226                         *bp++ = *cp;
1227                         *bp = '\0';
1228                         buflen--;
1229                 }
1230         }
1231
1232         return 0;
1233 }
1234
1235
1236 /*
1237 ** Copy some of the header fields of the initial message/partial
1238 ** message into the header of the reassembled message.
1239 */
1240
1241 static int
1242 copy_some_headers(FILE *out, CT ct)
1243 {
1244         HF hp;
1245
1246         hp = ct->c_first_hf;  /* start at first header field */
1247
1248         while (hp) {
1249                 /*
1250                 ** A few of the header fields of the enclosing
1251                 ** messages are not copied.
1252                 */
1253                 if (!uprf(hp->name, XXX_FIELD_PRF) &&
1254                                 mh_strcasecmp(hp->name, VRSN_FIELD) &&
1255                                 mh_strcasecmp(hp->name, "Subject") &&
1256                                 mh_strcasecmp(hp->name, "Message-ID"))
1257                         fprintf(out, "%s:%s", hp->name, hp->value);
1258                 hp = hp->next;  /* next header field */
1259         }
1260
1261         return OK;
1262 }