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