11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1991, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD$");
401556Srgrimes
4117987Speter#include <sys/types.h>
4217987Speter#include <sys/stat.h>
4317987Speter#include <stdlib.h>
4420425Ssteve#include <string.h>
4517987Speter#include <unistd.h>
4617987Speter#include <errno.h>
47100661Stjr#include <limits.h>
4817987Speter
491556Srgrimes/*
501556Srgrimes * The cd and pwd commands.
511556Srgrimes */
521556Srgrimes
531556Srgrimes#include "shell.h"
541556Srgrimes#include "var.h"
551556Srgrimes#include "nodes.h"	/* for jobs.h */
561556Srgrimes#include "jobs.h"
571556Srgrimes#include "options.h"
581556Srgrimes#include "output.h"
591556Srgrimes#include "memalloc.h"
601556Srgrimes#include "error.h"
6120425Ssteve#include "exec.h"
6217987Speter#include "redir.h"
631556Srgrimes#include "mystring.h"
6417987Speter#include "show.h"
6520425Ssteve#include "cd.h"
66223060Sjilles#include "builtins.h"
671556Srgrimes
68213811Sobrienstatic int cdlogical(char *);
69213811Sobrienstatic int cdphysical(char *);
70213811Sobrienstatic int docd(char *, int, int);
71213811Sobrienstatic char *getcomponent(void);
72213811Sobrienstatic char *findcwd(char *);
73213811Sobrienstatic void updatepwd(char *);
74213811Sobrienstatic char *getpwd(void);
75213811Sobrienstatic char *getpwd2(void);
761556Srgrimes
77213760Sobrienstatic char *curdir = NULL;	/* current working directory */
78213760Sobrienstatic char *prevdir;		/* previous working directory */
79213760Sobrienstatic char *cdcomppath;
801556Srgrimes
811556Srgrimesint
82240541Sjillescdcmd(int argc __unused, char **argv __unused)
8317987Speter{
84201053Sjilles	const char *dest;
85200956Sjilles	const char *path;
861556Srgrimes	char *p;
871556Srgrimes	struct stat statb;
88222154Sjilles	int ch, phys, print = 0, getcwderr = 0;
89222154Sjilles	int rc;
90222292Sjilles	int errno1 = ENOENT;
911556Srgrimes
92100664Stjr	phys = Pflag;
93240541Sjilles	while ((ch = nextopt("eLP")) != '\0') {
9497092Stjr		switch (ch) {
95222154Sjilles		case 'e':
96222154Sjilles			getcwderr = 1;
97222154Sjilles			break;
9897092Stjr		case 'L':
9997092Stjr			phys = 0;
10097092Stjr			break;
10197092Stjr		case 'P':
10297092Stjr			phys = 1;
10397092Stjr			break;
10497092Stjr		}
10597092Stjr	}
10697092Stjr
107240541Sjilles	if (*argptr != NULL && argptr[1] != NULL)
10897092Stjr		error("too many arguments");
10997092Stjr
110240541Sjilles	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
1111556Srgrimes		error("HOME not set");
1125234Sbde	if (*dest == '\0')
1135234Sbde		dest = ".";
1141556Srgrimes	if (dest[0] == '-' && dest[1] == '\0') {
1151556Srgrimes		dest = prevdir ? prevdir : curdir;
11612273Speter		if (dest)
11712273Speter			print = 1;
11812273Speter		else
11912273Speter			dest = ".";
1201556Srgrimes	}
121222381Sjilles	if (dest[0] == '/' ||
122222381Sjilles	    (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
123222381Sjilles	    (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
124222381Sjilles	    (path = bltinlookup("CDPATH", 1)) == NULL)
1251556Srgrimes		path = nullstr;
1261556Srgrimes	while ((p = padvance(&path, dest)) != NULL) {
127230095Sjilles		if (stat(p, &statb) < 0) {
128230095Sjilles			if (errno != ENOENT)
129230095Sjilles				errno1 = errno;
130230095Sjilles		} else if (!S_ISDIR(statb.st_mode))
131230095Sjilles			errno1 = ENOTDIR;
132230095Sjilles		else {
1331556Srgrimes			if (!print) {
1341556Srgrimes				/*
1351556Srgrimes				 * XXX - rethink
1361556Srgrimes				 */
13738886Stegge				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
138159551Sstefanf					print = strcmp(p + 2, dest);
139159551Sstefanf				else
140159551Sstefanf					print = strcmp(p, dest);
1411556Srgrimes			}
142222154Sjilles			rc = docd(p, print, phys);
143222154Sjilles			if (rc >= 0)
144222154Sjilles				return getcwderr ? rc : 0;
145222292Sjilles			if (errno != ENOENT)
146222292Sjilles				errno1 = errno;
1471556Srgrimes		}
1481556Srgrimes	}
149222292Sjilles	error("%s: %s", dest, strerror(errno1));
15017987Speter	/*NOTREACHED*/
15117987Speter	return 0;
1521556Srgrimes}
1531556Srgrimes
1541556Srgrimes
1551556Srgrimes/*
15697092Stjr * Actually change the directory.  In an interactive shell, print the
15720774Ssteve * directory name if "print" is nonzero.
1581556Srgrimes */
159213811Sobrienstatic int
16097092Stjrdocd(char *dest, int print, int phys)
16120425Ssteve{
162222154Sjilles	int rc;
16397092Stjr
16497092Stjr	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
16597092Stjr
16697092Stjr	/* If logical cd fails, fall back to physical. */
167222154Sjilles	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
16897092Stjr		return (-1);
16997092Stjr
17097092Stjr	if (print && iflag && curdir)
17197092Stjr		out1fmt("%s\n", curdir);
17297092Stjr
173222154Sjilles	return (rc);
17497092Stjr}
17597092Stjr
176213811Sobrienstatic int
17797092Stjrcdlogical(char *dest)
17897092Stjr{
17938886Stegge	char *p;
18038886Stegge	char *q;
18138886Stegge	char *component;
18238886Stegge	struct stat statb;
18338886Stegge	int first;
18438886Stegge	int badstat;
185262951Sjmmv	size_t len;
18620425Ssteve
18738886Stegge	/*
18838886Stegge	 *  Check each component of the path. If we find a symlink or
18938886Stegge	 *  something we can't stat, clear curdir to force a getcwd()
19038886Stegge	 *  next time we get the value of the current directory.
19138886Stegge	 */
19238886Stegge	badstat = 0;
193262951Sjmmv	len = strlen(dest);
194262951Sjmmv	cdcomppath = stalloc(len + 1);
195262951Sjmmv	memcpy(cdcomppath, dest, len + 1);
19638886Stegge	STARTSTACKSTR(p);
19738886Stegge	if (*dest == '/') {
19838886Stegge		STPUTC('/', p);
19938886Stegge		cdcomppath++;
20038886Stegge	}
20138886Stegge	first = 1;
20238886Stegge	while ((q = getcomponent()) != NULL) {
20338886Stegge		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
20438886Stegge			continue;
20538886Stegge		if (! first)
20638886Stegge			STPUTC('/', p);
20738886Stegge		first = 0;
20838886Stegge		component = q;
209215783Sjilles		STPUTS(q, p);
21038886Stegge		if (equal(component, ".."))
21138886Stegge			continue;
21238886Stegge		STACKSTRNUL(p);
21397092Stjr		if (lstat(stackblock(), &statb) < 0) {
21438886Stegge			badstat = 1;
21538886Stegge			break;
21638886Stegge		}
21738886Stegge	}
21838886Stegge
2191556Srgrimes	INTOFF;
220176521Sstefanf	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
2211556Srgrimes		INTON;
22297092Stjr		return (-1);
2231556Srgrimes	}
224176521Sstefanf	updatepwd(p);
2251556Srgrimes	INTON;
22697092Stjr	return (0);
2271556Srgrimes}
2281556Srgrimes
229213811Sobrienstatic int
23097092Stjrcdphysical(char *dest)
23197092Stjr{
232176521Sstefanf	char *p;
233222154Sjilles	int rc = 0;
2341556Srgrimes
23597092Stjr	INTOFF;
236215727Sjilles	if (chdir(dest) < 0) {
23797092Stjr		INTON;
23897092Stjr		return (-1);
23997092Stjr	}
240215727Sjilles	p = findcwd(NULL);
241222154Sjilles	if (p == NULL) {
242216622Sjilles		warning("warning: failed to get name of current directory");
243222154Sjilles		rc = 1;
244222154Sjilles	}
245176521Sstefanf	updatepwd(p);
24697092Stjr	INTON;
247222154Sjilles	return (rc);
24897092Stjr}
24997092Stjr
2501556Srgrimes/*
2511556Srgrimes * Get the next component of the path name pointed to by cdcomppath.
2521556Srgrimes * This routine overwrites the string pointed to by cdcomppath.
2531556Srgrimes */
254213811Sobrienstatic char *
25590111Simpgetcomponent(void)
25620774Ssteve{
25725222Ssteve	char *p;
2581556Srgrimes	char *start;
2591556Srgrimes
2601556Srgrimes	if ((p = cdcomppath) == NULL)
2611556Srgrimes		return NULL;
2621556Srgrimes	start = cdcomppath;
2631556Srgrimes	while (*p != '/' && *p != '\0')
2641556Srgrimes		p++;
2651556Srgrimes	if (*p == '\0') {
2661556Srgrimes		cdcomppath = NULL;
2671556Srgrimes	} else {
2681556Srgrimes		*p++ = '\0';
2691556Srgrimes		cdcomppath = p;
2701556Srgrimes	}
2711556Srgrimes	return start;
2721556Srgrimes}
2731556Srgrimes
2741556Srgrimes
275213811Sobrienstatic char *
276176521Sstefanffindcwd(char *dir)
27720774Ssteve{
2781556Srgrimes	char *new;
2791556Srgrimes	char *p;
280262951Sjmmv	size_t len;
2811556Srgrimes
28238886Stegge	/*
28338886Stegge	 * If our argument is NULL, we don't know the current directory
28438886Stegge	 * any more because we traversed a symbolic link or something
28538886Stegge	 * we couldn't stat().
28638886Stegge	 */
287199631Sstefanf	if (dir == NULL || curdir == NULL)
288199631Sstefanf		return getpwd2();
289262951Sjmmv	len = strlen(dir);
290262951Sjmmv	cdcomppath = stalloc(len + 1);
291262951Sjmmv	memcpy(cdcomppath, dir, len + 1);
2921556Srgrimes	STARTSTACKSTR(new);
2931556Srgrimes	if (*dir != '/') {
294215783Sjilles		STPUTS(curdir, new);
295215783Sjilles		if (STTOPC(new) == '/')
2961556Srgrimes			STUNPUTC(new);
2971556Srgrimes	}
2981556Srgrimes	while ((p = getcomponent()) != NULL) {
2991556Srgrimes		if (equal(p, "..")) {
3001556Srgrimes			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
3011556Srgrimes		} else if (*p != '\0' && ! equal(p, ".")) {
3021556Srgrimes			STPUTC('/', new);
303215783Sjilles			STPUTS(p, new);
3041556Srgrimes		}
3051556Srgrimes	}
3061556Srgrimes	if (new == stackblock())
3071556Srgrimes		STPUTC('/', new);
3081556Srgrimes	STACKSTRNUL(new);
309176521Sstefanf	return stackblock();
310176521Sstefanf}
311176521Sstefanf
312176521Sstefanf/*
313176521Sstefanf * Update curdir (the name of the current directory) in response to a
314176521Sstefanf * cd command.  We also call hashcd to let the routines in exec.c know
315176521Sstefanf * that the current directory has changed.
316176521Sstefanf */
317213811Sobrienstatic void
318176521Sstefanfupdatepwd(char *dir)
319176521Sstefanf{
320176521Sstefanf	hashcd();				/* update command hash table */
321176521Sstefanf
32238886Stegge	if (prevdir)
32338886Stegge		ckfree(prevdir);
32438886Stegge	prevdir = curdir;
325215727Sjilles	curdir = dir ? savestr(dir) : NULL;
32686176Stegge	setvar("PWD", curdir, VEXPORT);
32786176Stegge	setvar("OLDPWD", prevdir, VEXPORT);
3281556Srgrimes}
3291556Srgrimes
3301556Srgrimesint
331240541Sjillespwdcmd(int argc __unused, char **argv __unused)
33217987Speter{
333199631Sstefanf	char *p;
33497092Stjr	int ch, phys;
3351556Srgrimes
336100664Stjr	phys = Pflag;
337240541Sjilles	while ((ch = nextopt("LP")) != '\0') {
33897092Stjr		switch (ch) {
33997092Stjr		case 'L':
34097092Stjr			phys = 0;
34197092Stjr			break;
34297092Stjr		case 'P':
34397092Stjr			phys = 1;
34497092Stjr			break;
34597092Stjr		}
34697092Stjr	}
3471556Srgrimes
348240541Sjilles	if (*argptr != NULL)
34997092Stjr		error("too many arguments");
35038886Stegge
35197092Stjr	if (!phys && getpwd()) {
35297092Stjr		out1str(curdir);
35397092Stjr		out1c('\n');
35497092Stjr	} else {
355199631Sstefanf		if ((p = getpwd2()) == NULL)
35697092Stjr			error(".: %s", strerror(errno));
357199631Sstefanf		out1str(p);
35897092Stjr		out1c('\n');
35997092Stjr	}
36038886Stegge
36197092Stjr	return 0;
36297092Stjr}
36338886Stegge
3641556Srgrimes/*
365176521Sstefanf * Get the current directory and cache the result in curdir.
3661556Srgrimes */
367213811Sobrienstatic char *
36890111Simpgetpwd(void)
36920425Ssteve{
370176521Sstefanf	char *p;
37138886Stegge
3721556Srgrimes	if (curdir)
37338886Stegge		return curdir;
374176521Sstefanf
375199631Sstefanf	p = getpwd2();
376176521Sstefanf	if (p != NULL)
377176521Sstefanf		curdir = savestr(p);
378176521Sstefanf
379176521Sstefanf	return curdir;
380176521Sstefanf}
381176521Sstefanf
382199631Sstefanf#define MAXPWD 256
383199631Sstefanf
384176521Sstefanf/*
385176521Sstefanf * Return the current directory.
386176521Sstefanf */
387213811Sobrienstatic char *
388199631Sstefanfgetpwd2(void)
389176521Sstefanf{
390199631Sstefanf	char *pwd;
391199631Sstefanf	int i;
39238886Stegge
393199631Sstefanf	for (i = MAXPWD;; i *= 2) {
394199631Sstefanf		pwd = stalloc(i);
395199631Sstefanf		if (getcwd(pwd, i) != NULL)
396176521Sstefanf			return pwd;
397199631Sstefanf		stunalloc(pwd);
398199631Sstefanf		if (errno != ERANGE)
399199631Sstefanf			break;
40038886Stegge	}
401199631Sstefanf
402206759Sjilles	return NULL;
403206759Sjilles}
404206759Sjilles
405206759Sjilles/*
406206759Sjilles * Initialize PWD in a new shell.
407206759Sjilles * If the shell is interactive, we need to warn if this fails.
408206759Sjilles */
409206759Sjillesvoid
410206759Sjillespwd_init(int warn)
411206759Sjilles{
412206759Sjilles	char *pwd;
413206759Sjilles	struct stat stdot, stpwd;
414206759Sjilles
415206759Sjilles	pwd = lookupvar("PWD");
416199631Sstefanf	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
417199631Sstefanf	    stat(pwd, &stpwd) != -1 &&
418199631Sstefanf	    stdot.st_dev == stpwd.st_dev &&
419199631Sstefanf	    stdot.st_ino == stpwd.st_ino) {
420206759Sjilles		if (curdir)
421206759Sjilles			ckfree(curdir);
422206759Sjilles		curdir = savestr(pwd);
423199631Sstefanf	}
424206759Sjilles	if (getpwd() == NULL && warn)
425206759Sjilles		out2fmt_flush("sh: cannot determine working directory\n");
426206759Sjilles	setvar("PWD", curdir, VEXPORT);
4271556Srgrimes}
428