cd.c revision 240541
1179263Sjb/*-
2179263Sjb * Copyright (c) 1991, 1993
3179263Sjb *	The Regents of the University of California.  All rights reserved.
4179263Sjb *
5179263Sjb * This code is derived from software contributed to Berkeley by
6179263Sjb * Kenneth Almquist.
7179263Sjb *
8179263Sjb * Redistribution and use in source and binary forms, with or without
9179263Sjb * modification, are permitted provided that the following conditions
10179263Sjb * are met:
11179263Sjb * 1. Redistributions of source code must retain the above copyright
12179263Sjb *    notice, this list of conditions and the following disclaimer.
13179263Sjb * 2. Redistributions in binary form must reproduce the above copyright
14179263Sjb *    notice, this list of conditions and the following disclaimer in the
15179263Sjb *    documentation and/or other materials provided with the distribution.
16179263Sjb * 4. Neither the name of the University nor the names of its contributors
17179263Sjb *    may be used to endorse or promote products derived from this software
18179263Sjb *    without specific prior written permission.
19179263Sjb *
20179263Sjb * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21179263Sjb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22179263Sjb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23179263Sjb * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24179263Sjb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25179263Sjb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26179263Sjb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27179263Sjb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28179263Sjb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29179263Sjb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30179263Sjb * SUCH DAMAGE.
31179263Sjb */
32179263Sjb
33179263Sjb#ifndef lint
34193066Sjamie#if 0
35179263Sjbstatic char sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
36191915Szec#endif
37179263Sjb#endif /* not lint */
38179263Sjb#include <sys/cdefs.h>
39179263Sjb__FBSDID("$FreeBSD: head/bin/sh/cd.c 240541 2012-09-15 21:56:30Z jilles $");
40179263Sjb
41179263Sjb#include <sys/types.h>
42179263Sjb#include <sys/stat.h>
43222670Savg#include <stdlib.h>
44179263Sjb#include <string.h>
45179263Sjb#include <unistd.h>
46179263Sjb#include <errno.h>
47179263Sjb#include <limits.h>
48179263Sjb
49179263Sjb/*
50179263Sjb * The cd and pwd commands.
51179263Sjb */
52179263Sjb
53179263Sjb#include "shell.h"
54179263Sjb#include "var.h"
55179263Sjb#include "nodes.h"	/* for jobs.h */
56179263Sjb#include "jobs.h"
57179263Sjb#include "options.h"
58179263Sjb#include "output.h"
59179263Sjb#include "memalloc.h"
60179263Sjb#include "error.h"
61179263Sjb#include "exec.h"
62179263Sjb#include "redir.h"
63179263Sjb#include "mystring.h"
64222670Savg#include "show.h"
65222670Savg#include "cd.h"
66179263Sjb#include "builtins.h"
67179263Sjb
68179263Sjbstatic int cdlogical(char *);
69179263Sjbstatic int cdphysical(char *);
70179263Sjbstatic int docd(char *, int, int);
71179263Sjbstatic char *getcomponent(void);
72179263Sjbstatic char *findcwd(char *);
73179263Sjbstatic void updatepwd(char *);
74179263Sjbstatic char *getpwd(void);
75179263Sjbstatic char *getpwd2(void);
76179263Sjb
77179263Sjbstatic char *curdir = NULL;	/* current working directory */
78179263Sjbstatic char *prevdir;		/* previous working directory */
79179263Sjbstatic char *cdcomppath;
80179263Sjb
81179263Sjbint
82179263Sjbcdcmd(int argc __unused, char **argv __unused)
83179263Sjb{
84179263Sjb	const char *dest;
85194118Sjamie	const char *path;
86179263Sjb	char *p;
87179263Sjb	struct stat statb;
88179263Sjb	int ch, phys, print = 0, getcwderr = 0;
89179263Sjb	int rc;
90179263Sjb	int errno1 = ENOENT;
91179263Sjb
92179263Sjb	phys = Pflag;
93179263Sjb	while ((ch = nextopt("eLP")) != '\0') {
94179263Sjb		switch (ch) {
95179263Sjb		case 'e':
96179263Sjb			getcwderr = 1;
97179263Sjb			break;
98179263Sjb		case 'L':
99179263Sjb			phys = 0;
100179263Sjb			break;
101179263Sjb		case 'P':
102179263Sjb			phys = 1;
103179263Sjb			break;
104		}
105	}
106
107	if (*argptr != NULL && argptr[1] != NULL)
108		error("too many arguments");
109
110	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
111		error("HOME not set");
112	if (*dest == '\0')
113		dest = ".";
114	if (dest[0] == '-' && dest[1] == '\0') {
115		dest = prevdir ? prevdir : curdir;
116		if (dest)
117			print = 1;
118		else
119			dest = ".";
120	}
121	if (dest[0] == '/' ||
122	    (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
123	    (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
124	    (path = bltinlookup("CDPATH", 1)) == NULL)
125		path = nullstr;
126	while ((p = padvance(&path, dest)) != NULL) {
127		if (stat(p, &statb) < 0) {
128			if (errno != ENOENT)
129				errno1 = errno;
130		} else if (!S_ISDIR(statb.st_mode))
131			errno1 = ENOTDIR;
132		else {
133			if (!print) {
134				/*
135				 * XXX - rethink
136				 */
137				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
138					print = strcmp(p + 2, dest);
139				else
140					print = strcmp(p, dest);
141			}
142			rc = docd(p, print, phys);
143			if (rc >= 0)
144				return getcwderr ? rc : 0;
145			if (errno != ENOENT)
146				errno1 = errno;
147		}
148	}
149	error("%s: %s", dest, strerror(errno1));
150	/*NOTREACHED*/
151	return 0;
152}
153
154
155/*
156 * Actually change the directory.  In an interactive shell, print the
157 * directory name if "print" is nonzero.
158 */
159static int
160docd(char *dest, int print, int phys)
161{
162	int rc;
163
164	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
165
166	/* If logical cd fails, fall back to physical. */
167	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
168		return (-1);
169
170	if (print && iflag && curdir)
171		out1fmt("%s\n", curdir);
172
173	return (rc);
174}
175
176static int
177cdlogical(char *dest)
178{
179	char *p;
180	char *q;
181	char *component;
182	struct stat statb;
183	int first;
184	int badstat;
185
186	/*
187	 *  Check each component of the path. If we find a symlink or
188	 *  something we can't stat, clear curdir to force a getcwd()
189	 *  next time we get the value of the current directory.
190	 */
191	badstat = 0;
192	cdcomppath = stalloc(strlen(dest) + 1);
193	scopy(dest, cdcomppath);
194	STARTSTACKSTR(p);
195	if (*dest == '/') {
196		STPUTC('/', p);
197		cdcomppath++;
198	}
199	first = 1;
200	while ((q = getcomponent()) != NULL) {
201		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
202			continue;
203		if (! first)
204			STPUTC('/', p);
205		first = 0;
206		component = q;
207		STPUTS(q, p);
208		if (equal(component, ".."))
209			continue;
210		STACKSTRNUL(p);
211		if (lstat(stackblock(), &statb) < 0) {
212			badstat = 1;
213			break;
214		}
215	}
216
217	INTOFF;
218	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
219		INTON;
220		return (-1);
221	}
222	updatepwd(p);
223	INTON;
224	return (0);
225}
226
227static int
228cdphysical(char *dest)
229{
230	char *p;
231	int rc = 0;
232
233	INTOFF;
234	if (chdir(dest) < 0) {
235		INTON;
236		return (-1);
237	}
238	p = findcwd(NULL);
239	if (p == NULL) {
240		warning("warning: failed to get name of current directory");
241		rc = 1;
242	}
243	updatepwd(p);
244	INTON;
245	return (rc);
246}
247
248/*
249 * Get the next component of the path name pointed to by cdcomppath.
250 * This routine overwrites the string pointed to by cdcomppath.
251 */
252static char *
253getcomponent(void)
254{
255	char *p;
256	char *start;
257
258	if ((p = cdcomppath) == NULL)
259		return NULL;
260	start = cdcomppath;
261	while (*p != '/' && *p != '\0')
262		p++;
263	if (*p == '\0') {
264		cdcomppath = NULL;
265	} else {
266		*p++ = '\0';
267		cdcomppath = p;
268	}
269	return start;
270}
271
272
273static char *
274findcwd(char *dir)
275{
276	char *new;
277	char *p;
278
279	/*
280	 * If our argument is NULL, we don't know the current directory
281	 * any more because we traversed a symbolic link or something
282	 * we couldn't stat().
283	 */
284	if (dir == NULL || curdir == NULL)
285		return getpwd2();
286	cdcomppath = stalloc(strlen(dir) + 1);
287	scopy(dir, cdcomppath);
288	STARTSTACKSTR(new);
289	if (*dir != '/') {
290		STPUTS(curdir, new);
291		if (STTOPC(new) == '/')
292			STUNPUTC(new);
293	}
294	while ((p = getcomponent()) != NULL) {
295		if (equal(p, "..")) {
296			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
297		} else if (*p != '\0' && ! equal(p, ".")) {
298			STPUTC('/', new);
299			STPUTS(p, new);
300		}
301	}
302	if (new == stackblock())
303		STPUTC('/', new);
304	STACKSTRNUL(new);
305	return stackblock();
306}
307
308/*
309 * Update curdir (the name of the current directory) in response to a
310 * cd command.  We also call hashcd to let the routines in exec.c know
311 * that the current directory has changed.
312 */
313static void
314updatepwd(char *dir)
315{
316	hashcd();				/* update command hash table */
317
318	if (prevdir)
319		ckfree(prevdir);
320	prevdir = curdir;
321	curdir = dir ? savestr(dir) : NULL;
322	setvar("PWD", curdir, VEXPORT);
323	setvar("OLDPWD", prevdir, VEXPORT);
324}
325
326int
327pwdcmd(int argc __unused, char **argv __unused)
328{
329	char *p;
330	int ch, phys;
331
332	phys = Pflag;
333	while ((ch = nextopt("LP")) != '\0') {
334		switch (ch) {
335		case 'L':
336			phys = 0;
337			break;
338		case 'P':
339			phys = 1;
340			break;
341		}
342	}
343
344	if (*argptr != NULL)
345		error("too many arguments");
346
347	if (!phys && getpwd()) {
348		out1str(curdir);
349		out1c('\n');
350	} else {
351		if ((p = getpwd2()) == NULL)
352			error(".: %s", strerror(errno));
353		out1str(p);
354		out1c('\n');
355	}
356
357	return 0;
358}
359
360/*
361 * Get the current directory and cache the result in curdir.
362 */
363static char *
364getpwd(void)
365{
366	char *p;
367
368	if (curdir)
369		return curdir;
370
371	p = getpwd2();
372	if (p != NULL)
373		curdir = savestr(p);
374
375	return curdir;
376}
377
378#define MAXPWD 256
379
380/*
381 * Return the current directory.
382 */
383static char *
384getpwd2(void)
385{
386	char *pwd;
387	int i;
388
389	for (i = MAXPWD;; i *= 2) {
390		pwd = stalloc(i);
391		if (getcwd(pwd, i) != NULL)
392			return pwd;
393		stunalloc(pwd);
394		if (errno != ERANGE)
395			break;
396	}
397
398	return NULL;
399}
400
401/*
402 * Initialize PWD in a new shell.
403 * If the shell is interactive, we need to warn if this fails.
404 */
405void
406pwd_init(int warn)
407{
408	char *pwd;
409	struct stat stdot, stpwd;
410
411	pwd = lookupvar("PWD");
412	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
413	    stat(pwd, &stpwd) != -1 &&
414	    stdot.st_dev == stpwd.st_dev &&
415	    stdot.st_ino == stpwd.st_ino) {
416		if (curdir)
417			ckfree(curdir);
418		curdir = savestr(pwd);
419	}
420	if (getpwd() == NULL && warn)
421		out2fmt_flush("sh: cannot determine working directory\n");
422	setvar("PWD", curdir, VEXPORT);
423}
424