Fixed make_bcc_file () to use contents of From: in draft, if draft_from masquerade...
[mmh] / uip / whatnowsbr.c
1
2 /*
3  * whatnowsbr.c -- the WhatNow shell
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  *  Several options have been added to ease the inclusion of attachments
12  *  using the header field name mechanism added to anno and send.  The
13  *  -attach option is used to specify the header field name for attachments.
14  *
15  *  Several commands have been added at the whatnow prompt:
16  *
17  *      cd [ directory ]        This option works just like the shell's
18  *                              cd command and lets the user change the
19  *                              directory from which attachments are
20  *                              taken so that long path names are not
21  *                              needed with every file.
22  *
23  *      ls [ ls-options ]       This option works just like the normal
24  *                              ls command and exists to allow the user
25  *                              to verify file names in the directory.
26  *
27  *      pwd                     This option works just like the normal
28  *                              pwd command and exists to allow the user
29  *                              to verify the directory.
30  *
31  *      attach files            This option attaches the named files to
32  *                              the draft.
33  *
34  *      alist [-ln]             This option lists the attachments on the
35  *                              draft.  -l gets long listings, -n gets
36  *                              numbered listings.
37  *
38  *      detach files            This option removes attachments from the
39  *      detach -n numbers       draft.  This can be done by file name or
40  *                              by attachment number.
41  */
42
43 #include <h/mh.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <h/mime.h>
47 #include <h/utils.h>
48
49 static struct swit whatnowswitches[] = {
50 #define DFOLDSW                 0
51     { "draftfolder +folder", 0 },
52 #define DMSGSW                  1
53     { "draftmessage msg", 0 },
54 #define NDFLDSW                 2
55     { "nodraftfolder", 0 },
56 #define EDITRSW                 3
57     { "editor editor", 0 },
58 #define NEDITSW                 4
59     { "noedit", 0 },
60 #define PRMPTSW                 5
61     { "prompt string", 4 },
62 #define VERSIONSW               6
63     { "version", 0 },
64 #define HELPSW                  7
65     { "help", 0 },
66 #define ATTACHSW                8
67     { "attach header-field-name", 0 },
68     { NULL, 0 }
69 };
70
71 /*
72  * Options at the "whatnow" prompt
73  */
74 static struct swit aleqs[] = {
75 #define EDITSW                         0
76     { "edit [<editor> <switches>]", 0 },
77 #define REFILEOPT                      1
78     { "refile [<switches>] +folder", 0 },
79 #define BUILDMIMESW                    2
80     { "mime [<switches>]", 0 },
81 #define DISPSW                         3
82     { "display [<switches>]", 0 },
83 #define LISTSW                         4
84     { "list [<switches>]", 0 },
85 #define SENDSW                         5
86     { "send [<switches>]", 0 },
87 #define PUSHSW                         6
88     { "push [<switches>]", 0 },
89 #define WHOMSW                         7
90     { "whom [<switches>]", 0 },
91 #define QUITSW                         8
92     { "quit [-delete]", 0 },
93 #define DELETESW                       9
94     { "delete", 0 },
95 #define CDCMDSW                       10
96     { "cd [directory]", 0 },
97 #define PWDCMDSW                      11
98     { "pwd", 0 },
99 #define LSCMDSW                       12
100     { "ls", 0 },
101 #define ATTACHCMDSW                   13
102     { "attach", 0 },
103 #define DETACHCMDSW                   14
104     { "detach [-n]", 2 },
105 #define ALISTCMDSW                    15
106     { "alist [-ln] ", 2 },
107     { NULL, 0 }
108 };
109
110 static char *myprompt = "\nWhat now? ";
111
112 /*
113  * static prototypes
114  */
115 static int editfile (char **, char **, char *, int, struct msgs *,
116         char *, char *, int);
117 static int sendfile (char **, char *, int);
118 static void sendit (char *, char **, char *, int);
119 static int buildfile (char **, char *);
120 static int check_draft (char *);
121 static int whomfile (char **, char *);
122 static int removefile (char *);
123
124 #ifdef HAVE_LSTAT
125 static int copyf (char *, char *);
126 #endif
127
128
129 int
130 WhatNow (int argc, char **argv)
131 {
132     int isdf = 0, nedit = 0, use = 0;
133     char *cp, *dfolder = NULL, *dmsg = NULL;
134     char *ed = NULL, *drft = NULL, *msgnam = NULL;
135     char buf[BUFSIZ], prompt[BUFSIZ];
136     char **argp, **arguments;
137     struct stat st;
138     char        *attach = (char *)0;    /* attachment header field name */
139     char        cwd[MAXPATHLEN + 1];    /* current working directory */
140     char        file[MAXPATHLEN + 1];   /* file name buffer */
141     char        shell[MAXPATHLEN + 1];  /* shell response buffer */
142     FILE        *f;                     /* read pointer for bgnd proc */
143     char        *l;                     /* set on -l to alist  command */
144     int         n;                      /* set on -n to alist command */
145
146     invo_name = r1bindex (argv[0], '/');
147
148     /* read user profile/context */
149     context_read();
150
151     arguments = getarguments (invo_name, argc, argv, 1);
152     argp = arguments;
153
154     /*
155      *  Get the initial current working directory.
156      */
157
158     if (getcwd(cwd, sizeof (cwd)) == (char *)0) {
159         adios("getcwd", "could not get working directory");
160     }
161
162     while ((cp = *argp++)) {
163         if (*cp == '-') {
164             switch (smatch (++cp, whatnowswitches)) {
165             case AMBIGSW:
166                 ambigsw (cp, whatnowswitches);
167                 done (1);
168             case UNKWNSW:
169                 adios (NULL, "-%s unknown", cp);
170
171             case HELPSW:
172                 snprintf (buf, sizeof(buf), "%s [switches] [file]", invo_name);
173                 print_help (buf, whatnowswitches, 1);
174                 done (1);
175             case VERSIONSW:
176                 print_version(invo_name);
177                 done (1);
178
179             case DFOLDSW:
180                 if (dfolder)
181                     adios (NULL, "only one draft folder at a time!");
182                 if (!(cp = *argp++) || *cp == '-')
183                     adios (NULL, "missing argument to %s", argp[-2]);
184                 dfolder = path (*cp == '+' || *cp == '@' ? cp + 1 : cp,
185                                 *cp != '@' ? TFOLDER : TSUBCWF);
186                 continue;
187             case DMSGSW:
188                 if (dmsg)
189                     adios (NULL, "only one draft message at a time!");
190                 if (!(dmsg = *argp++) || *dmsg == '-')
191                     adios (NULL, "missing argument to %s", argp[-2]);
192                 continue;
193             case NDFLDSW:
194                 dfolder = NULL;
195                 isdf = NOTOK;
196                 continue;
197
198             case EDITRSW:
199                 if (!(ed = *argp++) || *ed == '-')
200                     adios (NULL, "missing argument to %s", argp[-2]);
201                 nedit = 0;
202                 continue;
203             case NEDITSW:
204                 nedit++;
205                 continue;
206
207             case PRMPTSW:
208                 if (!(myprompt = *argp++) || *myprompt == '-')
209                     adios (NULL, "missing argument to %s", argp[-2]);
210                 continue;
211
212             case ATTACHSW:
213                 if (attach != (char *)0)
214                     adios(NULL, "only one attachment header field name at a time!");
215                 if (!(attach = *argp++) || *attach == '-')
216                     adios (NULL, "missing argument to %s", argp[-2]);
217                 continue;
218             }
219         }
220         if (drft)
221             adios (NULL, "only one draft at a time!");
222         else
223             drft = cp;
224     }
225
226     if ((drft == NULL && (drft = getenv ("mhdraft")) == NULL) || *drft == 0)
227         drft = getcpy (m_draft (dfolder, dmsg, 1, &isdf));
228
229     msgnam = (cp = getenv ("mhaltmsg")) && *cp ? getcpy (cp) : NULL;
230
231     if ((cp = getenv ("mhuse")) && *cp)
232         use = atoi (cp);
233
234     if (ed == NULL && ((ed = getenv ("mheditor")) == NULL || *ed == 0)) {
235         ed = NULL;
236         nedit++;
237     }
238
239     /* start editing the draft, unless -noedit was given */
240     if (!nedit && editfile (&ed, NULL, drft, use, NULL, msgnam, NULL, 1) < 0)
241         done (1);
242
243     snprintf (prompt, sizeof(prompt), myprompt, invo_name);
244     for (;;) {
245         if (!(argp = getans (prompt, aleqs))) {
246             unlink (LINK);
247             done (1);
248         }
249         switch (smatch (*argp, aleqs)) {
250         case DISPSW:
251             /* display the message being replied to, or distributed */
252             if (msgnam)
253                 showfile (++argp, msgnam);
254             else
255                 advise (NULL, "no alternate message to display");
256             break;
257
258         case BUILDMIMESW:
259             /* Translate MIME composition file */
260             buildfile (++argp, drft);
261             break;
262
263         case EDITSW:
264             /* Call an editor on the draft file */
265             if (*++argp)
266                 ed = *argp++;
267             if (editfile (&ed, argp, drft, NOUSE, NULL, msgnam, NULL, 1) == NOTOK)
268                 done (1);
269             break;
270
271         case LISTSW:
272             /* display the draft file */
273             showfile (++argp, drft);
274             break;
275
276         case WHOMSW:
277             /* Check to whom the draft would be sent */
278             whomfile (++argp, drft);
279             break;
280
281         case QUITSW:
282             /* Quit, and possibly delete the draft */
283             if (*++argp && (*argp[0] == 'd' ||
284                 ((*argp)[0] == '-' && (*argp)[1] == 'd'))) {
285                 removefile (drft);
286             } else {
287                 if (stat (drft, &st) != NOTOK)
288                     advise (NULL, "draft left on %s", drft);
289             }
290             done (1);
291
292         case DELETESW:
293             /* Delete draft and exit */
294             removefile (drft);
295             done (1);
296
297         case PUSHSW:
298             /* Send draft in background */
299             if (sendfile (++argp, drft, 1))
300                 done (1);
301             break;
302
303         case SENDSW:
304             /* Send draft */
305             sendfile (++argp, drft, 0);
306             break;
307
308         case REFILEOPT:
309             /* Refile the draft */
310             if (refile (++argp, drft) == 0)
311                 done (0);
312             break;
313
314         case CDCMDSW:
315             /* Change the working directory for attachments
316              *
317              *  Run the directory through the user's shell so that
318              *  we can take advantage of any syntax that the user
319              *  is accustomed to.  Read back the absolute path.
320              */
321
322             if (*++argp == (char *)0) {
323                 (void)sprintf(buf, "$SHELL -c \"cd;pwd\"");
324             }
325             else if (strlen(*argp) >= BUFSIZ) {
326                 adios((char *)0, "arguments too long");
327             }
328             else {
329                 (void)sprintf(buf, "$SHELL -c \"cd %s;cd %s;pwd\"", cwd, *argp);
330             }
331             if ((f = popen(buf, "r")) != (FILE *)0) {
332                 fgets(cwd, sizeof (cwd), f);
333
334                 if (strchr(cwd, '\n') != (char *)0)
335                         *strchr(cwd, '\n') = '\0';
336
337                 pclose(f);
338             }
339             else {
340                 advise("popen", "could not get directory");
341             }
342
343             break;
344
345         case PWDCMDSW:
346             /* Print the working directory for attachments */
347             printf("%s\n", cwd);
348             break;
349
350         case LSCMDSW:
351             /* List files in the current attachment working directory
352              *
353              *  Use the user's shell so that we can take advantage of any
354              *  syntax that the user is accustomed to.
355              */
356
357             cp = buf + sprintf(buf, "$SHELL -c \" cd %s;ls", cwd);
358
359             while (*++argp != (char *)0) {
360                 if (cp + strlen(*argp) + 2 >= buf + BUFSIZ)
361                     adios((char *)0, "arguments too long");
362
363                 cp += sprintf(cp, " %s", *argp);
364             }
365
366             (void)strcat(cp, "\"");
367             (void)system(buf);
368             break;
369
370         case ALISTCMDSW:
371             /*
372              *  List attachments on current draft.  Options are:
373              *
374              *   -l     long listing (full path names)
375              *   -n     numbers listing
376              */
377
378             if (attach == (char *)0) {
379                 advise((char *)0, "can't list because no header field name was given.");
380                 break;
381             }
382
383             l = (char *)0;
384             n = 0;
385
386             while (*++argp != (char *)0) {
387                 if (strcmp(*argp, "-l") == 0)
388                     l = "/";
389
390                 else if (strcmp(*argp, "-n") == 0)
391                     n = 1;
392
393                 else if (strcmp(*argp, "-ln") == 0 || strcmp(*argp, "-nl") == 0) {
394                     l = "/";
395                     n = 1;
396                 }
397
398                 else {
399                     n = -1;
400                     break;
401                 }
402             }
403
404             if (n == -1)
405                 advise((char *)0, "usage is alist [-ln].");
406
407             else
408                 annolist(drft, attach, l, n);
409
410             break;
411
412         case ATTACHCMDSW:
413             /*
414              *  Attach files to current draft.
415              */
416
417             if (attach == (char *)0) {
418                 advise((char *)0, "can't attach because no header field name was given.");
419                 break;
420             }
421
422             /*
423              *  Build a command line that causes the user's shell to list the file name
424              *  arguments.  This handles and wildcard expansion, tilde expansion, etc.
425              */
426
427             cp = buf + sprintf(buf, "$SHELL -c \" cd %s;ls", cwd);
428
429             while (*++argp != (char *)0) {
430                 if (cp + strlen(*argp) + 3 >= buf + BUFSIZ)
431                     adios((char *)0, "arguments too long");
432
433                 cp += sprintf(cp, " %s", *argp);
434             }
435
436             (void)strcat(cp, "\"");
437
438             /*
439              *  Read back the response from the shell, which contains a number of lines
440              *  with one file name per line.  Remove off the newline.  Determine whether
441              *  we have an absolute or relative path name.  Prepend the current working
442              *  directory to relative path names.  Add the attachment annotation to the
443              *  draft.
444              */
445
446             if ((f = popen(buf, "r")) != (FILE *)0) {
447                 while (fgets(shell, sizeof (shell), f) != (char *)0) {
448                     *(strchr(shell, '\n')) = '\0';
449
450                     if (*shell == '/')
451                         (void)annotate(drft, attach, shell, 1, 0, -2, 1);
452                     else {
453                         (void)sprintf(file, "%s/%s", cwd, shell);
454                         (void)annotate(drft, attach, file, 1, 0, -2, 1);
455                     }
456                 }
457
458                 pclose(f);
459             }
460             else {
461                 advise("popen", "could not get file from shell");
462             }
463
464             break;
465
466         case DETACHCMDSW:
467             /*
468              *  Detach files from current draft.
469              */
470
471             if (attach == (char *)0) {
472                 advise((char *)0, "can't detach because no header field name was given.");
473                 break;
474             }
475
476             /*
477              *  Scan the arguments for a -n.  Mixed file names and numbers aren't allowed,
478              *  so this catches a -n anywhere in the argument list.
479              */
480
481             for (n = 0, arguments = argp + 1; *arguments != (char *)0; arguments++) {
482                 if (strcmp(*arguments, "-n") == 0) {
483                         n = 1;
484                         break;
485                 }
486             }
487
488             /*
489              *  A -n was found so interpret the arguments as attachment numbers.
490              *  Decrement any remaining argument number that is greater than the one
491              *  just processed after processing each one so that the numbering stays
492              *  correct.
493              */
494
495             if (n == 1) {
496                 for (arguments = argp + 1; *arguments != (char *)0; arguments++) {
497                     if (strcmp(*arguments, "-n") == 0)
498                         continue;
499
500                     if (**arguments != '\0') {
501                         n = atoi(*arguments);
502                         (void)annotate(drft, attach, (char *)0, 1, 0, n, 1);
503
504                         for (argp = arguments + 1; *argp != (char *)0; argp++) {
505                             if (atoi(*argp) > n) {
506                                 if (atoi(*argp) == 1)
507                                     *argp = "";
508                                 else
509                                     (void)sprintf(*argp, "%d", atoi(*argp) - 1);
510                             }
511                         }
512                     }
513                 }
514             }
515
516             /*
517              *  The arguments are interpreted as file names.  Run them through the
518              *  user's shell for wildcard expansion and other goodies.  Do this from
519              *  the current working directory if the argument is not an absolute path
520              *  name (does not begin with a /).
521              */
522
523             else {
524                 for (arguments = argp + 1; *arguments != (char *)0; arguments++) {
525                     if (**arguments == '/') {
526                         if (strlen(*arguments) + sizeof ("$SHELL -c \"ls \"") >= sizeof (buf))
527                             adios((char *)0, "arguments too long");
528
529                         (void)sprintf(buf, "$SHELL -c \"ls %s\"", *arguments);
530                     }
531                     else {
532                         if (strlen(cwd) + strlen(*arguments) + sizeof ("$SHELL -c \" cd ; ls \"") >= sizeof (buf))
533                             adios((char *)0, "arguments too long");
534
535                         (void)sprintf(buf, "$SHELL -c \" cd %s;ls %s\"", cwd, *arguments);
536                     }
537
538                     if ((f = popen(buf, "r")) != (FILE *)0) {
539                         while (fgets(shell, sizeof (cwd), f) != (char *)0) {
540                             *(strchr(shell, '\n')) = '\0';
541                             (void)annotate(drft, attach, shell, 1, 0, 0, 1);
542                         }
543
544                         pclose(f);
545                     }
546                     else {
547                         advise("popen", "could not get file from shell");
548                     }
549                 }
550             }
551
552             break;
553
554         default:
555             /* Unknown command */
556             advise (NULL, "say what?");
557             break;
558         }
559     }
560     /*NOTREACHED*/
561 }
562
563 /*
564  * EDIT
565  */
566
567 static int  reedit = 0;         /* have we been here before?     */
568 static char *edsave = NULL;     /* the editor we used previously */
569
570
571 static int
572 editfile (char **ed, char **arg, char *file, int use, struct msgs *mp,
573           char *altmsg, char *cwd, int save_editor)
574 {
575     int pid, status, vecp;
576     char altpath[BUFSIZ], linkpath[BUFSIZ];
577     char *cp, *vec[MAXARGS];
578     struct stat st;
579
580 #ifdef HAVE_LSTAT
581     int slinked;
582 #if 0
583     int oumask; /* PJS: for setting permissions on symlinks. */
584 #endif
585 #endif /* HAVE_LSTAT */
586
587     /* Was there a previous edit session? */
588     if (reedit) {
589         if (!*ed) {             /* no explicit editor      */
590             *ed = edsave;       /* so use the previous one */
591             if ((cp = r1bindex (*ed, '/')) == NULL)
592                 cp = *ed;
593
594             /* unless we've specified it via "editor-next" */
595             cp = concat (cp, "-next", NULL);
596             if ((cp = context_find (cp)) != NULL)
597                 *ed = cp;
598         }
599     } else {
600         /* set initial editor */
601         if (*ed == NULL && (*ed = context_find ("editor")) == NULL)
602             *ed = defaulteditor;
603     }
604
605     if (altmsg) {
606         if (mp == NULL || *altmsg == '/' || cwd == NULL)
607             strncpy (altpath, altmsg, sizeof(altpath));
608         else
609             snprintf (altpath, sizeof(altpath), "%s/%s", mp->foldpath, altmsg);
610         if (cwd == NULL)
611             strncpy (linkpath, LINK, sizeof(linkpath));
612         else
613             snprintf (linkpath, sizeof(linkpath), "%s/%s", cwd, LINK);
614     }
615
616     if (altmsg) {
617         unlink (linkpath);
618 #ifdef HAVE_LSTAT
619         if (link (altpath, linkpath) == NOTOK) {
620 #if 0
621             /* I don't think permission on symlinks matters /JLR */
622             oumask = umask(0044);       /* PJS: else symlinks are world 'r' */
623 #endif
624             symlink (altpath, linkpath);
625 #if 0
626             umask(oumask);              /* PJS: else symlinks are world 'r' */
627 #endif
628             slinked = 1;
629         } else {
630             slinked = 0;
631         }
632 #else /* not HAVE_LSTAT */
633         link (altpath, linkpath);
634 #endif /* not HAVE_LSTAT */
635     }
636
637     context_save ();    /* save the context file */
638     fflush (stdout);
639
640     switch (pid = vfork ()) {
641         case NOTOK:
642             advise ("fork", "unable to");
643             status = NOTOK;
644             break;
645
646         case OK:
647             if (cwd)
648                 chdir (cwd);
649             if (altmsg) {
650                 if (mp)
651                     m_putenv ("mhfolder", mp->foldpath);
652                 m_putenv ("editalt", altpath);
653             }
654
655             vecp = 0;
656             vec[vecp++] = r1bindex (*ed, '/');
657             if (arg)
658                 while (*arg)
659                     vec[vecp++] = *arg++;
660             vec[vecp++] = file;
661             vec[vecp] = NULL;
662
663             execvp (*ed, vec);
664             fprintf (stderr, "unable to exec ");
665             perror (*ed);
666             _exit (-1);
667
668         default:
669             if ((status = pidwait (pid, NOTOK))) {
670 #ifdef ATTVIBUG
671                 if ((cp = r1bindex (*ed, '/'))
672                         && strcmp (cp, "vi") == 0
673                         && (status & 0x00ff) == 0)
674                     status = 0;
675                 else {
676 #endif
677                 if (((status & 0xff00) != 0xff00)
678                     && (!reedit || (status & 0x00ff))) {
679                     if (!use && (status & 0xff00) &&
680                             (rename (file, cp = m_backup (file)) != NOTOK)) {
681                         advise (NULL, "problems with edit--draft left in %s", cp);
682                     } else {
683                         advise (NULL, "problems with edit--%s preserved", file);
684                     }
685                 }
686                 status = -2;    /* maybe "reedit ? -2 : -1"? */
687                 break;
688 #ifdef ATTVIBUG
689                 }
690 #endif
691             }
692
693             reedit++;
694 #ifdef HAVE_LSTAT
695             if (altmsg
696                     && mp
697                     && !is_readonly(mp)
698                     && (slinked
699                            ? lstat (linkpath, &st) != NOTOK
700                                 && S_ISREG(st.st_mode)
701                                 && copyf (linkpath, altpath) == NOTOK
702                            : stat (linkpath, &st) != NOTOK
703                                 && st.st_nlink == 1
704                                 && (unlink (altpath) == NOTOK
705                                         || link (linkpath, altpath) == NOTOK)))
706                 advise (linkpath, "unable to update %s from", altmsg);
707 #else /* HAVE_LSTAT */
708             if (altmsg
709                     && mp
710                     && !is_readonly(mp)
711                     && stat (linkpath, &st) != NOTOK
712                     && st.st_nlink == 1
713                     && (unlink (altpath) == NOTOK
714                         || link (linkpath, altpath) == NOTOK))
715                 advise (linkpath, "unable to update %s from", altmsg);
716 #endif /* HAVE_LSTAT */
717     }
718
719     /* normally, we remember which editor we used */
720     if (save_editor)
721         edsave = getcpy (*ed);
722
723     *ed = NULL;
724     if (altmsg)
725         unlink (linkpath);
726
727     return status;
728 }
729
730
731 #ifdef HAVE_LSTAT
732 static int
733 copyf (char *ifile, char *ofile)
734 {
735     int i, in, out;
736     char buffer[BUFSIZ];
737
738     if ((in = open (ifile, O_RDONLY)) == NOTOK)
739         return NOTOK;
740     if ((out = open (ofile, O_WRONLY | O_TRUNC)) == NOTOK) {
741         admonish (ofile, "unable to open and truncate");
742         close (in);
743         return NOTOK;
744     }
745
746     while ((i = read (in, buffer, sizeof(buffer))) > OK)
747         if (write (out, buffer, i) != i) {
748             advise (ofile, "may have damaged");
749             i = NOTOK;
750             break;
751         }
752
753     close (in);
754     close (out);
755     return i;
756 }
757 #endif /* HAVE_LSTAT */
758
759
760 /*
761  * SEND
762  */
763
764 static int
765 sendfile (char **arg, char *file, int pushsw)
766 {
767     pid_t child_id;
768     int i, vecp;
769     char *cp, *sp, *vec[MAXARGS];
770
771     /* Translate MIME composition file, if necessary */
772     if ((cp = context_find ("automimeproc"))
773             && (!strcmp (cp, "1"))
774             && !getenv ("NOMHNPROC")
775             && check_draft (file)
776             && (buildfile (NULL, file) == NOTOK))
777         return 0;
778
779     /* For backwards compatibility */
780     if ((cp = context_find ("automhnproc"))
781             && !getenv ("NOMHNPROC")
782             && check_draft (file)
783             && (i = editfile (&cp, NULL, file, NOUSE, NULL, NULL, NULL, 0)))
784         return 0;
785
786     /*
787      * If the sendproc is the nmh command `send', then we call
788      * those routines directly rather than exec'ing the command.
789      */
790     if (strcmp (sp = r1bindex (sendproc, '/'), "send") == 0) {
791         cp = invo_name;
792         sendit (invo_name = sp, arg, file, pushsw);
793         invo_name = cp;
794         return 1;
795     }
796
797     context_save ();    /* save the context file */
798     fflush (stdout);
799
800     for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
801         sleep (5);
802     switch (child_id) {
803         case NOTOK:
804             advise (NULL, "unable to fork, so sending directly...");
805         case OK:
806             vecp = 0;
807             vec[vecp++] = invo_name;
808             if (pushsw)
809                 vec[vecp++] = "-push";
810             if (arg)
811                 while (*arg)
812                     vec[vecp++] = *arg++;
813             vec[vecp++] = file;
814             vec[vecp] = NULL;
815
816             execvp (sendproc, vec);
817             fprintf (stderr, "unable to exec ");
818             perror (sendproc);
819             _exit (-1);
820
821         default:
822             if (pidwait(child_id, OK) == 0)
823                 done (0);
824             return 1;
825     }
826 }
827
828
829 /*
830  * Translate MIME composition file (call buildmimeproc)
831  */
832
833 static int
834 buildfile (char **argp, char *file)
835 {
836     int i;
837     char **args, *ed;
838
839     ed = buildmimeproc;
840
841     /* allocate space for arguments */
842     i = 0;
843     if (argp) {
844         while (argp[i])
845             i++;
846     }
847     args = (char **) mh_xmalloc((i + 2) * sizeof(char *));
848
849     /*
850      * For backward compatibility, we need to add -build
851      * if we are using mhn as buildmimeproc
852      */
853     i = 0;
854     if (strcmp (r1bindex (ed, '/'), "mhn") == 0)
855         args[i++] = "-build";
856
857     /* copy any other arguments */
858     while (argp && *argp)
859         args[i++] = *argp++;
860     args[i] = NULL;
861
862     i = editfile (&ed, args, file, NOUSE, NULL, NULL, NULL, 0);
863     free (args);
864
865     return (i ? NOTOK : OK);
866 }
867
868
869 /*
870  *  Check if draft is a mhbuild composition file
871  */
872
873 static int
874 check_draft (char *msgnam)
875 {
876     int state;
877     char buf[BUFSIZ], name[NAMESZ];
878     FILE *fp;
879
880     if ((fp = fopen (msgnam, "r")) == NULL)
881         return 0;
882     for (state = FLD;;)
883         switch (state = m_getfld (state, name, buf, sizeof(buf), fp)) {
884             case FLD:
885             case FLDPLUS:
886             case FLDEOF:
887                 /*
888                  * If draft already contains any of the
889                  * Content-XXX fields, then assume it already
890                  * been converted.
891                  */
892                 if (uprf (name, XXX_FIELD_PRF)) {
893                     fclose (fp);
894                     return 0;
895                 }
896                 while (state == FLDPLUS)
897                     state = m_getfld (state, name, buf, sizeof(buf), fp);
898                 break;
899
900             case BODY:
901                 do {
902                     char *bp;
903
904                     for (bp = buf; *bp; bp++)
905                         if (*bp != ' ' && *bp != '\t' && *bp != '\n') {
906                             fclose (fp);
907                             return 1;
908                         }
909
910                     state = m_getfld (state, name, buf, sizeof(buf), fp);
911                 } while (state == BODY);
912                 /* and fall... */
913
914             default:
915                 fclose (fp);
916                 return 0;
917         }
918 }
919
920
921 #ifndef CYRUS_SASL
922 # define SASLminc(a) (a)
923 #else /* CYRUS_SASL */
924 # define SASLminc(a)  0
925 #endif /* CYRUS_SASL */
926
927 static struct swit  sendswitches[] = {
928 #define ALIASW            0
929     { "alias aliasfile", 0 },
930 #define DEBUGSW           1
931     { "debug", -5 },
932 #define FILTSW            2
933     { "filter filterfile", 0 },
934 #define NFILTSW           3
935     { "nofilter", 0 },
936 #define FRMTSW            4
937     { "format", 0 },
938 #define NFRMTSW           5
939     { "noformat", 0 },
940 #define FORWSW            6
941     { "forward", 0 },
942 #define NFORWSW           7
943     { "noforward", 0 },
944 #define MIMESW            8
945     { "mime", 0 },
946 #define NMIMESW           9
947     { "nomime", 0 },
948 #define MSGDSW           10
949     { "msgid", 0 },
950 #define NMSGDSW          11
951     { "nomsgid", 0 },
952 #define SPSHSW           12
953     { "push", 0 },
954 #define NSPSHSW          13
955     { "nopush", 0 },
956 #define SPLITSW          14
957     { "split seconds", 0 },
958 #define UNIQSW           15
959     { "unique", -6 },
960 #define NUNIQSW          16
961     { "nounique", -8 },
962 #define VERBSW           17
963     { "verbose", 0 },
964 #define NVERBSW          18
965     { "noverbose", 0 },
966 #define WATCSW           19
967     { "watch", 0 },
968 #define NWATCSW          20
969     { "nowatch", 0 },
970 #define WIDTHSW          21
971     { "width columns", 0 },
972 #define SVERSIONSW       22
973     { "version", 0 },
974 #define SHELPSW          23
975     { "help", 0 },
976 #define BITSTUFFSW       24
977     { "dashstuffing", -12 },
978 #define NBITSTUFFSW      25
979     { "nodashstuffing", -14 },
980 #define MAILSW           26
981     { "mail", -4 },
982 #define SAMLSW           27
983     { "saml", -4 },
984 #define SSNDSW           28
985     { "send", -4 },
986 #define SOMLSW           29
987     { "soml", -4 },
988 #define CLIESW           30
989     { "client host", -6 },
990 #define SERVSW           31
991     { "server host", -6 },
992 #define SNOOPSW          32
993     { "snoop", -5 },
994 #define SDRFSW           33
995     { "draftfolder +folder", -6 },
996 #define SDRMSW           34
997     { "draftmessage msg", -6 },
998 #define SNDRFSW          35
999     { "nodraftfolder", -3 },
1000 #define SASLSW           36
1001     { "sasl", SASLminc(-4) },
1002 #define SASLMECHSW       37
1003     { "saslmech", SASLminc(-5) },
1004 #define USERSW           38
1005     { "user", SASLminc(-4) },
1006 #define SNDATTACHSW       39
1007     { "attach file", 6 },
1008     { NULL, 0 }
1009 };
1010
1011
1012 extern int debugsw;             /* from sendsbr.c */
1013 extern int forwsw;
1014 extern int inplace;
1015 extern int pushsw;
1016 extern int splitsw;
1017 extern int unique;
1018 extern int verbsw;
1019
1020 extern char *altmsg;            /*  .. */
1021 extern char *annotext;
1022 extern char *distfile;
1023
1024
1025 static void
1026 sendit (char *sp, char **arg, char *file, int pushed)
1027 {
1028     int vecp, n = 1;
1029     char *cp, buf[BUFSIZ], **argp;
1030     char **arguments, *vec[MAXARGS];
1031     struct stat st;
1032     char        *attach = (char *)0;    /* attachment header field name */
1033
1034 #ifndef lint
1035     int distsw = 0;
1036 #endif
1037 #ifdef UCI
1038     FILE *fp;
1039 #endif
1040
1041     /*
1042      * Make sure these are defined.  In particular, we need
1043      * vec[1] to be NULL, in case "arg" is NULL below.  It
1044      * doesn't matter what is the value of vec[0], but we
1045      * set it to NULL, to help catch "off-by-one" errors.
1046      */
1047     vec[0] = NULL;
1048     vec[1] = NULL;
1049
1050     /*
1051      * Temporarily copy arg to vec, since the brkstring() call in
1052      * getarguments() will wipe it out before it is merged in.
1053      * Also, we skip the first element of vec, since getarguments()
1054      * skips it.  Then we count the number of arguments
1055      * copied.  The value of "n" will be one greater than
1056      * this in order to simulate the standard argc/argv.
1057      */
1058     if (arg) {
1059         char **bp;
1060
1061         copyip (arg, vec+1, MAXARGS-1);
1062         bp = vec+1;
1063         while (*bp++)
1064             n++;
1065     }
1066
1067     /*
1068      * Merge any arguments from command line (now in vec)
1069      * and arguments from profile.
1070      */
1071     arguments = getarguments (sp, n, vec, 1);
1072     argp = arguments;
1073
1074     debugsw = 0;
1075     forwsw = 1;
1076     inplace = 1;
1077     unique = 0;
1078
1079     altmsg = NULL;
1080     annotext = NULL;
1081     distfile = NULL;
1082
1083     vecp = 1;                   /* we'll get the zero'th element later */
1084     vec[vecp++] = "-library";
1085     vec[vecp++] = getcpy (m_maildir (""));
1086
1087     while ((cp = *argp++)) {
1088         if (*cp == '-') {
1089             switch (smatch (++cp, sendswitches)) {
1090                 case AMBIGSW:
1091                     ambigsw (cp, sendswitches);
1092                     return;
1093                 case UNKWNSW:
1094                     advise (NULL, "-%s unknown\n", cp);
1095                     return;
1096
1097                 case SHELPSW:
1098                     snprintf (buf, sizeof(buf), "%s [switches]", sp);
1099                     print_help (buf, sendswitches, 1);
1100                     return;
1101                 case SVERSIONSW:
1102                     print_version (invo_name);
1103                     return;
1104
1105                 case SPSHSW:
1106                     pushed++;
1107                     continue;
1108                 case NSPSHSW:
1109                     pushed = 0;
1110                     continue;
1111
1112                 case SPLITSW:
1113                     if (!(cp = *argp++) || sscanf (cp, "%d", &splitsw) != 1) {
1114                         advise (NULL, "missing argument to %s", argp[-2]);
1115                         return;
1116                     }
1117                     continue;
1118
1119                 case UNIQSW:
1120                     unique++;
1121                     continue;
1122                 case NUNIQSW:
1123                     unique = 0;
1124                     continue;
1125                 case FORWSW:
1126                     forwsw++;
1127                     continue;
1128                 case NFORWSW:
1129                     forwsw = 0;
1130                     continue;
1131
1132                 case VERBSW:
1133                     verbsw++;
1134                     vec[vecp++] = --cp;
1135                     continue;
1136                 case NVERBSW:
1137                     verbsw = 0;
1138                     vec[vecp++] = --cp;
1139                     continue;
1140
1141                 case DEBUGSW:
1142                     debugsw++;  /* fall */
1143                 case NFILTSW:
1144                 case FRMTSW:
1145                 case NFRMTSW:
1146                 case BITSTUFFSW:
1147                 case NBITSTUFFSW:
1148                 case MIMESW:
1149                 case NMIMESW:
1150                 case MSGDSW:
1151                 case NMSGDSW:
1152                 case WATCSW:
1153                 case NWATCSW:
1154                 case MAILSW:
1155                 case SAMLSW:
1156                 case SSNDSW:
1157                 case SOMLSW:
1158                 case SNOOPSW:
1159                 case SASLSW:
1160                     vec[vecp++] = --cp;
1161                     continue;
1162
1163                 case ALIASW:
1164                 case FILTSW:
1165                 case WIDTHSW:
1166                 case CLIESW:
1167                 case SERVSW:
1168                 case SASLMECHSW:
1169                 case USERSW:
1170                     vec[vecp++] = --cp;
1171                     if (!(cp = *argp++) || *cp == '-') {
1172                         advise (NULL, "missing argument to %s", argp[-2]);
1173                         return;
1174                     }
1175                     vec[vecp++] = cp;
1176                     continue;
1177
1178                 case SDRFSW:
1179                 case SDRMSW:
1180                     if (!(cp = *argp++) || *cp == '-') {
1181                         advise (NULL, "missing argument to %s", argp[-2]);
1182                         return;
1183                     }
1184                 case SNDRFSW:
1185                     continue;
1186
1187                 case SNDATTACHSW:
1188                     if (!(attach = *argp++) || *attach == '-') {
1189                         advise (NULL, "missing argument to %s", argp[-2]);
1190                         return;
1191                     }
1192                     continue;
1193             }
1194         }
1195         advise (NULL, "usage: %s [switches]", sp);
1196         return;
1197     }
1198
1199     /* allow Aliasfile: profile entry */
1200     if ((cp = context_find ("Aliasfile"))) {
1201         char **ap, *dp;
1202
1203         dp = getcpy (cp);
1204         for (ap = brkstring (dp, " ", "\n"); ap && *ap; ap++) {
1205             vec[vecp++] = "-alias";
1206             vec[vecp++] = *ap;
1207         }
1208     }
1209
1210     if ((cp = getenv ("SIGNATURE")) == NULL || *cp == 0)
1211         if ((cp = context_find ("signature")) && *cp)
1212             m_putenv ("SIGNATURE", cp);
1213 #ifdef UCI
1214         else {
1215             snprintf (buf, sizeof(buf), "%s/.signature", mypath);
1216             if ((fp = fopen (buf, "r")) != NULL
1217                 && fgets (buf, sizeof(buf), fp) != NULL) {
1218                     fclose (fp);
1219                     if (cp = strchr (buf, '\n'))
1220                         *cp = 0;
1221                     m_putenv ("SIGNATURE", buf);
1222             }
1223         }
1224 #endif /* UCI */
1225
1226     if ((annotext = getenv ("mhannotate")) == NULL || *annotext == 0)
1227         annotext = NULL;
1228     if ((altmsg = getenv ("mhaltmsg")) == NULL || *altmsg == 0)
1229         altmsg = NULL;
1230     if (annotext && ((cp = getenv ("mhinplace")) != NULL && *cp != 0))
1231         inplace = atoi (cp);
1232
1233     if ((cp = getenv ("mhdist"))
1234             && *cp
1235 #ifndef lint
1236             && (distsw = atoi (cp))
1237 #endif /* not lint */
1238             && altmsg) {
1239         vec[vecp++] = "-dist";
1240         distfile = getcpy (m_scratch (altmsg, invo_name));
1241         if (link (altmsg, distfile) == NOTOK)
1242             adios (distfile, "unable to link %s to", altmsg);
1243     } else {
1244         distfile = NULL;
1245     }
1246
1247     if (altmsg == NULL || stat (altmsg, &st) == NOTOK) {
1248         st.st_mtime = 0;
1249         st.st_dev = 0;
1250         st.st_ino = 0;
1251     }
1252     if ((pushsw = pushed))
1253         push ();
1254
1255     vec[0] = r1bindex (postproc, '/');
1256     closefds (3);
1257
1258     if (sendsbr (vec, vecp, file, &st, 1, attach) == OK)
1259         done (0);
1260 }
1261
1262 /*
1263  * WHOM
1264  */
1265
1266 static int
1267 whomfile (char **arg, char *file)
1268 {
1269     pid_t pid;
1270     int vecp;
1271     char *vec[MAXARGS];
1272
1273     context_save ();    /* save the context file */
1274     fflush (stdout);
1275
1276     switch (pid = vfork ()) {
1277         case NOTOK:
1278             advise ("fork", "unable to");
1279             return 1;
1280
1281         case OK:
1282             vecp = 0;
1283             vec[vecp++] = r1bindex (whomproc, '/');
1284             vec[vecp++] = file;
1285             if (arg)
1286                 while (*arg)
1287                     vec[vecp++] = *arg++;
1288             vec[vecp] = NULL;
1289
1290             execvp (whomproc, vec);
1291             fprintf (stderr, "unable to exec ");
1292             perror (whomproc);
1293             _exit (-1);         /* NOTREACHED */
1294
1295         default:
1296             return (pidwait (pid, NOTOK) & 0377 ? 1 : 0);
1297     }
1298 }
1299
1300
1301 /*
1302  * Remove the draft file
1303  */
1304
1305 static int
1306 removefile (char *drft)
1307 {
1308     if (unlink (drft) == NOTOK)
1309         adios (drft, "unable to unlink");
1310
1311     return OK;
1312 }