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