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 if (!(cts = (CT *) mh_xcalloc((size_t) 2, sizeof(*cts))))
265 adios(EX_OSERR, NULL, "out of memory");
268 if ((ct = parse_mime(file)))
272 ** message(s) are coming from a folder
275 app_msgarg(&msgs, seq_cur);
277 folder = getcurfol();
278 maildir = toabsdir(folder);
280 if (chdir(maildir) == NOTOK)
281 adios(EX_OSERR, maildir, "unable to change directory to");
283 /* read folder and create message structure */
284 if (!(mp = folder_read(folder)))
285 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
287 /* check for empty folder */
289 adios(EX_DATAERR, NULL, "no messages in %s", folder);
291 /* parse all the message ranges/sequences and set SELECTED */
292 for (msgnum = 0; msgnum < msgs.size; msgnum++)
293 if (!m_convert(mp, msgs.msgs[msgnum]))
295 seq_setprev(mp); /* set the previous-sequence */
297 if (!(cts = (CT *) mh_xcalloc((size_t) (mp->numsel + 1),
299 adios(EX_OSERR, NULL, "out of memory");
302 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
303 if (is_selected(mp, msgnum)) {
306 msgnam = m_name(msgnum);
307 if ((ct = parse_mime(msgnam)))
317 SIGNAL(SIGQUIT, quitser);
318 SIGNAL(SIGPIPE, pipeser);
321 ** Get the associated umask for the relevant contents.
323 for (ctp = cts; *ctp; ctp++) {
327 if (type_ok(ct, 1) && !ct->c_umask) {
328 if (stat(ct->c_file, &st) != NOTOK)
329 ct->c_umask = ~(st.st_mode & 0777);
331 ct->c_umask = ~m_gmprot();
336 ** Store the message content
338 store_all_messages(cts);
340 /* Now free all the structures for the content */
341 for (ctp = cts; *ctp; ctp++)
347 /* If reading from a folder, do some updating */
349 context_replace(curfolder, folder); /* update current folder */
350 seq_setcur(mp, mp->hghsel); /* update current message */
351 seq_save(mp); /* synchronize sequences */
352 context_save(); /* save the context file */
365 fprintf(stderr, "\n");
376 ** Main entry point to store content from a collection of messages.
379 store_all_messages(CT *cts)
385 ** Check for the directory in which to
386 ** store any contents.
388 if ((cp = context_find(nmhstorage)) && *cp)
393 for (ctp = cts; *ctp; ctp++) {
395 store_single_message(ct);
403 ** Entry point to store the content
404 ** in a (single) message
408 store_single_message(CT ct)
410 if (type_ok(ct, 1)) {
417 if (ct->c_ceclosefnx)
418 (*ct->c_ceclosefnx) (ct);
424 ** Switching routine to store different content types
430 switch (ct->c_type) {
432 return store_multi(ct);
436 switch (ct->c_subtype) {
437 case MESSAGE_PARTIAL:
438 return store_partial(ct);
441 case MESSAGE_EXTERNAL:
442 return store_external(ct);
446 return store_generic(ct);
456 return store_generic(ct);
460 adios(EX_DATAERR, NULL, "unknown content type %d", ct->c_type);
464 return OK; /* NOT REACHED */
469 ** Generic routine to store a MIME content.
470 ** (application, audio, video, image, text, message/rfc922)
475 char **ap, **vp, *cp;
476 CI ci = &ct->c_ctinfo;
479 ** Check if the content specifies a filename in its MIME parameters.
480 ** Don't bother with this for type "message"
481 ** (only the "message" subtype "rfc822" will use store_generic).
483 if (autosw && ct->c_type != CT_MESSAGE) {
485 ** Check the attribute/value pairs, for the attribute "name".
486 ** If found, take the basename, do a few sanity checks and
487 ** copy the value into c_storeproc.
489 for (ap = ci->ci_attrs, vp = ci->ci_values; *ap; ap++,vp++) {
490 if (mh_strcasecmp(*ap, "name")!=0) {
493 cp = mhbasename(*vp);
494 if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
496 /* filename looks good: use it */
497 ct->c_storeproc = getcpy(cp);
503 return store_content(ct, NULL);
508 ** Store the content of a multipart message
515 struct multipart *m = (struct multipart *) ct->c_ctparams;
519 for (part = m->mp_parts; part; part = part->mp_next) {
520 CT p = part->mp_part;
522 if (part_ok(p, 1) && type_ok(p, 1)) {
523 result = store_switch(p);
524 if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
534 ** Reassemble and store the contents of a collection
535 ** of messages of type "message/partial".
544 struct partial *pm, *qm;
546 qm = (struct partial *) ct->c_ctparams;
551 for (ctp = cts; *ctp; ctp++) {
553 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
554 pm = (struct partial *) p->c_ctparams;
555 if (!pm->pm_stored &&
556 strcmp(qm->pm_partid, pm->pm_partid)
558 pm->pm_marked = pm->pm_partno;
569 advise(NULL, "missing (at least) last part of multipart message");
573 if ((base = (CT *) mh_xcalloc((size_t) (i + 1), sizeof(*base))) == NULL)
574 adios(EX_OSERR, NULL, "out of memory");
577 for (ctp = cts; *ctp; ctp++) {
579 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
580 pm = (struct partial *) p->c_ctparams;
588 qsort((char *) base, i, sizeof(*base), (qsort_comp) ct_compar);
591 for (ctq = base; *ctq; ctq++) {
593 pm = (struct partial *) p->c_ctparams;
594 if (pm->pm_marked != cur) {
595 if (pm->pm_marked == cur - 1) {
596 admonish(NULL, "duplicate part %d of %d part multipart message", pm->pm_marked, hi);
601 advise (NULL, "missing %spart %d of %d part multipart message", cur != hi ? "(at least) " : "", cur, hi);
612 ** Now cycle through the sorted list of messages of type
613 ** "message/partial" and save/append them to a file.
618 if (store_content(ct, NULL) == NOTOK) {
624 for (; *ctq; ctq++) {
626 if (store_content(p, ct) == NOTOK)
636 ** Show how to retrieve content of type "message/external".
639 store_external(CT ct)
646 msg = add("You need to fetch the contents yourself:", NULL);
647 ap = ct->c_ctinfo.ci_attrs;
648 ep = ct->c_ctinfo.ci_values;
649 for (; *ap; ap++, ep++) {
650 msg = add(concat("\n\t", *ap, ": ", *ep, NULL), msg);
652 if (!(fp = fopen(ct->c_file, "r"))) {
653 adios(EX_IOERR, ct->c_file, "unable to open");
655 fseek(fp, ct->c_begin, SEEK_SET);
656 while (!feof(fp) && ftell(fp) < ct->c_end) {
657 if (!fgets(buf, sizeof buf, fp)) {
658 adios(EX_IOERR, ct->c_file, "unable to read");
660 *strchr(buf, '\n') = '\0';
661 msg = add(concat("\n\t", buf, NULL), msg);
670 ** Compare the numbering from two different
671 ** message/partials (needed for sorting).
675 ct_compar(CT *a, CT *b)
677 struct partial *am = (struct partial *) ((*a)->c_ctparams);
678 struct partial *bm = (struct partial *) ((*b)->c_ctparams);
680 return (am->pm_marked - bm->pm_marked);
685 ** Store contents of a message or message part to
686 ** a folder, a file, the standard output, or pass
687 ** the contents to a command.
689 ** If the current content to be saved is a followup part
690 ** to a collection of messages of type "message/partial",
691 ** then field "p" is a pointer to the Content structure
692 ** to the first message/partial in the group.
696 store_content(CT ct, CT p)
698 int appending = 0, msgnum = 0;
699 int is_partial = 0, first_partial = 0;
700 int last_partial = 0;
701 char *cp, buffer[BUFSIZ];
704 ** Do special processing for messages of
705 ** type "message/partial".
707 ** We first check if this content is of type
708 ** "message/partial". If it is, then we need to check
709 ** whether it is the first and/or last in the group.
711 ** Then if "p" is a valid pointer, it points to the Content
712 ** structure of the first partial in the group. So we copy
713 ** the file name and/or folder name from that message. In
714 ** this case, we also note that we will be appending.
716 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
717 struct partial *pm = (struct partial *) ct->c_ctparams;
719 /* Yep, it's a message/partial */
722 /* But is it the first and/or last in the collection? */
723 if (pm->pm_partno == 1)
725 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
729 ** If "p" is a valid pointer, then it points to the
730 ** Content structure for the first message in the group.
731 ** So we just copy the filename or foldername information
732 ** from the previous iteration of this function.
736 ct->c_storage = getcpy(p->c_storage);
738 /* record the folder name */
740 ct->c_folder = getcpy(p->c_folder);
747 ** Get storage formatting string.
749 ** 1) If we have storeproc defined, then use that
750 ** 2) Else check for a mhstore-store-<type>/<subtype> entry
751 ** 3) Else check for a mhstore-store-<type> entry
752 ** 4) Else if content is "message", use "+" (current folder)
753 ** 5) Else use string "%m%P.%s".
755 if (!(cp = ct->c_storeproc) || !*cp) {
756 CI ci = &ct->c_ctinfo;
758 snprintf(buffer, sizeof(buffer), "%s-store-%s/%s",
759 invo_name, ci->ci_type, ci->ci_subtype);
760 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
761 snprintf(buffer, sizeof(buffer), "%s-store-%s",
762 invo_name, ci->ci_type);
763 if ((cp = context_find(buffer)) == NULL ||
765 cp = ct->c_type == CT_MESSAGE ?
772 ** Check the beginning of storage formatting string
773 ** to see if we are saving content to a folder.
775 if (*cp == '+' || *cp == '@') {
776 char *tmpfilenam, *folder;
778 /* Store content in temporary file for now */
779 tmpfilenam = m_mktemp(invo_name, NULL, NULL);
780 ct->c_storage = getcpy(tmpfilenam);
782 /* Get the folder name */
784 folder = getcpy(expandfol(cp));
786 folder = getcurfol();
788 /* Check if folder exists */
789 create_folder(toabsdir(folder), 0, exit);
791 /* Record the folder name */
792 ct->c_folder = getcpy(folder);
801 ** Parse and expand the storage formatting string
802 ** in `cp' into `buffer'.
804 parse_format_string(ct, cp, buffer, sizeof(buffer), dir);
807 ** If formatting begins with '|' or '!', then pass
808 ** content to standard input of a command and return.
810 if (buffer[0] == '|' || buffer[0] == '!')
811 return show_content_aux(ct, 0, buffer + 1, dir);
813 /* record the filename */
814 ct->c_storage = getcpy(buffer);
817 /* flush the output stream */
820 /* Now save or append the content to a file */
821 if (output_content_file(ct, appending) == NOTOK)
825 ** If necessary, link the file into a folder and remove
826 ** the temporary file. If this message is a partial,
827 ** then only do this if it is the last one in the group.
829 if (ct->c_folder && (!is_partial || last_partial)) {
830 msgnum = output_content_folder(ct->c_folder, ct->c_storage);
831 unlink(ct->c_storage);
837 ** Now print out the name/number of the message
838 ** that we are storing.
842 fprintf(stderr, "reassembling partials ");
844 fprintf(stderr, "%s", ct->c_file);
846 fprintf(stderr, "%s,", ct->c_file);
848 fprintf(stderr, "storing message %s", ct->c_file);
850 fprintf(stderr, " part %s", ct->c_partno);
854 ** Unless we are in the "middle" of group of message/partials,
855 ** we now print the name of the file, folder, and/or message
856 ** to which we are storing the content.
858 if (!is_partial || last_partial) {
860 fprintf(stderr, " to folder %s as message %d\n",
861 ct->c_folder, msgnum);
862 } else if (strcmp(ct->c_storage, "-")==0) {
863 fprintf(stderr, " to stdout\n");
867 cwdlen = strlen(cwd);
868 fprintf(stderr, " as file %s\n",
869 strncmp(ct->c_storage, cwd,
871 ct->c_storage[cwdlen] != '/' ?
873 ct->c_storage + cwdlen + 1);
882 ** Output content to a file
886 output_content_file(CT ct, int appending)
889 char *file, buffer[BUFSIZ];
894 ** If the pathname contains directories, make sure
895 ** all of them exist.
897 if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
901 if (ct->c_encoding != CE_7BIT) {
904 if (!ct->c_ceopenfnx) {
905 advise(NULL, "don't know how to decode part %s of message %s", ct->c_partno, ct->c_file);
909 file = appending || strcmp(ct->c_storage, "-")==0 ?
910 NULL : ct->c_storage;
911 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
913 if (strcmp(file, ct->c_storage)==0) {
914 (*ct->c_ceclosefnx) (ct);
919 ** Send to standard output
921 if (strcmp(ct->c_storage, "-")==0) {
924 if ((gd = dup(fileno(stdout))) == NOTOK) {
925 advise("stdout", "unable to dup");
927 (*ct->c_ceclosefnx) (ct);
930 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
931 advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
939 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
941 advise(ct->c_storage, "unable to fopen for %s",
943 "appending" : "writing");
949 ** Filter the header fields of the initial enclosing
950 ** message/partial into the file.
952 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
953 struct partial *pm = (struct partial *) ct->c_ctparams;
955 if (pm->pm_partno == 1)
956 copy_some_headers(fp, ct);
960 switch (cc = read(fd, buffer, sizeof(buffer))) {
962 advise(file, "error reading content from");
969 fwrite(buffer, sizeof(*buffer), cc, fp);
975 (*ct->c_ceclosefnx) (ct);
977 if (cc != NOTOK && fflush(fp))
978 advise(ct->c_storage, "error writing to");
982 return (cc != NOTOK ? OK : NOTOK);
985 if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
986 advise(ct->c_file, "unable to open for reading");
992 fseek(ct->c_fp, pos, SEEK_SET);
994 if (strcmp(ct->c_storage, "-")==0) {
997 if ((gd = dup(fileno(stdout))) == NOTOK) {
998 advise("stdout", "unable to dup");
1001 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
1002 advise("stdout", "unable to fdopen (%d, \"%s\") from",
1003 gd, appending ? "a" : "w");
1008 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
1010 advise(ct->c_storage, "unable to fopen for %s",
1011 appending ? "appending" : "writing");
1017 ** Copy a few of the header fields of the initial
1018 ** enclosing message/partial into the file.
1021 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
1022 struct partial *pm = (struct partial *) ct->c_ctparams;
1024 if (pm->pm_partno == 1) {
1025 copy_some_headers(fp, ct);
1030 while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
1031 if ((pos += strlen(buffer)) > last) {
1034 diff = strlen(buffer) - (pos - last);
1036 buffer[diff] = '\0';
1039 ** If this is the first content of a group of
1040 ** message/partial contents, then we only copy a few
1041 ** of the header fields of the enclosed message.
1044 switch (buffer[0]) {
1047 if (filterstate < 0)
1056 if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
1071 advise(ct->c_storage, "error writing to");
1081 ** Add a file to a folder.
1083 ** Return the new message number of the file
1084 ** when added to the folder. Return -1, if
1085 ** there is an error.
1089 output_content_folder(char *folder, char *filename)
1094 /* Read the folder. */
1095 if ((mp = folder_read(folder))) {
1096 /* Link file into folder */
1097 msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
1099 advise(NULL, "unable to read folder %s", folder);
1103 /* free folder structure */
1107 ** Return msgnum. We are relying on the fact that
1108 ** msgnum will be -1, if folder_addmsg() had an error.
1115 ** Parse and expand the storage formatting string
1116 ** pointed to by "cp" into "buffer".
1120 parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
1124 CI ci = &ct->c_ctinfo;
1127 ** If storage string is "-", just copy it, and
1128 ** return (send content to standard output).
1130 if (cp[0] == '-' && cp[1] == '\0') {
1131 strncpy(buffer, cp, buflen);
1139 ** If formatting string is a pathname that doesn't
1140 ** begin with '/', then preface the path with the
1141 ** appropriate directory.
1143 if (*cp != '/' && *cp != '|' && *cp != '!') {
1144 snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
1152 /* We are processing a storage escape */
1157 ** Insert parameters from Content-Type.
1158 ** This is only valid for '|' commands.
1160 if (buffer[0] != '|' && buffer[0] != '!') {
1169 for (ap=ci->ci_attrs, ep=ci->ci_values;
1171 snprintf(bp, buflen,
1183 /* insert message number */
1184 snprintf(bp, buflen, "%s",
1185 mhbasename(ct->c_file));
1189 /* insert part number with leading dot */
1191 snprintf(bp, buflen, ".%s",
1196 /* insert part number withouth leading dot */
1198 strncpy(bp, ct->c_partno, buflen);
1202 /* insert content type */
1203 strncpy(bp, ci->ci_type, buflen);
1207 /* insert content subtype */
1208 strncpy(bp, ci->ci_subtype, buflen);
1212 /* insert the character % */
1222 /* Advance bp and decrement buflen */
1240 ** Copy some of the header fields of the initial message/partial
1241 ** message into the header of the reassembled message.
1245 copy_some_headers(FILE *out, CT ct)
1249 hp = ct->c_first_hf; /* start at first header field */
1253 ** A few of the header fields of the enclosing
1254 ** messages are not copied.
1256 if (!uprf(hp->name, XXX_FIELD_PRF) &&
1257 mh_strcasecmp(hp->name, VRSN_FIELD) &&
1258 mh_strcasecmp(hp->name, "Subject") &&
1259 mh_strcasecmp(hp->name, "Message-ID"))
1260 fprintf(out, "%s:%s", hp->name, hp->value);
1261 hp = hp->next; /* next header field */