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 },
43 char *version=VERSION;
46 extern char *tmp; /* directory to place temp files */
51 extern char *parts[NPARTS + 1];
52 extern char *types[NTYPES + 1];
57 #define quitser pipeser
60 CT parse_mime(char *);
65 void set_endian(void);
66 void flush_errors(void);
69 void free_content(CT);
70 extern CT *cts; /* The list of top-level contents to display */
76 static void pipeser(int);
81 ** Cache of current directory. This must be
82 ** set before these routines are called.
87 ** The directory in which to store the contents.
92 ** Type for a compare function for qsort. This keeps
93 ** the compiler happy.
95 typedef int (*qsort_comp) (const void *, const void *);
100 int type_ok(CT, int);
101 int make_intermediates(char *);
102 void flush_errors(void);
105 int show_content_aux(CT, int, char *, char *);
110 static void store_single_message(CT);
111 static int store_switch(CT);
112 static int store_generic(CT);
113 static int store_multi(CT);
114 static int store_partial(CT);
115 static int store_external(CT);
116 static int ct_compar(CT *, CT *);
117 static int store_content(CT, CT);
118 static int output_content_file(CT, int);
119 static int output_content_folder(char *, char *);
120 static int parse_format_string(CT, char *, char *, int, char *);
121 static int copy_some_headers(FILE *, CT);
122 static void store_all_messages(CT *);
126 main(int argc, char **argv)
129 char *cp, *file = NULL, *folder = NULL;
130 char *maildir, buf[100], **argp;
132 struct msgs_array msgs = { 0, 0, NULL };
133 struct msgs *mp = NULL;
137 if (atexit(freects_done) != 0) {
138 adios(EX_OSERR, NULL, "atexit failed");
141 setlocale(LC_ALL, "");
142 invo_name = mhbasename(argv[0]);
144 /* read user profile/context */
147 arguments = getarguments(invo_name, argc, argv, 1);
153 while ((cp = *argp++)) {
155 switch (smatch(++cp, switches)) {
157 ambigsw(cp, switches);
160 adios(EX_USAGE, NULL, "-%s unknown", cp);
163 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
164 print_help(buf, switches, 1);
165 exit(argc == 2 ? EX_OK : EX_USAGE);
167 print_version(invo_name);
168 exit(argc == 2 ? EX_OK : EX_USAGE);
178 if (!(cp = *argp++) || *cp == '-')
179 adios(EX_USAGE, NULL, "missing argument to %s",
182 adios(EX_USAGE, NULL, "too many parts (starting with %s), %d max", cp, NPARTS);
187 if (!(cp = *argp++) || *cp == '-')
188 adios(EX_USAGE, NULL, "missing argument to %s",
191 adios(EX_USAGE, NULL, "too many types (starting with %s), %d max", cp, NTYPES);
196 if (!(cp = *argp++) || (*cp == '-' && cp[1]))
197 adios(EX_USAGE, NULL, "missing argument to %s",
199 file = *cp == '-' ? cp : mh_xstrdup(expanddir(cp));
207 if (*cp == '+' || *cp == '@') {
209 adios(EX_USAGE, NULL, "only one folder at a time!");
211 folder = mh_xstrdup(expandfol(cp));
213 app_msgarg(&msgs, cp);
216 /* null terminate the list of acceptable parts/types */
223 ** Check if we've specified an additional profile
225 if ((cp = getenv("MHSTORE"))) {
226 if ((fp = fopen(cp, "r"))) {
227 readconfig((struct node **) 0, fp, cp, 0);
230 admonish("", "unable to read $MHSTORE profile (%s)",
236 ** Read the standard profile setup
238 if ((fp = fopen(cp = etcpath("mhn.defaults"), "r"))) {
239 readconfig((struct node **) 0, fp, cp, 0);
244 ** Cache the current directory before we do any chdirs()'s.
246 cwd = mh_xstrdup(pwd());
249 ** Check for storage directory. If specified,
250 ** then store temporary files there. Else we
251 ** store them in standard nmh directory.
253 if ((cp = context_find(nmhstorage)) && *cp)
254 tmp = concat(cp, "/", invo_name, NULL);
256 tmp = mh_xstrdup(toabsdir(invo_name));
258 if (file && msgs.size)
259 adios(EX_USAGE, NULL, "cannot specify msg and file at same time!");
262 ** check if message is coming from file
265 cts = mh_xcalloc(2, sizeof(*cts));
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]))
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++)
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");
372 ** Main entry point to store content from a collection of messages.
375 store_all_messages(CT *cts)
381 ** Check for the directory in which to
382 ** store any contents.
384 if ((cp = context_find(nmhstorage)) && *cp)
385 dir = mh_xstrdup(cp);
387 dir = mh_xstrdup(cwd);
389 for (ctp = cts; *ctp; ctp++) {
391 store_single_message(ct);
399 ** Entry point to store the content
400 ** in a (single) message
404 store_single_message(CT ct)
406 if (type_ok(ct, 1)) {
413 if (ct->c_ceclosefnx)
414 (*ct->c_ceclosefnx) (ct);
420 ** Switching routine to store different content types
426 switch (ct->c_type) {
428 return store_multi(ct);
432 switch (ct->c_subtype) {
433 case MESSAGE_PARTIAL:
434 return store_partial(ct);
437 case MESSAGE_EXTERNAL:
438 return store_external(ct);
442 return store_generic(ct);
452 return store_generic(ct);
456 adios(EX_DATAERR, NULL, "unknown content type %d", ct->c_type);
460 return OK; /* NOT REACHED */
465 ** Generic routine to store a MIME content.
466 ** (application, audio, video, image, text, message/rfc922)
471 char **ap, **vp, *cp, *filename;
472 CI ci = &ct->c_ctinfo;
475 ** Check if the content specifies a filename in its MIME parameters.
476 ** Don't bother with this for type "message"
477 ** (only the "message" subtype "rfc822" will use store_generic).
479 if (autosw && ct->c_type != CT_MESSAGE) {
480 /* First check for "filename" in Content-Disposition header */
481 filename = extract_name_value("filename", ct->c_dispo);
482 if (filename && strcmp(filename, ct->c_dispo)!=0) {
483 /* We found "filename" */
484 cp = mhbasename(filename);
485 if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
487 /* filename looks good: use it */
488 ct->c_storeproc = mh_xstrdup(cp);
493 ** Check the attribute/value pairs, for the attribute "name".
494 ** If found, take the basename, do a few sanity checks and
495 ** copy the value into c_storeproc.
497 for (ap = ci->ci_attrs, vp = ci->ci_values; *ap; ap++,vp++) {
498 if (mh_strcasecmp(*ap, "name")!=0) {
501 cp = mhbasename(*vp);
502 if (*cp && *cp!='.' && *cp!='|' && *cp!='!' &&
504 /* filename looks good: use it */
505 ct->c_storeproc = mh_xstrdup(cp);
512 return store_content(ct, NULL);
517 ** Store the content of a multipart message
524 struct multipart *m = (struct multipart *) ct->c_ctparams;
528 for (part = m->mp_parts; part; part = part->mp_next) {
529 CT p = part->mp_part;
531 if (part_ok(p, 1) && type_ok(p, 1)) {
532 result = store_switch(p);
533 if (result == OK && ct->c_subtype == MULTI_ALTERNATE)
543 ** Reassemble and store the contents of a collection
544 ** of messages of type "message/partial".
553 struct partial *pm, *qm;
555 qm = (struct partial *) ct->c_ctparams;
560 for (ctp = cts; *ctp; ctp++) {
562 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
563 pm = (struct partial *) p->c_ctparams;
564 if (!pm->pm_stored &&
565 strcmp(qm->pm_partid, pm->pm_partid)
567 pm->pm_marked = pm->pm_partno;
578 advise(NULL, "missing (at least) last part of multipart message");
582 base = mh_xcalloc(i + 1, sizeof(*base));
585 for (ctp = cts; *ctp; ctp++) {
587 if (p->c_type == CT_MESSAGE && p->c_subtype == ct->c_subtype) {
588 pm = (struct partial *) p->c_ctparams;
596 qsort((char *) base, i, sizeof(*base), (qsort_comp) ct_compar);
599 for (ctq = base; *ctq; ctq++) {
601 pm = (struct partial *) p->c_ctparams;
602 if (pm->pm_marked != cur) {
603 if (pm->pm_marked == cur - 1) {
604 admonish(NULL, "duplicate part %d of %d part multipart message", pm->pm_marked, hi);
609 advise (NULL, "missing %spart %d of %d part multipart message", cur != hi ? "(at least) " : "", cur, hi);
620 ** Now cycle through the sorted list of messages of type
621 ** "message/partial" and save/append them to a file.
626 if (store_content(ct, NULL) == NOTOK) {
632 for (; *ctq; ctq++) {
634 if (store_content(p, ct) == NOTOK)
644 ** Show how to retrieve content of type "message/external".
647 store_external(CT ct)
654 msg = add("You need to fetch the contents yourself:", NULL);
655 ap = ct->c_ctinfo.ci_attrs;
656 ep = ct->c_ctinfo.ci_values;
657 for (; *ap; ap++, ep++) {
658 msg = add(concat("\n\t", *ap, ": ", *ep, NULL), msg);
660 if (!(fp = fopen(ct->c_file, "r"))) {
661 adios(EX_IOERR, ct->c_file, "unable to open");
663 fseek(fp, ct->c_begin, SEEK_SET);
664 while (!feof(fp) && ftell(fp) < ct->c_end) {
665 if (!fgets(buf, sizeof buf, fp)) {
666 adios(EX_IOERR, ct->c_file, "unable to read");
668 *strchr(buf, '\n') = '\0';
669 msg = add(concat("\n\t", buf, NULL), msg);
678 ** Compare the numbering from two different
679 ** message/partials (needed for sorting).
683 ct_compar(CT *a, CT *b)
685 struct partial *am = (struct partial *) ((*a)->c_ctparams);
686 struct partial *bm = (struct partial *) ((*b)->c_ctparams);
688 return (am->pm_marked - bm->pm_marked);
693 ** Store contents of a message or message part to
694 ** a folder, a file, the standard output, or pass
695 ** the contents to a command.
697 ** If the current content to be saved is a followup part
698 ** to a collection of messages of type "message/partial",
699 ** then field "p" is a pointer to the Content structure
700 ** to the first message/partial in the group.
704 store_content(CT ct, CT p)
706 int appending = 0, msgnum = 0;
707 int is_partial = 0, first_partial = 0;
708 int last_partial = 0;
709 char *cp, buffer[BUFSIZ];
712 ** Do special processing for messages of
713 ** type "message/partial".
715 ** We first check if this content is of type
716 ** "message/partial". If it is, then we need to check
717 ** whether it is the first and/or last in the group.
719 ** Then if "p" is a valid pointer, it points to the Content
720 ** structure of the first partial in the group. So we copy
721 ** the file name and/or folder name from that message. In
722 ** this case, we also note that we will be appending.
724 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
725 struct partial *pm = (struct partial *) ct->c_ctparams;
727 /* Yep, it's a message/partial */
730 /* But is it the first and/or last in the collection? */
731 if (pm->pm_partno == 1)
733 if (pm->pm_maxno && pm->pm_partno == pm->pm_maxno)
737 ** If "p" is a valid pointer, then it points to the
738 ** Content structure for the first message in the group.
739 ** So we just copy the filename or foldername information
740 ** from the previous iteration of this function.
744 ct->c_storage = mh_xstrdup(p->c_storage);
746 /* record the folder name */
748 ct->c_folder = mh_xstrdup(p->c_folder);
755 ** Get storage formatting string.
757 ** 1) If we have storeproc defined, then use that
758 ** 2) Else check for a mhstore-store-<type>/<subtype> entry
759 ** 3) Else check for a mhstore-store-<type> entry
760 ** 4) Else if content is "message", use "+" (current folder)
761 ** 5) Else use string "%m%P.%s".
763 if (!(cp = ct->c_storeproc) || !*cp) {
764 CI ci = &ct->c_ctinfo;
766 snprintf(buffer, sizeof(buffer), "%s-store-%s/%s",
767 invo_name, ci->ci_type, ci->ci_subtype);
768 if ((cp = context_find(buffer)) == NULL || *cp == '\0') {
769 snprintf(buffer, sizeof(buffer), "%s-store-%s",
770 invo_name, ci->ci_type);
771 if ((cp = context_find(buffer)) == NULL ||
773 cp = ct->c_type == CT_MESSAGE ?
780 ** Check the beginning of storage formatting string
781 ** to see if we are saving content to a folder.
783 if (*cp == '+' || *cp == '@') {
784 char *tmpfilenam, *folder;
786 /* Store content in temporary file for now */
787 tmpfilenam = m_mktemp(invo_name, NULL, NULL);
788 ct->c_storage = mh_xstrdup(tmpfilenam);
790 /* Get the folder name */
792 folder = mh_xstrdup(expandfol(cp));
794 folder = getcurfol();
796 /* Check if folder exists */
797 create_folder(toabsdir(folder), 0, exit);
799 /* Record the folder name */
800 ct->c_folder = mh_xstrdup(folder);
809 ** Parse and expand the storage formatting string
810 ** in `cp' into `buffer'.
812 parse_format_string(ct, cp, buffer, sizeof(buffer), dir);
815 ** If formatting begins with '|' or '!', then pass
816 ** content to standard input of a command and return.
818 if (buffer[0] == '|' || buffer[0] == '!')
819 return show_content_aux(ct, 0, buffer + 1, dir);
821 /* record the filename */
822 ct->c_storage = mh_xstrdup(buffer);
825 /* flush the output stream */
828 /* Now save or append the content to a file */
829 if (output_content_file(ct, appending) == NOTOK)
833 ** If necessary, link the file into a folder and remove
834 ** the temporary file. If this message is a partial,
835 ** then only do this if it is the last one in the group.
837 if (ct->c_folder && (!is_partial || last_partial)) {
838 msgnum = output_content_folder(ct->c_folder, ct->c_storage);
839 unlink(ct->c_storage);
845 ** Now print out the name/number of the message
846 ** that we are storing.
850 fprintf(stderr, "reassembling partials ");
852 fprintf(stderr, "%s", ct->c_file);
854 fprintf(stderr, "%s,", ct->c_file);
856 fprintf(stderr, "storing message %s", ct->c_file);
858 fprintf(stderr, " part %s", ct->c_partno);
862 ** Unless we are in the "middle" of group of message/partials,
863 ** we now print the name of the file, folder, and/or message
864 ** to which we are storing the content.
866 if (!is_partial || last_partial) {
868 fprintf(stderr, " to folder %s as message %d\n",
869 ct->c_folder, msgnum);
870 } else if (strcmp(ct->c_storage, "-")==0) {
871 fprintf(stderr, " to stdout\n");
875 cwdlen = strlen(cwd);
876 fprintf(stderr, " as file %s\n",
877 strncmp(ct->c_storage, cwd,
879 ct->c_storage[cwdlen] != '/' ?
881 ct->c_storage + cwdlen + 1);
890 ** Output content to a file
894 output_content_file(CT ct, int appending)
897 char *file, buffer[BUFSIZ];
902 ** If the pathname contains directories, make sure
903 ** all of them exist.
905 if (strchr(ct->c_storage, '/') && make_intermediates(ct->c_storage)
909 if (ct->c_encoding != CE_7BIT) {
912 if (!ct->c_ceopenfnx) {
913 advise(NULL, "don't know how to decode part %s of message %s", ct->c_partno, ct->c_file);
917 file = appending || strcmp(ct->c_storage, "-")==0 ?
918 NULL : ct->c_storage;
919 if ((fd = (*ct->c_ceopenfnx) (ct, &file)) == NOTOK)
921 if (strcmp(file, ct->c_storage)==0) {
922 (*ct->c_ceclosefnx) (ct);
927 ** Send to standard output
929 if (strcmp(ct->c_storage, "-")==0) {
932 if ((gd = dup(fileno(stdout))) == NOTOK) {
933 advise("stdout", "unable to dup");
935 (*ct->c_ceclosefnx) (ct);
938 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
939 advise("stdout", "unable to fdopen (%d, \"%s\") from", gd, appending ? "a" : "w");
947 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
949 advise(ct->c_storage, "unable to fopen for %s",
951 "appending" : "writing");
957 ** Filter the header fields of the initial enclosing
958 ** message/partial into the file.
960 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
961 struct partial *pm = (struct partial *) ct->c_ctparams;
963 if (pm->pm_partno == 1)
964 copy_some_headers(fp, ct);
968 switch (cc = read(fd, buffer, sizeof(buffer))) {
970 advise(file, "error reading content from");
977 fwrite(buffer, sizeof(*buffer), cc, fp);
983 (*ct->c_ceclosefnx) (ct);
985 if (cc != NOTOK && fflush(fp))
986 advise(ct->c_storage, "error writing to");
990 return (cc != NOTOK ? OK : NOTOK);
993 if (!ct->c_fp && (ct->c_fp = fopen(ct->c_file, "r")) == NULL) {
994 advise(ct->c_file, "unable to open for reading");
1000 fseek(ct->c_fp, pos, SEEK_SET);
1002 if (strcmp(ct->c_storage, "-")==0) {
1005 if ((gd = dup(fileno(stdout))) == NOTOK) {
1006 advise("stdout", "unable to dup");
1009 if ((fp = fdopen(gd, appending ? "a" : "w")) == NULL) {
1010 advise("stdout", "unable to fdopen (%d, \"%s\") from",
1011 gd, appending ? "a" : "w");
1016 if ((fp = fopen(ct->c_storage, appending ? "a" : "w"))
1018 advise(ct->c_storage, "unable to fopen for %s",
1019 appending ? "appending" : "writing");
1025 ** Copy a few of the header fields of the initial
1026 ** enclosing message/partial into the file.
1029 if (ct->c_type == CT_MESSAGE && ct->c_subtype == MESSAGE_PARTIAL) {
1030 struct partial *pm = (struct partial *) ct->c_ctparams;
1032 if (pm->pm_partno == 1) {
1033 copy_some_headers(fp, ct);
1038 while (fgets(buffer, sizeof(buffer) - 1, ct->c_fp)) {
1039 if ((pos += strlen(buffer)) > last) {
1042 diff = strlen(buffer) - (pos - last);
1044 buffer[diff] = '\0';
1047 ** If this is the first content of a group of
1048 ** message/partial contents, then we only copy a few
1049 ** of the header fields of the enclosed message.
1052 switch (buffer[0]) {
1055 if (filterstate < 0)
1064 if (!uprf(buffer, XXX_FIELD_PRF) && !uprf(buffer, VRSN_FIELD) && !uprf(buffer, "Subject:") && !uprf(buffer, "Message-ID:")) {
1079 advise(ct->c_storage, "error writing to");
1089 ** Add a file to a folder.
1091 ** Return the new message number of the file
1092 ** when added to the folder. Return -1, if
1093 ** there is an error.
1097 output_content_folder(char *folder, char *filename)
1102 /* Read the folder. */
1103 if ((mp = folder_read(folder))) {
1104 /* Link file into folder */
1105 msgnum = folder_addmsg(&mp, filename, 0, 0, 0, 0, NULL);
1107 advise(NULL, "unable to read folder %s", folder);
1111 /* free folder structure */
1115 ** Return msgnum. We are relying on the fact that
1116 ** msgnum will be -1, if folder_addmsg() had an error.
1123 ** Parse and expand the storage formatting string
1124 ** pointed to by "cp" into "buffer".
1128 parse_format_string(CT ct, char *cp, char *buffer, int buflen, char *dir)
1132 CI ci = &ct->c_ctinfo;
1135 ** If storage string is "-", just copy it, and
1136 ** return (send content to standard output).
1138 if (cp[0] == '-' && cp[1] == '\0') {
1139 strncpy(buffer, cp, buflen);
1147 ** If formatting string is a pathname that doesn't
1148 ** begin with '/', then preface the path with the
1149 ** appropriate directory.
1151 if (*cp != '/' && *cp != '|' && *cp != '!') {
1152 snprintf(bp, buflen, "%s/", dir[1] ? dir : "");
1160 /* We are processing a storage escape */
1165 ** Insert parameters from Content-Type.
1166 ** This is only valid for '|' commands.
1168 if (buffer[0] != '|' && buffer[0] != '!') {
1177 for (ap=ci->ci_attrs, ep=ci->ci_values;
1179 snprintf(bp, buflen,
1191 /* insert message number */
1192 snprintf(bp, buflen, "%s",
1193 mhbasename(ct->c_file));
1197 /* insert part number with leading dot */
1199 snprintf(bp, buflen, ".%s",
1204 /* insert part number withouth leading dot */
1206 strncpy(bp, ct->c_partno, buflen);
1210 /* insert content type */
1211 strncpy(bp, ci->ci_type, buflen);
1215 /* insert content subtype */
1216 strncpy(bp, ci->ci_subtype, buflen);
1220 /* insert the character % */
1230 /* Advance bp and decrement buflen */
1248 ** Copy some of the header fields of the initial message/partial
1249 ** message into the header of the reassembled message.
1253 copy_some_headers(FILE *out, CT ct)
1257 hp = ct->c_first_hf; /* start at first header field */
1261 ** A few of the header fields of the enclosing
1262 ** messages are not copied.
1264 if (!uprf(hp->name, XXX_FIELD_PRF) &&
1265 mh_strcasecmp(hp->name, VRSN_FIELD) &&
1266 mh_strcasecmp(hp->name, "Subject") &&
1267 mh_strcasecmp(hp->name, "Message-ID"))
1268 fprintf(out, "%s:%s", hp->name, hp->value);
1269 hp = hp->next; /* next header field */