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