fail in pick if a massage of -thread has no thread-id
[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 char *version=VERSION;
36
37 /*
38 ** Options at the "whatnow" prompt
39 */
40 static struct swit aleqs[] = {
41 #define EDITSW  0
42         { "edit [editor [switches]]", 0 },
43 #define LISTSW  1
44         { "list", 0 },
45 #define DISPSW  2
46         { "display", 0 },
47 #define WHOMSW  3
48         { "whom", 0 },
49 #define SENDSW  4
50         { "send", 0 },
51 #define REFILEOPT  5
52         { "refile +folder", 0 },
53 #define DELETESW  6
54         { "delete", 0 },
55 #define QUITSW  7
56         { "quit", 0 },
57 #define CDCMDSW  8
58         { "cd [directory]", 0 },
59 #define PWDCMDSW  9
60         { "pwd", 0 },
61 #define LSCMDSW  10
62         { "ls", 0 },
63 #define ALISTCMDSW  11
64         { "alist", 0 },
65 #define ATTACHCMDSW  12
66         { "attach files", 0 },
67 #define DETACHCMDSW  13
68         { "detach numbers", 0 },
69         { NULL, 0 }
70 };
71
72 static char *myprompt = "\nWhat now? ";
73
74 /*
75 ** static prototypes
76 */
77 static int editfile(char **, char **, char *);
78 static int sendfile(char **, char *);
79 static int refile(char **, char *);
80 static int removefile(char *);
81 static void writelscmd(char *, int, char **);
82 static void writesomecmd(char *, int, char *, char *, char **);
83 static FILE* popen_in_dir(const char *, const char *, const char *);
84 static int system_in_dir(const char *, const char *);
85
86
87 int
88 main(int argc, char **argv)
89 {
90         int use = NOUSE;
91         char *cp;
92         char *ed = NULL, *drft = NULL;
93         char buf[BUFSIZ], prompt[BUFSIZ];
94         char **argp, **arguments;
95         struct stat st;
96         char cwd[MAXPATHLEN + 1];  /* current working directory */
97         char file[MAXPATHLEN + 1];  /* file name buffer */
98         char shell[MAXPATHLEN + 1];  /* shell response buffer */
99         FILE *f;  /* read pointer for bgnd proc */
100
101         setlocale(LC_ALL, "");
102         invo_name = mhbasename(argv[0]);
103
104         /* read user profile/context */
105         context_read();
106
107         arguments = getarguments(invo_name, argc, argv, 1);
108         argp = arguments;
109
110         /*
111         ** Get the initial current working directory.
112         */
113
114         if (!getcwd(cwd, sizeof (cwd))) {
115                 adios(EX_USAGE, "getcwd", "could not get working directory");
116         }
117
118         while ((cp = *argp++)) {
119                 if (*cp == '-') {
120                         switch (smatch(++cp, switches)) {
121                         case AMBIGSW:
122                                 ambigsw(cp, switches);
123                                 exit(EX_USAGE);
124                         case UNKWNSW:
125                                 adios(EX_USAGE, NULL, "-%s unknown", cp);
126
127                         case HELPSW:
128                                 snprintf(buf, sizeof(buf),
129                                                 "%s [switches] [file]",
130                                                 invo_name);
131                                 print_help(buf, switches, 1);
132                                 exit(argc == 2 ? EX_OK : EX_USAGE);
133                         case VERSIONSW:
134                                 print_version(invo_name);
135                                 exit(argc == 2 ? EX_OK : EX_USAGE);
136
137                         case EDITRSW:
138                                 if (!(ed = *argp++) || *ed == '-')
139                                         adios(EX_USAGE, NULL, "missing argument to %s",
140                                                         argp[-2]);
141                                 continue;
142
143                         case PRMPTSW:
144                                 if (!(myprompt = *argp++) || *myprompt == '-')
145                                         adios(EX_USAGE, NULL, "missing argument to %s",
146                                                         argp[-2]);
147                                 continue;
148
149                         }
150                 }
151                 if (drft)
152                         adios(EX_USAGE, NULL, "only one draft at a time!");
153                 else
154                         drft = cp;
155         }
156
157         if ((!drft && !(drft = getenv("mhdraft"))) || !*drft)
158                 drft = mh_xstrdup(m_draft(seq_cur));
159
160         if ((cp = getenv("mhuse")) && *cp)
161                 use = atoi(cp);
162
163         if (!ed && !(ed = getenv("mheditor"))) {
164                 ed = "";  /* Don't initially edit the draft */
165         }
166
167         /* start editing the draft, unless editor is the empty string */
168         if (*ed) {
169                 if (editfile(&ed, NULL, drft) <0) {
170                         if (!use) {
171                                 unlink(drft);
172                         }
173                         adios(EX_SOFTWARE, NULL, "Try again.");
174                 }
175         }
176
177         snprintf(prompt, sizeof(prompt), myprompt, invo_name);
178         while ((argp = getans(prompt, aleqs))) {
179                 switch (smatch(*argp, aleqs)) {
180                 case DISPSW:
181                         /* display the msg being replied to or distributed */
182                         if ((cp = getenv("mhaltmsg")) && *cp) {
183                                 execprogl(listproc, listproc, "-file", cp,
184                                                 (char *)NULL);
185                         } else {
186                                 advise(NULL, "no alternate message to display");
187                         }
188                         break;
189
190                 case EDITSW:
191                         /* Call an editor on the draft file */
192                         if (*++argp)
193                                 ed = *argp++;
194                         editfile(&ed, argp, drft);
195                         break;
196
197                 case LISTSW:
198                         /* display the draft file */
199                         execprogl(listproc, listproc, "-file", drft,
200                                         (char *)NULL);
201                         break;
202
203                 case QUITSW:
204                         /* quit */
205                         if (stat(drft, &st) != NOTOK) {
206                                 advise(NULL, "draft left on %s", drft);
207                         }
208                         exit(EX_OK);
209
210                 case DELETESW:
211                         /* Delete draft and exit */
212                         removefile(drft);
213                         exit(EX_OK);
214
215                 case SENDSW:
216                         /* Send draft */
217                         sendfile(++argp, drft);
218                         break;
219
220                 case REFILEOPT:
221                         /* Refile the draft */
222                         if (refile(++argp, drft) == 0) {
223                                 exit(EX_OK);
224                         }
225                         break;
226
227                 case CDCMDSW:
228                         /*
229                         ** Change the working directory for attachments
230                         **
231                         ** Run the directory through the user's shell
232                         ** so that we can take advantage of any syntax
233                         ** that the user is accustomed to.  Read back
234                         ** the absolute path.
235                         */
236
237                         if (*(argp+1) == NULL) {
238                                 sprintf(buf, "$SHELL -c \"cd;pwd\"");
239                         } else {
240                                 writesomecmd(buf, BUFSIZ, "cd", "pwd", argp);
241                         }
242                         if ((f = popen_in_dir(cwd, buf, "r"))) {
243                                 fgets(cwd, sizeof (cwd), f);
244
245                                 if (strchr(cwd, '\n'))
246                                         *strchr(cwd, '\n') = '\0';
247
248                                 pclose(f);
249                         } else {
250                                 advise("popen", "could not get directory");
251                         }
252
253                         break;
254
255                 case PWDCMDSW:
256                         /* Print the working directory for attachments */
257                         printf("%s\n", cwd);
258                         break;
259
260                 case LSCMDSW:
261                         /*
262                         ** List files in the current attachment working
263                         ** directory
264                         **
265                         ** Use the user's shell so that we can take
266                         ** advantage of any syntax that the user is
267                         ** accustomed to.
268                         */
269                         writelscmd(buf, sizeof(buf), argp);
270                         system_in_dir(cwd, buf);
271                         break;
272
273                 case ALISTCMDSW:
274                         /*
275                         ** List attachments on current draft.
276                         */
277                         if (execprogl("anno", "anno", "-list", "-comp",
278                                         attach_hdr, "-number", drft,
279                                         (char *)NULL) != 0) {
280                                 advise(NULL, "Could not list attachment headers.");
281                         }
282                         break;
283
284                 case ATTACHCMDSW:
285                         /*
286                         ** Attach files to current draft.
287                         */
288
289                         if (*(argp+1) == NULL) {
290                                 advise(NULL, "attach command requires file argument(s).");
291                                 break;
292                         }
293
294                         /*
295                         ** Build a command line that causes the user's
296                         ** shell to list the file name arguments.
297                         ** This handles and wildcard expansion, tilde
298                         ** expansion, etc.
299                         */
300                         writelscmd(buf, sizeof(buf), argp);
301
302                         /*
303                         ** Read back the response from the shell,
304                         ** which contains a number of lines with one
305                         ** file name per line.  Remove off the newline.
306                         ** Determine whether we have an absolute or
307                         ** relative path name.  Prepend the current
308                         ** working directory to relative path names.
309                         ** Add the attachment annotation to the draft.
310                         */
311                         if (!(f = popen_in_dir(cwd, buf, "r"))) {
312                                 advise("popen", "could not get file from shell");
313                                 break;
314                         }
315
316                         while (fgets(shell, sizeof(shell), f)) {
317                                 *(strchr(shell, '\n')) = '\0';
318
319                                 if (*shell == '/')
320                                         sprintf(file, "%s", shell);
321                                 else {
322                                         sprintf(file, "%s/%s", cwd, shell);
323                                 }
324                                 if (execprogl("anno", "anno",
325                                                 "-nodate", "-append",
326                                                 "-comp", attach_hdr,
327                                                 "-text", file,
328                                                 drft, (char *)NULL) != 0) {
329                                         advise(NULL, "Could not add attachment header.");
330                                 }
331                         }
332                         pclose(f);
333                         break;
334
335                 case DETACHCMDSW:
336                         /*
337                         ** Detach files from current draft.
338                         **
339                         ** Interpret the arguments as
340                         ** attachment numbers.  Decrement any remaining
341                         ** argument number that is greater than the one
342                         ** just processed after processing each one so
343                         ** that the numbering stays correct.
344                         */
345                         for (arguments=argp+1; *arguments; arguments++) {
346                                 int n;
347
348                                 if (**arguments == '\0') {
349                                         continue;
350                                 }
351
352                                 if (execprogl("anno", "anno", "-delete",
353                                                 "-comp", attach_hdr,
354                                                 "-number", *arguments, drft,
355                                                 (char *)NULL) != 0) {
356                                         advise(NULL, "Could not delete attachment header.");
357                                 }
358
359                                 n = atoi(*arguments);
360                                 for (argp=arguments+1; *argp; argp++) {
361                                         if (atoi(*argp) > n) {
362                                                 if (atoi(*argp) == 1) {
363                                                         *argp = "";
364                                                 } else {
365                                                         sprintf(*argp, "%d", atoi(*argp) - 1);
366                                                 }
367                                         }
368                                 }
369                         }
370                         break;
371
372                 case WHOMSW:
373                         /* list recipients */
374                         execprogl("whom", "whom", drft, (char *)NULL);
375                         break;
376
377                 default:
378                         /* Unknown command */
379                         advise(NULL, "say what?");
380                         break;
381                 }
382         }
383
384         exit(EX_IOERR);
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 }