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 HAVE_SYS_TIME_H
20 # include <sys/time.h>
24 int debugsw = 0; /* global */
29 char *annotext = NULL;
30 char *distfile = NULL;
34 /* name of temp file for body content */
35 static char body_file_name[MAXPATHLEN + 1];
36 /* name of mhbuild composition temporary file */
37 static char composition_file_name[MAXPATHLEN + 1];
38 static int field_size; /* size of header field buffer */
39 static char *field; /* header field buffer */
40 static FILE *draft_file; /* draft file pointer */
41 static FILE *body_file; /* body file pointer */
42 static FILE *composition_file; /* composition file pointer */
47 static int sendsbr(char **, int, char *, struct stat *, int);
48 static void armed_done(int) NORETURN;
49 static void alert(char *, int);
50 static int tmp_fd(void);
51 static void anno(struct stat *);
52 static int sendaux(char **, int, char *, struct stat *);
53 static int attach(char *);
54 static void clean_up_temporary_files(void);
55 static int get_line(void);
56 static void make_mime_composition_file_entry(char *);
59 static struct swit switches[] = {
61 { "alias aliasfile", 0 },
89 main(int argc, char **argv)
91 int msgp = 0, nfiles = 0, distsw = 0, vecp = 1;
95 char *cp, *maildir = NULL;
96 char buf[BUFSIZ], **ap, **argp, **arguments;
97 char *msgs[MAXARGS], *vec[MAXARGS];
105 setlocale(LC_ALL, "");
107 invo_name = mhbasename(argv[0]);
109 /* read user profile/context */
112 arguments = getarguments(invo_name, argc, argv, 1);
115 vec[vecp++] = "-library";
116 vec[vecp++] = getcpy(toabsdir("+"));
118 while ((cp = *argp++)) {
120 switch (smatch(++cp, switches)) {
122 ambigsw(cp, switches);
125 adios(NULL, "-%s unknown\n", cp);
128 snprintf(buf, sizeof(buf),
129 "%s [file] [switches]",
131 print_help(buf, switches, 1);
134 print_version(invo_name);
161 debugsw++; /* fall */
169 if (!(cp = *argp++) || *cp == '-') {
170 adios(NULL, "missing argument to %s",
179 files[nfiles++] = cp;
186 /* check for "Aliasfile:" profile entry */
187 if ((cp = context_find("Aliasfile"))) {
190 for (ap=brkstring(dp=getcpy(cp), " ", "\n"); ap && *ap; ap++) {
191 vec[vecp++] = "-alias";
192 vec[vecp++] = getcpy(etcpath(*ap));
196 if (!msgp && !nfiles) {
197 msgs[msgp++] = seq_cur;
199 maildir = toabsdir(draftfolder);
201 if (chdir(maildir) == NOTOK) {
202 adios(maildir, "unable to change directory to");
205 if (!(mp = folder_read(draftfolder))) {
206 adios(NULL, "unable to read draft folder %s", draftfolder);
208 if (mp->nummsg == 0) {
209 adios(NULL, "no messages in draft folder %s", draftfolder);
211 /* parse all the message ranges/sequences and set SELECTED */
212 for (msgnum = 0; msgnum < msgp; msgnum++) {
213 if (!m_convert(mp, msgs[msgnum])) {
219 for (msgp = 0, msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
220 if (is_selected(mp, msgnum)) {
221 files[nfiles++] = getcpy(m_name(msgnum));
222 unset_exists(mp, msgnum);
226 mp->msgflags |= SEQMOD;
229 if (!(cp = getenv("SIGNATURE")) || !*cp) {
230 if ((cp = context_find("signature")) && *cp) {
231 m_putenv("SIGNATURE", cp);
235 for (msgnum = 0; msgnum < nfiles; msgnum++) {
236 if (stat(files[msgnum], &st) == NOTOK) {
237 adios(files[msgnum], "unable to stat draft file");
241 if (!(annotext = getenv("mhannotate")) || !*annotext) {
244 if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
245 altmsg = NULL; /* used by dist interface - see below */
248 if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
249 vec[vecp++] = "-dist";
250 if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
251 adios(altmsg, "unable to open for reading");
254 distfile = getcpy(m_mktemp2(NULL, invo_name, NULL, NULL));
255 if ((out = creat(distfile, (int)st2.st_mode & 0777))==NOTOK) {
256 adios(distfile, "unable to open for writing");
258 cpydata(in, out, altmsg, distfile);
265 if (!altmsg || stat(altmsg, &st) == NOTOK) {
271 /* push a fork into the background */
274 switch (pid = fork()) {
277 advise(NULL, "unable to fork, so can't push...");
281 /* parent, just exit */
285 /* child, block a few signals and continue */
286 SIGNAL(SIGHUP, SIG_IGN);
287 SIGNAL(SIGINT, SIG_IGN);
288 SIGNAL(SIGQUIT, SIG_IGN);
289 SIGNAL(SIGTERM, SIG_IGN);
291 SIGNAL(SIGTSTP, SIG_IGN);
292 SIGNAL(SIGTTIN, SIG_IGN);
293 SIGNAL(SIGTTOU, SIG_IGN);
295 freopen("/dev/null", "r", stdin);
296 freopen("/dev/null", "w", stdout);
302 for (n=3; n<OPEN_MAX; n++) {
306 for (msgnum = 0; msgnum < nfiles; msgnum++) {
307 switch (sendsbr(vec, vecp, files[msgnum], &st, 1)) {
324 ** message sending back-end
327 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
331 char *original_draft;
332 char *p; /* string pointer for building file name */
335 ** Save the original name of the draft file. The name of the
336 ** draft file is changed to a temporary file containing the built
337 ** MIME message if there are attachments. We need the original
338 ** name so that it can be renamed after the message is sent.
340 original_draft = drft;
343 ** Convert the draft to a MIME message.
344 ** Use the mhbuild composition file for the draft if there was
345 ** a successful conversion because that now contains the MIME
346 ** message. A nice side effect of this is that it leaves the
347 ** original draft file untouched so that it can be retrieved
348 ** and modified if desired.
350 switch (attach(drft)) {
352 drft = composition_file_name;
363 switch (setjmp(env)) {
365 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
366 /* rename the original draft */
367 if (rename_drft && status == OK &&
368 rename(original_draft, strncpy(buffer,
369 m_backup(original_draft), sizeof(buffer)))
371 advise(buffer, "unable to rename %s to", drft);
386 ** Get rid of any temporary files that we created for attachments.
387 ** Also get rid of the renamed composition file that mhbuild
388 ** leaves as a turd. It looks confusing, but we use the body
389 ** file name to help build the renamed composition file name.
391 if (drft == composition_file_name) {
392 clean_up_temporary_files();
394 if (strlen(composition_file_name) >=
395 sizeof (composition_file_name) - 6) {
396 advise(NULL, "unable to remove original composition file.");
398 if (!(p = strrchr(composition_file_name, '/'))) {
399 p = composition_file_name;
403 strcpy(body_file_name, p);
405 strcpy(p, body_file_name);
408 unlink(composition_file_name);
416 attach(char *draft_file_name)
418 char buf[MAXPATHLEN + 6];
422 int non_ascii; /* msg body contains non-ASCII chars */
423 int length; /* length of attachment header field name */
426 if (!(draft_file = fopen(draft_file_name, "r"))) {
427 adios(NULL, "can't open draft file `%s'.", draft_file_name);
430 /* We'll grow the buffer as needed. */
431 field = (char *)mh_xmalloc(field_size = 256);
434 ** Scan the draft file for an attachment header field name.
436 length = strlen(attach_hdr);
438 while (get_line() != EOF && *field != '\0' && *field != '-') {
439 if (strncasecmp(field, attach_hdr, length)==0 &&
440 field[length] == ':') {
446 ** Look for at least one non-blank line in the body of the
447 ** message which indicates content in the body.
448 ** Check if body contains at least one non-blank (= not empty)
449 ** and if it contains any non-ASCII chars (= need MIME).
453 while (get_line() != EOF) {
454 for (p = field; *p != '\0'; p++) {
455 if (*p != ' ' && *p != '\t') {
458 if (*p > 127 || *p < 0) {
462 if (has_body && non_ascii) {
463 break; /* that's been already enough information */
467 if (!has_attachment && non_ascii==0) {
468 /* We don't need to convert it to MIME. */
476 /* Make names for the temporary files. */
477 strncpy(body_file_name,
478 m_mktemp(toabsdir(invo_name), NULL, NULL),
479 sizeof (body_file_name));
480 strncpy(composition_file_name,
481 m_mktemp(toabsdir(invo_name), NULL, NULL),
482 sizeof (composition_file_name));
485 body_file = fopen(body_file_name, "w");
487 composition_file = fopen(composition_file_name, "w");
489 if ((has_body && !body_file) || !composition_file) {
490 clean_up_temporary_files();
491 adios(NULL, "unable to open all of the temporary files.");
494 /* Copy non-attachment header fields to the temp composition file. */
496 while (get_line() != EOF && *field && *field != '-') {
497 if (strncasecmp(field, attach_hdr, length) != 0 ||
498 field[length] != ':') {
499 fprintf(composition_file, "%s\n", field);
502 fputs("--------\n", composition_file);
505 /* Copy the message body to the temporary file. */
506 while ((c = getc(draft_file)) != EOF) {
511 /* Add a mhbuild MIME composition file line for the body */
512 /* charset will be discovered/guessed by mhbuild */
513 fprintf(composition_file, "#text/plain %s\n", body_file_name);
517 ** Now, go back to the beginning of the draft file and look for
518 ** header fields that specify attachments. Add a mhbuild MIME
519 ** composition file for each.
522 while (get_line() != EOF && *field && *field != '-') {
523 if (strncasecmp(field, attach_hdr, length) == 0 &&
524 field[length] == ':') {
525 for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
529 /* forwarded message */
530 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
532 /* regular attachment */
533 make_mime_composition_file_entry(p);
537 fclose(composition_file);
539 /* We're ready to roll! */
540 sprintf(buf, "mhbuild %s", composition_file_name);
541 if (system(buf) != 0) {
543 clean_up_temporary_files();
551 clean_up_temporary_files(void)
553 unlink(body_file_name);
554 unlink(composition_file_name);
562 int c; /* current character */
563 int n; /* number of bytes in buffer */
567 ** Get a line from the input file, growing the field buffer as
568 ** needed. We do this so that we can fit an entire line in the
569 ** buffer making it easy to do a string comparison on both the
570 ** field name and the field body which might be a long path name.
572 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
573 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
574 ungetc(c, draft_file);
578 if (++n >= field_size - 1) {
579 field = (char *)mh_xrealloc(field, field_size += 256);
589 make_mime_composition_file_entry(char *file_name)
594 char content_type[BUFSIZ];
596 char *cmd = mimetypequeryproc;
598 for (np = m_defs; np; np = np->n_next) {
599 if (strcasecmp(np->n_name, mimetypequery)==0) {
604 snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
606 if (!(fp = popen(cmdbuf, "r"))) {
607 clean_up_temporary_files();
608 adios(NULL, "unable to determine content type with `%s'",
611 if (fgets(content_type, sizeof content_type, fp) &&
612 (cp = strrchr(content_type, '\n'))) {
615 strcpy(content_type, "application/octet-stream");
616 admonish(NULL, "problems with `%s', using fall back type `%s'",
617 cmdbuf, content_type);
621 /* TODO: don't use access(2) because it checks for ruid, not euid */
622 if (access(file_name, R_OK) != 0) {
623 clean_up_temporary_files();
624 adios(NULL, "unable to access file `%s'", file_name);
627 cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
628 fprintf(composition_file, "#%s; name=\"%s\" <> [%s] {attachment}",
629 content_type, cp, cp);
631 fprintf(composition_file, " %s\n", file_name);
637 ** The back-end of the message sending back-end.
638 ** Annotate original message, and call `spost' to send message.
641 sendaux(char **vec, int vecp, char *drft, struct stat *st)
648 ** fd collects the output of spost, and is used for the
649 ** failure notice if we need to send one in alert().
651 fd = pushsw ? tmp_fd() : NOTOK;
654 if (distfile && distout(drft, distfile, backup) == NOTOK) {
659 switch (child_id = fork()) {
661 /* oops -- fork error */
662 adios("fork", "unable to");
663 break; /* NOT REACHED */
667 ** child process -- send it
669 ** If fd is ok, then we are pushing and fd points to temp
670 ** file, so capture anything on stdout and stderr there.
673 dup2(fd, fileno(stdout));
674 dup2(fd, fileno(stderr));
678 fprintf(stderr, "unable to exec ");
681 break; /* NOT REACHED */
684 /* parent process -- wait for it */
685 if ((status = pidwait(child_id, NOTOK)) == OK) {
691 ** If spost failed, and we have good fd (which
692 ** means we pushed), then mail error message
693 ** (and possibly the draft) back to the user.
699 advise(NULL, "message not delivered to anyone");
703 if (rename(backup, drft) == NOTOK) {
704 advise(drft, "unable to rename %s to",
717 ** Mail error notification (and possibly a copy of the
718 ** message) back to the user, using mhmail(1).
721 alert(char *file, int out)
727 switch (child_id = fork()) {
729 /* oops -- fork error */
730 advise("fork", "unable to");
733 /* child process -- send it */
734 SIGNAL(SIGHUP, SIG_IGN);
735 SIGNAL(SIGINT, SIG_IGN);
736 SIGNAL(SIGQUIT, SIG_IGN);
737 SIGNAL(SIGTERM, SIG_IGN);
739 if ((in = open(file, O_RDONLY)) == NOTOK) {
740 admonish(file, "unable to re-open");
742 lseek(out, (off_t) 0, SEEK_END);
743 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
744 write(out, buf, strlen(buf));
745 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
746 write(out, buf, strlen(buf));
747 cpydgst(in, out, file, "temporary file");
749 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
750 write(out, buf, strlen(buf));
751 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK) {
752 admonish(buf, "unable to rename %s to", file);
756 lseek(out, (off_t) 0, SEEK_SET);
757 dup2(out, fileno(stdin));
759 /* create subject for error notification */
760 snprintf(buf, sizeof(buf), "send failed on %s",
761 forwsw ? "enclosed draft" : file);
762 execlp("mhmail", "mhmail", getusername(),
763 "-subject", buf, NULL);
764 fprintf(stderr, "unable to exec ");
768 default: /* no waiting... */
780 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
781 if (tfile == NULL) return NOTOK;
785 advise(NULL, "temporary file %s selected", tfile);
787 if (unlink(tfile) == NOTOK) {
788 advise(tfile, "unable to remove");
797 anno(struct stat *st)
803 if (altmsg && (stat(altmsg, &st2) == NOTOK ||
804 st->st_mtime != st2.st_mtime ||
805 st->st_dev != st2.st_dev ||
806 st->st_ino != st2.st_ino)) {
808 admonish(NULL, "$mhaltmsg mismatch");
813 if (!(folder = getenv("mhfolder")) || !*folder) {
815 admonish(NULL, "$mhfolder not set");
819 if (!(msgs = getenv("mhmessages")) || !*msgs) {
821 admonish(NULL, "$mhmessages not set");
826 advise(NULL, "annotate as `%s': %s %s", annotext,
829 snprintf(buf, sizeof buf, "anno -comp '%s' '+%s' %s",
830 annotext, folder, msgs);
831 if (system(buf) != 0) {
832 advise(NULL, "unable to annotate");
838 armed_done(int status)
840 longjmp(env, status ? status : NOTOK);