cd.c revision 222154
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 222154 2011-05-20 22:55:18Z 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"
661556Srgrimes
67213811Sobrienstatic int cdlogical(char *);
68213811Sobrienstatic int cdphysical(char *);
69213811Sobrienstatic int docd(char *, int, int);
70213811Sobrienstatic char *getcomponent(void);
71213811Sobrienstatic char *findcwd(char *);
72213811Sobrienstatic void updatepwd(char *);
73213811Sobrienstatic char *getpwd(void);
74213811Sobrienstatic char *getpwd2(void);
751556Srgrimes
76213760Sobrienstatic char *curdir = NULL;	/* current working directory */
77213760Sobrienstatic char *prevdir;		/* previous working directory */
78213760Sobrienstatic char *cdcomppath;
791556Srgrimes
801556Srgrimesint
8197092Stjrcdcmd(int argc, char **argv)
8217987Speter{
83201053Sjilles	const char *dest;
84200956Sjilles	const char *path;
851556Srgrimes	char *p;
861556Srgrimes	struct stat statb;
87222154Sjilles	int ch, phys, print = 0, getcwderr = 0;
88222154Sjilles	int rc;
891556Srgrimes
90100663Stjr	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
91100664Stjr	phys = Pflag;
92222154Sjilles	while ((ch = getopt(argc, argv, "eLP")) != -1) {
9397092Stjr		switch (ch) {
94222154Sjilles		case 'e':
95222154Sjilles			getcwderr = 1;
96222154Sjilles			break;
9797092Stjr		case 'L':
9897092Stjr			phys = 0;
9997092Stjr			break;
10097092Stjr		case 'P':
10197092Stjr			phys = 1;
10297092Stjr			break;
10397092Stjr		default:
10497092Stjr			error("unknown option: -%c", optopt);
10597092Stjr			break;
10697092Stjr		}
10797092Stjr	}
10897092Stjr	argc -= optind;
10997092Stjr	argv += optind;
11097092Stjr
11197092Stjr	if (argc > 1)
11297092Stjr		error("too many arguments");
11397092Stjr
11497092Stjr	if ((dest = *argv) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
1151556Srgrimes		error("HOME not set");
1165234Sbde	if (*dest == '\0')
1175234Sbde		dest = ".";
1181556Srgrimes	if (dest[0] == '-' && dest[1] == '\0') {
1191556Srgrimes		dest = prevdir ? prevdir : curdir;
12012273Speter		if (dest)
12112273Speter			print = 1;
12212273Speter		else
12312273Speter			dest = ".";
1241556Srgrimes	}
1251556Srgrimes	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
1261556Srgrimes		path = nullstr;
1271556Srgrimes	while ((p = padvance(&path, dest)) != NULL) {
12817987Speter		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1291556Srgrimes			if (!print) {
1301556Srgrimes				/*
1311556Srgrimes				 * XXX - rethink
1321556Srgrimes				 */
13338886Stegge				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
134159551Sstefanf					print = strcmp(p + 2, dest);
135159551Sstefanf				else
136159551Sstefanf					print = strcmp(p, dest);
1371556Srgrimes			}
138222154Sjilles			rc = docd(p, print, phys);
139222154Sjilles			if (rc >= 0)
140222154Sjilles				return getcwderr ? rc : 0;
1411556Srgrimes		}
1421556Srgrimes	}
1431556Srgrimes	error("can't cd to %s", dest);
14417987Speter	/*NOTREACHED*/
14517987Speter	return 0;
1461556Srgrimes}
1471556Srgrimes
1481556Srgrimes
1491556Srgrimes/*
15097092Stjr * Actually change the directory.  In an interactive shell, print the
15120774Ssteve * directory name if "print" is nonzero.
1521556Srgrimes */
153213811Sobrienstatic int
15497092Stjrdocd(char *dest, int print, int phys)
15520425Ssteve{
156222154Sjilles	int rc;
15797092Stjr
15897092Stjr	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
15997092Stjr
16097092Stjr	/* If logical cd fails, fall back to physical. */
161222154Sjilles	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
16297092Stjr		return (-1);
16397092Stjr
16497092Stjr	if (print && iflag && curdir)
16597092Stjr		out1fmt("%s\n", curdir);
16697092Stjr
167222154Sjilles	return (rc);
16897092Stjr}
16997092Stjr
170213811Sobrienstatic int
17197092Stjrcdlogical(char *dest)
17297092Stjr{
17338886Stegge	char *p;
17438886Stegge	char *q;
17538886Stegge	char *component;
17638886Stegge	struct stat statb;
17738886Stegge	int first;
17838886Stegge	int badstat;
17920425Ssteve
18038886Stegge	/*
18138886Stegge	 *  Check each component of the path. If we find a symlink or
18238886Stegge	 *  something we can't stat, clear curdir to force a getcwd()
18338886Stegge	 *  next time we get the value of the current directory.
18438886Stegge	 */
18538886Stegge	badstat = 0;
18638886Stegge	cdcomppath = stalloc(strlen(dest) + 1);
18738886Stegge	scopy(dest, cdcomppath);
18838886Stegge	STARTSTACKSTR(p);
18938886Stegge	if (*dest == '/') {
19038886Stegge		STPUTC('/', p);
19138886Stegge		cdcomppath++;
19238886Stegge	}
19338886Stegge	first = 1;
19438886Stegge	while ((q = getcomponent()) != NULL) {
19538886Stegge		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
19638886Stegge			continue;
19738886Stegge		if (! first)
19838886Stegge			STPUTC('/', p);
19938886Stegge		first = 0;
20038886Stegge		component = q;
201215783Sjilles		STPUTS(q, p);
20238886Stegge		if (equal(component, ".."))
20338886Stegge			continue;
20438886Stegge		STACKSTRNUL(p);
20597092Stjr		if (lstat(stackblock(), &statb) < 0) {
20638886Stegge			badstat = 1;
20738886Stegge			break;
20838886Stegge		}
20938886Stegge	}
21038886Stegge
2111556Srgrimes	INTOFF;
212176521Sstefanf	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
2131556Srgrimes		INTON;
21497092Stjr		return (-1);
2151556Srgrimes	}
216176521Sstefanf	updatepwd(p);
2171556Srgrimes	INTON;
21897092Stjr	return (0);
2191556Srgrimes}
2201556Srgrimes
221213811Sobrienstatic int
22297092Stjrcdphysical(char *dest)
22397092Stjr{
224176521Sstefanf	char *p;
225222154Sjilles	int rc = 0;
2261556Srgrimes
22797092Stjr	INTOFF;
228215727Sjilles	if (chdir(dest) < 0) {
22997092Stjr		INTON;
23097092Stjr		return (-1);
23197092Stjr	}
232215727Sjilles	p = findcwd(NULL);
233222154Sjilles	if (p == NULL) {
234216622Sjilles		warning("warning: failed to get name of current directory");
235222154Sjilles		rc = 1;
236222154Sjilles	}
237176521Sstefanf	updatepwd(p);
23897092Stjr	INTON;
239222154Sjilles	return (rc);
24097092Stjr}
24197092Stjr
2421556Srgrimes/*
2431556Srgrimes * Get the next component of the path name pointed to by cdcomppath.
2441556Srgrimes * This routine overwrites the string pointed to by cdcomppath.
2451556Srgrimes */
246213811Sobrienstatic char *
24790111Simpgetcomponent(void)
24820774Ssteve{
24925222Ssteve	char *p;
2501556Srgrimes	char *start;
2511556Srgrimes
2521556Srgrimes	if ((p = cdcomppath) == NULL)
2531556Srgrimes		return NULL;
2541556Srgrimes	start = cdcomppath;
2551556Srgrimes	while (*p != '/' && *p != '\0')
2561556Srgrimes		p++;
2571556Srgrimes	if (*p == '\0') {
2581556Srgrimes		cdcomppath = NULL;
2591556Srgrimes	} else {
2601556Srgrimes		*p++ = '\0';
2611556Srgrimes		cdcomppath = p;
2621556Srgrimes	}
2631556Srgrimes	return start;
2641556Srgrimes}
2651556Srgrimes
2661556Srgrimes
267213811Sobrienstatic char *
268176521Sstefanffindcwd(char *dir)
26920774Ssteve{
2701556Srgrimes	char *new;
2711556Srgrimes	char *p;
2721556Srgrimes
27338886Stegge	/*
27438886Stegge	 * If our argument is NULL, we don't know the current directory
27538886Stegge	 * any more because we traversed a symbolic link or something
27638886Stegge	 * we couldn't stat().
27738886Stegge	 */
278199631Sstefanf	if (dir == NULL || curdir == NULL)
279199631Sstefanf		return getpwd2();
2801556Srgrimes	cdcomppath = stalloc(strlen(dir) + 1);
2811556Srgrimes	scopy(dir, cdcomppath);
2821556Srgrimes	STARTSTACKSTR(new);
2831556Srgrimes	if (*dir != '/') {
284215783Sjilles		STPUTS(curdir, new);
285215783Sjilles		if (STTOPC(new) == '/')
2861556Srgrimes			STUNPUTC(new);
2871556Srgrimes	}
2881556Srgrimes	while ((p = getcomponent()) != NULL) {
2891556Srgrimes		if (equal(p, "..")) {
2901556Srgrimes			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
2911556Srgrimes		} else if (*p != '\0' && ! equal(p, ".")) {
2921556Srgrimes			STPUTC('/', new);
293215783Sjilles			STPUTS(p, new);
2941556Srgrimes		}
2951556Srgrimes	}
2961556Srgrimes	if (new == stackblock())
2971556Srgrimes		STPUTC('/', new);
2981556Srgrimes	STACKSTRNUL(new);
299176521Sstefanf	return stackblock();
300176521Sstefanf}
301176521Sstefanf
302176521Sstefanf/*
303176521Sstefanf * Update curdir (the name of the current directory) in response to a
304176521Sstefanf * cd command.  We also call hashcd to let the routines in exec.c know
305176521Sstefanf * that the current directory has changed.
306176521Sstefanf */
307213811Sobrienstatic void
308176521Sstefanfupdatepwd(char *dir)
309176521Sstefanf{
310176521Sstefanf	hashcd();				/* update command hash table */
311176521Sstefanf
31238886Stegge	if (prevdir)
31338886Stegge		ckfree(prevdir);
31438886Stegge	prevdir = curdir;
315215727Sjilles	curdir = dir ? savestr(dir) : NULL;
31686176Stegge	setvar("PWD", curdir, VEXPORT);
31786176Stegge	setvar("OLDPWD", prevdir, VEXPORT);
3181556Srgrimes}
3191556Srgrimes
3201556Srgrimesint
321100660Stjrpwdcmd(int argc, char **argv)
32217987Speter{
323199631Sstefanf	char *p;
32497092Stjr	int ch, phys;
3251556Srgrimes
326100663Stjr	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
327100664Stjr	phys = Pflag;
32897092Stjr	while ((ch = getopt(argc, argv, "LP")) != -1) {
32997092Stjr		switch (ch) {
33097092Stjr		case 'L':
33197092Stjr			phys = 0;
33297092Stjr			break;
33397092Stjr		case 'P':
33497092Stjr			phys = 1;
33597092Stjr			break;
33697092Stjr		default:
33797092Stjr			error("unknown option: -%c", optopt);
33897092Stjr			break;
33997092Stjr		}
34097092Stjr	}
34197092Stjr	argc -= optind;
34297092Stjr	argv += optind;
3431556Srgrimes
34497092Stjr	if (argc != 0)
34597092Stjr		error("too many arguments");
34638886Stegge
34797092Stjr	if (!phys && getpwd()) {
34897092Stjr		out1str(curdir);
34997092Stjr		out1c('\n');
35097092Stjr	} else {
351199631Sstefanf		if ((p = getpwd2()) == NULL)
35297092Stjr			error(".: %s", strerror(errno));
353199631Sstefanf		out1str(p);
35497092Stjr		out1c('\n');
35597092Stjr	}
35638886Stegge
35797092Stjr	return 0;
35897092Stjr}
35938886Stegge
3601556Srgrimes/*
361176521Sstefanf * Get the current directory and cache the result in curdir.
3621556Srgrimes */
363213811Sobrienstatic char *
36490111Simpgetpwd(void)
36520425Ssteve{
366176521Sstefanf	char *p;
36738886Stegge
3681556Srgrimes	if (curdir)
36938886Stegge		return curdir;
370176521Sstefanf
371199631Sstefanf	p = getpwd2();
372176521Sstefanf	if (p != NULL)
373176521Sstefanf		curdir = savestr(p);
374176521Sstefanf
375176521Sstefanf	return curdir;
376176521Sstefanf}
377176521Sstefanf
378199631Sstefanf#define MAXPWD 256
379199631Sstefanf
380176521Sstefanf/*
381176521Sstefanf * Return the current directory.
382176521Sstefanf */
383213811Sobrienstatic char *
384199631Sstefanfgetpwd2(void)
385176521Sstefanf{
386199631Sstefanf	char *pwd;
387199631Sstefanf	int i;
38838886Stegge
389199631Sstefanf	for (i = MAXPWD;; i *= 2) {
390199631Sstefanf		pwd = stalloc(i);
391199631Sstefanf		if (getcwd(pwd, i) != NULL)
392176521Sstefanf			return pwd;
393199631Sstefanf		stunalloc(pwd);
394199631Sstefanf		if (errno != ERANGE)
395199631Sstefanf			break;
39638886Stegge	}
397199631Sstefanf
398206759Sjilles	return NULL;
399206759Sjilles}
400206759Sjilles
401206759Sjilles/*
402206759Sjilles * Initialize PWD in a new shell.
403206759Sjilles * If the shell is interactive, we need to warn if this fails.
404206759Sjilles */
405206759Sjillesvoid
406206759Sjillespwd_init(int warn)
407206759Sjilles{
408206759Sjilles	char *pwd;
409206759Sjilles	struct stat stdot, stpwd;
410206759Sjilles
411206759Sjilles	pwd = lookupvar("PWD");
412199631Sstefanf	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
413199631Sstefanf	    stat(pwd, &stpwd) != -1 &&
414199631Sstefanf	    stdot.st_dev == stpwd.st_dev &&
415199631Sstefanf	    stdot.st_ino == stpwd.st_ino) {
416206759Sjilles		if (curdir)
417206759Sjilles			ckfree(curdir);
418206759Sjilles		curdir = savestr(pwd);
419199631Sstefanf	}
420206759Sjilles	if (getpwd() == NULL && warn)
421206759Sjilles		out2fmt_flush("sh: cannot determine working directory\n");
422206759Sjilles	setvar("PWD", curdir, VEXPORT);
4231556Srgrimes}
424