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