#include <sys/cdefs.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)cd.c 8.2 (Berkeley) 5/4/95";
#else
__RCSID("$NetBSD: cd.c,v 1.56 2025/08/18 18:58:59 kre Exp $");
#endif
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "shell.h"
#include "var.h"
#include "nodes.h"
#include "jobs.h"
#include "options.h"
#include "builtins.h"
#include "output.h"
#include "memalloc.h"
#include "error.h"
#include "exec.h"
#include "redir.h"
#include "mystring.h"
#include "show.h"
#include "cd.h"
STATIC int docd(const char *, bool, bool);
STATIC char *getcomponent(void);
STATIC bool updatepwd(const char *);
STATIC void find_curdir(int noerror);
STATIC bool is_curdir(const char *);
char *curdir = NULL;
char *prevdir;
STATIC char *cdcomppath;
int
cdcmd(int argc, char **argv)
{
const char *dest;
const char *path, *cp;
char *p;
char *d;
struct stat statb;
int print = cdprint;
int err = ENOENT;
int err_set = -1;
bool eopt = false;
char opt;
while ((opt = nextopt("Pe")) != '\0')
if (opt == 'e')
eopt = true;
getpwd(1);
dest = *argptr;
if (dest == NULL) {
dest = bltinlookup("HOME", 1);
if (dest == NULL)
error("HOME not set");
} else if (argptr[1]) {
if (!curdir)
error("PWD not set");
p = strstr(curdir, dest);
if (!p)
error("bad substitution (no \"%s\" in \"%s\")",
dest, curdir);
d = stalloc(strlen(curdir) + strlen(argptr[1]) + 1);
memcpy(d, curdir, p - curdir);
strcpy(d + (p - curdir), argptr[1]);
strcat(d, p + strlen(dest));
dest = d;
print = 1;
} else if (dest[0] == '-' && dest[1] == '\0') {
dest = prevdir ? prevdir : curdir;
print = 1;
}
#if 0
if (*dest == '\0')
dest = ".";
#endif
cp = dest;
if (*cp == '.' && *++cp == '.')
cp++;
if (*cp == 0 || *cp == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
path = nullstr;
cp = dest;
while ((p = padvance(&path, dest, 0)) != NULL) {
int dopr = print;
int x;
stunalloc(p);
if (stat(p, &statb) < 0) {
if (err_set < 0 && errno != ENOENT) {
err = errno;
cp = stalloc((int)strlen(p) + 1);
err_set = 0;
}
continue;
}
if (!S_ISDIR(statb.st_mode)) {
if (err_set <= 0) {
err = ENOTDIR;
cp = stalloc((int)strlen(p) + 1);
err_set = 1;
}
continue;
}
if (!print)
dopr = strcmp(p, dest);
if ((x = docd(p, dopr != 0, eopt)) >= 0)
return x;
if (err_set <= 0 && errno != ENOENT) {
err = errno;
cp = stalloc(strlen(p) + 1);
err_set = 1;
}
}
error("Can't cd to \"%s\": %s", cp, strerror(err));
}
STATIC int
docd(const char *dest, bool print, bool eopt)
{
bool gotpwd;
#if 0
char *p;
char *q;
char *component;
struct stat statb;
int first;
int badstat;
badstat = 0;
cdcomppath = stalloc(strlen(dest) + 1);
scopy(dest, cdcomppath);
STARTSTACKSTR(p);
if (*dest == '/') {
STPUTC('/', p);
cdcomppath++;
}
first = 1;
while ((q = getcomponent()) != NULL) {
if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
continue;
if (! first)
STPUTC('/', p);
first = 0;
component = q;
while (*q)
STPUTC(*q++, p);
if (equal(component, ".."))
continue;
STACKSTRNUL(p);
if (lstat(stackblock(), &statb) < 0) {
badstat = 1;
break;
}
}
#endif
CTRACE(DBG_CMDS, ("docd(\"%s\", %s, %s) called\n", dest,
print ? "true" : "false", eopt ? "true" : "false"));
INTOFF;
if (chdir(dest) < 0) {
INTON;
return -1;
}
gotpwd = updatepwd(NULL);
INTON;
if (!gotpwd && eopt)
sh_warnx("Unable to determine new working directory");
else if (print && (iflag || posix))
out1fmt("%s\n", curdir);
return gotpwd || !eopt ? 0 : 1;
}
STATIC char *
getcomponent(void)
{
char *p;
char *start;
if ((p = cdcomppath) == NULL)
return NULL;
start = cdcomppath;
while (*p != '/' && *p != '\0')
p++;
if (*p == '\0') {
cdcomppath = NULL;
} else {
*p++ = '\0';
cdcomppath = p;
}
return start;
}
STATIC bool
updatepwd(const char *dir)
{
char *new;
char *p;
hashcd();
if (dir == NULL || curdir == NULL) {
if (prevdir)
ckfree(prevdir);
INTOFF;
prevdir = curdir;
curdir = NULL;
getpwd(1);
INTON;
if (curdir) {
setvar("OLDPWD", prevdir, VEXPORT);
setvar("PWD", curdir, VEXPORT);
return true;
} else
unsetvar("PWD", 0);
return false;
}
cdcomppath = stalloc(strlen(dir) + 1);
scopy(dir, cdcomppath);
STARTSTACKSTR(new);
if (*dir != '/') {
p = curdir;
while (*p)
STPUTC(*p++, new);
if (p[-1] == '/')
STUNPUTC(new);
}
while ((p = getcomponent()) != NULL) {
if (equal(p, "..")) {
while (new > stackblock() && (STUNPUTC(new), *new) != '/');
} else if (*p != '\0' && ! equal(p, ".")) {
STPUTC('/', new);
while (*p)
STPUTC(*p++, new);
}
}
if (new == stackblock())
STPUTC('/', new);
STACKSTRNUL(new);
INTOFF;
if (prevdir)
ckfree(prevdir);
prevdir = curdir;
curdir = savestr(stackblock());
setvar("OLDPWD", prevdir, VEXPORT);
setvar("PWD", curdir, VEXPORT);
INTON;
return true;
}
STATIC bool
is_curdir(const char *path)
{
struct stat stdot, stpath;
return path != NULL &&
*path == '/' &&
stat(".", &stdot) != -1 &&
stat(path, &stpath) != -1 &&
stdot.st_dev == stpath.st_dev &&
stdot.st_ino == stpath.st_ino;
}
int
pwdcmd(int argc, char **argv)
{
int i;
char opt = 'L';
while ((i = nextopt("LP")) != '\0')
opt = i;
if (*argptr)
error("unexpected argument");
if (opt == 'L')
getpwd(0);
else
find_curdir(0);
#if 0
setvar("OLDPWD", prevdir, VEXPORT);
setvar("PWD", curdir, VEXPORT);
#endif
if (!is_curdir(curdir)) {
find_curdir(1);
if (curdir == NULL)
error("Unable to find current directory");
}
flushout(out1);
clr_err(out1);
out1str(curdir);
out1c('\n');
flushout(out1);
if (io_err(out1))
error("stdout: %s", strerror(errno));
return 0;
}
void
initpwd(void)
{
getpwd(1);
if (curdir)
setvar("PWD", curdir, VEXPORT);
else
sh_warnx("Cannot determine current working directory");
}
#define MAXPWD 256
void
getpwd(int noerror)
{
char *pwd;
static int first = 1;
if (curdir)
return;
if (first) {
first = 0;
pwd = getenv("PWD");
if (is_curdir(pwd)) {
curdir = savestr(pwd);
return;
}
}
find_curdir(noerror);
return;
}
STATIC void
find_curdir(int noerror)
{
int i;
char *pwd;
#if defined(__NetBSD__) || defined(__SVR4)
for (i = MAXPWD;; i *= 2) {
pwd = stalloc(i);
if (getcwd(pwd, i) != NULL) {
curdir = savestr(pwd);
stunalloc(pwd);
return;
}
stunalloc(pwd);
if (errno == ERANGE)
continue;
if (!noerror)
error("getcwd() failed: %s", strerror(errno));
return;
}
#else
{
char *p;
int status;
struct job *jp;
int pip[2];
pwd = stalloc(MAXPWD);
INTOFF;
if (pipe(pip) < 0)
error("Pipe call failed");
jp = makejob(NULL, 1);
if (forkshell(jp, NULL, FORK_NOJOB) == 0) {
(void) close(pip[0]);
movefd(pip[1], 1);
(void) execl("/bin/pwd", "pwd", (char *)0);
error("Cannot exec /bin/pwd");
}
(void) close(pip[1]);
pip[1] = -1;
p = pwd;
while ((i = read(pip[0], p, pwd + MAXPWD - p)) > 0
|| (i == -1 && errno == EINTR)) {
if (i > 0)
p += i;
}
(void) close(pip[0]);
pip[0] = -1;
status = waitforjob(jp);
if (status != 0)
error((char *)0);
if (i < 0 || p == pwd || p[-1] != '\n') {
if (noerror) {
INTON;
return;
}
error("pwd command failed");
}
p[-1] = '\0';
INTON;
curdir = savestr(pwd);
stunalloc(pwd);
return;
}
#endif
}