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