xref: /freebsd/bin/sh/cd.c (revision 4f0a4502a1f33fef287ac558c98e5ef99a32216f)
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
35 static char sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
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 
68 static int cdlogical(char *);
69 static int cdphysical(char *);
70 static int docd(char *, int, int);
71 static char *getcomponent(void);
72 static char *findcwd(char *);
73 static void updatepwd(char *);
74 static char *getpwd(void);
75 static char *getpwd2(void);
76 
77 static char *curdir = NULL;	/* current working directory */
78 static char *cdcomppath;
79 
80 int
81 cdcmd(int argc __unused, char **argv __unused)
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 	phys = Pflag;
92 	while ((ch = nextopt("eLP")) != '\0') {
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 		}
104 	}
105 
106 	if (*argptr != NULL && argptr[1] != NULL)
107 		error("too many arguments");
108 
109 	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
110 		error("HOME not set");
111 	if (*dest == '\0')
112 		dest = ".";
113 	if (dest[0] == '-' && dest[1] == '\0') {
114 		dest = bltinlookup("OLDPWD", 1);
115 		if (dest == NULL)
116 			error("OLDPWD not set");
117 		print = 1;
118 	}
119 	if (dest[0] == '/' ||
120 	    (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
121 	    (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
122 	    (path = bltinlookup("CDPATH", 1)) == NULL)
123 		path = "";
124 	while ((p = padvance(&path, dest)) != NULL) {
125 		if (stat(p, &statb) < 0) {
126 			if (errno != ENOENT)
127 				errno1 = errno;
128 		} else if (!S_ISDIR(statb.st_mode))
129 			errno1 = ENOTDIR;
130 		else {
131 			if (!print) {
132 				/*
133 				 * XXX - rethink
134 				 */
135 				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
136 					print = strcmp(p + 2, dest);
137 				else
138 					print = strcmp(p, dest);
139 			}
140 			rc = docd(p, print, phys);
141 			if (rc >= 0)
142 				return getcwderr ? rc : 0;
143 			if (errno != ENOENT)
144 				errno1 = errno;
145 		}
146 	}
147 	error("%s: %s", dest, strerror(errno1));
148 	/*NOTREACHED*/
149 	return 0;
150 }
151 
152 
153 /*
154  * Actually change the directory.  In an interactive shell, print the
155  * directory name if "print" is nonzero.
156  */
157 static int
158 docd(char *dest, int print, int phys)
159 {
160 	int rc;
161 
162 	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
163 
164 	/* If logical cd fails, fall back to physical. */
165 	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
166 		return (-1);
167 
168 	if (print && iflag && curdir)
169 		out1fmt("%s\n", curdir);
170 
171 	return (rc);
172 }
173 
174 static int
175 cdlogical(char *dest)
176 {
177 	char *p;
178 	char *q;
179 	char *component;
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 	cdcomppath = stsavestr(dest);
191 	STARTSTACKSTR(p);
192 	if (*dest == '/') {
193 		STPUTC('/', p);
194 		cdcomppath++;
195 	}
196 	first = 1;
197 	while ((q = getcomponent()) != 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 
224 static int
225 cdphysical(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 cdcomppath.
247  * This routine overwrites the string pointed to by cdcomppath.
248  */
249 static char *
250 getcomponent(void)
251 {
252 	char *p;
253 	char *start;
254 
255 	if ((p = cdcomppath) == NULL)
256 		return NULL;
257 	start = cdcomppath;
258 	while (*p != '/' && *p != '\0')
259 		p++;
260 	if (*p == '\0') {
261 		cdcomppath = NULL;
262 	} else {
263 		*p++ = '\0';
264 		cdcomppath = p;
265 	}
266 	return start;
267 }
268 
269 
270 static char *
271 findcwd(char *dir)
272 {
273 	char *new;
274 	char *p;
275 
276 	/*
277 	 * If our argument is NULL, we don't know the current directory
278 	 * any more because we traversed a symbolic link or something
279 	 * we couldn't stat().
280 	 */
281 	if (dir == NULL || curdir == NULL)
282 		return getpwd2();
283 	cdcomppath = stsavestr(dir);
284 	STARTSTACKSTR(new);
285 	if (*dir != '/') {
286 		STPUTS(curdir, new);
287 		if (STTOPC(new) == '/')
288 			STUNPUTC(new);
289 	}
290 	while ((p = getcomponent()) != NULL) {
291 		if (equal(p, "..")) {
292 			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
293 		} else if (*p != '\0' && ! equal(p, ".")) {
294 			STPUTC('/', new);
295 			STPUTS(p, new);
296 		}
297 	}
298 	if (new == stackblock())
299 		STPUTC('/', new);
300 	STACKSTRNUL(new);
301 	return stackblock();
302 }
303 
304 /*
305  * Update curdir (the name of the current directory) in response to a
306  * cd command.  We also call hashcd to let the routines in exec.c know
307  * that the current directory has changed.
308  */
309 static void
310 updatepwd(char *dir)
311 {
312 	char *prevdir;
313 
314 	hashcd();				/* update command hash table */
315 
316 	setvar("PWD", dir, VEXPORT);
317 	setvar("OLDPWD", curdir, VEXPORT);
318 	prevdir = curdir;
319 	curdir = dir ? savestr(dir) : NULL;
320 	ckfree(prevdir);
321 }
322 
323 int
324 pwdcmd(int argc __unused, char **argv __unused)
325 {
326 	char *p;
327 	int ch, phys;
328 
329 	phys = Pflag;
330 	while ((ch = nextopt("LP")) != '\0') {
331 		switch (ch) {
332 		case 'L':
333 			phys = 0;
334 			break;
335 		case 'P':
336 			phys = 1;
337 			break;
338 		}
339 	}
340 
341 	if (*argptr != NULL)
342 		error("too many arguments");
343 
344 	if (!phys && getpwd()) {
345 		out1str(curdir);
346 		out1c('\n');
347 	} else {
348 		if ((p = getpwd2()) == NULL)
349 			error(".: %s", strerror(errno));
350 		out1str(p);
351 		out1c('\n');
352 	}
353 
354 	return 0;
355 }
356 
357 /*
358  * Get the current directory and cache the result in curdir.
359  */
360 static char *
361 getpwd(void)
362 {
363 	char *p;
364 
365 	if (curdir)
366 		return curdir;
367 
368 	p = getpwd2();
369 	if (p != NULL)
370 		curdir = savestr(p);
371 
372 	return curdir;
373 }
374 
375 #define MAXPWD 256
376 
377 /*
378  * Return the current directory.
379  */
380 static char *
381 getpwd2(void)
382 {
383 	char *pwd;
384 	int i;
385 
386 	for (i = MAXPWD;; i *= 2) {
387 		pwd = stalloc(i);
388 		if (getcwd(pwd, i) != NULL)
389 			return pwd;
390 		stunalloc(pwd);
391 		if (errno != ERANGE)
392 			break;
393 	}
394 
395 	return NULL;
396 }
397 
398 /*
399  * Initialize PWD in a new shell.
400  * If the shell is interactive, we need to warn if this fails.
401  */
402 void
403 pwd_init(int warn)
404 {
405 	char *pwd;
406 	struct stat stdot, stpwd;
407 
408 	pwd = lookupvar("PWD");
409 	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
410 	    stat(pwd, &stpwd) != -1 &&
411 	    stdot.st_dev == stpwd.st_dev &&
412 	    stdot.st_ino == stpwd.st_ino) {
413 		if (curdir)
414 			ckfree(curdir);
415 		curdir = savestr(pwd);
416 	}
417 	if (getpwd() == NULL && warn)
418 		out2fmt_flush("sh: cannot determine working directory\n");
419 	setvar("PWD", curdir, VEXPORT);
420 }
421