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