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