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