Fixed `alist' command at whatnow prompt.
[mmh] / uip / whatnow.c
1 /*
2 ** whatnow.c -- the WhatNow shell
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 **
8 **  The inclusion of attachments is eased by
9 **  using the header field name mechanism added to anno and send.
10 **  The header field name for attachments is predefined.
11 **
12 **  Several commands have been added at the whatnow prompt:
13 **
14 **        cd [ directory ]        This option works just like the shell's
15 **                                cd command and lets the user change the
16 **                                directory from which attachments are
17 **                                taken so that long path names are not
18 **                                needed with every file.
19 **
20 **        ls [ ls-options ]       This option works just like the normal
21 **                                ls command and exists to allow the user
22 **                                to verify file names in the directory.
23 **
24 **        pwd                     This option works just like the normal
25 **                                pwd command and exists to allow the user
26 **                                to verify the directory.
27 **
28 **        attach files            This option attaches the named files to
29 **                                the draft.
30 **
31 **        alist                   This option lists the attachments on the
32 **                                draft.
33 **
34 **        detach files            This option removes attachments from the
35 **        detach -n numbers       draft.  This can be done by file name or
36 **                                by attachment number.
37 */
38
39 #include <h/mh.h>
40 #include <fcntl.h>
41 #include <signal.h>
42 #include <h/mime.h>
43 #include <h/utils.h>
44
45 static struct swit whatnowswitches[] = {
46 #define EDITRSW  0
47         { "editor editor", 0 },
48 #define PRMPTSW  1
49         { "prompt string", 0 },
50 #define VERSIONSW  2
51         { "Version", 0 },
52 #define HELPSW  3
53         { "help", 0 },
54         { NULL, 0 }
55 };
56
57 /*
58 ** Options at the "whatnow" prompt
59 */
60 static struct swit aleqs[] = {
61 #define EDITSW  0
62         { "edit [<editor> <switches>]", 0 },
63 #define REFILEOPT  1
64         { "refile [<switches>] +folder", 0 },
65 #define DISPSW  2
66         { "display", 0 },
67 #define LISTSW  3
68         { "list", 0 },
69 #define SENDSW  4
70         { "send [<switches>]", 0 },
71 #define QUITSW  5
72         { "quit", 0 },
73 #define DELETESW  6
74         { "delete", 0 },
75 #define CDCMDSW  7
76         { "cd [directory]", 0 },
77 #define PWDCMDSW  8
78         { "pwd", 0 },
79 #define LSCMDSW  9
80         { "ls", 0 },
81 #define ATTACHCMDSW  10
82         { "attach", 0 },
83 #define DETACHCMDSW  11
84         { "detach [-n]", 0 },
85 #define ALISTCMDSW  12
86         { "alist", 0 },
87         { NULL, 0 }
88 };
89
90 static char *myprompt = "\nWhat now? ";
91
92 /*
93 ** static prototypes
94 */
95 static int editfile(char **, char **, char *, int);
96 static int sendfile(char **, char *);
97 static int refile(char **, char *);
98 static int removefile(char *);
99 static void writelscmd(char *, int, char **);
100 static void writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp);
101 static FILE* popen_in_dir(const char *dir, const char *cmd, const char *type);
102 static int system_in_dir(const char *dir, const char *cmd);
103
104
105 int
106 main(int argc, char **argv)
107 {
108         int use = 0;
109         char *cp;
110         char *ed = NULL, *drft = NULL;
111         char buf[BUFSIZ], prompt[BUFSIZ];
112         char **argp, **arguments;
113         struct stat st;
114         char cwd[MAXPATHLEN + 1];  /* current working directory */
115         char file[MAXPATHLEN + 1];  /* file name buffer */
116         char shell[MAXPATHLEN + 1];  /* shell response buffer */
117         FILE *f;  /* read pointer for bgnd proc */
118         int n;  /* set on -n to detach command */
119
120         setlocale(LC_ALL, "");
121         invo_name = mhbasename(argv[0]);
122
123         /* read user profile/context */
124         context_read();
125
126         arguments = getarguments(invo_name, argc, argv, 1);
127         argp = arguments;
128
129         /*
130         ** Get the initial current working directory.
131         */
132
133         if (!getcwd(cwd, sizeof (cwd))) {
134                 adios("getcwd", "could not get working directory");
135         }
136
137         while ((cp = *argp++)) {
138                 if (*cp == '-') {
139                         switch (smatch(++cp, whatnowswitches)) {
140                         case AMBIGSW:
141                                 ambigsw(cp, whatnowswitches);
142                                 done(1);
143                         case UNKWNSW:
144                                 adios(NULL, "-%s unknown", cp);
145
146                         case HELPSW:
147                                 snprintf(buf, sizeof(buf),
148                                                 "%s [switches] [file]",
149                                                 invo_name);
150                                 print_help(buf, whatnowswitches, 1);
151                                 done(1);
152                         case VERSIONSW:
153                                 print_version(invo_name);
154                                 done(1);
155
156                         case EDITRSW:
157                                 if (!(ed = *argp++) || *ed == '-')
158                                         adios(NULL, "missing argument to %s",
159                                                         argp[-2]);
160                                 continue;
161
162                         case PRMPTSW:
163                                 if (!(myprompt = *argp++) || *myprompt == '-')
164                                         adios(NULL, "missing argument to %s",
165                                                         argp[-2]);
166                                 continue;
167
168                         }
169                 }
170                 if (drft)
171                         adios(NULL, "only one draft at a time!");
172                 else
173                         drft = cp;
174         }
175
176         if ((!drft && !(drft = getenv("mhdraft"))) || !*drft)
177                 drft = getcpy(m_draft(seq_cur));
178
179         if ((cp = getenv("mhuse")) && *cp)
180                 use = atoi(cp);
181
182         if (!ed && !(ed = getenv("mheditor"))) {
183                 ed = "";  /* Don't initially edit the draft */
184         }
185
186         /* start editing the draft, unless editor is the empty string */
187         if (*ed) {
188                 if (editfile(&ed, NULL, drft, use) <0) {
189                         if (!use) {
190                                 unlink(drft);
191                         }
192                         advise(NULL, "Try again.");
193                         done(1);
194                 }
195         }
196
197         snprintf(prompt, sizeof(prompt), myprompt, invo_name);
198         for (;;) {
199                 if (!(argp = getans(prompt, aleqs))) {
200                         done(1);
201                 }
202                 switch (smatch(*argp, aleqs)) {
203                 case DISPSW:
204                         /* display the msg being replied to or distributed */
205                         if ((cp = getenv("mhaltmsg")) && *cp) {
206                                 snprintf(buf, sizeof buf, "%s '%s'",
207                                                 listproc, cp);
208                                 system(buf);
209                         } else {
210                                 advise(NULL, "no alternate message to display");
211                         }
212                         break;
213
214                 case EDITSW:
215                         /* Call an editor on the draft file */
216                         if (*++argp)
217                                 ed = *argp++;
218                         editfile(&ed, argp, drft, NOUSE);
219                         break;
220
221                 case LISTSW:
222                         /* display the draft file */
223                         snprintf(buf, sizeof buf, "%s '%s'", listproc, drft);
224                         system(buf);
225                         break;
226
227                 case QUITSW:
228                         /* quit */
229                         if (stat(drft, &st) != NOTOK) {
230                                 advise(NULL, "draft left on %s", drft);
231                         }
232                         done(1);
233
234                 case DELETESW:
235                         /* Delete draft and exit */
236                         removefile(drft);
237                         done(1);
238
239                 case SENDSW:
240                         /* Send draft */
241                         sendfile(++argp, drft);
242                         break;
243
244                 case REFILEOPT:
245                         /* Refile the draft */
246                         if (refile(++argp, drft) == 0) {
247                                 done(0);
248                         }
249                         break;
250
251                 case CDCMDSW:
252                         /*
253                         ** Change the working directory for attachments
254                         **
255                         ** Run the directory through the user's shell
256                         ** so that we can take advantage of any syntax
257                         ** that the user is accustomed to.  Read back
258                         ** the absolute path.
259                         */
260
261                         if (*(argp+1) == NULL) {
262                                 sprintf(buf, "$SHELL -c \"cd;pwd\"");
263                         } else {
264                                 writesomecmd(buf, BUFSIZ, "cd", "pwd", argp);
265                         }
266                         if ((f = popen_in_dir(cwd, buf, "r"))) {
267                                 fgets(cwd, sizeof (cwd), f);
268
269                                 if (strchr(cwd, '\n'))
270                                         *strchr(cwd, '\n') = '\0';
271
272                                 pclose(f);
273                         } else {
274                                 advise("popen", "could not get directory");
275                         }
276
277                         break;
278
279                 case PWDCMDSW:
280                         /* Print the working directory for attachments */
281                         printf("%s\n", cwd);
282                         break;
283
284                 case LSCMDSW:
285                         /*
286                         ** List files in the current attachment working
287                         ** directory
288                         **
289                         ** Use the user's shell so that we can take
290                         ** advantage of any syntax that the user is
291                         ** accustomed to.
292                         */
293                         writelscmd(buf, sizeof(buf), argp);
294                         system_in_dir(cwd, buf);
295                         break;
296
297                 case ALISTCMDSW:
298                         /*
299                         ** List attachments on current draft.
300                         */
301                         snprintf(buf, sizeof buf, "anno -list -comp '%s' "
302                                         "-number '%s'", attach_hdr, drft);
303                         if (system(buf) != 0) {
304                                 advise(NULL, "Could not list attachment headers.");
305                         }
306                         break;
307
308                 case ATTACHCMDSW:
309                         /*
310                         ** Attach files to current draft.
311                         */
312
313                         if (*(argp+1) == NULL) {
314                                 advise(NULL, "attach command requires file argument(s).");
315                                 break;
316                         }
317
318                         /*
319                         ** Build a command line that causes the user's
320                         ** shell to list the file name arguments.
321                         ** This handles and wildcard expansion, tilde
322                         ** expansion, etc.
323                         */
324                         writelscmd(buf, sizeof(buf), argp);
325
326                         /*
327                         ** Read back the response from the shell,
328                         ** which contains a number of lines with one
329                         ** file name per line.  Remove off the newline.
330                         ** Determine whether we have an absolute or
331                         ** relative path name.  Prepend the current
332                         ** working directory to relative path names.
333                         ** Add the attachment annotation to the draft.
334                         */
335                         if ((f = popen_in_dir(cwd, buf, "r"))) {
336                                 char buf[BUFSIZ];
337
338                                 while (fgets(shell, sizeof(shell), f)) {
339                                         *(strchr(shell, '\n')) = '\0';
340
341                                         if (*shell == '/')
342                                                 sprintf(file, "%s", shell);
343                                         else {
344                                                 sprintf(file, "%s/%s", cwd,
345                                                                 shell);
346                                         }
347                                         snprintf(buf, sizeof buf,
348                                                         "anno -nodate -append "
349                                                         "-comp '%s' -text '%s'"
350                                                         " '%s'",
351                                                         attach_hdr, file,
352                                                         drft);
353                                         if (system(buf) != 0) {
354                                                 advise(NULL, "Could not add attachment header.");
355                                         }
356                                 }
357
358                                 pclose(f);
359                         } else {
360                                 advise("popen", "could not get file from shell");
361                         }
362
363                         break;
364
365                 case DETACHCMDSW:
366                         /*
367                         ** Detach files from current draft.
368                         **
369                         ** Scan the arguments for a -n.  Mixed file
370                         ** names and numbers aren't allowed, so this
371                         ** catches a -n anywhere in the argument list.
372                         */
373                         for (n = 0, arguments = argp + 1;
374                                         *arguments != NULL;
375                                         arguments++) {
376                                 if (strcmp(*arguments, "-n") == 0) {
377                                                 n = 1;
378                                                 break;
379                                 }
380                         }
381
382                         /*
383                         ** A -n was found so interpret the arguments as
384                         ** attachment numbers.  Decrement any remaining
385                         ** argument number that is greater than the one
386                         ** just processed after processing each one so
387                         ** that the numbering stays correct.
388                         */
389                         if (n == 1) {
390                                 for (arguments=argp+1; *arguments;
391                                                 arguments++) {
392                                         if (strcmp(*arguments, "-n") == 0)
393                                                 continue;
394
395                                         if (**arguments != '\0') {
396                                                 char buf[BUFSIZ];
397
398                                                 n = atoi(*arguments);
399                                                 snprintf(buf, sizeof buf, "anno -delete -comp '%s' -number '%d' '%s'", attach_hdr, n, drft);
400                                                 if (system(buf) != 0) {
401                                                         advise(NULL, "Could not delete attachment header.");
402                                                 }
403
404                                                 for (argp=arguments+1; *argp;
405                                                                 argp++) {
406                                                         if (atoi(*argp) > n) {
407                                                                 if (atoi(*argp) == 1)
408                                                                         *argp = "";
409                                                                 else
410                                                                         sprintf(*argp, "%d", atoi(*argp) - 1);
411                                                         }
412                                                 }
413                                         }
414                                 }
415                                 break;
416                         }
417                         /* else */
418
419                         /*
420                         ** The arguments are interpreted as file names.
421                         ** Run them through the user's shell for wildcard
422                         ** expansion and other goodies.  Do this from
423                         ** the current working directory if the argument
424                         ** is not an absolute path name (does not begin
425                         ** with a /).
426                         **
427                         ** We feed all the file names to the shell at
428                         ** once, otherwise you can't provide a file name
429                         ** with a space in it.
430                         */
431                         writelscmd(buf, sizeof(buf), argp);
432                         if ((f = popen_in_dir(cwd, buf, "r"))) {
433                                 while (fgets(shell, sizeof (shell), f)) {
434                                         *(strchr(shell, '\n')) = '\0';
435                                         snprintf(buf, sizeof buf,
436                                                         "anno -delete -comp "
437                                                         "'%s' -text '%s' '%s'",
438                                                         attach_hdr, shell,
439                                                         drft);
440                                         if (system(buf) != 0) {
441                                                 advise(NULL, "Could not delete attachment header.");
442                                         }
443                                 }
444                                 pclose(f);
445                         } else {
446                                 advise("popen", "could not get file from shell");
447                         }
448
449                         break;
450
451                 default:
452                         /* Unknown command */
453                         advise(NULL, "say what?");
454                         break;
455                 }
456         }
457         /*NOTREACHED*/
458 }
459
460
461
462 /*
463 ** Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
464 ** trailcmd".
465 */
466 static void
467 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
468 {
469         char *cp;
470         /*
471         ** Note that we do not quote -- the argp from the user
472         ** is assumed to be quoted as they desire. (We can't treat
473         ** it as pure literal as that would prevent them using ~,
474         ** wildcards, etc.) The buffer produced by this function
475         ** should be given to popen_in_dir() or system_in_dir() so
476         ** that the current working directory is set correctly.
477         */
478         int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
479         /*
480         ** NB that some snprintf() return -1 on overflow rather than the
481         ** new C99 mandated 'number of chars that would have been written'
482         */
483         /*
484         ** length checks here and inside the loop allow for the
485         ** trailing ';', trailcmd, '"' and NUL
486         */
487         int trailln = strlen(trailcmd) + 3;
488         if (ln < 0 || ln + trailln > bufsz)
489                 adios(NULL, "arguments too long");
490
491         cp = buf + ln;
492
493         while (*++argp) {
494                 ln = strlen(*argp);
495                 /* +1 for leading space */
496                 if (ln + trailln + 1 > bufsz - (cp-buf))
497                         adios(NULL, "arguments too long");
498                 *cp++ = ' ';
499                 memcpy(cp, *argp, ln+1);
500                 cp += ln;
501         }
502         if (*trailcmd) {
503                 *cp++ = ';';
504                 strcpy(cp, trailcmd);
505                 cp += trailln - 3;
506         }
507         *cp++ = '"';
508         *cp = 0;
509 }
510
511 /*
512 ** Build a command line that causes the user's shell to list the file name
513 ** arguments.  This handles and wildcard expansion, tilde expansion, etc.
514 */
515 static void
516 writelscmd(char *buf, int bufsz, char **argp)
517 {
518         writesomecmd(buf, bufsz, "ls", "", argp);
519 }
520
521 /*
522 ** Like system(), but run the command in directory dir.
523 ** This assumes the program is single-threaded!
524 */
525 static int
526 system_in_dir(const char *dir, const char *cmd)
527 {
528         char olddir[BUFSIZ];
529         int r;
530         if (getcwd(olddir, sizeof(olddir)) == 0)
531                 adios("getcwd", "could not get working directory");
532         if (chdir(dir) != 0)
533                 adios("chdir", "could not change working directory");
534         r = system(cmd);
535         if (chdir(olddir) != 0)
536                 adios("chdir", "could not change working directory");
537         return r;
538 }
539
540 /* ditto for popen() */
541 static FILE*
542 popen_in_dir(const char *dir, const char *cmd, const char *type)
543 {
544         char olddir[BUFSIZ];
545         FILE *f;
546         if (getcwd(olddir, sizeof(olddir)) == 0)
547                 adios("getcwd", "could not get working directory");
548         if (chdir(dir) != 0)
549                 adios("chdir", "could not change working directory");
550         f = popen(cmd, type);
551         if (chdir(olddir) != 0)
552                 adios("chdir", "could not change working directory");
553         return f;
554 }
555
556
557 /*
558 ** EDIT
559 */
560
561 static char *edsave = NULL;  /* the editor we used previously */
562
563
564 static int
565 editfile(char **ed, char **arg, char *file, int use)
566 {
567         int pid, status, vecp;
568         char *cp, *vec[MAXARGS];
569
570         if (!*ed || !**ed) {
571                 /* We have no explicit editor. */
572                 if (edsave) {
573                         /* Use the previous editor ... */
574                         *ed = edsave;
575                         if (!(cp = mhbasename(*ed)))
576                                 cp = *ed;
577
578                         /* but prefer one specified via "editor-next" */
579                         cp = concat(cp, "-next", NULL);
580                         if ((cp = context_find(cp)))
581                                 *ed = cp;
582                 } else {
583                         /* set initial editor */
584                         *ed = defaulteditor;
585                 }
586         }
587
588         context_save();
589         fflush(stdout);
590
591         switch (pid = fork()) {
592         case NOTOK:
593                 advise("fork", "unable to");
594                 status = NOTOK;
595                 break;
596
597         case OK:
598                 vecp = 0;
599                 vec[vecp++] = mhbasename(*ed);
600                 if (arg)
601                         while (*arg)
602                                 vec[vecp++] = *arg++;
603                 vec[vecp++] = file;
604                 vec[vecp] = NULL;
605
606                 execvp(*ed, vec);
607                 fprintf(stderr, "%s: unable to exec ", invo_name);
608                 perror(*ed);
609                 _exit(-1);
610
611         default:
612                 if ((status = pidwait(pid, NOTOK))) {
613                         if ((status & 0xff00) == 0xff00) {
614                                 /* cmd not found or pidwait() failed */
615                                 status = -1;
616                                 break;
617                         }
618                         if (status & 0x00ff) {
619                                 /* terminated by signal */
620                                 advise(NULL, "%s terminated by signal %d",
621                                                 *ed, status & 0x7f);
622                         } else {
623                                 /* failure exit */
624                                 advise(NULL, "%s exited with return code %d",
625                                                 *ed, (status & 0xff00) >> 8);
626                         }
627                         status = -1;
628                         break;
629                 }
630         }
631
632         /* remember which editor we used */
633         edsave = getcpy(*ed);
634
635         *ed = NULL;
636
637         return status;
638 }
639
640
641 /*
642 ** SEND
643 */
644
645 static int
646 sendfile(char **arg, char *file)
647 {
648         pid_t child_id;
649         int vecp;
650         char *vec[MAXARGS];
651
652         context_save();  /* save the context file */
653         fflush(stdout);
654
655         switch (child_id = fork()) {
656         case NOTOK:
657                 advise(NULL, "unable to fork, so sending directly...");
658                 /* fall */
659         case OK:
660                 vecp = 0;
661                 vec[vecp++] = invo_name;
662                 if (arg)
663                         while (*arg)
664                                 vec[vecp++] = *arg++;
665                 vec[vecp++] = file;
666                 vec[vecp] = NULL;
667
668                 execvp("send", vec);
669                 fprintf(stderr, "%s: unable to exec ", invo_name);
670                 perror("send");
671                 _exit(-1);
672
673         default:
674                 if (pidwait(child_id, OK) == 0)
675                         done(0);
676                 return 1;
677         }
678 }
679
680
681 /*
682 ** refile msg into another folder
683 */
684 static int
685 refile(char **arg, char *file)
686 {
687         pid_t pid;
688         register int vecp;
689         char *vec[MAXARGS];
690
691         vecp = 0;
692         vec[vecp++] = "refile";
693         vec[vecp++] = "-nolink";  /* override bad .mh_profile defaults */
694         vec[vecp++] = "-file";
695         vec[vecp++] = file;
696
697         while (arg && *arg) {
698                 vec[vecp++] = *arg++;
699         }
700         vec[vecp] = NULL;
701
702         context_save();  /* save the context file */
703         fflush(stdout);
704
705         switch (pid = fork()) {
706         case -1:
707                 advise("fork", "unable to");
708                 return -1;
709
710         case 0:
711                 execvp(*vec, vec);
712                 fprintf(stderr, "%s: unable to exec ", invo_name);
713                 perror(*vec);
714                 _exit(-1);
715
716         default:
717                 return (pidwait(pid, -1));
718         }
719 }
720
721
722 /*
723 ** Remove the draft file
724 */
725
726 static int
727 removefile(char *drft)
728 {
729         if (unlink(drft) == NOTOK)
730                 adios(drft, "unable to unlink");
731
732         return OK;
733 }