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