xref: /netbsd-src/bin/sh/cd.c (revision fdecd6a253f999ae92b139670d9e15cc9df4497c)
1 /*	$NetBSD: cd.c,v 1.23 1997/07/04 20:59:40 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
43 #else
44 __RCSID("$NetBSD: cd.c,v 1.23 1997/07/04 20:59:40 christos Exp $");
45 #endif
46 #endif /* not lint */
47 
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <errno.h>
54 
55 /*
56  * The cd and pwd commands.
57  */
58 
59 #include "shell.h"
60 #include "var.h"
61 #include "nodes.h"	/* for jobs.h */
62 #include "jobs.h"
63 #include "options.h"
64 #include "output.h"
65 #include "memalloc.h"
66 #include "error.h"
67 #include "exec.h"
68 #include "redir.h"
69 #include "mystring.h"
70 #include "show.h"
71 #include "cd.h"
72 
73 STATIC int docd __P((char *, int));
74 STATIC char *getcomponent __P((void));
75 STATIC void updatepwd __P((char *));
76 
77 char *curdir = NULL;		/* current working directory */
78 char *prevdir;			/* previous working directory */
79 STATIC char *cdcomppath;
80 
81 int
82 cdcmd(argc, argv)
83 	int argc;
84 	char **argv;
85 {
86 	char *dest;
87 	char *path;
88 	char *p;
89 	struct stat statb;
90 	int print = 0;
91 
92 	nextopt(nullstr);
93 	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
94 		error("HOME not set");
95 	if (*dest == '\0')
96 	        dest = ".";
97 	if (dest[0] == '-' && dest[1] == '\0') {
98 		dest = prevdir ? prevdir : curdir;
99 		print = 1;
100 		if (dest)
101 		        print = 1;
102 		else
103 		        dest = ".";
104 	}
105 	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
106 		path = nullstr;
107 	while ((p = padvance(&path, dest)) != NULL) {
108 		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
109 			if (!print) {
110 				/*
111 				 * XXX - rethink
112 				 */
113 				if (p[0] == '.' && p[1] == '/')
114 					p += 2;
115 				print = strcmp(p, dest);
116 			}
117 			if (docd(p, print) >= 0)
118 				return 0;
119 
120 		}
121 	}
122 	error("can't cd to %s", dest);
123 	/*NOTREACHED*/
124 	return 0;
125 }
126 
127 
128 /*
129  * Actually do the chdir.  In an interactive shell, print the
130  * directory name if "print" is nonzero.
131  */
132 
133 STATIC int
134 docd(dest, print)
135 	char *dest;
136 	int print;
137 {
138 	char *p;
139 	char *q;
140 	char *component;
141 	struct stat statb;
142 	int first;
143 	int badstat;
144 
145 	TRACE(("docd(\"%s\", %d) called\n", dest, print));
146 
147 	/*
148 	 *  Check each component of the path. If we find a symlink or
149 	 *  something we can't stat, clear curdir to force a getcwd()
150 	 *  next time we get the value of the current directory.
151 	 */
152 	badstat = 0;
153 	cdcomppath = stalloc(strlen(dest) + 1);
154 	scopy(dest, cdcomppath);
155 	STARTSTACKSTR(p);
156 	if (*dest == '/') {
157 		STPUTC('/', p);
158 		cdcomppath++;
159 	}
160 	first = 1;
161 	while ((q = getcomponent()) != NULL) {
162 		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
163 			continue;
164 		if (! first)
165 			STPUTC('/', p);
166 		first = 0;
167 		component = q;
168 		while (*q)
169 			STPUTC(*q++, p);
170 		if (equal(component, ".."))
171 			continue;
172 		STACKSTRNUL(p);
173 		if ((lstat(stackblock(), &statb) < 0)
174 		    || (S_ISLNK(statb.st_mode)))  {
175 			/* print = 1; */
176 			badstat = 1;
177 			break;
178 		}
179 	}
180 
181 	INTOFF;
182 	if (chdir(dest) < 0) {
183 		INTON;
184 		return -1;
185 	}
186 	updatepwd(badstat ? NULL : dest);
187 	INTON;
188 	if (print && iflag && curdir)
189 		out1fmt("%s\n", curdir);
190 	return 0;
191 }
192 
193 
194 /*
195  * Get the next component of the path name pointed to by cdcomppath.
196  * This routine overwrites the string pointed to by cdcomppath.
197  */
198 
199 STATIC char *
200 getcomponent() {
201 	char *p;
202 	char *start;
203 
204 	if ((p = cdcomppath) == NULL)
205 		return NULL;
206 	start = cdcomppath;
207 	while (*p != '/' && *p != '\0')
208 		p++;
209 	if (*p == '\0') {
210 		cdcomppath = NULL;
211 	} else {
212 		*p++ = '\0';
213 		cdcomppath = p;
214 	}
215 	return start;
216 }
217 
218 
219 
220 /*
221  * Update curdir (the name of the current directory) in response to a
222  * cd command.  We also call hashcd to let the routines in exec.c know
223  * that the current directory has changed.
224  */
225 
226 STATIC void
227 updatepwd(dir)
228 	char *dir;
229 	{
230 	char *new;
231 	char *p;
232 
233 	hashcd();				/* update command hash table */
234 
235 	/*
236 	 * If our argument is NULL, we don't know the current directory
237 	 * any more because we traversed a symbolic link or something
238 	 * we couldn't stat().
239 	 */
240 	if (dir == NULL)  {
241 		if (prevdir)
242 			ckfree(prevdir);
243 		INTOFF;
244 		prevdir = curdir;
245 		curdir = NULL;
246 		getpwd();
247 		INTON;
248 		return;
249 	}
250 
251 	cdcomppath = stalloc(strlen(dir) + 1);
252 	scopy(dir, cdcomppath);
253 	STARTSTACKSTR(new);
254 	if (*dir != '/') {
255 		if (curdir == NULL)
256 			return;
257 		p = curdir;
258 		while (*p)
259 			STPUTC(*p++, new);
260 		if (p[-1] == '/')
261 			STUNPUTC(new);
262 	}
263 	while ((p = getcomponent()) != NULL) {
264 		if (equal(p, "..")) {
265 			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
266 		} else if (*p != '\0' && ! equal(p, ".")) {
267 			STPUTC('/', new);
268 			while (*p)
269 				STPUTC(*p++, new);
270 		}
271 	}
272 	if (new == stackblock())
273 		STPUTC('/', new);
274 	STACKSTRNUL(new);
275 	INTOFF;
276 	if (prevdir)
277 		ckfree(prevdir);
278 	prevdir = curdir;
279 	curdir = savestr(stackblock());
280 	setvar("PWD", curdir, VEXPORT|VTEXTFIXED);
281 	INTON;
282 }
283 
284 
285 
286 int
287 pwdcmd(argc, argv)
288 	int argc;
289 	char **argv;
290 {
291 	getpwd();
292 	out1str(curdir);
293 	out1c('\n');
294 	return 0;
295 }
296 
297 
298 
299 
300 #define MAXPWD 256
301 
302 /*
303  * Find out what the current directory is. If we already know the current
304  * directory, this routine returns immediately.
305  */
306 void
307 getpwd()
308 {
309 	char buf[MAXPWD];
310 
311 	if (curdir)
312 		return;
313 	/*
314 	 * Things are a bit complicated here; we could have just used
315 	 * getcwd, but traditionally getcwd is implemented using popen
316 	 * to /bin/pwd. This creates a problem for us, since we cannot
317 	 * keep track of the job if it is being ran behind our backs.
318 	 * So we re-implement getcwd(), and we suppress interrupts
319 	 * throughout the process. This is not completely safe, since
320 	 * the user can still break out of it by killing the pwd program.
321 	 * We still try to use getcwd for systems that we know have a
322 	 * c implementation of getcwd, that does not open a pipe to
323 	 * /bin/pwd.
324 	 */
325 #if defined(__NetBSD__) || defined(__SVR4)
326 
327 	if (getcwd(buf, sizeof(buf)) == NULL) {
328 		char *pwd = getenv("PWD");
329 		struct stat stdot, stpwd;
330 
331 		if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
332 		    stat(pwd, &stpwd) != -1 &&
333 		    stdot.st_dev == stpwd.st_dev &&
334 		    stdot.st_ino == stpwd.st_ino) {
335 			curdir = savestr(pwd);
336 			return;
337 		}
338 		error("getcwd() failed: %s", strerror(errno));
339 	}
340 	curdir = savestr(buf);
341 #else
342 	{
343 		char *p;
344 		int i;
345 		int status;
346 		struct job *jp;
347 		int pip[2];
348 
349 		INTOFF;
350 		if (pipe(pip) < 0)
351 			error("Pipe call failed");
352 		jp = makejob((union node *)NULL, 1);
353 		if (forkshell(jp, (union node *)NULL, FORK_NOJOB) == 0) {
354 			(void) close(pip[0]);
355 			if (pip[1] != 1) {
356 				close(1);
357 				copyfd(pip[1], 1);
358 				close(pip[1]);
359 			}
360 			(void) execl("/bin/pwd", "pwd", (char *)0);
361 			error("Cannot exec /bin/pwd");
362 		}
363 		(void) close(pip[1]);
364 		pip[1] = -1;
365 		p = buf;
366 		while ((i = read(pip[0], p, buf + MAXPWD - p)) > 0
367 		     || (i == -1 && errno == EINTR)) {
368 			if (i > 0)
369 				p += i;
370 		}
371 		(void) close(pip[0]);
372 		pip[0] = -1;
373 		status = waitforjob(jp);
374 		if (status != 0)
375 			error((char *)0);
376 		if (i < 0 || p == buf || p[-1] != '\n')
377 			error("pwd command failed");
378 		p[-1] = '\0';
379 	}
380 	curdir = savestr(buf);
381 	INTON;
382 #endif
383 }
384