2 ** sendsbr.c -- routines to help WhatNow/Send along
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.
10 #include <h/signals.h>
18 #ifdef TIME_WITH_SYS_TIME
19 # include <sys/time.h>
22 # ifdef TM_IN_SYS_TIME
23 # include <sys/time.h>
29 int debugsw = 0; /* global */
36 char *altmsg = NULL; /* .. */
37 char *annotext = NULL;
38 char *distfile = NULL;
42 /* name of temp file for body content */
43 static char body_file_name[MAXPATHLEN + 1];
44 /* name of mhbuild composition temporary file */
45 static char composition_file_name[MAXPATHLEN + 1];
46 static int field_size; /* size of header field buffer */
47 static char *field; /* header field buffer */
48 static FILE *draft_file; /* draft file pointer */
49 static FILE *body_file; /* body file pointer */
50 static FILE *composition_file; /* composition file pointer */
53 ** external prototypes
55 int sendsbr(char **, int, char *, struct stat *, int);
56 char *getusername(void);
61 static void armed_done(int) NORETURN;
62 static void alert(char *, int);
63 static int tmp_fd(void);
64 static void anno(int, struct stat *);
65 static void annoaux(int);
66 static int sendaux(char **, int, char *, struct stat *);
68 static int attach(char *);
69 static void clean_up_temporary_files(void);
70 static int get_line(void);
71 static void make_mime_composition_file_entry(char *);
75 ** Entry point into (back-end) routines to send message.
79 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
82 char buffer[BUFSIZ], file[BUFSIZ];
83 char *original_draft; /* name of original draft file */
84 char *p; /* string pointer for building file name */
87 ** Save the original name of the draft file. The name of the
88 ** draft file is changed to a temporary file containing the built
89 ** MIME message if there are attachments. We need the original
90 ** name so that it can be renamed after the message is sent.
93 original_draft = drft;
96 ** Convert the draft to a MIME message.
97 ** Use the mhbuild composition file for the draft if there was
98 ** a successful conversion because that now contains the MIME
99 ** message. A nice side effect of this is that it leaves the
100 ** original draft file untouched so that it can be retrieved
101 ** and modified if desired.
103 switch (attach(drft)) {
105 drft = composition_file_name;
116 switch (setjmp(env)) {
119 ** If given -push and -unique (which is undocumented), then
120 ** rename the draft file. I'm not quite sure why.
122 if (pushsw && unique) {
123 char *cp = m_mktemp2(drft, invo_name, NULL, NULL);
125 adios("sendsbr", "unable to create temporary file");
127 if (rename(drft, strncpy(file, cp, sizeof(file)))
129 adios(file, "unable to rename %s to", drft);
133 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
135 /* rename the original draft */
136 if (rename_drft && status == OK &&
137 rename(original_draft, strncpy(buffer,
138 m_backup(original_draft), sizeof(buffer)))
140 advise(buffer, "unable to rename %s to", drft);
153 ** Get rid of any temporary files that we created for attachments.
154 ** Also get rid of the renamed composition file that mhbuild
155 ** leaves as a turd. It looks confusing, but we use the body
156 ** file name to help build the renamed composition file name.
159 if (drft == composition_file_name) {
160 clean_up_temporary_files();
162 if (strlen(composition_file_name) >=
163 sizeof (composition_file_name) - 6)
164 advise(NULL, "unable to remove original composition file.");
167 if ((p = strrchr(composition_file_name, '/')) == NULL)
168 p = composition_file_name;
172 strcpy(body_file_name, p);
174 strcpy(p, body_file_name);
177 unlink(composition_file_name);
185 attach(char *draft_file_name)
187 char buf[MAXPATHLEN + 6]; /* miscellaneous buffer */
188 int c; /* current character for body copy */
189 int has_attachment; /* draft has at least one attachment */
190 int has_body; /* draft has a message body */
191 int non_ascii; /* msg body contains non-ASCII chars */
192 int length; /* length of attachment header field name */
193 char *p; /* miscellaneous string pointer */
195 /* Open up the draft file. */
196 if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
197 adios(NULL, "can't open draft file `%s'.",
201 ** Allocate a buffer to hold the header components as they're read in.
202 ** This buffer might need to be quite large, so we grow it as needed.
204 field = (char *)mh_xmalloc(field_size = 256);
207 ** Scan the draft file for an attachment header field name.
208 ** The existence of one indicates that the
209 ** draft has attachments. Bail out if there are no attachments
210 ** because we're done. Read to the end of the headers even if
211 ** we have no attachments.
213 length = strlen(attach_hdr);
217 while (get_line() != EOF && *field != '\0' && *field != '-')
218 if (strncasecmp(field, attach_hdr, length) == 0 &&
219 field[length] == ':')
223 ** We have at least one attachment. Look for at least one
224 ** non-blank line in the body of the message which indicates
225 ** content in the body.
226 ** Check if body contains at least one non-blank (= not empty)
227 ** and if it contains any non-ASCII chars (= need MIME).
232 while (get_line() != EOF) {
233 for (p = field; *p != '\0'; p++) {
234 if (*p != ' ' && *p != '\t') {
237 if (*p > 127 || *p < 0) {
241 if (has_body && non_ascii)
246 ** Bail out if there are no attachments and only ASCII text.
247 ** This means we don't need to convert it to MIME.
249 if (!has_attachment && non_ascii==0) {
257 /* Make names for the temporary files. */
258 strncpy(body_file_name,
259 m_mktemp(toabsdir(invo_name), NULL, NULL),
260 sizeof (body_file_name));
261 strncpy(composition_file_name,
262 m_mktemp(toabsdir(invo_name), NULL, NULL),
263 sizeof (composition_file_name));
266 body_file = fopen(body_file_name, "w");
268 composition_file = fopen(composition_file_name, "w");
270 if ((has_body && body_file == (FILE *)0) ||
271 composition_file == (FILE *)0) {
272 clean_up_temporary_files();
273 adios(NULL, "unable to open all of the temporary files.");
277 ** Start at the beginning of the draft file. Copy all
278 ** non-attachment header fields to the temporary composition file.
279 ** Then add the dashed line separator.
282 while (get_line() != EOF && *field != '\0' && *field != '-')
283 if (strncasecmp(field, attach_hdr, length) != 0 ||
284 field[length] != ':')
285 fprintf(composition_file, "%s\n", field);
286 fputs("--------\n", composition_file);
289 ** Copy the message body to a temporary file.
292 while ((c = getc(draft_file)) != EOF)
298 ** Add a mhbuild MIME composition file line for the body if
302 /* old: make_mime_composition_file_entry(body_file_name); */
303 /* charset will be discovered/guessed by buildmimeproc */
304 fprintf(composition_file, "#text/plain %s\n", body_file_name);
308 ** Now, go back to the beginning of the draft file and look for
309 ** header fields that specify attachments. Add a mhbuild MIME
310 ** composition file for each.
313 while (get_line() != EOF && *field != '\0' && *field != '-') {
314 if (strncasecmp(field, attach_hdr, length) == 0 &&
315 field[length] == ':') {
316 for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
320 /* forwarded message */
321 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
323 make_mime_composition_file_entry(p);
328 fclose(composition_file);
331 ** We're ready to roll! Run mhbuild on the composition file.
332 ** Note that mhbuild is in the context as buildmimeproc.
334 sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
336 if (system(buf) != 0) {
337 clean_up_temporary_files();
345 clean_up_temporary_files(void)
347 unlink(body_file_name);
348 unlink(composition_file_name);
356 int c; /* current character */
357 int n; /* number of bytes in buffer */
358 char *p; /* buffer pointer */
361 ** Get a line from the input file, growing the field buffer as
362 ** needed. We do this so that we can fit an entire line in the
363 ** buffer making it easy to do a string comparison on both the
364 ** field name and the field body which might be a long path name.
367 for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
368 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
369 ungetc(c, draft_file);
374 if (++n >= field_size - 1) {
375 field = (char *)mh_xrealloc((void *)field, field_size += 256);
381 /* NUL-terminate the field. */
388 make_mime_composition_file_entry(char *file_name)
390 int binary; /* binary character found flag */
391 int c; /* current character */
392 char *content_type; /* mime content type */
393 FILE *fp; /* content and pipe file pointer */
394 struct node *np; /* context scan node pointer */
395 char *p; /* miscellaneous string pointer */
400 ** Check the file name for a suffix. Scan the context for that
401 ** suffix on a mhshow-suffix- entry. We use these entries to
402 ** be compatible with mhshow, and there's no reason to make the
403 ** user specify each suffix twice. Context entries of the form
404 ** "mhshow-suffix-contenttype" in the name have the suffix in
405 ** the field, including the dot.
408 if ((p = strrchr(file_name, '.')) != NULL) {
409 for (np = m_defs; np; np = np->n_next) {
410 if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0
411 && mh_strcasecmp(p, np->n_field) == 0)
413 content_type = np->n_name + 14;
420 ** No content type was found, either because there was no matching
421 ** entry in the context or because the file name has no suffix.
422 ** Open the file and check for non-ASCII characters. Choose the
423 ** content type based on this check.
426 if (content_type == NULL) {
427 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
428 clean_up_temporary_files();
429 adios(NULL, "unable to access file \"%s\"",
435 while ((c = getc(fp)) != EOF) {
436 if (c > 127 || c < 0) {
444 content_type = binary ?
445 "application/octet-stream" : "text/plain";
449 ** Make sure that the attachment file exists and is readable.
450 ** Append a mhbuild directive to the draft file. This starts with
451 ** the content type. Append a file name attribute and a private
452 ** x-unix-mode attribute. Also append a description obtained
453 ** (if possible) by running the "file" command on the file.
456 if (access(file_name, R_OK) != 0) {
457 clean_up_temporary_files();
458 adios(NULL, "unable to access file \"%s\"", file_name);
462 if (stringdex(toabsdir(invo_name), file_name) == 0) {
464 ** Content had been placed by send into a temp file.
465 ** Don't generate Content-Disposition header, because
466 ** it confuses Microsoft Outlook, Build 10.0.6626, at
469 fprintf(composition_file, "#%s <>", content_type);
472 ** Suppress Content-Id, insert simple
473 ** Content-Disposition.
475 fprintf(composition_file,
476 "#%s; name=\"%s\" <>{attachment}",
478 ((p = strrchr(file_name, '/')) == NULL) ?
482 /* Finish up with the file name. */
483 fprintf(composition_file, " %s\n", file_name);
489 ** Annotate original message, and
490 ** call `postproc' to send message.
494 sendaux(char **vec, int vecp, char *drft, struct stat *st)
497 int i, status, fd, fd2;
498 char backup[BUFSIZ], buf[BUFSIZ];
500 fd = pushsw ? tmp_fd() : NOTOK;
505 if ((fd2 = tmp_fd()) != NOTOK) {
506 vec[vecp++] = "-idanno";
507 snprintf(buf, sizeof(buf), "%d", fd2);
510 admonish(NULL, "unable to create file for annotation list");
513 if (distfile && distout(drft, distfile, backup) == NOTOK)
517 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
522 /* oops -- fork error */
523 adios("fork", "unable to");
524 break; /* NOT REACHED */
528 ** child process -- send it
530 ** If fd is ok, then we are pushing and fd points to temp
531 ** file, so capture anything on stdout and stderr there.
534 dup2(fd, fileno(stdout));
535 dup2(fd, fileno(stderr));
538 execvp(postproc, vec);
539 fprintf(stderr, "unable to exec ");
542 break; /* NOT REACHED */
546 ** parent process -- wait for it
548 if ((status = pidwait(child_id, NOTOK)) == OK) {
549 if (annotext && fd2 != NOTOK)
553 ** If postproc failed, and we have good fd (which
554 ** means we pushed), then mail error message
555 ** (and possibly the draft) back to the user.
561 advise(NULL, "message not delivered to anyone");
563 if (annotext && fd2 != NOTOK)
567 if (rename(backup, drft) == NOTOK)
568 advise(drft, "unable to rename %s to",
580 ** Mail error notification (and possibly a copy of the
581 ** message) back to the user, using the mailproc
585 alert(char *file, int out)
591 for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
596 /* oops -- fork error */
597 advise("fork", "unable to");
600 /* child process -- send it */
601 SIGNAL(SIGHUP, SIG_IGN);
602 SIGNAL(SIGINT, SIG_IGN);
603 SIGNAL(SIGQUIT, SIG_IGN);
604 SIGNAL(SIGTERM, SIG_IGN);
606 if ((in = open(file, O_RDONLY)) == NOTOK) {
607 admonish(file, "unable to re-open");
609 lseek(out, (off_t) 0, SEEK_END);
610 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
611 write(out, buf, strlen(buf));
612 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
613 write(out, buf, strlen(buf));
614 cpydgst(in, out, file, "temporary file");
616 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
617 write(out, buf, strlen(buf));
618 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK)
619 admonish(buf, "unable to rename %s to", file);
622 lseek(out, (off_t) 0, SEEK_SET);
623 dup2(out, fileno(stdin));
625 /* create subject for error notification */
626 snprintf(buf, sizeof(buf), "send failed on %s",
627 forwsw ? "enclosed draft" : file);
629 execlp(mailproc, mhbasename(mailproc), getusername(),
630 "-subject", buf, NULL);
631 fprintf(stderr, "unable to exec ");
635 default: /* no waiting... */
647 tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
648 if (tfile == NULL) return NOTOK;
652 advise(NULL, "temporary file %s selected", tfile);
654 if (unlink(tfile) == NOTOK)
655 advise(tfile, "unable to remove");
662 anno(int fd, struct stat *st)
666 static char *cwd = NULL;
669 if (altmsg && (stat(altmsg, &st2) == NOTOK ||
670 st->st_mtime != st2.st_mtime ||
671 st->st_dev != st2.st_dev ||
672 st->st_ino != st2.st_ino)) {
674 admonish(NULL, "$mhaltmsg mismatch");
678 child_id = debugsw ? NOTOK : fork();
680 case NOTOK: /* oops */
682 advise(NULL, "unable to fork, so doing annotations by hand...");
687 /* block a few signals */
689 sigaddset(&set, SIGHUP);
690 sigaddset(&set, SIGINT);
691 sigaddset(&set, SIGQUIT);
692 sigaddset(&set, SIGTERM);
693 SIGPROCMASK(SIG_BLOCK, &set, &oset);
699 /* reset the signal mask */
700 SIGPROCMASK(SIG_SETMASK, &oset, &set);
705 default: /* no waiting... */
715 int fd2, fd3, msgnum;
716 char *cp, *folder, *maildir;
717 char buffer[BUFSIZ], **ap;
721 if ((folder = getenv("mhfolder")) == NULL || *folder == 0) {
723 admonish(NULL, "$mhfolder not set");
726 maildir = toabsdir(folder);
727 if (chdir(maildir) == NOTOK) {
729 admonish(maildir, "unable to change directory to");
732 if (!(mp = folder_read(folder))) {
734 admonish(NULL, "unable to read folder %s", folder);
738 /* check for empty folder */
739 if (mp->nummsg == 0) {
741 admonish(NULL, "no messages in %s", folder);
745 if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
747 admonish(NULL, "$mhmessages not set");
750 if (!debugsw /* MOBY HACK... */
752 && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
753 && (fd2 = dup(fileno(stderr))) != NOTOK) {
754 dup2(fd3, fileno(stderr));
759 for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++)
763 dup2(fd2, fileno(stderr));
764 if (mp->numsel == 0) {
766 admonish(NULL, "no messages to annotate");
770 lseek(fd, (off_t) 0, SEEK_SET);
771 if ((fp = fdopen(fd, "r")) == NULL) {
773 admonish(NULL, "unable to fdopen annotation list");
777 while (fgets(buffer, sizeof(buffer), fp) != NULL)
778 cp = add(buffer, cp);
782 advise(NULL, "annotate%s with %s: \"%s\"",
783 inplace ? " inplace" : "", annotext, cp);
784 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
785 if (is_selected(mp, msgnum)) {
787 advise(NULL, "annotate message %d", msgnum);
788 annotate(m_name (msgnum), annotext, cp, inplace,
796 folder_free(mp); /* free folder/message structure */
801 armed_done(int status)
803 longjmp(env, status ? status : NOTOK);