whatnow: Use execprog() ... one more time
[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                                 execprogl(listproc, listproc, "-file", cp,
178                                                 (char *)NULL);
179                         } else {
180                                 advise(NULL, "no alternate message to display");
181                         }
182                         break;
183
184                 case EDITSW:
185                         /* Call an editor on the draft file */
186                         if (*++argp)
187                                 ed = *argp++;
188                         editfile(&ed, argp, drft, NOUSE);
189                         break;
190
191                 case LISTSW:
192                         /* display the draft file */
193                         execprogl(listproc, listproc, "-file", drft,
194                                         (char *)NULL);
195                         break;
196
197                 case QUITSW:
198                         /* quit */
199                         if (stat(drft, &st) != NOTOK) {
200                                 advise(NULL, "draft left on %s", drft);
201                         }
202                         done(1);
203
204                 case DELETESW:
205                         /* Delete draft and exit */
206                         removefile(drft);
207                         done(1);
208
209                 case SENDSW:
210                         /* Send draft */
211                         sendfile(++argp, drft);
212                         break;
213
214                 case REFILEOPT:
215                         /* Refile the draft */
216                         if (refile(++argp, drft) == 0) {
217                                 done(0);
218                         }
219                         break;
220
221                 case CDCMDSW:
222                         /*
223                         ** Change the working directory for attachments
224                         **
225                         ** Run the directory through the user's shell
226                         ** so that we can take advantage of any syntax
227                         ** that the user is accustomed to.  Read back
228                         ** the absolute path.
229                         */
230
231                         if (*(argp+1) == NULL) {
232                                 sprintf(buf, "$SHELL -c \"cd;pwd\"");
233                         } else {
234                                 writesomecmd(buf, BUFSIZ, "cd", "pwd", argp);
235                         }
236                         if ((f = popen_in_dir(cwd, buf, "r"))) {
237                                 fgets(cwd, sizeof (cwd), f);
238
239                                 if (strchr(cwd, '\n'))
240                                         *strchr(cwd, '\n') = '\0';
241
242                                 pclose(f);
243                         } else {
244                                 advise("popen", "could not get directory");
245                         }
246
247                         break;
248
249                 case PWDCMDSW:
250                         /* Print the working directory for attachments */
251                         printf("%s\n", cwd);
252                         break;
253
254                 case LSCMDSW:
255                         /*
256                         ** List files in the current attachment working
257                         ** directory
258                         **
259                         ** Use the user's shell so that we can take
260                         ** advantage of any syntax that the user is
261                         ** accustomed to.
262                         */
263                         writelscmd(buf, sizeof(buf), argp);
264                         system_in_dir(cwd, buf);
265                         break;
266
267                 case ALISTCMDSW:
268                         /*
269                         ** List attachments on current draft.
270                         */
271                         if (execprogl("anno", "anno", "-list", "-comp",
272                                         attach_hdr, "-number", drft,
273                                         (char *)NULL) != 0) {
274                                 advise(NULL, "Could not list attachment headers.");
275                         }
276                         break;
277
278                 case ATTACHCMDSW:
279                         /*
280                         ** Attach files to current draft.
281                         */
282
283                         if (*(argp+1) == NULL) {
284                                 advise(NULL, "attach command requires file argument(s).");
285                                 break;
286                         }
287
288                         /*
289                         ** Build a command line that causes the user's
290                         ** shell to list the file name arguments.
291                         ** This handles and wildcard expansion, tilde
292                         ** expansion, etc.
293                         */
294                         writelscmd(buf, sizeof(buf), argp);
295
296                         /*
297                         ** Read back the response from the shell,
298                         ** which contains a number of lines with one
299                         ** file name per line.  Remove off the newline.
300                         ** Determine whether we have an absolute or
301                         ** relative path name.  Prepend the current
302                         ** working directory to relative path names.
303                         ** Add the attachment annotation to the draft.
304                         */
305                         if (!(f = popen_in_dir(cwd, buf, "r"))) {
306                                 advise("popen", "could not get file from shell");
307                                 break;
308                         }
309
310                         while (fgets(shell, sizeof(shell), f)) {
311                                 *(strchr(shell, '\n')) = '\0';
312
313                                 if (*shell == '/')
314                                         sprintf(file, "%s", shell);
315                                 else {
316                                         sprintf(file, "%s/%s", cwd, shell);
317                                 }
318                                 if (execprogl("anno", "anno",
319                                                 "-nodate", "-append",
320                                                 "-comp", attach_hdr,
321                                                 "-text", file,
322                                                 drft, (char *)NULL) != 0) {
323                                         advise(NULL, "Could not add attachment header.");
324                                 }
325                         }
326                         pclose(f);
327                         break;
328
329                 case DETACHCMDSW:
330                         /*
331                         ** Detach files from current draft.
332                         **
333                         ** Interpret the arguments as
334                         ** attachment numbers.  Decrement any remaining
335                         ** argument number that is greater than the one
336                         ** just processed after processing each one so
337                         ** that the numbering stays correct.
338                         */
339                         for (arguments=argp+1; *arguments; arguments++) {
340                                 int n;
341
342                                 if (**arguments == '\0') {
343                                         continue;
344                                 }
345
346                                 if (execprogl("anno", "anno", "-delete",
347                                                 "-comp", attach_hdr,
348                                                 "-number", *arguments, drft,
349                                                 (char *)NULL) != 0) {
350                                         advise(NULL, "Could not delete attachment header.");
351                                 }
352
353                                 n = atoi(*arguments);
354                                 for (argp=arguments+1; *argp; argp++) {
355                                         if (atoi(*argp) > n) {
356                                                 if (atoi(*argp) == 1) {
357                                                         *argp = "";
358                                                 } else {
359                                                         sprintf(*argp, "%d", atoi(*argp) - 1);
360                                                 }
361                                         }
362                                 }
363                         }
364                         break;
365
366                 case WHOMSW:
367                         /* list recipients */
368                         execprogl("whom", "whom", drft, (char *)NULL);
369                         break;
370
371                 default:
372                         /* Unknown command */
373                         advise(NULL, "say what?");
374                         break;
375                 }
376         }
377         /*NOTREACHED*/
378 }
379
380
381
382 /*
383 ** Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
384 ** trailcmd".
385 */
386 static void
387 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
388 {
389         char *cp;
390         /*
391         ** Note that we do not quote -- the argp from the user
392         ** is assumed to be quoted as they desire. (We can't treat
393         ** it as pure literal as that would prevent them using ~,
394         ** wildcards, etc.) The buffer produced by this function
395         ** should be given to popen_in_dir() or system_in_dir() so
396         ** that the current working directory is set correctly.
397         */
398         int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
399         /*
400         ** NB that some snprintf() return -1 on overflow rather than the
401         ** new C99 mandated 'number of chars that would have been written'
402         */
403         /*
404         ** length checks here and inside the loop allow for the
405         ** trailing ';', trailcmd, '"' and NUL
406         */
407         int trailln = strlen(trailcmd) + 3;
408         if (ln < 0 || ln + trailln > bufsz)
409                 adios(NULL, "arguments too long");
410
411         cp = buf + ln;
412
413         while (*++argp) {
414                 ln = strlen(*argp);
415                 /* +1 for leading space */
416                 if (ln + trailln + 1 > bufsz - (cp-buf))
417                         adios(NULL, "arguments too long");
418                 *cp++ = ' ';
419                 memcpy(cp, *argp, ln+1);
420                 cp += ln;
421         }
422         if (*trailcmd) {
423                 *cp++ = ';';
424                 strcpy(cp, trailcmd);
425                 cp += trailln - 3;
426         }
427         *cp++ = '"';
428         *cp = 0;
429 }
430
431 /*
432 ** Build a command line that causes the user's shell to list the file name
433 ** arguments.  This handles and wildcard expansion, tilde expansion, etc.
434 */
435 static void
436 writelscmd(char *buf, int bufsz, char **argp)
437 {
438         writesomecmd(buf, bufsz, "ls", "", argp);
439 }
440
441 /*
442 ** Like system(), but run the command in directory dir.
443 ** This assumes the program is single-threaded!
444 */
445 static int
446 system_in_dir(const char *dir, const char *cmd)
447 {
448         char olddir[BUFSIZ];
449         int r;
450         if (getcwd(olddir, sizeof(olddir)) == 0)
451                 adios("getcwd", "could not get working directory");
452         if (chdir(dir) != 0)
453                 adios("chdir", "could not change working directory");
454         r = system(cmd);
455         if (chdir(olddir) != 0)
456                 adios("chdir", "could not change working directory");
457         return r;
458 }
459
460 /* ditto for popen() */
461 static FILE*
462 popen_in_dir(const char *dir, const char *cmd, const char *type)
463 {
464         char olddir[BUFSIZ];
465         FILE *f;
466         if (getcwd(olddir, sizeof(olddir)) == 0)
467                 adios("getcwd", "could not get working directory");
468         if (chdir(dir) != 0)
469                 adios("chdir", "could not change working directory");
470         f = popen(cmd, type);
471         if (chdir(olddir) != 0)
472                 adios("chdir", "could not change working directory");
473         return f;
474 }
475
476
477 /*
478 ** EDIT
479 */
480
481 static char *edsave = NULL;  /* the editor we used previously */
482
483
484 static int
485 editfile(char **ed, char **arg, char *file, int use)
486 {
487         int pid, status, vecp;
488         char *cp, *vec[MAXARGS];
489
490         if (!*ed || !**ed) {
491                 /* We have no explicit editor. */
492                 if (edsave) {
493                         /* Use the previous editor ... */
494                         *ed = edsave;
495                         if (!(cp = mhbasename(*ed)))
496                                 cp = *ed;
497
498                         /* but prefer one specified via "editor-next" */
499                         cp = concat(cp, "-next", NULL);
500                         if ((cp = context_find(cp)))
501                                 *ed = cp;
502                 } else {
503                         /* set initial editor */
504                         *ed = defaulteditor;
505                 }
506         }
507
508         context_save();
509         fflush(stdout);
510
511         switch (pid = fork()) {
512         case NOTOK:
513                 advise("fork", "unable to");
514                 status = NOTOK;
515                 break;
516
517         case OK:
518                 vecp = 0;
519                 vec[vecp++] = mhbasename(*ed);
520                 while (arg && *arg) {
521                         vec[vecp++] = *arg++;
522                 }
523                 vec[vecp++] = file;
524                 vec[vecp] = NULL;
525
526                 execvp(*ed, vec);
527                 fprintf(stderr, "%s: unable to exec ", invo_name);
528                 perror(*ed);
529                 _exit(-1);
530
531         default:
532                 if ((status = pidwait(pid, NOTOK))) {
533                         if ((status & 0xff00) == 0xff00) {
534                                 /* cmd not found or pidwait() failed */
535                                 status = -1;
536                                 break;
537                         }
538                         if (status & 0x00ff) {
539                                 /* terminated by signal */
540                                 advise(NULL, "%s terminated by signal %d",
541                                                 *ed, status & 0x7f);
542                         } else {
543                                 /* failure exit */
544                                 advise(NULL, "%s exited with return code %d",
545                                                 *ed, (status & 0xff00) >> 8);
546                         }
547                         status = -1;
548                         break;
549                 }
550         }
551
552         /* remember which editor we used */
553         edsave = getcpy(*ed);
554
555         *ed = NULL;
556
557         return status;
558 }
559
560
561 /*
562 ** SEND
563 */
564
565 static int
566 sendfile(char **arg, char *file)
567 {
568         int vecp = 0;
569         char *vec[MAXARGS];
570
571         context_save();
572         fflush(stdout);
573
574         vec[vecp++] = "send";
575         while (arg && *arg) {
576                 vec[vecp++] = *arg++;
577         }
578         vec[vecp++] = file;
579         vec[vecp] = NULL;
580         execvp(*vec, vec);
581         fprintf(stderr, "%s: unable to exec ", invo_name);
582         perror("send");
583         _exit(-1);
584 }
585
586
587 /*
588 ** refile msg into another folder
589 */
590 static int
591 refile(char **arg, char *file)
592 {
593         int vecp = 0;
594         char *vec[MAXARGS];
595
596         vec[vecp++] = "refile";
597         vec[vecp++] = "-nolink";  /* override bad .mh_profile defaults */
598         vec[vecp++] = "-file";
599         vec[vecp++] = file;
600
601         while (arg && *arg) {
602                 vec[vecp++] = *arg++;
603         }
604         vec[vecp] = NULL;
605
606         context_save();
607         fflush(stdout);
608
609         return execprog(*vec, vec);
610 }
611
612
613 /*
614 ** Remove the draft file
615 */
616
617 static int
618 removefile(char *drft)
619 {
620         if (unlink(drft) == NOTOK)
621                 adios(drft, "unable to unlink");
622
623         return OK;
624 }