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>
19 #ifdef TIME_WITH_SYS_TIME
20 # include <sys/time.h>
23 # ifdef TM_IN_SYS_TIME
24 # include <sys/time.h>
30 int debugsw = 0; /* global */
38 char *altmsg = NULL; /* .. */
39 char *annotext = NULL;
40 char *distfile = NULL;
45 static char body_file_name[MAXPATHLEN + 1]; /* name of temporary file for body content */
46 static char composition_file_name[MAXPATHLEN + 1]; /* name of mhbuild composition temporary file */
47 static int field_size; /* size of header field buffer */
48 static char *field; /* header field buffer */
49 static FILE *draft_file; /* draft file pointer */
50 static FILE *body_file; /* body file pointer */
51 static FILE *composition_file; /* composition file pointer */
56 int sendsbr (char **, int, char *, struct stat *, int, char *);
58 char *getusername (void);
63 static void alert (char *, int);
64 static int tmp_fd (void);
65 static void anno (int, struct stat *);
66 static void annoaux (int);
67 static int splitmsg (char **, int, char *, struct stat *, int);
68 static int sendaux (char **, int, char *, struct stat *);
70 static int attach(char *, char *);
71 static void clean_up_temporary_files(void);
72 static int get_line(void);
73 static void make_mime_composition_file_entry(char *);
77 * Entry point into (back-end) routines to send message.
81 sendsbr (char **vec, int vecp, char *drft, struct stat *st, int rename_drft, char *attachment_header_field_name)
84 char buffer[BUFSIZ], file[BUFSIZ];
86 char *original_draft; /* name of original draft file */
87 char *p; /* string pointer for building file name */
90 * Save the original name of the draft file. The name of the draft file is changed
91 * to a temporary file containing the built MIME message if there are attachments.
92 * We need the original 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 attachments is supplied.
99 * Convert the draft to a MIME message. Use the mhbuild composition file for the
100 * draft if there was a successful conversion because that now contains the MIME
101 * message. A nice side effect of this is that it leaves the original draft file
102 * untouched so that it can be retrieved and modified if desired.
105 if (attachment_header_field_name != (char *)0) {
106 switch (attach(attachment_header_field_name, drft)) {
108 drft = composition_file_name;
120 switch (setjmp (env)) {
123 * If given -push and -unique (which is undocumented), then
124 * rename the draft file. I'm not quite sure why.
126 if (pushsw && unique) {
127 if (rename (drft, strncpy (file, m_scratch (drft, invo_name), sizeof(file)))
129 adios (file, "unable to rename %s to", drft);
134 * Check if we need to split the message into
135 * multiple messages of type "message/partial".
137 if (splitsw >= 0 && !distfile && stat (drft, &sts) != NOTOK
138 && sts.st_size >= CPERMSG) {
139 status = splitmsg (vec, vecp, drft, st, splitsw) ? NOTOK : OK;
141 status = sendaux (vec, vecp, drft, st) ? NOTOK : OK;
144 /* rename the original draft */
145 if (rename_drft && status == OK &&
146 rename (original_draft, strncpy (buffer, m_backup (original_draft), sizeof(buffer))) == NOTOK)
147 advise (buffer, "unable to rename %s to", drft);
160 * Get rid of any temporary files that we created for attachments. Also get rid of
161 * the renamed composition file that mhbuild leaves as a turd. It looks confusing,
162 * but we use the body file name to help build the renamed composition file name.
165 if (drft == composition_file_name) {
166 clean_up_temporary_files();
168 if (strlen(composition_file_name) >= sizeof (composition_file_name) - 6)
169 advise((char *)0, "unable to remove original composition file.");
172 if ((p = strrchr(composition_file_name, '/')) == (char *)0)
173 p = composition_file_name;
177 (void)strcpy(body_file_name, p);
179 (void)strcpy(p, body_file_name);
180 (void)strcat(p, ".orig");
182 (void)unlink(composition_file_name);
190 attach(char *attachment_header_field_name, char *draft_file_name)
192 char buf[MAXPATHLEN + 6]; /* miscellaneous buffer */
193 int c; /* current character for body copy */
194 int has_attachment; /* draft has at least one attachment */
195 int has_body; /* draft has a message body */
196 int length; /* length of attachment header field name */
197 char *p; /* miscellaneous string pointer */
200 * Open up the draft file.
203 if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
204 adios((char *)0, "can't open draft file `%s'.", draft_file_name);
207 * Allocate a buffer to hold the header components as they're read in.
208 * This buffer might need to be quite large, so we grow it as needed.
211 if ((field = (char *)malloc(field_size = 256)) == (char *)0)
212 adios(NULL, "can't allocate field buffer.");
215 * Scan the draft file for a header field name that matches the -attach
216 * argument. The existence of one indicates that the draft has attachments.
217 * Bail out if there are no attachments because we're done. Read to the
218 * end of the headers even if we have no attachments.
221 length = strlen(attachment_header_field_name);
225 while (get_line() != EOF && *field != '\0' && *field != '-')
226 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':')
229 if (has_attachment == 0)
233 * We have at least one attachment. Look for at least one non-blank line
234 * in the body of the message which indicates content in the body.
239 while (get_line() != EOF) {
240 for (p = field; *p != '\0'; p++) {
241 if (*p != ' ' && *p != '\t') {
252 * Make names for the temporary files.
255 (void)strncpy(body_file_name, m_scratch("", m_maildir(invo_name)), sizeof (body_file_name));
256 (void)strncpy(composition_file_name, m_scratch("", m_maildir(invo_name)), sizeof (composition_file_name));
259 body_file = fopen(body_file_name, "w");
261 composition_file = fopen(composition_file_name, "w");
263 if ((has_body && body_file == (FILE *)0) || composition_file == (FILE *)0) {
264 clean_up_temporary_files();
265 adios((char *)0, "unable to open all of the temporary files.");
269 * Start at the beginning of the draft file. Copy all non-attachment header fields
270 * to the temporary composition file. Then add the dashed line separator.
275 while (get_line() != EOF && *field != '\0' && *field != '-')
276 if (strncasecmp(field, attachment_header_field_name, length) != 0 || field[length] != ':')
277 (void)fprintf(composition_file, "%s\n", field);
279 (void)fputs("--------\n", composition_file);
282 * Copy the message body to a temporary file.
286 while ((c = getc(draft_file)) != EOF)
289 (void)fclose(body_file);
293 * Add a mhbuild MIME composition file line for the body if there was one.
297 make_mime_composition_file_entry(body_file_name);
300 * Now, go back to the beginning of the draft file and look for header fields
301 * that specify attachments. Add a mhbuild MIME composition file for each.
306 while (get_line() != EOF && *field != '\0' && *field != '-') {
307 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':') {
308 for (p = field + length + 1; *p == ' ' || *p == '\t'; p++)
311 make_mime_composition_file_entry(p);
315 (void)fclose(composition_file);
318 * We're ready to roll! Run mhbuild on the composition file. Note that mhbuild
319 * is in the context as buildmimeproc.
322 (void)sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
324 if (system(buf) != 0) {
325 clean_up_temporary_files();
333 clean_up_temporary_files(void)
335 (void)unlink(body_file_name);
336 (void)unlink(composition_file_name);
344 int c; /* current character */
345 int n; /* number of bytes in buffer */
346 char *p; /* buffer pointer */
349 * Get a line from the input file, growing the field buffer as needed. We do this
350 * so that we can fit an entire line in the buffer making it easy to do a string
351 * comparison on both the field name and the field body which might be a long path
355 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
356 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
357 (void)ungetc(c, draft_file);
362 if (++n >= field_size - 1) {
363 if ((field = (char *)realloc((void *)field, field_size += 256)) == (char *)0)
364 adios(NULL, "can't grow field buffer.");
371 * NUL-terminate the field..
380 make_mime_composition_file_entry(char *file_name)
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 (void)fprintf(composition_file, "#%s; name=\"%s\"; x-unix-mode=0%.3ho",
449 content_type, ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1, (unsigned short)(st.st_mode & 0777));
451 if (strlen(file_name) > MAXPATHLEN) {
452 clean_up_temporary_files();
453 adios((char *)0, "attachment file name `%s' too long.", file_name);
456 (void)sprintf(cmd, "file '%s'", file_name);
458 if ((fp = popen(cmd, "r")) != (FILE *)0 && fgets(cmd, sizeof (cmd), fp) != (char *)0) {
459 *strchr(cmd, '\n') = '\0';
462 * The output of the "file" command is of the form
466 * Strip off the "file:" and subsequent white space.
469 for (p = cmd; *p != '\0'; p++) {
471 for (p++; *p != '\0'; p++) {
480 (void)fprintf(composition_file, " [ %s ]", p);
486 * Finish up with the file name.
489 (void)fprintf(composition_file, " %s\n", file_name);
495 * Split large message into several messages of
496 * type "message/partial" and send them.
500 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
502 int compnum, nparts, partno, state, status;
505 char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
506 char subject[BUFSIZ];
507 char name[NAMESZ], partnum[BUFSIZ];
510 if ((in = fopen (drft, "r")) == NULL)
511 adios (drft, "unable to open for reading");
517 * Scan through the message and examine the various header fields,
518 * as well as locate the beginning of the message body.
520 for (compnum = 1, state = FLD;;) {
521 switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
528 * This header field is discarded.
530 if (!strcasecmp (name, "Message-ID")) {
531 while (state == FLDPLUS)
532 state = m_getfld (state, name, buffer, sizeof(buffer), in);
533 } else if (uprf (name, XXX_FIELD_PRF)
534 || !strcasecmp (name, VRSN_FIELD)
535 || !strcasecmp (name, "Subject")
536 || !strcasecmp (name, "Encrypted")) {
538 * These header fields are copied to the enclosed
539 * header of the first message in the collection
540 * of message/partials. For the "Subject" header
541 * field, we also record it, so that a modified
542 * version of it, can be copied to the header
543 * of each messsage/partial in the collection.
545 if (!strcasecmp (name, "Subject")) {
548 strncpy (subject, buffer, BUFSIZ);
549 sublen = strlen (subject);
550 if (sublen > 0 && subject[sublen - 1] == '\n')
551 subject[sublen - 1] = '\0';
554 dp = add (concat (name, ":", buffer, NULL), dp);
555 while (state == FLDPLUS) {
556 state = m_getfld (state, name, buffer, sizeof(buffer), in);
557 dp = add (buffer, dp);
561 * These header fields are copied to the header of
562 * each message/partial in the collection.
564 cp = add (concat (name, ":", buffer, NULL), cp);
565 while (state == FLDPLUS) {
566 state = m_getfld (state, name, buffer, sizeof(buffer), in);
567 cp = add (buffer, cp);
571 if (state != FLDEOF) {
572 start = ftell (in) + 1;
584 adios (NULL, "message format error in component #%d", compnum);
587 adios (NULL, "getfld () returned %d", state);
593 adios (NULL, "headers missing from draft");
597 while (fgets (buffer, sizeof(buffer) - 1, in)) {
600 if ((pos += (len = strlen (buffer))) > CPERMSG) {
606 /* Only one part, nothing to split */
613 return sendaux (vec, vecp, drft, st);
617 printf ("Sending as %d Partial Messages\n", nparts);
622 vec[vecp++] = "-partno";
623 vec[vecp++] = partnum;
625 vec[vecp++] = "-queued";
628 snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
629 (int) getpid(), (long) clock, LocalName());
631 fseek (in, start, SEEK_SET);
632 for (partno = 1; partno <= nparts; partno++) {
636 strncpy (tmpdrf, m_scratch (drft, invo_name), sizeof(tmpdrf));
637 if ((out = fopen (tmpdrf, "w")) == NULL)
638 adios (tmpdrf, "unable to open for writing");
639 chmod (tmpdrf, 0600);
642 * Output the header fields
645 fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
646 fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
647 fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
648 fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
649 fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
652 * If this is the first in the collection, output the
653 * header fields we are encapsulating at the beginning
654 * of the body of the first message.
659 fprintf (out, "Message-ID: %s\n", msgid);
667 if (!fgets (buffer, sizeof(buffer) - 1, in)) {
668 if (partno == nparts)
670 adios (NULL, "premature eof");
673 if ((pos += (len = strlen (buffer))) > CPERMSG) {
674 fseek (in, -len, SEEK_CUR);
682 adios (tmpdrf, "error writing to");
686 if (!pushsw && verbsw) {
691 /* Pause here, if a delay is specified */
692 if (delay > 0 && 1 < partno && partno <= nparts) {
694 printf ("pausing %d seconds before sending part %d...\n",
698 sleep ((unsigned int) delay);
701 snprintf (partnum, sizeof(partnum), "%d", partno);
702 status = sendaux (vec, vecp, tmpdrf, st);
708 * This is so sendaux will only annotate
709 * the altmsg the first time it is called.
718 fclose (in); /* close the draft */
724 * Annotate original message, and
725 * call `postproc' to send message.
729 sendaux (char **vec, int vecp, char *drft, struct stat *st)
732 int i, status, fd, fd2;
733 char backup[BUFSIZ], buf[BUFSIZ];
735 fd = pushsw ? tmp_fd () : NOTOK;
740 if ((fd2 = tmp_fd ()) != NOTOK) {
741 vec[vecp++] = "-idanno";
742 snprintf (buf, sizeof(buf), "%d", fd2);
745 admonish (NULL, "unable to create file for annotation list");
748 if (distfile && distout (drft, distfile, backup) == NOTOK)
752 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
757 /* oops -- fork error */
758 adios ("fork", "unable to");
759 break; /* NOT REACHED */
763 * child process -- send it
765 * If fd is ok, then we are pushing and fd points to temp
766 * file, so capture anything on stdout and stderr there.
769 dup2 (fd, fileno (stdout));
770 dup2 (fd, fileno (stderr));
773 execvp (postproc, vec);
774 fprintf (stderr, "unable to exec ");
777 break; /* NOT REACHED */
781 * parent process -- wait for it
783 if ((status = pidwait(child_id, NOTOK)) == OK) {
784 if (annotext && fd2 != NOTOK)
788 * If postproc failed, and we have good fd (which means
789 * we pushed), then mail error message (and possibly the
790 * draft) back to the user.
796 advise (NULL, "message not delivered to anyone");
798 if (annotext && fd2 != NOTOK)
802 if (rename (backup, drft) == NOTOK)
803 advise (drft, "unable to rename %s to", backup);
814 * Mail error notification (and possibly a copy of the
815 * message) back to the user, using the mailproc
819 alert (char *file, int out)
825 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
830 /* oops -- fork error */
831 advise ("fork", "unable to");
834 /* child process -- send it */
835 SIGNAL (SIGHUP, SIG_IGN);
836 SIGNAL (SIGINT, SIG_IGN);
837 SIGNAL (SIGQUIT, SIG_IGN);
838 SIGNAL (SIGTERM, SIG_IGN);
840 if ((in = open (file, O_RDONLY)) == NOTOK) {
841 admonish (file, "unable to re-open");
843 lseek (out, (off_t) 0, SEEK_END);
844 strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
845 write (out, buf, strlen (buf));
846 strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
847 write (out, buf, strlen (buf));
848 cpydgst (in, out, file, "temporary file");
850 strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
851 write (out, buf, strlen (buf));
852 if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
853 admonish (buf, "unable to rename %s to", file);
856 lseek (out, (off_t) 0, SEEK_SET);
857 dup2 (out, fileno (stdin));
859 /* create subject for error notification */
860 snprintf (buf, sizeof(buf), "send failed on %s",
861 forwsw ? "enclosed draft" : file);
863 execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
864 "-subject", buf, NULL);
865 fprintf (stderr, "unable to exec ");
869 default: /* no waiting... */
881 strncpy (tmpfil, m_tmpfil (invo_name), sizeof(tmpfil));
882 if ((fd = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == NOTOK)
885 advise (NULL, "temporary file %s selected", tmpfil);
887 if (unlink (tmpfil) == NOTOK)
888 advise (tmpfil, "unable to remove");
895 anno (int fd, struct stat *st)
899 static char *cwd = NULL;
903 (stat (altmsg, &st2) == NOTOK
904 || st->st_mtime != st2.st_mtime
905 || st->st_dev != st2.st_dev
906 || st->st_ino != st2.st_ino)) {
908 admonish (NULL, "$mhaltmsg mismatch");
912 child_id = debugsw ? NOTOK : fork ();
914 case NOTOK: /* oops */
917 "unable to fork, so doing annotations by hand...");
919 cwd = getcpy (pwd ());
922 /* block a few signals */
924 sigaddset (&set, SIGHUP);
925 sigaddset (&set, SIGINT);
926 sigaddset (&set, SIGQUIT);
927 sigaddset (&set, SIGTERM);
928 SIGPROCMASK (SIG_BLOCK, &set, &oset);
934 /* reset the signal mask */
935 SIGPROCMASK (SIG_SETMASK, &oset, &set);
940 default: /* no waiting... */
950 int fd2, fd3, msgnum;
951 char *cp, *folder, *maildir;
952 char buffer[BUFSIZ], **ap;
956 if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
958 admonish (NULL, "$mhfolder not set");
961 maildir = m_maildir (folder);
962 if (chdir (maildir) == NOTOK) {
964 admonish (maildir, "unable to change directory to");
967 if (!(mp = folder_read (folder))) {
969 admonish (NULL, "unable to read folder %s");
973 /* check for empty folder */
974 if (mp->nummsg == 0) {
976 admonish (NULL, "no messages in %s", folder);
980 if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
982 admonish (NULL, "$mhmessages not set");
985 if (!debugsw /* MOBY HACK... */
987 && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
988 && (fd2 = dup (fileno (stderr))) != NOTOK) {
989 dup2 (fd3, fileno (stderr));
994 for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
998 dup2 (fd2, fileno (stderr));
999 if (mp->numsel == 0) {
1001 admonish (NULL, "no messages to annotate");
1005 lseek (fd, (off_t) 0, SEEK_SET);
1006 if ((fp = fdopen (fd, "r")) == NULL) {
1008 admonish (NULL, "unable to fdopen annotation list");
1012 while (fgets (buffer, sizeof(buffer), fp) != NULL)
1013 cp = add (buffer, cp);
1017 advise (NULL, "annotate%s with %s: \"%s\"",
1018 inplace ? " inplace" : "", annotext, cp);
1019 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1020 if (is_selected(mp, msgnum)) {
1022 advise (NULL, "annotate message %d", msgnum);
1023 annotate (m_name (msgnum), annotext, cp, inplace, 1, 0, 0);
1030 folder_free (mp); /* free folder/message structure */
1038 longjmp (env, status ? status : NOTOK);
1041 return 1; /* dead code to satisfy the compiler */