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