cd.c revision 38886
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	"$Id: cd.c,v 1.17 1998/05/18 06:43:30 charnier Exp $";
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 __P((char *, int));
71STATIC char *getcomponent __P((void));
72STATIC void updatepwd __P((char *));
73
74char *curdir = NULL;		/* current working directory */
75char *prevdir;			/* previous working directory */
76STATIC char *cdcomppath;
77
78int
79cdcmd(argc, argv)
80	int argc __unused;
81	char **argv __unused;
82{
83	char *dest;
84	char *path;
85	char *p;
86	struct stat statb;
87	int print = 0;
88
89	nextopt(nullstr);
90	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
91		error("HOME not set");
92	if (*dest == '\0')
93		dest = ".";
94	if (dest[0] == '-' && dest[1] == '\0') {
95		dest = prevdir ? prevdir : curdir;
96		if (dest)
97			print = 1;
98		else
99			dest = ".";
100	}
101	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
102		path = nullstr;
103	while ((p = padvance(&path, dest)) != NULL) {
104		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
105			if (!print) {
106				/*
107				 * XXX - rethink
108				 */
109				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
110					p += 2;
111				print = strcmp(p, dest);
112			}
113			if (docd(p, print) >= 0)
114				return 0;
115
116		}
117	}
118	error("can't cd to %s", dest);
119	/*NOTREACHED*/
120	return 0;
121}
122
123
124/*
125 * Actually do the chdir.  In an interactive shell, print the
126 * directory name if "print" is nonzero.
127 */
128STATIC int
129docd(dest, print)
130	char *dest;
131	int print;
132{
133	char *p;
134	char *q;
135	char *component;
136	struct stat statb;
137	int first;
138	int badstat;
139
140	TRACE(("docd(\"%s\", %d) called\n", dest, print));
141
142	/*
143	 *  Check each component of the path. If we find a symlink or
144	 *  something we can't stat, clear curdir to force a getcwd()
145	 *  next time we get the value of the current directory.
146	 */
147	badstat = 0;
148	cdcomppath = stalloc(strlen(dest) + 1);
149	scopy(dest, cdcomppath);
150	STARTSTACKSTR(p);
151	if (*dest == '/') {
152		STPUTC('/', p);
153		cdcomppath++;
154	}
155	first = 1;
156	while ((q = getcomponent()) != NULL) {
157		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
158			continue;
159		if (! first)
160			STPUTC('/', p);
161		first = 0;
162		component = q;
163		while (*q)
164			STPUTC(*q++, p);
165		if (equal(component, ".."))
166			continue;
167		STACKSTRNUL(p);
168		if ((lstat(stackblock(), &statb) < 0)
169		    || (S_ISLNK(statb.st_mode)))  {
170			/* print = 1; */
171			badstat = 1;
172			break;
173		}
174	}
175
176	INTOFF;
177	if (chdir(dest) < 0) {
178		INTON;
179		return -1;
180	}
181	updatepwd(badstat ? NULL : dest);
182	INTON;
183	if (print && iflag && curdir)
184		out1fmt("%s\n", curdir);
185	return 0;
186}
187
188
189/*
190 * Get the next component of the path name pointed to by cdcomppath.
191 * This routine overwrites the string pointed to by cdcomppath.
192 */
193STATIC char *
194getcomponent()
195{
196	char *p;
197	char *start;
198
199	if ((p = cdcomppath) == NULL)
200		return NULL;
201	start = cdcomppath;
202	while (*p != '/' && *p != '\0')
203		p++;
204	if (*p == '\0') {
205		cdcomppath = NULL;
206	} else {
207		*p++ = '\0';
208		cdcomppath = p;
209	}
210	return start;
211}
212
213
214/*
215 * Update curdir (the name of the current directory) in response to a
216 * cd command.  We also call hashcd to let the routines in exec.c know
217 * that the current directory has changed.
218 */
219STATIC void
220updatepwd(dir)
221	char *dir;
222{
223	char *new;
224	char *p;
225
226	hashcd();				/* update command hash table */
227
228	/*
229	 * If our argument is NULL, we don't know the current directory
230	 * any more because we traversed a symbolic link or something
231	 * we couldn't stat().
232	 */
233	if (dir == NULL || curdir == NULL)  {
234		if (prevdir)
235			ckfree(prevdir);
236		INTOFF;
237		prevdir = curdir;
238		curdir = NULL;
239		if (getpwd() == NULL)
240			error("getcwd() failed: %s", strerror(errno));
241		setvar("PWD", curdir, VEXPORT | VTEXTFIXED);
242		setvar("OLDPWD", prevdir, VEXPORT | VTEXTFIXED);
243		INTON;
244		return;
245	}
246	cdcomppath = stalloc(strlen(dir) + 1);
247	scopy(dir, cdcomppath);
248	STARTSTACKSTR(new);
249	if (*dir != '/') {
250		p = curdir;
251		while (*p)
252			STPUTC(*p++, new);
253		if (p[-1] == '/')
254			STUNPUTC(new);
255	}
256	while ((p = getcomponent()) != NULL) {
257		if (equal(p, "..")) {
258			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
259		} else if (*p != '\0' && ! equal(p, ".")) {
260			STPUTC('/', new);
261			while (*p)
262				STPUTC(*p++, new);
263		}
264	}
265	if (new == stackblock())
266		STPUTC('/', new);
267	STACKSTRNUL(new);
268	INTOFF;
269	if (prevdir)
270		ckfree(prevdir);
271	prevdir = curdir;
272	curdir = savestr(stackblock());
273	setvar("PWD", curdir, VEXPORT | VTEXTFIXED);
274	setvar("OLDPWD", prevdir, VEXPORT | VTEXTFIXED);
275	INTON;
276}
277
278
279int
280pwdcmd(argc, argv)
281	int argc __unused;
282	char **argv __unused;
283{
284	if (!getpwd())
285		error("getcwd() failed: %s", strerror(errno));
286	out1str(curdir);
287	out1c('\n');
288	return 0;
289}
290
291
292
293
294#define MAXPWD 256
295
296/*
297 * Find out what the current directory is. If we already know the current
298 * directory, this routine returns immediately.
299 */
300char *
301getpwd()
302{
303	char buf[MAXPWD];
304
305	if (curdir)
306		return curdir;
307	/*
308	 * Things are a bit complicated here; we could have just used
309	 * getcwd, but traditionally getcwd is implemented using popen
310	 * to /bin/pwd. This creates a problem for us, since we cannot
311	 * keep track of the job if it is being ran behind our backs.
312	 * So we re-implement getcwd(), and we suppress interrupts
313	 * throughout the process. This is not completely safe, since
314	 * the user can still break out of it by killing the pwd program.
315	 * We still try to use getcwd for systems that we know have a
316	 * c implementation of getcwd, that does not open a pipe to
317	 * /bin/pwd.
318	 */
319#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__SVR4)
320
321	if (getcwd(buf, sizeof(buf)) == NULL) {
322		char *pwd = getenv("PWD");
323		struct stat stdot, stpwd;
324
325		if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
326		    stat(pwd, &stpwd) != -1 &&
327		    stdot.st_dev == stpwd.st_dev &&
328		    stdot.st_ino == stpwd.st_ino) {
329			curdir = savestr(pwd);
330			return curdir;
331		}
332		return NULL;
333	}
334	curdir = savestr(buf);
335#else
336	{
337		char *p;
338		int i;
339		int status;
340		struct job *jp;
341		int pip[2];
342
343		INTOFF;
344		if (pipe(pip) < 0)
345			error("Pipe call failed");
346		jp = makejob((union node *)NULL, 1);
347		if (forkshell(jp, (union node *)NULL, FORK_NOJOB) == 0) {
348			(void) close(pip[0]);
349			if (pip[1] != 1) {
350				close(1);
351				copyfd(pip[1], 1);
352				close(pip[1]);
353			}
354			(void) execl("/bin/pwd", "pwd", (char *)0);
355			error("Cannot exec /bin/pwd");
356		}
357		(void) close(pip[1]);
358		pip[1] = -1;
359		p = buf;
360		while ((i = read(pip[0], p, buf + MAXPWD - p)) > 0
361		     || (i == -1 && errno == EINTR)) {
362			if (i > 0)
363				p += i;
364		}
365		(void) close(pip[0]);
366		pip[0] = -1;
367		status = waitforjob(jp);
368		if (status != 0)
369			error((char *)0);
370		if (i < 0 || p == buf || p[-1] != '\n')
371			error("pwd command failed");
372		p[-1] = '\0';
373	}
374	curdir = savestr(buf);
375	INTON;
376#endif
377	return curdir;
378}
379