cd.c revision 294667
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 294667 2016-01-24 17:01:34Z 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#include "builtins.h"
67
68static int cdlogical(char *);
69static int cdphysical(char *);
70static int docd(char *, int, int);
71static char *getcomponent(char **);
72static char *findcwd(char *);
73static void updatepwd(char *);
74static char *getpwd(void);
75static char *getpwd2(void);
76
77static char *curdir = NULL;	/* current working directory */
78
79int
80cdcmd(int argc __unused, char **argv __unused)
81{
82	const char *dest;
83	const char *path;
84	char *p;
85	struct stat statb;
86	int ch, phys, print = 0, getcwderr = 0;
87	int rc;
88	int errno1 = ENOENT;
89
90	phys = Pflag;
91	while ((ch = nextopt("eLP")) != '\0') {
92		switch (ch) {
93		case 'e':
94			getcwderr = 1;
95			break;
96		case 'L':
97			phys = 0;
98			break;
99		case 'P':
100			phys = 1;
101			break;
102		}
103	}
104
105	if (*argptr != NULL && argptr[1] != NULL)
106		error("too many arguments");
107
108	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
109		error("HOME not set");
110	if (*dest == '\0')
111		dest = ".";
112	if (dest[0] == '-' && dest[1] == '\0') {
113		dest = bltinlookup("OLDPWD", 1);
114		if (dest == NULL)
115			error("OLDPWD not set");
116		print = 1;
117	}
118	if (dest[0] == '/' ||
119	    (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
120	    (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
121	    (path = bltinlookup("CDPATH", 1)) == NULL)
122		path = "";
123	while ((p = padvance(&path, dest)) != NULL) {
124		if (stat(p, &statb) < 0) {
125			if (errno != ENOENT)
126				errno1 = errno;
127		} else if (!S_ISDIR(statb.st_mode))
128			errno1 = ENOTDIR;
129		else {
130			if (!print) {
131				/*
132				 * XXX - rethink
133				 */
134				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
135					print = strcmp(p + 2, dest);
136				else
137					print = strcmp(p, dest);
138			}
139			rc = docd(p, print, phys);
140			if (rc >= 0)
141				return getcwderr ? rc : 0;
142			if (errno != ENOENT)
143				errno1 = errno;
144		}
145	}
146	error("%s: %s", dest, strerror(errno1));
147	/*NOTREACHED*/
148	return 0;
149}
150
151
152/*
153 * Actually change the directory.  In an interactive shell, print the
154 * directory name if "print" is nonzero.
155 */
156static int
157docd(char *dest, int print, int phys)
158{
159	int rc;
160
161	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
162
163	/* If logical cd fails, fall back to physical. */
164	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
165		return (-1);
166
167	if (print && iflag && curdir)
168		out1fmt("%s\n", curdir);
169
170	return (rc);
171}
172
173static int
174cdlogical(char *dest)
175{
176	char *p;
177	char *q;
178	char *component;
179	char *path;
180	struct stat statb;
181	int first;
182	int badstat;
183
184	/*
185	 *  Check each component of the path. If we find a symlink or
186	 *  something we can't stat, clear curdir to force a getcwd()
187	 *  next time we get the value of the current directory.
188	 */
189	badstat = 0;
190	path = stsavestr(dest);
191	STARTSTACKSTR(p);
192	if (*dest == '/') {
193		STPUTC('/', p);
194		path++;
195	}
196	first = 1;
197	while ((q = getcomponent(&path)) != NULL) {
198		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
199			continue;
200		if (! first)
201			STPUTC('/', p);
202		first = 0;
203		component = q;
204		STPUTS(q, p);
205		if (equal(component, ".."))
206			continue;
207		STACKSTRNUL(p);
208		if (lstat(stackblock(), &statb) < 0) {
209			badstat = 1;
210			break;
211		}
212	}
213
214	INTOFF;
215	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
216		INTON;
217		return (-1);
218	}
219	updatepwd(p);
220	INTON;
221	return (0);
222}
223
224static int
225cdphysical(char *dest)
226{
227	char *p;
228	int rc = 0;
229
230	INTOFF;
231	if (chdir(dest) < 0) {
232		INTON;
233		return (-1);
234	}
235	p = findcwd(NULL);
236	if (p == NULL) {
237		warning("warning: failed to get name of current directory");
238		rc = 1;
239	}
240	updatepwd(p);
241	INTON;
242	return (rc);
243}
244
245/*
246 * Get the next component of the path name pointed to by *path.
247 * This routine overwrites *path and the string pointed to by it.
248 */
249static char *
250getcomponent(char **path)
251{
252	char *p;
253	char *start;
254
255	if ((p = *path) == NULL)
256		return NULL;
257	start = *path;
258	while (*p != '/' && *p != '\0')
259		p++;
260	if (*p == '\0') {
261		*path = NULL;
262	} else {
263		*p++ = '\0';
264		*path = p;
265	}
266	return start;
267}
268
269
270static char *
271findcwd(char *dir)
272{
273	char *new;
274	char *p;
275	char *path;
276
277	/*
278	 * If our argument is NULL, we don't know the current directory
279	 * any more because we traversed a symbolic link or something
280	 * we couldn't stat().
281	 */
282	if (dir == NULL || curdir == NULL)
283		return getpwd2();
284	path = stsavestr(dir);
285	STARTSTACKSTR(new);
286	if (*dir != '/') {
287		STPUTS(curdir, new);
288		if (STTOPC(new) == '/')
289			STUNPUTC(new);
290	}
291	while ((p = getcomponent(&path)) != NULL) {
292		if (equal(p, "..")) {
293			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
294		} else if (*p != '\0' && ! equal(p, ".")) {
295			STPUTC('/', new);
296			STPUTS(p, new);
297		}
298	}
299	if (new == stackblock())
300		STPUTC('/', new);
301	STACKSTRNUL(new);
302	return stackblock();
303}
304
305/*
306 * Update curdir (the name of the current directory) in response to a
307 * cd command.  We also call hashcd to let the routines in exec.c know
308 * that the current directory has changed.
309 */
310static void
311updatepwd(char *dir)
312{
313	char *prevdir;
314
315	hashcd();				/* update command hash table */
316
317	setvar("PWD", dir, VEXPORT);
318	setvar("OLDPWD", curdir, VEXPORT);
319	prevdir = curdir;
320	curdir = dir ? savestr(dir) : NULL;
321	ckfree(prevdir);
322}
323
324int
325pwdcmd(int argc __unused, char **argv __unused)
326{
327	char *p;
328	int ch, phys;
329
330	phys = Pflag;
331	while ((ch = nextopt("LP")) != '\0') {
332		switch (ch) {
333		case 'L':
334			phys = 0;
335			break;
336		case 'P':
337			phys = 1;
338			break;
339		}
340	}
341
342	if (*argptr != NULL)
343		error("too many arguments");
344
345	if (!phys && getpwd()) {
346		out1str(curdir);
347		out1c('\n');
348	} else {
349		if ((p = getpwd2()) == NULL)
350			error(".: %s", strerror(errno));
351		out1str(p);
352		out1c('\n');
353	}
354
355	return 0;
356}
357
358/*
359 * Get the current directory and cache the result in curdir.
360 */
361static char *
362getpwd(void)
363{
364	char *p;
365
366	if (curdir)
367		return curdir;
368
369	p = getpwd2();
370	if (p != NULL)
371		curdir = savestr(p);
372
373	return curdir;
374}
375
376#define MAXPWD 256
377
378/*
379 * Return the current directory.
380 */
381static char *
382getpwd2(void)
383{
384	char *pwd;
385	int i;
386
387	for (i = MAXPWD;; i *= 2) {
388		pwd = stalloc(i);
389		if (getcwd(pwd, i) != NULL)
390			return pwd;
391		stunalloc(pwd);
392		if (errno != ERANGE)
393			break;
394	}
395
396	return NULL;
397}
398
399/*
400 * Initialize PWD in a new shell.
401 * If the shell is interactive, we need to warn if this fails.
402 */
403void
404pwd_init(int warn)
405{
406	char *pwd;
407	struct stat stdot, stpwd;
408
409	pwd = lookupvar("PWD");
410	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
411	    stat(pwd, &stpwd) != -1 &&
412	    stdot.st_dev == stpwd.st_dev &&
413	    stdot.st_ino == stpwd.st_ino) {
414		if (curdir)
415			ckfree(curdir);
416		curdir = savestr(pwd);
417	}
418	if (getpwd() == NULL && warn)
419		out2fmt_flush("sh: cannot determine working directory\n");
420	setvar("PWD", curdir, VEXPORT);
421}
422