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