cd.c revision 222381
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 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34#if 0
35static char sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
36#endif
37#endif /* not lint */
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/bin/sh/cd.c 222381 2011-05-27 20:01:46Z jilles $");
40
41#include <sys/types.h>
42#include <sys/stat.h>
43#include <stdlib.h>
44#include <string.h>
45#include <unistd.h>
46#include <errno.h>
47#include <limits.h>
48
49/*
50 * The cd and pwd commands.
51 */
52
53#include "shell.h"
54#include "var.h"
55#include "nodes.h"	/* for jobs.h */
56#include "jobs.h"
57#include "options.h"
58#include "output.h"
59#include "memalloc.h"
60#include "error.h"
61#include "exec.h"
62#include "redir.h"
63#include "mystring.h"
64#include "show.h"
65#include "cd.h"
66
67static int cdlogical(char *);
68static int cdphysical(char *);
69static int docd(char *, int, int);
70static char *getcomponent(void);
71static char *findcwd(char *);
72static void updatepwd(char *);
73static char *getpwd(void);
74static char *getpwd2(void);
75
76static char *curdir = NULL;	/* current working directory */
77static char *prevdir;		/* previous working directory */
78static char *cdcomppath;
79
80int
81cdcmd(int argc, char **argv)
82{
83	const char *dest;
84	const char *path;
85	char *p;
86	struct stat statb;
87	int ch, phys, print = 0, getcwderr = 0;
88	int rc;
89	int errno1 = ENOENT;
90
91	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
92	phys = Pflag;
93	while ((ch = getopt(argc, argv, "eLP")) != -1) {
94		switch (ch) {
95		case 'e':
96			getcwderr = 1;
97			break;
98		case 'L':
99			phys = 0;
100			break;
101		case 'P':
102			phys = 1;
103			break;
104		default:
105			error("unknown option: -%c", optopt);
106			break;
107		}
108	}
109	argc -= optind;
110	argv += optind;
111
112	if (argc > 1)
113		error("too many arguments");
114
115	if ((dest = *argv) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
116		error("HOME not set");
117	if (*dest == '\0')
118		dest = ".";
119	if (dest[0] == '-' && dest[1] == '\0') {
120		dest = prevdir ? prevdir : curdir;
121		if (dest)
122			print = 1;
123		else
124			dest = ".";
125	}
126	if (dest[0] == '/' ||
127	    (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
128	    (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
129	    (path = bltinlookup("CDPATH", 1)) == NULL)
130		path = nullstr;
131	while ((p = padvance(&path, dest)) != NULL) {
132		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
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, char **argv)
328{
329	char *p;
330	int ch, phys;
331
332	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
333	phys = Pflag;
334	while ((ch = getopt(argc, argv, "LP")) != -1) {
335		switch (ch) {
336		case 'L':
337			phys = 0;
338			break;
339		case 'P':
340			phys = 1;
341			break;
342		default:
343			error("unknown option: -%c", optopt);
344			break;
345		}
346	}
347	argc -= optind;
348	argv += optind;
349
350	if (argc != 0)
351		error("too many arguments");
352
353	if (!phys && getpwd()) {
354		out1str(curdir);
355		out1c('\n');
356	} else {
357		if ((p = getpwd2()) == NULL)
358			error(".: %s", strerror(errno));
359		out1str(p);
360		out1c('\n');
361	}
362
363	return 0;
364}
365
366/*
367 * Get the current directory and cache the result in curdir.
368 */
369static char *
370getpwd(void)
371{
372	char *p;
373
374	if (curdir)
375		return curdir;
376
377	p = getpwd2();
378	if (p != NULL)
379		curdir = savestr(p);
380
381	return curdir;
382}
383
384#define MAXPWD 256
385
386/*
387 * Return the current directory.
388 */
389static char *
390getpwd2(void)
391{
392	char *pwd;
393	int i;
394
395	for (i = MAXPWD;; i *= 2) {
396		pwd = stalloc(i);
397		if (getcwd(pwd, i) != NULL)
398			return pwd;
399		stunalloc(pwd);
400		if (errno != ERANGE)
401			break;
402	}
403
404	return NULL;
405}
406
407/*
408 * Initialize PWD in a new shell.
409 * If the shell is interactive, we need to warn if this fails.
410 */
411void
412pwd_init(int warn)
413{
414	char *pwd;
415	struct stat stdot, stpwd;
416
417	pwd = lookupvar("PWD");
418	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
419	    stat(pwd, &stpwd) != -1 &&
420	    stdot.st_dev == stpwd.st_dev &&
421	    stdot.st_ino == stpwd.st_ino) {
422		if (curdir)
423			ckfree(curdir);
424		curdir = savestr(pwd);
425	}
426	if (getpwd() == NULL && warn)
427		out2fmt_flush("sh: cannot determine working directory\n");
428	setvar("PWD", curdir, VEXPORT);
429}
430