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 = NULL; /* 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 = mhbasename(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)) == NULL) {
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",
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) == NULL) {
304 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') != NULL)
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 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 == NULL) {
348 advise(NULL, "can't list because no header field name was given.");
355 while (*++argp != NULL) {
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(NULL, "usage is alist [-ln].");
376 annolist(drft, attach, l, n);
382 ** Attach files to current draft.
385 if (attach == NULL) {
386 advise(NULL, "can't attach because no header field name was given.");
390 if (*(argp+1) == NULL) {
391 advise(NULL, "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 == NULL) {
442 advise(NULL, "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;
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;
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 != NULL; argp++) {
482 if (atoi(*argp) > n) {
483 if (atoi(*argp) == 1)
486 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(NULL, "arguments too long");
562 while (*++argp != NULL) {
564 /* +1 for leading space */
565 if (ln + trailln + 1 > bufsz - (cp-buf))
566 adios(NULL, "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 = mhbasename(*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++] = mhbasename(*ed);
725 vec[vecp++] = *arg++;
730 fprintf(stderr, "unable to exec ");
735 if ((status = pidwait(pid, NOTOK))) {
737 if ((cp = mhbasename(*ed)) &&
738 strcmp(cp, "vi") == 0 &&
739 (status & 0x00ff) == 0)
743 if (((status & 0xff00) != 0xff00)
744 && (!reedit || (status & 0x00ff))) {
745 if (!use && (status & 0xff00) && (rename(file, cp = m_backup (file)) != NOTOK)) {
746 advise(NULL, "problems with edit--draft left in %s", cp);
748 advise(NULL, "problems with edit--%s preserved", file);
751 status = -2; /* maybe "reedit ? -2 : -1"? */
760 if (altmsg && mp && !is_readonly(mp) && (slinked ?
761 lstat (linkpath, &st) != NOTOK &&
762 S_ISREG(st.st_mode) &&
763 copyf(linkpath, altpath) == NOTOK :
764 stat(linkpath, &st) != NOTOK &&
766 (unlink(altpath) == NOTOK ||
767 link(linkpath, altpath) == NOTOK)))
768 advise(linkpath, "unable to update %s from", altmsg);
769 #else /* HAVE_LSTAT */
770 if (altmsg && mp && !is_readonly(mp) &&
771 stat(linkpath, &st) != NOTOK &&
773 (unlink(altpath) == NOTOK ||
774 link(linkpath, altpath) == NOTOK))
775 advise(linkpath, "unable to update %s from",
777 #endif /* HAVE_LSTAT */
780 /* normally, we remember which editor we used */
782 edsave = getcpy(*ed);
794 copyf(char *ifile, char *ofile)
799 if ((in = open(ifile, O_RDONLY)) == NOTOK)
801 if ((out = open(ofile, O_WRONLY | O_TRUNC)) == NOTOK) {
802 admonish(ofile, "unable to open and truncate");
807 while ((i = read(in, buffer, sizeof(buffer))) > OK)
808 if (write(out, buffer, i) != i) {
809 advise(ofile, "may have damaged");
818 #endif /* HAVE_LSTAT */
826 sendfile(char **arg, char *file, int pushsw)
830 char *cp, *sp, *vec[MAXARGS];
832 /* Translate MIME composition file, if necessary */
833 if ((cp = context_find("automimeproc")) && (!strcmp(cp, "1")) &&
834 !getenv("NOMHNPROC") && check_draft(file) &&
835 (buildfile(NULL, file) == NOTOK))
838 /* For backwards compatibility */
839 if ((cp = context_find("automhnproc")) && !getenv("NOMHNPROC")
840 && check_draft(file) && (i = editfile(&cp, NULL,
841 file, NOUSE, NULL, NULL, NULL, 0)))
845 ** If the sendproc is the nmh command `send', then we call
846 ** those routines directly rather than exec'ing the command.
848 if (strcmp(sp = mhbasename(sendproc), "send") == 0) {
850 sendit(invo_name = sp, arg, file, pushsw);
855 context_save(); /* save the context file */
858 for (i = 0; (child_id = vfork()) == NOTOK && i < 5; i++)
862 advise(NULL, "unable to fork, so sending directly...");
865 vec[vecp++] = invo_name;
867 vec[vecp++] = "-push";
870 vec[vecp++] = *arg++;
874 execvp(sendproc, vec);
875 fprintf(stderr, "unable to exec ");
880 if (pidwait(child_id, OK) == 0)
888 ** Translate MIME composition file (call buildmimeproc)
892 buildfile(char **argp, char *file)
899 /* allocate space for arguments */
905 args = (char **) mh_xmalloc((i + 2) * sizeof(char *));
908 ** For backward compatibility, we need to add -build
909 ** if we are using mhn as buildmimeproc
912 if (strcmp(mhbasename(ed), "mhn") == 0)
913 args[i++] = "-build";
915 /* copy any other arguments */
916 while (argp && *argp)
920 i = editfile(&ed, args, file, NOUSE, NULL, NULL, NULL, 0);
923 return (i ? NOTOK : OK);
928 ** Check if draft is a mhbuild composition file
932 check_draft(char *msgnam)
935 char buf[BUFSIZ], name[NAMESZ];
938 if ((fp = fopen(msgnam, "r")) == NULL)
941 switch (state = m_getfld(state, name, buf, sizeof(buf), fp)) {
946 ** If draft already contains any of the
947 ** Content-XXX fields, then assume it already
950 if (uprf(name, XXX_FIELD_PRF)) {
954 while (state == FLDPLUS)
955 state = m_getfld(state, name, buf,
963 for (bp = buf; *bp; bp++)
964 if (*bp != ' ' && *bp != '\t' && *bp != '\n') {
969 state = m_getfld(state, name, buf,
971 } while (state == BODY);
981 static struct swit sendswitches[] = {
983 { "alias aliasfile", 0 },
987 { "filter filterfile", 0 },
1023 { "width columns", 0 },
1024 #define SVERSIONSW 21
1028 #define BITSTUFFSW 23
1029 { "dashstuffing", -12 },
1030 #define NBITSTUFFSW 24
1031 { "nodashstuffing", -14 },
1041 { "client host", -6 },
1043 { "server host", 6 },
1046 #define SNDATTACHSW 32
1047 { "attach file", 6 },
1048 #define SNDATTACHFORMAT 33
1049 { "attachformat", 7 },
1051 { "port server-port-name/number", 4 },
1056 extern int debugsw; /* from sendsbr.c */
1063 extern char *altmsg; /* .. */
1064 extern char *annotext;
1065 extern char *distfile;
1069 sendit(char *sp, char **arg, char *file, int pushed)
1072 char *cp, buf[BUFSIZ], **argp;
1073 char **arguments, *vec[MAXARGS];
1075 char *attach = NULL; /* attachment header field name */
1076 int attachformat = 0; /* mhbuild format specifier for attachments */
1086 ** Make sure these are defined. In particular, we need
1087 ** vec[1] to be NULL, in case "arg" is NULL below. It
1088 ** doesn't matter what is the value of vec[0], but we
1089 ** set it to NULL, to help catch "off-by-one" errors.
1095 ** Temporarily copy arg to vec, since the brkstring() call in
1096 ** getarguments() will wipe it out before it is merged in.
1097 ** Also, we skip the first element of vec, since getarguments()
1098 ** skips it. Then we count the number of arguments
1099 ** copied. The value of "n" will be one greater than
1100 ** this in order to simulate the standard argc/argv.
1105 copyip(arg, vec+1, MAXARGS-1);
1112 ** Merge any arguments from command line (now in vec)
1113 ** and arguments from profile.
1115 arguments = getarguments (sp, n, vec, 1);
1127 vecp = 1; /* we'll get the zero'th element later */
1128 vec[vecp++] = "-library";
1129 vec[vecp++] = getcpy(toabsdir("+"));
1131 while ((cp = *argp++)) {
1133 switch (smatch(++cp, sendswitches)) {
1135 ambigsw(cp, sendswitches);
1138 advise(NULL, "-%s unknown\n", cp);
1142 snprintf(buf, sizeof(buf),
1143 "%s [switches]", sp);
1144 print_help(buf, sendswitches, 1);
1147 print_version(invo_name);
1180 debugsw++; /* fall */
1207 if (!(cp = *argp++) || *cp == '-') {
1208 advise(NULL, "missing argument to %s", argp[-2]);
1215 if (!(attach = *argp++) ||
1217 advise(NULL, "missing argument to %s", argp[-2]);
1222 case SNDATTACHFORMAT:
1223 if (! *argp || **argp == '-')
1224 adios(NULL, "missing argument to %s", argp[-1]);
1226 attachformat = atoi(*argp);
1227 if (attachformat < 0 || attachformat > ATTACHFORMATS - 1) {
1228 advise(NULL, "unsupported attachformat %d", attachformat);
1236 advise(NULL, "usage: %s [switches]", sp);
1240 /* allow Aliasfile: profile entry */
1241 if ((cp = context_find("Aliasfile"))) {
1245 for (ap = brkstring(dp, " ", "\n"); ap && *ap; ap++) {
1246 vec[vecp++] = "-alias";
1251 if ((cp = getenv("SIGNATURE")) == NULL || *cp == 0)
1252 if ((cp = context_find("signature")) && *cp)
1253 m_putenv("SIGNATURE", cp);
1256 snprintf(buf, sizeof(buf), "%s/.signature", mypath);
1257 if ((fp = fopen(buf, "r")) != NULL &&
1258 fgets(buf, sizeof(buf), fp) != NULL) {
1260 if (cp = strchr(buf, '\n'))
1262 m_putenv("SIGNATURE", buf);
1267 if ((annotext = getenv("mhannotate")) == NULL || *annotext == 0)
1269 if ((altmsg = getenv("mhaltmsg")) == NULL || *altmsg == 0)
1271 if (annotext && ((cp = getenv("mhinplace")) != NULL && *cp != 0))
1274 if ((cp = getenv("mhdist")) && *cp
1276 && (distsw = atoi (cp))
1277 #endif /* not lint */
1279 vec[vecp++] = "-dist";
1280 distfile = getcpy(m_mktemp2(altmsg, invo_name, NULL, NULL));
1281 if (link(altmsg, distfile) == NOTOK)
1282 adios(distfile, "unable to link %s to", altmsg);
1287 if (altmsg == NULL || stat(altmsg, &st) == NOTOK) {
1292 if ((pushsw = pushed))
1295 vec[0] = mhbasename(postproc);
1298 if (sendsbr(vec, vecp, file, &st, 1, attach, attachformat) == OK)
1304 ** Remove the draft file
1308 removefile(char *drft)
1310 if (unlink(drft) == NOTOK)
1311 adios(drft, "unable to unlink");