2 ** mhstore.c -- store the contents of MIME messages
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.
11 #include <h/signals.h>
16 #include <h/mhparse.h>
19 static struct swit switches[] = {
24 #define FILESW 2 /* interface from show */
29 { "type content", 0 },
41 extern char *tmp; /* directory to place temp files */
46 extern char *parts[NPARTS + 1];
47 extern char *types[NTYPES + 1];
52 #define quitser pipeser
55 CT parse_mime(char *);
60 void set_endian(void);
61 void flush_errors(void);
64 void free_content(CT);
65 extern CT *cts; /* The list of top-level contents to display */
71 static void pipeser(int);
76 ** Cache of current directory. This must be
77 ** set before these routines are called.
82 ** The directory in which to store the contents.
87 ** Type for a compare function for qsort. This keeps
88 ** the compiler happy.
90 typedef int (*qsort_comp) (const void *, const void *);
96 int make_intermediates(char *);
97 void flush_errors(void);
100 int show_content_aux(CT, int, char *, char *);
105 static void store_single_message(CT);
106 static int store_switch(CT);
107 static int store_generic(CT);
108 static int store_multi(CT);
109 static int store_partial(CT);
110 static int store_external(CT);
111 static int ct_compar(CT *, CT *);
112 static int store_content(CT, CT);
113 static int output_content_file(CT, int);
114 static int output_content_folder(char *, char *);
115 static int parse_format_string(CT, char *, char *, int, char *);
116 static int copy_some_headers(FILE *, CT);
117 static void store_all_messages(CT *);
121 main(int argc, char **argv)
124 char *cp, *file = NULL, *folder = NULL;
125 char *maildir, buf[100], **argp;
127 struct msgs_array msgs = { 0, 0, NULL };
128 struct msgs *mp = NULL;
132 atexit(freects_done);
134 setlocale(LC_ALL, "");
135 invo_name = mhbasename(argv[0]);
137 /* read user profile/context */
140 arguments = getarguments(invo_name, argc, argv, 1);
146 while ((cp = *argp++)) {
148 switch (smatch(++cp, switches)) {
150 ambigsw(cp, switches);
153 adios(NULL, "-%s unknown", cp);
156 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
157 print_help(buf, switches, 1);
160 print_version(invo_name);
171 if (!(cp = *argp++) || *cp == '-')
172 adios(NULL, "missing argument to %s",
175 adios(NULL, "too many parts (starting with %s), %d max", cp, NPARTS);
180 if (!(cp = *argp++) || *cp == '-')
181 adios(NULL, "missing argument to %s",
184 adios(NULL, "too many types (starting with %s), %d max", cp, NTYPES);
189 if (!(cp = *argp++) || (*cp == '-' && cp[1]))
190 adios(NULL, "missing argument to %s",
192 file = *cp == '-' ? cp : getcpy(expanddir(cp));
200 if (*cp == '+' || *cp == '@') {
202 adios(NULL, "only one folder at a time!");
204 folder = getcpy(expandfol(cp));
206 app_msgarg(&msgs, cp);
209 /* null terminate the list of acceptable parts/types */
216 ** Check if we've specified an additional profile
218 if ((cp = getenv("MHSTORE"))) {
219 if ((fp = fopen(cp, "r"))) {
220 readconfig((struct node **) 0, fp, cp, 0);
223 admonish("", "unable to read $MHSTORE profile (%s)",
229 ** Read the standard profile setup
231 if ((fp = fopen(cp = etcpath("mhn.defaults"), "r"))) {
232 readconfig((struct node **) 0, fp, cp, 0);
237 ** Cache the current directory before we do any chdirs()'s.
242 ** Check for storage directory. If specified,
243 ** then store temporary files there. Else we
244 ** store them in standard nmh directory.
246 if ((cp = context_find(nmhstorage)) && *cp)
247 tmp = concat(cp, "/", invo_name, NULL);
249 tmp = getcpy(toabsdir(invo_name));
251 if (file && msgs.size)
252 adios(NULL, "cannot specify msg and file at same time!");
255 ** check if message is coming from file
258 if (!(cts = (CT *) calloc((size_t) 2, sizeof(*cts))))
259 adios(NULL, "out of memory");
262 if ((ct = parse_mime(file)))
266 ** message(s) are coming from a folder
269 app_msgarg(&msgs, seq_cur);
271 folder = getcurfol();
272 maildir = toabsdir(folder);
274 if (chdir(maildir) == NOTOK)
275 adios(maildir, "unable to change directory to");
277 /* read folder and create message structure */
278 if (!(mp = folder_read(folder)))
279 adios(NULL, "unable to read folder %s", folder);
281 /* check for empty folder */
283 adios(NULL, "no messages in %s", folder);
285 /* parse all the message ranges/sequences and set SELECTED */
286 for (msgnum = 0; msgnum < msgs.size; msgnum++)
287 if (!m_convert(mp, msgs.msgs[msgnum]))
289 seq_setprev(mp); /* set the previous-sequence */
291 if (!(cts = (CT *) calloc((size_t) (mp->numsel + 1),
293 adios(NULL, "out of memory");
296 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
297 if (is_selected(mp, msgnum)) {
300 msgnam = m_name(msgnum);
301 if ((ct = parse_mime(msgnam)))
311 SIGNAL(SIGQUIT, quitser);
312 SIGNAL(SIGPIPE, pipeser);
315 ** Get the associated umask for the relevant contents.
317 for (ctp = cts; *ctp; ctp++) {
321 if (type_ok(ct, 1) && !ct->c_umask) {
322 if (stat(ct->c_file, &st) != NOTOK)
323 ct->c_umask = ~(st.st_mode & 0777);
325 ct->c_umask = ~m_gmprot();
330 ** Store the message content
332 store_all_messages(cts);
334 /* Now free all the structures for the content */
335 for (ctp = cts; *ctp; ctp++)
341 /* If reading from a folder, do some updating */
343 context_replace(curfolder, folder); /* update current folder */
344 seq_setcur(mp, mp->hghsel); /* update current message */
345 seq_save(mp); /* synchronize sequences */
346 context_save(); /* save the context file */
359 fprintf(stderr, "\n");
369 ** Main entry point to store content from a collection of messages.
372 store_all_messages(CT *cts)
378 ** Check for the directory in which to
379 ** store any contents.
381 if ((cp = context_find(nmhstorage)) && *cp)
386 for (ctp = cts; *ctp; ctp++) {
388 store_single_message(ct);
396 ** Entry point to store the content
397 ** in a (single) message
401 store_single_message(CT ct)
403 if (type_ok(ct, 1)) {
410 if (ct->c_ceclosefnx)
411 (*ct->c_ceclosefnx) (ct);
417 ** Switching routine to store different content types
423 switch (ct->c_type) {
425 return store_multi(ct);
429 switch (ct->c_subtype) {
430 case MESSAGE_PARTIAL:
431 return store_partial(ct);
434 case MESSAGE_EXTERNAL:
435 return store_external(ct);
439 return store_generic(ct);
449 return store_generic(ct);
453 adios(NULL, "unknown content type %d", ct->c_type);
457 return OK; /* NOT REACHED */
462 ** Generic routine to store a MIME content.
463 ** (application, audio, video, image, text, message/rfc922)
468 char **ap, **vp, *cp;
469 CI ci = &ct->c_ctinfo;
472 ** Check if the content specifies a filename in its MIME parameters.
473 ** Don't bother with this for type "message"
474 ** (only the "message" subtype "rfc822" will use store_generic).
476 if (autosw && ct->c_type != CT_MESSAGE) {
478 ** Check the attribute/value pairs, for the attribute "name".
479 ** If found, take the basename, do a few sanity checks and
480 ** copy the value into c_storeproc.
482 for (ap = ci->ci_attrs, vp = ci->ci_values; *ap; ap++,vp++) {
483 if (mh_strcasecmp(*ap, "name")!=0) {
486 cp = mhbasename(*vp);
487 if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
489 /* filename looks good: use it */
490 ct->c_storeproc = getcpy(cp);
496 return store_content(ct, NULL);
501 ** Store the content of a multipart message
508 struct multipart *m = (struct multipart *) ct->c_ctparams;
512 for (part = m->mp_parts; part; part = part->mp_next) {
513 CT p = part->mp_part;
515 if (part_ok(p, 1) && type_ok(p, 1)) {
516 result = store_switch(p);
517 if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
527 ** Reassemble and store the contents of a collection
528 ** of messages of type "message/partial".
537 struct partial *pm, *qm;
539 qm = (struct partial *) ct->c_ctparams;
544 for (ctp = cts; *ctp; ctp++) {
546 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
547 pm = (struct partial *) p->c_ctparams;
548 if (!pm->pm_stored &&
549 strcmp(qm->pm_partid, pm->pm_partid)
551 pm->pm_marked = pm->pm_partno;
562 advise(NULL, "missing (at least) last part of multipart message");
566 if ((base = (CT *) calloc((size_t) (i + 1), sizeof(*base))) == NULL)
567 adios(NULL, "out of memory");
570 for (ctp = cts; *ctp; ctp++) {
572 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
573 pm = (struct partial *) p->c_ctparams;
581 qsort((char *) base, i, sizeof(*base), (qsort_comp) ct_compar);
584 for (ctq = base; *ctq; ctq++) {
586 pm = (struct partial *) p->c_ctparams;
587 if (pm->pm_marked != cur) {
588 if (pm->pm_marked == cur - 1) {
589 admonish(NULL, "duplicate part %d of %d part multipart message", pm->pm_marked, hi);
594 advise (NULL, "missing %spart %d of %d part multipart message", cur != hi ? "(at least) " : "", cur, hi);
605 ** Now cycle through the sorted list of messages of type
606 ** "message/partial" and save/append them to a file.
611 if (store_content(ct, NULL) == NOTOK) {
617 for (; *ctq; ctq++) {
619 if (store_content(p, ct) == NOTOK)
629 ** Show how to retrieve content of type "message/external".
632 store_external(CT ct)
639 msg = add("You need to fetch the contents yourself:", NULL);
640 ap = ct->c_ctinfo.ci_attrs;
641 ep = ct->c_ctinfo.ci_values;
642 for (; *ap; ap++, ep++) {
643 msg = add(concat("\n\t", *ap, ": ", *ep, NULL), msg);
645 if (!(fp = fopen(ct->c_file, "r"))) {
646 adios(ct->c_file, "unable to open");
648 fseek(fp, ct->c_begin, SEEK_SET);
649 while (!feof(fp) && ftell(fp) < ct->c_end) {
650 if (!fgets(buf, sizeof buf, fp)) {
651 adios(ct->c_file, "unable to read");
653 *strchr(buf, '\n') = '\0';
654 msg = add(concat("\n\t", buf, NULL), msg);
663 ** Compare the numbering from two different
664 ** message/partials (needed for sorting).
668 ct_compar(CT *a, CT *b)
670 struct partial *am = (struct partial *) ((*a)->c_ctparams);
671 struct partial *bm = (struct partial *) ((*b)->c_ctparams);
673 return (am->pm_marked - bm->pm_marked);
678 ** Store contents of a message or message part to
679 ** a folder, a file, the standard output, or pass
680 ** the contents to a command.
682 ** If the current content to be saved is a followup part
683 ** to a collection of messages of type "message/partial",
684 ** then field "p" is a pointer to the Content structure
685 ** to the first message/partial in the group.
689 store_content(CT ct, CT p)
691 int appending = 0, msgnum = 0;
692 int is_partial = 0, first_partial = 0;
693 int last_partial = 0;
694 char *cp, buffer[BUFSIZ];
697 ** Do special processing for messages of
698 ** type "message/partial".
700 ** We first check if this content is of type
701 ** "message/partial". If it is, then we need to check
702 ** whether it is the first and/or last in the group.
704 ** Then if "p" is a valid pointer, it points to the Content
705 ** structure of the first partial in the group. So we copy
706 ** the file name and/or folder name from that message. In
707 ** this case, we also note that we will be appending.
709 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
710 struct partial *pm = (struct partial *) ct->c_ctparams;
712 /* Yep, it's a message/partial */
715 /* But is it the first and/or last in the collection? */
716 if (pm->pm_partno == 1)
718 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
722 ** If "p" is a valid pointer, then it points to the
723 ** Content structure for the first message in the group.
724 ** So we just copy the filename or foldername information
725 ** from the previous iteration of this function.
729 ct->c_storage = getcpy(p->c_storage);
731 /* record the folder name */
733 ct->c_folder = getcpy(p->c_folder);
740 ** Get storage formatting string.
742 ** 1) If we have storeproc defined, then use that
743 ** 2) Else check for a mhstore-store-<type>/<subtype> entry
744 ** 3) Else check for a mhstore-store-<type> entry
745 ** 4) Else if content is "message", use "+" (current folder)
746 ** 5) Else use string "%m%P.%s".
748 if (!(cp = ct->c_storeproc) || !*cp) {
749 CI ci = &ct->c_ctinfo;
751 snprintf(buffer, sizeof(buffer), "%s-store-%s/%s",
752 invo_name, ci->ci_type, ci->ci_subtype);
753 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
754 snprintf(buffer, sizeof(buffer), "%s-store-%s",
755 invo_name, ci->ci_type);
756 if ((cp = context_find(buffer)) == NULL ||
758 cp = ct->c_type == CT_MESSAGE ?
765 ** Check the beginning of storage formatting string
766 ** to see if we are saving content to a folder.
768 if (*cp == '+' || *cp == '@') {
769 char *tmpfilenam, *folder;
771 /* Store content in temporary file for now */
772 tmpfilenam = m_mktemp(invo_name, NULL, NULL);
773 ct->c_storage = getcpy(tmpfilenam);
775 /* Get the folder name */
777 folder = getcpy(expandfol(cp));
779 folder = getcurfol();
781 /* Check if folder exists */
782 create_folder(toabsdir(folder), 0, exit);
784 /* Record the folder name */
785 ct->c_folder = getcpy(folder);
794 ** Parse and expand the storage formatting string
795 ** in `cp' into `buffer'.
797 parse_format_string(ct, cp, buffer, sizeof(buffer), dir);
800 ** If formatting begins with '|' or '!', then pass
801 ** content to standard input of a command and return.
803 if (buffer[0] == '|' || buffer[0] == '!')
804 return show_content_aux(ct, 0, buffer + 1, dir);
806 /* record the filename */
807 ct->c_storage = getcpy(buffer);
810 /* flush the output stream */
813 /* Now save or append the content to a file */
814 if (output_content_file(ct, appending) == NOTOK)
818 ** If necessary, link the file into a folder and remove
819 ** the temporary file. If this message is a partial,
820 ** then only do this if it is the last one in the group.
822 if (ct->c_folder && (!is_partial || last_partial)) {
823 msgnum = output_content_folder(ct->c_folder, ct->c_storage);
824 unlink(ct->c_storage);
830 ** Now print out the name/number of the message
831 ** that we are storing.
835 fprintf(stderr, "reassembling partials ");
837 fprintf(stderr, "%s", ct->c_file);
839 fprintf(stderr, "%s,", ct->c_file);
841 fprintf(stderr, "storing message %s", ct->c_file);
843 fprintf(stderr, " part %s", ct->c_partno);
847 ** Unless we are in the "middle" of group of message/partials,
848 ** we now print the name of the file, folder, and/or message
849 ** to which we are storing the content.
851 if (!is_partial || last_partial) {
853 fprintf(stderr, " to folder %s as message %d\n",
854 ct->c_folder, msgnum);
855 } else if (strcmp(ct->c_storage, "-")==0) {
856 fprintf(stderr, " to stdout\n");
860 cwdlen = strlen(cwd);
861 fprintf(stderr, " as file %s\n",
862 strncmp(ct->c_storage, cwd,
864 ct->c_storage[cwdlen] != '/' ?
866 ct->c_storage + cwdlen + 1);
875 ** Output content to a file
879 output_content_file(CT ct, int appending)
882 char *file, buffer[BUFSIZ];
887 ** If the pathname contains directories, make sure
888 ** all of them exist.
890 if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
894 if (ct->c_encoding != CE_7BIT) {
897 if (!ct->c_ceopenfnx) {
898 advise(NULL, "don't know how to decode part %s of message %s", ct->c_partno, ct->c_file);
902 file = appending || strcmp(ct->c_storage, "-")==0 ?
903 NULL : ct->c_storage;
904 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
906 if (strcmp(file, ct->c_storage)==0) {
907 (*ct->c_ceclosefnx) (ct);
912 ** Send to standard output
914 if (strcmp(ct->c_storage, "-")==0) {
917 if ((gd = dup(fileno(stdout))) == NOTOK) {
918 advise("stdout", "unable to dup");
920 (*ct->c_ceclosefnx) (ct);
923 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
924 advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
932 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
934 advise(ct->c_storage, "unable to fopen for %s",
936 "appending" : "writing");
942 ** Filter the header fields of the initial enclosing
943 ** message/partial into the file.
945 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
946 struct partial *pm = (struct partial *) ct->c_ctparams;
948 if (pm->pm_partno == 1)
949 copy_some_headers(fp, ct);
953 switch (cc = read(fd, buffer, sizeof(buffer))) {
955 advise(file, "error reading content from");
962 fwrite(buffer, sizeof(*buffer), cc, fp);
968 (*ct->c_ceclosefnx) (ct);
970 if (cc != NOTOK && fflush(fp))
971 advise(ct->c_storage, "error writing to");
975 return (cc != NOTOK ? OK : NOTOK);
978 if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
979 advise(ct->c_file, "unable to open for reading");
985 fseek(ct->c_fp, pos, SEEK_SET);
987 if (strcmp(ct->c_storage, "-")==0) {
990 if ((gd = dup(fileno(stdout))) == NOTOK) {
991 advise("stdout", "unable to dup");
994 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
995 advise("stdout", "unable to fdopen (%d, \"%s\") from",
996 gd, appending ? "a" : "w");
1001 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
1003 advise(ct->c_storage, "unable to fopen for %s",
1004 appending ? "appending" : "writing");
1010 ** Copy a few of the header fields of the initial
1011 ** enclosing message/partial into the file.
1014 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
1015 struct partial *pm = (struct partial *) ct->c_ctparams;
1017 if (pm->pm_partno == 1) {
1018 copy_some_headers(fp, ct);
1023 while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
1024 if ((pos += strlen(buffer)) > last) {
1027 diff = strlen(buffer) - (pos - last);
1029 buffer[diff] = '\0';
1032 ** If this is the first content of a group of
1033 ** message/partial contents, then we only copy a few
1034 ** of the header fields of the enclosed message.
1037 switch (buffer[0]) {
1040 if (filterstate < 0)
1049 if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
1064 advise(ct->c_storage, "error writing to");
1074 ** Add a file to a folder.
1076 ** Return the new message number of the file
1077 ** when added to the folder. Return -1, if
1078 ** there is an error.
1082 output_content_folder(char *folder, char *filename)
1087 /* Read the folder. */
1088 if ((mp = folder_read(folder))) {
1089 /* Link file into folder */
1090 msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
1092 advise(NULL, "unable to read folder %s", folder);
1096 /* free folder structure */
1100 ** Return msgnum. We are relying on the fact that
1101 ** msgnum will be -1, if folder_addmsg() had an error.
1108 ** Parse and expand the storage formatting string
1109 ** pointed to by "cp" into "buffer".
1113 parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
1117 CI ci = &ct->c_ctinfo;
1120 ** If storage string is "-", just copy it, and
1121 ** return (send content to standard output).
1123 if (cp[0] == '-' && cp[1] == '\0') {
1124 strncpy(buffer, cp, buflen);
1132 ** If formatting string is a pathname that doesn't
1133 ** begin with '/', then preface the path with the
1134 ** appropriate directory.
1136 if (*cp != '/' && *cp != '|' && *cp != '!') {
1137 snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
1145 /* We are processing a storage escape */
1150 ** Insert parameters from Content-Type.
1151 ** This is only valid for '|' commands.
1153 if (buffer[0] != '|' && buffer[0] != '!') {
1162 for (ap=ci->ci_attrs, ep=ci->ci_values;
1164 snprintf(bp, buflen,
1176 /* insert message number */
1177 snprintf(bp, buflen, "%s",
1178 mhbasename(ct->c_file));
1182 /* insert part number with leading dot */
1184 snprintf(bp, buflen, ".%s",
1189 /* insert part number withouth leading dot */
1191 strncpy(bp, ct->c_partno, buflen);
1195 /* insert content type */
1196 strncpy(bp, ci->ci_type, buflen);
1200 /* insert content subtype */
1201 strncpy(bp, ci->ci_subtype, buflen);
1205 /* insert the character % */
1215 /* Advance bp and decrement buflen */
1233 ** Copy some of the header fields of the initial message/partial
1234 ** message into the header of the reassembled message.
1238 copy_some_headers(FILE *out, CT ct)
1242 hp = ct->c_first_hf; /* start at first header field */
1246 ** A few of the header fields of the enclosing
1247 ** messages are not copied.
1249 if (!uprf(hp->name, XXX_FIELD_PRF) &&
1250 mh_strcasecmp(hp->name, VRSN_FIELD) &&
1251 mh_strcasecmp(hp->name, "Subject") &&
1252 mh_strcasecmp(hp->name, "Message-ID"))
1253 fprintf(out, "%s:%s", hp->name, hp->value);
1254 hp = hp->next; /* next header field */