2 ** send.c -- send a composed message
4 ** This code is Copyright (c) 2002, by the authors of nmh. See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** 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 */
36 char *annotext = NULL;
37 char *distfile = NULL;
41 /* name of temp file for body content */
42 static char body_file_name[MAXPATHLEN + 1];
43 /* name of mhbuild composition temporary file */
44 static char composition_file_name[MAXPATHLEN + 1];
45 static int field_size; /* size of header field buffer */
46 static char *field; /* header field buffer */
47 static FILE *draft_file; /* draft file pointer */
48 static FILE *body_file; /* body file pointer */
49 static FILE *composition_file; /* composition file pointer */
54 static int sendsbr(char **, int, char *, struct stat *, int);
55 static void armed_done(int) NORETURN;
56 static void alert(char *, int);
57 static int tmp_fd(void);
58 static void anno(int, struct stat *);
59 static void annoaux(int);
60 static int sendaux(char **, int, char *, struct stat *);
61 static int attach(char *);
62 static void clean_up_temporary_files(void);
63 static int get_line(void);
64 static void make_mime_composition_file_entry(char *);
67 static struct swit switches[] = {
69 { "alias aliasfile", 0 },
73 { "filter filterfile", 0 },
105 main(int argc, char **argv)
107 int msgp = 0, nfiles = 0, distsw = 0, vecp = 1;
110 char *cp, *maildir = NULL;
111 char buf[BUFSIZ], **ap, **argp, **arguments;
112 char *msgs[MAXARGS], *vec[MAXARGS];
113 char *files[MAXARGS];
120 setlocale(LC_ALL, "");
122 invo_name = mhbasename(argv[0]);
124 /* read user profile/context */
127 arguments = getarguments(invo_name, argc, argv, 1);
130 vec[vecp++] = "-library";
131 vec[vecp++] = getcpy(toabsdir("+"));
133 while ((cp = *argp++)) {
135 switch (smatch(++cp, switches)) {
137 ambigsw(cp, switches);
140 adios(NULL, "-%s unknown\n", cp);
143 snprintf(buf, sizeof(buf),
144 "%s [file] [switches]",
146 print_help(buf, switches, 1);
149 print_version(invo_name);
176 debugsw++; /* fall */
188 if (!(cp = *argp++) || *cp == '-') {
189 adios(NULL, "missing argument to %s",
198 files[nfiles++] = cp;
205 /* check for "Aliasfile:" profile entry */
206 if ((cp = context_find("Aliasfile"))) {
209 for (ap=brkstring(dp=getcpy(cp), " ", "\n"); ap && *ap; ap++) {
210 vec[vecp++] = "-alias";
211 vec[vecp++] = getcpy(etcpath(*ap));
215 if (!msgp && !nfiles) {
216 msgs[msgp++] = seq_cur;
218 maildir = toabsdir(draftfolder);
220 if (chdir(maildir) == NOTOK) {
221 adios(maildir, "unable to change directory to");
224 if (!(mp = folder_read(draftfolder))) {
225 adios(NULL, "unable to read draft folder %s", draftfolder);
227 if (mp->nummsg == 0) {
228 adios(NULL, "no messages in draft folder %s", draftfolder);
230 /* parse all the message ranges/sequences and set SELECTED */
231 for (msgnum = 0; msgnum < msgp; msgnum++) {
232 if (!m_convert(mp, msgs[msgnum])) {
238 for (msgp = 0, msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
239 if (is_selected(mp, msgnum)) {
240 files[nfiles++] = getcpy(m_name(msgnum));
241 unset_exists(mp, msgnum);
245 mp->msgflags |= SEQMOD;
248 if (!(cp = getenv("SIGNATURE")) || !*cp) {
249 if ((cp = context_find("signature")) && *cp) {
250 m_putenv("SIGNATURE", cp);
254 for (msgnum = 0; msgnum < nfiles; msgnum++) {
255 if (stat(files[msgnum], &st) == NOTOK) {
256 adios(files[msgnum], "unable to stat draft file");
260 if (!(annotext = getenv("mhannotate")) || !*annotext) {
263 if (annotext && ((cp = getenv("mhinplace")) && *cp)) {
266 if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
267 altmsg = NULL; /* used by dist interface - see below */
270 if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
271 vec[vecp++] = "-dist";
272 distfile = getcpy(m_mktemp2(altmsg, invo_name, NULL, NULL));
273 if (link(altmsg, distfile) == NOTOK) {
274 if (errno != EXDEV) {
275 adios(distfile, "unable to link %s to",
279 distfile = getcpy(m_mktemp2(NULL, invo_name,
281 if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
282 adios(altmsg, "unable to open");
285 if ((out = creat(distfile, (int)st2.st_mode & 0777)) ==
287 adios(distfile, "unable to write");
289 cpydata(in, out, altmsg, distfile);
297 if (!altmsg || stat(altmsg, &st) == NOTOK) {
306 vec[0] = mhbasename(postproc);
309 for (msgnum = 0; msgnum < nfiles; msgnum++) {
310 switch (sendsbr(vec, vecp, files[msgnum], &st, 1)) {
327 ** message sending back-end
330 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
334 char *original_draft;
335 char *p; /* string pointer for building file name */
338 ** Save the original name of the draft file. The name of the
339 ** draft file is changed to a temporary file containing the built
340 ** MIME message if there are attachments. We need the original
341 ** name so that it can be renamed after the message is sent.
343 original_draft = drft;
346 ** Convert the draft to a MIME message.
347 ** Use the mhbuild composition file for the draft if there was
348 ** a successful conversion because that now contains the MIME
349 ** message. A nice side effect of this is that it leaves the
350 ** original draft file untouched so that it can be retrieved
351 ** and modified if desired.
353 switch (attach(drft)) {
355 drft = composition_file_name;
366 switch (setjmp(env)) {
368 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
369 /* rename the original draft */
370 if (rename_drft && status == OK &&
371 rename(original_draft, strncpy(buffer,
372 m_backup(original_draft), sizeof(buffer)))
374 advise(buffer, "unable to rename %s to", drft);
389 ** Get rid of any temporary files that we created for attachments.
390 ** Also get rid of the renamed composition file that mhbuild
391 ** leaves as a turd. It looks confusing, but we use the body
392 ** file name to help build the renamed composition file name.
394 if (drft == composition_file_name) {
395 clean_up_temporary_files();
397 if (strlen(composition_file_name) >=
398 sizeof (composition_file_name) - 6) {
399 advise(NULL, "unable to remove original composition file.");
401 if (!(p = strrchr(composition_file_name, '/'))) {
402 p = composition_file_name;
406 strcpy(body_file_name, p);
408 strcpy(p, body_file_name);
411 unlink(composition_file_name);
419 attach(char *draft_file_name)
421 char buf[MAXPATHLEN + 6];
425 int non_ascii; /* msg body contains non-ASCII chars */
426 int length; /* length of attachment header field name */
429 if (!(draft_file = fopen(draft_file_name, "r"))) {
430 adios(NULL, "can't open draft file `%s'.", draft_file_name);
433 /* We'll grow the buffer as needed. */
434 field = (char *)mh_xmalloc(field_size = 256);
437 ** Scan the draft file for an attachment header field name.
439 length = strlen(attach_hdr);
441 while (get_line() != EOF && *field != '\0' && *field != '-') {
442 if (strncasecmp(field, attach_hdr, length)==0 &&
443 field[length] == ':') {
449 ** Look for at least one non-blank line in the body of the
450 ** message which indicates content in the body.
451 ** Check if body contains at least one non-blank (= not empty)
452 ** and if it contains any non-ASCII chars (= need MIME).
456 while (get_line() != EOF) {
457 for (p = field; *p != '\0'; p++) {
458 if (*p != ' ' && *p != '\t') {
461 if (*p > 127 || *p < 0) {
465 if (has_body && non_ascii) {
466 break; /* that's been already enough information */
470 if (!has_attachment && non_ascii==0) {
471 /* We don't need to convert it to MIME. */
479 /* Make names for the temporary files. */
480 strncpy(body_file_name,
481 m_mktemp(toabsdir(invo_name), NULL, NULL),
482 sizeof (body_file_name));
483 strncpy(composition_file_name,
484 m_mktemp(toabsdir(invo_name), NULL, NULL),
485 sizeof (composition_file_name));
488 body_file = fopen(body_file_name, "w");
490 composition_file = fopen(composition_file_name, "w");
492 if ((has_body && !body_file) || !composition_file) {
493 clean_up_temporary_files();
494 adios(NULL, "unable to open all of the temporary files.");
497 /* Copy non-attachment header fields to the temp composition file. */
499 while (get_line() != EOF && *field && *field != '-') {
500 if (strncasecmp(field, attach_hdr, length) != 0 ||
501 field[length] != ':') {
502 fprintf(composition_file, "%s\n", field);
505 fputs("--------\n", composition_file);
508 /* Copy the message body to the temporary file. */
509 while ((c = getc(draft_file)) != EOF) {
514 /* Add a mhbuild MIME composition file line for the body */
515 /* charset will be discovered/guessed by buildmimeproc */
516 fprintf(composition_file, "#text/plain %s\n", body_file_name);
520 ** Now, go back to the beginning of the draft file and look for
521 ** header fields that specify attachments. Add a mhbuild MIME
522 ** composition file for each.
525 while (get_line() != EOF && *field && *field != '-') {
526 if (strncasecmp(field, attach_hdr, length) == 0 &&
527 field[length] == ':') {
528 for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
532 /* forwarded message */
533 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
535 /* regular attachment */
536 make_mime_composition_file_entry(p);
540 fclose(composition_file);
543 ** We're ready to roll! Run mhbuild on the composition file.
544 ** Note that mhbuild is in the context as buildmimeproc.
546 sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
548 if (system(buf) != 0) {
550 clean_up_temporary_files();
558 clean_up_temporary_files(void)
560 unlink(body_file_name);
561 unlink(composition_file_name);
569 int c; /* current character */
570 int n; /* number of bytes in buffer */
574 ** Get a line from the input file, growing the field buffer as
575 ** needed. We do this so that we can fit an entire line in the
576 ** buffer making it easy to do a string comparison on both the
577 ** field name and the field body which might be a long path name.
579 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
580 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
581 ungetc(c, draft_file);
585 if (++n >= field_size - 1) {
586 field = (char *)mh_xrealloc(field, field_size += 256);
596 make_mime_composition_file_entry(char *file_name)
601 char content_type[BUFSIZ];
603 char *cmd = mimetypequeryproc;
605 for (np = m_defs; np; np = np->n_next) {
606 if (strcasecmp(np->n_name, mimetypequery)==0) {
611 snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
613 if (!(fp = popen(cmdbuf, "r"))) {
614 clean_up_temporary_files();
615 adios(NULL, "unable to determine content type with `%s'",
618 if (fgets(content_type, sizeof content_type, fp) &&
619 (cp = strrchr(content_type, '\n'))) {
622 strcpy(content_type, "application/octet-stream");
623 admonish(NULL, "problems with `%s', using fall back type `%s'",
624 cmdbuf, content_type);
628 /* TODO: don't use access(2) because it checks for ruid, not euid */
629 if (access(file_name, R_OK) != 0) {
630 clean_up_temporary_files();
631 adios(NULL, "unable to access file `%s'", file_name);
634 fprintf(composition_file, "#%s; name=\"%s\" <>{attachment}",
636 (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1);
638 fprintf(composition_file, " %s\n", file_name);
644 ** The back-end of the message sending back-end.
645 ** Annotate original message, and call `postproc' to send message.
648 sendaux(char **vec, int vecp, char *drft, struct stat *st)
651 int i, status, fd, fd2;
654 fd = pushsw ? tmp_fd() : NOTOK;
658 if (annotext && (fd2 = tmp_fd()) == NOTOK) {
659 admonish(NULL, "unable to create file for annotation list");
661 if (distfile && distout(drft, distfile, backup) == NOTOK) {
666 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++) {
672 /* oops -- fork error */
673 adios("fork", "unable to");
674 break; /* NOT REACHED */
678 ** child process -- send it
680 ** If fd is ok, then we are pushing and fd points to temp
681 ** file, so capture anything on stdout and stderr there.
684 dup2(fd, fileno(stdout));
685 dup2(fd, fileno(stderr));
688 execvp(postproc, vec);
689 fprintf(stderr, "unable to exec ");
692 break; /* NOT REACHED */
695 /* parent process -- wait for it */
696 if ((status = pidwait(child_id, NOTOK)) == OK) {
697 if (annotext && fd2 != NOTOK)
701 ** If postproc failed, and we have good fd (which
702 ** means we pushed), then mail error message
703 ** (and possibly the draft) back to the user.
709 advise(NULL, "message not delivered to anyone");
711 if (annotext && fd2 != NOTOK) {
716 if (rename(backup, drft) == NOTOK) {
717 advise(drft, "unable to rename %s to",
730 ** Mail error notification (and possibly a copy of the
731 ** message) back to the user, using the mailproc
734 alert(char *file, int out)
740 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++) {
746 /* oops -- fork error */
747 advise("fork", "unable to");
750 /* child process -- send it */
751 SIGNAL(SIGHUP, SIG_IGN);
752 SIGNAL(SIGINT, SIG_IGN);
753 SIGNAL(SIGQUIT, SIG_IGN);
754 SIGNAL(SIGTERM, SIG_IGN);
756 if ((in = open(file, O_RDONLY)) == NOTOK) {
757 admonish(file, "unable to re-open");
759 lseek(out, (off_t) 0, SEEK_END);
760 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
761 write(out, buf, strlen(buf));
762 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
763 write(out, buf, strlen(buf));
764 cpydgst(in, out, file, "temporary file");
766 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
767 write(out, buf, strlen(buf));
768 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK) {
769 admonish(buf, "unable to rename %s to", file);
773 lseek(out, (off_t) 0, SEEK_SET);
774 dup2(out, fileno(stdin));
776 /* create subject for error notification */
777 snprintf(buf, sizeof(buf), "send failed on %s",
778 forwsw ? "enclosed draft" : file);
780 execlp(mailproc, mhbasename(mailproc), getusername(),
781 "-subject", buf, NULL);
782 fprintf(stderr, "unable to exec ");
786 default: /* no waiting... */
798 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
799 if (tfile == NULL) return NOTOK;
803 advise(NULL, "temporary file %s selected", tfile);
805 if (unlink(tfile) == NOTOK) {
806 advise(tfile, "unable to remove");
815 anno(int fd, struct stat *st)
819 static char *cwd = NULL;
822 if (altmsg && (stat(altmsg, &st2) == NOTOK ||
823 st->st_mtime != st2.st_mtime ||
824 st->st_dev != st2.st_dev ||
825 st->st_ino != st2.st_ino)) {
827 admonish(NULL, "$mhaltmsg mismatch");
832 child_id = debugsw ? NOTOK : fork();
834 case NOTOK: /* oops */
836 advise(NULL, "unable to fork, so doing annotations by hand...");
844 /* block a few signals */
846 sigaddset(&set, SIGHUP);
847 sigaddset(&set, SIGINT);
848 sigaddset(&set, SIGQUIT);
849 sigaddset(&set, SIGTERM);
850 SIGPROCMASK(SIG_BLOCK, &set, &oset);
853 if (child_id == OK) {
857 /* reset the signal mask */
858 SIGPROCMASK(SIG_SETMASK, &oset, &set);
863 default: /* no waiting... */
873 int fd2, fd3, msgnum;
874 char *cp, *folder, *maildir;
875 char buffer[BUFSIZ], **ap;
879 if (!(folder = getenv("mhfolder")) || !*folder) {
881 admonish(NULL, "$mhfolder not set");
885 maildir = toabsdir(folder);
886 if (chdir(maildir) == NOTOK) {
888 admonish(maildir, "unable to change directory to");
892 if (!(mp = folder_read(folder))) {
894 admonish(NULL, "unable to read folder %s", folder);
899 if (mp->nummsg == 0) {
901 admonish(NULL, "no messages in %s", folder);
905 if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
907 admonish(NULL, "$mhmessages not set");
911 if (!debugsw /* MOBY HACK... */
913 && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
914 && (fd2 = dup(fileno(stderr))) != NOTOK) {
915 dup2(fd3, fileno(stderr));
920 for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++) {
925 dup2(fd2, fileno(stderr));
927 if (mp->numsel == 0) {
929 admonish(NULL, "no messages to annotate");
934 lseek(fd, (off_t) 0, SEEK_SET);
935 if ((fp = fdopen(fd, "r")) == NULL) {
937 admonish(NULL, "unable to fdopen annotation list");
942 while (fgets(buffer, sizeof(buffer), fp) != NULL) {
943 cp = add(buffer, cp);
948 advise(NULL, "annotate%s with %s: \"%s\"",
949 inplace ? " inplace" : "", annotext, cp);
951 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
952 if (is_selected(mp, msgnum)) {
954 advise(NULL, "annotate message %d", msgnum);
956 annotate(m_name(msgnum), annotext, cp, inplace,
968 armed_done(int status)
970 longjmp(env, status ? status : NOTOK);