cd.c revision 199631
167761Smsmith/*-
267761Smsmith * Copyright (c) 1991, 1993
367761Smsmith *	The Regents of the University of California.  All rights reserved.
467761Smsmith *
567761Smsmith * This code is derived from software contributed to Berkeley by
667761Smsmith * Kenneth Almquist.
767761Smsmith *
867761Smsmith * Redistribution and use in source and binary forms, with or without
967761Smsmith * modification, are permitted provided that the following conditions
1067761Smsmith * are met:
1167761Smsmith * 1. Redistributions of source code must retain the above copyright
1267761Smsmith *    notice, this list of conditions and the following disclaimer.
1367761Smsmith * 2. Redistributions in binary form must reproduce the above copyright
1467761Smsmith *    notice, this list of conditions and the following disclaimer in the
1567761Smsmith *    documentation and/or other materials provided with the distribution.
1667761Smsmith * 4. Neither the name of the University nor the names of its contributors
1767761Smsmith *    may be used to endorse or promote products derived from this software
1867761Smsmith *    without specific prior written permission.
1967761Smsmith *
2067761Smsmith * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2167761Smsmith * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2267761Smsmith * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2367761Smsmith * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2467761Smsmith * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2567761Smsmith * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2667761Smsmith * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2767761Smsmith * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2867761Smsmith * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2967761Smsmith * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30119418Sobrien * SUCH DAMAGE.
31119418Sobrien */
32119418Sobrien
3367761Smsmith#ifndef lint
3467761Smsmith#if 0
3567761Smsmithstatic char sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
36129879Sphk#endif
3767761Smsmith#endif /* not lint */
3874914Sjhb#include <sys/cdefs.h>
3967761Smsmith__FBSDID("$FreeBSD: head/bin/sh/cd.c 199631 2009-11-21 14:53:22Z stefanf $");
40193530Sjkim
41193530Sjkim#include <sys/types.h>
42193530Sjkim#include <sys/stat.h>
4367761Smsmith#include <stdlib.h>
4467761Smsmith#include <string.h>
45119529Snjl#include <unistd.h>
4677432Smsmith#include <errno.h>
4791123Smsmith#include <limits.h>
4869744Smsmith
4967761Smsmith/*
5067761Smsmith * The cd and pwd commands.
5167761Smsmith */
5267761Smsmith
5367761Smsmith#include "shell.h"
5467761Smsmith#include "var.h"
55133618Snjl#include "nodes.h"	/* for jobs.h */
56133618Snjl#include "jobs.h"
5767761Smsmith#include "options.h"
5867761Smsmith#include "output.h"
59100497Siwasaki#include "memalloc.h"
60100497Siwasaki#include "error.h"
6167761Smsmith#include "exec.h"
62121493Snjl#include "redir.h"
63121493Snjl#include "mystring.h"
6467761Smsmith#include "show.h"
6567761Smsmith#include "cd.h"
6667761Smsmith
6767761SmsmithSTATIC int cdlogical(char *);
6867761SmsmithSTATIC int cdphysical(char *);
69100497SiwasakiSTATIC int docd(char *, int, int);
70100497SiwasakiSTATIC char *getcomponent(void);
7167761SmsmithSTATIC char *findcwd(char *);
72246128SsbzSTATIC void updatepwd(char *);
7367761SmsmithSTATIC char *getpwd2(void);
7467761Smsmith
7567761SmsmithSTATIC char *curdir = NULL;	/* current working directory */
7667761SmsmithSTATIC char *prevdir;		/* previous working directory */
7767761SmsmithSTATIC char *cdcomppath;
7867761Smsmith
7967761Smsmithint
8067761Smsmithcdcmd(int argc, char **argv)
8189054Smsmith{
8267761Smsmith	char *dest;
83128071Snjl	char *path;
8467761Smsmith	char *p;
8567761Smsmith	struct stat statb;
8667761Smsmith	int ch, phys, print = 0;
8767761Smsmith
88131282Snjl	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
89119529Snjl	phys = Pflag;
90131282Snjl	while ((ch = getopt(argc, argv, "LP")) != -1) {
91131282Snjl		switch (ch) {
92131282Snjl		case 'L':
93131282Snjl			phys = 0;
94131282Snjl			break;
95131282Snjl		case 'P':
9667761Smsmith			phys = 1;
9767761Smsmith			break;
9867761Smsmith		default:
9967761Smsmith			error("unknown option: -%c", optopt);
10067761Smsmith			break;
101209746Sjkim		}
10267761Smsmith	}
10367761Smsmith	argc -= optind;
10496926Speter	argv += optind;
10569744Smsmith
10667761Smsmith	if (argc > 1)
10767761Smsmith		error("too many arguments");
10867761Smsmith
10967761Smsmith	if ((dest = *argv) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
110129692Snjl		error("HOME not set");
111129692Snjl	if (*dest == '\0')
112129692Snjl		dest = ".";
113129692Snjl	if (dest[0] == '-' && dest[1] == '\0') {
114129692Snjl		dest = prevdir ? prevdir : curdir;
115119529Snjl		if (dest)
116119529Snjl			print = 1;
117119529Snjl		else
118129783Snjl			dest = ".";
119129783Snjl	}
120209746Sjkim	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
121209746Sjkim		path = nullstr;
122129783Snjl	while ((p = padvance(&path, dest)) != NULL) {
123133618Snjl		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
12467761Smsmith			if (!print) {
12567761Smsmith				/*
126100497Siwasaki				 * XXX - rethink
127100497Siwasaki				 */
128100497Siwasaki				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
129100497Siwasaki					print = strcmp(p + 2, dest);
130100497Siwasaki				else
131100497Siwasaki					print = strcmp(p, dest);
132100497Siwasaki			}
133100497Siwasaki			if (docd(p, print, phys) >= 0)
134100497Siwasaki				return 0;
135100497Siwasaki		}
136100497Siwasaki	}
137100497Siwasaki	error("can't cd to %s", dest);
13867761Smsmith	/*NOTREACHED*/
13967761Smsmith	return 0;
14067761Smsmith}
14167761Smsmith
14267761Smsmith
143119529Snjl/*
14467761Smsmith * Actually change the directory.  In an interactive shell, print the
14596926Speter * directory name if "print" is nonzero.
14669744Smsmith */
14767761SmsmithSTATIC int
148134305Snjldocd(char *dest, int print, int phys)
14967761Smsmith{
15067761Smsmith
15171872Smsmith	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
15267761Smsmith
15367761Smsmith	/* If logical cd fails, fall back to physical. */
15467761Smsmith	if ((phys || cdlogical(dest) < 0) && cdphysical(dest) < 0)
155134305Snjl		return (-1);
156119529Snjl
157134305Snjl	if (print && iflag && curdir)
15867761Smsmith		out1fmt("%s\n", curdir);
159134305Snjl
160134305Snjl	return 0;
161134305Snjl}
16267761Smsmith
163134305SnjlSTATIC int
164134305Snjlcdlogical(char *dest)
16586552Siwasaki{
166134305Snjl	char *p;
167121493Snjl	char *q;
168134305Snjl	char *component;
169134305Snjl	struct stat statb;
170134305Snjl	int first;
171134305Snjl	int badstat;
172134305Snjl
173133618Snjl	/*
174133618Snjl	 *  Check each component of the path. If we find a symlink or
17569744Smsmith	 *  something we can't stat, clear curdir to force a getcwd()
17667761Smsmith	 *  next time we get the value of the current directory.
17767761Smsmith	 */
17867761Smsmith	badstat = 0;
17967761Smsmith	cdcomppath = stalloc(strlen(dest) + 1);
18067761Smsmith	scopy(dest, cdcomppath);
18167761Smsmith	STARTSTACKSTR(p);
18267761Smsmith	if (*dest == '/') {
18367761Smsmith		STPUTC('/', p);
184129692Snjl		cdcomppath++;
18567761Smsmith	}
18696926Speter	first = 1;
18769744Smsmith	while ((q = getcomponent()) != NULL) {
188129692Snjl		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
18967761Smsmith			continue;
19067761Smsmith		if (! first)
191167814Sjkim			STPUTC('/', p);
192167814Sjkim		first = 0;
19367761Smsmith		component = q;
19467761Smsmith		while (*q)
195129692Snjl			STPUTC(*q++, p);
196119529Snjl		if (equal(component, ".."))
19767761Smsmith			continue;
198119529Snjl		STACKSTRNUL(p);
19969744Smsmith		if (lstat(stackblock(), &statb) < 0) {
20067761Smsmith			badstat = 1;
201			break;
202		}
203	}
204
205	INTOFF;
206	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
207		INTON;
208		return (-1);
209	}
210	updatepwd(p);
211	INTON;
212	return (0);
213}
214
215STATIC int
216cdphysical(char *dest)
217{
218	char *p;
219
220	INTOFF;
221	if (chdir(dest) < 0 || (p = findcwd(NULL)) == NULL) {
222		INTON;
223		return (-1);
224	}
225	updatepwd(p);
226	INTON;
227	return (0);
228}
229
230/*
231 * Get the next component of the path name pointed to by cdcomppath.
232 * This routine overwrites the string pointed to by cdcomppath.
233 */
234STATIC char *
235getcomponent(void)
236{
237	char *p;
238	char *start;
239
240	if ((p = cdcomppath) == NULL)
241		return NULL;
242	start = cdcomppath;
243	while (*p != '/' && *p != '\0')
244		p++;
245	if (*p == '\0') {
246		cdcomppath = NULL;
247	} else {
248		*p++ = '\0';
249		cdcomppath = p;
250	}
251	return start;
252}
253
254
255STATIC char *
256findcwd(char *dir)
257{
258	char *new;
259	char *p;
260
261	/*
262	 * If our argument is NULL, we don't know the current directory
263	 * any more because we traversed a symbolic link or something
264	 * we couldn't stat().
265	 */
266	if (dir == NULL || curdir == NULL)
267		return getpwd2();
268	cdcomppath = stalloc(strlen(dir) + 1);
269	scopy(dir, cdcomppath);
270	STARTSTACKSTR(new);
271	if (*dir != '/') {
272		p = curdir;
273		while (*p)
274			STPUTC(*p++, new);
275		if (p[-1] == '/')
276			STUNPUTC(new);
277	}
278	while ((p = getcomponent()) != NULL) {
279		if (equal(p, "..")) {
280			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
281		} else if (*p != '\0' && ! equal(p, ".")) {
282			STPUTC('/', new);
283			while (*p)
284				STPUTC(*p++, new);
285		}
286	}
287	if (new == stackblock())
288		STPUTC('/', new);
289	STACKSTRNUL(new);
290	return stackblock();
291}
292
293/*
294 * Update curdir (the name of the current directory) in response to a
295 * cd command.  We also call hashcd to let the routines in exec.c know
296 * that the current directory has changed.
297 */
298STATIC void
299updatepwd(char *dir)
300{
301	hashcd();				/* update command hash table */
302
303	if (prevdir)
304		ckfree(prevdir);
305	prevdir = curdir;
306	curdir = savestr(dir);
307	setvar("PWD", curdir, VEXPORT);
308	setvar("OLDPWD", prevdir, VEXPORT);
309}
310
311int
312pwdcmd(int argc, char **argv)
313{
314	char *p;
315	int ch, phys;
316
317	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
318	phys = Pflag;
319	while ((ch = getopt(argc, argv, "LP")) != -1) {
320		switch (ch) {
321		case 'L':
322			phys = 0;
323			break;
324		case 'P':
325			phys = 1;
326			break;
327		default:
328			error("unknown option: -%c", optopt);
329			break;
330		}
331	}
332	argc -= optind;
333	argv += optind;
334
335	if (argc != 0)
336		error("too many arguments");
337
338	if (!phys && getpwd()) {
339		out1str(curdir);
340		out1c('\n');
341	} else {
342		if ((p = getpwd2()) == NULL)
343			error(".: %s", strerror(errno));
344		out1str(p);
345		out1c('\n');
346	}
347
348	return 0;
349}
350
351/*
352 * Get the current directory and cache the result in curdir.
353 */
354char *
355getpwd(void)
356{
357	char *p;
358
359	if (curdir)
360		return curdir;
361
362	p = getpwd2();
363	if (p != NULL)
364		curdir = savestr(p);
365
366	return curdir;
367}
368
369#define MAXPWD 256
370
371/*
372 * Return the current directory.
373 */
374STATIC char *
375getpwd2(void)
376{
377	struct stat stdot, stpwd;
378	char *pwd;
379	int i;
380
381	for (i = MAXPWD;; i *= 2) {
382		pwd = stalloc(i);
383		if (getcwd(pwd, i) != NULL)
384			return pwd;
385		stunalloc(pwd);
386		if (errno != ERANGE)
387			break;
388	}
389
390	pwd = getenv("PWD");
391	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
392	    stat(pwd, &stpwd) != -1 &&
393	    stdot.st_dev == stpwd.st_dev &&
394	    stdot.st_ino == stpwd.st_ino) {
395		return pwd;
396	}
397	return NULL;
398}
399