d54877e343cf1bfd08b28b938ae93af11a297453
[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 *, 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), "-d", 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), "-d", 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) + 4;
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++ = '&'; *cp++ = '&';
583         strcpy(cp, trailcmd);
584         cp += trailln - 4;
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 *lsoptions, char **argp)
596 {
597   char *lscmd = concat ("ls ", lsoptions, " --", NULL);
598   writesomecmd(buf, bufsz, lscmd, "", argp);
599   free (lscmd);
600 }
601
602 /* Like system(), but run the command in directory dir.
603  * This assumes the program is single-threaded!
604  */
605 static int
606 system_in_dir(const char *dir, const char *cmd)
607 {
608     char olddir[BUFSIZ];
609     int r;
610
611     /* ensure that $SHELL exists, as the cmd was written relying on
612        a non-blank $SHELL... */
613     setenv("SHELL","/bin/sh",0); /* don't overwrite */
614
615     if (getcwd(olddir, sizeof(olddir)) == 0)
616         adios("getcwd", "could not get working directory");
617     if (chdir(dir) != 0)
618         adios("chdir", "could not change working directory");
619     r = system(cmd);
620     if (chdir(olddir) != 0)
621         adios("chdir", "could not change working directory");
622     return r;
623 }
624
625 /* ditto for popen() */
626 static FILE*
627 popen_in_dir(const char *dir, const char *cmd, const char *type)
628 {
629     char olddir[BUFSIZ];
630     FILE *f;
631
632     /* ensure that $SHELL exists, as the cmd was written relying on
633        a non-blank $SHELL... */
634     setenv("SHELL","/bin/sh",0); /* don't overwrite */
635     
636     if (getcwd(olddir, sizeof(olddir)) == 0)
637         adios("getcwd", "could not get working directory");
638     if (chdir(dir) != 0)
639         adios("chdir", "could not change working directory");
640     f = popen(cmd, type);
641     if (chdir(olddir) != 0)
642         adios("chdir", "could not change working directory");
643     return f;
644 }
645
646
647 /*
648  * EDIT
649  */
650
651 static int  reedit = 0;         /* have we been here before?     */
652 static char *edsave = NULL;     /* the editor we used previously */
653
654
655 static int
656 editfile (char **ed, char **arg, char *file, int use, struct msgs *mp,
657           char *altmsg, char *cwd, int save_editor, int atfile)
658 {
659     int pid, status, vecp;
660     char altpath[BUFSIZ], linkpath[BUFSIZ];
661     char *cp, *vec[MAXARGS];
662     struct stat st;
663
664 #ifdef HAVE_LSTAT
665     int slinked = 0;
666 #endif /* HAVE_LSTAT */
667
668     /* Was there a previous edit session? */
669     if (reedit) {
670         if (!*ed) {             /* no explicit editor      */
671             *ed = edsave;       /* so use the previous one */
672             if ((cp = r1bindex (*ed, '/')) == NULL)
673                 cp = *ed;
674
675             /* unless we've specified it via "editor-next" */
676             cp = concat (cp, "-next", NULL);
677             if ((cp = context_find (cp)) != NULL)
678                 *ed = cp;
679         }
680     } else {
681         /* set initial editor */
682         if (*ed == NULL && (*ed = context_find ("editor")) == NULL)
683             *ed = defaulteditor;
684     }
685
686     if (altmsg && atfile) {
687         if (mp == NULL || *altmsg == '/' || cwd == NULL)
688             strncpy (altpath, altmsg, sizeof(altpath));
689         else
690             snprintf (altpath, sizeof(altpath), "%s/%s", mp->foldpath, altmsg);
691         if (cwd == NULL)
692             strncpy (linkpath, LINK, sizeof(linkpath));
693         else
694             snprintf (linkpath, sizeof(linkpath), "%s/%s", cwd, LINK);
695
696         unlink (linkpath);
697 #ifdef HAVE_LSTAT
698         if (link (altpath, linkpath) == NOTOK) {
699             symlink (altpath, linkpath);
700             slinked = 1;
701         } else {
702             slinked = 0;
703         }
704 #else /* not HAVE_LSTAT */
705         link (altpath, linkpath);
706 #endif /* not HAVE_LSTAT */
707     }
708
709     context_save ();    /* save the context file */
710     fflush (stdout);
711
712     switch (pid = vfork()) {
713         case NOTOK:
714             advise ("fork", "unable to");
715             status = NOTOK;
716             break;
717
718         case OK:
719             if (cwd)
720                 chdir (cwd);
721             if (altmsg) {
722                 if (mp)
723                     m_putenv ("mhfolder", mp->foldpath);
724                 m_putenv ("editalt", altpath);
725             }
726
727             vecp = 0;
728             vec[vecp++] = r1bindex (*ed, '/');
729             if (arg)
730                 while (*arg)
731                     vec[vecp++] = *arg++;
732             vec[vecp++] = file;
733             vec[vecp] = NULL;
734
735             execvp (*ed, vec);
736             fprintf (stderr, "unable to exec ");
737             perror (*ed);
738             _exit (-1);
739
740         default:
741             if ((status = pidwait (pid, NOTOK))) {
742                 if (((status & 0xff00) != 0xff00)
743                     && (!reedit || (status & 0x00ff))) {
744                     if (!use && (status & 0xff00) &&
745                             (rename (file, cp = m_backup (file)) != NOTOK)) {
746                         advise (NULL, "problems with edit--draft left in %s", cp);
747                     } else {
748                         advise (NULL, "problems with edit--%s preserved", file);
749                     }
750                 }
751                 status = -2;    /* maybe "reedit ? -2 : -1"? */
752                 break;
753             }
754
755             reedit++;
756 #ifdef HAVE_LSTAT
757             if (altmsg
758                     && mp
759                     && !is_readonly(mp)
760                     && (slinked
761                            ? lstat (linkpath, &st) != NOTOK
762                                 && S_ISREG(st.st_mode)
763                                 && copyf (linkpath, altpath) == NOTOK
764                            : stat (linkpath, &st) != NOTOK
765                                 && st.st_nlink == 1
766                                 && (unlink (altpath) == NOTOK
767                                         || link (linkpath, altpath) == NOTOK)))
768                 advise (linkpath, "unable to update %s from", altmsg);
769 #else /* HAVE_LSTAT */
770             if (altmsg
771                     && mp
772                     && !is_readonly(mp)
773                     && stat (linkpath, &st) != NOTOK
774                     && st.st_nlink == 1
775                     && (unlink (altpath) == NOTOK
776                         || link (linkpath, altpath) == NOTOK))
777                 advise (linkpath, "unable to update %s from", altmsg);
778 #endif /* HAVE_LSTAT */
779     }
780
781     /* normally, we remember which editor we used */
782     if (save_editor)
783         edsave = getcpy (*ed);
784
785     *ed = NULL;
786     if (altmsg && atfile)
787         unlink (linkpath);
788
789     return status;
790 }
791
792
793 #ifdef HAVE_LSTAT
794 static int
795 copyf (char *ifile, char *ofile)
796 {
797     int i, in, out;
798     char buffer[BUFSIZ];
799
800     if ((in = open (ifile, O_RDONLY)) == NOTOK)
801         return NOTOK;
802     if ((out = open (ofile, O_WRONLY | O_TRUNC)) == NOTOK) {
803         admonish (ofile, "unable to open and truncate");
804         close (in);
805         return NOTOK;
806     }
807
808     while ((i = read (in, buffer, sizeof(buffer))) > OK)
809         if (write (out, buffer, i) != i) {
810             advise (ofile, "may have damaged");
811             i = NOTOK;
812             break;
813         }
814
815     close (in);
816     close (out);
817     return i;
818 }
819 #endif /* HAVE_LSTAT */
820
821
822 /*
823  * SEND
824  */
825
826 static int
827 sendfile (char **arg, char *file, int pushsw)
828 {
829     pid_t child_id;
830     int i, vecp;
831     char *cp, *sp, *vec[MAXARGS];
832
833     /* Translate MIME composition file, if necessary */
834     if ((cp = context_find ("automimeproc"))
835             && (!strcmp (cp, "1"))
836             && check_draft (file)
837             && (buildfile (NULL, file) == NOTOK))
838         return 0;
839
840     /* For backwards compatibility */
841     if ((cp = context_find ("automhnproc"))
842             && check_draft (file)
843             && (i = editfile (&cp, NULL, file, NOUSE, NULL, NULL, NULL, 0, 0)))
844         return 0;
845
846     /*
847      * If the sendproc is the nmh command `send', then we call
848      * those routines directly rather than exec'ing the command.
849      */
850     if (strcmp (sp = r1bindex (sendproc, '/'), "send") == 0) {
851         cp = invo_name;
852         sendit (invo_name = sp, arg, file, pushsw);
853         invo_name = cp;
854         return 1;
855     }
856
857     context_save ();    /* save the context file */
858     fflush (stdout);
859
860     for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
861         sleep (5);
862     switch (child_id) {
863         case NOTOK:
864             advise (NULL, "unable to fork, so sending directly...");
865         case OK:
866             vecp = 0;
867             vec[vecp++] = invo_name;
868             if (pushsw)
869                 vec[vecp++] = "-push";
870             if (arg)
871                 while (*arg)
872                     vec[vecp++] = *arg++;
873             vec[vecp++] = file;
874             vec[vecp] = NULL;
875
876             execvp (sendproc, vec);
877             fprintf (stderr, "unable to exec ");
878             perror (sendproc);
879             _exit (-1);
880
881         default:
882             if (pidwait(child_id, OK) == 0)
883                 done (0);
884             return 1;
885     }
886 }
887
888
889 /*
890  * Translate MIME composition file (call buildmimeproc)
891  */
892
893 static int
894 buildfile (char **argp, char *file)
895 {
896     int i;
897     char **args, *ed;
898
899     ed = buildmimeproc;
900
901     /* allocate space for arguments */
902     i = 0;
903     if (argp) {
904         while (argp[i])
905             i++;
906     }
907     args = (char **) mh_xmalloc((i + 2) * sizeof(char *));
908
909     /*
910      * For backward compatibility, we need to add -build
911      * if we are using mhn as buildmimeproc
912      */
913     i = 0;
914     if (strcmp (r1bindex (ed, '/'), "mhn") == 0)
915         args[i++] = "-build";
916
917     /* copy any other arguments */
918     while (argp && *argp)
919         args[i++] = *argp++;
920     args[i] = NULL;
921
922     i = editfile (&ed, args, file, NOUSE, NULL, NULL, NULL, 0, 0);
923     free (args);
924
925     return (i ? NOTOK : OK);
926 }
927
928
929 /*
930  *  Check if draft is a mhbuild composition file
931  */
932
933 static int
934 check_draft (char *msgnam)
935 {
936     int state;
937     char buf[BUFSIZ], name[NAMESZ];
938     FILE *fp;
939
940     if ((fp = fopen (msgnam, "r")) == NULL)
941         return 0;
942     for (state = FLD;;)
943         switch (state = m_getfld (state, name, buf, sizeof(buf), fp)) {
944             case FLD:
945             case FLDPLUS:
946             case FLDEOF:
947                 /*
948                  * If draft already contains any of the
949                  * Content-XXX fields, then assume it already
950                  * been converted.
951                  */
952                 if (uprf (name, XXX_FIELD_PRF)) {
953                     fclose (fp);
954                     return 0;
955                 }
956                 while (state == FLDPLUS)
957                     state = m_getfld (state, name, buf, sizeof(buf), fp);
958                 break;
959
960             case BODY:
961                 do {
962                     char *bp;
963
964                     for (bp = buf; *bp; bp++)
965                         if (*bp != ' ' && *bp != '\t' && *bp != '\n') {
966                             fclose (fp);
967                             return 1;
968                         }
969
970                     state = m_getfld (state, name, buf, sizeof(buf), fp);
971                 } while (state == BODY);
972                 /* and fall... */
973
974             default:
975                 fclose (fp);
976                 return 0;
977         }
978 }
979
980
981 #ifndef CYRUS_SASL
982 # define SASLminc(a) (a)
983 #else /* CYRUS_SASL */
984 # define SASLminc(a)  0
985 #endif /* CYRUS_SASL */
986
987 #ifndef TLS_SUPPORT
988 # define TLSminc(a)  (a)
989 #else /* TLS_SUPPORT */
990 # define TLSminc(a)   0
991 #endif /* TLS_SUPPORT */
992
993 static struct swit  sendswitches[] = {
994 #define ALIASW            0
995     { "alias aliasfile", 0 },
996 #define DEBUGSW           1
997     { "debug", -5 },
998 #define FILTSW            2
999     { "filter filterfile", 0 },
1000 #define NFILTSW           3
1001     { "nofilter", 0 },
1002 #define FRMTSW            4
1003     { "format", 0 },
1004 #define NFRMTSW           5
1005     { "noformat", 0 },
1006 #define FORWSW            6
1007     { "forward", 0 },
1008 #define NFORWSW           7
1009     { "noforward", 0 },
1010 #define MIMESW            8
1011     { "mime", 0 },
1012 #define NMIMESW           9
1013     { "nomime", 0 },
1014 #define MSGDSW           10
1015     { "msgid", 0 },
1016 #define NMSGDSW          11
1017     { "nomsgid", 0 },
1018 #define SPSHSW           12
1019     { "push", 0 },
1020 #define NSPSHSW          13
1021     { "nopush", 0 },
1022 #define SPLITSW          14
1023     { "split seconds", 0 },
1024 #define UNIQSW           15
1025     { "unique", -6 },
1026 #define NUNIQSW          16
1027     { "nounique", -8 },
1028 #define VERBSW           17
1029     { "verbose", 0 },
1030 #define NVERBSW          18
1031     { "noverbose", 0 },
1032 #define WATCSW           19
1033     { "watch", 0 },
1034 #define NWATCSW          20
1035     { "nowatch", 0 },
1036 #define WIDTHSW          21
1037     { "width columns", 0 },
1038 #define SVERSIONSW       22
1039     { "version", 0 },
1040 #define SHELPSW          23
1041     { "help", 0 },
1042 #define BITSTUFFSW       24
1043     { "dashstuffing", -12 },
1044 #define NBITSTUFFSW      25
1045     { "nodashstuffing", -14 },
1046 #define MAILSW           26
1047     { "mail", -4 },
1048 #define SAMLSW           27
1049     { "saml", -4 },
1050 #define SSNDSW           28
1051     { "send", -4 },
1052 #define SOMLSW           29
1053     { "soml", -4 },
1054 #define CLIESW           30
1055     { "client host", -6 },
1056 #define SERVSW           31
1057     { "server host", 6 },
1058 #define SNOOPSW          32
1059     { "snoop", -5 },
1060 #define SDRFSW           33
1061     { "draftfolder +folder", -6 },
1062 #define SDRMSW           34
1063     { "draftmessage msg", -6 },
1064 #define SNDRFSW          35
1065     { "nodraftfolder", -3 },
1066 #define SASLSW           36
1067     { "sasl", SASLminc(-4) },
1068 #define NOSASLSW         37
1069     { "nosasl", SASLminc(-6) },
1070 #define SASLMXSSFSW      38
1071     { "saslmaxssf", SASLminc(-10) },
1072 #define SASLMECHSW       39
1073     { "saslmech", SASLminc(-5) },
1074 #define USERSW           40
1075     { "user", SASLminc(-4) },
1076 #define SNDATTACHSW       41
1077     { "attach file", 6 },
1078 #define SNDNOATTACHSW     42
1079     { "noattach", 0 },
1080 #define SNDATTACHFORMAT   43
1081     { "attachformat", 7 },
1082 #define PORTSW            44
1083     { "port server-port-name/number", 4 },
1084 #define TLSSW             45
1085     { "tls", TLSminc(-3) },
1086 #define NTLSSW            46
1087     { "notls", TLSminc(-5) },
1088 #define MTSSW             47
1089     { "mts smtp|sendmail/smtp|sendmail/pipe", 2 },
1090 #define MESSAGEIDSW       48
1091     { "messageid localname|random", 2 },
1092     { NULL, 0 }
1093 };
1094
1095
1096 extern int debugsw;             /* from sendsbr.c */
1097 extern int forwsw;
1098 extern int inplace;
1099 extern int pushsw;
1100 extern int splitsw;
1101 extern int unique;
1102 extern int verbsw;
1103
1104 extern char *altmsg;            /*  .. */
1105 extern char *annotext;
1106 extern char *distfile;
1107
1108
1109 static void
1110 sendit (char *sp, char **arg, char *file, int pushed)
1111 {
1112     int vecp, n = 1;
1113     char *cp, buf[BUFSIZ], **argp;
1114     char **arguments, *vec[MAXARGS];
1115     struct stat st;
1116     char        *attach = NMH_ATTACH_HEADER;/* attachment header field name */
1117     int         attachformat = 1;       /* mhbuild format specifier for
1118                                            attachments */
1119
1120 #ifndef lint
1121     int distsw = 0;
1122 #endif
1123
1124     /*
1125      * Make sure these are defined.  In particular, we need
1126      * vec[1] to be NULL, in case "arg" is NULL below.  It
1127      * doesn't matter what is the value of vec[0], but we
1128      * set it to NULL, to help catch "off-by-one" errors.
1129      */
1130     vec[0] = NULL;
1131     vec[1] = NULL;
1132
1133     /*
1134      * Temporarily copy arg to vec, since the brkstring() call in
1135      * getarguments() will wipe it out before it is merged in.
1136      * Also, we skip the first element of vec, since getarguments()
1137      * skips it.  Then we count the number of arguments
1138      * copied.  The value of "n" will be one greater than
1139      * this in order to simulate the standard argc/argv.
1140      */
1141     if (arg) {
1142         char **bp;
1143
1144         copyip (arg, vec+1, MAXARGS-1);
1145         bp = vec+1;
1146         while (*bp++)
1147             n++;
1148     }
1149
1150     /*
1151      * Merge any arguments from command line (now in vec)
1152      * and arguments from profile.
1153      */
1154     arguments = getarguments (sp, n, vec, 1);
1155     argp = arguments;
1156
1157     debugsw = 0;
1158     forwsw = 1;
1159     inplace = 1;
1160     unique = 0;
1161
1162     altmsg = NULL;
1163     annotext = NULL;
1164     distfile = NULL;
1165
1166     vecp = 1;                   /* we'll get the zero'th element later */
1167     vec[vecp++] = "-library";
1168     vec[vecp++] = getcpy (m_maildir (""));
1169
1170     if ((cp = context_find ("fileproc"))) {
1171       vec[vecp++] = "-fileproc";
1172       vec[vecp++] = cp;
1173     }
1174
1175     if ((cp = context_find ("mhlproc"))) {
1176       vec[vecp++] = "-mhlproc";
1177       vec[vecp++] = cp;
1178     }
1179
1180     while ((cp = *argp++)) {
1181         if (*cp == '-') {
1182             switch (smatch (++cp, sendswitches)) {
1183                 case AMBIGSW:
1184                     ambigsw (cp, sendswitches);
1185                     return;
1186                 case UNKWNSW:
1187                     advise (NULL, "-%s unknown\n", cp);
1188                     return;
1189
1190                 case SHELPSW:
1191                     snprintf (buf, sizeof(buf), "%s [switches]", sp);
1192                     print_help (buf, sendswitches, 1);
1193                     return;
1194                 case SVERSIONSW:
1195                     print_version (invo_name);
1196                     return;
1197
1198                 case SPSHSW:
1199                     pushed++;
1200                     continue;
1201                 case NSPSHSW:
1202                     pushed = 0;
1203                     continue;
1204
1205                 case SPLITSW:
1206                     if (!(cp = *argp++) || sscanf (cp, "%d", &splitsw) != 1) {
1207                         advise (NULL, "missing argument to %s", argp[-2]);
1208                         return;
1209                     }
1210                     continue;
1211
1212                 case UNIQSW:
1213                     unique++;
1214                     continue;
1215                 case NUNIQSW:
1216                     unique = 0;
1217                     continue;
1218                 case FORWSW:
1219                     forwsw++;
1220                     continue;
1221                 case NFORWSW:
1222                     forwsw = 0;
1223                     continue;
1224
1225                 case VERBSW:
1226                     verbsw++;
1227                     vec[vecp++] = --cp;
1228                     continue;
1229                 case NVERBSW:
1230                     verbsw = 0;
1231                     vec[vecp++] = --cp;
1232                     continue;
1233
1234                 case DEBUGSW:
1235                     debugsw++;  /* fall */
1236                 case NFILTSW:
1237                 case FRMTSW:
1238                 case NFRMTSW:
1239                 case BITSTUFFSW:
1240                 case NBITSTUFFSW:
1241                 case MIMESW:
1242                 case NMIMESW:
1243                 case MSGDSW:
1244                 case NMSGDSW:
1245                 case WATCSW:
1246                 case NWATCSW:
1247                 case MAILSW:
1248                 case SAMLSW:
1249                 case SSNDSW:
1250                 case SOMLSW:
1251                 case SNOOPSW:
1252                 case SASLSW:
1253                 case NOSASLSW:
1254                 case TLSSW:
1255                 case NTLSSW:
1256                     vec[vecp++] = --cp;
1257                     continue;
1258
1259                 case ALIASW:
1260                 case FILTSW:
1261                 case WIDTHSW:
1262                 case CLIESW:
1263                 case SERVSW:
1264                 case SASLMXSSFSW:
1265                 case SASLMECHSW:
1266                 case USERSW:
1267                 case PORTSW:
1268                 case MTSSW:
1269                 case MESSAGEIDSW:
1270                     vec[vecp++] = --cp;
1271                     if (!(cp = *argp++) || *cp == '-') {
1272                         advise (NULL, "missing argument to %s", argp[-2]);
1273                         return;
1274                     }
1275                     vec[vecp++] = cp;
1276                     continue;
1277
1278                 case SDRFSW:
1279                 case SDRMSW:
1280                     if (!(cp = *argp++) || *cp == '-') {
1281                         advise (NULL, "missing argument to %s", argp[-2]);
1282                         return;
1283                     }
1284                 case SNDRFSW:
1285                     continue;
1286
1287                 case SNDATTACHSW:
1288                     if (!(attach = *argp++) || *attach == '-') {
1289                         advise (NULL, "missing argument to %s", argp[-2]);
1290                         return;
1291                     }
1292                     continue;
1293                 case SNDNOATTACHSW:
1294                     attach = NULL;
1295                     continue;
1296
1297                 case SNDATTACHFORMAT:
1298                     if (! *argp || **argp == '-')
1299                         adios (NULL, "missing argument to %s", argp[-1]);
1300                     else {
1301                         attachformat = atoi (*argp);
1302                         if (attachformat < 0 ||
1303                             attachformat > ATTACHFORMATS - 1) {
1304                             advise (NULL, "unsupported attachformat %d",
1305                                     attachformat);
1306                             continue;
1307                         }
1308                     }
1309                     ++argp;
1310                     continue;
1311             }
1312         }
1313         advise (NULL, "usage: %s [switches]", sp);
1314         return;
1315     }
1316
1317     /* allow Aliasfile: profile entry */
1318     if ((cp = context_find ("Aliasfile"))) {
1319         char **ap, *dp;
1320
1321         dp = getcpy (cp);
1322         for (ap = brkstring (dp, " ", "\n"); ap && *ap; ap++) {
1323             vec[vecp++] = "-alias";
1324             vec[vecp++] = *ap;
1325         }
1326     }
1327
1328     if ((cp = getenv ("SIGNATURE")) == NULL || *cp == 0)
1329         if ((cp = context_find ("signature")) && *cp)
1330             m_putenv ("SIGNATURE", cp);
1331
1332     if ((annotext = getenv ("mhannotate")) == NULL || *annotext == 0)
1333         annotext = NULL;
1334     if ((altmsg = getenv ("mhaltmsg")) == NULL || *altmsg == 0)
1335         altmsg = NULL;
1336     if (annotext && ((cp = getenv ("mhinplace")) != NULL && *cp != 0))
1337         inplace = atoi (cp);
1338
1339     if ((cp = getenv ("mhdist"))
1340             && *cp
1341 #ifndef lint
1342             && (distsw = atoi (cp))
1343 #endif /* not lint */
1344             && altmsg) {
1345         vec[vecp++] = "-dist";
1346         distfile = getcpy (m_mktemp2(altmsg, invo_name, NULL, NULL));
1347         unlink(distfile);
1348         if (link (altmsg, distfile) == NOTOK)
1349             adios (distfile, "unable to link %s to", altmsg);
1350     } else {
1351         distfile = NULL;
1352     }
1353
1354     if (altmsg == NULL || stat (altmsg, &st) == NOTOK) {
1355         st.st_mtime = 0;
1356         st.st_dev = 0;
1357         st.st_ino = 0;
1358     }
1359     if ((pushsw = pushed))
1360         push ();
1361
1362     vec[0] = r1bindex (postproc, '/');
1363     closefds (3);
1364
1365     if (sendsbr (vec, vecp, file, &st, 1, attach, attachformat) == OK)
1366         done (0);
1367 }
1368
1369 /*
1370  * WHOM
1371  */
1372
1373 static int
1374 whomfile (char **arg, char *file)
1375 {
1376     pid_t pid;
1377     int vecp;
1378     char *vec[MAXARGS];
1379
1380     context_save ();    /* save the context file */
1381     fflush (stdout);
1382
1383     switch (pid = vfork()) {
1384         case NOTOK:
1385             advise ("fork", "unable to");
1386             return 1;
1387
1388         case OK:
1389             vecp = 0;
1390             vec[vecp++] = r1bindex (whomproc, '/');
1391             vec[vecp++] = file;
1392             if (arg)
1393                 while (*arg)
1394                     vec[vecp++] = *arg++;
1395             vec[vecp] = NULL;
1396
1397             execvp (whomproc, vec);
1398             fprintf (stderr, "unable to exec ");
1399             perror (whomproc);
1400             _exit (-1);         /* NOTREACHED */
1401
1402         default:
1403             return (pidwait (pid, NOTOK) & 0377 ? 1 : 0);
1404     }
1405 }
1406
1407
1408 /*
1409  * Remove the draft file
1410  */
1411
1412 static int
1413 removefile (char *drft)
1414 {
1415     if (unlink (drft) == NOTOK)
1416         adios (drft, "unable to unlink");
1417
1418     return OK;
1419 }