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 if (atexit(freects_done) != 0) {
133 adios(NULL, "atexit failed");
136 setlocale(LC_ALL, "");
137 invo_name = mhbasename(argv[0]);
139 /* read user profile/context */
142 arguments = getarguments(invo_name, argc, argv, 1);
148 while ((cp = *argp++)) {
150 switch (smatch(++cp, switches)) {
152 ambigsw(cp, switches);
155 adios(NULL, "-%s unknown", cp);
158 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
159 print_help(buf, switches, 1);
162 print_version(invo_name);
173 if (!(cp = *argp++) || *cp == '-')
174 adios(NULL, "missing argument to %s",
177 adios(NULL, "too many parts (starting with %s), %d max", cp, NPARTS);
182 if (!(cp = *argp++) || *cp == '-')
183 adios(NULL, "missing argument to %s",
186 adios(NULL, "too many types (starting with %s), %d max", cp, NTYPES);
191 if (!(cp = *argp++) || (*cp == '-' && cp[1]))
192 adios(NULL, "missing argument to %s",
194 file = *cp == '-' ? cp : getcpy(expanddir(cp));
202 if (*cp == '+' || *cp == '@') {
204 adios(NULL, "only one folder at a time!");
206 folder = getcpy(expandfol(cp));
208 app_msgarg(&msgs, cp);
211 /* null terminate the list of acceptable parts/types */
218 ** Check if we've specified an additional profile
220 if ((cp = getenv("MHSTORE"))) {
221 if ((fp = fopen(cp, "r"))) {
222 readconfig((struct node **) 0, fp, cp, 0);
225 admonish("", "unable to read $MHSTORE profile (%s)",
231 ** Read the standard profile setup
233 if ((fp = fopen(cp = etcpath("mhn.defaults"), "r"))) {
234 readconfig((struct node **) 0, fp, cp, 0);
239 ** Cache the current directory before we do any chdirs()'s.
244 ** Check for storage directory. If specified,
245 ** then store temporary files there. Else we
246 ** store them in standard nmh directory.
248 if ((cp = context_find(nmhstorage)) && *cp)
249 tmp = concat(cp, "/", invo_name, NULL);
251 tmp = getcpy(toabsdir(invo_name));
253 if (file && msgs.size)
254 adios(NULL, "cannot specify msg and file at same time!");
257 ** check if message is coming from file
260 if (!(cts = (CT *) calloc((size_t) 2, sizeof(*cts))))
261 adios(NULL, "out of memory");
264 if ((ct = parse_mime(file)))
268 ** message(s) are coming from a folder
271 app_msgarg(&msgs, seq_cur);
273 folder = getcurfol();
274 maildir = toabsdir(folder);
276 if (chdir(maildir) == NOTOK)
277 adios(maildir, "unable to change directory to");
279 /* read folder and create message structure */
280 if (!(mp = folder_read(folder)))
281 adios(NULL, "unable to read folder %s", folder);
283 /* check for empty folder */
285 adios(NULL, "no messages in %s", folder);
287 /* parse all the message ranges/sequences and set SELECTED */
288 for (msgnum = 0; msgnum < msgs.size; msgnum++)
289 if (!m_convert(mp, msgs.msgs[msgnum]))
291 seq_setprev(mp); /* set the previous-sequence */
293 if (!(cts = (CT *) calloc((size_t) (mp->numsel + 1),
295 adios(NULL, "out of memory");
298 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
299 if (is_selected(mp, msgnum)) {
302 msgnam = m_name(msgnum);
303 if ((ct = parse_mime(msgnam)))
313 SIGNAL(SIGQUIT, quitser);
314 SIGNAL(SIGPIPE, pipeser);
317 ** Get the associated umask for the relevant contents.
319 for (ctp = cts; *ctp; ctp++) {
323 if (type_ok(ct, 1) && !ct->c_umask) {
324 if (stat(ct->c_file, &st) != NOTOK)
325 ct->c_umask = ~(st.st_mode & 0777);
327 ct->c_umask = ~m_gmprot();
332 ** Store the message content
334 store_all_messages(cts);
336 /* Now free all the structures for the content */
337 for (ctp = cts; *ctp; ctp++)
343 /* If reading from a folder, do some updating */
345 context_replace(curfolder, folder); /* update current folder */
346 seq_setcur(mp, mp->hghsel); /* update current message */
347 seq_save(mp); /* synchronize sequences */
348 context_save(); /* save the context file */
361 fprintf(stderr, "\n");
371 ** Main entry point to store content from a collection of messages.
374 store_all_messages(CT *cts)
380 ** Check for the directory in which to
381 ** store any contents.
383 if ((cp = context_find(nmhstorage)) && *cp)
388 for (ctp = cts; *ctp; ctp++) {
390 store_single_message(ct);
398 ** Entry point to store the content
399 ** in a (single) message
403 store_single_message(CT ct)
405 if (type_ok(ct, 1)) {
412 if (ct->c_ceclosefnx)
413 (*ct->c_ceclosefnx) (ct);
419 ** Switching routine to store different content types
425 switch (ct->c_type) {
427 return store_multi(ct);
431 switch (ct->c_subtype) {
432 case MESSAGE_PARTIAL:
433 return store_partial(ct);
436 case MESSAGE_EXTERNAL:
437 return store_external(ct);
441 return store_generic(ct);
451 return store_generic(ct);
455 adios(NULL, "unknown content type %d", ct->c_type);
459 return OK; /* NOT REACHED */
464 ** Generic routine to store a MIME content.
465 ** (application, audio, video, image, text, message/rfc922)
470 char **ap, **vp, *cp;
471 CI ci = &ct->c_ctinfo;
474 ** Check if the content specifies a filename in its MIME parameters.
475 ** Don't bother with this for type "message"
476 ** (only the "message" subtype "rfc822" will use store_generic).
478 if (autosw && ct->c_type != CT_MESSAGE) {
480 ** Check the attribute/value pairs, for the attribute "name".
481 ** If found, take the basename, do a few sanity checks and
482 ** copy the value into c_storeproc.
484 for (ap = ci->ci_attrs, vp = ci->ci_values; *ap; ap++,vp++) {
485 if (mh_strcasecmp(*ap, "name")!=0) {
488 cp = mhbasename(*vp);
489 if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
491 /* filename looks good: use it */
492 ct->c_storeproc = getcpy(cp);
498 return store_content(ct, NULL);
503 ** Store the content of a multipart message
510 struct multipart *m = (struct multipart *) ct->c_ctparams;
514 for (part = m->mp_parts; part; part = part->mp_next) {
515 CT p = part->mp_part;
517 if (part_ok(p, 1) && type_ok(p, 1)) {
518 result = store_switch(p);
519 if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
529 ** Reassemble and store the contents of a collection
530 ** of messages of type "message/partial".
539 struct partial *pm, *qm;
541 qm = (struct partial *) ct->c_ctparams;
546 for (ctp = cts; *ctp; ctp++) {
548 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
549 pm = (struct partial *) p->c_ctparams;
550 if (!pm->pm_stored &&
551 strcmp(qm->pm_partid, pm->pm_partid)
553 pm->pm_marked = pm->pm_partno;
564 advise(NULL, "missing (at least) last part of multipart message");
568 if ((base = (CT *) calloc((size_t) (i + 1), sizeof(*base))) == NULL)
569 adios(NULL, "out of memory");
572 for (ctp = cts; *ctp; ctp++) {
574 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
575 pm = (struct partial *) p->c_ctparams;
583 qsort((char *) base, i, sizeof(*base), (qsort_comp) ct_compar);
586 for (ctq = base; *ctq; ctq++) {
588 pm = (struct partial *) p->c_ctparams;
589 if (pm->pm_marked != cur) {
590 if (pm->pm_marked == cur - 1) {
591 admonish(NULL, "duplicate part %d of %d part multipart message", pm->pm_marked, hi);
596 advise (NULL, "missing %spart %d of %d part multipart message", cur != hi ? "(at least) " : "", cur, hi);
607 ** Now cycle through the sorted list of messages of type
608 ** "message/partial" and save/append them to a file.
613 if (store_content(ct, NULL) == NOTOK) {
619 for (; *ctq; ctq++) {
621 if (store_content(p, ct) == NOTOK)
631 ** Show how to retrieve content of type "message/external".
634 store_external(CT ct)
641 msg = add("You need to fetch the contents yourself:", NULL);
642 ap = ct->c_ctinfo.ci_attrs;
643 ep = ct->c_ctinfo.ci_values;
644 for (; *ap; ap++, ep++) {
645 msg = add(concat("\n\t", *ap, ": ", *ep, NULL), msg);
647 if (!(fp = fopen(ct->c_file, "r"))) {
648 adios(ct->c_file, "unable to open");
650 fseek(fp, ct->c_begin, SEEK_SET);
651 while (!feof(fp) && ftell(fp) < ct->c_end) {
652 if (!fgets(buf, sizeof buf, fp)) {
653 adios(ct->c_file, "unable to read");
655 *strchr(buf, '\n') = '\0';
656 msg = add(concat("\n\t", buf, NULL), msg);
665 ** Compare the numbering from two different
666 ** message/partials (needed for sorting).
670 ct_compar(CT *a, CT *b)
672 struct partial *am = (struct partial *) ((*a)->c_ctparams);
673 struct partial *bm = (struct partial *) ((*b)->c_ctparams);
675 return (am->pm_marked - bm->pm_marked);
680 ** Store contents of a message or message part to
681 ** a folder, a file, the standard output, or pass
682 ** the contents to a command.
684 ** If the current content to be saved is a followup part
685 ** to a collection of messages of type "message/partial",
686 ** then field "p" is a pointer to the Content structure
687 ** to the first message/partial in the group.
691 store_content(CT ct, CT p)
693 int appending = 0, msgnum = 0;
694 int is_partial = 0, first_partial = 0;
695 int last_partial = 0;
696 char *cp, buffer[BUFSIZ];
699 ** Do special processing for messages of
700 ** type "message/partial".
702 ** We first check if this content is of type
703 ** "message/partial". If it is, then we need to check
704 ** whether it is the first and/or last in the group.
706 ** Then if "p" is a valid pointer, it points to the Content
707 ** structure of the first partial in the group. So we copy
708 ** the file name and/or folder name from that message. In
709 ** this case, we also note that we will be appending.
711 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
712 struct partial *pm = (struct partial *) ct->c_ctparams;
714 /* Yep, it's a message/partial */
717 /* But is it the first and/or last in the collection? */
718 if (pm->pm_partno == 1)
720 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
724 ** If "p" is a valid pointer, then it points to the
725 ** Content structure for the first message in the group.
726 ** So we just copy the filename or foldername information
727 ** from the previous iteration of this function.
731 ct->c_storage = getcpy(p->c_storage);
733 /* record the folder name */
735 ct->c_folder = getcpy(p->c_folder);
742 ** Get storage formatting string.
744 ** 1) If we have storeproc defined, then use that
745 ** 2) Else check for a mhstore-store-<type>/<subtype> entry
746 ** 3) Else check for a mhstore-store-<type> entry
747 ** 4) Else if content is "message", use "+" (current folder)
748 ** 5) Else use string "%m%P.%s".
750 if (!(cp = ct->c_storeproc) || !*cp) {
751 CI ci = &ct->c_ctinfo;
753 snprintf(buffer, sizeof(buffer), "%s-store-%s/%s",
754 invo_name, ci->ci_type, ci->ci_subtype);
755 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
756 snprintf(buffer, sizeof(buffer), "%s-store-%s",
757 invo_name, ci->ci_type);
758 if ((cp = context_find(buffer)) == NULL ||
760 cp = ct->c_type == CT_MESSAGE ?
767 ** Check the beginning of storage formatting string
768 ** to see if we are saving content to a folder.
770 if (*cp == '+' || *cp == '@') {
771 char *tmpfilenam, *folder;
773 /* Store content in temporary file for now */
774 tmpfilenam = m_mktemp(invo_name, NULL, NULL);
775 ct->c_storage = getcpy(tmpfilenam);
777 /* Get the folder name */
779 folder = getcpy(expandfol(cp));
781 folder = getcurfol();
783 /* Check if folder exists */
784 create_folder(toabsdir(folder), 0, exit);
786 /* Record the folder name */
787 ct->c_folder = getcpy(folder);
796 ** Parse and expand the storage formatting string
797 ** in `cp' into `buffer'.
799 parse_format_string(ct, cp, buffer, sizeof(buffer), dir);
802 ** If formatting begins with '|' or '!', then pass
803 ** content to standard input of a command and return.
805 if (buffer[0] == '|' || buffer[0] == '!')
806 return show_content_aux(ct, 0, buffer + 1, dir);
808 /* record the filename */
809 ct->c_storage = getcpy(buffer);
812 /* flush the output stream */
815 /* Now save or append the content to a file */
816 if (output_content_file(ct, appending) == NOTOK)
820 ** If necessary, link the file into a folder and remove
821 ** the temporary file. If this message is a partial,
822 ** then only do this if it is the last one in the group.
824 if (ct->c_folder && (!is_partial || last_partial)) {
825 msgnum = output_content_folder(ct->c_folder, ct->c_storage);
826 unlink(ct->c_storage);
832 ** Now print out the name/number of the message
833 ** that we are storing.
837 fprintf(stderr, "reassembling partials ");
839 fprintf(stderr, "%s", ct->c_file);
841 fprintf(stderr, "%s,", ct->c_file);
843 fprintf(stderr, "storing message %s", ct->c_file);
845 fprintf(stderr, " part %s", ct->c_partno);
849 ** Unless we are in the "middle" of group of message/partials,
850 ** we now print the name of the file, folder, and/or message
851 ** to which we are storing the content.
853 if (!is_partial || last_partial) {
855 fprintf(stderr, " to folder %s as message %d\n",
856 ct->c_folder, msgnum);
857 } else if (strcmp(ct->c_storage, "-")==0) {
858 fprintf(stderr, " to stdout\n");
862 cwdlen = strlen(cwd);
863 fprintf(stderr, " as file %s\n",
864 strncmp(ct->c_storage, cwd,
866 ct->c_storage[cwdlen] != '/' ?
868 ct->c_storage + cwdlen + 1);
877 ** Output content to a file
881 output_content_file(CT ct, int appending)
884 char *file, buffer[BUFSIZ];
889 ** If the pathname contains directories, make sure
890 ** all of them exist.
892 if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
896 if (ct->c_encoding != CE_7BIT) {
899 if (!ct->c_ceopenfnx) {
900 advise(NULL, "don't know how to decode part %s of message %s", ct->c_partno, ct->c_file);
904 file = appending || strcmp(ct->c_storage, "-")==0 ?
905 NULL : ct->c_storage;
906 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
908 if (strcmp(file, ct->c_storage)==0) {
909 (*ct->c_ceclosefnx) (ct);
914 ** Send to standard output
916 if (strcmp(ct->c_storage, "-")==0) {
919 if ((gd = dup(fileno(stdout))) == NOTOK) {
920 advise("stdout", "unable to dup");
922 (*ct->c_ceclosefnx) (ct);
925 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
926 advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
934 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
936 advise(ct->c_storage, "unable to fopen for %s",
938 "appending" : "writing");
944 ** Filter the header fields of the initial enclosing
945 ** message/partial into the file.
947 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
948 struct partial *pm = (struct partial *) ct->c_ctparams;
950 if (pm->pm_partno == 1)
951 copy_some_headers(fp, ct);
955 switch (cc = read(fd, buffer, sizeof(buffer))) {
957 advise(file, "error reading content from");
964 fwrite(buffer, sizeof(*buffer), cc, fp);
970 (*ct->c_ceclosefnx) (ct);
972 if (cc != NOTOK && fflush(fp))
973 advise(ct->c_storage, "error writing to");
977 return (cc != NOTOK ? OK : NOTOK);
980 if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
981 advise(ct->c_file, "unable to open for reading");
987 fseek(ct->c_fp, pos, SEEK_SET);
989 if (strcmp(ct->c_storage, "-")==0) {
992 if ((gd = dup(fileno(stdout))) == NOTOK) {
993 advise("stdout", "unable to dup");
996 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
997 advise("stdout", "unable to fdopen (%d, \"%s\") from",
998 gd, appending ? "a" : "w");
1003 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
1005 advise(ct->c_storage, "unable to fopen for %s",
1006 appending ? "appending" : "writing");
1012 ** Copy a few of the header fields of the initial
1013 ** enclosing message/partial into the file.
1016 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
1017 struct partial *pm = (struct partial *) ct->c_ctparams;
1019 if (pm->pm_partno == 1) {
1020 copy_some_headers(fp, ct);
1025 while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
1026 if ((pos += strlen(buffer)) > last) {
1029 diff = strlen(buffer) - (pos - last);
1031 buffer[diff] = '\0';
1034 ** If this is the first content of a group of
1035 ** message/partial contents, then we only copy a few
1036 ** of the header fields of the enclosed message.
1039 switch (buffer[0]) {
1042 if (filterstate < 0)
1051 if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
1066 advise(ct->c_storage, "error writing to");
1076 ** Add a file to a folder.
1078 ** Return the new message number of the file
1079 ** when added to the folder. Return -1, if
1080 ** there is an error.
1084 output_content_folder(char *folder, char *filename)
1089 /* Read the folder. */
1090 if ((mp = folder_read(folder))) {
1091 /* Link file into folder */
1092 msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
1094 advise(NULL, "unable to read folder %s", folder);
1098 /* free folder structure */
1102 ** Return msgnum. We are relying on the fact that
1103 ** msgnum will be -1, if folder_addmsg() had an error.
1110 ** Parse and expand the storage formatting string
1111 ** pointed to by "cp" into "buffer".
1115 parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
1119 CI ci = &ct->c_ctinfo;
1122 ** If storage string is "-", just copy it, and
1123 ** return (send content to standard output).
1125 if (cp[0] == '-' && cp[1] == '\0') {
1126 strncpy(buffer, cp, buflen);
1134 ** If formatting string is a pathname that doesn't
1135 ** begin with '/', then preface the path with the
1136 ** appropriate directory.
1138 if (*cp != '/' && *cp != '|' && *cp != '!') {
1139 snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
1147 /* We are processing a storage escape */
1152 ** Insert parameters from Content-Type.
1153 ** This is only valid for '|' commands.
1155 if (buffer[0] != '|' && buffer[0] != '!') {
1164 for (ap=ci->ci_attrs, ep=ci->ci_values;
1166 snprintf(bp, buflen,
1178 /* insert message number */
1179 snprintf(bp, buflen, "%s",
1180 mhbasename(ct->c_file));
1184 /* insert part number with leading dot */
1186 snprintf(bp, buflen, ".%s",
1191 /* insert part number withouth leading dot */
1193 strncpy(bp, ct->c_partno, buflen);
1197 /* insert content type */
1198 strncpy(bp, ci->ci_type, buflen);
1202 /* insert content subtype */
1203 strncpy(bp, ci->ci_subtype, buflen);
1207 /* insert the character % */
1217 /* Advance bp and decrement buflen */
1235 ** Copy some of the header fields of the initial message/partial
1236 ** message into the header of the reassembled message.
1240 copy_some_headers(FILE *out, CT ct)
1244 hp = ct->c_first_hf; /* start at first header field */
1248 ** A few of the header fields of the enclosing
1249 ** messages are not copied.
1251 if (!uprf(hp->name, XXX_FIELD_PRF) &&
1252 mh_strcasecmp(hp->name, VRSN_FIELD) &&
1253 mh_strcasecmp(hp->name, "Subject") &&
1254 mh_strcasecmp(hp->name, "Message-ID"))
1255 fprintf(out, "%s:%s", hp->name, hp->value);
1256 hp = hp->next; /* next header field */