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