cd.c revision 222154
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 222154 2011-05-20 22:55:18Z 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
90	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
91	phys = Pflag;
92	while ((ch = getopt(argc, argv, "eLP")) != -1) {
93		switch (ch) {
94		case 'e':
95			getcwderr = 1;
96			break;
97		case 'L':
98			phys = 0;
99			break;
100		case 'P':
101			phys = 1;
102			break;
103		default:
104			error("unknown option: -%c", optopt);
105			break;
106		}
107	}
108	argc -= optind;
109	argv += optind;
110
111	if (argc > 1)
112		error("too many arguments");
113
114	if ((dest = *argv) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
115		error("HOME not set");
116	if (*dest == '\0')
117		dest = ".";
118	if (dest[0] == '-' && dest[1] == '\0') {
119		dest = prevdir ? prevdir : curdir;
120		if (dest)
121			print = 1;
122		else
123			dest = ".";
124	}
125	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
126		path = nullstr;
127	while ((p = padvance(&path, dest)) != NULL) {
128		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
129			if (!print) {
130				/*
131				 * XXX - rethink
132				 */
133				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
134					print = strcmp(p + 2, dest);
135				else
136					print = strcmp(p, dest);
137			}
138			rc = docd(p, print, phys);
139			if (rc >= 0)
140				return getcwderr ? rc : 0;
141		}
142	}
143	error("can't cd to %s", dest);
144	/*NOTREACHED*/
145	return 0;
146}
147
148
149/*
150 * Actually change the directory.  In an interactive shell, print the
151 * directory name if "print" is nonzero.
152 */
153static int
154docd(char *dest, int print, int phys)
155{
156	int rc;
157
158	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
159
160	/* If logical cd fails, fall back to physical. */
161	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
162		return (-1);
163
164	if (print && iflag && curdir)
165		out1fmt("%s\n", curdir);
166
167	return (rc);
168}
169
170static int
171cdlogical(char *dest)
172{
173	char *p;
174	char *q;
175	char *component;
176	struct stat statb;
177	int first;
178	int badstat;
179
180	/*
181	 *  Check each component of the path. If we find a symlink or
182	 *  something we can't stat, clear curdir to force a getcwd()
183	 *  next time we get the value of the current directory.
184	 */
185	badstat = 0;
186	cdcomppath = stalloc(strlen(dest) + 1);
187	scopy(dest, cdcomppath);
188	STARTSTACKSTR(p);
189	if (*dest == '/') {
190		STPUTC('/', p);
191		cdcomppath++;
192	}
193	first = 1;
194	while ((q = getcomponent()) != NULL) {
195		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
196			continue;
197		if (! first)
198			STPUTC('/', p);
199		first = 0;
200		component = q;
201		STPUTS(q, p);
202		if (equal(component, ".."))
203			continue;
204		STACKSTRNUL(p);
205		if (lstat(stackblock(), &statb) < 0) {
206			badstat = 1;
207			break;
208		}
209	}
210
211	INTOFF;
212	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
213		INTON;
214		return (-1);
215	}
216	updatepwd(p);
217	INTON;
218	return (0);
219}
220
221static int
222cdphysical(char *dest)
223{
224	char *p;
225	int rc = 0;
226
227	INTOFF;
228	if (chdir(dest) < 0) {
229		INTON;
230		return (-1);
231	}
232	p = findcwd(NULL);
233	if (p == NULL) {
234		warning("warning: failed to get name of current directory");
235		rc = 1;
236	}
237	updatepwd(p);
238	INTON;
239	return (rc);
240}
241
242/*
243 * Get the next component of the path name pointed to by cdcomppath.
244 * This routine overwrites the string pointed to by cdcomppath.
245 */
246static char *
247getcomponent(void)
248{
249	char *p;
250	char *start;
251
252	if ((p = cdcomppath) == NULL)
253		return NULL;
254	start = cdcomppath;
255	while (*p != '/' && *p != '\0')
256		p++;
257	if (*p == '\0') {
258		cdcomppath = NULL;
259	} else {
260		*p++ = '\0';
261		cdcomppath = p;
262	}
263	return start;
264}
265
266
267static char *
268findcwd(char *dir)
269{
270	char *new;
271	char *p;
272
273	/*
274	 * If our argument is NULL, we don't know the current directory
275	 * any more because we traversed a symbolic link or something
276	 * we couldn't stat().
277	 */
278	if (dir == NULL || curdir == NULL)
279		return getpwd2();
280	cdcomppath = stalloc(strlen(dir) + 1);
281	scopy(dir, cdcomppath);
282	STARTSTACKSTR(new);
283	if (*dir != '/') {
284		STPUTS(curdir, new);
285		if (STTOPC(new) == '/')
286			STUNPUTC(new);
287	}
288	while ((p = getcomponent()) != NULL) {
289		if (equal(p, "..")) {
290			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
291		} else if (*p != '\0' && ! equal(p, ".")) {
292			STPUTC('/', new);
293			STPUTS(p, new);
294		}
295	}
296	if (new == stackblock())
297		STPUTC('/', new);
298	STACKSTRNUL(new);
299	return stackblock();
300}
301
302/*
303 * Update curdir (the name of the current directory) in response to a
304 * cd command.  We also call hashcd to let the routines in exec.c know
305 * that the current directory has changed.
306 */
307static void
308updatepwd(char *dir)
309{
310	hashcd();				/* update command hash table */
311
312	if (prevdir)
313		ckfree(prevdir);
314	prevdir = curdir;
315	curdir = dir ? savestr(dir) : NULL;
316	setvar("PWD", curdir, VEXPORT);
317	setvar("OLDPWD", prevdir, VEXPORT);
318}
319
320int
321pwdcmd(int argc, char **argv)
322{
323	char *p;
324	int ch, phys;
325
326	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
327	phys = Pflag;
328	while ((ch = getopt(argc, argv, "LP")) != -1) {
329		switch (ch) {
330		case 'L':
331			phys = 0;
332			break;
333		case 'P':
334			phys = 1;
335			break;
336		default:
337			error("unknown option: -%c", optopt);
338			break;
339		}
340	}
341	argc -= optind;
342	argv += optind;
343
344	if (argc != 0)
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