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 },
95 main(int argc, char **argv)
97 int msgp = 0, nfiles = 0, distsw = 0, vecp = 1;
101 char *cp, *maildir = NULL;
102 char buf[BUFSIZ], **ap, **argp, **arguments;
103 char *msgs[MAXARGS], *vec[MAXARGS];
104 char *files[MAXARGS];
111 setlocale(LC_ALL, "");
113 invo_name = mhbasename(argv[0]);
115 /* read user profile/context */
118 arguments = getarguments(invo_name, argc, argv, 1);
121 vec[vecp++] = "-library";
122 vec[vecp++] = getcpy(toabsdir("+"));
124 while ((cp = *argp++)) {
126 switch (smatch(++cp, switches)) {
128 ambigsw(cp, switches);
131 adios(NULL, "-%s unknown\n", cp);
134 snprintf(buf, sizeof(buf),
135 "%s [file] [switches]",
137 print_help(buf, switches, 1);
140 print_version(invo_name);
167 debugsw++; /* fall */
175 if (!(cp = *argp++) || *cp == '-') {
176 adios(NULL, "missing argument to %s",
185 files[nfiles++] = cp;
192 /* check for "Aliasfile:" profile entry */
193 if ((cp = context_find("Aliasfile"))) {
196 for (ap=brkstring(dp=getcpy(cp), " ", "\n"); ap && *ap; ap++) {
197 vec[vecp++] = "-alias";
198 vec[vecp++] = getcpy(etcpath(*ap));
202 if (!msgp && !nfiles) {
203 msgs[msgp++] = seq_cur;
205 maildir = toabsdir(draftfolder);
207 if (chdir(maildir) == NOTOK) {
208 adios(maildir, "unable to change directory to");
211 if (!(mp = folder_read(draftfolder))) {
212 adios(NULL, "unable to read draft folder %s", draftfolder);
214 if (mp->nummsg == 0) {
215 adios(NULL, "no messages in draft folder %s", draftfolder);
217 /* parse all the message ranges/sequences and set SELECTED */
218 for (msgnum = 0; msgnum < msgp; msgnum++) {
219 if (!m_convert(mp, msgs[msgnum])) {
225 for (msgp = 0, msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
226 if (is_selected(mp, msgnum)) {
227 files[nfiles++] = getcpy(m_name(msgnum));
228 unset_exists(mp, msgnum);
232 mp->msgflags |= SEQMOD;
235 if (!(cp = getenv("SIGNATURE")) || !*cp) {
236 if ((cp = context_find("signature")) && *cp) {
237 m_putenv("SIGNATURE", cp);
241 for (msgnum = 0; msgnum < nfiles; msgnum++) {
242 if (stat(files[msgnum], &st) == NOTOK) {
243 adios(files[msgnum], "unable to stat draft file");
247 if (!(annotext = getenv("mhannotate")) || !*annotext) {
250 if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
251 altmsg = NULL; /* used by dist interface - see below */
254 if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
255 vec[vecp++] = "-dist";
256 if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
257 adios(altmsg, "unable to open for reading");
260 distfile = getcpy(m_mktemp2(NULL, invo_name, NULL, NULL));
261 if ((out = creat(distfile, (int)st2.st_mode & 0777))==NOTOK) {
262 adios(distfile, "unable to open for writing");
264 cpydata(in, out, altmsg, distfile);
271 if (!altmsg || stat(altmsg, &st) == NOTOK) {
277 /* push a fork into the background */
280 switch (pid = fork()) {
283 advise(NULL, "unable to fork, so can't push...");
287 /* parent, just exit */
291 /* child, block a few signals and continue */
292 SIGNAL(SIGHUP, SIG_IGN);
293 SIGNAL(SIGINT, SIG_IGN);
294 SIGNAL(SIGQUIT, SIG_IGN);
295 SIGNAL(SIGTERM, SIG_IGN);
297 SIGNAL(SIGTSTP, SIG_IGN);
298 SIGNAL(SIGTTIN, SIG_IGN);
299 SIGNAL(SIGTTOU, SIG_IGN);
301 freopen("/dev/null", "r", stdin);
302 freopen("/dev/null", "w", stdout);
308 for (n=3; n<OPEN_MAX; n++) {
312 for (msgnum = 0; msgnum < nfiles; msgnum++) {
313 switch (sendsbr(vec, vecp, files[msgnum], &st, 1)) {
330 ** message sending back-end
333 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
337 char *original_draft;
338 char *p; /* string pointer for building file name */
341 ** Save the original name of the draft file. The name of the
342 ** draft file is changed to a temporary file containing the built
343 ** MIME message if there are attachments. We need the original
344 ** name so that it can be renamed after the message is sent.
346 original_draft = drft;
349 ** Convert the draft to a MIME message.
350 ** Use the mhbuild composition file for the draft if there was
351 ** a successful conversion because that now contains the MIME
352 ** message. A nice side effect of this is that it leaves the
353 ** original draft file untouched so that it can be retrieved
354 ** and modified if desired.
356 switch (attach(drft)) {
358 drft = composition_file_name;
369 switch (setjmp(env)) {
371 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
372 /* rename the original draft */
373 if (rename_drft && status == OK &&
374 rename(original_draft, strncpy(buffer,
375 m_backup(original_draft), sizeof(buffer)))
377 advise(buffer, "unable to rename %s to", drft);
392 ** Get rid of any temporary files that we created for attachments.
393 ** Also get rid of the renamed composition file that mhbuild
394 ** leaves as a turd. It looks confusing, but we use the body
395 ** file name to help build the renamed composition file name.
397 if (drft == composition_file_name) {
398 clean_up_temporary_files();
400 if (strlen(composition_file_name) >=
401 sizeof (composition_file_name) - 6) {
402 advise(NULL, "unable to remove original composition file.");
404 if (!(p = strrchr(composition_file_name, '/'))) {
405 p = composition_file_name;
409 strcpy(body_file_name, p);
411 strcpy(p, body_file_name);
414 unlink(composition_file_name);
422 attach(char *draft_file_name)
424 char buf[MAXPATHLEN + 6];
428 int non_ascii; /* msg body contains non-ASCII chars */
429 int length; /* length of attachment header field name */
432 if (!(draft_file = fopen(draft_file_name, "r"))) {
433 adios(NULL, "can't open draft file `%s'.", draft_file_name);
436 /* We'll grow the buffer as needed. */
437 field = (char *)mh_xmalloc(field_size = 256);
440 ** Scan the draft file for an attachment header field name.
442 length = strlen(attach_hdr);
444 while (get_line() != EOF && *field != '\0' && *field != '-') {
445 if (strncasecmp(field, attach_hdr, length)==0 &&
446 field[length] == ':') {
452 ** Look for at least one non-blank line in the body of the
453 ** message which indicates content in the body.
454 ** Check if body contains at least one non-blank (= not empty)
455 ** and if it contains any non-ASCII chars (= need MIME).
459 while (get_line() != EOF) {
460 for (p = field; *p != '\0'; p++) {
461 if (*p != ' ' && *p != '\t') {
464 if (*p > 127 || *p < 0) {
468 if (has_body && non_ascii) {
469 break; /* that's been already enough information */
473 if (!has_attachment && non_ascii==0) {
474 /* We don't need to convert it to MIME. */
482 /* Make names for the temporary files. */
483 strncpy(body_file_name,
484 m_mktemp(toabsdir(invo_name), NULL, NULL),
485 sizeof (body_file_name));
486 strncpy(composition_file_name,
487 m_mktemp(toabsdir(invo_name), NULL, NULL),
488 sizeof (composition_file_name));
491 body_file = fopen(body_file_name, "w");
493 composition_file = fopen(composition_file_name, "w");
495 if ((has_body && !body_file) || !composition_file) {
496 clean_up_temporary_files();
497 adios(NULL, "unable to open all of the temporary files.");
500 /* Copy non-attachment header fields to the temp composition file. */
502 while (get_line() != EOF && *field && *field != '-') {
503 if (strncasecmp(field, attach_hdr, length) != 0 ||
504 field[length] != ':') {
505 fprintf(composition_file, "%s\n", field);
508 fputs("--------\n", composition_file);
511 /* Copy the message body to the temporary file. */
512 while ((c = getc(draft_file)) != EOF) {
517 /* Add a mhbuild MIME composition file line for the body */
518 /* charset will be discovered/guessed by mhbuild */
519 fprintf(composition_file, "#text/plain %s\n", body_file_name);
523 ** Now, go back to the beginning of the draft file and look for
524 ** header fields that specify attachments. Add a mhbuild MIME
525 ** composition file for each.
528 while (get_line() != EOF && *field && *field != '-') {
529 if (strncasecmp(field, attach_hdr, length) == 0 &&
530 field[length] == ':') {
531 for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
535 /* forwarded message */
536 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
538 /* regular attachment */
539 make_mime_composition_file_entry(p);
543 fclose(composition_file);
545 /* We're ready to roll! */
546 sprintf(buf, "mhbuild %s", composition_file_name);
547 if (system(buf) != 0) {
549 clean_up_temporary_files();
557 clean_up_temporary_files(void)
559 unlink(body_file_name);
560 unlink(composition_file_name);
568 int c; /* current character */
569 int n; /* number of bytes in buffer */
573 ** Get a line from the input file, growing the field buffer as
574 ** needed. We do this so that we can fit an entire line in the
575 ** buffer making it easy to do a string comparison on both the
576 ** field name and the field body which might be a long path name.
578 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
579 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
580 ungetc(c, draft_file);
584 if (++n >= field_size - 1) {
585 field = (char *)mh_xrealloc(field, field_size += 256);
595 make_mime_composition_file_entry(char *file_name)
600 char content_type[BUFSIZ];
602 char *cmd = mimetypequeryproc;
604 for (np = m_defs; np; np = np->n_next) {
605 if (strcasecmp(np->n_name, mimetypequery)==0) {
610 snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
612 if (!(fp = popen(cmdbuf, "r"))) {
613 clean_up_temporary_files();
614 adios(NULL, "unable to determine content type with `%s'",
617 if (fgets(content_type, sizeof content_type, fp) &&
618 (cp = strrchr(content_type, '\n'))) {
621 strcpy(content_type, "application/octet-stream");
622 admonish(NULL, "problems with `%s', using fall back type `%s'",
623 cmdbuf, content_type);
627 /* TODO: don't use access(2) because it checks for ruid, not euid */
628 if (access(file_name, R_OK) != 0) {
629 clean_up_temporary_files();
630 adios(NULL, "unable to access file `%s'", file_name);
633 fprintf(composition_file, "#%s; name=\"%s\" <>{attachment}",
635 (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1);
637 fprintf(composition_file, " %s\n", file_name);
643 ** The back-end of the message sending back-end.
644 ** Annotate original message, and call `spost' to send message.
647 sendaux(char **vec, int vecp, char *drft, struct stat *st)
654 ** fd collects the output of spost, and is used for the
655 ** failure notice if we need to send one in alert().
657 fd = pushsw ? tmp_fd() : NOTOK;
660 if (distfile && distout(drft, distfile, backup) == NOTOK) {
665 switch (child_id = fork()) {
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));
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 spost 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 mhmail(1).
727 alert(char *file, int out)
733 switch (child_id = fork()) {
735 /* oops -- fork error */
736 advise("fork", "unable to");
739 /* child process -- send it */
740 SIGNAL(SIGHUP, SIG_IGN);
741 SIGNAL(SIGINT, SIG_IGN);
742 SIGNAL(SIGQUIT, SIG_IGN);
743 SIGNAL(SIGTERM, SIG_IGN);
745 if ((in = open(file, O_RDONLY)) == NOTOK) {
746 admonish(file, "unable to re-open");
748 lseek(out, (off_t) 0, SEEK_END);
749 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
750 write(out, buf, strlen(buf));
751 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
752 write(out, buf, strlen(buf));
753 cpydgst(in, out, file, "temporary file");
755 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
756 write(out, buf, strlen(buf));
757 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK) {
758 admonish(buf, "unable to rename %s to", file);
762 lseek(out, (off_t) 0, SEEK_SET);
763 dup2(out, fileno(stdin));
765 /* create subject for error notification */
766 snprintf(buf, sizeof(buf), "send failed on %s",
767 forwsw ? "enclosed draft" : file);
768 execlp("mhmail", "mhmail", getusername(),
769 "-subject", buf, NULL);
770 fprintf(stderr, "unable to exec ");
774 default: /* no waiting... */
786 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
787 if (tfile == NULL) return NOTOK;
791 advise(NULL, "temporary file %s selected", tfile);
793 if (unlink(tfile) == NOTOK) {
794 advise(tfile, "unable to remove");
803 anno(struct stat *st)
809 if (altmsg && (stat(altmsg, &st2) == NOTOK ||
810 st->st_mtime != st2.st_mtime ||
811 st->st_dev != st2.st_dev ||
812 st->st_ino != st2.st_ino)) {
814 admonish(NULL, "$mhaltmsg mismatch");
819 if (!(folder = getenv("mhfolder")) || !*folder) {
821 admonish(NULL, "$mhfolder not set");
825 if (!(msgs = getenv("mhmessages")) || !*msgs) {
827 admonish(NULL, "$mhmessages not set");
832 advise(NULL, "annotate as `%s': %s %s", annotext,
835 snprintf(buf, sizeof buf, "anno -comp '%s' '+%s' %s",
836 annotext, folder, msgs);
837 if (system(buf) != 0) {
838 advise(NULL, "unable to annotate");
844 armed_done(int status)
846 longjmp(env, status ? status : NOTOK);