Added Content-Description header with the filename of the attachment, with attachform...
[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 TIME_WITH_SYS_TIME
20 # include <sys/time.h>
21 # include <time.h>
22 #else
23 # ifdef TM_IN_SYS_TIME
24 #  include <sys/time.h>
25 # else
26 #  include <time.h>
27 # endif
28 #endif
29
30 int debugsw = 0;                /* global */
31 int forwsw  = 1;
32 int inplace = 1;
33 int pushsw  = 0;
34 int splitsw = -1;
35 int unique  = 0;
36 int verbsw  = 0;
37
38 char *altmsg   = NULL;          /*  .. */
39 char *annotext = NULL;
40 char *distfile = NULL;
41
42 static jmp_buf env;
43
44 static  char    body_file_name[MAXPATHLEN + 1];         /* name of temporary file for body content */
45 static  char    composition_file_name[MAXPATHLEN + 1];  /* name of mhbuild composition temporary file */
46 static  int     field_size;                             /* size of header field buffer */
47 static  char    *field;                                 /* header field buffer */
48 static  FILE    *draft_file;                            /* draft file pointer */
49 static  FILE    *body_file;                             /* body file pointer */
50 static  FILE    *composition_file;                      /* composition file pointer */
51
52 /*
53  * external prototypes
54  */
55 int sendsbr (char **, int, char *, struct stat *, int, char *, int);
56 char *getusername (void);
57
58 /*
59  * static prototypes
60  */
61 static void armed_done (int) NORETURN;
62 static void alert (char *, int);
63 static int tmp_fd (void);
64 static void anno (int, struct stat *);
65 static void annoaux (int);
66 static int splitmsg (char **, int, char *, struct stat *, int);
67 static int sendaux (char **, int, char *, struct stat *);
68
69 static  int     attach(char *, char *, int);
70 static  void    clean_up_temporary_files(void);
71 static  int     get_line(void);
72 static  void    make_mime_composition_file_entry(char *, int);
73
74
75 /*
76  * Entry point into (back-end) routines to send message.
77  */
78
79 int
80 sendsbr (char **vec, int vecp, char *drft, struct stat *st, int rename_drft, char *attachment_header_field_name, int attachformat)
81 {
82     int status;
83     char buffer[BUFSIZ], file[BUFSIZ];
84     struct stat sts;
85     char        *original_draft;                /* name of original draft file */
86     char        *p;                             /* string pointer for building file name */
87
88     /*
89      *  Save the original name of the draft file.  The name of the draft file is changed
90      *  to a temporary file containing the built MIME message if there are attachments.
91      *  We need the original name so that it can be renamed after the message is sent.
92      */
93
94     original_draft = drft;
95
96     /*
97      *  There might be attachments if a header field name for attachments is supplied.
98      *  Convert the draft to a MIME message.  Use the mhbuild composition file for the
99      *  draft if there was a successful conversion because that now contains the MIME
100      *  message.  A nice side effect of this is that it leaves the original draft file
101      *  untouched so that it can be retrieved and modified if desired.
102      */
103
104     if (attachment_header_field_name != (char *)0) {
105         switch (attach(attachment_header_field_name, drft, attachformat)) {
106         case OK:
107             drft = composition_file_name;
108             break;
109
110         case NOTOK:
111             return (NOTOK);
112
113         case DONE:
114             break;
115         }
116     }
117
118     done=armed_done;
119     switch (setjmp (env)) {
120     case OK: 
121         /*
122          * If given -push and -unique (which is undocumented), then
123          * rename the draft file.  I'm not quite sure why.
124          */
125         if (pushsw && unique) {
126             char *cp = m_mktemp2(drft, invo_name, NULL, NULL);
127             if (cp == NULL) {
128                 adios ("sendsbr", "unable to create temporary file");
129             }
130             if (rename (drft, strncpy(file, cp, sizeof(file))) == 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     done=exit;
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,
258                   m_mktemp(m_maildir(invo_name), NULL, NULL),
259                   sizeof (body_file_name));
260     (void)strncpy(composition_file_name,
261                   m_mktemp(m_maildir(invo_name), NULL, NULL),
262                   sizeof (composition_file_name));
263
264     if (has_body)
265         body_file = fopen(body_file_name, "w");
266
267     composition_file = fopen(composition_file_name, "w");
268
269     if ((has_body && body_file == (FILE *)0) || composition_file == (FILE *)0) {
270         clean_up_temporary_files();
271         adios((char *)0, "unable to open all of the temporary files.");
272     }
273
274     /*
275      *  Start at the beginning of the draft file.  Copy all non-attachment header fields
276      *  to the temporary composition file.  Then add the dashed line separator.
277      */
278
279     rewind(draft_file);
280
281     while (get_line() != EOF && *field != '\0' && *field != '-')
282         if (strncasecmp(field, attachment_header_field_name, length) != 0 || field[length] != ':')
283             (void)fprintf(composition_file, "%s\n", field);
284
285     (void)fputs("--------\n", composition_file);
286
287     /*
288      *  Copy the message body to a temporary file.
289      */
290
291     if (has_body) {
292         while ((c = getc(draft_file)) != EOF)
293                 putc(c, body_file);
294
295         (void)fclose(body_file);
296     }
297
298     /*
299      *  Add a mhbuild MIME composition file line for the body if there was one.
300      */
301
302     if (has_body)
303         make_mime_composition_file_entry(body_file_name, attachformat);
304
305     /*
306      *  Now, go back to the beginning of the draft file and look for header fields
307      *  that specify attachments.  Add a mhbuild MIME composition file for each.
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[MAXPATHLEN + 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) > MAXPATHLEN) {
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             (void) fprintf (composition_file,
506                             "#%1$s; name=\"%2$s\" <> [%2$s]{attachment}",
507                             content_type,
508                             ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1);
509         }
510
511         break;
512     case 2:
513         if (stringdex (m_maildir(invo_name), file_name) == 0) {
514             /* Content had been placed by send into a temp file.
515                Don't generate Content-Disposition header, because
516                it confuses Microsoft Outlook, Build 10.0.6626, at
517                least. */
518             (void) fprintf (composition_file, "#%s <>", content_type);
519         } else {
520             /* Suppress Content-Id, insert Content-Disposition with
521                modification date and Content-Description wtih filename. */
522             (void) fprintf (composition_file,
523                             "#%1$s; name=\"%2$s\" <>[%2$s]{attachment; modification-date=\"%3$s\"}",
524                             content_type,
525                             ((p = strrchr(file_name, '/')) == (char *)0) ? file_name : p + 1,
526                             dtime (&st.st_mtime, 0));
527         }
528
529         break;
530     default:
531         adios ((char *)0, "unsupported attachformat %d", attachformat);
532     }
533
534     /*
535      *  Finish up with the file name.
536      */
537
538     (void)fprintf(composition_file, " %s\n", file_name);
539
540     return;
541 }
542
543 /*
544  * Split large message into several messages of
545  * type "message/partial" and send them.
546  */
547
548 static int
549 splitmsg (char **vec, int vecp, char *drft, struct stat *st, int delay)
550 {
551     int compnum, nparts, partno, state, status;
552     long pos, start;
553     time_t clock;
554     char *cp, *dp, buffer[BUFSIZ], msgid[BUFSIZ];
555     char subject[BUFSIZ];
556     char name[NAMESZ], partnum[BUFSIZ];
557     FILE *in;
558
559     if ((in = fopen (drft, "r")) == NULL)
560         adios (drft, "unable to open for reading");
561
562     cp = dp = NULL;
563     start = 0L;
564
565     /*
566      * Scan through the message and examine the various header fields,
567      * as well as locate the beginning of the message body.
568      */
569     for (compnum = 1, state = FLD;;) {
570         switch (state = m_getfld (state, name, buffer, sizeof(buffer), in)) {
571             case FLD:
572             case FLDPLUS:
573             case FLDEOF:
574                 compnum++;
575
576                 /*
577                  * This header field is discarded.
578                  */
579                 if (!mh_strcasecmp (name, "Message-ID")) {
580                     while (state == FLDPLUS)
581                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
582                 } else if (uprf (name, XXX_FIELD_PRF)
583                         || !mh_strcasecmp (name, VRSN_FIELD)
584                         || !mh_strcasecmp (name, "Subject")
585                         || !mh_strcasecmp (name, "Encrypted")) {
586                     /*
587                      * These header fields are copied to the enclosed
588                      * header of the first message in the collection
589                      * of message/partials.  For the "Subject" header
590                      * field, we also record it, so that a modified
591                      * version of it, can be copied to the header
592                      * of each messsage/partial in the collection.
593                      */
594                     if (!mh_strcasecmp (name, "Subject")) {
595                         size_t sublen;
596
597                         strncpy (subject, buffer, BUFSIZ);
598                         sublen = strlen (subject);
599                         if (sublen > 0 && subject[sublen - 1] == '\n')
600                             subject[sublen - 1] = '\0';
601                     }
602
603                     dp = add (concat (name, ":", buffer, NULL), dp);
604                     while (state == FLDPLUS) {
605                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
606                         dp = add (buffer, dp);
607                     }
608                 } else {
609                     /*
610                      * These header fields are copied to the header of
611                      * each message/partial in the collection.
612                      */
613                     cp = add (concat (name, ":", buffer, NULL), cp);
614                     while (state == FLDPLUS) {
615                         state = m_getfld (state, name, buffer, sizeof(buffer), in);
616                         cp = add (buffer, cp);
617                     }
618                 }
619
620                 if (state != FLDEOF) {
621                     start = ftell (in) + 1;
622                     continue;
623                 }
624                 /* else fall... */
625
626            case BODY:
627            case BODYEOF:
628            case FILEEOF:
629                 break;
630
631            case LENERR:
632            case FMTERR:
633                 adios (NULL, "message format error in component #%d", compnum);
634
635            default:
636                 adios (NULL, "getfld () returned %d", state);
637         }
638
639         break;
640     }
641     if (cp == NULL)
642         adios (NULL, "headers missing from draft");
643
644     nparts = 1;
645     pos = start;
646     while (fgets (buffer, sizeof(buffer) - 1, in)) {
647         long len;
648
649         if ((pos += (len = strlen (buffer))) > CPERMSG) {
650             nparts++;
651             pos = len;
652         }
653     }
654
655     /* Only one part, nothing to split */
656     if (nparts == 1) {
657         free (cp);
658         if (dp)
659             free (dp);
660
661         fclose (in);
662         return sendaux (vec, vecp, drft, st);
663     }
664
665     if (!pushsw) {
666         printf ("Sending as %d Partial Messages\n", nparts);
667         fflush (stdout);
668     }
669     status = OK;
670
671     vec[vecp++] = "-partno";
672     vec[vecp++] = partnum;
673     if (delay == 0)
674         vec[vecp++] = "-queued";
675
676     time (&clock);
677     snprintf (msgid, sizeof(msgid), "<%d.%ld@%s>",
678                 (int) getpid(), (long) clock, LocalName());
679
680     fseek (in, start, SEEK_SET);
681     for (partno = 1; partno <= nparts; partno++) {
682         char tmpdrf[BUFSIZ];
683         FILE *out;
684
685         char *cp = m_mktemp2(drft, invo_name, NULL, &out);
686         if (cp == NULL) {
687             adios (drft, "unable to create temporary file for");
688         }
689         strncpy(tmpdrf, cp, sizeof(tmpdrf));
690         chmod (tmpdrf, 0600);
691
692         /*
693          * Output the header fields
694          */
695         fputs (cp, out);
696         fprintf (out, "Subject: %s (part %d of %d)\n", subject, partno, nparts);
697         fprintf (out, "%s: %s\n", VRSN_FIELD, VRSN_VALUE);
698         fprintf (out, "%s: message/partial; id=\"%s\";\n", TYPE_FIELD, msgid);
699         fprintf (out, "\tnumber=%d; total=%d\n", partno, nparts);
700         fprintf (out, "%s: part %d of %d\n\n", DESCR_FIELD, partno, nparts);
701
702         /*
703          * If this is the first in the collection, output the
704          * header fields we are encapsulating at the beginning
705          * of the body of the first message.
706          */
707         if (partno == 1) {
708             if (dp)
709                 fputs (dp, out);
710             fprintf (out, "Message-ID: %s\n", msgid);
711             fprintf (out, "\n");
712         }
713
714         pos = 0;
715         for (;;) {
716             long len;
717
718             if (!fgets (buffer, sizeof(buffer) - 1, in)) {
719                 if (partno == nparts)
720                     break;
721                 adios (NULL, "premature eof");
722             }
723             
724             if ((pos += (len = strlen (buffer))) > CPERMSG) {
725                 fseek (in, -len, SEEK_CUR);
726                 break;
727             }
728
729             fputs (buffer, out);
730         }
731
732         if (fflush (out))
733             adios (tmpdrf, "error writing to");
734
735         fclose (out);
736
737         if (!pushsw && verbsw) {
738             printf ("\n");
739             fflush (stdout);
740         }
741
742         /* Pause here, if a delay is specified */
743         if (delay > 0 && 1 < partno && partno <= nparts) {
744             if (!pushsw) {
745                 printf ("pausing %d seconds before sending part %d...\n",
746                         delay, partno);
747                 fflush (stdout);
748             }
749             sleep ((unsigned int) delay);
750         }
751
752         snprintf (partnum, sizeof(partnum), "%d", partno);
753         status = sendaux (vec, vecp, tmpdrf, st);
754         unlink (tmpdrf);
755         if (status != OK)
756             break;
757
758         /*
759          * This is so sendaux will only annotate
760          * the altmsg the first time it is called.
761          */
762         annotext = NULL;
763     }
764
765     free (cp);
766     if (dp)
767         free (dp);
768
769     fclose (in);        /* close the draft */
770     return status;
771 }
772
773
774 /*
775  * Annotate original message, and
776  * call `postproc' to send message.
777  */
778
779 static int
780 sendaux (char **vec, int vecp, char *drft, struct stat *st)
781 {
782     pid_t child_id;
783     int i, status, fd, fd2;
784     char backup[BUFSIZ], buf[BUFSIZ];
785
786     fd = pushsw ? tmp_fd () : NOTOK;
787     fd2 = NOTOK;
788
789     vec[vecp++] = drft;
790     if (annotext) {
791         if ((fd2 = tmp_fd ()) != NOTOK) {
792             vec[vecp++] = "-idanno";
793             snprintf (buf, sizeof(buf), "%d", fd2);
794             vec[vecp++] = buf;
795         } else {
796             admonish (NULL, "unable to create file for annotation list");
797         }
798     }
799     if (distfile && distout (drft, distfile, backup) == NOTOK)
800         done (1);
801     vec[vecp] = NULL;
802
803     for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
804         sleep (5);
805
806     switch (child_id) {
807     case -1:
808         /* oops -- fork error */
809         adios ("fork", "unable to");
810         break;  /* NOT REACHED */
811
812     case 0:
813         /*
814          * child process -- send it
815          *
816          * If fd is ok, then we are pushing and fd points to temp
817          * file, so capture anything on stdout and stderr there.
818          */
819         if (fd != NOTOK) {
820             dup2 (fd, fileno (stdout));
821             dup2 (fd, fileno (stderr));
822             close (fd);
823         }
824         execvp (postproc, vec);
825         fprintf (stderr, "unable to exec ");
826         perror (postproc);
827         _exit (-1);
828         break;  /* NOT REACHED */
829
830     default:
831         /*
832          * parent process -- wait for it
833          */
834         if ((status = pidwait(child_id, NOTOK)) == OK) {
835             if (annotext && fd2 != NOTOK)
836                 anno (fd2, st);
837         } else {
838             /*
839              * If postproc failed, and we have good fd (which means
840              * we pushed), then mail error message (and possibly the
841              * draft) back to the user.
842              */
843             if (fd != NOTOK) {
844                 alert (drft, fd);
845                 close (fd);
846             } else {
847                 advise (NULL, "message not delivered to anyone");
848             }
849             if (annotext && fd2 != NOTOK)
850                 close (fd2);
851             if (distfile) {
852                 unlink (drft);
853                 if (rename (backup, drft) == NOTOK)
854                     advise (drft, "unable to rename %s to", backup);
855             }
856         }
857         break;
858     }
859
860     return status;
861 }
862
863
864 /*
865  * Mail error notification (and possibly a copy of the
866  * message) back to the user, using the mailproc
867  */
868
869 static void
870 alert (char *file, int out)
871 {
872     pid_t child_id;
873     int i, in;
874     char buf[BUFSIZ];
875
876     for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
877         sleep (5);
878
879     switch (child_id) {
880         case NOTOK:
881             /* oops -- fork error */
882             advise ("fork", "unable to");
883
884         case OK:
885             /* child process -- send it */
886             SIGNAL (SIGHUP, SIG_IGN);
887             SIGNAL (SIGINT, SIG_IGN);
888             SIGNAL (SIGQUIT, SIG_IGN);
889             SIGNAL (SIGTERM, SIG_IGN);
890             if (forwsw) {
891                 if ((in = open (file, O_RDONLY)) == NOTOK) {
892                     admonish (file, "unable to re-open");
893                 } else {
894                     lseek (out, (off_t) 0, SEEK_END);
895                     strncpy (buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
896                     write (out, buf, strlen (buf));
897                     strncpy (buf, "\n------- Unsent Draft\n\n", sizeof(buf));
898                     write (out, buf, strlen (buf));
899                     cpydgst (in, out, file, "temporary file");
900                     close (in);
901                     strncpy (buf, "\n------- End of Unsent Draft\n", sizeof(buf));
902                     write (out, buf, strlen (buf));
903                     if (rename (file, strncpy (buf, m_backup (file), sizeof(buf))) == NOTOK)
904                         admonish (buf, "unable to rename %s to", file);
905                 }
906             }
907             lseek (out, (off_t) 0, SEEK_SET);
908             dup2 (out, fileno (stdin));
909             close (out);
910             /* create subject for error notification */
911             snprintf (buf, sizeof(buf), "send failed on %s",
912                         forwsw ? "enclosed draft" : file);
913
914             execlp (mailproc, r1bindex (mailproc, '/'), getusername (),
915                     "-subject", buf, NULL);
916             fprintf (stderr, "unable to exec ");
917             perror (mailproc);
918             _exit (-1);
919
920         default:                /* no waiting... */
921             break;
922     }
923 }
924
925
926 static int
927 tmp_fd (void)
928 {
929     int fd;
930     char *tfile = NULL;
931
932     tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
933     if (tfile == NULL) return NOTOK;
934     fchmod(fd, 0600);
935
936     if (debugsw)
937         advise (NULL, "temporary file %s selected", tfile);
938     else
939         if (unlink (tfile) == NOTOK)
940             advise (tfile, "unable to remove");
941
942     return fd;
943 }
944
945
946 static void
947 anno (int fd, struct stat *st)
948 {
949     pid_t child_id;
950     sigset_t set, oset;
951     static char *cwd = NULL;
952     struct stat st2;
953
954     if (altmsg &&
955             (stat (altmsg, &st2) == NOTOK
956                 || st->st_mtime != st2.st_mtime
957                 || st->st_dev != st2.st_dev
958                 || st->st_ino != st2.st_ino)) {
959         if (debugsw)
960             admonish (NULL, "$mhaltmsg mismatch");
961         return;
962     }
963
964     child_id = debugsw ? NOTOK : fork ();
965     switch (child_id) {
966         case NOTOK:             /* oops */
967             if (!debugsw)
968                 advise (NULL,
969                             "unable to fork, so doing annotations by hand...");
970             if (cwd == NULL)
971                 cwd = getcpy (pwd ());
972
973         case OK: 
974             /* block a few signals */
975             sigemptyset (&set);
976             sigaddset (&set, SIGHUP);
977             sigaddset (&set, SIGINT);
978             sigaddset (&set, SIGQUIT);
979             sigaddset (&set, SIGTERM);
980             SIGPROCMASK (SIG_BLOCK, &set, &oset);
981
982             annoaux (fd);
983             if (child_id == OK)
984                 _exit (0);
985
986             /* reset the signal mask */
987             SIGPROCMASK (SIG_SETMASK, &oset, &set);
988
989             chdir (cwd);
990             break;
991
992         default:                /* no waiting... */
993             close (fd);
994             break;
995     }
996 }
997
998
999 static void
1000 annoaux (int fd)
1001 {
1002     int fd2, fd3, msgnum;
1003     char *cp, *folder, *maildir;
1004     char buffer[BUFSIZ], **ap;
1005     FILE *fp;
1006     struct msgs *mp;
1007
1008     if ((folder = getenv ("mhfolder")) == NULL || *folder == 0) {
1009         if (debugsw)
1010             admonish (NULL, "$mhfolder not set");
1011         return;
1012     }
1013     maildir = m_maildir (folder);
1014     if (chdir (maildir) == NOTOK) {
1015         if (debugsw)
1016             admonish (maildir, "unable to change directory to");
1017         return;
1018     }
1019     if (!(mp = folder_read (folder))) {
1020         if (debugsw)
1021             admonish (NULL, "unable to read folder %s", folder);
1022         return;
1023     }
1024
1025     /* check for empty folder */
1026     if (mp->nummsg == 0) {
1027         if (debugsw)
1028             admonish (NULL, "no messages in %s", folder);
1029         goto oops;
1030     }
1031
1032     if ((cp = getenv ("mhmessages")) == NULL || *cp == 0) {
1033         if (debugsw)
1034             admonish (NULL, "$mhmessages not set");
1035         goto oops;
1036     }
1037     if (!debugsw                        /* MOBY HACK... */
1038             && pushsw
1039             && (fd3 = open ("/dev/null", O_RDWR)) != NOTOK
1040             && (fd2 = dup (fileno (stderr))) != NOTOK) {
1041         dup2 (fd3, fileno (stderr));
1042         close (fd3);
1043     }
1044     else
1045         fd2 = NOTOK;
1046     for (ap = brkstring (cp = getcpy (cp), " ", NULL); *ap; ap++)
1047         m_convert (mp, *ap);
1048     free (cp);
1049     if (fd2 != NOTOK)
1050         dup2 (fd2, fileno (stderr));
1051     if (mp->numsel == 0) {
1052         if (debugsw)
1053             admonish (NULL, "no messages to annotate");
1054         goto oops;
1055     }
1056
1057     lseek (fd, (off_t) 0, SEEK_SET);
1058     if ((fp = fdopen (fd, "r")) == NULL) {
1059         if (debugsw)
1060             admonish (NULL, "unable to fdopen annotation list");
1061         goto oops;
1062     }
1063     cp = NULL;
1064     while (fgets (buffer, sizeof(buffer), fp) != NULL)
1065         cp = add (buffer, cp);
1066     fclose (fp);
1067
1068     if (debugsw)
1069         advise (NULL, "annotate%s with %s: \"%s\"",
1070                 inplace ? " inplace" : "", annotext, cp);
1071     for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
1072         if (is_selected(mp, msgnum)) {
1073             if (debugsw)
1074                 advise (NULL, "annotate message %d", msgnum);
1075             annotate (m_name (msgnum), annotext, cp, inplace, 1, -2, 0);
1076         }
1077     }
1078
1079     free (cp);
1080
1081 oops:
1082     folder_free (mp);   /* free folder/message structure */
1083 }
1084
1085
1086 static void
1087 armed_done (int status)
1088 {
1089     longjmp (env, status ? status : NOTOK);
1090
1091     exit (status);
1092 }