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);
71294667Sjillesstatic char *getcomponent(char **);
72213811Sobrienstatic char *findcwd(char *);
73213811Sobrienstatic void updatepwd(char *);
74213811Sobrienstatic char *getpwd(void);
75213811Sobrienstatic char *getpwd2(void);
761556Srgrimes
77213760Sobrienstatic char *curdir = NULL;	/* current working directory */
781556Srgrimes
791556Srgrimesint
80240541Sjillescdcmd(int argc __unused, char **argv __unused)
8117987Speter{
82201053Sjilles	const char *dest;
83200956Sjilles	const char *path;
841556Srgrimes	char *p;
851556Srgrimes	struct stat statb;
86222154Sjilles	int ch, phys, print = 0, getcwderr = 0;
87222154Sjilles	int rc;
88222292Sjilles	int errno1 = ENOENT;
891556Srgrimes
90100664Stjr	phys = Pflag;
91240541Sjilles	while ((ch = nextopt("eLP")) != '\0') {
9297092Stjr		switch (ch) {
93222154Sjilles		case 'e':
94222154Sjilles			getcwderr = 1;
95222154Sjilles			break;
9697092Stjr		case 'L':
9797092Stjr			phys = 0;
9897092Stjr			break;
9997092Stjr		case 'P':
10097092Stjr			phys = 1;
10197092Stjr			break;
10297092Stjr		}
10397092Stjr	}
10497092Stjr
105240541Sjilles	if (*argptr != NULL && argptr[1] != NULL)
10697092Stjr		error("too many arguments");
10797092Stjr
108240541Sjilles	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
1091556Srgrimes		error("HOME not set");
1105234Sbde	if (*dest == '\0')
1115234Sbde		dest = ".";
1121556Srgrimes	if (dest[0] == '-' && dest[1] == '\0') {
113294649Sjilles		dest = bltinlookup("OLDPWD", 1);
114294649Sjilles		if (dest == NULL)
115294649Sjilles			error("OLDPWD not set");
116294649Sjilles		print = 1;
1171556Srgrimes	}
118222381Sjilles	if (dest[0] == '/' ||
119222381Sjilles	    (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
120222381Sjilles	    (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
121222381Sjilles	    (path = bltinlookup("CDPATH", 1)) == NULL)
122278820Sjilles		path = "";
1231556Srgrimes	while ((p = padvance(&path, dest)) != NULL) {
124230095Sjilles		if (stat(p, &statb) < 0) {
125230095Sjilles			if (errno != ENOENT)
126230095Sjilles				errno1 = errno;
127230095Sjilles		} else if (!S_ISDIR(statb.st_mode))
128230095Sjilles			errno1 = ENOTDIR;
129230095Sjilles		else {
1301556Srgrimes			if (!print) {
1311556Srgrimes				/*
1321556Srgrimes				 * XXX - rethink
1331556Srgrimes				 */
13438886Stegge				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
135159551Sstefanf					print = strcmp(p + 2, dest);
136159551Sstefanf				else
137159551Sstefanf					print = strcmp(p, dest);
1381556Srgrimes			}
139222154Sjilles			rc = docd(p, print, phys);
140222154Sjilles			if (rc >= 0)
141222154Sjilles				return getcwderr ? rc : 0;
142222292Sjilles			if (errno != ENOENT)
143222292Sjilles				errno1 = errno;
1441556Srgrimes		}
1451556Srgrimes	}
146222292Sjilles	error("%s: %s", dest, strerror(errno1));
14717987Speter	/*NOTREACHED*/
14817987Speter	return 0;
1491556Srgrimes}
1501556Srgrimes
1511556Srgrimes
1521556Srgrimes/*
15397092Stjr * Actually change the directory.  In an interactive shell, print the
15420774Ssteve * directory name if "print" is nonzero.
1551556Srgrimes */
156213811Sobrienstatic int
15797092Stjrdocd(char *dest, int print, int phys)
15820425Ssteve{
159222154Sjilles	int rc;
16097092Stjr
16197092Stjr	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
16297092Stjr
16397092Stjr	/* If logical cd fails, fall back to physical. */
164222154Sjilles	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
16597092Stjr		return (-1);
16697092Stjr
16797092Stjr	if (print && iflag && curdir)
16897092Stjr		out1fmt("%s\n", curdir);
16997092Stjr
170222154Sjilles	return (rc);
17197092Stjr}
17297092Stjr
173213811Sobrienstatic int
17497092Stjrcdlogical(char *dest)
17597092Stjr{
17638886Stegge	char *p;
17738886Stegge	char *q;
17838886Stegge	char *component;
179294667Sjilles	char *path;
18038886Stegge	struct stat statb;
18138886Stegge	int first;
18238886Stegge	int badstat;
18320425Ssteve
18438886Stegge	/*
18538886Stegge	 *  Check each component of the path. If we find a symlink or
18638886Stegge	 *  something we can't stat, clear curdir to force a getcwd()
18738886Stegge	 *  next time we get the value of the current directory.
18838886Stegge	 */
18938886Stegge	badstat = 0;
190294667Sjilles	path = stsavestr(dest);
19138886Stegge	STARTSTACKSTR(p);
19238886Stegge	if (*dest == '/') {
19338886Stegge		STPUTC('/', p);
194294667Sjilles		path++;
19538886Stegge	}
19638886Stegge	first = 1;
197294667Sjilles	while ((q = getcomponent(&path)) != NULL) {
19838886Stegge		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
19938886Stegge			continue;
20038886Stegge		if (! first)
20138886Stegge			STPUTC('/', p);
20238886Stegge		first = 0;
20338886Stegge		component = q;
204215783Sjilles		STPUTS(q, p);
20538886Stegge		if (equal(component, ".."))
20638886Stegge			continue;
20738886Stegge		STACKSTRNUL(p);
20897092Stjr		if (lstat(stackblock(), &statb) < 0) {
20938886Stegge			badstat = 1;
21038886Stegge			break;
21138886Stegge		}
21238886Stegge	}
21338886Stegge
2141556Srgrimes	INTOFF;
215176521Sstefanf	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
2161556Srgrimes		INTON;
21797092Stjr		return (-1);
2181556Srgrimes	}
219176521Sstefanf	updatepwd(p);
2201556Srgrimes	INTON;
22197092Stjr	return (0);
2221556Srgrimes}
2231556Srgrimes
224213811Sobrienstatic int
22597092Stjrcdphysical(char *dest)
22697092Stjr{
227176521Sstefanf	char *p;
228222154Sjilles	int rc = 0;
2291556Srgrimes
23097092Stjr	INTOFF;
231215727Sjilles	if (chdir(dest) < 0) {
23297092Stjr		INTON;
23397092Stjr		return (-1);
23497092Stjr	}
235215727Sjilles	p = findcwd(NULL);
236222154Sjilles	if (p == NULL) {
237216622Sjilles		warning("warning: failed to get name of current directory");
238222154Sjilles		rc = 1;
239222154Sjilles	}
240176521Sstefanf	updatepwd(p);
24197092Stjr	INTON;
242222154Sjilles	return (rc);
24397092Stjr}
24497092Stjr
2451556Srgrimes/*
246294667Sjilles * Get the next component of the path name pointed to by *path.
247294667Sjilles * This routine overwrites *path and the string pointed to by it.
2481556Srgrimes */
249213811Sobrienstatic char *
250294667Sjillesgetcomponent(char **path)
25120774Ssteve{
25225222Ssteve	char *p;
2531556Srgrimes	char *start;
2541556Srgrimes
255294667Sjilles	if ((p = *path) == NULL)
2561556Srgrimes		return NULL;
257294667Sjilles	start = *path;
2581556Srgrimes	while (*p != '/' && *p != '\0')
2591556Srgrimes		p++;
2601556Srgrimes	if (*p == '\0') {
261294667Sjilles		*path = NULL;
2621556Srgrimes	} else {
2631556Srgrimes		*p++ = '\0';
264294667Sjilles		*path = p;
2651556Srgrimes	}
2661556Srgrimes	return start;
2671556Srgrimes}
2681556Srgrimes
2691556Srgrimes
270213811Sobrienstatic char *
271176521Sstefanffindcwd(char *dir)
27220774Ssteve{
2731556Srgrimes	char *new;
2741556Srgrimes	char *p;
275294667Sjilles	char *path;
2761556Srgrimes
27738886Stegge	/*
27838886Stegge	 * If our argument is NULL, we don't know the current directory
27938886Stegge	 * any more because we traversed a symbolic link or something
28038886Stegge	 * we couldn't stat().
28138886Stegge	 */
282199631Sstefanf	if (dir == NULL || curdir == NULL)
283199631Sstefanf		return getpwd2();
284294667Sjilles	path = stsavestr(dir);
2851556Srgrimes	STARTSTACKSTR(new);
2861556Srgrimes	if (*dir != '/') {
287215783Sjilles		STPUTS(curdir, new);
288215783Sjilles		if (STTOPC(new) == '/')
2891556Srgrimes			STUNPUTC(new);
2901556Srgrimes	}
291294667Sjilles	while ((p = getcomponent(&path)) != NULL) {
2921556Srgrimes		if (equal(p, "..")) {
2931556Srgrimes			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
2941556Srgrimes		} else if (*p != '\0' && ! equal(p, ".")) {
2951556Srgrimes			STPUTC('/', new);
296215783Sjilles			STPUTS(p, new);
2971556Srgrimes		}
2981556Srgrimes	}
2991556Srgrimes	if (new == stackblock())
3001556Srgrimes		STPUTC('/', new);
3011556Srgrimes	STACKSTRNUL(new);
302176521Sstefanf	return stackblock();
303176521Sstefanf}
304176521Sstefanf
305176521Sstefanf/*
306176521Sstefanf * Update curdir (the name of the current directory) in response to a
307176521Sstefanf * cd command.  We also call hashcd to let the routines in exec.c know
308176521Sstefanf * that the current directory has changed.
309176521Sstefanf */
310213811Sobrienstatic void
311176521Sstefanfupdatepwd(char *dir)
312176521Sstefanf{
313294649Sjilles	char *prevdir;
314294649Sjilles
315176521Sstefanf	hashcd();				/* update command hash table */
316176521Sstefanf
317294649Sjilles	setvar("PWD", dir, VEXPORT);
318294649Sjilles	setvar("OLDPWD", curdir, VEXPORT);
31938886Stegge	prevdir = curdir;
320215727Sjilles	curdir = dir ? savestr(dir) : NULL;
321294649Sjilles	ckfree(prevdir);
3221556Srgrimes}
3231556Srgrimes
3241556Srgrimesint
325240541Sjillespwdcmd(int argc __unused, char **argv __unused)
32617987Speter{
327199631Sstefanf	char *p;
32897092Stjr	int ch, phys;
3291556Srgrimes
330100664Stjr	phys = Pflag;
331240541Sjilles	while ((ch = nextopt("LP")) != '\0') {
33297092Stjr		switch (ch) {
33397092Stjr		case 'L':
33497092Stjr			phys = 0;
33597092Stjr			break;
33697092Stjr		case 'P':
33797092Stjr			phys = 1;
33897092Stjr			break;
33997092Stjr		}
34097092Stjr	}
3411556Srgrimes
342240541Sjilles	if (*argptr != NULL)
34397092Stjr		error("too many arguments");
34438886Stegge
34597092Stjr	if (!phys && getpwd()) {
34697092Stjr		out1str(curdir);
34797092Stjr		out1c('\n');
34897092Stjr	} else {
349199631Sstefanf		if ((p = getpwd2()) == NULL)
35097092Stjr			error(".: %s", strerror(errno));
351199631Sstefanf		out1str(p);
35297092Stjr		out1c('\n');
35397092Stjr	}
35438886Stegge
35597092Stjr	return 0;
35697092Stjr}
35738886Stegge
3581556Srgrimes/*
359176521Sstefanf * Get the current directory and cache the result in curdir.
3601556Srgrimes */
361213811Sobrienstatic char *
36290111Simpgetpwd(void)
36320425Ssteve{
364176521Sstefanf	char *p;
36538886Stegge
3661556Srgrimes	if (curdir)
36738886Stegge		return curdir;
368176521Sstefanf
369199631Sstefanf	p = getpwd2();
370176521Sstefanf	if (p != NULL)
371176521Sstefanf		curdir = savestr(p);
372176521Sstefanf
373176521Sstefanf	return curdir;
374176521Sstefanf}
375176521Sstefanf
376199631Sstefanf#define MAXPWD 256
377199631Sstefanf
378176521Sstefanf/*
379176521Sstefanf * Return the current directory.
380176521Sstefanf */
381213811Sobrienstatic char *
382199631Sstefanfgetpwd2(void)
383176521Sstefanf{
384199631Sstefanf	char *pwd;
385199631Sstefanf	int i;
38638886Stegge
387199631Sstefanf	for (i = MAXPWD;; i *= 2) {
388199631Sstefanf		pwd = stalloc(i);
389199631Sstefanf		if (getcwd(pwd, i) != NULL)
390176521Sstefanf			return pwd;
391199631Sstefanf		stunalloc(pwd);
392199631Sstefanf		if (errno != ERANGE)
393199631Sstefanf			break;
39438886Stegge	}
395199631Sstefanf
396206759Sjilles	return NULL;
397206759Sjilles}
398206759Sjilles
399206759Sjilles/*
400206759Sjilles * Initialize PWD in a new shell.
401206759Sjilles * If the shell is interactive, we need to warn if this fails.
402206759Sjilles */
403206759Sjillesvoid
404206759Sjillespwd_init(int warn)
405206759Sjilles{
406206759Sjilles	char *pwd;
407206759Sjilles	struct stat stdot, stpwd;
408206759Sjilles
409206759Sjilles	pwd = lookupvar("PWD");
410199631Sstefanf	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
411199631Sstefanf	    stat(pwd, &stpwd) != -1 &&
412199631Sstefanf	    stdot.st_dev == stpwd.st_dev &&
413199631Sstefanf	    stdot.st_ino == stpwd.st_ino) {
414206759Sjilles		if (curdir)
415206759Sjilles			ckfree(curdir);
416206759Sjilles		curdir = savestr(pwd);
417199631Sstefanf	}
418206759Sjilles	if (getpwd() == NULL && warn)
419206759Sjilles		out2fmt_flush("sh: cannot determine working directory\n");
420206759Sjilles	setvar("PWD", curdir, VEXPORT);
4211556Srgrimes}
422