bbb468dafb768bc16a206519265174e23da3b6fb
[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 all -text IGNORE '%s'",
303                                         attach_hdr, drft);
304                         if (system(buf) != 0) {
305                                 advise(NULL, "Could not list attachment headers.");
306                         }
307                         break;
308
309                 case ATTACHCMDSW:
310                         /*
311                         ** Attach files to current draft.
312                         */
313
314                         if (*(argp+1) == NULL) {
315                                 advise(NULL, "attach command requires file argument(s).");
316                                 break;
317                         }
318
319                         /*
320                         ** Build a command line that causes the user's
321                         ** shell to list the file name arguments.
322                         ** This handles and wildcard expansion, tilde
323                         ** expansion, etc.
324                         */
325                         writelscmd(buf, sizeof(buf), argp);
326
327                         /*
328                         ** Read back the response from the shell,
329                         ** which contains a number of lines with one
330                         ** file name per line.  Remove off the newline.
331                         ** Determine whether we have an absolute or
332                         ** relative path name.  Prepend the current
333                         ** working directory to relative path names.
334                         ** Add the attachment annotation to the draft.
335                         */
336                         if ((f = popen_in_dir(cwd, buf, "r"))) {
337                                 char buf[BUFSIZ];
338
339                                 while (fgets(shell, sizeof(shell), f)) {
340                                         *(strchr(shell, '\n')) = '\0';
341
342                                         if (*shell == '/')
343                                                 sprintf(file, "%s", shell);
344                                         else {
345                                                 sprintf(file, "%s/%s", cwd,
346                                                                 shell);
347                                         }
348                                         snprintf(buf, sizeof buf,
349                                                         "anno -nodate -append "
350                                                         "-comp '%s' -text '%s'"
351                                                         " '%s'",
352                                                         attach_hdr, file,
353                                                         drft);
354                                         if (system(buf) != 0) {
355                                                 advise(NULL, "Could not add attachment header.");
356                                         }
357                                 }
358
359                                 pclose(f);
360                         } else {
361                                 advise("popen", "could not get file from shell");
362                         }
363
364                         break;
365
366                 case DETACHCMDSW:
367                         /*
368                         ** Detach files from current draft.
369                         **
370                         ** Scan the arguments for a -n.  Mixed file
371                         ** names and numbers aren't allowed, so this
372                         ** catches a -n anywhere in the argument list.
373                         */
374                         for (n = 0, arguments = argp + 1;
375                                         *arguments != NULL;
376                                         arguments++) {
377                                 if (strcmp(*arguments, "-n") == 0) {
378                                                 n = 1;
379                                                 break;
380                                 }
381                         }
382
383                         /*
384                         ** A -n was found so interpret the arguments as
385                         ** attachment numbers.  Decrement any remaining
386                         ** argument number that is greater than the one
387                         ** just processed after processing each one so
388                         ** that the numbering stays correct.
389                         */
390                         if (n == 1) {
391                                 for (arguments=argp+1; *arguments;
392                                                 arguments++) {
393                                         if (strcmp(*arguments, "-n") == 0)
394                                                 continue;
395
396                                         if (**arguments != '\0') {
397                                                 char buf[BUFSIZ];
398
399                                                 n = atoi(*arguments);
400                                                 snprintf(buf, sizeof buf, "anno -delete -comp '%s' -number '%d' '%s'", attach_hdr, n, drft);
401                                                 if (system(buf) != 0) {
402                                                         advise(NULL, "Could not delete attachment header.");
403                                                 }
404
405                                                 for (argp=arguments+1; *argp;
406                                                                 argp++) {
407                                                         if (atoi(*argp) > n) {
408                                                                 if (atoi(*argp) == 1)
409                                                                         *argp = "";
410                                                                 else
411                                                                         sprintf(*argp, "%d", atoi(*argp) - 1);
412                                                         }
413                                                 }
414                                         }
415                                 }
416                                 break;
417                         }
418                         /* else */
419
420                         /*
421                         ** The arguments are interpreted as file names.
422                         ** Run them through the user's shell for wildcard
423                         ** expansion and other goodies.  Do this from
424                         ** the current working directory if the argument
425                         ** is not an absolute path name (does not begin
426                         ** with a /).
427                         **
428                         ** We feed all the file names to the shell at
429                         ** once, otherwise you can't provide a file name
430                         ** with a space in it.
431                         */
432                         writelscmd(buf, sizeof(buf), argp);
433                         if ((f = popen_in_dir(cwd, buf, "r"))) {
434                                 while (fgets(shell, sizeof (shell), f)) {
435                                         *(strchr(shell, '\n')) = '\0';
436                                         snprintf(buf, sizeof buf,
437                                                         "anno -delete -comp "
438                                                         "'%s' -text '%s' '%s'",
439                                                         attach_hdr, shell,
440                                                         drft);
441                                         if (system(buf) != 0) {
442                                                 advise(NULL, "Could not delete attachment header.");
443                                         }
444                                 }
445                                 pclose(f);
446                         } else {
447                                 advise("popen", "could not get file from shell");
448                         }
449
450                         break;
451
452                 default:
453                         /* Unknown command */
454                         advise(NULL, "say what?");
455                         break;
456                 }
457         }
458         /*NOTREACHED*/
459 }
460
461
462
463 /*
464 ** Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
465 ** trailcmd".
466 */
467 static void
468 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
469 {
470         char *cp;
471         /*
472         ** Note that we do not quote -- the argp from the user
473         ** is assumed to be quoted as they desire. (We can't treat
474         ** it as pure literal as that would prevent them using ~,
475         ** wildcards, etc.) The buffer produced by this function
476         ** should be given to popen_in_dir() or system_in_dir() so
477         ** that the current working directory is set correctly.
478         */
479         int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
480         /*
481         ** NB that some snprintf() return -1 on overflow rather than the
482         ** new C99 mandated 'number of chars that would have been written'
483         */
484         /*
485         ** length checks here and inside the loop allow for the
486         ** trailing ';', trailcmd, '"' and NUL
487         */
488         int trailln = strlen(trailcmd) + 3;
489         if (ln < 0 || ln + trailln > bufsz)
490                 adios(NULL, "arguments too long");
491
492         cp = buf + ln;
493
494         while (*++argp) {
495                 ln = strlen(*argp);
496                 /* +1 for leading space */
497                 if (ln + trailln + 1 > bufsz - (cp-buf))
498                         adios(NULL, "arguments too long");
499                 *cp++ = ' ';
500                 memcpy(cp, *argp, ln+1);
501                 cp += ln;
502         }
503         if (*trailcmd) {
504                 *cp++ = ';';
505                 strcpy(cp, trailcmd);
506                 cp += trailln - 3;
507         }
508         *cp++ = '"';
509         *cp = 0;
510 }
511
512 /*
513 ** Build a command line that causes the user's shell to list the file name
514 ** arguments.  This handles and wildcard expansion, tilde expansion, etc.
515 */
516 static void
517 writelscmd(char *buf, int bufsz, char **argp)
518 {
519         writesomecmd(buf, bufsz, "ls", "", argp);
520 }
521
522 /*
523 ** Like system(), but run the command in directory dir.
524 ** This assumes the program is single-threaded!
525 */
526 static int
527 system_in_dir(const char *dir, const char *cmd)
528 {
529         char olddir[BUFSIZ];
530         int r;
531         if (getcwd(olddir, sizeof(olddir)) == 0)
532                 adios("getcwd", "could not get working directory");
533         if (chdir(dir) != 0)
534                 adios("chdir", "could not change working directory");
535         r = system(cmd);
536         if (chdir(olddir) != 0)
537                 adios("chdir", "could not change working directory");
538         return r;
539 }
540
541 /* ditto for popen() */
542 static FILE*
543 popen_in_dir(const char *dir, const char *cmd, const char *type)
544 {
545         char olddir[BUFSIZ];
546         FILE *f;
547         if (getcwd(olddir, sizeof(olddir)) == 0)
548                 adios("getcwd", "could not get working directory");
549         if (chdir(dir) != 0)
550                 adios("chdir", "could not change working directory");
551         f = popen(cmd, type);
552         if (chdir(olddir) != 0)
553                 adios("chdir", "could not change working directory");
554         return f;
555 }
556
557
558 /*
559 ** EDIT
560 */
561
562 static char *edsave = NULL;  /* the editor we used previously */
563
564
565 static int
566 editfile(char **ed, char **arg, char *file, int use)
567 {
568         int pid, status, vecp;
569         char *cp, *vec[MAXARGS];
570
571         if (!*ed || !**ed) {
572                 /* We have no explicit editor. */
573                 if (edsave) {
574                         /* Use the previous editor ... */
575                         *ed = edsave;
576                         if (!(cp = mhbasename(*ed)))
577                                 cp = *ed;
578
579                         /* but prefer one specified via "editor-next" */
580                         cp = concat(cp, "-next", NULL);
581                         if ((cp = context_find(cp)))
582                                 *ed = cp;
583                 } else {
584                         /* set initial editor */
585                         *ed = defaulteditor;
586                 }
587         }
588
589         context_save();
590         fflush(stdout);
591
592         switch (pid = fork()) {
593         case NOTOK:
594                 advise("fork", "unable to");
595                 status = NOTOK;
596                 break;
597
598         case OK:
599                 vecp = 0;
600                 vec[vecp++] = mhbasename(*ed);
601                 if (arg)
602                         while (*arg)
603                                 vec[vecp++] = *arg++;
604                 vec[vecp++] = file;
605                 vec[vecp] = NULL;
606
607                 execvp(*ed, vec);
608                 fprintf(stderr, "%s: unable to exec ", invo_name);
609                 perror(*ed);
610                 _exit(-1);
611
612         default:
613                 if ((status = pidwait(pid, NOTOK))) {
614                         if ((status & 0xff00) == 0xff00) {
615                                 /* cmd not found or pidwait() failed */
616                                 status = -1;
617                                 break;
618                         }
619                         if (status & 0x00ff) {
620                                 /* terminated by signal */
621                                 advise(NULL, "%s terminated by signal %d",
622                                                 *ed, status & 0x7f);
623                         } else {
624                                 /* failure exit */
625                                 advise(NULL, "%s exited with return code %d",
626                                                 *ed, (status & 0xff00) >> 8);
627                         }
628                         status = -1;
629                         break;
630                 }
631         }
632
633         /* remember which editor we used */
634         edsave = getcpy(*ed);
635
636         *ed = NULL;
637
638         return status;
639 }
640
641
642 /*
643 ** SEND
644 */
645
646 static int
647 sendfile(char **arg, char *file)
648 {
649         pid_t child_id;
650         int vecp;
651         char *vec[MAXARGS];
652
653         context_save();  /* save the context file */
654         fflush(stdout);
655
656         switch (child_id = fork()) {
657         case NOTOK:
658                 advise(NULL, "unable to fork, so sending directly...");
659                 /* fall */
660         case OK:
661                 vecp = 0;
662                 vec[vecp++] = invo_name;
663                 if (arg)
664                         while (*arg)
665                                 vec[vecp++] = *arg++;
666                 vec[vecp++] = file;
667                 vec[vecp] = NULL;
668
669                 execvp("send", vec);
670                 fprintf(stderr, "%s: unable to exec ", invo_name);
671                 perror("send");
672                 _exit(-1);
673
674         default:
675                 if (pidwait(child_id, OK) == 0)
676                         done(0);
677                 return 1;
678         }
679 }
680
681
682 /*
683 ** refile msg into another folder
684 */
685 static int
686 refile(char **arg, char *file)
687 {
688         pid_t pid;
689         register int vecp;
690         char *vec[MAXARGS];
691
692         vecp = 0;
693         vec[vecp++] = "refile";
694         vec[vecp++] = "-nolink";  /* override bad .mh_profile defaults */
695         vec[vecp++] = "-file";
696         vec[vecp++] = file;
697
698         while (arg && *arg) {
699                 vec[vecp++] = *arg++;
700         }
701         vec[vecp] = NULL;
702
703         context_save();  /* save the context file */
704         fflush(stdout);
705
706         switch (pid = fork()) {
707         case -1:
708                 advise("fork", "unable to");
709                 return -1;
710
711         case 0:
712                 execvp(*vec, vec);
713                 fprintf(stderr, "%s: unable to exec ", invo_name);
714                 perror(*vec);
715                 _exit(-1);
716
717         default:
718                 return (pidwait(pid, -1));
719         }
720 }
721
722
723 /*
724 ** Remove the draft file
725 */
726
727 static int
728 removefile(char *drft)
729 {
730         if (unlink(drft) == NOTOK)
731                 adios(drft, "unable to unlink");
732
733         return OK;
734 }