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 *);
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 *);
72 static void clean_up_temporary_files(void);
73 static int get_line(void);
74 static void make_mime_composition_file_entry(char *);
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)
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)) {
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)
193 char buf[MAXPATHLEN + 6]; /* miscellaneous buffer */
194 int c; /* current character for body copy */
195 int has_attachment; /* draft has at least one attachment */
196 int has_body; /* draft has a message body */
197 int length; /* length of attachment header field name */
198 char *p; /* miscellaneous string pointer */
201 * Open up the draft file.
204 if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
205 adios((char *)0, "can't open draft file `%s'.", draft_file_name);
208 * Allocate a buffer to hold the header components as they're read in.
209 * This buffer might need to be quite large, so we grow it as needed.
212 field = (char *)mh_xmalloc(field_size = 256);
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 field = (char *)mh_xrealloc((void *)field, field_size += 256);
370 * NUL-terminate the field..
379 make_mime_composition_file_entry(char *file_name)
381 int binary; /* binary character found flag */
382 int c; /* current character */
383 char cmd[MAXPATHLEN + 6]; /* file command buffer */
384 char *content_type; /* mime content type */
385 FILE *fp; /* content and pipe file pointer */
386 struct node *np; /* context scan node pointer */
387 char *p; /* miscellaneous string pointer */
388 struct stat st; /* file status buffer */
390 content_type = (char *)0;
393 * Check the file name for a suffix. Scan the context for that suffix on a
394 * mhshow-suffix- entry. We use these entries to be compatible with mhnshow,
395 * and there's no reason to make the user specify each suffix twice. Context
396 * entries of the form "mhshow-suffix-contenttype" in the name have the suffix
397 * in the field, including the dot.
400 if ((p = strrchr(file_name, '.')) != (char *)0) {
401 for (np = m_defs; np; np = np->n_next) {
402 if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0 && strcasecmp(p, np->n_field) == 0) {
403 content_type = np->n_name + 14;
410 * No content type was found, either because there was no matching entry in the
411 * context or because the file name has no suffix. Open the file and check for
412 * non-ASCII characters. Choose the content type based on this check.
415 if (content_type == (char *)0) {
416 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
417 clean_up_temporary_files();
418 adios((char *)0, "unable to access file \"%s\"", file_name);
423 while ((c = getc(fp)) != EOF) {
424 if (c > 127 || c < 0) {
432 content_type = binary ? "application/octet-stream" : "text/plain";
436 * Make sure that the attachment file exists and is readable. Append a mhbuild
437 * directive to the draft file. This starts with the content type. Append a
438 * file name attribute and a private x-unix-mode attribute. Also append a
439 * description obtained (if possible) by running the "file" command on the file.
442 if (stat(file_name, &st) == -1 || access(file_name, R_OK) != 0) {
443 clean_up_temporary_files();
444 adios((char *)0, "unable to access file \"%s\"", file_name);
447 (void)fprintf(composition_file, "#%s; name=\"%s\"; x-unix-mode=0%.3ho",
448 content_type, ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1, (unsigned short)(st.st_mode & 0777));
450 if (strlen(file_name) > MAXPATHLEN) {
451 clean_up_temporary_files();
452 adios((char *)0, "attachment file name `%s' too long.", file_name);
455 (void)sprintf(cmd, "file '%s'", file_name);
457 if ((fp = popen(cmd, "r")) != (FILE *)0 && fgets(cmd, sizeof (cmd), fp) != (char *)0) {
458 *strchr(cmd, '\n') = '\0';
461 * The output of the "file" command is of the form
465 * Strip off the "file:" and subsequent white space.
468 for (p = cmd; *p != '\0'; p++) {
470 for (p++; *p != '\0'; p++) {
479 (void)fprintf(composition_file, " [ %s ]", p);
485 * Finish up with the file name.
488 (void)fprintf(composition_file, " %s\n", file_name);
494 * Split large message into several messages of
495 * type "message/partial" and send them.
499 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
501 int compnum, nparts, partno, state, status;
504 char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
505 char subject[BUFSIZ];
506 char name[NAMESZ], partnum[BUFSIZ];
509 if ((in = fopen (drft, "r")) == NULL)
510 adios (drft, "unable to open for reading");
516 * Scan through the message and examine the various header fields,
517 * as well as locate the beginning of the message body.
519 for (compnum = 1, state = FLD;;) {
520 switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
527 * This header field is discarded.
529 if (!strcasecmp (name, "Message-ID")) {
530 while (state == FLDPLUS)
531 state = m_getfld (state, name, buffer, sizeof(buffer), in);
532 } else if (uprf (name, XXX_FIELD_PRF)
533 || !strcasecmp (name, VRSN_FIELD)
534 || !strcasecmp (name, "Subject")
535 || !strcasecmp (name, "Encrypted")) {
537 * These header fields are copied to the enclosed
538 * header of the first message in the collection
539 * of message/partials. For the "Subject" header
540 * field, we also record it, so that a modified
541 * version of it, can be copied to the header
542 * of each messsage/partial in the collection.
544 if (!strcasecmp (name, "Subject")) {
547 strncpy (subject, buffer, BUFSIZ);
548 sublen = strlen (subject);
549 if (sublen > 0 && subject[sublen - 1] == '\n')
550 subject[sublen - 1] = '\0';
553 dp = add (concat (name, ":", buffer, NULL), dp);
554 while (state == FLDPLUS) {
555 state = m_getfld (state, name, buffer, sizeof(buffer), in);
556 dp = add (buffer, dp);
560 * These header fields are copied to the header of
561 * each message/partial in the collection.
563 cp = add (concat (name, ":", buffer, NULL), cp);
564 while (state == FLDPLUS) {
565 state = m_getfld (state, name, buffer, sizeof(buffer), in);
566 cp = add (buffer, cp);
570 if (state != FLDEOF) {
571 start = ftell (in) + 1;
583 adios (NULL, "message format error in component #%d", compnum);
586 adios (NULL, "getfld () returned %d", state);
592 adios (NULL, "headers missing from draft");
596 while (fgets (buffer, sizeof(buffer) - 1, in)) {
599 if ((pos += (len = strlen (buffer))) > CPERMSG) {
605 /* Only one part, nothing to split */
612 return sendaux (vec, vecp, drft, st);
616 printf ("Sending as %d Partial Messages\n", nparts);
621 vec[vecp++] = "-partno";
622 vec[vecp++] = partnum;
624 vec[vecp++] = "-queued";
627 snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
628 (int) getpid(), (long) clock, LocalName());
630 fseek (in, start, SEEK_SET);
631 for (partno = 1; partno <= nparts; partno++) {
635 strncpy (tmpdrf, m_scratch (drft, invo_name), sizeof(tmpdrf));
636 if ((out = fopen (tmpdrf, "w")) == NULL)
637 adios (tmpdrf, "unable to open for writing");
638 chmod (tmpdrf, 0600);
641 * Output the header fields
644 fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
645 fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
646 fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
647 fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
648 fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
651 * If this is the first in the collection, output the
652 * header fields we are encapsulating at the beginning
653 * of the body of the first message.
658 fprintf (out, "Message-ID: %s\n", msgid);
666 if (!fgets (buffer, sizeof(buffer) - 1, in)) {
667 if (partno == nparts)
669 adios (NULL, "premature eof");
672 if ((pos += (len = strlen (buffer))) > CPERMSG) {
673 fseek (in, -len, SEEK_CUR);
681 adios (tmpdrf, "error writing to");
685 if (!pushsw && verbsw) {
690 /* Pause here, if a delay is specified */
691 if (delay > 0 && 1 < partno && partno <= nparts) {
693 printf ("pausing %d seconds before sending part %d...\n",
697 sleep ((unsigned int) delay);
700 snprintf (partnum, sizeof(partnum), "%d", partno);
701 status = sendaux (vec, vecp, tmpdrf, st);
707 * This is so sendaux will only annotate
708 * the altmsg the first time it is called.
717 fclose (in); /* close the draft */
723 * Annotate original message, and
724 * call `postproc' to send message.
728 sendaux (char **vec, int vecp, char *drft, struct stat *st)
731 int i, status, fd, fd2;
732 char backup[BUFSIZ], buf[BUFSIZ];
734 fd = pushsw ? tmp_fd () : NOTOK;
739 if ((fd2 = tmp_fd ()) != NOTOK) {
740 vec[vecp++] = "-idanno";
741 snprintf (buf, sizeof(buf), "%d", fd2);
744 admonish (NULL, "unable to create file for annotation list");
747 if (distfile && distout (drft, distfile, backup) == NOTOK)
751 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
756 /* oops -- fork error */
757 adios ("fork", "unable to");
758 break; /* NOT REACHED */
762 * child process -- send it
764 * If fd is ok, then we are pushing and fd points to temp
765 * file, so capture anything on stdout and stderr there.
768 dup2 (fd, fileno (stdout));
769 dup2 (fd, fileno (stderr));
772 execvp (postproc, vec);
773 fprintf (stderr, "unable to exec ");
776 break; /* NOT REACHED */
780 * parent process -- wait for it
782 if ((status = pidwait(child_id, NOTOK)) == OK) {
783 if (annotext && fd2 != NOTOK)
787 * If postproc failed, and we have good fd (which means
788 * we pushed), then mail error message (and possibly the
789 * draft) back to the user.
795 advise (NULL, "message not delivered to anyone");
797 if (annotext && fd2 != NOTOK)
801 if (rename (backup, drft) == NOTOK)
802 advise (drft, "unable to rename %s to", backup);
813 * Mail error notification (and possibly a copy of the
814 * message) back to the user, using the mailproc
818 alert (char *file, int out)
824 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
829 /* oops -- fork error */
830 advise ("fork", "unable to");
833 /* child process -- send it */
834 SIGNAL (SIGHUP, SIG_IGN);
835 SIGNAL (SIGINT, SIG_IGN);
836 SIGNAL (SIGQUIT, SIG_IGN);
837 SIGNAL (SIGTERM, SIG_IGN);
839 if ((in = open (file, O_RDONLY)) == NOTOK) {
840 admonish (file, "unable to re-open");
842 lseek (out, (off_t) 0, SEEK_END);
843 strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
844 write (out, buf, strlen (buf));
845 strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
846 write (out, buf, strlen (buf));
847 cpydgst (in, out, file, "temporary file");
849 strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
850 write (out, buf, strlen (buf));
851 if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
852 admonish (buf, "unable to rename %s to", file);
855 lseek (out, (off_t) 0, SEEK_SET);
856 dup2 (out, fileno (stdin));
858 /* create subject for error notification */
859 snprintf (buf, sizeof(buf), "send failed on %s",
860 forwsw ? "enclosed draft" : file);
862 execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
863 "-subject", buf, NULL);
864 fprintf (stderr, "unable to exec ");
868 default: /* no waiting... */
880 strncpy (tmpfil, m_tmpfil (invo_name), sizeof(tmpfil));
881 if ((fd = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == NOTOK)
884 advise (NULL, "temporary file %s selected", tmpfil);
886 if (unlink (tmpfil) == NOTOK)
887 advise (tmpfil, "unable to remove");
894 anno (int fd, struct stat *st)
898 static char *cwd = NULL;
902 (stat (altmsg, &st2) == NOTOK
903 || st->st_mtime != st2.st_mtime
904 || st->st_dev != st2.st_dev
905 || st->st_ino != st2.st_ino)) {
907 admonish (NULL, "$mhaltmsg mismatch");
911 child_id = debugsw ? NOTOK : fork ();
913 case NOTOK: /* oops */
916 "unable to fork, so doing annotations by hand...");
918 cwd = getcpy (pwd ());
921 /* block a few signals */
923 sigaddset (&set, SIGHUP);
924 sigaddset (&set, SIGINT);
925 sigaddset (&set, SIGQUIT);
926 sigaddset (&set, SIGTERM);
927 SIGPROCMASK (SIG_BLOCK, &set, &oset);
933 /* reset the signal mask */
934 SIGPROCMASK (SIG_SETMASK, &oset, &set);
939 default: /* no waiting... */
949 int fd2, fd3, msgnum;
950 char *cp, *folder, *maildir;
951 char buffer[BUFSIZ], **ap;
955 if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
957 admonish (NULL, "$mhfolder not set");
960 maildir = m_maildir (folder);
961 if (chdir (maildir) == NOTOK) {
963 admonish (maildir, "unable to change directory to");
966 if (!(mp = folder_read (folder))) {
968 admonish (NULL, "unable to read folder %s");
972 /* check for empty folder */
973 if (mp->nummsg == 0) {
975 admonish (NULL, "no messages in %s", folder);
979 if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
981 admonish (NULL, "$mhmessages not set");
984 if (!debugsw /* MOBY HACK... */
986 && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
987 && (fd2 = dup (fileno (stderr))) != NOTOK) {
988 dup2 (fd3, fileno (stderr));
993 for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
997 dup2 (fd2, fileno (stderr));
998 if (mp->numsel == 0) {
1000 admonish (NULL, "no messages to annotate");
1004 lseek (fd, (off_t) 0, SEEK_SET);
1005 if ((fp = fdopen (fd, "r")) == NULL) {
1007 admonish (NULL, "unable to fdopen annotation list");
1011 while (fgets (buffer, sizeof(buffer), fp) != NULL)
1012 cp = add (buffer, cp);
1016 advise (NULL, "annotate%s with %s: \"%s\"",
1017 inplace ? " inplace" : "", annotext, cp);
1018 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1019 if (is_selected(mp, msgnum)) {
1021 advise (NULL, "annotate message %d", msgnum);
1022 annotate (m_name (msgnum), annotext, cp, inplace, 1, -2, 0);
1029 folder_free (mp); /* free folder/message structure */
1037 longjmp (env, status ? status : NOTOK);
1040 return 1; /* dead code to satisfy the compiler */