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>
23 static struct swit switches[] = {
28 #define FILESW 2 /* interface from show */
33 { "type content", 0 },
45 extern char *tmp; /* directory to place temp files */
50 extern char *parts[NPARTS + 1];
51 extern char *types[NTYPES + 1];
56 #define quitser pipeser
59 CT parse_mime(char *);
64 void set_endian(void);
65 void flush_errors(void);
68 void free_content(CT);
69 extern CT *cts; /* The list of top-level contents to display */
75 static void pipeser(int);
80 ** Cache of current directory. This must be
81 ** set before these routines are called.
86 ** The directory in which to store the contents.
91 ** Type for a compare function for qsort. This keeps
92 ** the compiler happy.
94 typedef int (*qsort_comp) (const void *, const void *);
100 int make_intermediates(char *);
101 void flush_errors(void);
104 int show_content_aux(CT, int, char *, char *);
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 *);
125 main(int argc, char **argv)
128 char *cp, *file = NULL, *folder = NULL;
129 char *maildir, buf[100], **argp;
131 struct msgs_array msgs = { 0, 0, NULL };
132 struct msgs *mp = NULL;
136 if (atexit(freects_done) != 0) {
137 adios(EX_OSERR, NULL, "atexit failed");
140 setlocale(LC_ALL, "");
141 invo_name = mhbasename(argv[0]);
143 /* read user profile/context */
146 arguments = getarguments(invo_name, argc, argv, 1);
152 while ((cp = *argp++)) {
154 switch (smatch(++cp, switches)) {
156 ambigsw(cp, switches);
159 adios(EX_USAGE, NULL, "-%s unknown", cp);
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);
166 print_version(invo_name);
167 exit(argc == 2 ? EX_OK : EX_USAGE);
177 if (!(cp = *argp++) || *cp == '-')
178 adios(EX_USAGE, NULL, "missing argument to %s",
181 adios(EX_USAGE, NULL, "too many parts (starting with %s), %d max", cp, NPARTS);
186 if (!(cp = *argp++) || *cp == '-')
187 adios(EX_USAGE, NULL, "missing argument to %s",
190 adios(EX_USAGE, NULL, "too many types (starting with %s), %d max", cp, NTYPES);
195 if (!(cp = *argp++) || (*cp == '-' && cp[1]))
196 adios(EX_USAGE, NULL, "missing argument to %s",
198 file = *cp == '-' ? cp : getcpy(expanddir(cp));
206 if (*cp == '+' || *cp == '@') {
208 adios(EX_USAGE, NULL, "only one folder at a time!");
210 folder = getcpy(expandfol(cp));
212 app_msgarg(&msgs, cp);
215 /* null terminate the list of acceptable parts/types */
222 ** Check if we've specified an additional profile
224 if ((cp = getenv("MHSTORE"))) {
225 if ((fp = fopen(cp, "r"))) {
226 readconfig((struct node **) 0, fp, cp, 0);
229 admonish("", "unable to read $MHSTORE profile (%s)",
235 ** Read the standard profile setup
237 if ((fp = fopen(cp = etcpath("mhn.defaults"), "r"))) {
238 readconfig((struct node **) 0, fp, cp, 0);
243 ** Cache the current directory before we do any chdirs()'s.
248 ** Check for storage directory. If specified,
249 ** then store temporary files there. Else we
250 ** store them in standard nmh directory.
252 if ((cp = context_find(nmhstorage)) && *cp)
253 tmp = concat(cp, "/", invo_name, NULL);
255 tmp = getcpy(toabsdir(invo_name));
257 if (file && msgs.size)
258 adios(EX_USAGE, NULL, "cannot specify msg and file at same time!");
261 ** check if message is coming from file
264 cts = mh_xcalloc(2, sizeof(*cts));
267 if ((ct = parse_mime(file)))
271 ** message(s) are coming from a folder
274 app_msgarg(&msgs, seq_cur);
276 folder = getcurfol();
277 maildir = toabsdir(folder);
279 if (chdir(maildir) == NOTOK)
280 adios(EX_OSERR, maildir, "unable to change directory to");
282 /* read folder and create message structure */
283 if (!(mp = folder_read(folder)))
284 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
286 /* check for empty folder */
288 adios(EX_DATAERR, NULL, "no messages in %s", folder);
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]))
294 seq_setprev(mp); /* set the previous-sequence */
296 cts = mh_xcalloc(mp->numsel + 1, sizeof(*cts));
299 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
300 if (is_selected(mp, msgnum)) {
303 msgnam = m_name(msgnum);
304 if ((ct = parse_mime(msgnam)))
314 SIGNAL(SIGQUIT, quitser);
315 SIGNAL(SIGPIPE, pipeser);
318 ** Get the associated umask for the relevant contents.
320 for (ctp = cts; *ctp; 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);
328 ct->c_umask = ~m_gmprot();
333 ** Store the message content
335 store_all_messages(cts);
337 /* Now free all the structures for the content */
338 for (ctp = cts; *ctp; ctp++)
344 /* If reading from a folder, do some updating */
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 */
362 fprintf(stderr, "\n");
373 ** Main entry point to store content from a collection of messages.
376 store_all_messages(CT *cts)
382 ** Check for the directory in which to
383 ** store any contents.
385 if ((cp = context_find(nmhstorage)) && *cp)
390 for (ctp = cts; *ctp; ctp++) {
392 store_single_message(ct);
400 ** Entry point to store the content
401 ** in a (single) message
405 store_single_message(CT ct)
407 if (type_ok(ct, 1)) {
414 if (ct->c_ceclosefnx)
415 (*ct->c_ceclosefnx) (ct);
421 ** Switching routine to store different content types
427 switch (ct->c_type) {
429 return store_multi(ct);
433 switch (ct->c_subtype) {
434 case MESSAGE_PARTIAL:
435 return store_partial(ct);
438 case MESSAGE_EXTERNAL:
439 return store_external(ct);
443 return store_generic(ct);
453 return store_generic(ct);
457 adios(EX_DATAERR, NULL, "unknown content type %d", ct->c_type);
461 return OK; /* NOT REACHED */
466 ** Generic routine to store a MIME content.
467 ** (application, audio, video, image, text, message/rfc922)
472 char **ap, **vp, *cp;
473 CI ci = &ct->c_ctinfo;
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).
480 if (autosw && ct->c_type != CT_MESSAGE) {
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.
486 for (ap = ci->ci_attrs, vp = ci->ci_values; *ap; ap++,vp++) {
487 if (mh_strcasecmp(*ap, "name")!=0) {
490 cp = mhbasename(*vp);
491 if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
493 /* filename looks good: use it */
494 ct->c_storeproc = getcpy(cp);
500 return store_content(ct, NULL);
505 ** Store the content of a multipart message
512 struct multipart *m = (struct multipart *) ct->c_ctparams;
516 for (part = m->mp_parts; part; part = part->mp_next) {
517 CT p = part->mp_part;
519 if (part_ok(p, 1) && type_ok(p, 1)) {
520 result = store_switch(p);
521 if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
531 ** Reassemble and store the contents of a collection
532 ** of messages of type "message/partial".
541 struct partial *pm, *qm;
543 qm = (struct partial *) ct->c_ctparams;
548 for (ctp = cts; *ctp; 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)
555 pm->pm_marked = pm->pm_partno;
566 advise(NULL, "missing (at least) last part of multipart message");
570 base = mh_xcalloc(i + 1, sizeof(*base));
573 for (ctp = cts; *ctp; ctp++) {
575 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
576 pm = (struct partial *) p->c_ctparams;
584 qsort((char *) base, i, sizeof(*base), (qsort_comp) ct_compar);
587 for (ctq = base; *ctq; 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);
597 advise (NULL, "missing %spart %d of %d part multipart message", cur != hi ? "(at least) " : "", cur, hi);
608 ** Now cycle through the sorted list of messages of type
609 ** "message/partial" and save/append them to a file.
614 if (store_content(ct, NULL) == NOTOK) {
620 for (; *ctq; ctq++) {
622 if (store_content(p, ct) == NOTOK)
632 ** Show how to retrieve content of type "message/external".
635 store_external(CT ct)
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);
648 if (!(fp = fopen(ct->c_file, "r"))) {
649 adios(EX_IOERR, ct->c_file, "unable to open");
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");
656 *strchr(buf, '\n') = '\0';
657 msg = add(concat("\n\t", buf, NULL), msg);
666 ** Compare the numbering from two different
667 ** message/partials (needed for sorting).
671 ct_compar(CT *a, CT *b)
673 struct partial *am = (struct partial *) ((*a)->c_ctparams);
674 struct partial *bm = (struct partial *) ((*b)->c_ctparams);
676 return (am->pm_marked - bm->pm_marked);
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.
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.
692 store_content(CT ct, CT p)
694 int appending = 0, msgnum = 0;
695 int is_partial = 0, first_partial = 0;
696 int last_partial = 0;
697 char *cp, buffer[BUFSIZ];
700 ** Do special processing for messages of
701 ** type "message/partial".
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.
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.
712 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
713 struct partial *pm = (struct partial *) ct->c_ctparams;
715 /* Yep, it's a message/partial */
718 /* But is it the first and/or last in the collection? */
719 if (pm->pm_partno == 1)
721 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
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.
732 ct->c_storage = getcpy(p->c_storage);
734 /* record the folder name */
736 ct->c_folder = getcpy(p->c_folder);
743 ** Get storage formatting string.
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".
751 if (!(cp = ct->c_storeproc) || !*cp) {
752 CI ci = &ct->c_ctinfo;
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 ||
761 cp = ct->c_type == CT_MESSAGE ?
768 ** Check the beginning of storage formatting string
769 ** to see if we are saving content to a folder.
771 if (*cp == '+' || *cp == '@') {
772 char *tmpfilenam, *folder;
774 /* Store content in temporary file for now */
775 tmpfilenam = m_mktemp(invo_name, NULL, NULL);
776 ct->c_storage = getcpy(tmpfilenam);
778 /* Get the folder name */
780 folder = getcpy(expandfol(cp));
782 folder = getcurfol();
784 /* Check if folder exists */
785 create_folder(toabsdir(folder), 0, exit);
787 /* Record the folder name */
788 ct->c_folder = getcpy(folder);
797 ** Parse and expand the storage formatting string
798 ** in `cp' into `buffer'.
800 parse_format_string(ct, cp, buffer, sizeof(buffer), dir);
803 ** If formatting begins with '|' or '!', then pass
804 ** content to standard input of a command and return.
806 if (buffer[0] == '|' || buffer[0] == '!')
807 return show_content_aux(ct, 0, buffer + 1, dir);
809 /* record the filename */
810 ct->c_storage = getcpy(buffer);
813 /* flush the output stream */
816 /* Now save or append the content to a file */
817 if (output_content_file(ct, appending) == NOTOK)
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.
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);
833 ** Now print out the name/number of the message
834 ** that we are storing.
838 fprintf(stderr, "reassembling partials ");
840 fprintf(stderr, "%s", ct->c_file);
842 fprintf(stderr, "%s,", ct->c_file);
844 fprintf(stderr, "storing message %s", ct->c_file);
846 fprintf(stderr, " part %s", ct->c_partno);
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.
854 if (!is_partial || last_partial) {
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");
863 cwdlen = strlen(cwd);
864 fprintf(stderr, " as file %s\n",
865 strncmp(ct->c_storage, cwd,
867 ct->c_storage[cwdlen] != '/' ?
869 ct->c_storage + cwdlen + 1);
878 ** Output content to a file
882 output_content_file(CT ct, int appending)
885 char *file, buffer[BUFSIZ];
890 ** If the pathname contains directories, make sure
891 ** all of them exist.
893 if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
897 if (ct->c_encoding != CE_7BIT) {
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);
905 file = appending || strcmp(ct->c_storage, "-")==0 ?
906 NULL : ct->c_storage;
907 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
909 if (strcmp(file, ct->c_storage)==0) {
910 (*ct->c_ceclosefnx) (ct);
915 ** Send to standard output
917 if (strcmp(ct->c_storage, "-")==0) {
920 if ((gd = dup(fileno(stdout))) == NOTOK) {
921 advise("stdout", "unable to dup");
923 (*ct->c_ceclosefnx) (ct);
926 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
927 advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
935 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
937 advise(ct->c_storage, "unable to fopen for %s",
939 "appending" : "writing");
945 ** Filter the header fields of the initial enclosing
946 ** message/partial into the file.
948 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
949 struct partial *pm = (struct partial *) ct->c_ctparams;
951 if (pm->pm_partno == 1)
952 copy_some_headers(fp, ct);
956 switch (cc = read(fd, buffer, sizeof(buffer))) {
958 advise(file, "error reading content from");
965 fwrite(buffer, sizeof(*buffer), cc, fp);
971 (*ct->c_ceclosefnx) (ct);
973 if (cc != NOTOK && fflush(fp))
974 advise(ct->c_storage, "error writing to");
978 return (cc != NOTOK ? OK : NOTOK);
981 if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
982 advise(ct->c_file, "unable to open for reading");
988 fseek(ct->c_fp, pos, SEEK_SET);
990 if (strcmp(ct->c_storage, "-")==0) {
993 if ((gd = dup(fileno(stdout))) == NOTOK) {
994 advise("stdout", "unable to dup");
997 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
998 advise("stdout", "unable to fdopen (%d, \"%s\") from",
999 gd, appending ? "a" : "w");
1004 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
1006 advise(ct->c_storage, "unable to fopen for %s",
1007 appending ? "appending" : "writing");
1013 ** Copy a few of the header fields of the initial
1014 ** enclosing message/partial into the file.
1017 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
1018 struct partial *pm = (struct partial *) ct->c_ctparams;
1020 if (pm->pm_partno == 1) {
1021 copy_some_headers(fp, ct);
1026 while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
1027 if ((pos += strlen(buffer)) > last) {
1030 diff = strlen(buffer) - (pos - last);
1032 buffer[diff] = '\0';
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.
1040 switch (buffer[0]) {
1043 if (filterstate < 0)
1052 if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
1067 advise(ct->c_storage, "error writing to");
1077 ** Add a file to a folder.
1079 ** Return the new message number of the file
1080 ** when added to the folder. Return -1, if
1081 ** there is an error.
1085 output_content_folder(char *folder, char *filename)
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);
1095 advise(NULL, "unable to read folder %s", folder);
1099 /* free folder structure */
1103 ** Return msgnum. We are relying on the fact that
1104 ** msgnum will be -1, if folder_addmsg() had an error.
1111 ** Parse and expand the storage formatting string
1112 ** pointed to by "cp" into "buffer".
1116 parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
1120 CI ci = &ct->c_ctinfo;
1123 ** If storage string is "-", just copy it, and
1124 ** return (send content to standard output).
1126 if (cp[0] == '-' && cp[1] == '\0') {
1127 strncpy(buffer, cp, buflen);
1135 ** If formatting string is a pathname that doesn't
1136 ** begin with '/', then preface the path with the
1137 ** appropriate directory.
1139 if (*cp != '/' && *cp != '|' && *cp != '!') {
1140 snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
1148 /* We are processing a storage escape */
1153 ** Insert parameters from Content-Type.
1154 ** This is only valid for '|' commands.
1156 if (buffer[0] != '|' && buffer[0] != '!') {
1165 for (ap=ci->ci_attrs, ep=ci->ci_values;
1167 snprintf(bp, buflen,
1179 /* insert message number */
1180 snprintf(bp, buflen, "%s",
1181 mhbasename(ct->c_file));
1185 /* insert part number with leading dot */
1187 snprintf(bp, buflen, ".%s",
1192 /* insert part number withouth leading dot */
1194 strncpy(bp, ct->c_partno, buflen);
1198 /* insert content type */
1199 strncpy(bp, ci->ci_type, buflen);
1203 /* insert content subtype */
1204 strncpy(bp, ci->ci_subtype, buflen);
1208 /* insert the character % */
1218 /* Advance bp and decrement buflen */
1236 ** Copy some of the header fields of the initial message/partial
1237 ** message into the header of the reassembled message.
1241 copy_some_headers(FILE *out, CT ct)
1245 hp = ct->c_first_hf; /* start at first header field */
1249 ** A few of the header fields of the enclosing
1250 ** messages are not copied.
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 */