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