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