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>
17 #include <h/mhparse.h>
20 static struct swit switches[] = {
25 #define FILESW 2 /* interface from show */
30 { "type content", 0 },
42 extern char *tmp; /* directory to place temp files */
47 extern char *parts[NPARTS + 1];
48 extern char *types[NTYPES + 1];
53 #define quitser pipeser
56 CT parse_mime(char *);
61 void set_endian(void);
62 void flush_errors(void);
65 void free_content(CT);
66 extern CT *cts; /* The list of top-level contents to display */
67 void freects_done(int) NORETURN;
72 static void pipeser(int);
77 ** Cache of current directory. This must be
78 ** set before these routines are called.
83 ** The directory in which to store the contents.
88 ** Type for a compare function for qsort. This keeps
89 ** the compiler happy.
91 typedef int (*qsort_comp) (const void *, const void *);
97 int make_intermediates(char *);
98 void flush_errors(void);
101 int show_content_aux(CT, int, char *, char *);
106 static void store_single_message(CT);
107 static int store_switch(CT);
108 static int store_generic(CT);
109 static int store_multi(CT);
110 static int store_partial(CT);
111 static int store_external(CT);
112 static int ct_compar(CT *, CT *);
113 static int store_content(CT, CT);
114 static int output_content_file(CT, int);
115 static int output_content_folder(char *, char *);
116 static int parse_format_string(CT, char *, char *, int, char *);
117 static int copy_some_headers(FILE *, CT);
118 static void store_all_messages(CT *);
122 main(int argc, char **argv)
125 char *cp, *file = NULL, *folder = NULL;
126 char *maildir, buf[100], **argp;
128 struct msgs_array msgs = { 0, 0, NULL };
129 struct msgs *mp = NULL;
136 setlocale(LC_ALL, "");
138 invo_name = mhbasename(argv[0]);
140 /* read user profile/context */
143 arguments = getarguments(invo_name, argc, argv, 1);
149 while ((cp = *argp++)) {
151 switch (smatch(++cp, switches)) {
153 ambigsw(cp, switches);
156 adios(NULL, "-%s unknown", cp);
159 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
160 print_help(buf, switches, 1);
163 print_version(invo_name);
174 if (!(cp = *argp++) || *cp == '-')
175 adios(NULL, "missing argument to %s",
178 adios(NULL, "too many parts (starting with %s), %d max", cp, NPARTS);
183 if (!(cp = *argp++) || *cp == '-')
184 adios(NULL, "missing argument to %s",
187 adios(NULL, "too many types (starting with %s), %d max", cp, NTYPES);
192 if (!(cp = *argp++) || (*cp == '-' && cp[1]))
193 adios(NULL, "missing argument to %s",
195 file = *cp == '-' ? cp : getcpy(expanddir(cp));
203 if (*cp == '+' || *cp == '@') {
205 adios(NULL, "only one folder at a time!");
207 folder = getcpy(expandfol(cp));
209 app_msgarg(&msgs, cp);
212 /* null terminate the list of acceptable parts/types */
219 ** Check if we've specified an additional profile
221 if ((cp = getenv("MHSTORE"))) {
222 if ((fp = fopen(cp, "r"))) {
223 readconfig((struct node **) 0, fp, cp, 0);
226 admonish("", "unable to read $MHSTORE profile (%s)",
232 ** Read the standard profile setup
234 if ((fp = fopen(cp = etcpath("mhn.defaults"), "r"))) {
235 readconfig((struct node **) 0, fp, cp, 0);
240 ** Cache the current directory before we do any chdirs()'s.
245 ** Check for storage directory. If specified,
246 ** then store temporary files there. Else we
247 ** store them in standard nmh directory.
249 if ((cp = context_find(nmhstorage)) && *cp)
250 tmp = concat(cp, "/", invo_name, NULL);
252 tmp = getcpy(toabsdir(invo_name));
254 if (file && msgs.size)
255 adios(NULL, "cannot specify msg and file at same time!");
258 ** check if message is coming from file
261 if (!(cts = (CT *) calloc((size_t) 2, sizeof(*cts))))
262 adios(NULL, "out of memory");
265 if ((ct = parse_mime(file)))
269 ** message(s) are coming from a folder
272 app_msgarg(&msgs, seq_cur);
274 folder = getcurfol();
275 maildir = toabsdir(folder);
277 if (chdir(maildir) == NOTOK)
278 adios(maildir, "unable to change directory to");
280 /* read folder and create message structure */
281 if (!(mp = folder_read(folder)))
282 adios(NULL, "unable to read folder %s", folder);
284 /* check for empty folder */
286 adios(NULL, "no messages in %s", folder);
288 /* parse all the message ranges/sequences and set SELECTED */
289 for (msgnum = 0; msgnum < msgs.size; msgnum++)
290 if (!m_convert(mp, msgs.msgs[msgnum]))
292 seq_setprev(mp); /* set the previous-sequence */
294 if (!(cts = (CT *) calloc((size_t) (mp->numsel + 1),
296 adios(NULL, "out of memory");
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 */
363 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(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)
473 char **ap, **vp, *cp;
474 CI ci = &ct->c_ctinfo;
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 ** The storeproc may already be defined, if this content
481 ** is part of a "message/external", for instance.
483 if (autosw && ct->c_type != CT_MESSAGE && !ct->c_storeproc) {
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 *) calloc((size_t) (i + 1), sizeof(*base))) == NULL)
574 adios(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 ** Store content from a message of type "message/external".
640 store_external(CT ct)
643 struct exbody *e = (struct exbody *) ct->c_ctparams;
644 CT p = e->eb_content;
650 ** Check if the parameters for the external body
651 ** specified a filename.
656 cp = mhbasename(e->eb_name);
657 if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
659 /* filename looks good: use it */
660 if (!ct->c_storeproc)
661 ct->c_storeproc = getcpy(cp);
663 p->c_storeproc = getcpy(cp);
668 ** Since we will let the Content structure for the
669 ** external body substitute for the current content,
670 ** we temporarily change its partno (number inside
671 ** multipart), so everything looks right.
673 p->c_partno = ct->c_partno;
675 /* we probably need to check if content is really there */
676 result = store_switch(p);
684 ** Compare the numbering from two different
685 ** message/partials (needed for sorting).
689 ct_compar(CT *a, CT *b)
691 struct partial *am = (struct partial *) ((*a)->c_ctparams);
692 struct partial *bm = (struct partial *) ((*b)->c_ctparams);
694 return (am->pm_marked - bm->pm_marked);
699 ** Store contents of a message or message part to
700 ** a folder, a file, the standard output, or pass
701 ** the contents to a command.
703 ** If the current content to be saved is a followup part
704 ** to a collection of messages of type "message/partial",
705 ** then field "p" is a pointer to the Content structure
706 ** to the first message/partial in the group.
710 store_content(CT ct, CT p)
712 int appending = 0, msgnum = 0;
713 int is_partial = 0, first_partial = 0;
714 int last_partial = 0;
715 char *cp, buffer[BUFSIZ];
718 ** Do special processing for messages of
719 ** type "message/partial".
721 ** We first check if this content is of type
722 ** "message/partial". If it is, then we need to check
723 ** whether it is the first and/or last in the group.
725 ** Then if "p" is a valid pointer, it points to the Content
726 ** structure of the first partial in the group. So we copy
727 ** the file name and/or folder name from that message. In
728 ** this case, we also note that we will be appending.
730 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
731 struct partial *pm = (struct partial *) ct->c_ctparams;
733 /* Yep, it's a message/partial */
736 /* But is it the first and/or last in the collection? */
737 if (pm->pm_partno == 1)
739 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
743 ** If "p" is a valid pointer, then it points to the
744 ** Content structure for the first message in the group.
745 ** So we just copy the filename or foldername information
746 ** from the previous iteration of this function.
750 ct->c_storage = getcpy(p->c_storage);
752 /* record the folder name */
754 ct->c_folder = getcpy(p->c_folder);
761 ** Get storage formatting string.
763 ** 1) If we have storeproc defined, then use that
764 ** 2) Else check for a mhstore-store-<type>/<subtype> entry
765 ** 3) Else check for a mhstore-store-<type> entry
766 ** 4) Else if content is "message", use "+" (current folder)
767 ** 5) Else use string "%m%P.%s".
769 if ((cp = ct->c_storeproc) == NULL || *cp == '\0') {
770 CI ci = &ct->c_ctinfo;
772 snprintf(buffer, sizeof(buffer), "%s-store-%s/%s",
773 invo_name, ci->ci_type, ci->ci_subtype);
774 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
775 snprintf(buffer, sizeof(buffer), "%s-store-%s",
776 invo_name, ci->ci_type);
777 if ((cp = context_find(buffer)) == NULL ||
779 cp = ct->c_type == CT_MESSAGE ?
786 ** Check the beginning of storage formatting string
787 ** to see if we are saving content to a folder.
789 if (*cp == '+' || *cp == '@') {
790 char *tmpfilenam, *folder;
792 /* Store content in temporary file for now */
793 tmpfilenam = m_mktemp(invo_name, NULL, NULL);
794 ct->c_storage = getcpy(tmpfilenam);
796 /* Get the folder name */
798 folder = getcpy(expandfol(cp));
800 folder = getcurfol();
802 /* Check if folder exists */
803 create_folder(toabsdir(folder), 0, exit);
805 /* Record the folder name */
806 ct->c_folder = getcpy(folder);
815 ** Parse and expand the storage formatting string
816 ** in `cp' into `buffer'.
818 parse_format_string(ct, cp, buffer, sizeof(buffer), dir);
821 ** If formatting begins with '|' or '!', then pass
822 ** content to standard input of a command and return.
824 if (buffer[0] == '|' || buffer[0] == '!')
825 return show_content_aux(ct, 0, buffer + 1, dir);
827 /* record the filename */
828 ct->c_storage = getcpy(buffer);
831 /* flush the output stream */
834 /* Now save or append the content to a file */
835 if (output_content_file(ct, appending) == NOTOK)
839 ** If necessary, link the file into a folder and remove
840 ** the temporary file. If this message is a partial,
841 ** then only do this if it is the last one in the group.
843 if (ct->c_folder && (!is_partial || last_partial)) {
844 msgnum = output_content_folder(ct->c_folder, ct->c_storage);
845 unlink(ct->c_storage);
851 ** Now print out the name/number of the message
852 ** that we are storing.
856 fprintf(stderr, "reassembling partials ");
858 fprintf(stderr, "%s", ct->c_file);
860 fprintf(stderr, "%s,", ct->c_file);
862 fprintf(stderr, "storing message %s", ct->c_file);
864 fprintf(stderr, " part %s", ct->c_partno);
868 ** Unless we are in the "middle" of group of message/partials,
869 ** we now print the name of the file, folder, and/or message
870 ** to which we are storing the content.
872 if (!is_partial || last_partial) {
874 fprintf(stderr, " to folder %s as message %d\n",
875 ct->c_folder, msgnum);
876 } else if (strcmp(ct->c_storage, "-")==0) {
877 fprintf(stderr, " to stdout\n");
881 cwdlen = strlen(cwd);
882 fprintf(stderr, " as file %s\n",
883 strncmp(ct->c_storage, cwd,
885 ct->c_storage[cwdlen] != '/' ?
887 ct->c_storage + cwdlen + 1);
896 ** Output content to a file
900 output_content_file(CT ct, int appending)
903 char *file, buffer[BUFSIZ];
908 ** If the pathname contains directories, make sure
909 ** all of them exist.
911 if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
915 if (ct->c_encoding != CE_7BIT) {
918 if (!ct->c_ceopenfnx) {
919 advise(NULL, "don't know how to decode part %s of message %s", ct->c_partno, ct->c_file);
923 file = appending || strcmp(ct->c_storage, "-")==0 ?
924 NULL : ct->c_storage;
925 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
927 if (strcmp(file, ct->c_storage)==0) {
928 (*ct->c_ceclosefnx) (ct);
933 ** Send to standard output
935 if (strcmp(ct->c_storage, "-")==0) {
938 if ((gd = dup(fileno(stdout))) == NOTOK) {
939 advise("stdout", "unable to dup");
941 (*ct->c_ceclosefnx) (ct);
944 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
945 advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
953 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
955 advise(ct->c_storage, "unable to fopen for %s",
957 "appending" : "writing");
963 ** Filter the header fields of the initial enclosing
964 ** message/partial into the file.
966 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
967 struct partial *pm = (struct partial *) ct->c_ctparams;
969 if (pm->pm_partno == 1)
970 copy_some_headers(fp, ct);
974 switch (cc = read(fd, buffer, sizeof(buffer))) {
976 advise(file, "error reading content from");
983 fwrite(buffer, sizeof(*buffer), cc, fp);
989 (*ct->c_ceclosefnx) (ct);
991 if (cc != NOTOK && fflush(fp))
992 advise(ct->c_storage, "error writing to");
996 return (cc != NOTOK ? OK : NOTOK);
999 if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
1000 advise(ct->c_file, "unable to open for reading");
1006 fseek(ct->c_fp, pos, SEEK_SET);
1008 if (strcmp(ct->c_storage, "-")==0) {
1011 if ((gd = dup(fileno(stdout))) == NOTOK) {
1012 advise("stdout", "unable to dup");
1015 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
1016 advise("stdout", "unable to fdopen (%d, \"%s\") from",
1017 gd, appending ? "a" : "w");
1022 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
1024 advise(ct->c_storage, "unable to fopen for %s",
1025 appending ? "appending" : "writing");
1031 ** Copy a few of the header fields of the initial
1032 ** enclosing message/partial into the file.
1035 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
1036 struct partial *pm = (struct partial *) ct->c_ctparams;
1038 if (pm->pm_partno == 1) {
1039 copy_some_headers(fp, ct);
1044 while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
1045 if ((pos += strlen(buffer)) > last) {
1048 diff = strlen(buffer) - (pos - last);
1050 buffer[diff] = '\0';
1053 ** If this is the first content of a group of
1054 ** message/partial contents, then we only copy a few
1055 ** of the header fields of the enclosed message.
1058 switch (buffer[0]) {
1061 if (filterstate < 0)
1070 if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
1085 advise(ct->c_storage, "error writing to");
1095 ** Add a file to a folder.
1097 ** Return the new message number of the file
1098 ** when added to the folder. Return -1, if
1099 ** there is an error.
1103 output_content_folder(char *folder, char *filename)
1108 /* Read the folder. */
1109 if ((mp = folder_read(folder))) {
1110 /* Link file into folder */
1111 msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
1113 advise(NULL, "unable to read folder %s", folder);
1117 /* free folder structure */
1121 ** Return msgnum. We are relying on the fact that
1122 ** msgnum will be -1, if folder_addmsg() had an error.
1129 ** Parse and expand the storage formatting string
1130 ** pointed to by "cp" into "buffer".
1134 parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
1138 CI ci = &ct->c_ctinfo;
1141 ** If storage string is "-", just copy it, and
1142 ** return (send content to standard output).
1144 if (cp[0] == '-' && cp[1] == '\0') {
1145 strncpy(buffer, cp, buflen);
1153 ** If formatting string is a pathname that doesn't
1154 ** begin with '/', then preface the path with the
1155 ** appropriate directory.
1157 if (*cp != '/' && *cp != '|' && *cp != '!') {
1158 snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
1166 /* We are processing a storage escape */
1171 ** Insert parameters from Content-Type.
1172 ** This is only valid for '|' commands.
1174 if (buffer[0] != '|' && buffer[0] != '!') {
1183 for (ap=ci->ci_attrs, ep=ci->ci_values;
1185 snprintf(bp, buflen,
1197 /* insert message number */
1198 snprintf(bp, buflen, "%s",
1199 mhbasename(ct->c_file));
1203 /* insert part number with leading dot */
1205 snprintf(bp, buflen, ".%s",
1210 /* insert part number withouth leading dot */
1212 strncpy(bp, ct->c_partno, buflen);
1216 /* insert content type */
1217 strncpy(bp, ci->ci_type, buflen);
1221 /* insert content subtype */
1222 strncpy(bp, ci->ci_subtype, buflen);
1226 /* insert the character % */
1236 /* Advance bp and decrement buflen */
1254 ** Copy some of the header fields of the initial message/partial
1255 ** message into the header of the reassembled message.
1259 copy_some_headers(FILE *out, CT ct)
1263 hp = ct->c_first_hf; /* start at first header field */
1267 ** A few of the header fields of the enclosing
1268 ** messages are not copied.
1270 if (!uprf(hp->name, XXX_FIELD_PRF) &&
1271 mh_strcasecmp(hp->name, VRSN_FIELD) &&
1272 mh_strcasecmp(hp->name, "Subject") &&
1273 mh_strcasecmp(hp->name, "Message-ID"))
1274 fprintf(out, "%s:%s", hp->name, hp->value);
1275 hp = hp->next; /* next header field */