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>
20 #ifdef TIME_WITH_SYS_TIME
21 # include <sys/time.h>
24 # ifdef TM_IN_SYS_TIME
25 # include <sys/time.h>
31 int debugsw = 0; /* global */
39 char *altmsg = NULL; /* .. */
40 char *annotext = NULL;
41 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);
59 char *getusername (void);
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 if (rename (drft, strncpy (file, m_scratch (drft, invo_name), sizeof(file)))
130 adios (file, "unable to rename %s to", drft);
135 * Check if we need to split the message into
136 * multiple messages of type "message/partial".
138 if (splitsw >= 0 && !distfile && stat (drft, &sts) != NOTOK
139 && sts.st_size >= CPERMSG) {
140 status = splitmsg (vec, vecp, drft, st, splitsw) ? NOTOK : OK;
142 status = sendaux (vec, vecp, drft, st) ? NOTOK : OK;
145 /* rename the original draft */
146 if (rename_drft && status == OK &&
147 rename (original_draft, strncpy (buffer, m_backup (original_draft), sizeof(buffer))) == NOTOK)
148 advise (buffer, "unable to rename %s to", drft);
161 * Get rid of any temporary files that we created for attachments. Also get rid of
162 * the renamed composition file that mhbuild leaves as a turd. It looks confusing,
163 * but we use the body file name to help build the renamed composition file name.
166 if (drft == composition_file_name) {
167 clean_up_temporary_files();
169 if (strlen(composition_file_name) >= sizeof (composition_file_name) - 6)
170 advise((char *)0, "unable to remove original composition file.");
173 if ((p = strrchr(composition_file_name, '/')) == (char *)0)
174 p = composition_file_name;
178 (void)strcpy(body_file_name, p);
180 (void)strcpy(p, body_file_name);
181 (void)strcat(p, ".orig");
183 (void)unlink(composition_file_name);
191 attach(char *attachment_header_field_name, char *draft_file_name,
194 char buf[MAXPATHLEN + 6]; /* miscellaneous buffer */
195 int c; /* current character for body copy */
196 int has_attachment; /* draft has at least one attachment */
197 int has_body; /* draft has a message body */
198 int length; /* length of attachment header field name */
199 char *p; /* miscellaneous string pointer */
202 * Open up the draft file.
205 if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
206 adios((char *)0, "can't open draft file `%s'.", draft_file_name);
209 * Allocate a buffer to hold the header components as they're read in.
210 * This buffer might need to be quite large, so we grow it as needed.
213 field = (char *)mh_xmalloc(field_size = 256);
216 * Scan the draft file for a header field name that matches the -attach
217 * argument. The existence of one indicates that the draft has attachments.
218 * Bail out if there are no attachments because we're done. Read to the
219 * end of the headers even if we have no attachments.
222 length = strlen(attachment_header_field_name);
226 while (get_line() != EOF && *field != '\0' && *field != '-')
227 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':')
230 if (has_attachment == 0)
234 * We have at least one attachment. Look for at least one non-blank line
235 * in the body of the message which indicates content in the body.
240 while (get_line() != EOF) {
241 for (p = field; *p != '\0'; p++) {
242 if (*p != ' ' && *p != '\t') {
253 * Make names for the temporary files.
256 (void)strncpy(body_file_name, m_scratch("", m_maildir(invo_name)), sizeof (body_file_name));
257 (void)strncpy(composition_file_name, m_scratch("", m_maildir(invo_name)), sizeof (composition_file_name));
260 body_file = fopen(body_file_name, "w");
262 composition_file = fopen(composition_file_name, "w");
264 if ((has_body && body_file == (FILE *)0) || composition_file == (FILE *)0) {
265 clean_up_temporary_files();
266 adios((char *)0, "unable to open all of the temporary files.");
270 * Start at the beginning of the draft file. Copy all non-attachment header fields
271 * to the temporary composition file. Then add the dashed line separator.
276 while (get_line() != EOF && *field != '\0' && *field != '-')
277 if (strncasecmp(field, attachment_header_field_name, length) != 0 || field[length] != ':')
278 (void)fprintf(composition_file, "%s\n", field);
280 (void)fputs("--------\n", composition_file);
283 * Copy the message body to a temporary file.
287 while ((c = getc(draft_file)) != EOF)
290 (void)fclose(body_file);
294 * Add a mhbuild MIME composition file line for the body if there was one.
298 make_mime_composition_file_entry(body_file_name, attachformat);
301 * Now, go back to the beginning of the draft file and look for header fields
302 * that specify attachments. Add a mhbuild MIME composition file for each.
307 while (get_line() != EOF && *field != '\0' && *field != '-') {
308 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':') {
309 for (p = field + length + 1; *p == ' ' || *p == '\t'; p++)
312 make_mime_composition_file_entry(p, attachformat);
316 (void)fclose(composition_file);
319 * We're ready to roll! Run mhbuild on the composition file. Note that mhbuild
320 * is in the context as buildmimeproc.
323 (void)sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
325 if (system(buf) != 0) {
326 clean_up_temporary_files();
334 clean_up_temporary_files(void)
336 (void)unlink(body_file_name);
337 (void)unlink(composition_file_name);
345 int c; /* current character */
346 int n; /* number of bytes in buffer */
347 char *p; /* buffer pointer */
350 * Get a line from the input file, growing the field buffer as needed. We do this
351 * so that we can fit an entire line in the buffer making it easy to do a string
352 * comparison on both the field name and the field body which might be a long path
356 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
357 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
358 (void)ungetc(c, draft_file);
363 if (++n >= field_size - 1) {
364 field = (char *)mh_xrealloc((void *)field, field_size += 256);
371 * NUL-terminate the field..
380 make_mime_composition_file_entry(char *file_name, int attachformat)
382 int binary; /* binary character found flag */
383 int c; /* current character */
384 char cmd[MAXPATHLEN + 6]; /* file command buffer */
385 char *content_type; /* mime content type */
386 FILE *fp; /* content and pipe file pointer */
387 struct node *np; /* context scan node pointer */
388 char *p; /* miscellaneous string pointer */
389 struct stat st; /* file status buffer */
391 content_type = (char *)0;
394 * Check the file name for a suffix. Scan the context for that suffix on a
395 * mhshow-suffix- entry. We use these entries to be compatible with mhnshow,
396 * and there's no reason to make the user specify each suffix twice. Context
397 * entries of the form "mhshow-suffix-contenttype" in the name have the suffix
398 * in the field, including the dot.
401 if ((p = strrchr(file_name, '.')) != (char *)0) {
402 for (np = m_defs; np; np = np->n_next) {
403 if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0 && strcasecmp(p, np->n_field) == 0) {
404 content_type = np->n_name + 14;
411 * No content type was found, either because there was no matching entry in the
412 * context or because the file name has no suffix. Open the file and check for
413 * non-ASCII characters. Choose the content type based on this check.
416 if (content_type == (char *)0) {
417 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
418 clean_up_temporary_files();
419 adios((char *)0, "unable to access file \"%s\"", file_name);
424 while ((c = getc(fp)) != EOF) {
425 if (c > 127 || c < 0) {
433 content_type = binary ? "application/octet-stream" : "text/plain";
437 * Make sure that the attachment file exists and is readable. Append a mhbuild
438 * directive to the draft file. This starts with the content type. Append a
439 * file name attribute and a private x-unix-mode attribute. Also append a
440 * description obtained (if possible) by running the "file" command on the file.
443 if (stat(file_name, &st) == -1 || access(file_name, R_OK) != 0) {
444 clean_up_temporary_files();
445 adios((char *)0, "unable to access file \"%s\"", file_name);
448 switch (attachformat) {
450 /* Insert name, file mode, and Content-Id. */
451 (void)fprintf(composition_file, "#%s; name=\"%s\"; x-unix-mode=0%.3ho",
452 content_type, ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1, (unsigned short)(st.st_mode & 0777));
454 if (strlen(file_name) > MAXPATHLEN) {
455 clean_up_temporary_files();
456 adios((char *)0, "attachment file name `%s' too long.", file_name);
459 (void)sprintf(cmd, "file '%s'", file_name);
461 if ((fp = popen(cmd, "r")) != (FILE *)0 && fgets(cmd, sizeof (cmd), fp) != (char *)0) {
462 *strchr(cmd, '\n') = '\0';
465 * The output of the "file" command is of the form
469 * Strip off the "file:" and subsequent white space.
472 for (p = cmd; *p != '\0'; p++) {
474 for (p++; *p != '\0'; p++) {
483 /* Insert Content-Description. */
484 (void)fprintf(composition_file, " [ %s ]", p);
491 /* Suppress Content-Id, insert simple Content-Disposition. */
492 (void) fprintf (composition_file, "#%s <>{attachment}", content_type);
496 /* Suppress Content-Id, insert Content-Disposition with
497 modification date. */
498 (void) fprintf (composition_file,
499 "#%s <>{attachment; modification-date=\"%s\"}",
501 dtime (&st.st_mtim, 0));
505 adios ((char *)0, "unsupported attachformat %d", attachformat);
509 * Finish up with the file name.
512 (void)fprintf(composition_file, " %s\n", file_name);
518 * Split large message into several messages of
519 * type "message/partial" and send them.
523 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
525 int compnum, nparts, partno, state, status;
528 char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
529 char subject[BUFSIZ];
530 char name[NAMESZ], partnum[BUFSIZ];
533 if ((in = fopen (drft, "r")) == NULL)
534 adios (drft, "unable to open for reading");
540 * Scan through the message and examine the various header fields,
541 * as well as locate the beginning of the message body.
543 for (compnum = 1, state = FLD;;) {
544 switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
551 * This header field is discarded.
553 if (!strcasecmp (name, "Message-ID")) {
554 while (state == FLDPLUS)
555 state = m_getfld (state, name, buffer, sizeof(buffer), in);
556 } else if (uprf (name, XXX_FIELD_PRF)
557 || !strcasecmp (name, VRSN_FIELD)
558 || !strcasecmp (name, "Subject")
559 || !strcasecmp (name, "Encrypted")) {
561 * These header fields are copied to the enclosed
562 * header of the first message in the collection
563 * of message/partials. For the "Subject" header
564 * field, we also record it, so that a modified
565 * version of it, can be copied to the header
566 * of each messsage/partial in the collection.
568 if (!strcasecmp (name, "Subject")) {
571 strncpy (subject, buffer, BUFSIZ);
572 sublen = strlen (subject);
573 if (sublen > 0 && subject[sublen - 1] == '\n')
574 subject[sublen - 1] = '\0';
577 dp = add (concat (name, ":", buffer, NULL), dp);
578 while (state == FLDPLUS) {
579 state = m_getfld (state, name, buffer, sizeof(buffer), in);
580 dp = add (buffer, dp);
584 * These header fields are copied to the header of
585 * each message/partial in the collection.
587 cp = add (concat (name, ":", buffer, NULL), cp);
588 while (state == FLDPLUS) {
589 state = m_getfld (state, name, buffer, sizeof(buffer), in);
590 cp = add (buffer, cp);
594 if (state != FLDEOF) {
595 start = ftell (in) + 1;
607 adios (NULL, "message format error in component #%d", compnum);
610 adios (NULL, "getfld () returned %d", state);
616 adios (NULL, "headers missing from draft");
620 while (fgets (buffer, sizeof(buffer) - 1, in)) {
623 if ((pos += (len = strlen (buffer))) > CPERMSG) {
629 /* Only one part, nothing to split */
636 return sendaux (vec, vecp, drft, st);
640 printf ("Sending as %d Partial Messages\n", nparts);
645 vec[vecp++] = "-partno";
646 vec[vecp++] = partnum;
648 vec[vecp++] = "-queued";
651 snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
652 (int) getpid(), (long) clock, LocalName());
654 fseek (in, start, SEEK_SET);
655 for (partno = 1; partno <= nparts; partno++) {
659 strncpy (tmpdrf, m_scratch (drft, invo_name), sizeof(tmpdrf));
660 if ((out = fopen (tmpdrf, "w")) == NULL)
661 adios (tmpdrf, "unable to open for writing");
662 chmod (tmpdrf, 0600);
665 * Output the header fields
668 fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
669 fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
670 fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
671 fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
672 fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
675 * If this is the first in the collection, output the
676 * header fields we are encapsulating at the beginning
677 * of the body of the first message.
682 fprintf (out, "Message-ID: %s\n", msgid);
690 if (!fgets (buffer, sizeof(buffer) - 1, in)) {
691 if (partno == nparts)
693 adios (NULL, "premature eof");
696 if ((pos += (len = strlen (buffer))) > CPERMSG) {
697 fseek (in, -len, SEEK_CUR);
705 adios (tmpdrf, "error writing to");
709 if (!pushsw && verbsw) {
714 /* Pause here, if a delay is specified */
715 if (delay > 0 && 1 < partno && partno <= nparts) {
717 printf ("pausing %d seconds before sending part %d...\n",
721 sleep ((unsigned int) delay);
724 snprintf (partnum, sizeof(partnum), "%d", partno);
725 status = sendaux (vec, vecp, tmpdrf, st);
731 * This is so sendaux will only annotate
732 * the altmsg the first time it is called.
741 fclose (in); /* close the draft */
747 * Annotate original message, and
748 * call `postproc' to send message.
752 sendaux (char **vec, int vecp, char *drft, struct stat *st)
755 int i, status, fd, fd2;
756 char backup[BUFSIZ], buf[BUFSIZ];
758 fd = pushsw ? tmp_fd () : NOTOK;
763 if ((fd2 = tmp_fd ()) != NOTOK) {
764 vec[vecp++] = "-idanno";
765 snprintf (buf, sizeof(buf), "%d", fd2);
768 admonish (NULL, "unable to create file for annotation list");
771 if (distfile && distout (drft, distfile, backup) == NOTOK)
775 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
780 /* oops -- fork error */
781 adios ("fork", "unable to");
782 break; /* NOT REACHED */
786 * child process -- send it
788 * If fd is ok, then we are pushing and fd points to temp
789 * file, so capture anything on stdout and stderr there.
792 dup2 (fd, fileno (stdout));
793 dup2 (fd, fileno (stderr));
796 execvp (postproc, vec);
797 fprintf (stderr, "unable to exec ");
800 break; /* NOT REACHED */
804 * parent process -- wait for it
806 if ((status = pidwait(child_id, NOTOK)) == OK) {
807 if (annotext && fd2 != NOTOK)
811 * If postproc failed, and we have good fd (which means
812 * we pushed), then mail error message (and possibly the
813 * draft) back to the user.
819 advise (NULL, "message not delivered to anyone");
821 if (annotext && fd2 != NOTOK)
825 if (rename (backup, drft) == NOTOK)
826 advise (drft, "unable to rename %s to", backup);
837 * Mail error notification (and possibly a copy of the
838 * message) back to the user, using the mailproc
842 alert (char *file, int out)
848 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
853 /* oops -- fork error */
854 advise ("fork", "unable to");
857 /* child process -- send it */
858 SIGNAL (SIGHUP, SIG_IGN);
859 SIGNAL (SIGINT, SIG_IGN);
860 SIGNAL (SIGQUIT, SIG_IGN);
861 SIGNAL (SIGTERM, SIG_IGN);
863 if ((in = open (file, O_RDONLY)) == NOTOK) {
864 admonish (file, "unable to re-open");
866 lseek (out, (off_t) 0, SEEK_END);
867 strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
868 write (out, buf, strlen (buf));
869 strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
870 write (out, buf, strlen (buf));
871 cpydgst (in, out, file, "temporary file");
873 strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
874 write (out, buf, strlen (buf));
875 if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
876 admonish (buf, "unable to rename %s to", file);
879 lseek (out, (off_t) 0, SEEK_SET);
880 dup2 (out, fileno (stdin));
882 /* create subject for error notification */
883 snprintf (buf, sizeof(buf), "send failed on %s",
884 forwsw ? "enclosed draft" : file);
886 execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
887 "-subject", buf, NULL);
888 fprintf (stderr, "unable to exec ");
892 default: /* no waiting... */
904 strncpy (tmpfil, m_tmpfil (invo_name), sizeof(tmpfil));
905 if ((fd = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == NOTOK)
908 advise (NULL, "temporary file %s selected", tmpfil);
910 if (unlink (tmpfil) == NOTOK)
911 advise (tmpfil, "unable to remove");
918 anno (int fd, struct stat *st)
922 static char *cwd = NULL;
926 (stat (altmsg, &st2) == NOTOK
927 || st->st_mtime != st2.st_mtime
928 || st->st_dev != st2.st_dev
929 || st->st_ino != st2.st_ino)) {
931 admonish (NULL, "$mhaltmsg mismatch");
935 child_id = debugsw ? NOTOK : fork ();
937 case NOTOK: /* oops */
940 "unable to fork, so doing annotations by hand...");
942 cwd = getcpy (pwd ());
945 /* block a few signals */
947 sigaddset (&set, SIGHUP);
948 sigaddset (&set, SIGINT);
949 sigaddset (&set, SIGQUIT);
950 sigaddset (&set, SIGTERM);
951 SIGPROCMASK (SIG_BLOCK, &set, &oset);
957 /* reset the signal mask */
958 SIGPROCMASK (SIG_SETMASK, &oset, &set);
963 default: /* no waiting... */
973 int fd2, fd3, msgnum;
974 char *cp, *folder, *maildir;
975 char buffer[BUFSIZ], **ap;
979 if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
981 admonish (NULL, "$mhfolder not set");
984 maildir = m_maildir (folder);
985 if (chdir (maildir) == NOTOK) {
987 admonish (maildir, "unable to change directory to");
990 if (!(mp = folder_read (folder))) {
992 admonish (NULL, "unable to read folder %s");
996 /* check for empty folder */
997 if (mp->nummsg == 0) {
999 admonish (NULL, "no messages in %s", folder);
1003 if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
1005 admonish (NULL, "$mhmessages not set");
1008 if (!debugsw /* MOBY HACK... */
1010 && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
1011 && (fd2 = dup (fileno (stderr))) != NOTOK) {
1012 dup2 (fd3, fileno (stderr));
1017 for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
1018 m_convert (mp, *ap);
1021 dup2 (fd2, fileno (stderr));
1022 if (mp->numsel == 0) {
1024 admonish (NULL, "no messages to annotate");
1028 lseek (fd, (off_t) 0, SEEK_SET);
1029 if ((fp = fdopen (fd, "r")) == NULL) {
1031 admonish (NULL, "unable to fdopen annotation list");
1035 while (fgets (buffer, sizeof(buffer), fp) != NULL)
1036 cp = add (buffer, cp);
1040 advise (NULL, "annotate%s with %s: \"%s\"",
1041 inplace ? " inplace" : "", annotext, cp);
1042 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1043 if (is_selected(mp, msgnum)) {
1045 advise (NULL, "annotate message %d", msgnum);
1046 annotate (m_name (msgnum), annotext, cp, inplace, 1, -2, 0);
1053 folder_free (mp); /* free folder/message structure */
1061 longjmp (env, status ? status : NOTOK);
1064 return 1; /* dead code to satisfy the compiler */