2 * whatnowsbr.c -- the WhatNow shell
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.
8 * Several options have been added to ease the inclusion of attachments
9 * using the header field name mechanism added to anno and send. The
10 * -attach option is used to specify the header field name for attachments.
12 * Several commands have been added at the whatnow prompt:
14 * cd [ directory ] This option works just like the shell's
15 * cd command and lets the user change the
16 * directory from which attachments are
17 * taken so that long path names are not
18 * needed with every file.
20 * ls [ ls-options ] This option works just like the normal
21 * ls command and exists to allow the user
22 * to verify file names in the directory.
24 * pwd This option works just like the normal
25 * pwd command and exists to allow the user
26 * to verify the directory.
28 * attach files This option attaches the named files to
31 * alist [-ln] This option lists the attachments on the
32 * draft. -l gets long listings, -n gets
35 * detach files This option removes attachments from the
36 * detach -n numbers draft. This can be done by file name or
37 * by attachment number.
46 static struct swit whatnowswitches[] = {
48 { "editor editor", 0 },
52 { "prompt string", 4 },
58 { "attach header-field-name", 0 },
63 * Options at the "whatnow" prompt
65 static struct swit aleqs[] = {
67 { "edit [<editor> <switches>]", 0 },
69 { "refile [<switches>] +folder", 0 },
71 { "mime [<switches>]", 0 },
73 { "display [<switches>]", 0 },
75 { "list [<switches>]", 0 },
77 { "send [<switches>]", 0 },
79 { "push [<switches>]", 0 },
81 { "quit [-delete]", 0 },
85 { "cd [directory]", 0 },
90 #define ATTACHCMDSW 12
92 #define DETACHCMDSW 13
95 { "alist [-ln] ", 2 },
99 static char *myprompt = "\nWhat now? ";
104 static int editfile (char **, char **, char *, int, struct msgs *,
105 char *, char *, int);
106 static int sendfile (char **, char *, int);
107 static void sendit (char *, char **, char *, int);
108 static int buildfile (char **, char *);
109 static int check_draft (char *);
110 static int removefile (char *);
111 static void writelscmd(char *, int, char **);
112 static void writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp);
113 static FILE* popen_in_dir(const char *dir, const char *cmd, const char *type);
114 static int system_in_dir(const char *dir, const char *cmd);
118 static int copyf (char *, char *);
123 WhatNow (int argc, char **argv)
125 int nedit = 0, use = 0;
127 char *ed = NULL, *drft = NULL, *msgnam = NULL;
128 char buf[BUFSIZ], prompt[BUFSIZ];
129 char **argp, **arguments;
131 char *attach = (char *)0; /* attachment header field name */
132 char cwd[MAXPATHLEN + 1]; /* current working directory */
133 char file[MAXPATHLEN + 1]; /* file name buffer */
134 char shell[MAXPATHLEN + 1]; /* shell response buffer */
135 FILE *f; /* read pointer for bgnd proc */
136 char *l; /* set on -l to alist command */
137 int n; /* set on -n to alist command */
139 invo_name = r1bindex (argv[0], '/');
141 /* read user profile/context */
144 arguments = getarguments (invo_name, argc, argv, 1);
148 * Get the initial current working directory.
151 if (getcwd(cwd, sizeof (cwd)) == (char *)0) {
152 adios("getcwd", "could not get working directory");
155 while ((cp = *argp++)) {
157 switch (smatch (++cp, whatnowswitches)) {
159 ambigsw (cp, whatnowswitches);
162 adios (NULL, "-%s unknown", cp);
165 snprintf (buf, sizeof(buf), "%s [switches] [file]", invo_name);
166 print_help (buf, whatnowswitches, 1);
169 print_version(invo_name);
173 if (!(ed = *argp++) || *ed == '-')
174 adios (NULL, "missing argument to %s", argp[-2]);
182 if (!(myprompt = *argp++) || *myprompt == '-')
183 adios (NULL, "missing argument to %s", argp[-2]);
187 if (attach != (char *)0)
188 adios(NULL, "only one attachment header field name at a time!");
189 if (!(attach = *argp++) || *attach == '-')
190 adios (NULL, "missing argument to %s", argp[-2]);
195 adios (NULL, "only one draft at a time!");
200 if ((drft == NULL && (drft = getenv ("mhdraft")) == NULL) || *drft == 0)
201 drft = getcpy (m_draft("cur"));
203 msgnam = (cp = getenv ("mhaltmsg")) && *cp ? getcpy (cp) : NULL;
205 if ((cp = getenv ("mhuse")) && *cp)
208 if (ed == NULL && ((ed = getenv ("mheditor")) == NULL || *ed == 0)) {
213 /* start editing the draft, unless -noedit was given */
214 if (!nedit && editfile (&ed, NULL, drft, use, NULL, msgnam, NULL, 1) < 0)
217 snprintf (prompt, sizeof(prompt), myprompt, invo_name);
219 if (!(argp = getans (prompt, aleqs))) {
223 switch (smatch (*argp, aleqs)) {
225 /* display the message being replied to, or distributed */
227 showfile (++argp, msgnam);
229 advise (NULL, "no alternate message to display");
233 /* Translate MIME composition file */
234 buildfile (++argp, drft);
238 /* Call an editor on the draft file */
241 if (editfile (&ed, argp, drft, NOUSE, NULL, msgnam, NULL, 1) == NOTOK)
246 /* display the draft file */
247 showfile (++argp, drft);
251 /* Quit, and possibly delete the draft */
252 if (*++argp && (*argp[0] == 'd' ||
253 ((*argp)[0] == '-' && (*argp)[1] == 'd'))) {
256 if (stat (drft, &st) != NOTOK)
257 advise (NULL, "draft left on %s", drft);
262 /* Delete draft and exit */
267 /* Send draft in background */
268 if (sendfile (++argp, drft, 1))
274 sendfile (++argp, drft, 0);
278 /* Refile the draft */
279 if (refile (++argp, drft) == 0)
285 * Change the working directory for attachments
287 * Run the directory through the user's shell
288 * so that we can take advantage of any syntax
289 * that the user is accustomed to. Read back
293 if (*(argp+1) == (char *)0) {
294 (void)sprintf(buf, "$SHELL -c \"cd;pwd\"");
296 writesomecmd(buf, BUFSIZ, "cd", "pwd", argp);
298 if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
299 fgets(cwd, sizeof (cwd), f);
301 if (strchr(cwd, '\n') != (char *)0)
302 *strchr(cwd, '\n') = '\0';
306 advise("popen", "could not get directory");
312 /* Print the working directory for attachments */
318 * List files in the current attachment working
321 * Use the user's shell so that we can take
322 * advantage of any syntax that the user is
325 writelscmd(buf, sizeof(buf), argp);
326 (void)system_in_dir(cwd, buf);
331 * List attachments on current draft. Options are:
333 * -l long listing (full path names)
337 if (attach == (char *)0) {
338 advise((char *)0, "can't list because no header field name was given.");
345 while (*++argp != (char *)0) {
346 if (strcmp(*argp, "-l") == 0)
349 else if (strcmp(*argp, "-n") == 0)
352 else if (strcmp(*argp, "-ln") == 0 || strcmp(*argp, "-nl") == 0) {
362 advise((char *)0, "usage is alist [-ln].");
365 annolist(drft, attach, l, n);
371 * Attach files to current draft.
374 if (attach == (char *)0) {
375 advise((char *)0, "can't attach because no header field name was given.");
379 if (*(argp+1) == (char *)0) {
380 advise((char *)0, "attach command requires file argument(s).");
385 * Build a command line that causes the user's
386 * shell to list the file name arguments.
387 * This handles and wildcard expansion, tilde
390 writelscmd(buf, sizeof(buf), argp);
393 * Read back the response from the shell,
394 * which contains a number of lines with one
395 * file name per line. Remove off the newline.
396 * Determine whether we have an absolute or
397 * relative path name. Prepend the current
398 * working directory to relative path names.
399 * Add the attachment annotation to the draft.
402 if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
403 while (fgets(shell, sizeof (shell), f) != (char *)0) {
404 *(strchr(shell, '\n')) = '\0';
407 (void)annotate(drft, attach, shell, 1, 0, -2, 1);
409 (void)sprintf(file, "%s/%s", cwd, shell);
410 (void)annotate(drft, attach, file, 1, 0, -2, 1);
416 advise("popen", "could not get file from shell");
423 * Detach files from current draft.
426 if (attach == (char *)0) {
427 advise((char *)0, "can't detach because no header field name was given.");
432 * Scan the arguments for a -n. Mixed file
433 * names and numbers aren't allowed, so this
434 * catches a -n anywhere in the argument list.
437 for (n = 0, arguments = argp + 1; *arguments != (char *)0; arguments++) {
438 if (strcmp(*arguments, "-n") == 0) {
445 * A -n was found so interpret the arguments as
446 * attachment numbers. Decrement any remaining
447 * argument number that is greater than the one
448 * just processed after processing each one so
449 * that the numbering stays correct.
453 for (arguments = argp + 1; *arguments != (char *)0; arguments++) {
454 if (strcmp(*arguments, "-n") == 0)
457 if (**arguments != '\0') {
458 n = atoi(*arguments);
459 (void)annotate(drft, attach, (char *)0, 1, 0, n, 1);
461 for (argp = arguments + 1; *argp != (char *)0; argp++) {
462 if (atoi(*argp) > n) {
463 if (atoi(*argp) == 1)
466 (void)sprintf(*argp, "%d", atoi(*argp) - 1);
474 * The arguments are interpreted as file names.
475 * Run them through the user's shell for wildcard
476 * expansion and other goodies. Do this from
477 * the current working directory if the argument
478 * is not an absolute path name (does not begin
481 * We feed all the file names to the shell at
482 * once, otherwise you can't provide a file name
483 * with a space in it.
485 writelscmd(buf, sizeof(buf), argp);
486 if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
487 while (fgets(shell, sizeof (shell), f) != (char *)0) {
488 *(strchr(shell, '\n')) = '\0';
489 (void)annotate(drft, attach, shell, 1, 0, 0, 1);
493 advise("popen", "could not get file from shell");
499 /* Unknown command */
500 advise (NULL, "say what?");
510 * Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
514 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
517 /* Note that we do not quote -- the argp from the user
518 * is assumed to be quoted as they desire. (We can't treat
519 * it as pure literal as that would prevent them using ~,
520 * wildcards, etc.) The buffer produced by this function
521 * should be given to popen_in_dir() or system_in_dir() so
522 * that the current working directory is set correctly.
524 int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
525 /* NB that some snprintf() return -1 on overflow rather than the
526 * new C99 mandated 'number of chars that would have been written'
528 /* length checks here and inside the loop allow for the
529 * trailing ';', trailcmd, '"' and NUL
531 int trailln = strlen(trailcmd) + 3;
532 if (ln < 0 || ln + trailln > bufsz)
533 adios((char *)0, "arguments too long");
537 while (*++argp != (char *)0) {
539 /* +1 for leading space */
540 if (ln + trailln + 1 > bufsz - (cp-buf))
541 adios((char *)0, "arguments too long");
543 memcpy(cp, *argp, ln+1);
548 strcpy(cp, trailcmd);
556 * Build a command line that causes the user's shell to list the file name
557 * arguments. This handles and wildcard expansion, tilde expansion, etc.
560 writelscmd(char *buf, int bufsz, char **argp)
562 writesomecmd(buf, bufsz, "ls", "", argp);
565 /* Like system(), but run the command in directory dir.
566 * This assumes the program is single-threaded!
569 system_in_dir(const char *dir, const char *cmd)
573 if (getcwd(olddir, sizeof(olddir)) == 0)
574 adios("getcwd", "could not get working directory");
576 adios("chdir", "could not change working directory");
578 if (chdir(olddir) != 0)
579 adios("chdir", "could not change working directory");
583 /* ditto for popen() */
585 popen_in_dir(const char *dir, const char *cmd, const char *type)
589 if (getcwd(olddir, sizeof(olddir)) == 0)
590 adios("getcwd", "could not get working directory");
592 adios("chdir", "could not change working directory");
593 f = popen(cmd, type);
594 if (chdir(olddir) != 0)
595 adios("chdir", "could not change working directory");
604 static int reedit = 0; /* have we been here before? */
605 static char *edsave = NULL; /* the editor we used previously */
609 editfile (char **ed, char **arg, char *file, int use, struct msgs *mp,
610 char *altmsg, char *cwd, int save_editor)
612 int pid, status, vecp;
613 char altpath[BUFSIZ], linkpath[BUFSIZ];
614 char *cp, *vec[MAXARGS];
620 int oumask; /* PJS: for setting permissions on symlinks. */
622 #endif /* HAVE_LSTAT */
624 /* Was there a previous edit session? */
626 if (!*ed) { /* no explicit editor */
627 *ed = edsave; /* so use the previous one */
628 if ((cp = r1bindex (*ed, '/')) == NULL)
631 /* unless we've specified it via "editor-next" */
632 cp = concat (cp, "-next", NULL);
633 if ((cp = context_find (cp)) != NULL)
637 /* set initial editor */
638 if (*ed == NULL && (*ed = context_find ("editor")) == NULL)
643 if (mp == NULL || *altmsg == '/' || cwd == NULL)
644 strncpy (altpath, altmsg, sizeof(altpath));
646 snprintf (altpath, sizeof(altpath), "%s/%s", mp->foldpath, altmsg);
648 strncpy (linkpath, altmsglink, sizeof(linkpath));
650 snprintf (linkpath, sizeof(linkpath), "%s/%s", cwd, altmsglink);
656 if (link (altpath, linkpath) == NOTOK) {
658 /* I don't think permission on symlinks matters /JLR */
659 oumask = umask(0044); /* PJS: else symlinks are world 'r' */
661 symlink (altpath, linkpath);
663 umask(oumask); /* PJS: else symlinks are world 'r' */
669 #else /* not HAVE_LSTAT */
670 link (altpath, linkpath);
671 #endif /* not HAVE_LSTAT */
674 context_save (); /* save the context file */
677 switch (pid = vfork ()) {
679 advise ("fork", "unable to");
688 m_putenv ("mhfolder", mp->foldpath);
689 m_putenv ("editalt", altpath);
693 vec[vecp++] = r1bindex (*ed, '/');
696 vec[vecp++] = *arg++;
701 fprintf (stderr, "unable to exec ");
706 if ((status = pidwait (pid, NOTOK))) {
708 if ((cp = r1bindex (*ed, '/'))
709 && strcmp (cp, "vi") == 0
710 && (status & 0x00ff) == 0)
714 if (((status & 0xff00) != 0xff00)
715 && (!reedit || (status & 0x00ff))) {
716 if (!use && (status & 0xff00) &&
717 (rename (file, cp = m_backup (file)) != NOTOK)) {
718 advise (NULL, "problems with edit--draft left in %s", cp);
720 advise (NULL, "problems with edit--%s preserved", file);
723 status = -2; /* maybe "reedit ? -2 : -1"? */
736 ? lstat (linkpath, &st) != NOTOK
737 && S_ISREG(st.st_mode)
738 && copyf (linkpath, altpath) == NOTOK
739 : stat (linkpath, &st) != NOTOK
741 && (unlink (altpath) == NOTOK
742 || link (linkpath, altpath) == NOTOK)))
743 advise (linkpath, "unable to update %s from", altmsg);
744 #else /* HAVE_LSTAT */
748 && stat (linkpath, &st) != NOTOK
750 && (unlink (altpath) == NOTOK
751 || link (linkpath, altpath) == NOTOK))
752 advise (linkpath, "unable to update %s from", altmsg);
753 #endif /* HAVE_LSTAT */
756 /* normally, we remember which editor we used */
758 edsave = getcpy (*ed);
770 copyf (char *ifile, char *ofile)
775 if ((in = open (ifile, O_RDONLY)) == NOTOK)
777 if ((out = open (ofile, O_WRONLY | O_TRUNC)) == NOTOK) {
778 admonish (ofile, "unable to open and truncate");
783 while ((i = read (in, buffer, sizeof(buffer))) > OK)
784 if (write (out, buffer, i) != i) {
785 advise (ofile, "may have damaged");
794 #endif /* HAVE_LSTAT */
802 sendfile (char **arg, char *file, int pushsw)
806 char *cp, *sp, *vec[MAXARGS];
808 /* Translate MIME composition file, if necessary */
809 if ((cp = context_find ("automimeproc"))
810 && (!strcmp (cp, "1"))
811 && !getenv ("NOMHNPROC")
812 && check_draft (file)
813 && (buildfile (NULL, file) == NOTOK))
816 /* For backwards compatibility */
817 if ((cp = context_find ("automhnproc"))
818 && !getenv ("NOMHNPROC")
819 && check_draft (file)
820 && (i = editfile (&cp, NULL, file, NOUSE, NULL, NULL, NULL, 0)))
824 * If the sendproc is the nmh command `send', then we call
825 * those routines directly rather than exec'ing the command.
827 if (strcmp (sp = r1bindex (sendproc, '/'), "send") == 0) {
829 sendit (invo_name = sp, arg, file, pushsw);
834 context_save (); /* save the context file */
837 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
841 advise (NULL, "unable to fork, so sending directly...");
844 vec[vecp++] = invo_name;
846 vec[vecp++] = "-push";
849 vec[vecp++] = *arg++;
853 execvp (sendproc, vec);
854 fprintf (stderr, "unable to exec ");
859 if (pidwait(child_id, OK) == 0)
867 * Translate MIME composition file (call buildmimeproc)
871 buildfile (char **argp, char *file)
878 /* allocate space for arguments */
884 args = (char **) mh_xmalloc((i + 2) * sizeof(char *));
887 * For backward compatibility, we need to add -build
888 * if we are using mhn as buildmimeproc
891 if (strcmp (r1bindex (ed, '/'), "mhn") == 0)
892 args[i++] = "-build";
894 /* copy any other arguments */
895 while (argp && *argp)
899 i = editfile (&ed, args, file, NOUSE, NULL, NULL, NULL, 0);
902 return (i ? NOTOK : OK);
907 * Check if draft is a mhbuild composition file
911 check_draft (char *msgnam)
914 char buf[BUFSIZ], name[NAMESZ];
917 if ((fp = fopen (msgnam, "r")) == NULL)
920 switch (state = m_getfld (state, name, buf, sizeof(buf), fp)) {
925 * If draft already contains any of the
926 * Content-XXX fields, then assume it already
929 if (uprf (name, XXX_FIELD_PRF)) {
933 while (state == FLDPLUS)
934 state = m_getfld (state, name, buf, sizeof(buf), fp);
941 for (bp = buf; *bp; bp++)
942 if (*bp != ' ' && *bp != '\t' && *bp != '\n') {
947 state = m_getfld (state, name, buf, sizeof(buf), fp);
948 } while (state == BODY);
958 static struct swit sendswitches[] = {
960 { "alias aliasfile", 0 },
964 { "filter filterfile", 0 },
1000 { "width columns", 0 },
1001 #define SVERSIONSW 21
1005 #define BITSTUFFSW 23
1006 { "dashstuffing", -12 },
1007 #define NBITSTUFFSW 24
1008 { "nodashstuffing", -14 },
1018 { "client host", -6 },
1020 { "server host", 6 },
1023 #define SNDATTACHSW 32
1024 { "attach file", 6 },
1025 #define SNDATTACHFORMAT 33
1026 { "attachformat", 7 },
1028 { "port server-port-name/number", 4 },
1033 extern int debugsw; /* from sendsbr.c */
1040 extern char *altmsg; /* .. */
1041 extern char *annotext;
1042 extern char *distfile;
1046 sendit (char *sp, char **arg, char *file, int pushed)
1049 char *cp, buf[BUFSIZ], **argp;
1050 char **arguments, *vec[MAXARGS];
1052 char *attach = (char *)0; /* attachment header field name */
1053 int attachformat = 0; /* mhbuild format specifier for
1064 * Make sure these are defined. In particular, we need
1065 * vec[1] to be NULL, in case "arg" is NULL below. It
1066 * doesn't matter what is the value of vec[0], but we
1067 * set it to NULL, to help catch "off-by-one" errors.
1073 * Temporarily copy arg to vec, since the brkstring() call in
1074 * getarguments() will wipe it out before it is merged in.
1075 * Also, we skip the first element of vec, since getarguments()
1076 * skips it. Then we count the number of arguments
1077 * copied. The value of "n" will be one greater than
1078 * this in order to simulate the standard argc/argv.
1083 copyip (arg, vec+1, MAXARGS-1);
1090 * Merge any arguments from command line (now in vec)
1091 * and arguments from profile.
1093 arguments = getarguments (sp, n, vec, 1);
1105 vecp = 1; /* we'll get the zero'th element later */
1106 vec[vecp++] = "-library";
1107 vec[vecp++] = getcpy (m_maildir (""));
1109 while ((cp = *argp++)) {
1111 switch (smatch (++cp, sendswitches)) {
1113 ambigsw (cp, sendswitches);
1116 advise (NULL, "-%s unknown\n", cp);
1120 snprintf (buf, sizeof(buf), "%s [switches]", sp);
1121 print_help (buf, sendswitches, 1);
1124 print_version (invo_name);
1157 debugsw++; /* fall */
1184 if (!(cp = *argp++) || *cp == '-') {
1185 advise (NULL, "missing argument to %s", argp[-2]);
1192 if (!(attach = *argp++) || *attach == '-') {
1193 advise (NULL, "missing argument to %s", argp[-2]);
1198 case SNDATTACHFORMAT:
1199 if (! *argp || **argp == '-')
1200 adios (NULL, "missing argument to %s", argp[-1]);
1202 attachformat = atoi (*argp);
1203 if (attachformat < 0 ||
1204 attachformat > ATTACHFORMATS - 1) {
1205 advise (NULL, "unsupported attachformat %d",
1214 advise (NULL, "usage: %s [switches]", sp);
1218 /* allow Aliasfile: profile entry */
1219 if ((cp = context_find ("Aliasfile"))) {
1223 for (ap = brkstring (dp, " ", "\n"); ap && *ap; ap++) {
1224 vec[vecp++] = "-alias";
1229 if ((cp = getenv ("SIGNATURE")) == NULL || *cp == 0)
1230 if ((cp = context_find ("signature")) && *cp)
1231 m_putenv ("SIGNATURE", cp);
1234 snprintf (buf, sizeof(buf), "%s/.signature", mypath);
1235 if ((fp = fopen (buf, "r")) != NULL
1236 && fgets (buf, sizeof(buf), fp) != NULL) {
1238 if (cp = strchr (buf, '\n'))
1240 m_putenv ("SIGNATURE", buf);
1245 if ((annotext = getenv ("mhannotate")) == NULL || *annotext == 0)
1247 if ((altmsg = getenv ("mhaltmsg")) == NULL || *altmsg == 0)
1249 if (annotext && ((cp = getenv ("mhinplace")) != NULL && *cp != 0))
1250 inplace = atoi (cp);
1252 if ((cp = getenv ("mhdist"))
1255 && (distsw = atoi (cp))
1256 #endif /* not lint */
1258 vec[vecp++] = "-dist";
1259 distfile = getcpy (m_mktemp2(altmsg, invo_name, NULL, NULL));
1260 if (link (altmsg, distfile) == NOTOK)
1261 adios (distfile, "unable to link %s to", altmsg);
1266 if (altmsg == NULL || stat (altmsg, &st) == NOTOK) {
1271 if ((pushsw = pushed))
1274 vec[0] = r1bindex (postproc, '/');
1277 if (sendsbr (vec, vecp, file, &st, 1, attach, attachformat) == OK)
1283 * Remove the draft file
1287 removefile (char *drft)
1289 if (unlink (drft) == NOTOK)
1290 adios (drft, "unable to unlink");