Use execprog() instead of system() ... partly transition
[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                                 while (fgets(shell, sizeof(shell), f)) {
307                                         *(strchr(shell, '\n')) = '\0';
308
309                                         if (*shell == '/')
310                                                 sprintf(file, "%s", shell);
311                                         else {
312                                                 sprintf(file, "%s/%s", cwd,
313                                                                 shell);
314                                         }
315                                         if (execprogl("anno", "anno",
316                                                         "-nodate",
317                                                         "-append", "-comp",
318                                                         attach_hdr, "-text",
319                                                         file, drft,
320                                                         (char *)NULL)
321                                                         != 0) {
322                                                 advise(NULL, "Could not add attachment header.");
323                                         }
324                                 }
325
326                                 pclose(f);
327                         } else {
328                                 advise("popen", "could not get file from shell");
329                         }
330
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         /*NOTREACHED*/
382 }
383
384
385
386 /*
387 ** Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
388 ** trailcmd".
389 */
390 static void
391 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
392 {
393         char *cp;
394         /*
395         ** Note that we do not quote -- the argp from the user
396         ** is assumed to be quoted as they desire. (We can't treat
397         ** it as pure literal as that would prevent them using ~,
398         ** wildcards, etc.) The buffer produced by this function
399         ** should be given to popen_in_dir() or system_in_dir() so
400         ** that the current working directory is set correctly.
401         */
402         int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
403         /*
404         ** NB that some snprintf() return -1 on overflow rather than the
405         ** new C99 mandated 'number of chars that would have been written'
406         */
407         /*
408         ** length checks here and inside the loop allow for the
409         ** trailing ';', trailcmd, '"' and NUL
410         */
411         int trailln = strlen(trailcmd) + 3;
412         if (ln < 0 || ln + trailln > bufsz)
413                 adios(NULL, "arguments too long");
414
415         cp = buf + ln;
416
417         while (*++argp) {
418                 ln = strlen(*argp);
419                 /* +1 for leading space */
420                 if (ln + trailln + 1 > bufsz - (cp-buf))
421                         adios(NULL, "arguments too long");
422                 *cp++ = ' ';
423                 memcpy(cp, *argp, ln+1);
424                 cp += ln;
425         }
426         if (*trailcmd) {
427                 *cp++ = ';';
428                 strcpy(cp, trailcmd);
429                 cp += trailln - 3;
430         }
431         *cp++ = '"';
432         *cp = 0;
433 }
434
435 /*
436 ** Build a command line that causes the user's shell to list the file name
437 ** arguments.  This handles and wildcard expansion, tilde expansion, etc.
438 */
439 static void
440 writelscmd(char *buf, int bufsz, char **argp)
441 {
442         writesomecmd(buf, bufsz, "ls", "", argp);
443 }
444
445 /*
446 ** Like system(), but run the command in directory dir.
447 ** This assumes the program is single-threaded!
448 */
449 static int
450 system_in_dir(const char *dir, const char *cmd)
451 {
452         char olddir[BUFSIZ];
453         int r;
454         if (getcwd(olddir, sizeof(olddir)) == 0)
455                 adios("getcwd", "could not get working directory");
456         if (chdir(dir) != 0)
457                 adios("chdir", "could not change working directory");
458         r = system(cmd);
459         if (chdir(olddir) != 0)
460                 adios("chdir", "could not change working directory");
461         return r;
462 }
463
464 /* ditto for popen() */
465 static FILE*
466 popen_in_dir(const char *dir, const char *cmd, const char *type)
467 {
468         char olddir[BUFSIZ];
469         FILE *f;
470         if (getcwd(olddir, sizeof(olddir)) == 0)
471                 adios("getcwd", "could not get working directory");
472         if (chdir(dir) != 0)
473                 adios("chdir", "could not change working directory");
474         f = popen(cmd, type);
475         if (chdir(olddir) != 0)
476                 adios("chdir", "could not change working directory");
477         return f;
478 }
479
480
481 /*
482 ** EDIT
483 */
484
485 static char *edsave = NULL;  /* the editor we used previously */
486
487
488 static int
489 editfile(char **ed, char **arg, char *file, int use)
490 {
491         int pid, status, vecp;
492         char *cp, *vec[MAXARGS];
493
494         if (!*ed || !**ed) {
495                 /* We have no explicit editor. */
496                 if (edsave) {
497                         /* Use the previous editor ... */
498                         *ed = edsave;
499                         if (!(cp = mhbasename(*ed)))
500                                 cp = *ed;
501
502                         /* but prefer one specified via "editor-next" */
503                         cp = concat(cp, "-next", NULL);
504                         if ((cp = context_find(cp)))
505                                 *ed = cp;
506                 } else {
507                         /* set initial editor */
508                         *ed = defaulteditor;
509                 }
510         }
511
512         context_save();
513         fflush(stdout);
514
515         switch (pid = fork()) {
516         case NOTOK:
517                 advise("fork", "unable to");
518                 status = NOTOK;
519                 break;
520
521         case OK:
522                 vecp = 0;
523                 vec[vecp++] = mhbasename(*ed);
524                 if (arg)
525                         while (*arg)
526                                 vec[vecp++] = *arg++;
527                 vec[vecp++] = file;
528                 vec[vecp] = NULL;
529
530                 execvp(*ed, vec);
531                 fprintf(stderr, "%s: unable to exec ", invo_name);
532                 perror(*ed);
533                 _exit(-1);
534
535         default:
536                 if ((status = pidwait(pid, NOTOK))) {
537                         if ((status & 0xff00) == 0xff00) {
538                                 /* cmd not found or pidwait() failed */
539                                 status = -1;
540                                 break;
541                         }
542                         if (status & 0x00ff) {
543                                 /* terminated by signal */
544                                 advise(NULL, "%s terminated by signal %d",
545                                                 *ed, status & 0x7f);
546                         } else {
547                                 /* failure exit */
548                                 advise(NULL, "%s exited with return code %d",
549                                                 *ed, (status & 0xff00) >> 8);
550                         }
551                         status = -1;
552                         break;
553                 }
554         }
555
556         /* remember which editor we used */
557         edsave = getcpy(*ed);
558
559         *ed = NULL;
560
561         return status;
562 }
563
564
565 /*
566 ** SEND
567 */
568
569 static int
570 sendfile(char **arg, char *file)
571 {
572         pid_t child_id;
573         int vecp;
574         char *vec[MAXARGS];
575
576         context_save();  /* save the context file */
577         fflush(stdout);
578
579         switch (child_id = fork()) {
580         case NOTOK:
581                 advise(NULL, "unable to fork, so sending directly...");
582                 /* fall */
583         case OK:
584                 vecp = 0;
585                 vec[vecp++] = "send";
586                 if (arg)
587                         while (*arg)
588                                 vec[vecp++] = *arg++;
589                 vec[vecp++] = file;
590                 vec[vecp] = NULL;
591
592                 execvp("send", vec);
593                 fprintf(stderr, "%s: unable to exec ", invo_name);
594                 perror("send");
595                 _exit(-1);
596
597         default:
598                 if (pidwait(child_id, OK) == 0)
599                         done(0);
600                 return 1;
601         }
602 }
603
604
605 /*
606 ** refile msg into another folder
607 */
608 static int
609 refile(char **arg, char *file)
610 {
611         pid_t pid;
612         register int vecp;
613         char *vec[MAXARGS];
614
615         vecp = 0;
616         vec[vecp++] = "refile";
617         vec[vecp++] = "-nolink";  /* override bad .mh_profile defaults */
618         vec[vecp++] = "-file";
619         vec[vecp++] = file;
620
621         while (arg && *arg) {
622                 vec[vecp++] = *arg++;
623         }
624         vec[vecp] = NULL;
625
626         context_save();  /* save the context file */
627         fflush(stdout);
628
629         switch (pid = fork()) {
630         case -1:
631                 advise("fork", "unable to");
632                 return -1;
633
634         case 0:
635                 execvp(*vec, vec);
636                 fprintf(stderr, "%s: unable to exec ", invo_name);
637                 perror(*vec);
638                 _exit(-1);
639
640         default:
641                 return (pidwait(pid, -1));
642         }
643 }
644
645
646 /*
647 ** Remove the draft file
648 */
649
650 static int
651 removefile(char *drft)
652 {
653         if (unlink(drft) == NOTOK)
654                 adios(drft, "unable to unlink");
655
656         return OK;
657 }