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