6cb96f775a286d64c57848999b2b40242f8e3abc
[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 numbers          This option removes attachments by
35 **                                attachment number from the draft.
36 */
37
38 #include <h/mh.h>
39 #include <fcntl.h>
40 #include <signal.h>
41 #include <h/mime.h>
42 #include <h/utils.h>
43
44 static struct swit switches[] = {
45 #define EDITRSW  0
46         { "editor editor", 0 },
47 #define PRMPTSW  1
48         { "prompt string", 0 },
49 #define VERSIONSW  2
50         { "Version", 0 },
51 #define HELPSW  3
52         { "help", 0 },
53         { NULL, 0 }
54 };
55
56 /*
57 ** Options at the "whatnow" prompt
58 */
59 static struct swit aleqs[] = {
60 #define EDITSW  0
61         { "edit [editor [switches]]", 0 },
62 #define LISTSW  1
63         { "list", 0 },
64 #define DISPSW  2
65         { "display", 0 },
66 #define WHOMSW  3
67         { "whom", 0 },
68 #define SENDSW  4
69         { "send", 0 },
70 #define REFILEOPT  5
71         { "refile +folder", 0 },
72 #define DELETESW  6
73         { "delete", 0 },
74 #define QUITSW  7
75         { "quit", 0 },
76 #define CDCMDSW  8
77         { "cd [directory]", 0 },
78 #define PWDCMDSW  9
79         { "pwd", 0 },
80 #define LSCMDSW  10
81         { "ls", 0 },
82 #define ALISTCMDSW  11
83         { "alist", 0 },
84 #define ATTACHCMDSW  12
85         { "attach files", 0 },
86 #define DETACHCMDSW  13
87         { "detach numbers", 0 },
88         { NULL, 0 }
89 };
90
91 static char *myprompt = "\nWhat now? ";
92
93 /*
94 ** static prototypes
95 */
96 static int editfile(char **, char **, char *, int);
97 static int sendfile(char **, char *);
98 static int refile(char **, char *);
99 static int removefile(char *);
100 static void writelscmd(char *, int, char **);
101 static void writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp);
102 static FILE* popen_in_dir(const char *dir, const char *cmd, const char *type);
103 static int system_in_dir(const char *dir, const char *cmd);
104
105
106 int
107 main(int argc, char **argv)
108 {
109         int use = 0;
110         char *cp;
111         char *ed = NULL, *drft = NULL;
112         char buf[BUFSIZ], prompt[BUFSIZ];
113         char **argp, **arguments;
114         struct stat st;
115         char cwd[MAXPATHLEN + 1];  /* current working directory */
116         char file[MAXPATHLEN + 1];  /* file name buffer */
117         char shell[MAXPATHLEN + 1];  /* shell response buffer */
118         FILE *f;  /* read pointer for bgnd proc */
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, switches)) {
140                         case AMBIGSW:
141                                 ambigsw(cp, switches);
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, switches, 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                         ** Interpret the arguments as
370                         ** attachment numbers.  Decrement any remaining
371                         ** argument number that is greater than the one
372                         ** just processed after processing each one so
373                         ** that the numbering stays correct.
374                         */
375                         for (arguments=argp+1; *arguments; arguments++) {
376                                 char buf[BUFSIZ];
377                                 int n;
378
379                                 if (**arguments == '\0') {
380                                         continue;
381                                 }
382
383                                 n = atoi(*arguments);
384                                 snprintf(buf, sizeof buf, "anno -delete "
385                                                 "-comp '%s' -number '%d' "
386                                                 "'%s'",
387                                                 attach_hdr, n, drft);
388                                 if (system(buf) != 0) {
389                                         advise(NULL, "Could not delete attachment header.");
390                                 }
391
392                                 for (argp=arguments+1; *argp; argp++) {
393                                         if (atoi(*argp) > n) {
394                                                 if (atoi(*argp) == 1) {
395                                                         *argp = "";
396                                                 } else {
397                                                         sprintf(*argp, "%d", atoi(*argp) - 1);
398                                                 }
399                                         }
400                                 }
401                         }
402                         break;
403
404                 case WHOMSW:
405                         /* list recipients */
406                         snprintf(buf, sizeof buf, "%s '%s'", "whom", drft);
407                         system(buf);
408                         break;
409
410                 default:
411                         /* Unknown command */
412                         advise(NULL, "say what?");
413                         break;
414                 }
415         }
416         /*NOTREACHED*/
417 }
418
419
420
421 /*
422 ** Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
423 ** trailcmd".
424 */
425 static void
426 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
427 {
428         char *cp;
429         /*
430         ** Note that we do not quote -- the argp from the user
431         ** is assumed to be quoted as they desire. (We can't treat
432         ** it as pure literal as that would prevent them using ~,
433         ** wildcards, etc.) The buffer produced by this function
434         ** should be given to popen_in_dir() or system_in_dir() so
435         ** that the current working directory is set correctly.
436         */
437         int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
438         /*
439         ** NB that some snprintf() return -1 on overflow rather than the
440         ** new C99 mandated 'number of chars that would have been written'
441         */
442         /*
443         ** length checks here and inside the loop allow for the
444         ** trailing ';', trailcmd, '"' and NUL
445         */
446         int trailln = strlen(trailcmd) + 3;
447         if (ln < 0 || ln + trailln > bufsz)
448                 adios(NULL, "arguments too long");
449
450         cp = buf + ln;
451
452         while (*++argp) {
453                 ln = strlen(*argp);
454                 /* +1 for leading space */
455                 if (ln + trailln + 1 > bufsz - (cp-buf))
456                         adios(NULL, "arguments too long");
457                 *cp++ = ' ';
458                 memcpy(cp, *argp, ln+1);
459                 cp += ln;
460         }
461         if (*trailcmd) {
462                 *cp++ = ';';
463                 strcpy(cp, trailcmd);
464                 cp += trailln - 3;
465         }
466         *cp++ = '"';
467         *cp = 0;
468 }
469
470 /*
471 ** Build a command line that causes the user's shell to list the file name
472 ** arguments.  This handles and wildcard expansion, tilde expansion, etc.
473 */
474 static void
475 writelscmd(char *buf, int bufsz, char **argp)
476 {
477         writesomecmd(buf, bufsz, "ls", "", argp);
478 }
479
480 /*
481 ** Like system(), but run the command in directory dir.
482 ** This assumes the program is single-threaded!
483 */
484 static int
485 system_in_dir(const char *dir, const char *cmd)
486 {
487         char olddir[BUFSIZ];
488         int r;
489         if (getcwd(olddir, sizeof(olddir)) == 0)
490                 adios("getcwd", "could not get working directory");
491         if (chdir(dir) != 0)
492                 adios("chdir", "could not change working directory");
493         r = system(cmd);
494         if (chdir(olddir) != 0)
495                 adios("chdir", "could not change working directory");
496         return r;
497 }
498
499 /* ditto for popen() */
500 static FILE*
501 popen_in_dir(const char *dir, const char *cmd, const char *type)
502 {
503         char olddir[BUFSIZ];
504         FILE *f;
505         if (getcwd(olddir, sizeof(olddir)) == 0)
506                 adios("getcwd", "could not get working directory");
507         if (chdir(dir) != 0)
508                 adios("chdir", "could not change working directory");
509         f = popen(cmd, type);
510         if (chdir(olddir) != 0)
511                 adios("chdir", "could not change working directory");
512         return f;
513 }
514
515
516 /*
517 ** EDIT
518 */
519
520 static char *edsave = NULL;  /* the editor we used previously */
521
522
523 static int
524 editfile(char **ed, char **arg, char *file, int use)
525 {
526         int pid, status, vecp;
527         char *cp, *vec[MAXARGS];
528
529         if (!*ed || !**ed) {
530                 /* We have no explicit editor. */
531                 if (edsave) {
532                         /* Use the previous editor ... */
533                         *ed = edsave;
534                         if (!(cp = mhbasename(*ed)))
535                                 cp = *ed;
536
537                         /* but prefer one specified via "editor-next" */
538                         cp = concat(cp, "-next", NULL);
539                         if ((cp = context_find(cp)))
540                                 *ed = cp;
541                 } else {
542                         /* set initial editor */
543                         *ed = defaulteditor;
544                 }
545         }
546
547         context_save();
548         fflush(stdout);
549
550         switch (pid = fork()) {
551         case NOTOK:
552                 advise("fork", "unable to");
553                 status = NOTOK;
554                 break;
555
556         case OK:
557                 vecp = 0;
558                 vec[vecp++] = mhbasename(*ed);
559                 if (arg)
560                         while (*arg)
561                                 vec[vecp++] = *arg++;
562                 vec[vecp++] = file;
563                 vec[vecp] = NULL;
564
565                 execvp(*ed, vec);
566                 fprintf(stderr, "%s: unable to exec ", invo_name);
567                 perror(*ed);
568                 _exit(-1);
569
570         default:
571                 if ((status = pidwait(pid, NOTOK))) {
572                         if ((status & 0xff00) == 0xff00) {
573                                 /* cmd not found or pidwait() failed */
574                                 status = -1;
575                                 break;
576                         }
577                         if (status & 0x00ff) {
578                                 /* terminated by signal */
579                                 advise(NULL, "%s terminated by signal %d",
580                                                 *ed, status & 0x7f);
581                         } else {
582                                 /* failure exit */
583                                 advise(NULL, "%s exited with return code %d",
584                                                 *ed, (status & 0xff00) >> 8);
585                         }
586                         status = -1;
587                         break;
588                 }
589         }
590
591         /* remember which editor we used */
592         edsave = getcpy(*ed);
593
594         *ed = NULL;
595
596         return status;
597 }
598
599
600 /*
601 ** SEND
602 */
603
604 static int
605 sendfile(char **arg, char *file)
606 {
607         pid_t child_id;
608         int vecp;
609         char *vec[MAXARGS];
610
611         context_save();  /* save the context file */
612         fflush(stdout);
613
614         switch (child_id = fork()) {
615         case NOTOK:
616                 advise(NULL, "unable to fork, so sending directly...");
617                 /* fall */
618         case OK:
619                 vecp = 0;
620                 vec[vecp++] = "send";
621                 if (arg)
622                         while (*arg)
623                                 vec[vecp++] = *arg++;
624                 vec[vecp++] = file;
625                 vec[vecp] = NULL;
626
627                 execvp("send", vec);
628                 fprintf(stderr, "%s: unable to exec ", invo_name);
629                 perror("send");
630                 _exit(-1);
631
632         default:
633                 if (pidwait(child_id, OK) == 0)
634                         done(0);
635                 return 1;
636         }
637 }
638
639
640 /*
641 ** refile msg into another folder
642 */
643 static int
644 refile(char **arg, char *file)
645 {
646         pid_t pid;
647         register int vecp;
648         char *vec[MAXARGS];
649
650         vecp = 0;
651         vec[vecp++] = "refile";
652         vec[vecp++] = "-nolink";  /* override bad .mh_profile defaults */
653         vec[vecp++] = "-file";
654         vec[vecp++] = file;
655
656         while (arg && *arg) {
657                 vec[vecp++] = *arg++;
658         }
659         vec[vecp] = NULL;
660
661         context_save();  /* save the context file */
662         fflush(stdout);
663
664         switch (pid = fork()) {
665         case -1:
666                 advise("fork", "unable to");
667                 return -1;
668
669         case 0:
670                 execvp(*vec, vec);
671                 fprintf(stderr, "%s: unable to exec ", invo_name);
672                 perror(*vec);
673                 _exit(-1);
674
675         default:
676                 return (pidwait(pid, -1));
677         }
678 }
679
680
681 /*
682 ** Remove the draft file
683 */
684
685 static int
686 removefile(char *drft)
687 {
688         if (unlink(drft) == NOTOK)
689                 adios(drft, "unable to unlink");
690
691         return OK;
692 }