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;
47 static char body_file_name[MAXPATHLEN + 1]; /* name of temporary file for body content */
48 static char composition_file_name[MAXPATHLEN + 1]; /* name of mhbuild composition temporary file */
49 static int field_size; /* size of header field buffer */
50 static char *field; /* header field buffer */
51 static FILE *draft_file; /* draft file pointer */
52 static FILE *body_file; /* body file pointer */
53 static FILE *composition_file; /* composition file pointer */
58 int sendsbr (char **, int, char *, struct stat *, int, char *, int);
60 char *getusername (void);
65 static void alert (char *, int);
66 static int tmp_fd (void);
67 static void anno (int, struct stat *);
68 static void annoaux (int);
69 static int splitmsg (char **, int, char *, struct stat *, int);
70 static int sendaux (char **, int, char *, struct stat *);
72 static int attach(char *, char *, int);
73 static void clean_up_temporary_files(void);
74 static int get_line(void);
75 static void make_mime_composition_file_entry(char *, int);
79 * Entry point into (back-end) routines to send message.
83 sendsbr (char **vec, int vecp, char *drft, struct stat *st, int rename_drft, char *attachment_header_field_name, int attachformat)
86 char buffer[BUFSIZ], file[BUFSIZ];
88 char *original_draft; /* name of original draft file */
89 char *p; /* string pointer for building file name */
92 * Save the original name of the draft file. The name of the draft file is changed
93 * to a temporary file containing the built MIME message if there are attachments.
94 * We need the original name so that it can be renamed after the message is sent.
97 original_draft = drft;
100 * There might be attachments if a header field name for attachments is supplied.
101 * Convert the draft to a MIME message. Use the mhbuild composition file for the
102 * draft if there was a successful conversion because that now contains the MIME
103 * message. A nice side effect of this is that it leaves the original draft file
104 * untouched so that it can be retrieved 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 if (rename (drft, strncpy (file, m_scratch (drft, invo_name), sizeof(file)))
131 adios (file, "unable to rename %s to", drft);
136 * Check if we need to split the message into
137 * multiple messages of type "message/partial".
139 if (splitsw >= 0 && !distfile && stat (drft, &sts) != NOTOK
140 && sts.st_size >= CPERMSG) {
141 status = splitmsg (vec, vecp, drft, st, splitsw) ? NOTOK : OK;
143 status = sendaux (vec, vecp, drft, st) ? NOTOK : OK;
146 /* rename the original draft */
147 if (rename_drft && status == OK &&
148 rename (original_draft, strncpy (buffer, m_backup (original_draft), sizeof(buffer))) == NOTOK)
149 advise (buffer, "unable to rename %s to", drft);
162 * Get rid of any temporary files that we created for attachments. Also get rid of
163 * the renamed composition file that mhbuild leaves as a turd. It looks confusing,
164 * but we use the body file name to help build the renamed composition file name.
167 if (drft == composition_file_name) {
168 clean_up_temporary_files();
170 if (strlen(composition_file_name) >= sizeof (composition_file_name) - 6)
171 advise((char *)0, "unable to remove original composition file.");
174 if ((p = strrchr(composition_file_name, '/')) == (char *)0)
175 p = composition_file_name;
179 (void)strcpy(body_file_name, p);
181 (void)strcpy(p, body_file_name);
182 (void)strcat(p, ".orig");
184 (void)unlink(composition_file_name);
192 attach(char *attachment_header_field_name, char *draft_file_name,
195 char buf[MAXPATHLEN + 6]; /* miscellaneous buffer */
196 int c; /* current character for body copy */
197 int has_attachment; /* draft has at least one attachment */
198 int has_body; /* draft has a message body */
199 int length; /* length of attachment header field name */
200 char *p; /* miscellaneous string pointer */
203 * Open up the draft file.
206 if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
207 adios((char *)0, "can't open draft file `%s'.", draft_file_name);
210 * Allocate a buffer to hold the header components as they're read in.
211 * This buffer might need to be quite large, so we grow it as needed.
214 field = (char *)mh_xmalloc(field_size = 256);
217 * Scan the draft file for a header field name that matches the -attach
218 * argument. The existence of one indicates that the draft has attachments.
219 * Bail out if there are no attachments because we're done. Read to the
220 * end of the headers even if we have no attachments.
223 length = strlen(attachment_header_field_name);
227 while (get_line() != EOF && *field != '\0' && *field != '-')
228 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':')
231 if (has_attachment == 0)
235 * We have at least one attachment. Look for at least one non-blank line
236 * in the body of the message which indicates content in the body.
241 while (get_line() != EOF) {
242 for (p = field; *p != '\0'; p++) {
243 if (*p != ' ' && *p != '\t') {
254 * Make names for the temporary files.
257 (void)strncpy(body_file_name, m_scratch("", m_maildir(invo_name)), sizeof (body_file_name));
258 (void)strncpy(composition_file_name, m_scratch("", m_maildir(invo_name)), sizeof (composition_file_name));
261 body_file = fopen(body_file_name, "w");
263 composition_file = fopen(composition_file_name, "w");
265 if ((has_body && body_file == (FILE *)0) || composition_file == (FILE *)0) {
266 clean_up_temporary_files();
267 adios((char *)0, "unable to open all of the temporary files.");
271 * Start at the beginning of the draft file. Copy all non-attachment header fields
272 * to the temporary composition file. Then add the dashed line separator.
277 while (get_line() != EOF && *field != '\0' && *field != '-')
278 if (strncasecmp(field, attachment_header_field_name, length) != 0 || field[length] != ':')
279 (void)fprintf(composition_file, "%s\n", field);
281 (void)fputs("--------\n", composition_file);
284 * Copy the message body to a temporary file.
288 while ((c = getc(draft_file)) != EOF)
291 (void)fclose(body_file);
295 * Add a mhbuild MIME composition file line for the body if there was one.
299 make_mime_composition_file_entry(body_file_name, attachformat);
302 * Now, go back to the beginning of the draft file and look for header fields
303 * that specify attachments. Add a mhbuild MIME composition file for each.
308 while (get_line() != EOF && *field != '\0' && *field != '-') {
309 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':') {
310 for (p = field + length + 1; *p == ' ' || *p == '\t'; p++)
313 make_mime_composition_file_entry(p, attachformat);
317 (void)fclose(composition_file);
320 * We're ready to roll! Run mhbuild on the composition file. Note that mhbuild
321 * is in the context as buildmimeproc.
324 (void)sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
326 if (system(buf) != 0) {
327 clean_up_temporary_files();
335 clean_up_temporary_files(void)
337 (void)unlink(body_file_name);
338 (void)unlink(composition_file_name);
346 int c; /* current character */
347 int n; /* number of bytes in buffer */
348 char *p; /* buffer pointer */
351 * Get a line from the input file, growing the field buffer as needed. We do this
352 * so that we can fit an entire line in the buffer making it easy to do a string
353 * comparison on both the field name and the field body which might be a long path
357 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
358 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
359 (void)ungetc(c, draft_file);
364 if (++n >= field_size - 1) {
365 field = (char *)mh_xrealloc((void *)field, field_size += 256);
372 * NUL-terminate the field..
381 make_mime_composition_file_entry(char *file_name, int attachformat)
383 int binary; /* binary character found flag */
384 int c; /* current character */
385 char cmd[MAXPATHLEN + 6]; /* file command buffer */
386 char *content_type; /* mime content type */
387 FILE *fp; /* content and pipe file pointer */
388 struct node *np; /* context scan node pointer */
389 char *p; /* miscellaneous string pointer */
390 struct stat st; /* file status buffer */
392 content_type = (char *)0;
395 * Check the file name for a suffix. Scan the context for that suffix on a
396 * mhshow-suffix- entry. We use these entries to be compatible with mhnshow,
397 * and there's no reason to make the user specify each suffix twice. Context
398 * entries of the form "mhshow-suffix-contenttype" in the name have the suffix
399 * in the field, including the dot.
402 if ((p = strrchr(file_name, '.')) != (char *)0) {
403 for (np = m_defs; np; np = np->n_next) {
404 if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0 && mh_strcasecmp(p, np->n_field) == 0) {
405 content_type = np->n_name + 14;
412 * No content type was found, either because there was no matching entry in the
413 * context or because the file name has no suffix. Open the file and check for
414 * non-ASCII characters. Choose the content type based on this check.
417 if (content_type == (char *)0) {
418 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
419 clean_up_temporary_files();
420 adios((char *)0, "unable to access file \"%s\"", file_name);
425 while ((c = getc(fp)) != EOF) {
426 if (c > 127 || c < 0) {
434 content_type = binary ? "application/octet-stream" : "text/plain";
438 * Make sure that the attachment file exists and is readable. Append a mhbuild
439 * directive to the draft file. This starts with the content type. Append a
440 * file name attribute and a private x-unix-mode attribute. Also append a
441 * description obtained (if possible) by running the "file" command on the file.
444 if (stat(file_name, &st) == -1 || access(file_name, R_OK) != 0) {
445 clean_up_temporary_files();
446 adios((char *)0, "unable to access file \"%s\"", file_name);
449 switch (attachformat) {
451 /* Insert name, file mode, and Content-Id. */
452 (void)fprintf(composition_file, "#%s; name=\"%s\"; x-unix-mode=0%.3ho",
453 content_type, ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1, (unsigned short)(st.st_mode & 0777));
455 if (strlen(file_name) > MAXPATHLEN) {
456 clean_up_temporary_files();
457 adios((char *)0, "attachment file name `%s' too long.", file_name);
460 (void)sprintf(cmd, "file '%s'", file_name);
462 if ((fp = popen(cmd, "r")) != (FILE *)0 && fgets(cmd, sizeof (cmd), fp) != (char *)0) {
463 *strchr(cmd, '\n') = '\0';
466 * The output of the "file" command is of the form
470 * Strip off the "file:" and subsequent white space.
473 for (p = cmd; *p != '\0'; p++) {
475 for (p++; *p != '\0'; p++) {
484 /* Insert Content-Description. */
485 (void)fprintf(composition_file, " [ %s ]", p);
492 /* Suppress Content-Id, insert simple Content-Disposition. */
493 (void) fprintf (composition_file, "#%s <>{attachment}", content_type);
497 /* Suppress Content-Id, insert Content-Disposition with
498 modification date. */
499 (void) fprintf (composition_file,
500 "#%s <>{attachment; modification-date=\"%s\"}",
502 dtime (&st.st_mtime, 0));
506 adios ((char *)0, "unsupported attachformat %d", attachformat);
510 * Finish up with the file name.
513 (void)fprintf(composition_file, " %s\n", file_name);
519 * Split large message into several messages of
520 * type "message/partial" and send them.
524 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
526 int compnum, nparts, partno, state, status;
529 char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
530 char subject[BUFSIZ];
531 char name[NAMESZ], partnum[BUFSIZ];
534 if ((in = fopen (drft, "r")) == NULL)
535 adios (drft, "unable to open for reading");
541 * Scan through the message and examine the various header fields,
542 * as well as locate the beginning of the message body.
544 for (compnum = 1, state = FLD;;) {
545 switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
552 * This header field is discarded.
554 if (!mh_strcasecmp (name, "Message-ID")) {
555 while (state == FLDPLUS)
556 state = m_getfld (state, name, buffer, sizeof(buffer), in);
557 } else if (uprf (name, XXX_FIELD_PRF)
558 || !mh_strcasecmp (name, VRSN_FIELD)
559 || !mh_strcasecmp (name, "Subject")
560 || !mh_strcasecmp (name, "Encrypted")) {
562 * These header fields are copied to the enclosed
563 * header of the first message in the collection
564 * of message/partials. For the "Subject" header
565 * field, we also record it, so that a modified
566 * version of it, can be copied to the header
567 * of each messsage/partial in the collection.
569 if (!mh_strcasecmp (name, "Subject")) {
572 strncpy (subject, buffer, BUFSIZ);
573 sublen = strlen (subject);
574 if (sublen > 0 && subject[sublen - 1] == '\n')
575 subject[sublen - 1] = '\0';
578 dp = add (concat (name, ":", buffer, NULL), dp);
579 while (state == FLDPLUS) {
580 state = m_getfld (state, name, buffer, sizeof(buffer), in);
581 dp = add (buffer, dp);
585 * These header fields are copied to the header of
586 * each message/partial in the collection.
588 cp = add (concat (name, ":", buffer, NULL), cp);
589 while (state == FLDPLUS) {
590 state = m_getfld (state, name, buffer, sizeof(buffer), in);
591 cp = add (buffer, cp);
595 if (state != FLDEOF) {
596 start = ftell (in) + 1;
608 adios (NULL, "message format error in component #%d", compnum);
611 adios (NULL, "getfld () returned %d", state);
617 adios (NULL, "headers missing from draft");
621 while (fgets (buffer, sizeof(buffer) - 1, in)) {
624 if ((pos += (len = strlen (buffer))) > CPERMSG) {
630 /* Only one part, nothing to split */
637 return sendaux (vec, vecp, drft, st);
641 printf ("Sending as %d Partial Messages\n", nparts);
646 vec[vecp++] = "-partno";
647 vec[vecp++] = partnum;
649 vec[vecp++] = "-queued";
652 snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
653 (int) getpid(), (long) clock, LocalName());
655 fseek (in, start, SEEK_SET);
656 for (partno = 1; partno <= nparts; partno++) {
660 strncpy (tmpdrf, m_scratch (drft, invo_name), sizeof(tmpdrf));
661 if ((out = fopen (tmpdrf, "w")) == NULL)
662 adios (tmpdrf, "unable to open for writing");
663 chmod (tmpdrf, 0600);
666 * Output the header fields
669 fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
670 fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
671 fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
672 fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
673 fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
676 * If this is the first in the collection, output the
677 * header fields we are encapsulating at the beginning
678 * of the body of the first message.
683 fprintf (out, "Message-ID: %s\n", msgid);
691 if (!fgets (buffer, sizeof(buffer) - 1, in)) {
692 if (partno == nparts)
694 adios (NULL, "premature eof");
697 if ((pos += (len = strlen (buffer))) > CPERMSG) {
698 fseek (in, -len, SEEK_CUR);
706 adios (tmpdrf, "error writing to");
710 if (!pushsw && verbsw) {
715 /* Pause here, if a delay is specified */
716 if (delay > 0 && 1 < partno && partno <= nparts) {
718 printf ("pausing %d seconds before sending part %d...\n",
722 sleep ((unsigned int) delay);
725 snprintf (partnum, sizeof(partnum), "%d", partno);
726 status = sendaux (vec, vecp, tmpdrf, st);
732 * This is so sendaux will only annotate
733 * the altmsg the first time it is called.
742 fclose (in); /* close the draft */
748 * Annotate original message, and
749 * call `postproc' to send message.
753 sendaux (char **vec, int vecp, char *drft, struct stat *st)
756 int i, status, fd, fd2;
757 char backup[BUFSIZ], buf[BUFSIZ];
759 fd = pushsw ? tmp_fd () : NOTOK;
764 if ((fd2 = tmp_fd ()) != NOTOK) {
765 vec[vecp++] = "-idanno";
766 snprintf (buf, sizeof(buf), "%d", fd2);
769 admonish (NULL, "unable to create file for annotation list");
772 if (distfile && distout (drft, distfile, backup) == NOTOK)
776 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
781 /* oops -- fork error */
782 adios ("fork", "unable to");
783 break; /* NOT REACHED */
787 * child process -- send it
789 * If fd is ok, then we are pushing and fd points to temp
790 * file, so capture anything on stdout and stderr there.
793 dup2 (fd, fileno (stdout));
794 dup2 (fd, fileno (stderr));
797 execvp (postproc, vec);
798 fprintf (stderr, "unable to exec ");
801 break; /* NOT REACHED */
805 * parent process -- wait for it
807 if ((status = pidwait(child_id, NOTOK)) == OK) {
808 if (annotext && fd2 != NOTOK)
812 * If postproc failed, and we have good fd (which means
813 * we pushed), then mail error message (and possibly the
814 * draft) back to the user.
820 advise (NULL, "message not delivered to anyone");
822 if (annotext && fd2 != NOTOK)
826 if (rename (backup, drft) == NOTOK)
827 advise (drft, "unable to rename %s to", backup);
838 * Mail error notification (and possibly a copy of the
839 * message) back to the user, using the mailproc
843 alert (char *file, int out)
849 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
854 /* oops -- fork error */
855 advise ("fork", "unable to");
858 /* child process -- send it */
859 SIGNAL (SIGHUP, SIG_IGN);
860 SIGNAL (SIGINT, SIG_IGN);
861 SIGNAL (SIGQUIT, SIG_IGN);
862 SIGNAL (SIGTERM, SIG_IGN);
864 if ((in = open (file, O_RDONLY)) == NOTOK) {
865 admonish (file, "unable to re-open");
867 lseek (out, (off_t) 0, SEEK_END);
868 strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
869 write (out, buf, strlen (buf));
870 strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
871 write (out, buf, strlen (buf));
872 cpydgst (in, out, file, "temporary file");
874 strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
875 write (out, buf, strlen (buf));
876 if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
877 admonish (buf, "unable to rename %s to", file);
880 lseek (out, (off_t) 0, SEEK_SET);
881 dup2 (out, fileno (stdin));
883 /* create subject for error notification */
884 snprintf (buf, sizeof(buf), "send failed on %s",
885 forwsw ? "enclosed draft" : file);
887 execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
888 "-subject", buf, NULL);
889 fprintf (stderr, "unable to exec ");
893 default: /* no waiting... */
905 strncpy (tmpfil, m_tmpfil (invo_name), sizeof(tmpfil));
906 if ((fd = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == NOTOK)
909 advise (NULL, "temporary file %s selected", tmpfil);
911 if (unlink (tmpfil) == NOTOK)
912 advise (tmpfil, "unable to remove");
919 anno (int fd, struct stat *st)
923 static char *cwd = NULL;
927 (stat (altmsg, &st2) == NOTOK
928 || st->st_mtime != st2.st_mtime
929 || st->st_dev != st2.st_dev
930 || st->st_ino != st2.st_ino)) {
932 admonish (NULL, "$mhaltmsg mismatch");
936 child_id = debugsw ? NOTOK : fork ();
938 case NOTOK: /* oops */
941 "unable to fork, so doing annotations by hand...");
943 cwd = getcpy (pwd ());
946 /* block a few signals */
948 sigaddset (&set, SIGHUP);
949 sigaddset (&set, SIGINT);
950 sigaddset (&set, SIGQUIT);
951 sigaddset (&set, SIGTERM);
952 SIGPROCMASK (SIG_BLOCK, &set, &oset);
958 /* reset the signal mask */
959 SIGPROCMASK (SIG_SETMASK, &oset, &set);
964 default: /* no waiting... */
974 int fd2, fd3, msgnum;
975 char *cp, *folder, *maildir;
976 char buffer[BUFSIZ], **ap;
980 if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
982 admonish (NULL, "$mhfolder not set");
985 maildir = m_maildir (folder);
986 if (chdir (maildir) == NOTOK) {
988 admonish (maildir, "unable to change directory to");
991 if (!(mp = folder_read (folder))) {
993 admonish (NULL, "unable to read folder %s");
997 /* check for empty folder */
998 if (mp->nummsg == 0) {
1000 admonish (NULL, "no messages in %s", folder);
1004 if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
1006 admonish (NULL, "$mhmessages not set");
1009 if (!debugsw /* MOBY HACK... */
1011 && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
1012 && (fd2 = dup (fileno (stderr))) != NOTOK) {
1013 dup2 (fd3, fileno (stderr));
1018 for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
1019 m_convert (mp, *ap);
1022 dup2 (fd2, fileno (stderr));
1023 if (mp->numsel == 0) {
1025 admonish (NULL, "no messages to annotate");
1029 lseek (fd, (off_t) 0, SEEK_SET);
1030 if ((fp = fdopen (fd, "r")) == NULL) {
1032 admonish (NULL, "unable to fdopen annotation list");
1036 while (fgets (buffer, sizeof(buffer), fp) != NULL)
1037 cp = add (buffer, cp);
1041 advise (NULL, "annotate%s with %s: \"%s\"",
1042 inplace ? " inplace" : "", annotext, cp);
1043 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1044 if (is_selected(mp, msgnum)) {
1046 advise (NULL, "annotate message %d", msgnum);
1047 annotate (m_name (msgnum), annotext, cp, inplace, 1, -2, 0);
1054 folder_free (mp); /* free folder/message structure */
1062 longjmp (env, status ? status : NOTOK);
1065 return 1; /* dead code to satisfy the compiler */