Merge ../mmh
[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                                 exit(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                                 exit(0);
123                         case VERSIONSW:
124                                 print_version(invo_name);
125                                 exit(0);
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                         /* sysexits.h EX_SOFTWARE */
165                         exit(1);
166                 }
167         }
168
169         snprintf(prompt, sizeof(prompt), myprompt, invo_name);
170         for (;;) {
171                 if (!(argp = getans(prompt, aleqs))) {
172                         exit(1);
173                 }
174                 switch (smatch(*argp, aleqs)) {
175                 case DISPSW:
176                         /* display the msg being replied to or distributed */
177                         if ((cp = getenv("mhaltmsg")) && *cp) {
178                                 execprogl(listproc, listproc, "-file", cp,
179                                                 (char *)NULL);
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                         execprogl(listproc, listproc, "-file", drft,
195                                         (char *)NULL);
196                         break;
197
198                 case QUITSW:
199                         /* quit */
200                         if (stat(drft, &st) != NOTOK) {
201                                 advise(NULL, "draft left on %s", drft);
202                         }
203                         exit(1);
204
205                 case DELETESW:
206                         /* Delete draft and exit */
207                         removefile(drft);
208                         exit(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                                 exit(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                         if (execprogl("anno", "anno", "-list", "-comp",
273                                         attach_hdr, "-number", drft,
274                                         (char *)NULL) != 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                                 advise("popen", "could not get file from shell");
308                                 break;
309                         }
310
311                         while (fgets(shell, sizeof(shell), f)) {
312                                 *(strchr(shell, '\n')) = '\0';
313
314                                 if (*shell == '/')
315                                         sprintf(file, "%s", shell);
316                                 else {
317                                         sprintf(file, "%s/%s", cwd, shell);
318                                 }
319                                 if (execprogl("anno", "anno",
320                                                 "-nodate", "-append",
321                                                 "-comp", attach_hdr,
322                                                 "-text", file,
323                                                 drft, (char *)NULL) != 0) {
324                                         advise(NULL, "Could not add attachment header.");
325                                 }
326                         }
327                         pclose(f);
328                         break;
329
330                 case DETACHCMDSW:
331                         /*
332                         ** Detach files from current draft.
333                         **
334                         ** Interpret the arguments as
335                         ** attachment numbers.  Decrement any remaining
336                         ** argument number that is greater than the one
337                         ** just processed after processing each one so
338                         ** that the numbering stays correct.
339                         */
340                         for (arguments=argp+1; *arguments; arguments++) {
341                                 int n;
342
343                                 if (**arguments == '\0') {
344                                         continue;
345                                 }
346
347                                 if (execprogl("anno", "anno", "-delete",
348                                                 "-comp", attach_hdr,
349                                                 "-number", *arguments, drft,
350                                                 (char *)NULL) != 0) {
351                                         advise(NULL, "Could not delete attachment header.");
352                                 }
353
354                                 n = atoi(*arguments);
355                                 for (argp=arguments+1; *argp; argp++) {
356                                         if (atoi(*argp) > n) {
357                                                 if (atoi(*argp) == 1) {
358                                                         *argp = "";
359                                                 } else {
360                                                         sprintf(*argp, "%d", atoi(*argp) - 1);
361                                                 }
362                                         }
363                                 }
364                         }
365                         break;
366
367                 case WHOMSW:
368                         /* list recipients */
369                         execprogl("whom", "whom", drft, (char *)NULL);
370                         break;
371
372                 default:
373                         /* Unknown command */
374                         advise(NULL, "say what?");
375                         break;
376                 }
377         }
378         /*NOTREACHED*/
379 }
380
381
382
383 /*
384 ** Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
385 ** trailcmd".
386 */
387 static void
388 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
389 {
390         char *cp;
391         /*
392         ** Note that we do not quote -- the argp from the user
393         ** is assumed to be quoted as they desire. (We can't treat
394         ** it as pure literal as that would prevent them using ~,
395         ** wildcards, etc.) The buffer produced by this function
396         ** should be given to popen_in_dir() or system_in_dir() so
397         ** that the current working directory is set correctly.
398         */
399         int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
400         /*
401         ** NB that some snprintf() return -1 on overflow rather than the
402         ** new C99 mandated 'number of chars that would have been written'
403         */
404         /*
405         ** length checks here and inside the loop allow for the
406         ** trailing ';', trailcmd, '"' and NUL
407         */
408         int trailln = strlen(trailcmd) + 3;
409         if (ln < 0 || ln + trailln > bufsz)
410                 adios(NULL, "arguments too long");
411
412         cp = buf + ln;
413
414         while (*++argp) {
415                 ln = strlen(*argp);
416                 /* +1 for leading space */
417                 if (ln + trailln + 1 > bufsz - (cp-buf))
418                         adios(NULL, "arguments too long");
419                 *cp++ = ' ';
420                 memcpy(cp, *argp, ln+1);
421                 cp += ln;
422         }
423         if (*trailcmd) {
424                 *cp++ = ';';
425                 strcpy(cp, trailcmd);
426                 cp += trailln - 3;
427         }
428         *cp++ = '"';
429         *cp = 0;
430 }
431
432 /*
433 ** Build a command line that causes the user's shell to list the file name
434 ** arguments.  This handles and wildcard expansion, tilde expansion, etc.
435 */
436 static void
437 writelscmd(char *buf, int bufsz, char **argp)
438 {
439         writesomecmd(buf, bufsz, "ls", "", argp);
440 }
441
442 /*
443 ** Like system(), but run the command in directory dir.
444 ** This assumes the program is single-threaded!
445 */
446 static int
447 system_in_dir(const char *dir, const char *cmd)
448 {
449         char olddir[BUFSIZ];
450         int r;
451         if (getcwd(olddir, sizeof(olddir)) == 0)
452                 adios("getcwd", "could not get working directory");
453         if (chdir(dir) != 0)
454                 adios("chdir", "could not change working directory");
455         r = system(cmd);
456         if (chdir(olddir) != 0)
457                 adios("chdir", "could not change working directory");
458         return r;
459 }
460
461 /* ditto for popen() */
462 static FILE*
463 popen_in_dir(const char *dir, const char *cmd, const char *type)
464 {
465         char olddir[BUFSIZ];
466         FILE *f;
467         if (getcwd(olddir, sizeof(olddir)) == 0)
468                 adios("getcwd", "could not get working directory");
469         if (chdir(dir) != 0)
470                 adios("chdir", "could not change working directory");
471         f = popen(cmd, type);
472         if (chdir(olddir) != 0)
473                 adios("chdir", "could not change working directory");
474         return f;
475 }
476
477
478 /*
479 ** EDIT
480 */
481
482 static char *edsave = NULL;  /* the editor we used previously */
483
484
485 static int
486 editfile(char **ed, char **arg, char *file, int use)
487 {
488         int pid, status, vecp;
489         char *cp, *vec[MAXARGS];
490
491         if (!*ed || !**ed) {
492                 /* We have no explicit editor. */
493                 if (edsave) {
494                         /* Use the previous editor ... */
495                         *ed = edsave;
496                         if (!(cp = mhbasename(*ed)))
497                                 cp = *ed;
498
499                         /* but prefer one specified via "editor-next" */
500                         cp = concat(cp, "-next", NULL);
501                         if ((cp = context_find(cp)))
502                                 *ed = cp;
503                 } else {
504                         /* set initial editor */
505                         *ed = defaulteditor;
506                 }
507         }
508
509         context_save();
510         fflush(stdout);
511
512         switch (pid = fork()) {
513         case NOTOK:
514                 advise("fork", "unable to");
515                 status = NOTOK;
516                 break;
517
518         case OK:
519                 vecp = 0;
520                 vec[vecp++] = mhbasename(*ed);
521                 while (arg && *arg) {
522                         vec[vecp++] = *arg++;
523                 }
524                 vec[vecp++] = file;
525                 vec[vecp] = NULL;
526
527                 execvp(*ed, vec);
528                 fprintf(stderr, "%s: unable to exec ", invo_name);
529                 perror(*ed);
530                 _exit(-1);
531
532         default:
533                 if ((status = pidwait(pid, NOTOK))) {
534                         if ((status & 0xff00) == 0xff00) {
535                                 /* cmd not found or pidwait() failed */
536                                 status = -1;
537                                 break;
538                         }
539                         if (status & 0x00ff) {
540                                 /* terminated by signal */
541                                 advise(NULL, "%s terminated by signal %d",
542                                                 *ed, status & 0x7f);
543                         } else {
544                                 /* failure exit */
545                                 advise(NULL, "%s exited with return code %d",
546                                                 *ed, (status & 0xff00) >> 8);
547                         }
548                         status = -1;
549                         break;
550                 }
551         }
552
553         /* remember which editor we used */
554         edsave = getcpy(*ed);
555
556         *ed = NULL;
557
558         return status;
559 }
560
561
562 /*
563 ** SEND
564 */
565
566 static int
567 sendfile(char **arg, char *file)
568 {
569         int vecp = 0;
570         char *vec[MAXARGS];
571
572         context_save();
573         fflush(stdout);
574
575         vec[vecp++] = "send";
576         while (arg && *arg) {
577                 vec[vecp++] = *arg++;
578         }
579         vec[vecp++] = file;
580         vec[vecp] = NULL;
581         execvp(*vec, vec);
582         fprintf(stderr, "%s: unable to exec ", invo_name);
583         perror("send");
584         _exit(-1);
585 }
586
587
588 /*
589 ** refile msg into another folder
590 */
591 static int
592 refile(char **arg, char *file)
593 {
594         int vecp = 0;
595         char *vec[MAXARGS];
596
597         vec[vecp++] = "refile";
598         vec[vecp++] = "-nolink";  /* override bad .mh_profile defaults */
599         vec[vecp++] = "-file";
600         vec[vecp++] = file;
601
602         while (arg && *arg) {
603                 vec[vecp++] = *arg++;
604         }
605         vec[vecp] = NULL;
606
607         context_save();
608         fflush(stdout);
609
610         return execprog(*vec, vec);
611 }
612
613
614 /*
615 ** Remove the draft file
616 */
617
618 static int
619 removefile(char *drft)
620 {
621         if (unlink(drft) == NOTOK)
622                 adios(drft, "unable to unlink");
623
624         return OK;
625 }