3 * sendsbr.c -- routines to help WhatNow/Send along
7 * This code is Copyright (c) 2002, by the authors of nmh. See the
8 * COPYRIGHT file in the root directory of the nmh distribution for
9 * complete copyright information.
13 #include <h/signals.h>
21 #ifdef TIME_WITH_SYS_TIME
22 # include <sys/time.h>
25 # ifdef TM_IN_SYS_TIME
26 # include <sys/time.h>
32 int debugsw = 0; /* global */
40 char *altmsg = NULL; /* .. */
41 char *annotext = NULL;
42 char *distfile = NULL;
46 static char body_file_name[MAXPATHLEN + 1]; /* name of temporary file for body content */
47 static char composition_file_name[MAXPATHLEN + 1]; /* name of mhbuild composition temporary file */
48 static int field_size; /* size of header field buffer */
49 static char *field; /* header field buffer */
50 static FILE *draft_file; /* draft file pointer */
51 static FILE *body_file; /* body file pointer */
52 static FILE *composition_file; /* composition file pointer */
57 int sendsbr (char **, int, char *, struct stat *, int, char *, int);
58 char *getusername (void);
63 static void armed_done (int) NORETURN;
64 static void alert (char *, int);
65 static int tmp_fd (void);
66 static void anno (int, struct stat *);
67 static void annoaux (int);
68 static int splitmsg (char **, int, char *, struct stat *, int);
69 static int sendaux (char **, int, char *, struct stat *);
71 static int attach(char *, char *, int);
72 static void clean_up_temporary_files(void);
73 static int get_line(void);
74 static void make_mime_composition_file_entry(char *, int);
78 * Entry point into (back-end) routines to send message.
82 sendsbr (char **vec, int vecp, char *drft, struct stat *st, int rename_drft, char *attachment_header_field_name, int attachformat)
85 char buffer[BUFSIZ], file[BUFSIZ];
87 char *original_draft; /* name of original draft file */
88 char *p; /* string pointer for building file name */
91 * Save the original name of the draft file. The name of the draft file is changed
92 * to a temporary file containing the built MIME message if there are attachments.
93 * We need the original name so that it can be renamed after the message is sent.
96 original_draft = drft;
99 * There might be attachments if a header field name for attachments is supplied.
100 * Convert the draft to a MIME message. Use the mhbuild composition file for the
101 * draft if there was a successful conversion because that now contains the MIME
102 * message. A nice side effect of this is that it leaves the original draft file
103 * untouched so that it can be retrieved and modified if desired.
106 if (attachment_header_field_name != (char *)0) {
107 switch (attach(attachment_header_field_name, drft, attachformat)) {
109 drft = composition_file_name;
121 switch (setjmp (env)) {
124 * If given -push and -unique (which is undocumented), then
125 * rename the draft file. I'm not quite sure why.
127 if (pushsw && unique) {
128 char *cp = m_mktemp2(drft, invo_name, NULL, NULL);
130 adios ("sendsbr", "unable to create temporary file");
132 if (rename (drft, strncpy(file, cp, sizeof(file))) == NOTOK)
133 adios (file, "unable to rename %s to", drft);
138 * Check if we need to split the message into
139 * multiple messages of type "message/partial".
141 if (splitsw >= 0 && !distfile && stat (drft, &sts) != NOTOK
142 && sts.st_size >= CPERMSG) {
143 status = splitmsg (vec, vecp, drft, st, splitsw) ? NOTOK : OK;
145 status = sendaux (vec, vecp, drft, st) ? NOTOK : OK;
148 /* rename the original draft */
149 if (rename_drft && status == OK &&
150 rename (original_draft, strncpy (buffer, m_backup (original_draft), sizeof(buffer))) == NOTOK)
151 advise (buffer, "unable to rename %s to", drft);
164 * Get rid of any temporary files that we created for attachments. Also get rid of
165 * the renamed composition file that mhbuild leaves as a turd. It looks confusing,
166 * but we use the body file name to help build the renamed composition file name.
169 if (drft == composition_file_name) {
170 clean_up_temporary_files();
172 if (strlen(composition_file_name) >= sizeof (composition_file_name) - 6)
173 advise((char *)0, "unable to remove original composition file.");
176 if ((p = strrchr(composition_file_name, '/')) == (char *)0)
177 p = composition_file_name;
181 (void)strcpy(body_file_name, p);
183 (void)strcpy(p, body_file_name);
184 (void)strcat(p, ".orig");
186 (void)unlink(composition_file_name);
194 attach(char *attachment_header_field_name, char *draft_file_name,
197 char buf[MAXPATHLEN + 6]; /* miscellaneous buffer */
198 int c; /* current character for body copy */
199 int has_attachment; /* draft has at least one attachment */
200 int has_body; /* draft has a message body */
201 int length; /* length of attachment header field name */
202 char *p; /* miscellaneous string pointer */
205 * Open up the draft file.
208 if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
209 adios((char *)0, "can't open draft file `%s'.", draft_file_name);
212 * Allocate a buffer to hold the header components as they're read in.
213 * This buffer might need to be quite large, so we grow it as needed.
216 field = (char *)mh_xmalloc(field_size = 256);
219 * Scan the draft file for a header field name that matches the -attach
220 * argument. The existence of one indicates that the draft has attachments.
221 * Bail out if there are no attachments because we're done. Read to the
222 * end of the headers even if we have no attachments.
225 length = strlen(attachment_header_field_name);
229 while (get_line() != EOF && *field != '\0' && *field != '-')
230 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':')
233 if (has_attachment == 0)
237 * We have at least one attachment. Look for at least one non-blank line
238 * in the body of the message which indicates content in the body.
243 while (get_line() != EOF) {
244 for (p = field; *p != '\0'; p++) {
245 if (*p != ' ' && *p != '\t') {
256 * Make names for the temporary files.
259 (void)strncpy(body_file_name,
260 m_mktemp(m_maildir(invo_name), NULL, NULL),
261 sizeof (body_file_name));
262 (void)strncpy(composition_file_name,
263 m_mktemp(m_maildir(invo_name), NULL, NULL),
264 sizeof (composition_file_name));
267 body_file = fopen(body_file_name, "w");
269 composition_file = fopen(composition_file_name, "w");
271 if ((has_body && body_file == (FILE *)0) || composition_file == (FILE *)0) {
272 clean_up_temporary_files();
273 adios((char *)0, "unable to open all of the temporary files.");
277 * Start at the beginning of the draft file. Copy all non-attachment header fields
278 * to the temporary composition file. Then add the dashed line separator.
283 while (get_line() != EOF && *field != '\0' && *field != '-')
284 if (strncasecmp(field, attachment_header_field_name, length) != 0 || field[length] != ':')
285 (void)fprintf(composition_file, "%s\n", field);
287 (void)fputs("--------\n", composition_file);
290 * Copy the message body to a temporary file.
294 while ((c = getc(draft_file)) != EOF)
297 (void)fclose(body_file);
301 * Add a mhbuild MIME composition file line for the body if there was one.
305 make_mime_composition_file_entry(body_file_name, attachformat);
308 * Now, go back to the beginning of the draft file and look for header fields
309 * that specify attachments. Add a mhbuild MIME composition file for each.
314 while (get_line() != EOF && *field != '\0' && *field != '-') {
315 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':') {
316 for (p = field + length + 1; *p == ' ' || *p == '\t'; p++)
319 make_mime_composition_file_entry(p, attachformat);
323 (void)fclose(composition_file);
326 * We're ready to roll! Run mhbuild on the composition file. Note that mhbuild
327 * is in the context as buildmimeproc.
330 (void)sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
332 if (system(buf) != 0) {
333 clean_up_temporary_files();
341 clean_up_temporary_files(void)
343 (void)unlink(body_file_name);
344 (void)unlink(composition_file_name);
352 int c; /* current character */
353 int n; /* number of bytes in buffer */
354 char *p; /* buffer pointer */
357 * Get a line from the input file, growing the field buffer as needed. We do this
358 * so that we can fit an entire line in the buffer making it easy to do a string
359 * comparison on both the field name and the field body which might be a long path
363 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
364 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
365 (void)ungetc(c, draft_file);
370 if (++n >= field_size - 1) {
371 field = (char *)mh_xrealloc((void *)field, field_size += 256);
378 * NUL-terminate the field..
387 make_mime_composition_file_entry(char *file_name, int attachformat)
389 int binary; /* binary character found flag */
390 int c; /* current character */
391 char cmd[MAXPATHLEN + 6]; /* file command buffer */
392 char *content_type; /* mime content type */
393 FILE *fp; /* content and pipe file pointer */
394 struct node *np; /* context scan node pointer */
395 char *p; /* miscellaneous string pointer */
396 struct stat st; /* file status buffer */
398 content_type = (char *)0;
401 * Check the file name for a suffix. Scan the context for that suffix on a
402 * mhshow-suffix- entry. We use these entries to be compatible with mhnshow,
403 * and there's no reason to make the user specify each suffix twice. Context
404 * entries of the form "mhshow-suffix-contenttype" in the name have the suffix
405 * in the field, including the dot.
408 if ((p = strrchr(file_name, '.')) != (char *)0) {
409 for (np = m_defs; np; np = np->n_next) {
410 if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0 && mh_strcasecmp(p, np->n_field) == 0) {
411 content_type = np->n_name + 14;
418 * No content type was found, either because there was no matching entry in the
419 * context or because the file name has no suffix. Open the file and check for
420 * non-ASCII characters. Choose the content type based on this check.
423 if (content_type == (char *)0) {
424 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
425 clean_up_temporary_files();
426 adios((char *)0, "unable to access file \"%s\"", file_name);
431 while ((c = getc(fp)) != EOF) {
432 if (c > 127 || c < 0) {
440 content_type = binary ? "application/octet-stream" : "text/plain";
444 * Make sure that the attachment file exists and is readable. Append a mhbuild
445 * directive to the draft file. This starts with the content type. Append a
446 * file name attribute and a private x-unix-mode attribute. Also append a
447 * description obtained (if possible) by running the "file" command on the file.
450 if (stat(file_name, &st) == -1 || access(file_name, R_OK) != 0) {
451 clean_up_temporary_files();
452 adios((char *)0, "unable to access file \"%s\"", file_name);
455 switch (attachformat) {
457 /* Insert name, file mode, and Content-Id. */
458 (void)fprintf(composition_file, "#%s; name=\"%s\"; x-unix-mode=0%.3ho",
459 content_type, ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1, (unsigned short)(st.st_mode & 0777));
461 if (strlen(file_name) > MAXPATHLEN) {
462 clean_up_temporary_files();
463 adios((char *)0, "attachment file name `%s' too long.", file_name);
466 (void)sprintf(cmd, "file '%s'", file_name);
468 if ((fp = popen(cmd, "r")) != (FILE *)0 && fgets(cmd, sizeof (cmd), fp) != (char *)0) {
469 *strchr(cmd, '\n') = '\0';
472 * The output of the "file" command is of the form
476 * Strip off the "file:" and subsequent white space.
479 for (p = cmd; *p != '\0'; p++) {
481 for (p++; *p != '\0'; p++) {
490 /* Insert Content-Description. */
491 (void)fprintf(composition_file, " [ %s ]", p);
498 if (stringdex (m_maildir(invo_name), file_name) == 0) {
499 /* Content had been placed by send into a temp file.
500 Don't generate Content-Disposition header, because
501 it confuses Microsoft Outlook, Build 10.0.6626, at
503 (void) fprintf (composition_file, "#%s <>", content_type);
505 /* Suppress Content-Id, insert simple Content-Disposition. */
506 (void) fprintf (composition_file,
507 "#%s; name=\"%s\" <>{attachment}",
509 ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1);
514 if (stringdex (m_maildir(invo_name), file_name) == 0) {
515 /* Content had been placed by send into a temp file.
516 Don't generate Content-Disposition header, because
517 it confuses Microsoft Outlook, Build 10.0.6626, at
519 (void) fprintf (composition_file, "#%s <>", content_type);
521 /* Suppress Content-Id, insert Content-Disposition with
522 modification date. */
523 (void) fprintf (composition_file,
524 "#%s; name=\"%s\" <>{attachment; modification-date=\"%s\"}",
526 ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1,
527 dtime (&st.st_mtime, 0));
532 adios ((char *)0, "unsupported attachformat %d", attachformat);
536 * Finish up with the file name.
539 (void)fprintf(composition_file, " %s\n", file_name);
545 * Split large message into several messages of
546 * type "message/partial" and send them.
550 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
552 int compnum, nparts, partno, state, status;
555 char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
556 char subject[BUFSIZ];
557 char name[NAMESZ], partnum[BUFSIZ];
560 if ((in = fopen (drft, "r")) == NULL)
561 adios (drft, "unable to open for reading");
567 * Scan through the message and examine the various header fields,
568 * as well as locate the beginning of the message body.
570 for (compnum = 1, state = FLD;;) {
571 switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
578 * This header field is discarded.
580 if (!mh_strcasecmp (name, "Message-ID")) {
581 while (state == FLDPLUS)
582 state = m_getfld (state, name, buffer, sizeof(buffer), in);
583 } else if (uprf (name, XXX_FIELD_PRF)
584 || !mh_strcasecmp (name, VRSN_FIELD)
585 || !mh_strcasecmp (name, "Subject")
586 || !mh_strcasecmp (name, "Encrypted")) {
588 * These header fields are copied to the enclosed
589 * header of the first message in the collection
590 * of message/partials. For the "Subject" header
591 * field, we also record it, so that a modified
592 * version of it, can be copied to the header
593 * of each messsage/partial in the collection.
595 if (!mh_strcasecmp (name, "Subject")) {
598 strncpy (subject, buffer, BUFSIZ);
599 sublen = strlen (subject);
600 if (sublen > 0 && subject[sublen - 1] == '\n')
601 subject[sublen - 1] = '\0';
604 dp = add (concat (name, ":", buffer, NULL), dp);
605 while (state == FLDPLUS) {
606 state = m_getfld (state, name, buffer, sizeof(buffer), in);
607 dp = add (buffer, dp);
611 * These header fields are copied to the header of
612 * each message/partial in the collection.
614 cp = add (concat (name, ":", buffer, NULL), cp);
615 while (state == FLDPLUS) {
616 state = m_getfld (state, name, buffer, sizeof(buffer), in);
617 cp = add (buffer, cp);
621 if (state != FLDEOF) {
622 start = ftell (in) + 1;
634 adios (NULL, "message format error in component #%d", compnum);
637 adios (NULL, "getfld () returned %d", state);
643 adios (NULL, "headers missing from draft");
647 while (fgets (buffer, sizeof(buffer) - 1, in)) {
650 if ((pos += (len = strlen (buffer))) > CPERMSG) {
656 /* Only one part, nothing to split */
663 return sendaux (vec, vecp, drft, st);
667 printf ("Sending as %d Partial Messages\n", nparts);
672 vec[vecp++] = "-partno";
673 vec[vecp++] = partnum;
675 vec[vecp++] = "-queued";
678 snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
679 (int) getpid(), (long) clock, LocalName());
681 fseek (in, start, SEEK_SET);
682 for (partno = 1; partno <= nparts; partno++) {
686 char *cp = m_mktemp2(drft, invo_name, NULL, &out);
688 adios (drft, "unable to create temporary file for");
690 strncpy(tmpdrf, cp, sizeof(tmpdrf));
691 chmod (tmpdrf, 0600);
694 * Output the header fields
697 fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
698 fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
699 fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
700 fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
701 fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
704 * If this is the first in the collection, output the
705 * header fields we are encapsulating at the beginning
706 * of the body of the first message.
711 fprintf (out, "Message-ID: %s\n", msgid);
719 if (!fgets (buffer, sizeof(buffer) - 1, in)) {
720 if (partno == nparts)
722 adios (NULL, "premature eof");
725 if ((pos += (len = strlen (buffer))) > CPERMSG) {
726 fseek (in, -len, SEEK_CUR);
734 adios (tmpdrf, "error writing to");
738 if (!pushsw && verbsw) {
743 /* Pause here, if a delay is specified */
744 if (delay > 0 && 1 < partno && partno <= nparts) {
746 printf ("pausing %d seconds before sending part %d...\n",
750 sleep ((unsigned int) delay);
753 snprintf (partnum, sizeof(partnum), "%d", partno);
754 status = sendaux (vec, vecp, tmpdrf, st);
760 * This is so sendaux will only annotate
761 * the altmsg the first time it is called.
770 fclose (in); /* close the draft */
776 * Annotate original message, and
777 * call `postproc' to send message.
781 sendaux (char **vec, int vecp, char *drft, struct stat *st)
784 int i, status, fd, fd2;
785 char backup[BUFSIZ], buf[BUFSIZ];
787 fd = pushsw ? tmp_fd () : NOTOK;
792 if ((fd2 = tmp_fd ()) != NOTOK) {
793 vec[vecp++] = "-idanno";
794 snprintf (buf, sizeof(buf), "%d", fd2);
797 admonish (NULL, "unable to create file for annotation list");
800 if (distfile && distout (drft, distfile, backup) == NOTOK)
804 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
809 /* oops -- fork error */
810 adios ("fork", "unable to");
811 break; /* NOT REACHED */
815 * child process -- send it
817 * If fd is ok, then we are pushing and fd points to temp
818 * file, so capture anything on stdout and stderr there.
821 dup2 (fd, fileno (stdout));
822 dup2 (fd, fileno (stderr));
825 execvp (postproc, vec);
826 fprintf (stderr, "unable to exec ");
829 break; /* NOT REACHED */
833 * parent process -- wait for it
835 if ((status = pidwait(child_id, NOTOK)) == OK) {
836 if (annotext && fd2 != NOTOK)
840 * If postproc failed, and we have good fd (which means
841 * we pushed), then mail error message (and possibly the
842 * draft) back to the user.
848 advise (NULL, "message not delivered to anyone");
850 if (annotext && fd2 != NOTOK)
854 if (rename (backup, drft) == NOTOK)
855 advise (drft, "unable to rename %s to", backup);
866 * Mail error notification (and possibly a copy of the
867 * message) back to the user, using the mailproc
871 alert (char *file, int out)
877 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
882 /* oops -- fork error */
883 advise ("fork", "unable to");
886 /* child process -- send it */
887 SIGNAL (SIGHUP, SIG_IGN);
888 SIGNAL (SIGINT, SIG_IGN);
889 SIGNAL (SIGQUIT, SIG_IGN);
890 SIGNAL (SIGTERM, SIG_IGN);
892 if ((in = open (file, O_RDONLY)) == NOTOK) {
893 admonish (file, "unable to re-open");
895 lseek (out, (off_t) 0, SEEK_END);
896 strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
897 write (out, buf, strlen (buf));
898 strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
899 write (out, buf, strlen (buf));
900 cpydgst (in, out, file, "temporary file");
902 strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
903 write (out, buf, strlen (buf));
904 if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
905 admonish (buf, "unable to rename %s to", file);
908 lseek (out, (off_t) 0, SEEK_SET);
909 dup2 (out, fileno (stdin));
911 /* create subject for error notification */
912 snprintf (buf, sizeof(buf), "send failed on %s",
913 forwsw ? "enclosed draft" : file);
915 execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
916 "-subject", buf, NULL);
917 fprintf (stderr, "unable to exec ");
921 default: /* no waiting... */
933 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
934 if (tfile == NULL) return NOTOK;
938 advise (NULL, "temporary file %s selected", tfile);
940 if (unlink (tfile) == NOTOK)
941 advise (tfile, "unable to remove");
948 anno (int fd, struct stat *st)
952 static char *cwd = NULL;
956 (stat (altmsg, &st2) == NOTOK
957 || st->st_mtime != st2.st_mtime
958 || st->st_dev != st2.st_dev
959 || st->st_ino != st2.st_ino)) {
961 admonish (NULL, "$mhaltmsg mismatch");
965 child_id = debugsw ? NOTOK : fork ();
967 case NOTOK: /* oops */
970 "unable to fork, so doing annotations by hand...");
972 cwd = getcpy (pwd ());
975 /* block a few signals */
977 sigaddset (&set, SIGHUP);
978 sigaddset (&set, SIGINT);
979 sigaddset (&set, SIGQUIT);
980 sigaddset (&set, SIGTERM);
981 SIGPROCMASK (SIG_BLOCK, &set, &oset);
987 /* reset the signal mask */
988 SIGPROCMASK (SIG_SETMASK, &oset, &set);
993 default: /* no waiting... */
1003 int fd2, fd3, msgnum;
1004 char *cp, *folder, *maildir;
1005 char buffer[BUFSIZ], **ap;
1009 if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
1011 admonish (NULL, "$mhfolder not set");
1014 maildir = m_maildir (folder);
1015 if (chdir (maildir) == NOTOK) {
1017 admonish (maildir, "unable to change directory to");
1020 if (!(mp = folder_read (folder))) {
1022 admonish (NULL, "unable to read folder %s", folder);
1026 /* check for empty folder */
1027 if (mp->nummsg == 0) {
1029 admonish (NULL, "no messages in %s", folder);
1033 if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
1035 admonish (NULL, "$mhmessages not set");
1038 if (!debugsw /* MOBY HACK... */
1040 && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
1041 && (fd2 = dup (fileno (stderr))) != NOTOK) {
1042 dup2 (fd3, fileno (stderr));
1047 for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
1048 m_convert (mp, *ap);
1051 dup2 (fd2, fileno (stderr));
1052 if (mp->numsel == 0) {
1054 admonish (NULL, "no messages to annotate");
1058 lseek (fd, (off_t) 0, SEEK_SET);
1059 if ((fp = fdopen (fd, "r")) == NULL) {
1061 admonish (NULL, "unable to fdopen annotation list");
1065 while (fgets (buffer, sizeof(buffer), fp) != NULL)
1066 cp = add (buffer, cp);
1070 advise (NULL, "annotate%s with %s: \"%s\"",
1071 inplace ? " inplace" : "", annotext, cp);
1072 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1073 if (is_selected(mp, msgnum)) {
1075 advise (NULL, "annotate message %d", msgnum);
1076 annotate (m_name (msgnum), annotext, cp, inplace, 1, -2, 0);
1083 folder_free (mp); /* free folder/message structure */
1088 armed_done (int status)
1090 longjmp (env, status ? status : NOTOK);