Moved sendsbr.c into send.c as it is not compiled into other binaries anymore.
[mmh] / uip / send.c
1 /*
2 ** send.c -- send a composed message
3 **
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.
7 */
8
9 #include <h/mh.h>
10 #include <fcntl.h>
11 #include <errno.h>
12 #include <signal.h>
13 #include <h/signals.h>
14 #include <setjmp.h>
15 #include <h/mime.h>
16 #include <h/tws.h>
17 #include <h/utils.h>
18
19 #ifdef TIME_WITH_SYS_TIME
20 # include <sys/time.h>
21 # include <time.h>
22 #else
23 # ifdef TM_IN_SYS_TIME
24 #  include <sys/time.h>
25 # else
26 #  include <time.h>
27 # endif
28 #endif
29
30 int debugsw = 0;  /* global */
31 int forwsw  = 1;
32 int inplace = 1;
33 int pushsw  = 0;
34 int verbsw  = 0;
35 char *altmsg   = NULL;
36 char *annotext = NULL;
37 char *distfile = NULL;
38
39 static jmp_buf env;
40
41 /* name of temp file for body content */
42 static char body_file_name[MAXPATHLEN + 1];
43 /* name of mhbuild composition temporary file */
44 static char composition_file_name[MAXPATHLEN + 1]; 
45 static int field_size;  /* size of header field buffer */
46 static char *field;  /* header field buffer */
47 static FILE *draft_file;  /* draft file pointer */
48 static FILE *body_file;  /* body file pointer */
49 static FILE *composition_file;  /* composition file pointer */
50
51 /*
52 ** external prototypes
53 */
54 char *getusername(void);
55
56 /*
57 ** static prototypes
58 */
59 static int sendsbr(char **, int, char *, struct stat *, int);
60 static void armed_done(int) NORETURN;
61 static void alert(char *, int);
62 static int tmp_fd(void);
63 static void anno(int, struct stat *);
64 static void annoaux(int);
65 static int sendaux(char **, int, char *, struct stat *);
66
67 static int attach(char *);
68 static void clean_up_temporary_files(void);
69 static int get_line(void);
70 static void make_mime_composition_file_entry(char *);
71
72
73 static struct swit switches[] = {
74 #define ALIASW  0
75         { "alias aliasfile", 0 },
76 #define DEBUGSW  1
77         { "debug", -5 },
78 #define FILTSW  2
79         { "filter filterfile", 0 },
80 #define NFILTSW  3
81         { "nofilter", 0 },
82 #define FRMTSW  4
83         { "format", 0 },
84 #define NFRMTSW  5
85         { "noformat", 0 },
86 #define FORWSW  6
87         { "forward", 0 },
88 #define NFORWSW  7
89         { "noforward", 0 },
90 #define PUSHSW  8
91         { "push", 0 },
92 #define NPUSHSW  9
93         { "nopush", 0 },
94 #define VERBSW  10
95         { "verbose", 0 },
96 #define NVERBSW  11
97         { "noverbose", 0 },
98 #define WATCSW  12
99         { "watch", 0 },
100 #define NWATCSW  13
101         { "nowatch", 0 },
102 #define VERSIONSW  14
103         { "version", 0 },
104 #define HELPSW  15
105         { "help", 0 },
106         { NULL, 0 }
107 };
108
109
110 int
111 main(int argc, char **argv)
112 {
113         int msgp = 0, nfiles = 0, distsw = 0, vecp = 1;
114         int msgnum, status;
115         char *cp, *maildir = NULL;
116         char buf[BUFSIZ], **ap, **argp, **arguments;
117         char *msgs[MAXARGS], *vec[MAXARGS];
118         char *files[MAXARGS];
119         struct msgs *mp;
120         struct stat st;
121
122 #ifdef LOCALE
123         setlocale(LC_ALL, "");
124 #endif
125         invo_name = mhbasename(argv[0]);
126
127         /* read user profile/context */
128         context_read();
129
130         arguments = getarguments(invo_name, argc, argv, 1);
131         argp = arguments;
132
133         vec[vecp++] = "-library";
134         vec[vecp++] = getcpy(toabsdir("+"));
135
136         while ((cp = *argp++)) {
137                 if (*cp == '-') {
138                         switch (smatch(++cp, switches)) {
139                         case AMBIGSW:
140                                 ambigsw(cp, switches);
141                                 done(1);
142                         case UNKWNSW:
143                                 adios(NULL, "-%s unknown\n", cp);
144
145                         case HELPSW:
146                                 snprintf(buf, sizeof(buf),
147                                                 "%s [file] [switches]",
148                                                 invo_name);
149                                 print_help(buf, switches, 1);
150                                 done(1);
151                         case VERSIONSW:
152                                 print_version(invo_name);
153                                 done(1);
154
155                         case PUSHSW:
156                                 pushsw++;
157                                 continue;
158                         case NPUSHSW:
159                                 pushsw = 0;
160                                 continue;
161
162                         case FORWSW:
163                                 forwsw++;
164                                 continue;
165                         case NFORWSW:
166                                 forwsw = 0;
167                                 continue;
168
169                         case VERBSW:
170                                 verbsw++;
171                                 vec[vecp++] = --cp;
172                                 continue;
173                         case NVERBSW:
174                                 verbsw = 0;
175                                 vec[vecp++] = --cp;
176                                 continue;
177
178                         case DEBUGSW:
179                                 debugsw++;  /* fall */
180                         case NFILTSW:
181                         case FRMTSW:
182                         case NFRMTSW:
183                         case WATCSW:
184                         case NWATCSW:
185                                 vec[vecp++] = --cp;
186                                 continue;
187
188                         case ALIASW:
189                         case FILTSW:
190                                 vec[vecp++] = --cp;
191                                 if (!(cp = *argp++) || *cp == '-')
192                                         adios(NULL, "missing argument to %s",
193                                                         argp[-2]);
194                                 vec[vecp++] = cp;
195                                 continue;
196
197                         }
198                 } else {
199                         if (*cp == '/') {
200                                 files[nfiles++] = cp;
201                         } else {
202                                 msgs[msgp++] = cp;
203                         }
204                 }
205         }
206
207         /*
208         ** check for "Aliasfile:" profile entry
209         */
210         if ((cp = context_find("Aliasfile"))) {
211                 char *dp = NULL;
212
213                 for (ap = brkstring(dp = getcpy(cp), " ", "\n"); ap && *ap;
214                                 ap++) {
215                         vec[vecp++] = "-alias";
216                         vec[vecp++] = getcpy(etcpath(*ap));
217                 }
218         }
219
220         if (!msgp && !nfiles)
221                 msgs[msgp++] = seq_cur;
222         maildir = toabsdir(draftfolder);
223
224         if (chdir(maildir) == NOTOK)
225                 adios(maildir, "unable to change directory to");
226
227         /* read folder and create message structure */
228         if (!(mp = folder_read(draftfolder)))
229                 adios(NULL, "unable to read draft folder %s", draftfolder);
230
231         /* check for empty folder */
232         if (mp->nummsg == 0)
233                 adios(NULL, "no messages in draft folder %s", draftfolder);
234
235         /* parse all the message ranges/sequences and set SELECTED */
236         for (msgnum = 0; msgnum < msgp; msgnum++) {
237                 if (!m_convert(mp, msgs[msgnum])) {
238                         done(1);
239                 }
240         }
241         seq_setprev(mp);  /* set the previous-sequence */
242
243         for (msgp = 0, msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
244                 if (is_selected(mp, msgnum)) {
245                         files[nfiles++] = getcpy(m_name(msgnum));
246                         unset_exists(mp, msgnum);
247                 }
248         }
249
250         mp->msgflags |= SEQMOD;
251         seq_save(mp);
252
253         if (!(cp = getenv("SIGNATURE")) || !*cp)
254                 if ((cp = context_find("signature")) && *cp)
255                         m_putenv("SIGNATURE", cp);
256
257         for (msgnum = 0; msgnum < nfiles; msgnum++)
258                 if (stat(files[msgnum], &st) == NOTOK)
259                         adios(files[msgnum], "unable to stat draft file");
260
261         if ((annotext = getenv("mhannotate")) == NULL || *annotext == 0)
262                 annotext = NULL;
263         if (annotext && ((cp = getenv("mhinplace")) != NULL && *cp != 0))
264                 inplace = atoi(cp);
265         if ((altmsg = getenv("mhaltmsg")) == NULL || *altmsg == 0)
266                 altmsg = NULL;  /* used by dist interface - see below */
267
268         if ((cp = getenv("mhdist")) && *cp && (distsw = atoi (cp)) && altmsg) {
269                 vec[vecp++] = "-dist";
270                 distfile = getcpy(m_mktemp2(altmsg, invo_name, NULL, NULL));
271                 if (link(altmsg, distfile) == NOTOK) {
272                         if (errno != EXDEV)
273                                 adios(distfile, "unable to link %s to",
274                                                 altmsg);
275                         free(distfile);
276                         distfile = getcpy(m_mktemp2(NULL, invo_name,
277                                         NULL, NULL));
278                         {
279                                 int in, out;
280                                 struct stat st;
281
282                                 if ((in = open(altmsg, O_RDONLY)) == NOTOK)
283                                         adios(altmsg, "unable to open");
284                                 fstat(in, &st);
285                                 if ((out = creat(distfile,
286                                                 (int) st.st_mode & 0777))
287                                                 == NOTOK)
288                                         adios(distfile, "unable to write");
289                                 cpydata(in, out, altmsg, distfile);
290                                 close(in);
291                                 close(out);
292                         }
293                 }
294         } else {
295                 distfile = NULL;
296         }
297
298         if (altmsg == NULL || stat(altmsg, &st) == NOTOK) {
299                 st.st_mtime = 0;
300                 st.st_dev = 0;
301                 st.st_ino = 0;
302         }
303         if (pushsw)
304                 push();
305
306         status = 0;
307         vec[0] = mhbasename(postproc);
308         closefds(3);
309
310         for (msgnum = 0; msgnum < nfiles; msgnum++) {
311                 switch (sendsbr(vec, vecp, files[msgnum], &st, 1)) {
312                 case DONE:
313                         done(++status);
314                 case NOTOK:
315                         status++;  /* fall */
316                 case OK:
317                         break;
318                 }
319         }
320
321         context_save();  /* save the context file */
322         done(status);
323         return 1;
324 }
325
326
327 /*
328 ** send message back-end
329 */
330 static int
331 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
332 {
333         int status;
334         char buffer[BUFSIZ];
335         char *original_draft;  /* name of original draft file */
336         char *p;  /* string pointer for building file name */
337
338         /*
339         ** Save the original name of the draft file.  The name of the
340         ** draft file is changed to a temporary file containing the built
341         ** MIME message if there are attachments.  We need the original
342         ** name so that it can be renamed after the message is sent.
343         */
344
345         original_draft = drft;
346
347         /*
348         ** Convert the draft to a MIME message.
349         ** Use the mhbuild composition file for the draft if there was
350         ** a successful conversion because that now contains the MIME
351         ** message.  A nice side effect of this is that it leaves the
352         ** original draft file untouched so that it can be retrieved
353         ** and modified if desired.
354         */
355         switch (attach(drft)) {
356         case OK:
357                 drft = composition_file_name;
358                 break;
359
360         case NOTOK:
361                 return (NOTOK);
362
363         case DONE:
364                 break;
365         }
366
367         done=armed_done;
368         switch (setjmp(env)) {
369         case OK:
370                 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
371                 /* rename the original draft */
372                 if (rename_drft && status == OK &&
373                                 rename(original_draft, strncpy(buffer,
374                                 m_backup(original_draft), sizeof(buffer)))
375                                 == NOTOK)
376                         advise(buffer, "unable to rename %s to", drft);
377                 break;
378
379         default:
380                 status = DONE;
381                 break;
382         }
383
384         done=exit;
385         if (distfile)
386                 unlink(distfile);
387
388         /*
389         ** Get rid of any temporary files that we created for attachments.
390         ** Also get rid of the renamed composition file that mhbuild
391         ** leaves as a turd.  It looks confusing, but we use the body
392         ** file name to help build the renamed composition file name.
393         */
394
395         if (drft == composition_file_name) {
396                 clean_up_temporary_files();
397
398                 if (strlen(composition_file_name) >=
399                                 sizeof (composition_file_name) - 6)
400                         advise(NULL, "unable to remove original composition file.");
401
402                 else {
403                         if ((p = strrchr(composition_file_name, '/')) == NULL)
404                                 p = composition_file_name;
405                         else
406                                 p++;
407
408                         strcpy(body_file_name, p);
409                         *p++ = ',';
410                         strcpy(p, body_file_name);
411                         strcat(p, ".orig");
412
413                         unlink(composition_file_name);
414                 }
415         }
416
417         return status;
418 }
419
420 static int
421 attach(char *draft_file_name)
422 {
423         char buf[MAXPATHLEN + 6];  /* miscellaneous buffer */
424         int c;  /* current character for body copy */
425         int has_attachment;  /* draft has at least one attachment */
426         int has_body;  /* draft has a message body */
427         int non_ascii; /* msg body contains non-ASCII chars */
428         int length;  /* length of attachment header field name */
429         char *p;  /* miscellaneous string pointer */
430
431         /* Open up the draft file. */
432         if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
433                 adios(NULL, "can't open draft file `%s'.",
434                                 draft_file_name);
435
436         /*
437         **  Allocate a buffer to hold the header components as they're read in.
438         **  This buffer might need to be quite large, so we grow it as needed.
439         */
440         field = (char *)mh_xmalloc(field_size = 256);
441
442         /*
443         ** Scan the draft file for an attachment header field name.
444         ** The existence of one indicates that the
445         ** draft has attachments.  Bail out if there are no attachments
446         ** because we're done.  Read to the end of the headers even if
447         ** we have no attachments.
448         */
449         length = strlen(attach_hdr);
450
451         has_attachment = 0;
452
453         while (get_line() != EOF && *field != '\0' && *field != '-') {
454                 if (strncasecmp(field, attach_hdr, length) == 0 &&
455                                 field[length] == ':') {
456                         has_attachment = 1;
457                 }
458         }
459
460         /*
461         ** Look for at least one non-blank line in the body of the
462         ** message which indicates content in the body.
463         ** Check if body contains at least one non-blank (= not empty)
464         ** and if it contains any non-ASCII chars (= need MIME).
465         */
466         has_body = 0;
467         non_ascii = 0;
468
469         while (get_line() != EOF) {
470                 for (p = field; *p != '\0'; p++) {
471                         if (*p != ' ' && *p != '\t') {
472                                 has_body = 1;
473                         }
474                         if (*p > 127 || *p < 0) {
475                                 non_ascii = 1;
476                         }
477                 }
478                 if (has_body && non_ascii)
479                         break;
480         }
481
482         /*
483         ** Bail out if there are no attachments and only ASCII text.
484         ** This means we don't need to convert it to MIME.
485         */
486         if (!has_attachment && non_ascii==0) {
487                 return DONE;
488         }
489
490         /*
491         ** Else: mimify
492         */
493
494         /* Make names for the temporary files.  */
495         strncpy(body_file_name,
496                         m_mktemp(toabsdir(invo_name), NULL, NULL),
497                         sizeof (body_file_name));
498         strncpy(composition_file_name,
499                         m_mktemp(toabsdir(invo_name), NULL, NULL),
500                         sizeof (composition_file_name));
501
502         if (has_body)
503                 body_file = fopen(body_file_name, "w");
504
505         composition_file = fopen(composition_file_name, "w");
506
507         if ((has_body && !body_file) || !composition_file) {
508                 clean_up_temporary_files();
509                 adios(NULL, "unable to open all of the temporary files.");
510         }
511
512         /*
513         ** Start at the beginning of the draft file.  Copy all
514         ** non-attachment header fields to the temporary composition file.
515         ** Then add the dashed line separator.
516         */
517         rewind(draft_file);
518         while (get_line() != EOF && *field && *field != '-') {
519                 if (strncasecmp(field, attach_hdr, length) != 0 ||
520                                 field[length] != ':') {
521                         fprintf(composition_file, "%s\n", field);
522                 }
523         }
524         fputs("--------\n", composition_file);
525
526         if (has_body) {
527                 /* Copy the message body to the temporary file. */
528                 while ((c = getc(draft_file)) != EOF) {
529                         putc(c, body_file);
530                 }
531                 fclose(body_file);
532
533                 /* Add a mhbuild MIME composition file line for the body */
534                 /* charset will be discovered/guessed by buildmimeproc */
535                 fprintf(composition_file, "#text/plain %s\n", body_file_name);
536         }
537
538         /*
539         ** Now, go back to the beginning of the draft file and look for
540         ** header fields that specify attachments.  Add a mhbuild MIME
541         ** composition file for each.
542         */
543         rewind(draft_file);
544         while (get_line() != EOF && *field && *field != '-') {
545                 if (strncasecmp(field, attach_hdr, length) == 0 &&
546                                 field[length] == ':') {
547                         for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
548                                 continue;
549                         }
550                         if (*p == '+') {
551                                 /* forwarded message */
552                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
553                         } else {
554                                 make_mime_composition_file_entry(p);
555                         }
556                 }
557         }
558
559         fclose(composition_file);
560
561         /*
562         ** We're ready to roll!  Run mhbuild on the composition file.
563         ** Note that mhbuild is in the context as buildmimeproc.
564         */
565         sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
566
567         if (system(buf) != 0) {
568                 clean_up_temporary_files();
569                 return (NOTOK);
570         }
571
572         return (OK);
573 }
574
575 static void
576 clean_up_temporary_files(void)
577 {
578         unlink(body_file_name);
579         unlink(composition_file_name);
580
581         return;
582 }
583
584 static int
585 get_line(void)
586 {
587         int c;  /* current character */
588         int n;  /* number of bytes in buffer */
589         char *p;  /* buffer pointer */
590
591         /*
592         ** Get a line from the input file, growing the field buffer as
593         ** needed.  We do this so that we can fit an entire line in the
594         ** buffer making it easy to do a string comparison on both the
595         ** field name and the field body which might be a long path name.
596         */
597
598         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
599                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
600                         ungetc(c, draft_file);
601                         c = '\n';
602                         break;
603                 }
604
605                 if (++n >= field_size - 1) {
606                         field = (char *)mh_xrealloc((void *)field, field_size += 256);
607
608                         p = field + n - 1;
609                 }
610         }
611
612         /* NUL-terminate the field. */
613         *p = '\0';
614
615         return (c);
616 }
617
618 static void
619 make_mime_composition_file_entry(char *file_name)
620 {
621         FILE *fp;
622         struct node *np;
623         char *cp;
624         char content_type[BUFSIZ];
625         char cmdbuf[BUFSIZ];
626         char *cmd = mimetypequeryproc;
627
628         for (np = m_defs; np; np = np->n_next) {
629                 if (strcasecmp(np->n_name, mimetypequery)==0) {
630                         cmd = np->n_field;
631                         break;
632                 }
633         }
634         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
635
636         if (!(fp = popen(cmdbuf, "r"))) {
637                 clean_up_temporary_files();
638                 adios(NULL, "unable to determine content type with `%s'",
639                                 cmdbuf);
640         }
641         if (fgets(content_type, sizeof content_type, fp) &&
642                         (cp = strrchr(content_type, '\n'))) {
643                 *cp = '\0';
644         } else {
645                 strcpy(content_type, "application/octet-stream");
646                 admonish(NULL, "problems with `%s', using fall back type `%s'",
647                                 cmdbuf, content_type);
648         }
649         pclose(fp);
650
651         /* TODO: don't use access(2) because it checks for ruid, not euid */
652         if (access(file_name, R_OK) != 0) {
653                 clean_up_temporary_files();
654                 adios(NULL, "unable to access file `%s'", file_name);
655         }
656
657         fprintf(composition_file, "#%s; name=\"%s\" <>{attachment}",
658                 content_type,
659                 (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1);
660
661         fprintf(composition_file, " %s\n", file_name);
662
663         return;
664 }
665
666 /*
667 ** Annotate original message, and
668 ** call `postproc' to send message.
669 */
670 static int
671 sendaux(char **vec, int vecp, char *drft, struct stat *st)
672 {
673         pid_t child_id;
674         int i, status, fd, fd2;
675         char backup[BUFSIZ];
676
677         fd = pushsw ? tmp_fd() : NOTOK;
678         fd2 = NOTOK;
679
680         vec[vecp++] = drft;
681         if (annotext && (fd2 = tmp_fd()) == NOTOK) {
682                 admonish(NULL, "unable to create file for annotation list");
683         }
684         if (distfile && distout(drft, distfile, backup) == NOTOK)
685                 done(1);
686         vec[vecp] = NULL;
687
688         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
689                 sleep(5);
690
691         switch (child_id) {
692         case -1:
693                 /* oops -- fork error */
694                 adios("fork", "unable to");
695                 break;  /* NOT REACHED */
696
697         case 0:
698                 /*
699                 ** child process -- send it
700                 **
701                 ** If fd is ok, then we are pushing and fd points to temp
702                 ** file, so capture anything on stdout and stderr there.
703                 */
704                 if (fd != NOTOK) {
705                         dup2(fd, fileno(stdout));
706                         dup2(fd, fileno(stderr));
707                         close(fd);
708                 }
709                 execvp(postproc, vec);
710                 fprintf(stderr, "unable to exec ");
711                 perror(postproc);
712                 _exit(-1);
713                 break;  /* NOT REACHED */
714
715         default:
716                 /*
717                 ** parent process -- wait for it
718                 */
719                 if ((status = pidwait(child_id, NOTOK)) == OK) {
720                         if (annotext && fd2 != NOTOK)
721                                 anno(fd2, st);
722                 } else {
723                         /*
724                         ** If postproc failed, and we have good fd (which
725                         ** means we pushed), then mail error message
726                         ** (and possibly the draft) back to the user.
727                         */
728                         if (fd != NOTOK) {
729                                 alert(drft, fd);
730                                 close(fd);
731                         } else {
732                                 advise(NULL, "message not delivered to anyone");
733                         }
734                         if (annotext && fd2 != NOTOK)
735                                 close(fd2);
736                         if (distfile) {
737                                 unlink(drft);
738                                 if (rename(backup, drft) == NOTOK)
739                                         advise(drft, "unable to rename %s to",
740                                                         backup);
741                         }
742                 }
743                 break;
744         }
745
746         return status;
747 }
748
749
750 /*
751 ** Mail error notification (and possibly a copy of the
752 ** message) back to the user, using the mailproc
753 */
754 static void
755 alert(char *file, int out)
756 {
757         pid_t child_id;
758         int i, in;
759         char buf[BUFSIZ];
760
761         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
762                 sleep(5);
763
764         switch (child_id) {
765         case NOTOK:
766                 /* oops -- fork error */
767                 advise("fork", "unable to");
768
769         case OK:
770                 /* child process -- send it */
771                 SIGNAL(SIGHUP, SIG_IGN);
772                 SIGNAL(SIGINT, SIG_IGN);
773                 SIGNAL(SIGQUIT, SIG_IGN);
774                 SIGNAL(SIGTERM, SIG_IGN);
775                 if (forwsw) {
776                         if ((in = open(file, O_RDONLY)) == NOTOK) {
777                                 admonish(file, "unable to re-open");
778                         } else {
779                                 lseek(out, (off_t) 0, SEEK_END);
780                                 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
781                                 write(out, buf, strlen(buf));
782                                 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
783                                 write(out, buf, strlen(buf));
784                                 cpydgst(in, out, file, "temporary file");
785                                 close(in);
786                                 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
787                                 write(out, buf, strlen(buf));
788                                 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK)
789                                         admonish(buf, "unable to rename %s to", file);
790                         }
791                 }
792                 lseek(out, (off_t) 0, SEEK_SET);
793                 dup2(out, fileno(stdin));
794                 close(out);
795                 /* create subject for error notification */
796                 snprintf(buf, sizeof(buf), "send failed on %s",
797                                 forwsw ? "enclosed draft" : file);
798
799                 execlp(mailproc, mhbasename(mailproc), getusername(),
800                                 "-subject", buf, NULL);
801                 fprintf(stderr, "unable to exec ");
802                 perror(mailproc);
803                 _exit(-1);
804
805         default:  /* no waiting... */
806                 break;
807         }
808 }
809
810
811 static int
812 tmp_fd(void)
813 {
814         int fd;
815         char *tfile = NULL;
816
817         tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
818         if (tfile == NULL) return NOTOK;
819         fchmod(fd, 0600);
820
821         if (debugsw)
822                 advise(NULL, "temporary file %s selected", tfile);
823         else
824                 if (unlink(tfile) == NOTOK)
825                         advise(tfile, "unable to remove");
826
827         return fd;
828 }
829
830
831 static void
832 anno(int fd, struct stat *st)
833 {
834         pid_t child_id;
835         sigset_t set, oset;
836         static char *cwd = NULL;
837         struct stat st2;
838
839         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
840                         st->st_mtime != st2.st_mtime ||
841                         st->st_dev != st2.st_dev ||
842                         st->st_ino != st2.st_ino)) {
843                 if (debugsw)
844                         admonish(NULL, "$mhaltmsg mismatch");
845                 return;
846         }
847
848         child_id = debugsw ? NOTOK : fork();
849         switch (child_id) {
850         case NOTOK:  /* oops */
851                 if (!debugsw)
852                         advise(NULL, "unable to fork, so doing annotations by hand...");
853                 if (cwd == NULL)
854                         cwd = getcpy(pwd());
855                 /* fall */
856
857         case OK:
858                 /* block a few signals */
859                 sigemptyset(&set);
860                 sigaddset(&set, SIGHUP);
861                 sigaddset(&set, SIGINT);
862                 sigaddset(&set, SIGQUIT);
863                 sigaddset(&set, SIGTERM);
864                 SIGPROCMASK(SIG_BLOCK, &set, &oset);
865
866                 annoaux(fd);
867                 if (child_id == OK)
868                         _exit(0);
869
870                 /* reset the signal mask */
871                 SIGPROCMASK(SIG_SETMASK, &oset, &set);
872
873                 chdir(cwd);
874                 break;
875
876         default:  /* no waiting... */
877                 close(fd);
878                 break;
879         }
880 }
881
882
883 static void
884 annoaux(int fd)
885 {
886         int fd2, fd3, msgnum;
887         char *cp, *folder, *maildir;
888         char buffer[BUFSIZ], **ap;
889         FILE *fp;
890         struct msgs *mp;
891
892         if ((folder = getenv("mhfolder")) == NULL || *folder == 0) {
893                 if (debugsw)
894                         admonish(NULL, "$mhfolder not set");
895                 return;
896         }
897         maildir = toabsdir(folder);
898         if (chdir(maildir) == NOTOK) {
899                 if (debugsw)
900                         admonish(maildir, "unable to change directory to");
901                 return;
902         }
903         if (!(mp = folder_read(folder))) {
904                 if (debugsw)
905                         admonish(NULL, "unable to read folder %s", folder);
906                 return;
907         }
908
909         /* check for empty folder */
910         if (mp->nummsg == 0) {
911                 if (debugsw)
912                         admonish(NULL, "no messages in %s", folder);
913                 goto oops;
914         }
915
916         if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
917                 if (debugsw)
918                         admonish(NULL, "$mhmessages not set");
919                 goto oops;
920         }
921         if (!debugsw  /* MOBY HACK... */
922                         && pushsw
923                         && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
924                         && (fd2 = dup(fileno(stderr))) != NOTOK) {
925                 dup2(fd3, fileno(stderr));
926                 close(fd3);
927         } else
928                 fd2 = NOTOK;
929         for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++)
930                 m_convert(mp, *ap);
931         free(cp);
932         if (fd2 != NOTOK)
933                 dup2(fd2, fileno(stderr));
934         if (mp->numsel == 0) {
935                 if (debugsw)
936                         admonish(NULL, "no messages to annotate");
937                 goto oops;
938         }
939
940         lseek(fd, (off_t) 0, SEEK_SET);
941         if ((fp = fdopen(fd, "r")) == NULL) {
942                 if (debugsw)
943                         admonish(NULL, "unable to fdopen annotation list");
944                 goto oops;
945         }
946         cp = NULL;
947         while (fgets(buffer, sizeof(buffer), fp) != NULL)
948                 cp = add(buffer, cp);
949         fclose(fp);
950
951         if (debugsw)
952                 advise(NULL, "annotate%s with %s: \"%s\"",
953                                 inplace ? " inplace" : "", annotext, cp);
954         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
955                 if (is_selected(mp, msgnum)) {
956                         if (debugsw)
957                                 advise(NULL, "annotate message %d", msgnum);
958                         annotate(m_name(msgnum), annotext, cp, inplace,
959                                         1, -2, 0);
960                 }
961         }
962
963         free(cp);
964
965 oops:
966         folder_free(mp);  /* free folder/message structure */
967 }
968
969
970 static void
971 armed_done(int status)
972 {
973         longjmp(env, status ? status : NOTOK);
974
975         exit(status);
976 }