2 * sendsbr.c -- routines to help WhatNow/Send along
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.
10 #include <h/signals.h>
18 #ifdef TIME_WITH_SYS_TIME
19 # include <sys/time.h>
22 # ifdef TM_IN_SYS_TIME
23 # include <sys/time.h>
29 int debugsw = 0; /* global */
37 char *altmsg = NULL; /* .. */
38 char *annotext = NULL;
39 char *distfile = NULL;
43 static char body_file_name[MAXPATHLEN + 1]; /* name of temporary file for body content */
44 static char composition_file_name[MAXPATHLEN + 1]; /* name of mhbuild composition temporary file */
45 static int field_size; /* size of header field buffer */
46 static char *field; /* header field buffer */
47 static FILE *draft_file; /* draft file pointer */
48 static FILE *body_file; /* body file pointer */
49 static FILE *composition_file; /* composition file pointer */
54 int sendsbr (char **, int, char *, struct stat *, int, char *, int);
55 char *getusername (void);
60 static void armed_done (int) NORETURN;
61 static void alert (char *, int);
62 static int tmp_fd (void);
63 static void anno (int, struct stat *);
64 static void annoaux (int);
65 static int splitmsg (char **, int, char *, struct stat *, int);
66 static int sendaux (char **, int, char *, struct stat *);
68 static int attach(char *, char *, int);
69 static void clean_up_temporary_files(void);
70 static int get_line(void);
71 static void make_mime_composition_file_entry(char *, int);
75 * Entry point into (back-end) routines to send message.
79 sendsbr (char **vec, int vecp, char *drft, struct stat *st,
80 int rename_drft, char *attachment_header_field_name, int attachformat)
83 char buffer[BUFSIZ], file[BUFSIZ];
85 char *original_draft; /* name of original draft file */
86 char *p; /* string pointer for building file name */
89 * Save the original name of the draft file. The name of the
90 * draft file is changed to a temporary file containing the built
91 * MIME message if there are attachments. We need the original
92 * name so that it can be renamed after the message is sent.
95 original_draft = drft;
98 * There might be attachments if a header field name for
99 * attachments is supplied. Convert the draft to a MIME message.
100 * Use the mhbuild composition file for the draft if there was
101 * a successful conversion because that now contains the MIME
102 * message. A nice side effect of this is that it leaves the
103 * original draft file untouched so that it can be retrieved
104 * and modified if desired.
107 if (attachment_header_field_name != (char *)0) {
108 switch (attach(attachment_header_field_name, drft, attachformat)) {
110 drft = composition_file_name;
122 switch (setjmp (env)) {
125 * If given -push and -unique (which is undocumented), then
126 * rename the draft file. I'm not quite sure why.
128 if (pushsw && unique) {
129 char *cp = m_mktemp2(drft, invo_name, NULL, NULL);
131 adios ("sendsbr", "unable to create temporary file");
133 if (rename (drft, strncpy(file, cp, sizeof(file))) == NOTOK)
134 adios (file, "unable to rename %s to", drft);
139 * Check if we need to split the message into
140 * multiple messages of type "message/partial".
142 if (splitsw >= 0 && !distfile && stat (drft, &sts) != NOTOK
143 && sts.st_size >= CPERMSG) {
144 status = splitmsg (vec, vecp, drft, st, splitsw) ? NOTOK : OK;
146 status = sendaux (vec, vecp, drft, st) ? NOTOK : OK;
149 /* rename the original draft */
150 if (rename_drft && status == OK &&
151 rename (original_draft, strncpy (buffer, m_backup (original_draft), sizeof(buffer))) == NOTOK)
152 advise (buffer, "unable to rename %s to", drft);
165 * Get rid of any temporary files that we created for attachments.
166 * Also get rid of the renamed composition file that mhbuild
167 * leaves as a turd. It looks confusing, but we use the body
168 * file name to help build the renamed composition file name.
171 if (drft == composition_file_name) {
172 clean_up_temporary_files();
174 if (strlen(composition_file_name) >= sizeof (composition_file_name) - 6)
175 advise((char *)0, "unable to remove original composition file.");
178 if ((p = strrchr(composition_file_name, '/')) == (char *)0)
179 p = composition_file_name;
183 (void)strcpy(body_file_name, p);
185 (void)strcpy(p, body_file_name);
186 (void)strcat(p, ".orig");
188 (void)unlink(composition_file_name);
196 attach(char *attachment_header_field_name, char *draft_file_name,
199 char buf[MAXPATHLEN + 6]; /* miscellaneous buffer */
200 int c; /* current character for body copy */
201 int has_attachment; /* draft has at least one attachment */
202 int has_body; /* draft has a message body */
203 int length; /* length of attachment header field name */
204 char *p; /* miscellaneous string pointer */
207 * Open up the draft file.
210 if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
211 adios((char *)0, "can't open draft file `%s'.", draft_file_name);
214 * Allocate a buffer to hold the header components as they're read in.
215 * This buffer might need to be quite large, so we grow it as needed.
218 field = (char *)mh_xmalloc(field_size = 256);
221 * Scan the draft file for a header field name that matches the
222 * -attach argument. The existence of one indicates that the
223 * draft has attachments. Bail out if there are no attachments
224 * because we're done. Read to the end of the headers even if
225 * we have no attachments.
228 length = strlen(attachment_header_field_name);
232 while (get_line() != EOF && *field != '\0' && *field != '-')
233 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':')
236 if (has_attachment == 0)
240 * We have at least one attachment. Look for at least one
241 * non-blank line in the body of the message which indicates
242 * content in the body.
247 while (get_line() != EOF) {
248 for (p = field; *p != '\0'; p++) {
249 if (*p != ' ' && *p != '\t') {
260 * Make names for the temporary files.
263 (void)strncpy(body_file_name,
264 m_mktemp(m_maildir(invo_name), NULL, NULL),
265 sizeof (body_file_name));
266 (void)strncpy(composition_file_name,
267 m_mktemp(m_maildir(invo_name), NULL, NULL),
268 sizeof (composition_file_name));
271 body_file = fopen(body_file_name, "w");
273 composition_file = fopen(composition_file_name, "w");
275 if ((has_body && body_file == (FILE *)0) || composition_file == (FILE *)0) {
276 clean_up_temporary_files();
277 adios((char *)0, "unable to open all of the temporary files.");
281 * Start at the beginning of the draft file. Copy all
282 * non-attachment header fields to the temporary composition file.
283 * Then add the dashed line separator.
288 while (get_line() != EOF && *field != '\0' && *field != '-')
289 if (strncasecmp(field, attachment_header_field_name, length) != 0 || field[length] != ':')
290 (void)fprintf(composition_file, "%s\n", field);
292 (void)fputs("--------\n", composition_file);
295 * Copy the message body to a temporary file.
299 while ((c = getc(draft_file)) != EOF)
302 (void)fclose(body_file);
306 * Add a mhbuild MIME composition file line for the body if
311 make_mime_composition_file_entry(body_file_name, attachformat);
314 * Now, go back to the beginning of the draft file and look for
315 * header fields that specify attachments. Add a mhbuild MIME
316 * composition file for each.
321 while (get_line() != EOF && *field != '\0' && *field != '-') {
322 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':') {
323 for (p = field + length + 1; *p == ' ' || *p == '\t'; p++)
326 make_mime_composition_file_entry(p, attachformat);
330 (void)fclose(composition_file);
333 * We're ready to roll! Run mhbuild on the composition file.
334 * Note that mhbuild is in the context as buildmimeproc.
337 (void)sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
339 if (system(buf) != 0) {
340 clean_up_temporary_files();
348 clean_up_temporary_files(void)
350 (void)unlink(body_file_name);
351 (void)unlink(composition_file_name);
359 int c; /* current character */
360 int n; /* number of bytes in buffer */
361 char *p; /* buffer pointer */
364 * Get a line from the input file, growing the field buffer as
365 * needed. We do this so that we can fit an entire line in the
366 * buffer making it easy to do a string comparison on both the
367 * field name and the field body which might be a long path name.
370 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
371 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
372 (void)ungetc(c, draft_file);
377 if (++n >= field_size - 1) {
378 field = (char *)mh_xrealloc((void *)field, field_size += 256);
385 * NUL-terminate the field..
394 make_mime_composition_file_entry(char *file_name, int attachformat)
396 int binary; /* binary character found flag */
397 int c; /* current character */
398 char cmd[MAXPATHLEN + 6]; /* file command buffer */
399 char *content_type; /* mime content type */
400 FILE *fp; /* content and pipe file pointer */
401 struct node *np; /* context scan node pointer */
402 char *p; /* miscellaneous string pointer */
403 struct stat st; /* file status buffer */
405 content_type = (char *)0;
408 * Check the file name for a suffix. Scan the context for that
409 * suffix on a mhshow-suffix- entry. We use these entries to
410 * be compatible with mhshow, and there's no reason to make the
411 * user specify each suffix twice. Context entries of the form
412 * "mhshow-suffix-contenttype" in the name have the suffix in
413 * the field, including the dot.
416 if ((p = strrchr(file_name, '.')) != (char *)0) {
417 for (np = m_defs; np; np = np->n_next) {
418 if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0 && mh_strcasecmp(p, np->n_field) == 0) {
419 content_type = np->n_name + 14;
426 * No content type was found, either because there was no matching
427 * entry in the context or because the file name has no suffix.
428 * Open the file and check for non-ASCII characters. Choose the
429 * content type based on this check.
432 if (content_type == (char *)0) {
433 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
434 clean_up_temporary_files();
435 adios((char *)0, "unable to access file \"%s\"", file_name);
440 while ((c = getc(fp)) != EOF) {
441 if (c > 127 || c < 0) {
449 content_type = binary ? "application/octet-stream" : "text/plain";
453 * Make sure that the attachment file exists and is readable.
454 * Append a mhbuild directive to the draft file. This starts with
455 * the content type. Append a file name attribute and a private
456 * x-unix-mode attribute. Also append a description obtained
457 * (if possible) by running the "file" command on the file.
460 if (stat(file_name, &st) == -1 || access(file_name, R_OK) != 0) {
461 clean_up_temporary_files();
462 adios((char *)0, "unable to access file \"%s\"", file_name);
465 switch (attachformat) {
467 /* Insert name, file mode, and Content-Id. */
468 (void)fprintf(composition_file, "#%s; name=\"%s\"; x-unix-mode=0%.3ho",
469 content_type, ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1, (unsigned short)(st.st_mode & 0777));
471 if (strlen(file_name) > MAXPATHLEN) {
472 clean_up_temporary_files();
473 adios((char *)0, "attachment file name `%s' too long.", file_name);
476 (void)sprintf(cmd, "file '%s'", file_name);
478 if ((fp = popen(cmd, "r")) != (FILE *)0 && fgets(cmd, sizeof (cmd), fp) != (char *)0) {
479 *strchr(cmd, '\n') = '\0';
482 * The output of the "file" command is of the form
486 * Strip off the "file:" and subsequent white space.
489 for (p = cmd; *p != '\0'; p++) {
491 for (p++; *p != '\0'; p++) {
500 /* Insert Content-Description. */
501 (void)fprintf(composition_file, " [ %s ]", p);
508 if (stringdex (m_maildir(invo_name), file_name) == 0) {
510 * Content had been placed by send into a temp file.
511 * Don't generate Content-Disposition header, because
512 * it confuses Microsoft Outlook, Build 10.0.6626, at
515 (void) fprintf (composition_file, "#%s <>", content_type);
517 /* Suppress Content-Id, insert simple Content-Disposition. */
518 (void) fprintf (composition_file,
519 "#%s; name=\"%s\" <>{attachment}",
521 ((p = strrchr(file_name, '/')) == (char *)0) ?
527 if (stringdex (m_maildir(invo_name), file_name) == 0) {
529 * Content had been placed by send into a temp file.
530 * Don't generate Content-Disposition header, because
531 * it confuses Microsoft Outlook, Build 10.0.6626, at
534 (void) fprintf (composition_file, "#%s <>", content_type);
537 * Suppress Content-Id, insert Content-Disposition
538 * with modification date.
540 (void) fprintf (composition_file,
541 "#%s; name=\"%s\" <>{attachment; modification-date=\"%s\"}",
543 ((p = strrchr(file_name, '/')) == (char *)0) ?
544 file_name : p + 1, dtime (&st.st_mtime, 0));
549 adios ((char *)0, "unsupported attachformat %d", attachformat);
553 * Finish up with the file name.
556 (void)fprintf(composition_file, " %s\n", file_name);
562 * Split large message into several messages of
563 * type "message/partial" and send them.
567 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
569 int compnum, nparts, partno, state, status;
572 char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
573 char subject[BUFSIZ];
574 char name[NAMESZ], partnum[BUFSIZ];
577 if ((in = fopen (drft, "r")) == NULL)
578 adios (drft, "unable to open for reading");
584 * Scan through the message and examine the various header fields,
585 * as well as locate the beginning of the message body.
587 for (compnum = 1, state = FLD;;) {
588 switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
595 * This header field is discarded.
597 if (!mh_strcasecmp (name, "Message-ID")) {
598 while (state == FLDPLUS)
599 state = m_getfld (state, name, buffer, sizeof(buffer), in);
600 } else if (uprf (name, XXX_FIELD_PRF)
601 || !mh_strcasecmp (name, VRSN_FIELD)
602 || !mh_strcasecmp (name, "Subject")
603 || !mh_strcasecmp (name, "Encrypted")) {
605 * These header fields are copied
606 * to the enclosed header of the
607 * first message in the collection
608 * of message/partials. For the
609 * "Subject" header field,
610 * we also record it, so that
611 * a modified version of it,
612 * can be copied to the header
613 * of each messsage/partial in
616 if (!mh_strcasecmp (name, "Subject")) {
619 strncpy (subject, buffer, BUFSIZ);
620 sublen = strlen (subject);
621 if (sublen > 0 && subject[sublen - 1] == '\n')
622 subject[sublen - 1] = '\0';
625 dp = add (concat (name, ":", buffer, NULL), dp);
626 while (state == FLDPLUS) {
627 state = m_getfld (state, name, buffer, sizeof(buffer), in);
628 dp = add (buffer, dp);
632 * These header fields are
633 * copied to the header of
634 * each message/partial in
637 cp = add (concat (name, ":", buffer, NULL), cp);
638 while (state == FLDPLUS) {
639 state = m_getfld (state, name, buffer, sizeof(buffer), in);
640 cp = add (buffer, cp);
644 if (state != FLDEOF) {
645 start = ftell (in) + 1;
657 adios (NULL, "message format error in component #%d", compnum);
660 adios (NULL, "getfld () returned %d", state);
666 adios (NULL, "headers missing from draft");
670 while (fgets (buffer, sizeof(buffer) - 1, in)) {
673 if ((pos += (len = strlen (buffer))) > CPERMSG) {
679 /* Only one part, nothing to split */
686 return sendaux (vec, vecp, drft, st);
690 printf ("Sending as %d Partial Messages\n", nparts);
695 vec[vecp++] = "-partno";
696 vec[vecp++] = partnum;
698 vec[vecp++] = "-queued";
701 snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
702 (int) getpid(), (long) clock, LocalName());
704 fseek (in, start, SEEK_SET);
705 for (partno = 1; partno <= nparts; partno++) {
709 char *cp = m_mktemp2(drft, invo_name, NULL, &out);
711 adios (drft, "unable to create temporary file for");
713 strncpy(tmpdrf, cp, sizeof(tmpdrf));
714 chmod (tmpdrf, 0600);
717 * Output the header fields
720 fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
721 fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
722 fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
723 fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
724 fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
727 * If this is the first in the collection, output the
728 * header fields we are encapsulating at the beginning
729 * of the body of the first message.
734 fprintf (out, "Message-ID: %s\n", msgid);
742 if (!fgets (buffer, sizeof(buffer) - 1, in)) {
743 if (partno == nparts)
745 adios (NULL, "premature eof");
748 if ((pos += (len = strlen (buffer))) > CPERMSG) {
749 fseek (in, -len, SEEK_CUR);
757 adios (tmpdrf, "error writing to");
761 if (!pushsw && verbsw) {
766 /* Pause here, if a delay is specified */
767 if (delay > 0 && 1 < partno && partno <= nparts) {
769 printf ("pausing %d seconds before sending part %d...\n",
773 sleep ((unsigned int) delay);
776 snprintf (partnum, sizeof(partnum), "%d", partno);
777 status = sendaux (vec, vecp, tmpdrf, st);
783 * This is so sendaux will only annotate
784 * the altmsg the first time it is called.
793 fclose (in); /* close the draft */
799 * Annotate original message, and
800 * call `postproc' to send message.
804 sendaux (char **vec, int vecp, char *drft, struct stat *st)
807 int i, status, fd, fd2;
808 char backup[BUFSIZ], buf[BUFSIZ];
810 fd = pushsw ? tmp_fd () : NOTOK;
815 if ((fd2 = tmp_fd ()) != NOTOK) {
816 vec[vecp++] = "-idanno";
817 snprintf (buf, sizeof(buf), "%d", fd2);
820 admonish (NULL, "unable to create file for annotation list");
823 if (distfile && distout (drft, distfile, backup) == NOTOK)
827 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
832 /* oops -- fork error */
833 adios ("fork", "unable to");
834 break; /* NOT REACHED */
838 * child process -- send it
840 * If fd is ok, then we are pushing and fd points to temp
841 * file, so capture anything on stdout and stderr there.
844 dup2 (fd, fileno (stdout));
845 dup2 (fd, fileno (stderr));
848 execvp (postproc, vec);
849 fprintf (stderr, "unable to exec ");
852 break; /* NOT REACHED */
856 * parent process -- wait for it
858 if ((status = pidwait(child_id, NOTOK)) == OK) {
859 if (annotext && fd2 != NOTOK)
863 * If postproc failed, and we have good fd (which means
864 * we pushed), then mail error message (and possibly the
865 * draft) back to the user.
871 advise (NULL, "message not delivered to anyone");
873 if (annotext && fd2 != NOTOK)
877 if (rename (backup, drft) == NOTOK)
878 advise (drft, "unable to rename %s to", backup);
889 * Mail error notification (and possibly a copy of the
890 * message) back to the user, using the mailproc
894 alert (char *file, int out)
900 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
905 /* oops -- fork error */
906 advise ("fork", "unable to");
909 /* child process -- send it */
910 SIGNAL (SIGHUP, SIG_IGN);
911 SIGNAL (SIGINT, SIG_IGN);
912 SIGNAL (SIGQUIT, SIG_IGN);
913 SIGNAL (SIGTERM, SIG_IGN);
915 if ((in = open (file, O_RDONLY)) == NOTOK) {
916 admonish (file, "unable to re-open");
918 lseek (out, (off_t) 0, SEEK_END);
919 strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
920 write (out, buf, strlen (buf));
921 strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
922 write (out, buf, strlen (buf));
923 cpydgst (in, out, file, "temporary file");
925 strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
926 write (out, buf, strlen (buf));
927 if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
928 admonish (buf, "unable to rename %s to", file);
931 lseek (out, (off_t) 0, SEEK_SET);
932 dup2 (out, fileno (stdin));
934 /* create subject for error notification */
935 snprintf (buf, sizeof(buf), "send failed on %s",
936 forwsw ? "enclosed draft" : file);
938 execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
939 "-subject", buf, NULL);
940 fprintf (stderr, "unable to exec ");
944 default: /* no waiting... */
956 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
957 if (tfile == NULL) return NOTOK;
961 advise (NULL, "temporary file %s selected", tfile);
963 if (unlink (tfile) == NOTOK)
964 advise (tfile, "unable to remove");
971 anno (int fd, struct stat *st)
975 static char *cwd = NULL;
979 (stat (altmsg, &st2) == NOTOK
980 || st->st_mtime != st2.st_mtime
981 || st->st_dev != st2.st_dev
982 || st->st_ino != st2.st_ino)) {
984 admonish (NULL, "$mhaltmsg mismatch");
988 child_id = debugsw ? NOTOK : fork ();
990 case NOTOK: /* oops */
993 "unable to fork, so doing annotations by hand...");
995 cwd = getcpy (pwd ());
998 /* block a few signals */
1000 sigaddset (&set, SIGHUP);
1001 sigaddset (&set, SIGINT);
1002 sigaddset (&set, SIGQUIT);
1003 sigaddset (&set, SIGTERM);
1004 SIGPROCMASK (SIG_BLOCK, &set, &oset);
1010 /* reset the signal mask */
1011 SIGPROCMASK (SIG_SETMASK, &oset, &set);
1016 default: /* no waiting... */
1026 int fd2, fd3, msgnum;
1027 char *cp, *folder, *maildir;
1028 char buffer[BUFSIZ], **ap;
1032 if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
1034 admonish (NULL, "$mhfolder not set");
1037 maildir = m_maildir (folder);
1038 if (chdir (maildir) == NOTOK) {
1040 admonish (maildir, "unable to change directory to");
1043 if (!(mp = folder_read (folder))) {
1045 admonish (NULL, "unable to read folder %s", folder);
1049 /* check for empty folder */
1050 if (mp->nummsg == 0) {
1052 admonish (NULL, "no messages in %s", folder);
1056 if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
1058 admonish (NULL, "$mhmessages not set");
1061 if (!debugsw /* MOBY HACK... */
1063 && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
1064 && (fd2 = dup (fileno (stderr))) != NOTOK) {
1065 dup2 (fd3, fileno (stderr));
1070 for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
1071 m_convert (mp, *ap);
1074 dup2 (fd2, fileno (stderr));
1075 if (mp->numsel == 0) {
1077 admonish (NULL, "no messages to annotate");
1081 lseek (fd, (off_t) 0, SEEK_SET);
1082 if ((fp = fdopen (fd, "r")) == NULL) {
1084 admonish (NULL, "unable to fdopen annotation list");
1088 while (fgets (buffer, sizeof(buffer), fp) != NULL)
1089 cp = add (buffer, cp);
1093 advise (NULL, "annotate%s with %s: \"%s\"",
1094 inplace ? " inplace" : "", annotext, cp);
1095 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1096 if (is_selected(mp, msgnum)) {
1098 advise (NULL, "annotate message %d", msgnum);
1099 annotate (m_name (msgnum), annotext, cp, inplace, 1, -2, 0);
1106 folder_free (mp); /* free folder/message structure */
1111 armed_done (int status)
1113 longjmp (env, status ? status : NOTOK);