When building on gcc, use noreturn attribute on adios and the various done
[mmh] / uip / sendsbr.c
1
2 /*
3  * sendsbr.c -- routines to help WhatNow/Send along
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2002, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 #include <h/mh.h>
13 #include <h/signals.h>
14 #include <setjmp.h>
15 #include <signal.h>
16 #include <fcntl.h>
17 #include <h/mime.h>
18 #include <h/tws.h>
19 #include <h/utils.h>
20
21 #ifdef TIME_WITH_SYS_TIME
22 # include <sys/time.h>
23 # include <time.h>
24 #else
25 # ifdef TM_IN_SYS_TIME
26 #  include <sys/time.h>
27 # else
28 #  include <time.h>
29 # endif
30 #endif
31
32 int debugsw = 0;                /* global */
33 int forwsw  = 1;
34 int inplace = 1;
35 int pushsw  = 0;
36 int splitsw = -1;
37 int unique  = 0;
38 int verbsw  = 0;
39
40 char *altmsg   = NULL;          /*  .. */
41 char *annotext = NULL;
42 char *distfile = NULL;
43
44 static jmp_buf env;
45
46 static  char    body_file_name[MAXPATHLEN + 1];         /* name of temporary file for body content */
47 static  char    composition_file_name[MAXPATHLEN + 1];  /* name of mhbuild composition temporary file */
48 static  int     field_size;                             /* size of header field buffer */
49 static  char    *field;                                 /* header field buffer */
50 static  FILE    *draft_file;                            /* draft file pointer */
51 static  FILE    *body_file;                             /* body file pointer */
52 static  FILE    *composition_file;                      /* composition file pointer */
53
54 /*
55  * external prototypes
56  */
57 int sendsbr (char **, int, char *, struct stat *, int, char *, int);
58 char *getusername (void);
59
60 /*
61  * static prototypes
62  */
63 static void armed_done (int) NORETURN;
64 static void alert (char *, int);
65 static int tmp_fd (void);
66 static void anno (int, struct stat *);
67 static void annoaux (int);
68 static int splitmsg (char **, int, char *, struct stat *, int);
69 static int sendaux (char **, int, char *, struct stat *);
70
71 static  int     attach(char *, char *, int);
72 static  void    clean_up_temporary_files(void);
73 static  int     get_line(void);
74 static  void    make_mime_composition_file_entry(char *, int);
75
76
77 /*
78  * Entry point into (back-end) routines to send message.
79  */
80
81 int
82 sendsbr (char **vec, int vecp, char *drft, struct stat *st, int rename_drft, char *attachment_header_field_name, int attachformat)
83 {
84     int status;
85     char buffer[BUFSIZ], file[BUFSIZ];
86     struct stat sts;
87     char        *original_draft;                /* name of original draft file */
88     char        *p;                             /* string pointer for building file name */
89
90     /*
91      *  Save the original name of the draft file.  The name of the draft file is changed
92      *  to a temporary file containing the built MIME message if there are attachments.
93      *  We need the original name so that it can be renamed after the message is sent.
94      */
95
96     original_draft = drft;
97
98     /*
99      *  There might be attachments if a header field name for attachments is supplied.
100      *  Convert the draft to a MIME message.  Use the mhbuild composition file for the
101      *  draft if there was a successful conversion because that now contains the MIME
102      *  message.  A nice side effect of this is that it leaves the original draft file
103      *  untouched so that it can be retrieved and modified if desired.
104      */
105
106     if (attachment_header_field_name != (char *)0) {
107         switch (attach(attachment_header_field_name, drft, attachformat)) {
108         case OK:
109             drft = composition_file_name;
110             break;
111
112         case NOTOK:
113             return (NOTOK);
114
115         case DONE:
116             break;
117         }
118     }
119
120     done=armed_done;
121     switch (setjmp (env)) {
122     case OK: 
123         /*
124          * If given -push and -unique (which is undocumented), then
125          * rename the draft file.  I'm not quite sure why.
126          */
127         if (pushsw && unique) {
128             if (rename (drft, strncpy (file, m_scratch (drft, invo_name), sizeof(file)))
129                     == NOTOK)
130                 adios (file, "unable to rename %s to", drft);
131             drft = file;
132         }
133
134         /*
135          * Check if we need to split the message into
136          * multiple messages of type "message/partial".
137          */
138         if (splitsw >= 0 && !distfile && stat (drft, &sts) != NOTOK
139                 && sts.st_size >= CPERMSG) {
140             status = splitmsg (vec, vecp, drft, st, splitsw) ? NOTOK : OK;
141         } else {
142             status = sendaux (vec, vecp, drft, st) ? NOTOK : OK;
143         }
144
145         /* rename the original draft */
146         if (rename_drft && status == OK &&
147                 rename (original_draft, strncpy (buffer, m_backup (original_draft), sizeof(buffer))) == NOTOK)
148             advise (buffer, "unable to rename %s to", drft);
149         break;
150
151     default: 
152         status = DONE;
153         break;
154     }
155
156     done=exit;
157     if (distfile)
158         unlink (distfile);
159
160     /*
161      *  Get rid of any temporary files that we created for attachments.  Also get rid of
162      *  the renamed composition file that mhbuild leaves as a turd.  It looks confusing,
163      *  but we use the body file name to help build the renamed composition file name.
164      */
165
166     if (drft == composition_file_name) {
167         clean_up_temporary_files();
168
169         if (strlen(composition_file_name) >= sizeof (composition_file_name) - 6)
170             advise((char *)0, "unable to remove original composition file.");
171
172         else {
173             if ((p = strrchr(composition_file_name, '/')) == (char *)0)
174                 p = composition_file_name;
175             else
176                 p++;
177             
178             (void)strcpy(body_file_name, p);
179             *p++ = ',';
180             (void)strcpy(p, body_file_name);
181             (void)strcat(p, ".orig");
182             
183             (void)unlink(composition_file_name);
184         }
185     }
186
187     return status;
188 }
189
190 static  int
191 attach(char *attachment_header_field_name, char *draft_file_name,
192        int attachformat)
193 {
194     char                buf[MAXPATHLEN + 6];    /* miscellaneous buffer */
195     int                 c;                      /* current character for body copy */
196     int                 has_attachment;         /* draft has at least one attachment */
197     int                 has_body;               /* draft has a message body */
198     int                 length;                 /* length of attachment header field name */
199     char                *p;                     /* miscellaneous string pointer */
200
201     /*
202      *  Open up the draft file.
203      */
204
205     if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
206         adios((char *)0, "can't open draft file `%s'.", draft_file_name);
207
208     /*
209      *  Allocate a buffer to hold the header components as they're read in.
210      *  This buffer might need to be quite large, so we grow it as needed.
211      */
212
213     field = (char *)mh_xmalloc(field_size = 256);
214
215     /*
216      *  Scan the draft file for a header field name that matches the -attach
217      *  argument.  The existence of one indicates that the draft has attachments.
218      *  Bail out if there are no attachments because we're done.  Read to the
219      *  end of the headers even if we have no attachments.
220      */
221
222     length = strlen(attachment_header_field_name);
223
224     has_attachment = 0;
225
226     while (get_line() != EOF && *field != '\0' && *field != '-')
227         if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':')
228             has_attachment = 1;
229
230     if (has_attachment == 0)
231         return (DONE);
232
233     /*
234      *  We have at least one attachment.  Look for at least one non-blank line
235      *  in the body of the message which indicates content in the body.
236      */
237
238     has_body = 0;
239
240     while (get_line() != EOF) {
241         for (p = field; *p != '\0'; p++) {
242             if (*p != ' ' && *p != '\t') {
243                 has_body = 1;
244                 break;
245             }
246         }
247
248         if (has_body)
249             break;
250     }
251
252     /*
253      *  Make names for the temporary files.
254      */
255
256     (void)strncpy(body_file_name, m_scratch("", m_maildir(invo_name)), sizeof (body_file_name));
257     (void)strncpy(composition_file_name, m_scratch("", m_maildir(invo_name)), sizeof (composition_file_name));
258
259     if (has_body)
260         body_file = fopen(body_file_name, "w");
261
262     composition_file = fopen(composition_file_name, "w");
263
264     if ((has_body && body_file == (FILE *)0) || composition_file == (FILE *)0) {
265         clean_up_temporary_files();
266         adios((char *)0, "unable to open all of the temporary files.");
267     }
268
269     /*
270      *  Start at the beginning of the draft file.  Copy all non-attachment header fields
271      *  to the temporary composition file.  Then add the dashed line separator.
272      */
273
274     rewind(draft_file);
275
276     while (get_line() != EOF && *field != '\0' && *field != '-')
277         if (strncasecmp(field, attachment_header_field_name, length) != 0 || field[length] != ':')
278             (void)fprintf(composition_file, "%s\n", field);
279
280     (void)fputs("--------\n", composition_file);
281
282     /*
283      *  Copy the message body to a temporary file.
284      */
285
286     if (has_body) {
287         while ((c = getc(draft_file)) != EOF)
288                 putc(c, body_file);
289
290         (void)fclose(body_file);
291     }
292
293     /*
294      *  Add a mhbuild MIME composition file line for the body if there was one.
295      */
296
297     if (has_body)
298         make_mime_composition_file_entry(body_file_name, attachformat);
299
300     /*
301      *  Now, go back to the beginning of the draft file and look for header fields
302      *  that specify attachments.  Add a mhbuild MIME composition file for each.
303      */
304
305     rewind(draft_file);
306
307     while (get_line() != EOF && *field != '\0' && *field != '-') {
308         if (strncasecmp(field, attachment_header_field_name, length) == 0 && field[length] == ':') {
309             for (p = field + length + 1; *p == ' ' || *p == '\t'; p++)
310                 ;
311
312             make_mime_composition_file_entry(p, attachformat);
313         }
314     }
315
316     (void)fclose(composition_file);
317
318     /*
319      *  We're ready to roll!  Run mhbuild on the composition file.  Note that mhbuild
320      *  is in the context as buildmimeproc.
321      */
322
323     (void)sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
324
325     if (system(buf) != 0) {
326         clean_up_temporary_files();
327         return (NOTOK);
328     }
329
330     return (OK);
331 }
332
333 static  void
334 clean_up_temporary_files(void)
335 {
336     (void)unlink(body_file_name);
337     (void)unlink(composition_file_name);
338
339     return;
340 }
341
342 static  int
343 get_line(void)
344 {
345     int         c;      /* current character */
346     int         n;      /* number of bytes in buffer */
347     char        *p;     /* buffer pointer */
348
349     /*
350      *  Get a line from the input file, growing the field buffer as needed.  We do this
351      *  so that we can fit an entire line in the buffer making it easy to do a string
352      *  comparison on both the field name and the field body which might be a long path
353      *  name.
354      */
355
356     for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
357         if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
358             (void)ungetc(c, draft_file);
359             c = '\n';
360             break;
361         }
362
363         if (++n >= field_size - 1) {
364             field = (char *)mh_xrealloc((void *)field, field_size += 256);
365
366             p = field + n - 1;
367         }
368     }
369
370     /*
371      *  NUL-terminate the field..
372      */
373
374     *p = '\0';
375
376     return (c);
377 }
378
379 static  void
380 make_mime_composition_file_entry(char *file_name, int attachformat)
381 {
382     int                 binary;                 /* binary character found flag */
383     int                 c;                      /* current character */
384     char                cmd[MAXPATHLEN + 6];    /* file command buffer */
385     char                *content_type;          /* mime content type */
386     FILE                *fp;                    /* content and pipe file pointer */
387     struct      node    *np;                    /* context scan node pointer */
388     char                *p;                     /* miscellaneous string pointer */
389     struct      stat    st;                     /* file status buffer */
390
391     content_type = (char *)0;
392
393     /*
394      *  Check the file name for a suffix.  Scan the context for that suffix on a
395      *  mhshow-suffix- entry.  We use these entries to be compatible with mhnshow,
396      *  and there's no reason to make the user specify each suffix twice.  Context
397      *  entries of the form "mhshow-suffix-contenttype" in the name have the suffix
398      *  in the field, including the dot.
399      */
400
401     if ((p = strrchr(file_name, '.')) != (char *)0) {
402         for (np = m_defs; np; np = np->n_next) {
403             if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0 && mh_strcasecmp(p, np->n_field) == 0) {
404                 content_type = np->n_name + 14;
405                 break;
406             }
407         }
408     }
409
410     /*
411      *  No content type was found, either because there was no matching entry in the
412      *  context or because the file name has no suffix.  Open the file and check for
413      *  non-ASCII characters.  Choose the content type based on this check.
414      */
415
416     if (content_type == (char *)0) {
417         if ((fp = fopen(file_name, "r")) == (FILE *)0) {
418             clean_up_temporary_files();
419             adios((char *)0, "unable to access file \"%s\"", file_name);
420         }
421
422         binary = 0;
423
424         while ((c = getc(fp)) != EOF) {
425             if (c > 127 || c < 0) {
426                 binary = 1;
427                 break;
428             }
429         }
430
431         (void)fclose(fp);
432
433         content_type = binary ? "application/octet-stream" : "text/plain";
434     }
435
436     /*
437      *  Make sure that the attachment file exists and is readable.  Append a mhbuild
438      *  directive to the draft file.  This starts with the content type.  Append a
439      *  file name attribute and a private x-unix-mode attribute.  Also append a
440      *  description obtained (if possible) by running the "file" command on the file.
441      */
442
443     if (stat(file_name, &st) == -1 || access(file_name, R_OK) != 0) {
444         clean_up_temporary_files();
445         adios((char *)0, "unable to access file \"%s\"", file_name);
446     }
447
448     switch (attachformat) {
449     case 0:
450         /* Insert name, file mode, and Content-Id. */
451         (void)fprintf(composition_file, "#%s; name=\"%s\"; x-unix-mode=0%.3ho",
452             content_type, ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1, (unsigned short)(st.st_mode & 0777));
453
454         if (strlen(file_name) > MAXPATHLEN) {
455             clean_up_temporary_files();
456             adios((char *)0, "attachment file name `%s' too long.", file_name);
457         }
458
459         (void)sprintf(cmd, "file '%s'", file_name);
460
461         if ((fp = popen(cmd, "r")) != (FILE *)0 && fgets(cmd, sizeof (cmd), fp) != (char *)0) {
462             *strchr(cmd, '\n') = '\0';
463
464             /*
465              *  The output of the "file" command is of the form
466              *
467              *          file:   description
468              *
469              *  Strip off the "file:" and subsequent white space.
470              */
471
472             for (p = cmd; *p != '\0'; p++) {
473                 if (*p == ':') {
474                     for (p++; *p != '\0'; p++) {
475                         if (*p != '\t')
476                             break;
477                     }
478                     break;
479                 }
480             }
481
482             if (*p != '\0')
483                 /* Insert Content-Description. */
484                 (void)fprintf(composition_file, " [ %s ]", p);
485
486             (void)pclose(fp);
487         }
488
489         break;
490     case 1:
491         if (stringdex (m_maildir(invo_name), file_name) == 0) {
492             /* Content had been placed by send into a temp file.
493                Don't generate Content-Disposition header, because
494                it confuses Microsoft Outlook, Build 10.0.6626, at
495                least. */
496             (void) fprintf (composition_file, "#%s <>", content_type);
497         } else {
498             /* Suppress Content-Id, insert simple Content-Disposition. */
499             (void) fprintf (composition_file,
500                             "#%s; name=\"%s\" <>{attachment}",
501                             content_type,
502                             ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1);
503         }
504
505         break;
506     case 2:
507         if (stringdex (m_maildir(invo_name), file_name) == 0) {
508             /* Content had been placed by send into a temp file.
509                Don't generate Content-Disposition header, because
510                it confuses Microsoft Outlook, Build 10.0.6626, at
511                least. */
512             (void) fprintf (composition_file, "#%s <>", content_type);
513         } else {
514             /* Suppress Content-Id, insert Content-Disposition with
515                modification date. */
516             (void) fprintf (composition_file,
517                             "#%s; name=\"%s\" <>{attachment; modification-date=\"%s\"}",
518                             content_type,
519                             ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1,
520                             dtime (&st.st_mtime, 0));
521         }
522
523         break;
524     default:
525         adios ((char *)0, "unsupported attachformat %d", attachformat);
526     }
527
528     /*
529      *  Finish up with the file name.
530      */
531
532     (void)fprintf(composition_file, " %s\n", file_name);
533
534     return;
535 }
536
537 /*
538  * Split large message into several messages of
539  * type "message/partial" and send them.
540  */
541
542 static int
543 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
544 {
545     int compnum, nparts, partno, state, status;
546     long pos, start;
547     time_t clock;
548     char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
549     char subject[BUFSIZ];
550     char name[NAMESZ], partnum[BUFSIZ];
551     FILE *in;
552
553     if ((in = fopen (drft, "r")) == NULL)
554         adios (drft, "unable to open for reading");
555
556     cp = dp = NULL;
557     start = 0L;
558
559     /*
560      * Scan through the message and examine the various header fields,
561      * as well as locate the beginning of the message body.
562      */
563     for (compnum = 1, state = FLD;;) {
564         switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
565             case FLD:
566             case FLDPLUS:
567             case FLDEOF:
568                 compnum++;
569
570                 /*
571                  * This header field is discarded.
572                  */
573                 if (!mh_strcasecmp (name, "Message-ID")) {
574                     while (state == FLDPLUS)
575                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
576                 } else if (uprf (name, XXX_FIELD_PRF)
577                         || !mh_strcasecmp (name, VRSN_FIELD)
578                         || !mh_strcasecmp (name, "Subject")
579                         || !mh_strcasecmp (name, "Encrypted")) {
580                     /*
581                      * These header fields are copied to the enclosed
582                      * header of the first message in the collection
583                      * of message/partials.  For the "Subject" header
584                      * field, we also record it, so that a modified
585                      * version of it, can be copied to the header
586                      * of each messsage/partial in the collection.
587                      */
588                     if (!mh_strcasecmp (name, "Subject")) {
589                         size_t sublen;
590
591                         strncpy (subject, buffer, BUFSIZ);
592                         sublen = strlen (subject);
593                         if (sublen > 0 && subject[sublen - 1] == '\n')
594                             subject[sublen - 1] = '\0';
595                     }
596
597                     dp = add (concat (name, ":", buffer, NULL), dp);
598                     while (state == FLDPLUS) {
599                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
600                         dp = add (buffer, dp);
601                     }
602                 } else {
603                     /*
604                      * These header fields are copied to the header of
605                      * each message/partial in the collection.
606                      */
607                     cp = add (concat (name, ":", buffer, NULL), cp);
608                     while (state == FLDPLUS) {
609                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
610                         cp = add (buffer, cp);
611                     }
612                 }
613
614                 if (state != FLDEOF) {
615                     start = ftell (in) + 1;
616                     continue;
617                 }
618                 /* else fall... */
619
620            case BODY:
621            case BODYEOF:
622            case FILEEOF:
623                 break;
624
625            case LENERR:
626            case FMTERR:
627                 adios (NULL, "message format error in component #%d", compnum);
628
629            default:
630                 adios (NULL, "getfld () returned %d", state);
631         }
632
633         break;
634     }
635     if (cp == NULL)
636         adios (NULL, "headers missing from draft");
637
638     nparts = 1;
639     pos = start;
640     while (fgets (buffer, sizeof(buffer) - 1, in)) {
641         long len;
642
643         if ((pos += (len = strlen (buffer))) > CPERMSG) {
644             nparts++;
645             pos = len;
646         }
647     }
648
649     /* Only one part, nothing to split */
650     if (nparts == 1) {
651         free (cp);
652         if (dp)
653             free (dp);
654
655         fclose (in);
656         return sendaux (vec, vecp, drft, st);
657     }
658
659     if (!pushsw) {
660         printf ("Sending as %d Partial Messages\n", nparts);
661         fflush (stdout);
662     }
663     status = OK;
664
665     vec[vecp++] = "-partno";
666     vec[vecp++] = partnum;
667     if (delay == 0)
668         vec[vecp++] = "-queued";
669
670     time (&clock);
671     snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
672                 (int) getpid(), (long) clock, LocalName());
673
674     fseek (in, start, SEEK_SET);
675     for (partno = 1; partno <= nparts; partno++) {
676         char tmpdrf[BUFSIZ];
677         FILE *out;
678
679         strncpy (tmpdrf, m_scratch (drft, invo_name), sizeof(tmpdrf));
680         if ((out = fopen (tmpdrf, "w")) == NULL)
681             adios (tmpdrf, "unable to open for writing");
682         chmod (tmpdrf, 0600);
683
684         /*
685          * Output the header fields
686          */
687         fputs (cp, out);
688         fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
689         fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
690         fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
691         fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
692         fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
693
694         /*
695          * If this is the first in the collection, output the
696          * header fields we are encapsulating at the beginning
697          * of the body of the first message.
698          */
699         if (partno == 1) {
700             if (dp)
701                 fputs (dp, out);
702             fprintf (out, "Message-ID: %s\n", msgid);
703             fprintf (out, "\n");
704         }
705
706         pos = 0;
707         for (;;) {
708             long len;
709
710             if (!fgets (buffer, sizeof(buffer) - 1, in)) {
711                 if (partno == nparts)
712                     break;
713                 adios (NULL, "premature eof");
714             }
715             
716             if ((pos += (len = strlen (buffer))) > CPERMSG) {
717                 fseek (in, -len, SEEK_CUR);
718                 break;
719             }
720
721             fputs (buffer, out);
722         }
723
724         if (fflush (out))
725             adios (tmpdrf, "error writing to");
726
727         fclose (out);
728
729         if (!pushsw && verbsw) {
730             printf ("\n");
731             fflush (stdout);
732         }
733
734         /* Pause here, if a delay is specified */
735         if (delay > 0 && 1 < partno && partno <= nparts) {
736             if (!pushsw) {
737                 printf ("pausing %d seconds before sending part %d...\n",
738                         delay, partno);
739                 fflush (stdout);
740             }
741             sleep ((unsigned int) delay);
742         }
743
744         snprintf (partnum, sizeof(partnum), "%d", partno);
745         status = sendaux (vec, vecp, tmpdrf, st);
746         unlink (tmpdrf);
747         if (status != OK)
748             break;
749
750         /*
751          * This is so sendaux will only annotate
752          * the altmsg the first time it is called.
753          */
754         annotext = NULL;
755     }
756
757     free (cp);
758     if (dp)
759         free (dp);
760
761     fclose (in);        /* close the draft */
762     return status;
763 }
764
765
766 /*
767  * Annotate original message, and
768  * call `postproc' to send message.
769  */
770
771 static int
772 sendaux (char **vec, int vecp, char *drft, struct stat *st)
773 {
774     pid_t child_id;
775     int i, status, fd, fd2;
776     char backup[BUFSIZ], buf[BUFSIZ];
777
778     fd = pushsw ? tmp_fd () : NOTOK;
779     fd2 = NOTOK;
780
781     vec[vecp++] = drft;
782     if (annotext) {
783         if ((fd2 = tmp_fd ()) != NOTOK) {
784             vec[vecp++] = "-idanno";
785             snprintf (buf, sizeof(buf), "%d", fd2);
786             vec[vecp++] = buf;
787         } else {
788             admonish (NULL, "unable to create file for annotation list");
789         }
790     }
791     if (distfile && distout (drft, distfile, backup) == NOTOK)
792         done (1);
793     vec[vecp] = NULL;
794
795     for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
796         sleep (5);
797
798     switch (child_id) {
799     case -1:
800         /* oops -- fork error */
801         adios ("fork", "unable to");
802         break;  /* NOT REACHED */
803
804     case 0:
805         /*
806          * child process -- send it
807          *
808          * If fd is ok, then we are pushing and fd points to temp
809          * file, so capture anything on stdout and stderr there.
810          */
811         if (fd != NOTOK) {
812             dup2 (fd, fileno (stdout));
813             dup2 (fd, fileno (stderr));
814             close (fd);
815         }
816         execvp (postproc, vec);
817         fprintf (stderr, "unable to exec ");
818         perror (postproc);
819         _exit (-1);
820         break;  /* NOT REACHED */
821
822     default:
823         /*
824          * parent process -- wait for it
825          */
826         if ((status = pidwait(child_id, NOTOK)) == OK) {
827             if (annotext && fd2 != NOTOK)
828                 anno (fd2, st);
829         } else {
830             /*
831              * If postproc failed, and we have good fd (which means
832              * we pushed), then mail error message (and possibly the
833              * draft) back to the user.
834              */
835             if (fd != NOTOK) {
836                 alert (drft, fd);
837                 close (fd);
838             } else {
839                 advise (NULL, "message not delivered to anyone");
840             }
841             if (annotext && fd2 != NOTOK)
842                 close (fd2);
843             if (distfile) {
844                 unlink (drft);
845                 if (rename (backup, drft) == NOTOK)
846                     advise (drft, "unable to rename %s to", backup);
847             }
848         }
849         break;
850     }
851
852     return status;
853 }
854
855
856 /*
857  * Mail error notification (and possibly a copy of the
858  * message) back to the user, using the mailproc
859  */
860
861 static void
862 alert (char *file, int out)
863 {
864     pid_t child_id;
865     int i, in;
866     char buf[BUFSIZ];
867
868     for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
869         sleep (5);
870
871     switch (child_id) {
872         case NOTOK:
873             /* oops -- fork error */
874             advise ("fork", "unable to");
875
876         case OK:
877             /* child process -- send it */
878             SIGNAL (SIGHUP, SIG_IGN);
879             SIGNAL (SIGINT, SIG_IGN);
880             SIGNAL (SIGQUIT, SIG_IGN);
881             SIGNAL (SIGTERM, SIG_IGN);
882             if (forwsw) {
883                 if ((in = open (file, O_RDONLY)) == NOTOK) {
884                     admonish (file, "unable to re-open");
885                 } else {
886                     lseek (out, (off_t) 0, SEEK_END);
887                     strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
888                     write (out, buf, strlen (buf));
889                     strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
890                     write (out, buf, strlen (buf));
891                     cpydgst (in, out, file, "temporary file");
892                     close (in);
893                     strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
894                     write (out, buf, strlen (buf));
895                     if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
896                         admonish (buf, "unable to rename %s to", file);
897                 }
898             }
899             lseek (out, (off_t) 0, SEEK_SET);
900             dup2 (out, fileno (stdin));
901             close (out);
902             /* create subject for error notification */
903             snprintf (buf, sizeof(buf), "send failed on %s",
904                         forwsw ? "enclosed draft" : file);
905
906             execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
907                     "-subject", buf, NULL);
908             fprintf (stderr, "unable to exec ");
909             perror (mailproc);
910             _exit (-1);
911
912         default:                /* no waiting... */
913             break;
914     }
915 }
916
917
918 static int
919 tmp_fd (void)
920 {
921     int fd;
922     char tmpfil[BUFSIZ];
923
924     strncpy (tmpfil, m_tmpfil (invo_name), sizeof(tmpfil));
925     if ((fd = open (tmpfil, O_RDWR | O_CREAT | O_TRUNC, 0600)) == NOTOK)
926         return NOTOK;
927     if (debugsw)
928         advise (NULL, "temporary file %s selected", tmpfil);
929     else
930         if (unlink (tmpfil) == NOTOK)
931             advise (tmpfil, "unable to remove");
932
933     return fd;
934 }
935
936
937 static void
938 anno (int fd, struct stat *st)
939 {
940     pid_t child_id;
941     sigset_t set, oset;
942     static char *cwd = NULL;
943     struct stat st2;
944
945     if (altmsg &&
946             (stat (altmsg, &st2) == NOTOK
947                 || st->st_mtime != st2.st_mtime
948                 || st->st_dev != st2.st_dev
949                 || st->st_ino != st2.st_ino)) {
950         if (debugsw)
951             admonish (NULL, "$mhaltmsg mismatch");
952         return;
953     }
954
955     child_id = debugsw ? NOTOK : fork ();
956     switch (child_id) {
957         case NOTOK:             /* oops */
958             if (!debugsw)
959                 advise (NULL,
960                             "unable to fork, so doing annotations by hand...");
961             if (cwd == NULL)
962                 cwd = getcpy (pwd ());
963
964         case OK: 
965             /* block a few signals */
966             sigemptyset (&set);
967             sigaddset (&set, SIGHUP);
968             sigaddset (&set, SIGINT);
969             sigaddset (&set, SIGQUIT);
970             sigaddset (&set, SIGTERM);
971             SIGPROCMASK (SIG_BLOCK, &set, &oset);
972
973             annoaux (fd);
974             if (child_id == OK)
975                 _exit (0);
976
977             /* reset the signal mask */
978             SIGPROCMASK (SIG_SETMASK, &oset, &set);
979
980             chdir (cwd);
981             break;
982
983         default:                /* no waiting... */
984             close (fd);
985             break;
986     }
987 }
988
989
990 static void
991 annoaux (int fd)
992 {
993     int fd2, fd3, msgnum;
994     char *cp, *folder, *maildir;
995     char buffer[BUFSIZ], **ap;
996     FILE *fp;
997     struct msgs *mp;
998
999     if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
1000         if (debugsw)
1001             admonish (NULL, "$mhfolder not set");
1002         return;
1003     }
1004     maildir = m_maildir (folder);
1005     if (chdir (maildir) == NOTOK) {
1006         if (debugsw)
1007             admonish (maildir, "unable to change directory to");
1008         return;
1009     }
1010     if (!(mp = folder_read (folder))) {
1011         if (debugsw)
1012             admonish (NULL, "unable to read folder %s", folder);
1013         return;
1014     }
1015
1016     /* check for empty folder */
1017     if (mp->nummsg == 0) {
1018         if (debugsw)
1019             admonish (NULL, "no messages in %s", folder);
1020         goto oops;
1021     }
1022
1023     if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
1024         if (debugsw)
1025             admonish (NULL, "$mhmessages not set");
1026         goto oops;
1027     }
1028     if (!debugsw                        /* MOBY HACK... */
1029             && pushsw
1030             && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
1031             && (fd2 = dup (fileno (stderr))) != NOTOK) {
1032         dup2 (fd3, fileno (stderr));
1033         close (fd3);
1034     }
1035     else
1036         fd2 = NOTOK;
1037     for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
1038         m_convert (mp, *ap);
1039     free (cp);
1040     if (fd2 != NOTOK)
1041         dup2 (fd2, fileno (stderr));
1042     if (mp->numsel == 0) {
1043         if (debugsw)
1044             admonish (NULL, "no messages to annotate");
1045         goto oops;
1046     }
1047
1048     lseek (fd, (off_t) 0, SEEK_SET);
1049     if ((fp = fdopen (fd, "r")) == NULL) {
1050         if (debugsw)
1051             admonish (NULL, "unable to fdopen annotation list");
1052         goto oops;
1053     }
1054     cp = NULL;
1055     while (fgets (buffer, sizeof(buffer), fp) != NULL)
1056         cp = add (buffer, cp);
1057     fclose (fp);
1058
1059     if (debugsw)
1060         advise (NULL, "annotate%s with %s: \"%s\"",
1061                 inplace ? " inplace" : "", annotext, cp);
1062     for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1063         if (is_selected(mp, msgnum)) {
1064             if (debugsw)
1065                 advise (NULL, "annotate message %d", msgnum);
1066             annotate (m_name (msgnum), annotext, cp, inplace, 1, -2, 0);
1067         }
1068     }
1069
1070     free (cp);
1071
1072 oops:
1073     folder_free (mp);   /* free folder/message structure */
1074 }
1075
1076
1077 static void
1078 armed_done (int status)
1079 {
1080     longjmp (env, status ? status : NOTOK);
1081
1082     exit (status);
1083 }