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 */
35 char *annotext = NULL;
36 char *distfile = NULL;
40 /* name of temp file for body content */
41 static char body_file_name[MAXPATHLEN + 1];
42 /* name of mhbuild composition temporary file */
43 static char composition_file_name[MAXPATHLEN + 1];
44 static int field_size; /* size of header field buffer */
45 static char *field; /* header field buffer */
46 static FILE *draft_file; /* draft file pointer */
47 static FILE *body_file; /* body file pointer */
48 static FILE *composition_file; /* composition file pointer */
53 static int sendsbr(char **, int, char *, struct stat *, int);
54 static void armed_done(int) NORETURN;
55 static void alert(char *, int);
56 static int tmp_fd(void);
57 static void anno(struct stat *);
58 static void annoaux(void);
59 static int sendaux(char **, int, char *, struct stat *);
60 static int attach(char *);
61 static void clean_up_temporary_files(void);
62 static int get_line(void);
63 static void make_mime_composition_file_entry(char *);
66 static struct swit switches[] = {
68 { "alias aliasfile", 0 },
72 { "filter filterfile", 0 },
104 main(int argc, char **argv)
106 int msgp = 0, nfiles = 0, distsw = 0, vecp = 1;
109 char *cp, *maildir = NULL;
110 char buf[BUFSIZ], **ap, **argp, **arguments;
111 char *msgs[MAXARGS], *vec[MAXARGS];
112 char *files[MAXARGS];
119 setlocale(LC_ALL, "");
121 invo_name = mhbasename(argv[0]);
123 /* read user profile/context */
126 arguments = getarguments(invo_name, argc, argv, 1);
129 vec[vecp++] = "-library";
130 vec[vecp++] = getcpy(toabsdir("+"));
132 while ((cp = *argp++)) {
134 switch (smatch(++cp, switches)) {
136 ambigsw(cp, switches);
139 adios(NULL, "-%s unknown\n", cp);
142 snprintf(buf, sizeof(buf),
143 "%s [file] [switches]",
145 print_help(buf, switches, 1);
148 print_version(invo_name);
175 debugsw++; /* fall */
187 if (!(cp = *argp++) || *cp == '-') {
188 adios(NULL, "missing argument to %s",
197 files[nfiles++] = cp;
204 /* check for "Aliasfile:" profile entry */
205 if ((cp = context_find("Aliasfile"))) {
208 for (ap=brkstring(dp=getcpy(cp), " ", "\n"); ap && *ap; ap++) {
209 vec[vecp++] = "-alias";
210 vec[vecp++] = getcpy(etcpath(*ap));
214 if (!msgp && !nfiles) {
215 msgs[msgp++] = seq_cur;
217 maildir = toabsdir(draftfolder);
219 if (chdir(maildir) == NOTOK) {
220 adios(maildir, "unable to change directory to");
223 if (!(mp = folder_read(draftfolder))) {
224 adios(NULL, "unable to read draft folder %s", draftfolder);
226 if (mp->nummsg == 0) {
227 adios(NULL, "no messages in draft folder %s", draftfolder);
229 /* parse all the message ranges/sequences and set SELECTED */
230 for (msgnum = 0; msgnum < msgp; msgnum++) {
231 if (!m_convert(mp, msgs[msgnum])) {
237 for (msgp = 0, msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
238 if (is_selected(mp, msgnum)) {
239 files[nfiles++] = getcpy(m_name(msgnum));
240 unset_exists(mp, msgnum);
244 mp->msgflags |= SEQMOD;
247 if (!(cp = getenv("SIGNATURE")) || !*cp) {
248 if ((cp = context_find("signature")) && *cp) {
249 m_putenv("SIGNATURE", cp);
253 for (msgnum = 0; msgnum < nfiles; msgnum++) {
254 if (stat(files[msgnum], &st) == NOTOK) {
255 adios(files[msgnum], "unable to stat draft file");
259 if (!(annotext = getenv("mhannotate")) || !*annotext) {
262 if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
263 altmsg = NULL; /* used by dist interface - see below */
266 if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
267 vec[vecp++] = "-dist";
268 distfile = getcpy(m_mktemp2(altmsg, invo_name, NULL, NULL));
269 if (link(altmsg, distfile) == NOTOK) {
270 if (errno != EXDEV) {
271 adios(distfile, "unable to link %s to",
275 distfile = getcpy(m_mktemp2(NULL, invo_name,
277 if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
278 adios(altmsg, "unable to open");
281 if ((out = creat(distfile, (int)st2.st_mode & 0777)) ==
283 adios(distfile, "unable to write");
285 cpydata(in, out, altmsg, distfile);
293 if (!altmsg || stat(altmsg, &st) == NOTOK) {
302 vec[0] = mhbasename(postproc);
305 for (msgnum = 0; msgnum < nfiles; msgnum++) {
306 switch (sendsbr(vec, vecp, files[msgnum], &st, 1)) {
323 ** message sending back-end
326 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
330 char *original_draft;
331 char *p; /* string pointer for building file name */
334 ** Save the original name of the draft file. The name of the
335 ** draft file is changed to a temporary file containing the built
336 ** MIME message if there are attachments. We need the original
337 ** name so that it can be renamed after the message is sent.
339 original_draft = drft;
342 ** Convert the draft to a MIME message.
343 ** Use the mhbuild composition file for the draft if there was
344 ** a successful conversion because that now contains the MIME
345 ** message. A nice side effect of this is that it leaves the
346 ** original draft file untouched so that it can be retrieved
347 ** and modified if desired.
349 switch (attach(drft)) {
351 drft = composition_file_name;
362 switch (setjmp(env)) {
364 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
365 /* rename the original draft */
366 if (rename_drft && status == OK &&
367 rename(original_draft, strncpy(buffer,
368 m_backup(original_draft), sizeof(buffer)))
370 advise(buffer, "unable to rename %s to", drft);
385 ** Get rid of any temporary files that we created for attachments.
386 ** Also get rid of the renamed composition file that mhbuild
387 ** leaves as a turd. It looks confusing, but we use the body
388 ** file name to help build the renamed composition file name.
390 if (drft == composition_file_name) {
391 clean_up_temporary_files();
393 if (strlen(composition_file_name) >=
394 sizeof (composition_file_name) - 6) {
395 advise(NULL, "unable to remove original composition file.");
397 if (!(p = strrchr(composition_file_name, '/'))) {
398 p = composition_file_name;
402 strcpy(body_file_name, p);
404 strcpy(p, body_file_name);
407 unlink(composition_file_name);
415 attach(char *draft_file_name)
417 char buf[MAXPATHLEN + 6];
421 int non_ascii; /* msg body contains non-ASCII chars */
422 int length; /* length of attachment header field name */
425 if (!(draft_file = fopen(draft_file_name, "r"))) {
426 adios(NULL, "can't open draft file `%s'.", draft_file_name);
429 /* We'll grow the buffer as needed. */
430 field = (char *)mh_xmalloc(field_size = 256);
433 ** Scan the draft file for an attachment header field name.
435 length = strlen(attach_hdr);
437 while (get_line() != EOF && *field != '\0' && *field != '-') {
438 if (strncasecmp(field, attach_hdr, length)==0 &&
439 field[length] == ':') {
445 ** Look for at least one non-blank line in the body of the
446 ** message which indicates content in the body.
447 ** Check if body contains at least one non-blank (= not empty)
448 ** and if it contains any non-ASCII chars (= need MIME).
452 while (get_line() != EOF) {
453 for (p = field; *p != '\0'; p++) {
454 if (*p != ' ' && *p != '\t') {
457 if (*p > 127 || *p < 0) {
461 if (has_body && non_ascii) {
462 break; /* that's been already enough information */
466 if (!has_attachment && non_ascii==0) {
467 /* We don't need to convert it to MIME. */
475 /* Make names for the temporary files. */
476 strncpy(body_file_name,
477 m_mktemp(toabsdir(invo_name), NULL, NULL),
478 sizeof (body_file_name));
479 strncpy(composition_file_name,
480 m_mktemp(toabsdir(invo_name), NULL, NULL),
481 sizeof (composition_file_name));
484 body_file = fopen(body_file_name, "w");
486 composition_file = fopen(composition_file_name, "w");
488 if ((has_body && !body_file) || !composition_file) {
489 clean_up_temporary_files();
490 adios(NULL, "unable to open all of the temporary files.");
493 /* Copy non-attachment header fields to the temp composition file. */
495 while (get_line() != EOF && *field && *field != '-') {
496 if (strncasecmp(field, attach_hdr, length) != 0 ||
497 field[length] != ':') {
498 fprintf(composition_file, "%s\n", field);
501 fputs("--------\n", composition_file);
504 /* Copy the message body to the temporary file. */
505 while ((c = getc(draft_file)) != EOF) {
510 /* Add a mhbuild MIME composition file line for the body */
511 /* charset will be discovered/guessed by buildmimeproc */
512 fprintf(composition_file, "#text/plain %s\n", body_file_name);
516 ** Now, go back to the beginning of the draft file and look for
517 ** header fields that specify attachments. Add a mhbuild MIME
518 ** composition file for each.
521 while (get_line() != EOF && *field && *field != '-') {
522 if (strncasecmp(field, attach_hdr, length) == 0 &&
523 field[length] == ':') {
524 for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
528 /* forwarded message */
529 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
531 /* regular attachment */
532 make_mime_composition_file_entry(p);
536 fclose(composition_file);
539 ** We're ready to roll! Run mhbuild on the composition file.
540 ** Note that mhbuild is in the context as buildmimeproc.
542 sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
544 if (system(buf) != 0) {
546 clean_up_temporary_files();
554 clean_up_temporary_files(void)
556 unlink(body_file_name);
557 unlink(composition_file_name);
565 int c; /* current character */
566 int n; /* number of bytes in buffer */
570 ** Get a line from the input file, growing the field buffer as
571 ** needed. We do this so that we can fit an entire line in the
572 ** buffer making it easy to do a string comparison on both the
573 ** field name and the field body which might be a long path name.
575 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
576 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
577 ungetc(c, draft_file);
581 if (++n >= field_size - 1) {
582 field = (char *)mh_xrealloc(field, field_size += 256);
592 make_mime_composition_file_entry(char *file_name)
597 char content_type[BUFSIZ];
599 char *cmd = mimetypequeryproc;
601 for (np = m_defs; np; np = np->n_next) {
602 if (strcasecmp(np->n_name, mimetypequery)==0) {
607 snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
609 if (!(fp = popen(cmdbuf, "r"))) {
610 clean_up_temporary_files();
611 adios(NULL, "unable to determine content type with `%s'",
614 if (fgets(content_type, sizeof content_type, fp) &&
615 (cp = strrchr(content_type, '\n'))) {
618 strcpy(content_type, "application/octet-stream");
619 admonish(NULL, "problems with `%s', using fall back type `%s'",
620 cmdbuf, content_type);
624 /* TODO: don't use access(2) because it checks for ruid, not euid */
625 if (access(file_name, R_OK) != 0) {
626 clean_up_temporary_files();
627 adios(NULL, "unable to access file `%s'", file_name);
630 fprintf(composition_file, "#%s; name=\"%s\" <>{attachment}",
632 (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1);
634 fprintf(composition_file, " %s\n", file_name);
640 ** The back-end of the message sending back-end.
641 ** Annotate original message, and call `postproc' to send message.
644 sendaux(char **vec, int vecp, char *drft, struct stat *st)
651 ** fd collects the output of postproc, and is used for the
652 ** failure notice if we need to send one in alert().
654 fd = pushsw ? tmp_fd() : NOTOK;
657 if (distfile && distout(drft, distfile, backup) == NOTOK) {
662 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++) {
667 /* oops -- fork error */
668 adios("fork", "unable to");
669 break; /* NOT REACHED */
673 ** child process -- send it
675 ** If fd is ok, then we are pushing and fd points to temp
676 ** file, so capture anything on stdout and stderr there.
679 dup2(fd, fileno(stdout));
680 dup2(fd, fileno(stderr));
683 execvp(postproc, vec);
684 fprintf(stderr, "unable to exec ");
687 break; /* NOT REACHED */
690 /* parent process -- wait for it */
691 if ((status = pidwait(child_id, NOTOK)) == OK) {
697 ** If postproc failed, and we have good fd (which
698 ** means we pushed), then mail error message
699 ** (and possibly the draft) back to the user.
705 advise(NULL, "message not delivered to anyone");
709 if (rename(backup, drft) == NOTOK) {
710 advise(drft, "unable to rename %s to",
723 ** Mail error notification (and possibly a copy of the
724 ** message) back to the user, using the mailproc
727 alert(char *file, int out)
733 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++) {
739 /* oops -- fork error */
740 advise("fork", "unable to");
743 /* child process -- send it */
744 SIGNAL(SIGHUP, SIG_IGN);
745 SIGNAL(SIGINT, SIG_IGN);
746 SIGNAL(SIGQUIT, SIG_IGN);
747 SIGNAL(SIGTERM, SIG_IGN);
749 if ((in = open(file, O_RDONLY)) == NOTOK) {
750 admonish(file, "unable to re-open");
752 lseek(out, (off_t) 0, SEEK_END);
753 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
754 write(out, buf, strlen(buf));
755 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
756 write(out, buf, strlen(buf));
757 cpydgst(in, out, file, "temporary file");
759 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
760 write(out, buf, strlen(buf));
761 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK) {
762 admonish(buf, "unable to rename %s to", file);
766 lseek(out, (off_t) 0, SEEK_SET);
767 dup2(out, fileno(stdin));
769 /* create subject for error notification */
770 snprintf(buf, sizeof(buf), "send failed on %s",
771 forwsw ? "enclosed draft" : file);
773 execlp(mailproc, mhbasename(mailproc), getusername(),
774 "-subject", buf, NULL);
775 fprintf(stderr, "unable to exec ");
779 default: /* no waiting... */
791 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
792 if (tfile == NULL) return NOTOK;
796 advise(NULL, "temporary file %s selected", tfile);
798 if (unlink(tfile) == NOTOK) {
799 advise(tfile, "unable to remove");
808 anno(struct stat *st)
812 static char *cwd = NULL;
815 if (altmsg && (stat(altmsg, &st2) == NOTOK ||
816 st->st_mtime != st2.st_mtime ||
817 st->st_dev != st2.st_dev ||
818 st->st_ino != st2.st_ino)) {
820 admonish(NULL, "$mhaltmsg mismatch");
825 child_id = debugsw ? NOTOK : fork();
827 case NOTOK: /* oops */
829 advise(NULL, "unable to fork, so doing annotations by hand...");
837 /* block a few signals */
839 sigaddset(&set, SIGHUP);
840 sigaddset(&set, SIGINT);
841 sigaddset(&set, SIGQUIT);
842 sigaddset(&set, SIGTERM);
843 SIGPROCMASK(SIG_BLOCK, &set, &oset);
846 if (child_id == OK) {
850 /* reset the signal mask */
851 SIGPROCMASK(SIG_SETMASK, &oset, &set);
856 default: /* no waiting... */
865 int fd2, fd3, msgnum;
866 char *cp, *folder, *maildir;
870 if (!(folder = getenv("mhfolder")) || !*folder) {
872 admonish(NULL, "$mhfolder not set");
876 maildir = toabsdir(folder);
877 if (chdir(maildir) == NOTOK) {
879 admonish(maildir, "unable to change directory to");
883 if (!(mp = folder_read(folder))) {
885 admonish(NULL, "unable to read folder %s", folder);
890 if (mp->nummsg == 0) {
892 admonish(NULL, "no messages in %s", folder);
896 if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
898 admonish(NULL, "$mhmessages not set");
902 if (!debugsw /* MOBY HACK... */
904 && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
905 && (fd2 = dup(fileno(stderr))) != NOTOK) {
906 dup2(fd3, fileno(stderr));
911 for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++) {
916 dup2(fd2, fileno(stderr));
918 if (mp->numsel == 0) {
920 admonish(NULL, "no messages to annotate");
926 advise(NULL, "annotate as `%s'", annotext);
928 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
929 if (is_selected(mp, msgnum)) {
931 advise(NULL, "annotate message %d", msgnum);
933 annotate(m_name(msgnum), annotext, NULL, 1, -2, 0);
943 armed_done(int status)
945 longjmp(env, status ? status : NOTOK);