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),
166 "%s [switches] [file]",
168 print_help (buf, whatnowswitches, 1);
171 print_version(invo_name);
175 if (!(ed = *argp++) || *ed == '-')
176 adios (NULL, "missing argument to %s",
185 if (!(myprompt = *argp++) || *myprompt == '-')
186 adios (NULL, "missing argument to %s",
191 if (attach != (char *)0)
192 adios(NULL, "only one attachment header field name at a time!");
193 if (!(attach = *argp++) || *attach == '-')
194 adios (NULL, "missing argument to %s",
200 adios (NULL, "only one draft at a time!");
205 if ((drft == NULL && (drft = getenv("mhdraft")) == NULL) || *drft == 0)
206 drft = getcpy (m_draft("cur"));
208 msgnam = (cp = getenv ("mhaltmsg")) && *cp ? getcpy (cp) : NULL;
210 if ((cp = getenv ("mhuse")) && *cp)
213 if (ed == NULL && ((ed = getenv ("mheditor")) == NULL || *ed == 0)) {
218 /* start editing the draft, unless -noedit was given */
219 if (!nedit && editfile(&ed, NULL, drft, use, NULL, msgnam, NULL, 1)
223 snprintf (prompt, sizeof(prompt), myprompt, invo_name);
225 if (!(argp = getans (prompt, aleqs))) {
229 switch (smatch (*argp, aleqs)) {
232 ** display the message being replied to,
236 showfile (++argp, msgnam);
238 advise (NULL, "no alternate message to display");
242 /* Translate MIME composition file */
243 buildfile (++argp, drft);
247 /* Call an editor on the draft file */
250 if (editfile (&ed, argp, drft, NOUSE, NULL,
251 msgnam, NULL, 1) == NOTOK)
256 /* display the draft file */
257 showfile (++argp, drft);
261 /* Quit, and possibly delete the draft */
262 if (*++argp && (*argp[0] == 'd' ||
263 ((*argp)[0] == '-' && (*argp)[1] == 'd'))) {
266 if (stat (drft, &st) != NOTOK)
267 advise(NULL, "draft left on %s", drft);
272 /* Delete draft and exit */
277 /* Send draft in background */
278 if (sendfile (++argp, drft, 1))
284 sendfile (++argp, drft, 0);
288 /* Refile the draft */
289 if (refile (++argp, drft) == 0)
295 ** Change the working directory for attachments
297 ** Run the directory through the user's shell
298 ** so that we can take advantage of any syntax
299 ** that the user is accustomed to. Read back
300 ** the absolute path.
303 if (*(argp+1) == (char *)0) {
304 (void)sprintf(buf, "$SHELL -c \"cd;pwd\"");
306 writesomecmd(buf, BUFSIZ, "cd", "pwd", argp);
308 if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
309 fgets(cwd, sizeof (cwd), f);
311 if (strchr(cwd, '\n') != (char *)0)
312 *strchr(cwd, '\n') = '\0';
316 advise("popen", "could not get directory");
322 /* Print the working directory for attachments */
328 ** List files in the current attachment working
331 ** Use the user's shell so that we can take
332 ** advantage of any syntax that the user is
335 writelscmd(buf, sizeof(buf), argp);
336 (void)system_in_dir(cwd, buf);
341 ** List attachments on current draft. Options are:
343 ** -l long listing (full path names)
344 ** -n numbers listing
347 if (attach == (char *)0) {
348 advise((char *)0, "can't list because no header field name was given.");
355 while (*++argp != (char *)0) {
356 if (strcmp(*argp, "-l") == 0)
359 else if (strcmp(*argp, "-n") == 0)
362 else if (strcmp(*argp, "-ln") == 0 ||
363 strcmp(*argp, "-nl") == 0) {
373 advise((char *)0, "usage is alist [-ln].");
376 annolist(drft, attach, l, n);
382 ** Attach files to current draft.
385 if (attach == (char *)0) {
386 advise((char *)0, "can't attach because no header field name was given.");
390 if (*(argp+1) == (char *)0) {
391 advise((char *)0, "attach command requires file argument(s).");
396 ** Build a command line that causes the user's
397 ** shell to list the file name arguments.
398 ** This handles and wildcard expansion, tilde
401 writelscmd(buf, sizeof(buf), argp);
404 ** Read back the response from the shell,
405 ** which contains a number of lines with one
406 ** file name per line. Remove off the newline.
407 ** Determine whether we have an absolute or
408 ** relative path name. Prepend the current
409 ** working directory to relative path names.
410 ** Add the attachment annotation to the draft.
413 if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
414 while (fgets(shell, sizeof (shell), f)
416 *(strchr(shell, '\n')) = '\0';
419 annotate(drft, attach, shell,
422 sprintf(file, "%s/%s", cwd,
424 annotate(drft, attach, file,
431 advise("popen", "could not get file from shell");
438 ** Detach files from current draft.
441 if (attach == (char *)0) {
442 advise((char *)0, "can't detach because no header field name was given.");
447 ** Scan the arguments for a -n. Mixed file
448 ** names and numbers aren't allowed, so this
449 ** catches a -n anywhere in the argument list.
452 for (n = 0, arguments = argp + 1;
453 *arguments != (char *)0;
455 if (strcmp(*arguments, "-n") == 0) {
462 ** A -n was found so interpret the arguments as
463 ** attachment numbers. Decrement any remaining
464 ** argument number that is greater than the one
465 ** just processed after processing each one so
466 ** that the numbering stays correct.
470 for (arguments = argp + 1;
471 *arguments != (char *)0;
473 if (strcmp(*arguments, "-n") == 0)
476 if (**arguments != '\0') {
477 n = atoi(*arguments);
478 annotate(drft, attach, NULL,
481 for (argp = arguments + 1; *argp != (char *)0; argp++) {
482 if (atoi(*argp) > n) {
483 if (atoi(*argp) == 1)
486 (void)sprintf(*argp, "%d", atoi(*argp) - 1);
494 ** The arguments are interpreted as file names.
495 ** Run them through the user's shell for wildcard
496 ** expansion and other goodies. Do this from
497 ** the current working directory if the argument
498 ** is not an absolute path name (does not begin
501 ** We feed all the file names to the shell at
502 ** once, otherwise you can't provide a file name
503 ** with a space in it.
505 writelscmd(buf, sizeof(buf), argp);
506 if ((f = popen_in_dir(cwd, buf, "r")) != (FILE *)0) {
507 while (fgets(shell, sizeof (shell), f)
509 *(strchr(shell, '\n')) = '\0';
510 annotate(drft, attach, shell,
515 advise("popen", "could not get file from shell");
521 /* Unknown command */
522 advise (NULL, "say what?");
532 ** Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ;
536 writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
540 ** Note that we do not quote -- the argp from the user
541 ** is assumed to be quoted as they desire. (We can't treat
542 ** it as pure literal as that would prevent them using ~,
543 ** wildcards, etc.) The buffer produced by this function
544 ** should be given to popen_in_dir() or system_in_dir() so
545 ** that the current working directory is set correctly.
547 int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
549 ** NB that some snprintf() return -1 on overflow rather than the
550 ** new C99 mandated 'number of chars that would have been written'
553 ** length checks here and inside the loop allow for the
554 ** trailing ';', trailcmd, '"' and NUL
556 int trailln = strlen(trailcmd) + 3;
557 if (ln < 0 || ln + trailln > bufsz)
558 adios((char *)0, "arguments too long");
562 while (*++argp != (char *)0) {
564 /* +1 for leading space */
565 if (ln + trailln + 1 > bufsz - (cp-buf))
566 adios((char *)0, "arguments too long");
568 memcpy(cp, *argp, ln+1);
573 strcpy(cp, trailcmd);
581 ** Build a command line that causes the user's shell to list the file name
582 ** arguments. This handles and wildcard expansion, tilde expansion, etc.
585 writelscmd(char *buf, int bufsz, char **argp)
587 writesomecmd(buf, bufsz, "ls", "", argp);
591 ** Like system(), but run the command in directory dir.
592 ** This assumes the program is single-threaded!
595 system_in_dir(const char *dir, const char *cmd)
599 if (getcwd(olddir, sizeof(olddir)) == 0)
600 adios("getcwd", "could not get working directory");
602 adios("chdir", "could not change working directory");
604 if (chdir(olddir) != 0)
605 adios("chdir", "could not change working directory");
609 /* ditto for popen() */
611 popen_in_dir(const char *dir, const char *cmd, const char *type)
615 if (getcwd(olddir, sizeof(olddir)) == 0)
616 adios("getcwd", "could not get working directory");
618 adios("chdir", "could not change working directory");
619 f = popen(cmd, type);
620 if (chdir(olddir) != 0)
621 adios("chdir", "could not change working directory");
630 static int reedit = 0; /* have we been here before? */
631 static char *edsave = NULL; /* the editor we used previously */
635 editfile (char **ed, char **arg, char *file, int use, struct msgs *mp,
636 char *altmsg, char *cwd, int save_editor)
638 int pid, status, vecp;
639 char altpath[BUFSIZ], linkpath[BUFSIZ];
640 char *cp, *vec[MAXARGS];
646 int oumask; /* PJS: for setting permissions on symlinks. */
648 #endif /* HAVE_LSTAT */
650 /* Was there a previous edit session? */
652 if (!*ed) { /* no explicit editor */
653 *ed = edsave; /* so use the previous one */
654 if ((cp = r1bindex (*ed, '/')) == NULL)
657 /* unless we've specified it via "editor-next" */
658 cp = concat (cp, "-next", NULL);
659 if ((cp = context_find (cp)) != NULL)
663 /* set initial editor */
664 if (*ed == NULL && (*ed = context_find ("editor")) == NULL)
669 if (mp == NULL || *altmsg == '/' || cwd == NULL)
670 strncpy (altpath, altmsg, sizeof(altpath));
672 snprintf (altpath, sizeof(altpath), "%s/%s",
673 mp->foldpath, altmsg);
675 strncpy (linkpath, altmsglink, sizeof(linkpath));
677 snprintf (linkpath, sizeof(linkpath), "%s/%s",
684 if (link (altpath, linkpath) == NOTOK) {
686 /* I don't think permission on symlinks matters /JLR */
687 /* PJS: else symlinks are world 'r' */
688 oumask = umask(0044);
690 symlink (altpath, linkpath);
692 umask(oumask); /* PJS: else symlinks are world 'r' */
698 #else /* not HAVE_LSTAT */
699 link (altpath, linkpath);
700 #endif /* not HAVE_LSTAT */
703 context_save (); /* save the context file */
706 switch (pid = vfork ()) {
708 advise ("fork", "unable to");
717 m_putenv ("mhfolder", mp->foldpath);
718 m_putenv ("editalt", altpath);
722 vec[vecp++] = r1bindex (*ed, '/');
725 vec[vecp++] = *arg++;
730 fprintf (stderr, "unable to exec ");
735 if ((status = pidwait (pid, NOTOK))) {
737 if ((cp = r1bindex (*ed, '/'))
738 && strcmp (cp, "vi") == 0
739 && (status & 0x00ff) == 0)
743 if (((status & 0xff00) != 0xff00)
744 && (!reedit || (status & 0x00ff))) {
745 if (!use && (status & 0xff00) &&
746 (rename (file, cp = m_backup (file)) != NOTOK)) {
747 advise (NULL, "problems with edit--draft left in %s", cp);
749 advise (NULL, "problems with edit--%s preserved", file);
752 status = -2; /* maybe "reedit ? -2 : -1"? */
765 ? lstat (linkpath, &st) != NOTOK
766 && S_ISREG(st.st_mode)
767 && copyf (linkpath, altpath) == NOTOK
768 : stat (linkpath, &st) != NOTOK
770 && (unlink (altpath) == NOTOK
771 || link (linkpath, altpath) == NOTOK)))
772 advise (linkpath, "unable to update %s from", altmsg);
773 #else /* HAVE_LSTAT */
774 if (altmsg && mp && !is_readonly(mp)
775 && stat (linkpath, &st) != NOTOK
777 && (unlink (altpath) == NOTOK
778 || link (linkpath, altpath) == NOTOK))
779 advise (linkpath, "unable to update %s from",
781 #endif /* HAVE_LSTAT */
784 /* normally, we remember which editor we used */
786 edsave = getcpy (*ed);
798 copyf (char *ifile, char *ofile)
803 if ((in = open (ifile, O_RDONLY)) == NOTOK)
805 if ((out = open (ofile, O_WRONLY | O_TRUNC)) == NOTOK) {
806 admonish (ofile, "unable to open and truncate");
811 while ((i = read (in, buffer, sizeof(buffer))) > OK)
812 if (write (out, buffer, i) != i) {
813 advise (ofile, "may have damaged");
822 #endif /* HAVE_LSTAT */
830 sendfile (char **arg, char *file, int pushsw)
834 char *cp, *sp, *vec[MAXARGS];
836 /* Translate MIME composition file, if necessary */
837 if ((cp = context_find ("automimeproc")) && (!strcmp (cp, "1"))
838 && !getenv ("NOMHNPROC") && check_draft (file)
839 && (buildfile (NULL, file) == NOTOK))
842 /* For backwards compatibility */
843 if ((cp = context_find ("automhnproc")) && !getenv ("NOMHNPROC")
844 && check_draft (file) && (i = editfile (&cp, NULL,
845 file, NOUSE, NULL, NULL, NULL, 0)))
849 ** If the sendproc is the nmh command `send', then we call
850 ** those routines directly rather than exec'ing the command.
852 if (strcmp (sp = r1bindex (sendproc, '/'), "send") == 0) {
854 sendit (invo_name = sp, arg, file, pushsw);
859 context_save (); /* save the context file */
862 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
866 advise (NULL, "unable to fork, so sending directly...");
869 vec[vecp++] = invo_name;
871 vec[vecp++] = "-push";
874 vec[vecp++] = *arg++;
878 execvp (sendproc, vec);
879 fprintf (stderr, "unable to exec ");
884 if (pidwait(child_id, OK) == 0)
892 ** Translate MIME composition file (call buildmimeproc)
896 buildfile (char **argp, char *file)
903 /* allocate space for arguments */
909 args = (char **) mh_xmalloc((i + 2) * sizeof(char *));
912 ** For backward compatibility, we need to add -build
913 ** if we are using mhn as buildmimeproc
916 if (strcmp (r1bindex (ed, '/'), "mhn") == 0)
917 args[i++] = "-build";
919 /* copy any other arguments */
920 while (argp && *argp)
924 i = editfile (&ed, args, file, NOUSE, NULL, NULL, NULL, 0);
927 return (i ? NOTOK : OK);
932 ** Check if draft is a mhbuild composition file
936 check_draft (char *msgnam)
939 char buf[BUFSIZ], name[NAMESZ];
942 if ((fp = fopen (msgnam, "r")) == NULL)
945 switch (state = m_getfld (state, name, buf, sizeof(buf), fp)) {
950 ** If draft already contains any of the
951 ** Content-XXX fields, then assume it already
954 if (uprf (name, XXX_FIELD_PRF)) {
958 while (state == FLDPLUS)
959 state = m_getfld (state, name, buf,
967 for (bp = buf; *bp; bp++)
968 if (*bp != ' ' && *bp != '\t' && *bp != '\n') {
973 state = m_getfld (state, name, buf,
975 } while (state == BODY);
985 static struct swit sendswitches[] = {
987 { "alias aliasfile", 0 },
991 { "filter filterfile", 0 },
1027 { "width columns", 0 },
1028 #define SVERSIONSW 21
1032 #define BITSTUFFSW 23
1033 { "dashstuffing", -12 },
1034 #define NBITSTUFFSW 24
1035 { "nodashstuffing", -14 },
1045 { "client host", -6 },
1047 { "server host", 6 },
1050 #define SNDATTACHSW 32
1051 { "attach file", 6 },
1052 #define SNDATTACHFORMAT 33
1053 { "attachformat", 7 },
1055 { "port server-port-name/number", 4 },
1060 extern int debugsw; /* from sendsbr.c */
1067 extern char *altmsg; /* .. */
1068 extern char *annotext;
1069 extern char *distfile;
1073 sendit (char *sp, char **arg, char *file, int pushed)
1076 char *cp, buf[BUFSIZ], **argp;
1077 char **arguments, *vec[MAXARGS];
1079 char *attach = (char *)0; /* attachment header field name */
1080 int attachformat = 0; /* mhbuild format specifier for attachments */
1090 ** Make sure these are defined. In particular, we need
1091 ** vec[1] to be NULL, in case "arg" is NULL below. It
1092 ** doesn't matter what is the value of vec[0], but we
1093 ** set it to NULL, to help catch "off-by-one" errors.
1099 ** Temporarily copy arg to vec, since the brkstring() call in
1100 ** getarguments() will wipe it out before it is merged in.
1101 ** Also, we skip the first element of vec, since getarguments()
1102 ** skips it. Then we count the number of arguments
1103 ** copied. The value of "n" will be one greater than
1104 ** this in order to simulate the standard argc/argv.
1109 copyip (arg, vec+1, MAXARGS-1);
1116 ** Merge any arguments from command line (now in vec)
1117 ** and arguments from profile.
1119 arguments = getarguments (sp, n, vec, 1);
1131 vecp = 1; /* we'll get the zero'th element later */
1132 vec[vecp++] = "-library";
1133 vec[vecp++] = getcpy (m_maildir (""));
1135 while ((cp = *argp++)) {
1137 switch (smatch (++cp, sendswitches)) {
1139 ambigsw (cp, sendswitches);
1142 advise (NULL, "-%s unknown\n", cp);
1146 snprintf (buf, sizeof(buf),
1147 "%s [switches]", sp);
1148 print_help (buf, sendswitches, 1);
1151 print_version (invo_name);
1184 debugsw++; /* fall */
1211 if (!(cp = *argp++) || *cp == '-') {
1212 advise (NULL, "missing argument to %s", argp[-2]);
1219 if (!(attach = *argp++) ||
1221 advise (NULL, "missing argument to %s", argp[-2]);
1226 case SNDATTACHFORMAT:
1227 if (! *argp || **argp == '-')
1228 adios (NULL, "missing argument to %s", argp[-1]);
1230 attachformat = atoi (*argp);
1231 if (attachformat < 0 || attachformat > ATTACHFORMATS - 1) {
1232 advise (NULL, "unsupported attachformat %d", attachformat);
1240 advise (NULL, "usage: %s [switches]", sp);
1244 /* allow Aliasfile: profile entry */
1245 if ((cp = context_find ("Aliasfile"))) {
1249 for (ap = brkstring (dp, " ", "\n"); ap && *ap; ap++) {
1250 vec[vecp++] = "-alias";
1255 if ((cp = getenv ("SIGNATURE")) == NULL || *cp == 0)
1256 if ((cp = context_find ("signature")) && *cp)
1257 m_putenv ("SIGNATURE", cp);
1260 snprintf (buf, sizeof(buf), "%s/.signature", mypath);
1261 if ((fp = fopen (buf, "r")) != NULL
1262 && fgets (buf, sizeof(buf), fp) != NULL) {
1264 if (cp = strchr (buf, '\n'))
1266 m_putenv ("SIGNATURE", buf);
1271 if ((annotext = getenv ("mhannotate")) == NULL || *annotext == 0)
1273 if ((altmsg = getenv ("mhaltmsg")) == NULL || *altmsg == 0)
1275 if (annotext && ((cp = getenv ("mhinplace")) != NULL && *cp != 0))
1276 inplace = atoi (cp);
1278 if ((cp = getenv ("mhdist"))
1281 && (distsw = atoi (cp))
1282 #endif /* not lint */
1284 vec[vecp++] = "-dist";
1285 distfile = getcpy (m_mktemp2(altmsg, invo_name, NULL, NULL));
1286 if (link (altmsg, distfile) == NOTOK)
1287 adios (distfile, "unable to link %s to", altmsg);
1292 if (altmsg == NULL || stat (altmsg, &st) == NOTOK) {
1297 if ((pushsw = pushed))
1300 vec[0] = r1bindex (postproc, '/');
1303 if (sendsbr (vec, vecp, file, &st, 1, attach, attachformat) == OK)
1309 ** Remove the draft file
1313 removefile (char *drft)
1315 if (unlink (drft) == NOTOK)
1316 adios (drft, "unable to unlink");