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 int sendaux(char **, int, char *, struct stat *);
59 static int attach(char *);
60 static void clean_up_temporary_files(void);
61 static int get_line(void);
62 static void make_mime_composition_file_entry(char *);
65 static struct swit switches[] = {
67 { "alias aliasfile", 0 },
71 { "filter filterfile", 0 },
103 main(int argc, char **argv)
105 int msgp = 0, nfiles = 0, distsw = 0, vecp = 1;
108 char *cp, *maildir = NULL;
109 char buf[BUFSIZ], **ap, **argp, **arguments;
110 char *msgs[MAXARGS], *vec[MAXARGS];
111 char *files[MAXARGS];
118 setlocale(LC_ALL, "");
120 invo_name = mhbasename(argv[0]);
122 /* read user profile/context */
125 arguments = getarguments(invo_name, argc, argv, 1);
128 vec[vecp++] = "-library";
129 vec[vecp++] = getcpy(toabsdir("+"));
131 while ((cp = *argp++)) {
133 switch (smatch(++cp, switches)) {
135 ambigsw(cp, switches);
138 adios(NULL, "-%s unknown\n", cp);
141 snprintf(buf, sizeof(buf),
142 "%s [file] [switches]",
144 print_help(buf, switches, 1);
147 print_version(invo_name);
174 debugsw++; /* fall */
186 if (!(cp = *argp++) || *cp == '-') {
187 adios(NULL, "missing argument to %s",
196 files[nfiles++] = cp;
203 /* check for "Aliasfile:" profile entry */
204 if ((cp = context_find("Aliasfile"))) {
207 for (ap=brkstring(dp=getcpy(cp), " ", "\n"); ap && *ap; ap++) {
208 vec[vecp++] = "-alias";
209 vec[vecp++] = getcpy(etcpath(*ap));
213 if (!msgp && !nfiles) {
214 msgs[msgp++] = seq_cur;
216 maildir = toabsdir(draftfolder);
218 if (chdir(maildir) == NOTOK) {
219 adios(maildir, "unable to change directory to");
222 if (!(mp = folder_read(draftfolder))) {
223 adios(NULL, "unable to read draft folder %s", draftfolder);
225 if (mp->nummsg == 0) {
226 adios(NULL, "no messages in draft folder %s", draftfolder);
228 /* parse all the message ranges/sequences and set SELECTED */
229 for (msgnum = 0; msgnum < msgp; msgnum++) {
230 if (!m_convert(mp, msgs[msgnum])) {
236 for (msgp = 0, msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
237 if (is_selected(mp, msgnum)) {
238 files[nfiles++] = getcpy(m_name(msgnum));
239 unset_exists(mp, msgnum);
243 mp->msgflags |= SEQMOD;
246 if (!(cp = getenv("SIGNATURE")) || !*cp) {
247 if ((cp = context_find("signature")) && *cp) {
248 m_putenv("SIGNATURE", cp);
252 for (msgnum = 0; msgnum < nfiles; msgnum++) {
253 if (stat(files[msgnum], &st) == NOTOK) {
254 adios(files[msgnum], "unable to stat draft file");
258 if (!(annotext = getenv("mhannotate")) || !*annotext) {
261 if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
262 altmsg = NULL; /* used by dist interface - see below */
265 if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
266 vec[vecp++] = "-dist";
267 distfile = getcpy(m_mktemp2(altmsg, invo_name, NULL, NULL));
268 if (link(altmsg, distfile) == NOTOK) {
269 if (errno != EXDEV) {
270 adios(distfile, "unable to link %s to",
274 distfile = getcpy(m_mktemp2(NULL, invo_name,
276 if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
277 adios(altmsg, "unable to open");
280 if ((out = creat(distfile, (int)st2.st_mode & 0777)) ==
282 adios(distfile, "unable to write");
284 cpydata(in, out, altmsg, distfile);
292 if (!altmsg || stat(altmsg, &st) == NOTOK) {
301 vec[0] = mhbasename(postproc);
304 for (msgnum = 0; msgnum < nfiles; msgnum++) {
305 switch (sendsbr(vec, vecp, files[msgnum], &st, 1)) {
322 ** message sending back-end
325 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
329 char *original_draft;
330 char *p; /* string pointer for building file name */
333 ** Save the original name of the draft file. The name of the
334 ** draft file is changed to a temporary file containing the built
335 ** MIME message if there are attachments. We need the original
336 ** name so that it can be renamed after the message is sent.
338 original_draft = drft;
341 ** Convert the draft to a MIME message.
342 ** Use the mhbuild composition file for the draft if there was
343 ** a successful conversion because that now contains the MIME
344 ** message. A nice side effect of this is that it leaves the
345 ** original draft file untouched so that it can be retrieved
346 ** and modified if desired.
348 switch (attach(drft)) {
350 drft = composition_file_name;
361 switch (setjmp(env)) {
363 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
364 /* rename the original draft */
365 if (rename_drft && status == OK &&
366 rename(original_draft, strncpy(buffer,
367 m_backup(original_draft), sizeof(buffer)))
369 advise(buffer, "unable to rename %s to", drft);
384 ** Get rid of any temporary files that we created for attachments.
385 ** Also get rid of the renamed composition file that mhbuild
386 ** leaves as a turd. It looks confusing, but we use the body
387 ** file name to help build the renamed composition file name.
389 if (drft == composition_file_name) {
390 clean_up_temporary_files();
392 if (strlen(composition_file_name) >=
393 sizeof (composition_file_name) - 6) {
394 advise(NULL, "unable to remove original composition file.");
396 if (!(p = strrchr(composition_file_name, '/'))) {
397 p = composition_file_name;
401 strcpy(body_file_name, p);
403 strcpy(p, body_file_name);
406 unlink(composition_file_name);
414 attach(char *draft_file_name)
416 char buf[MAXPATHLEN + 6];
420 int non_ascii; /* msg body contains non-ASCII chars */
421 int length; /* length of attachment header field name */
424 if (!(draft_file = fopen(draft_file_name, "r"))) {
425 adios(NULL, "can't open draft file `%s'.", draft_file_name);
428 /* We'll grow the buffer as needed. */
429 field = (char *)mh_xmalloc(field_size = 256);
432 ** Scan the draft file for an attachment header field name.
434 length = strlen(attach_hdr);
436 while (get_line() != EOF && *field != '\0' && *field != '-') {
437 if (strncasecmp(field, attach_hdr, length)==0 &&
438 field[length] == ':') {
444 ** Look for at least one non-blank line in the body of the
445 ** message which indicates content in the body.
446 ** Check if body contains at least one non-blank (= not empty)
447 ** and if it contains any non-ASCII chars (= need MIME).
451 while (get_line() != EOF) {
452 for (p = field; *p != '\0'; p++) {
453 if (*p != ' ' && *p != '\t') {
456 if (*p > 127 || *p < 0) {
460 if (has_body && non_ascii) {
461 break; /* that's been already enough information */
465 if (!has_attachment && non_ascii==0) {
466 /* We don't need to convert it to MIME. */
474 /* Make names for the temporary files. */
475 strncpy(body_file_name,
476 m_mktemp(toabsdir(invo_name), NULL, NULL),
477 sizeof (body_file_name));
478 strncpy(composition_file_name,
479 m_mktemp(toabsdir(invo_name), NULL, NULL),
480 sizeof (composition_file_name));
483 body_file = fopen(body_file_name, "w");
485 composition_file = fopen(composition_file_name, "w");
487 if ((has_body && !body_file) || !composition_file) {
488 clean_up_temporary_files();
489 adios(NULL, "unable to open all of the temporary files.");
492 /* Copy non-attachment header fields to the temp composition file. */
494 while (get_line() != EOF && *field && *field != '-') {
495 if (strncasecmp(field, attach_hdr, length) != 0 ||
496 field[length] != ':') {
497 fprintf(composition_file, "%s\n", field);
500 fputs("--------\n", composition_file);
503 /* Copy the message body to the temporary file. */
504 while ((c = getc(draft_file)) != EOF) {
509 /* Add a mhbuild MIME composition file line for the body */
510 /* charset will be discovered/guessed by buildmimeproc */
511 fprintf(composition_file, "#text/plain %s\n", body_file_name);
515 ** Now, go back to the beginning of the draft file and look for
516 ** header fields that specify attachments. Add a mhbuild MIME
517 ** composition file for each.
520 while (get_line() != EOF && *field && *field != '-') {
521 if (strncasecmp(field, attach_hdr, length) == 0 &&
522 field[length] == ':') {
523 for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
527 /* forwarded message */
528 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
530 /* regular attachment */
531 make_mime_composition_file_entry(p);
535 fclose(composition_file);
538 ** We're ready to roll! Run mhbuild on the composition file.
539 ** Note that mhbuild is in the context as buildmimeproc.
541 sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
543 if (system(buf) != 0) {
545 clean_up_temporary_files();
553 clean_up_temporary_files(void)
555 unlink(body_file_name);
556 unlink(composition_file_name);
564 int c; /* current character */
565 int n; /* number of bytes in buffer */
569 ** Get a line from the input file, growing the field buffer as
570 ** needed. We do this so that we can fit an entire line in the
571 ** buffer making it easy to do a string comparison on both the
572 ** field name and the field body which might be a long path name.
574 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
575 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
576 ungetc(c, draft_file);
580 if (++n >= field_size - 1) {
581 field = (char *)mh_xrealloc(field, field_size += 256);
591 make_mime_composition_file_entry(char *file_name)
596 char content_type[BUFSIZ];
598 char *cmd = mimetypequeryproc;
600 for (np = m_defs; np; np = np->n_next) {
601 if (strcasecmp(np->n_name, mimetypequery)==0) {
606 snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
608 if (!(fp = popen(cmdbuf, "r"))) {
609 clean_up_temporary_files();
610 adios(NULL, "unable to determine content type with `%s'",
613 if (fgets(content_type, sizeof content_type, fp) &&
614 (cp = strrchr(content_type, '\n'))) {
617 strcpy(content_type, "application/octet-stream");
618 admonish(NULL, "problems with `%s', using fall back type `%s'",
619 cmdbuf, content_type);
623 /* TODO: don't use access(2) because it checks for ruid, not euid */
624 if (access(file_name, R_OK) != 0) {
625 clean_up_temporary_files();
626 adios(NULL, "unable to access file `%s'", file_name);
629 fprintf(composition_file, "#%s; name=\"%s\" <>{attachment}",
631 (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1);
633 fprintf(composition_file, " %s\n", file_name);
639 ** The back-end of the message sending back-end.
640 ** Annotate original message, and call `postproc' to send message.
643 sendaux(char **vec, int vecp, char *drft, struct stat *st)
650 ** fd collects the output of postproc, and is used for the
651 ** failure notice if we need to send one in alert().
653 fd = pushsw ? tmp_fd() : NOTOK;
656 if (distfile && distout(drft, distfile, backup) == NOTOK) {
661 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++) {
666 /* oops -- fork error */
667 adios("fork", "unable to");
668 break; /* NOT REACHED */
672 ** child process -- send it
674 ** If fd is ok, then we are pushing and fd points to temp
675 ** file, so capture anything on stdout and stderr there.
678 dup2(fd, fileno(stdout));
679 dup2(fd, fileno(stderr));
682 execvp(postproc, vec);
683 fprintf(stderr, "unable to exec ");
686 break; /* NOT REACHED */
689 /* parent process -- wait for it */
690 if ((status = pidwait(child_id, NOTOK)) == OK) {
696 ** If postproc failed, and we have good fd (which
697 ** means we pushed), then mail error message
698 ** (and possibly the draft) back to the user.
704 advise(NULL, "message not delivered to anyone");
708 if (rename(backup, drft) == NOTOK) {
709 advise(drft, "unable to rename %s to",
722 ** Mail error notification (and possibly a copy of the
723 ** message) back to the user, using the mailproc
726 alert(char *file, int out)
732 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++) {
738 /* oops -- fork error */
739 advise("fork", "unable to");
742 /* child process -- send it */
743 SIGNAL(SIGHUP, SIG_IGN);
744 SIGNAL(SIGINT, SIG_IGN);
745 SIGNAL(SIGQUIT, SIG_IGN);
746 SIGNAL(SIGTERM, SIG_IGN);
748 if ((in = open(file, O_RDONLY)) == NOTOK) {
749 admonish(file, "unable to re-open");
751 lseek(out, (off_t) 0, SEEK_END);
752 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
753 write(out, buf, strlen(buf));
754 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
755 write(out, buf, strlen(buf));
756 cpydgst(in, out, file, "temporary file");
758 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
759 write(out, buf, strlen(buf));
760 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK) {
761 admonish(buf, "unable to rename %s to", file);
765 lseek(out, (off_t) 0, SEEK_SET);
766 dup2(out, fileno(stdin));
768 /* create subject for error notification */
769 snprintf(buf, sizeof(buf), "send failed on %s",
770 forwsw ? "enclosed draft" : file);
772 execlp(mailproc, mhbasename(mailproc), getusername(),
773 "-subject", buf, NULL);
774 fprintf(stderr, "unable to exec ");
778 default: /* no waiting... */
790 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
791 if (tfile == NULL) return NOTOK;
795 advise(NULL, "temporary file %s selected", tfile);
797 if (unlink(tfile) == NOTOK) {
798 advise(tfile, "unable to remove");
807 anno(struct stat *st)
813 if (altmsg && (stat(altmsg, &st2) == NOTOK ||
814 st->st_mtime != st2.st_mtime ||
815 st->st_dev != st2.st_dev ||
816 st->st_ino != st2.st_ino)) {
818 admonish(NULL, "$mhaltmsg mismatch");
823 if (!(folder = getenv("mhfolder")) || !*folder) {
825 admonish(NULL, "$mhfolder not set");
829 if (!(msgs = getenv("mhmessages")) || !*msgs) {
831 admonish(NULL, "$mhmessages not set");
836 advise(NULL, "annotate as `%s': %s %s", annotext,
839 snprintf(buf, sizeof buf, "anno -comp '%s' '+%s' %s",
840 annotext, folder, msgs);
841 if (system(buf) != 0) {
842 advise(NULL, "unable to annotate");
848 armed_done(int status)
850 longjmp(env, status ? status : NOTOK);