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