cd.c revision 223060
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: head/bin/sh/cd.c 223060 2011-06-13 21:03:27Z jilles $");
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
8297092Stjrcdcmd(int argc, char **argv)
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
92100663Stjr	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
93100664Stjr	phys = Pflag;
94222154Sjilles	while ((ch = getopt(argc, argv, "eLP")) != -1) {
9597092Stjr		switch (ch) {
96222154Sjilles		case 'e':
97222154Sjilles			getcwderr = 1;
98222154Sjilles			break;
9997092Stjr		case 'L':
10097092Stjr			phys = 0;
10197092Stjr			break;
10297092Stjr		case 'P':
10397092Stjr			phys = 1;
10497092Stjr			break;
10597092Stjr		default:
10697092Stjr			error("unknown option: -%c", optopt);
10797092Stjr			break;
10897092Stjr		}
10997092Stjr	}
11097092Stjr	argc -= optind;
11197092Stjr	argv += optind;
11297092Stjr
11397092Stjr	if (argc > 1)
11497092Stjr		error("too many arguments");
11597092Stjr
11697092Stjr	if ((dest = *argv) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
1171556Srgrimes		error("HOME not set");
1185234Sbde	if (*dest == '\0')
1195234Sbde		dest = ".";
1201556Srgrimes	if (dest[0] == '-' && dest[1] == '\0') {
1211556Srgrimes		dest = prevdir ? prevdir : curdir;
12212273Speter		if (dest)
12312273Speter			print = 1;
12412273Speter		else
12512273Speter			dest = ".";
1261556Srgrimes	}
127222381Sjilles	if (dest[0] == '/' ||
128222381Sjilles	    (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
129222381Sjilles	    (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
130222381Sjilles	    (path = bltinlookup("CDPATH", 1)) == NULL)
1311556Srgrimes		path = nullstr;
1321556Srgrimes	while ((p = padvance(&path, dest)) != NULL) {
13317987Speter		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1341556Srgrimes			if (!print) {
1351556Srgrimes				/*
1361556Srgrimes				 * XXX - rethink
1371556Srgrimes				 */
13838886Stegge				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
139159551Sstefanf					print = strcmp(p + 2, dest);
140159551Sstefanf				else
141159551Sstefanf					print = strcmp(p, dest);
1421556Srgrimes			}
143222154Sjilles			rc = docd(p, print, phys);
144222154Sjilles			if (rc >= 0)
145222154Sjilles				return getcwderr ? rc : 0;
146222292Sjilles			if (errno != ENOENT)
147222292Sjilles				errno1 = errno;
1481556Srgrimes		}
1491556Srgrimes	}
150222292Sjilles	error("%s: %s", dest, strerror(errno1));
15117987Speter	/*NOTREACHED*/
15217987Speter	return 0;
1531556Srgrimes}
1541556Srgrimes
1551556Srgrimes
1561556Srgrimes/*
15797092Stjr * Actually change the directory.  In an interactive shell, print the
15820774Ssteve * directory name if "print" is nonzero.
1591556Srgrimes */
160213811Sobrienstatic int
16197092Stjrdocd(char *dest, int print, int phys)
16220425Ssteve{
163222154Sjilles	int rc;
16497092Stjr
16597092Stjr	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
16697092Stjr
16797092Stjr	/* If logical cd fails, fall back to physical. */
168222154Sjilles	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
16997092Stjr		return (-1);
17097092Stjr
17197092Stjr	if (print && iflag && curdir)
17297092Stjr		out1fmt("%s\n", curdir);
17397092Stjr
174222154Sjilles	return (rc);
17597092Stjr}
17697092Stjr
177213811Sobrienstatic int
17897092Stjrcdlogical(char *dest)
17997092Stjr{
18038886Stegge	char *p;
18138886Stegge	char *q;
18238886Stegge	char *component;
18338886Stegge	struct stat statb;
18438886Stegge	int first;
18538886Stegge	int badstat;
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;
19338886Stegge	cdcomppath = stalloc(strlen(dest) + 1);
19438886Stegge	scopy(dest, cdcomppath);
19538886Stegge	STARTSTACKSTR(p);
19638886Stegge	if (*dest == '/') {
19738886Stegge		STPUTC('/', p);
19838886Stegge		cdcomppath++;
19938886Stegge	}
20038886Stegge	first = 1;
20138886Stegge	while ((q = getcomponent()) != NULL) {
20238886Stegge		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
20338886Stegge			continue;
20438886Stegge		if (! first)
20538886Stegge			STPUTC('/', p);
20638886Stegge		first = 0;
20738886Stegge		component = q;
208215783Sjilles		STPUTS(q, p);
20938886Stegge		if (equal(component, ".."))
21038886Stegge			continue;
21138886Stegge		STACKSTRNUL(p);
21297092Stjr		if (lstat(stackblock(), &statb) < 0) {
21338886Stegge			badstat = 1;
21438886Stegge			break;
21538886Stegge		}
21638886Stegge	}
21738886Stegge
2181556Srgrimes	INTOFF;
219176521Sstefanf	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
2201556Srgrimes		INTON;
22197092Stjr		return (-1);
2221556Srgrimes	}
223176521Sstefanf	updatepwd(p);
2241556Srgrimes	INTON;
22597092Stjr	return (0);
2261556Srgrimes}
2271556Srgrimes
228213811Sobrienstatic int
22997092Stjrcdphysical(char *dest)
23097092Stjr{
231176521Sstefanf	char *p;
232222154Sjilles	int rc = 0;
2331556Srgrimes
23497092Stjr	INTOFF;
235215727Sjilles	if (chdir(dest) < 0) {
23697092Stjr		INTON;
23797092Stjr		return (-1);
23897092Stjr	}
239215727Sjilles	p = findcwd(NULL);
240222154Sjilles	if (p == NULL) {
241216622Sjilles		warning("warning: failed to get name of current directory");
242222154Sjilles		rc = 1;
243222154Sjilles	}
244176521Sstefanf	updatepwd(p);
24597092Stjr	INTON;
246222154Sjilles	return (rc);
24797092Stjr}
24897092Stjr
2491556Srgrimes/*
2501556Srgrimes * Get the next component of the path name pointed to by cdcomppath.
2511556Srgrimes * This routine overwrites the string pointed to by cdcomppath.
2521556Srgrimes */
253213811Sobrienstatic char *
25490111Simpgetcomponent(void)
25520774Ssteve{
25625222Ssteve	char *p;
2571556Srgrimes	char *start;
2581556Srgrimes
2591556Srgrimes	if ((p = cdcomppath) == NULL)
2601556Srgrimes		return NULL;
2611556Srgrimes	start = cdcomppath;
2621556Srgrimes	while (*p != '/' && *p != '\0')
2631556Srgrimes		p++;
2641556Srgrimes	if (*p == '\0') {
2651556Srgrimes		cdcomppath = NULL;
2661556Srgrimes	} else {
2671556Srgrimes		*p++ = '\0';
2681556Srgrimes		cdcomppath = p;
2691556Srgrimes	}
2701556Srgrimes	return start;
2711556Srgrimes}
2721556Srgrimes
2731556Srgrimes
274213811Sobrienstatic char *
275176521Sstefanffindcwd(char *dir)
27620774Ssteve{
2771556Srgrimes	char *new;
2781556Srgrimes	char *p;
2791556Srgrimes
28038886Stegge	/*
28138886Stegge	 * If our argument is NULL, we don't know the current directory
28238886Stegge	 * any more because we traversed a symbolic link or something
28338886Stegge	 * we couldn't stat().
28438886Stegge	 */
285199631Sstefanf	if (dir == NULL || curdir == NULL)
286199631Sstefanf		return getpwd2();
2871556Srgrimes	cdcomppath = stalloc(strlen(dir) + 1);
2881556Srgrimes	scopy(dir, cdcomppath);
2891556Srgrimes	STARTSTACKSTR(new);
2901556Srgrimes	if (*dir != '/') {
291215783Sjilles		STPUTS(curdir, new);
292215783Sjilles		if (STTOPC(new) == '/')
2931556Srgrimes			STUNPUTC(new);
2941556Srgrimes	}
2951556Srgrimes	while ((p = getcomponent()) != NULL) {
2961556Srgrimes		if (equal(p, "..")) {
2971556Srgrimes			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
2981556Srgrimes		} else if (*p != '\0' && ! equal(p, ".")) {
2991556Srgrimes			STPUTC('/', new);
300215783Sjilles			STPUTS(p, new);
3011556Srgrimes		}
3021556Srgrimes	}
3031556Srgrimes	if (new == stackblock())
3041556Srgrimes		STPUTC('/', new);
3051556Srgrimes	STACKSTRNUL(new);
306176521Sstefanf	return stackblock();
307176521Sstefanf}
308176521Sstefanf
309176521Sstefanf/*
310176521Sstefanf * Update curdir (the name of the current directory) in response to a
311176521Sstefanf * cd command.  We also call hashcd to let the routines in exec.c know
312176521Sstefanf * that the current directory has changed.
313176521Sstefanf */
314213811Sobrienstatic void
315176521Sstefanfupdatepwd(char *dir)
316176521Sstefanf{
317176521Sstefanf	hashcd();				/* update command hash table */
318176521Sstefanf
31938886Stegge	if (prevdir)
32038886Stegge		ckfree(prevdir);
32138886Stegge	prevdir = curdir;
322215727Sjilles	curdir = dir ? savestr(dir) : NULL;
32386176Stegge	setvar("PWD", curdir, VEXPORT);
32486176Stegge	setvar("OLDPWD", prevdir, VEXPORT);
3251556Srgrimes}
3261556Srgrimes
3271556Srgrimesint
328100660Stjrpwdcmd(int argc, char **argv)
32917987Speter{
330199631Sstefanf	char *p;
33197092Stjr	int ch, phys;
3321556Srgrimes
333100663Stjr	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
334100664Stjr	phys = Pflag;
33597092Stjr	while ((ch = getopt(argc, argv, "LP")) != -1) {
33697092Stjr		switch (ch) {
33797092Stjr		case 'L':
33897092Stjr			phys = 0;
33997092Stjr			break;
34097092Stjr		case 'P':
34197092Stjr			phys = 1;
34297092Stjr			break;
34397092Stjr		default:
34497092Stjr			error("unknown option: -%c", optopt);
34597092Stjr			break;
34697092Stjr		}
34797092Stjr	}
34897092Stjr	argc -= optind;
34997092Stjr	argv += optind;
3501556Srgrimes
35197092Stjr	if (argc != 0)
35297092Stjr		error("too many arguments");
35338886Stegge
35497092Stjr	if (!phys && getpwd()) {
35597092Stjr		out1str(curdir);
35697092Stjr		out1c('\n');
35797092Stjr	} else {
358199631Sstefanf		if ((p = getpwd2()) == NULL)
35997092Stjr			error(".: %s", strerror(errno));
360199631Sstefanf		out1str(p);
36197092Stjr		out1c('\n');
36297092Stjr	}
36338886Stegge
36497092Stjr	return 0;
36597092Stjr}
36638886Stegge
3671556Srgrimes/*
368176521Sstefanf * Get the current directory and cache the result in curdir.
3691556Srgrimes */
370213811Sobrienstatic char *
37190111Simpgetpwd(void)
37220425Ssteve{
373176521Sstefanf	char *p;
37438886Stegge
3751556Srgrimes	if (curdir)
37638886Stegge		return curdir;
377176521Sstefanf
378199631Sstefanf	p = getpwd2();
379176521Sstefanf	if (p != NULL)
380176521Sstefanf		curdir = savestr(p);
381176521Sstefanf
382176521Sstefanf	return curdir;
383176521Sstefanf}
384176521Sstefanf
385199631Sstefanf#define MAXPWD 256
386199631Sstefanf
387176521Sstefanf/*
388176521Sstefanf * Return the current directory.
389176521Sstefanf */
390213811Sobrienstatic char *
391199631Sstefanfgetpwd2(void)
392176521Sstefanf{
393199631Sstefanf	char *pwd;
394199631Sstefanf	int i;
39538886Stegge
396199631Sstefanf	for (i = MAXPWD;; i *= 2) {
397199631Sstefanf		pwd = stalloc(i);
398199631Sstefanf		if (getcwd(pwd, i) != NULL)
399176521Sstefanf			return pwd;
400199631Sstefanf		stunalloc(pwd);
401199631Sstefanf		if (errno != ERANGE)
402199631Sstefanf			break;
40338886Stegge	}
404199631Sstefanf
405206759Sjilles	return NULL;
406206759Sjilles}
407206759Sjilles
408206759Sjilles/*
409206759Sjilles * Initialize PWD in a new shell.
410206759Sjilles * If the shell is interactive, we need to warn if this fails.
411206759Sjilles */
412206759Sjillesvoid
413206759Sjillespwd_init(int warn)
414206759Sjilles{
415206759Sjilles	char *pwd;
416206759Sjilles	struct stat stdot, stpwd;
417206759Sjilles
418206759Sjilles	pwd = lookupvar("PWD");
419199631Sstefanf	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
420199631Sstefanf	    stat(pwd, &stpwd) != -1 &&
421199631Sstefanf	    stdot.st_dev == stpwd.st_dev &&
422199631Sstefanf	    stdot.st_ino == stpwd.st_ino) {
423206759Sjilles		if (curdir)
424206759Sjilles			ckfree(curdir);
425206759Sjilles		curdir = savestr(pwd);
426199631Sstefanf	}
427206759Sjilles	if (getpwd() == NULL && warn)
428206759Sjilles		out2fmt_flush("sh: cannot determine working directory\n");
429206759Sjilles	setvar("PWD", curdir, VEXPORT);
4301556Srgrimes}
431