+
+
+/* Build a command line of the form $SHELL -c "cd 'cwd'; cmd argp ... ; trailcmd". */
+static void
+writesomecmd(char *buf, int bufsz, char *cmd, char *trailcmd, char **argp)
+{
+ char *cp;
+ /* Note that we do not quote -- the argp from the user
+ * is assumed to be quoted as they desire. (We can't treat
+ * it as pure literal as that would prevent them using ~,
+ * wildcards, etc.) The buffer produced by this function
+ * should be given to popen_in_dir() or system_in_dir() so
+ * that the current working directory is set correctly.
+ */
+ int ln = snprintf(buf, bufsz, "$SHELL -c \"%s", cmd);
+ /* NB that some snprintf() return -1 on overflow rather than the
+ * new C99 mandated 'number of chars that would have been written'
+ */
+ /* length checks here and inside the loop allow for the
+ * trailing ';', trailcmd, '"' and NUL
+ */
+ int trailln = strlen(trailcmd) + 3;
+ if (ln < 0 || ln + trailln > bufsz)
+ adios((char *)0, "arguments too long");
+
+ cp = buf + ln;
+
+ while (*++argp != (char *)0) {
+ ln = strlen(*argp);
+ /* +1 for leading space */
+ if (ln + trailln + 1 > bufsz - (cp-buf))
+ adios((char *)0, "arguments too long");
+ *cp++ = ' ';
+ memcpy(cp, *argp, ln+1);
+ cp += ln;
+ }
+ if (*trailcmd) {
+ *cp++ = ';';
+ strcpy(cp, trailcmd);
+ cp += trailln - 3;
+ }
+ *cp++ = '"';
+ *cp = 0;
+}
+
+/*
+ * Build a command line that causes the user's shell to list the file name
+ * arguments. This handles and wildcard expansion, tilde expansion, etc.
+ */
+static void
+writelscmd(char *buf, int bufsz, char **argp)
+{
+ writesomecmd(buf, bufsz, "ls", "", argp);
+}
+
+/* Like system(), but run the command in directory dir.
+ * This assumes the program is single-threaded!
+ */
+static int
+system_in_dir(const char *dir, const char *cmd)
+{
+ char olddir[BUFSIZ];
+ int r;
+ if (getcwd(olddir, sizeof(olddir)) == 0)
+ adios("getcwd", "could not get working directory");
+ if (chdir(dir) != 0)
+ adios("chdir", "could not change working directory");
+ r = system(cmd);
+ if (chdir(olddir) != 0)
+ adios("chdir", "could not change working directory");
+ return r;
+}
+
+/* ditto for popen() */
+static FILE*
+popen_in_dir(const char *dir, const char *cmd, const char *type)
+{
+ char olddir[BUFSIZ];
+ FILE *f;
+ if (getcwd(olddir, sizeof(olddir)) == 0)
+ adios("getcwd", "could not get working directory");
+ if (chdir(dir) != 0)
+ adios("chdir", "could not change working directory");
+ f = popen(cmd, type);
+ if (chdir(olddir) != 0)
+ adios("chdir", "could not change working directory");
+ return f;
+}
+
+