cd.c revision 90111
1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38#if 0
39static char sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
40#endif
41static const char rcsid[] =
42  "$FreeBSD: head/bin/sh/cd.c 90111 2002-02-02 06:50:57Z imp $";
43#endif /* not lint */
44
45#include <sys/types.h>
46#include <sys/stat.h>
47#include <stdlib.h>
48#include <string.h>
49#include <unistd.h>
50#include <errno.h>
51
52/*
53 * The cd and pwd commands.
54 */
55
56#include "shell.h"
57#include "var.h"
58#include "nodes.h"	/* for jobs.h */
59#include "jobs.h"
60#include "options.h"
61#include "output.h"
62#include "memalloc.h"
63#include "error.h"
64#include "exec.h"
65#include "redir.h"
66#include "mystring.h"
67#include "show.h"
68#include "cd.h"
69
70STATIC int docd(char *, int);
71STATIC char *getcomponent(void);
72STATIC void updatepwd(char *);
73
74char *curdir = NULL;		/* current working directory */
75char *prevdir;			/* previous working directory */
76STATIC char *cdcomppath;
77
78int
79cdcmd(int argc __unused, char **argv __unused)
80{
81	char *dest;
82	char *path;
83	char *p;
84	struct stat statb;
85	int print = 0;
86
87	nextopt(nullstr);
88	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
89		error("HOME not set");
90	if (*dest == '\0')
91		dest = ".";
92	if (dest[0] == '-' && dest[1] == '\0') {
93		dest = prevdir ? prevdir : curdir;
94		if (dest)
95			print = 1;
96		else
97			dest = ".";
98	}
99	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
100		path = nullstr;
101	while ((p = padvance(&path, dest)) != NULL) {
102		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
103			if (!print) {
104				/*
105				 * XXX - rethink
106				 */
107				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
108					p += 2;
109				print = strcmp(p, dest);
110			}
111			if (docd(p, print) >= 0)
112				return 0;
113
114		}
115	}
116	error("can't cd to %s", dest);
117	/*NOTREACHED*/
118	return 0;
119}
120
121
122/*
123 * Actually do the chdir.  In an interactive shell, print the
124 * directory name if "print" is nonzero.
125 */
126STATIC int
127docd(char *dest, int print)
128{
129	char *p;
130	char *q;
131	char *component;
132	struct stat statb;
133	int first;
134	int badstat;
135
136	TRACE(("docd(\"%s\", %d) called\n", dest, print));
137
138	/*
139	 *  Check each component of the path. If we find a symlink or
140	 *  something we can't stat, clear curdir to force a getcwd()
141	 *  next time we get the value of the current directory.
142	 */
143	badstat = 0;
144	cdcomppath = stalloc(strlen(dest) + 1);
145	scopy(dest, cdcomppath);
146	STARTSTACKSTR(p);
147	if (*dest == '/') {
148		STPUTC('/', p);
149		cdcomppath++;
150	}
151	first = 1;
152	while ((q = getcomponent()) != NULL) {
153		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
154			continue;
155		if (! first)
156			STPUTC('/', p);
157		first = 0;
158		component = q;
159		while (*q)
160			STPUTC(*q++, p);
161		if (equal(component, ".."))
162			continue;
163		STACKSTRNUL(p);
164		if ((lstat(stackblock(), &statb) < 0)
165		    || (S_ISLNK(statb.st_mode)))  {
166			/* print = 1; */
167			badstat = 1;
168			break;
169		}
170	}
171
172	INTOFF;
173	if (chdir(dest) < 0) {
174		INTON;
175		return -1;
176	}
177	updatepwd(badstat ? NULL : dest);
178	INTON;
179	if (print && iflag && curdir)
180		out1fmt("%s\n", curdir);
181	return 0;
182}
183
184
185/*
186 * Get the next component of the path name pointed to by cdcomppath.
187 * This routine overwrites the string pointed to by cdcomppath.
188 */
189STATIC char *
190getcomponent(void)
191{
192	char *p;
193	char *start;
194
195	if ((p = cdcomppath) == NULL)
196		return NULL;
197	start = cdcomppath;
198	while (*p != '/' && *p != '\0')
199		p++;
200	if (*p == '\0') {
201		cdcomppath = NULL;
202	} else {
203		*p++ = '\0';
204		cdcomppath = p;
205	}
206	return start;
207}
208
209
210/*
211 * Update curdir (the name of the current directory) in response to a
212 * cd command.  We also call hashcd to let the routines in exec.c know
213 * that the current directory has changed.
214 */
215STATIC void
216updatepwd(char *dir)
217{
218	char *new;
219	char *p;
220
221	hashcd();				/* update command hash table */
222
223	/*
224	 * If our argument is NULL, we don't know the current directory
225	 * any more because we traversed a symbolic link or something
226	 * we couldn't stat().
227	 */
228	if (dir == NULL || curdir == NULL)  {
229		if (prevdir)
230			ckfree(prevdir);
231		INTOFF;
232		prevdir = curdir;
233		curdir = NULL;
234		if (getpwd() == NULL)
235			error("getcwd() failed: %s", strerror(errno));
236		setvar("PWD", curdir, VEXPORT);
237		setvar("OLDPWD", prevdir, VEXPORT);
238		INTON;
239		return;
240	}
241	cdcomppath = stalloc(strlen(dir) + 1);
242	scopy(dir, cdcomppath);
243	STARTSTACKSTR(new);
244	if (*dir != '/') {
245		p = curdir;
246		while (*p)
247			STPUTC(*p++, new);
248		if (p[-1] == '/')
249			STUNPUTC(new);
250	}
251	while ((p = getcomponent()) != NULL) {
252		if (equal(p, "..")) {
253			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
254		} else if (*p != '\0' && ! equal(p, ".")) {
255			STPUTC('/', new);
256			while (*p)
257				STPUTC(*p++, new);
258		}
259	}
260	if (new == stackblock())
261		STPUTC('/', new);
262	STACKSTRNUL(new);
263	INTOFF;
264	if (prevdir)
265		ckfree(prevdir);
266	prevdir = curdir;
267	curdir = savestr(stackblock());
268	setvar("PWD", curdir, VEXPORT);
269	setvar("OLDPWD", prevdir, VEXPORT);
270	INTON;
271}
272
273
274int
275pwdcmd(int argc __unused, char **argv __unused)
276{
277	if (!getpwd())
278		error("getcwd() failed: %s", strerror(errno));
279	out1str(curdir);
280	out1c('\n');
281	return 0;
282}
283
284
285
286
287#define MAXPWD 256
288
289/*
290 * Find out what the current directory is. If we already know the current
291 * directory, this routine returns immediately.
292 */
293char *
294getpwd(void)
295{
296	char buf[MAXPWD];
297
298	if (curdir)
299		return curdir;
300	/*
301	 * Things are a bit complicated here; we could have just used
302	 * getcwd, but traditionally getcwd is implemented using popen
303	 * to /bin/pwd. This creates a problem for us, since we cannot
304	 * keep track of the job if it is being ran behind our backs.
305	 * So we re-implement getcwd(), and we suppress interrupts
306	 * throughout the process. This is not completely safe, since
307	 * the user can still break out of it by killing the pwd program.
308	 * We still try to use getcwd for systems that we know have a
309	 * c implementation of getcwd, that does not open a pipe to
310	 * /bin/pwd.
311	 */
312#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__SVR4)
313
314	if (getcwd(buf, sizeof(buf)) == NULL) {
315		char *pwd = getenv("PWD");
316		struct stat stdot, stpwd;
317
318		if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
319		    stat(pwd, &stpwd) != -1 &&
320		    stdot.st_dev == stpwd.st_dev &&
321		    stdot.st_ino == stpwd.st_ino) {
322			curdir = savestr(pwd);
323			return curdir;
324		}
325		return NULL;
326	}
327	curdir = savestr(buf);
328#else
329	{
330		char *p;
331		int i;
332		int status;
333		struct job *jp;
334		int pip[2];
335
336		INTOFF;
337		if (pipe(pip) < 0)
338			error("Pipe call failed: %s", strerror(errno));
339		jp = makejob((union node *)NULL, 1);
340		if (forkshell(jp, (union node *)NULL, FORK_NOJOB) == 0) {
341			(void) close(pip[0]);
342			if (pip[1] != 1) {
343				close(1);
344				copyfd(pip[1], 1);
345				close(pip[1]);
346			}
347			(void) execl("/bin/pwd", "pwd", (char *)0);
348			error("Cannot exec /bin/pwd");
349		}
350		(void) close(pip[1]);
351		pip[1] = -1;
352		p = buf;
353		while ((i = read(pip[0], p, buf + MAXPWD - p)) > 0
354		     || (i == -1 && errno == EINTR)) {
355			if (i > 0)
356				p += i;
357		}
358		(void) close(pip[0]);
359		pip[0] = -1;
360		status = waitforjob(jp);
361		if (status != 0)
362			error((char *)0);
363		if (i < 0 || p == buf || p[-1] != '\n')
364			error("pwd command failed");
365		p[-1] = '\0';
366	}
367	curdir = savestr(buf);
368	INTON;
369#endif
370	return curdir;
371}
372