3 * sendsbr.c -- routines to help WhatNow/Send along
5 * This code is Copyright (c) 2002, by the authors of nmh. See the
6 * COPYRIGHT file in the root directory of the nmh distribution for
7 * complete copyright information.
11 #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;
44 static char body_file_name[MAXPATHLEN + 1]; /* name of temporary file for body content */
45 static char composition_file_name[MAXPATHLEN + 1]; /* name of mhbuild composition temporary file */
46 static int field_size; /* size of header field buffer */
47 static char *field; /* header field buffer */
48 static FILE *draft_file; /* draft file pointer */
49 static FILE *body_file; /* body file pointer */
50 static FILE *composition_file; /* composition file pointer */
55 int sendsbr (char **, int, char *, struct stat *, int, char *, int);
56 char *getusername (void);
61 static void armed_done (int) NORETURN;
62 static void alert (char *, int);
63 static int tmp_fd (void);
64 static void anno (int, struct stat *);
65 static void annoaux (int);
66 static int splitmsg (char **, int, char *, struct stat *, int);
67 static int sendaux (char **, int, char *, struct stat *);
69 static int attach(char *, char *, int);
70 static void clean_up_temporary_files(void);
71 static int get_line(void);
72 static void make_mime_composition_file_entry(char *, int);
76 * Entry point into (back-end) routines to send message.
80 sendsbr (char **vec, int vecp, char *drft, struct stat *st, int rename_drft, char *attachment_header_field_name, int attachformat)
83 char buffer[BUFSIZ], file[BUFSIZ];
85 char *original_draft; /* name of original draft file */
86 char *p; /* string pointer for building file name */
89 * Save the original name of the draft file. The name of the draft file is changed
90 * to a temporary file containing the built MIME message if there are attachments.
91 * We need the original name so that it can be renamed after the message is sent.
94 original_draft = drft;
97 * There might be attachments if a header field name for attachments is supplied.
98 * Convert the draft to a MIME message. Use the mhbuild composition file for the
99 * draft if there was a successful conversion because that now contains the MIME
100 * message. A nice side effect of this is that it leaves the original draft file
101 * untouched so that it can be retrieved and modified if desired.
104 if (attachment_header_field_name != (char *)0) {
105 switch (attach(attachment_header_field_name, drft, attachformat)) {
107 drft = composition_file_name;
119 switch (setjmp (env)) {
122 * If given -push and -unique (which is undocumented), then
123 * rename the draft file. I'm not quite sure why.
125 if (pushsw && unique) {
126 char *cp = m_mktemp2(drft, invo_name, NULL, NULL);
128 adios ("sendsbr", "unable to create temporary file");
130 if (rename (drft, strncpy(file, cp, sizeof(file))) == NOTOK)
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,
258 m_mktemp(m_maildir(invo_name), NULL, NULL),
259 sizeof (body_file_name));
260 (void)strncpy(composition_file_name,
261 m_mktemp(m_maildir(invo_name), NULL, NULL),
262 sizeof (composition_file_name));
265 body_file = fopen(body_file_name, "w");
267 composition_file = fopen(composition_file_name, "w");
269 if ((has_body && body_file == (FILE *)0) || composition_file == (FILE *)0) {
270 clean_up_temporary_files();
271 adios((char *)0, "unable to open all of the temporary files.");
275 * Start at the beginning of the draft file. Copy all non-attachment header fields
276 * to the temporary composition file. Then add the dashed line separator.
281 while (get_line() != EOF && *field != '\0' && *field != '-')
282 if (strncasecmp(field, attachment_header_field_name, length) != 0 || field[length] != ':')
283 (void)fprintf(composition_file, "%s\n", field);
285 (void)fputs("--------\n", composition_file);
288 * Copy the message body to a temporary file.
292 while ((c = getc(draft_file)) != EOF)
295 (void)fclose(body_file);
299 * Add a mhbuild MIME composition file line for the body if there was one.
303 make_mime_composition_file_entry(body_file_name, attachformat);
306 * Now, go back to the beginning of the draft file and look for header fields
307 * that specify attachments. Add a mhbuild MIME composition file for each.
312 while (get_line() != EOF && *field != '\0' && *field != '-') {
313 if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':') {
314 for (p = field + length + 1; *p == ' ' || *p == '\t'; p++)
317 make_mime_composition_file_entry(p, attachformat);
321 (void)fclose(composition_file);
324 * We're ready to roll! Run mhbuild on the composition file. Note that mhbuild
325 * is in the context as buildmimeproc.
328 (void)sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
330 if (system(buf) != 0) {
331 clean_up_temporary_files();
339 clean_up_temporary_files(void)
341 (void)unlink(body_file_name);
342 (void)unlink(composition_file_name);
350 int c; /* current character */
351 int n; /* number of bytes in buffer */
352 char *p; /* buffer pointer */
355 * Get a line from the input file, growing the field buffer as needed. We do this
356 * so that we can fit an entire line in the buffer making it easy to do a string
357 * comparison on both the field name and the field body which might be a long path
361 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
362 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
363 (void)ungetc(c, draft_file);
368 if (++n >= field_size - 1) {
369 field = (char *)mh_xrealloc((void *)field, field_size += 256);
376 * NUL-terminate the field..
385 make_mime_composition_file_entry(char *file_name, int attachformat)
387 int binary; /* binary character found flag */
388 int c; /* current character */
389 char cmd[MAXPATHLEN + 6]; /* file command buffer */
390 char *content_type; /* mime content type */
391 FILE *fp; /* content and pipe file pointer */
392 struct node *np; /* context scan node pointer */
393 char *p; /* miscellaneous string pointer */
394 struct stat st; /* file status buffer */
396 content_type = (char *)0;
399 * Check the file name for a suffix. Scan the context for that suffix on a
400 * mhshow-suffix- entry. We use these entries to be compatible with mhnshow,
401 * and there's no reason to make the user specify each suffix twice. Context
402 * entries of the form "mhshow-suffix-contenttype" in the name have the suffix
403 * in the field, including the dot.
406 if ((p = strrchr(file_name, '.')) != (char *)0) {
407 for (np = m_defs; np; np = np->n_next) {
408 if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0 && mh_strcasecmp(p, np->n_field) == 0) {
409 content_type = np->n_name + 14;
416 * No content type was found, either because there was no matching entry in the
417 * context or because the file name has no suffix. Open the file and check for
418 * non-ASCII characters. Choose the content type based on this check.
421 if (content_type == (char *)0) {
422 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
423 clean_up_temporary_files();
424 adios((char *)0, "unable to access file \"%s\"", file_name);
429 while ((c = getc(fp)) != EOF) {
430 if (c > 127 || c < 0) {
438 content_type = binary ? "application/octet-stream" : "text/plain";
442 * Make sure that the attachment file exists and is readable. Append a mhbuild
443 * directive to the draft file. This starts with the content type. Append a
444 * file name attribute and a private x-unix-mode attribute. Also append a
445 * description obtained (if possible) by running the "file" command on the file.
448 if (stat(file_name, &st) == -1 || access(file_name, R_OK) != 0) {
449 clean_up_temporary_files();
450 adios((char *)0, "unable to access file \"%s\"", file_name);
453 switch (attachformat) {
455 /* Insert name, file mode, and Content-Id. */
456 (void)fprintf(composition_file, "#%s; name=\"%s\"; x-unix-mode=0%.3ho",
457 content_type, ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1, (unsigned short)(st.st_mode & 0777));
459 if (strlen(file_name) > MAXPATHLEN) {
460 clean_up_temporary_files();
461 adios((char *)0, "attachment file name `%s' too long.", file_name);
464 (void)sprintf(cmd, "file '%s'", file_name);
466 if ((fp = popen(cmd, "r")) != (FILE *)0 && fgets(cmd, sizeof (cmd), fp) != (char *)0) {
467 *strchr(cmd, '\n') = '\0';
470 * The output of the "file" command is of the form
474 * Strip off the "file:" and subsequent white space.
477 for (p = cmd; *p != '\0'; p++) {
479 for (p++; *p != '\0'; p++) {
488 /* Insert Content-Description. */
489 (void)fprintf(composition_file, " [ %s ]", p);
496 if (stringdex (m_maildir(invo_name), file_name) == 0) {
497 /* Content had been placed by send into a temp file.
498 Don't generate Content-Disposition header, because
499 it confuses Microsoft Outlook, Build 10.0.6626, at
501 (void) fprintf (composition_file, "#%s <>", content_type);
503 /* Suppress Content-Id, insert simple Content-Disposition. */
504 (void) fprintf (composition_file,
505 "#%s; name=\"%s\" <>{attachment}",
507 ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1);
512 if (stringdex (m_maildir(invo_name), file_name) == 0) {
513 /* Content had been placed by send into a temp file.
514 Don't generate Content-Disposition header, because
515 it confuses Microsoft Outlook, Build 10.0.6626, at
517 (void) fprintf (composition_file, "#%s <>", content_type);
519 /* Suppress Content-Id, insert Content-Disposition with
520 modification date. */
521 (void) fprintf (composition_file,
522 "#%s; name=\"%s\" <>{attachment; modification-date=\"%s\"}",
524 ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1,
525 dtime (&st.st_mtime, 0));
530 adios ((char *)0, "unsupported attachformat %d", attachformat);
534 * Finish up with the file name.
537 (void)fprintf(composition_file, " %s\n", file_name);
543 * Split large message into several messages of
544 * type "message/partial" and send them.
548 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
550 int compnum, nparts, partno, state, status;
553 char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
554 char subject[BUFSIZ];
555 char name[NAMESZ], partnum[BUFSIZ];
558 if ((in = fopen (drft, "r")) == NULL)
559 adios (drft, "unable to open for reading");
565 * Scan through the message and examine the various header fields,
566 * as well as locate the beginning of the message body.
568 for (compnum = 1, state = FLD;;) {
569 switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
576 * This header field is discarded.
578 if (!mh_strcasecmp (name, "Message-ID")) {
579 while (state == FLDPLUS)
580 state = m_getfld (state, name, buffer, sizeof(buffer), in);
581 } else if (uprf (name, XXX_FIELD_PRF)
582 || !mh_strcasecmp (name, VRSN_FIELD)
583 || !mh_strcasecmp (name, "Subject")
584 || !mh_strcasecmp (name, "Encrypted")) {
586 * These header fields are copied to the enclosed
587 * header of the first message in the collection
588 * of message/partials. For the "Subject" header
589 * field, we also record it, so that a modified
590 * version of it, can be copied to the header
591 * of each messsage/partial in the collection.
593 if (!mh_strcasecmp (name, "Subject")) {
596 strncpy (subject, buffer, BUFSIZ);
597 sublen = strlen (subject);
598 if (sublen > 0 && subject[sublen - 1] == '\n')
599 subject[sublen - 1] = '\0';
602 dp = add (concat (name, ":", buffer, NULL), dp);
603 while (state == FLDPLUS) {
604 state = m_getfld (state, name, buffer, sizeof(buffer), in);
605 dp = add (buffer, dp);
609 * These header fields are copied to the header of
610 * each message/partial in the collection.
612 cp = add (concat (name, ":", buffer, NULL), cp);
613 while (state == FLDPLUS) {
614 state = m_getfld (state, name, buffer, sizeof(buffer), in);
615 cp = add (buffer, cp);
619 if (state != FLDEOF) {
620 start = ftell (in) + 1;
632 adios (NULL, "message format error in component #%d", compnum);
635 adios (NULL, "getfld () returned %d", state);
641 adios (NULL, "headers missing from draft");
645 while (fgets (buffer, sizeof(buffer) - 1, in)) {
648 if ((pos += (len = strlen (buffer))) > CPERMSG) {
654 /* Only one part, nothing to split */
661 return sendaux (vec, vecp, drft, st);
665 printf ("Sending as %d Partial Messages\n", nparts);
670 vec[vecp++] = "-partno";
671 vec[vecp++] = partnum;
673 vec[vecp++] = "-queued";
676 snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
677 (int) getpid(), (long) clock, LocalName());
679 fseek (in, start, SEEK_SET);
680 for (partno = 1; partno <= nparts; partno++) {
684 char *cp = m_mktemp2(drft, invo_name, NULL, &out);
686 adios (drft, "unable to create temporary file for");
688 strncpy(tmpdrf, cp, sizeof(tmpdrf));
689 chmod (tmpdrf, 0600);
692 * Output the header fields
695 fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
696 fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
697 fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
698 fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
699 fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
702 * If this is the first in the collection, output the
703 * header fields we are encapsulating at the beginning
704 * of the body of the first message.
709 fprintf (out, "Message-ID: %s\n", msgid);
717 if (!fgets (buffer, sizeof(buffer) - 1, in)) {
718 if (partno == nparts)
720 adios (NULL, "premature eof");
723 if ((pos += (len = strlen (buffer))) > CPERMSG) {
724 fseek (in, -len, SEEK_CUR);
732 adios (tmpdrf, "error writing to");
736 if (!pushsw && verbsw) {
741 /* Pause here, if a delay is specified */
742 if (delay > 0 && 1 < partno && partno <= nparts) {
744 printf ("pausing %d seconds before sending part %d...\n",
748 sleep ((unsigned int) delay);
751 snprintf (partnum, sizeof(partnum), "%d", partno);
752 status = sendaux (vec, vecp, tmpdrf, st);
758 * This is so sendaux will only annotate
759 * the altmsg the first time it is called.
768 fclose (in); /* close the draft */
774 * Annotate original message, and
775 * call `postproc' to send message.
779 sendaux (char **vec, int vecp, char *drft, struct stat *st)
782 int i, status, fd, fd2;
783 char backup[BUFSIZ], buf[BUFSIZ];
785 fd = pushsw ? tmp_fd () : NOTOK;
790 if ((fd2 = tmp_fd ()) != NOTOK) {
791 vec[vecp++] = "-idanno";
792 snprintf (buf, sizeof(buf), "%d", fd2);
795 admonish (NULL, "unable to create file for annotation list");
798 if (distfile && distout (drft, distfile, backup) == NOTOK)
802 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
807 /* oops -- fork error */
808 adios ("fork", "unable to");
809 break; /* NOT REACHED */
813 * child process -- send it
815 * If fd is ok, then we are pushing and fd points to temp
816 * file, so capture anything on stdout and stderr there.
819 dup2 (fd, fileno (stdout));
820 dup2 (fd, fileno (stderr));
823 execvp (postproc, vec);
824 fprintf (stderr, "unable to exec ");
827 break; /* NOT REACHED */
831 * parent process -- wait for it
833 if ((status = pidwait(child_id, NOTOK)) == OK) {
834 if (annotext && fd2 != NOTOK)
838 * If postproc failed, and we have good fd (which means
839 * we pushed), then mail error message (and possibly the
840 * draft) back to the user.
846 advise (NULL, "message not delivered to anyone");
848 if (annotext && fd2 != NOTOK)
852 if (rename (backup, drft) == NOTOK)
853 advise (drft, "unable to rename %s to", backup);
864 * Mail error notification (and possibly a copy of the
865 * message) back to the user, using the mailproc
869 alert (char *file, int out)
875 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
880 /* oops -- fork error */
881 advise ("fork", "unable to");
884 /* child process -- send it */
885 SIGNAL (SIGHUP, SIG_IGN);
886 SIGNAL (SIGINT, SIG_IGN);
887 SIGNAL (SIGQUIT, SIG_IGN);
888 SIGNAL (SIGTERM, SIG_IGN);
890 if ((in = open (file, O_RDONLY)) == NOTOK) {
891 admonish (file, "unable to re-open");
893 lseek (out, (off_t) 0, SEEK_END);
894 strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
895 write (out, buf, strlen (buf));
896 strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
897 write (out, buf, strlen (buf));
898 cpydgst (in, out, file, "temporary file");
900 strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
901 write (out, buf, strlen (buf));
902 if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
903 admonish (buf, "unable to rename %s to", file);
906 lseek (out, (off_t) 0, SEEK_SET);
907 dup2 (out, fileno (stdin));
909 /* create subject for error notification */
910 snprintf (buf, sizeof(buf), "send failed on %s",
911 forwsw ? "enclosed draft" : file);
913 execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
914 "-subject", buf, NULL);
915 fprintf (stderr, "unable to exec ");
919 default: /* no waiting... */
931 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
932 if (tfile == NULL) return NOTOK;
936 advise (NULL, "temporary file %s selected", tfile);
938 if (unlink (tfile) == NOTOK)
939 advise (tfile, "unable to remove");
946 anno (int fd, struct stat *st)
950 static char *cwd = NULL;
954 (stat (altmsg, &st2) == NOTOK
955 || st->st_mtime != st2.st_mtime
956 || st->st_dev != st2.st_dev
957 || st->st_ino != st2.st_ino)) {
959 admonish (NULL, "$mhaltmsg mismatch");
963 child_id = debugsw ? NOTOK : fork ();
965 case NOTOK: /* oops */
968 "unable to fork, so doing annotations by hand...");
970 cwd = getcpy (pwd ());
973 /* block a few signals */
975 sigaddset (&set, SIGHUP);
976 sigaddset (&set, SIGINT);
977 sigaddset (&set, SIGQUIT);
978 sigaddset (&set, SIGTERM);
979 SIGPROCMASK (SIG_BLOCK, &set, &oset);
985 /* reset the signal mask */
986 SIGPROCMASK (SIG_SETMASK, &oset, &set);
991 default: /* no waiting... */
1001 int fd2, fd3, msgnum;
1002 char *cp, *folder, *maildir;
1003 char buffer[BUFSIZ], **ap;
1007 if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
1009 admonish (NULL, "$mhfolder not set");
1012 maildir = m_maildir (folder);
1013 if (chdir (maildir) == NOTOK) {
1015 admonish (maildir, "unable to change directory to");
1018 if (!(mp = folder_read (folder))) {
1020 admonish (NULL, "unable to read folder %s", folder);
1024 /* check for empty folder */
1025 if (mp->nummsg == 0) {
1027 admonish (NULL, "no messages in %s", folder);
1031 if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
1033 admonish (NULL, "$mhmessages not set");
1036 if (!debugsw /* MOBY HACK... */
1038 && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
1039 && (fd2 = dup (fileno (stderr))) != NOTOK) {
1040 dup2 (fd3, fileno (stderr));
1045 for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
1046 m_convert (mp, *ap);
1049 dup2 (fd2, fileno (stderr));
1050 if (mp->numsel == 0) {
1052 admonish (NULL, "no messages to annotate");
1056 lseek (fd, (off_t) 0, SEEK_SET);
1057 if ((fp = fdopen (fd, "r")) == NULL) {
1059 admonish (NULL, "unable to fdopen annotation list");
1063 while (fgets (buffer, sizeof(buffer), fp) != NULL)
1064 cp = add (buffer, cp);
1068 advise (NULL, "annotate%s with %s: \"%s\"",
1069 inplace ? " inplace" : "", annotext, cp);
1070 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1071 if (is_selected(mp, msgnum)) {
1073 advise (NULL, "annotate message %d", msgnum);
1074 annotate (m_name (msgnum), annotext, cp, inplace, 1, -2, 0);
1081 folder_free (mp); /* free folder/message structure */
1086 armed_done (int status)
1088 longjmp (env, status ? status : NOTOK);