1 /* $NetBSD: cd.c,v 1.39 2006/05/04 11:16:53 simonb 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.39 2006/05/04 11:16:53 simonb 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(const char *, int); 70 STATIC char *getcomponent(void); 71 STATIC void updatepwd(const char *); 72 STATIC void find_curdir(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, *p; 83 char *d; 84 struct stat statb; 85 int print = cdprint; /* set -cdprint to enable */ 86 87 nextopt(nullstr); 88 89 /* 90 * Try (quite hard) to have 'curdir' defined, nothing has set 91 * it on entry to the shell, but we want 'cd fred; cd -' to work. 92 */ 93 getpwd(1); 94 dest = *argptr; 95 if (dest == NULL) { 96 dest = bltinlookup("HOME", 1); 97 if (dest == NULL) 98 error("HOME not set"); 99 } else { 100 if (argptr[1]) { 101 /* Do 'ksh' style substitution */ 102 if (!curdir) 103 error("PWD not set"); 104 p = strstr(curdir, dest); 105 if (!p) 106 error("bad substitution"); 107 d = stalloc(strlen(curdir) + strlen(argptr[1]) + 1); 108 memcpy(d, curdir, p - curdir); 109 strcpy(d + (p - curdir), argptr[1]); 110 strcat(d, p + strlen(dest)); 111 dest = d; 112 print = 1; 113 } 114 } 115 116 if (dest[0] == '-' && dest[1] == '\0') { 117 dest = prevdir ? prevdir : curdir; 118 print = 1; 119 } 120 if (*dest == '\0') 121 dest = "."; 122 p = dest; 123 if (*p == '.' && *++p == '.') 124 p++; 125 if (*p == 0 || *p == '/' || (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 if (docd(p, print) >= 0) 139 return 0; 140 141 } 142 } 143 error("can't cd to %s", dest); 144 /* NOTREACHED */ 145 } 146 147 148 /* 149 * Actually do the chdir. In an interactive shell, print the 150 * directory name if "print" is nonzero. 151 */ 152 153 STATIC int 154 docd(const char *dest, int print) 155 { 156 char *p; 157 char *q; 158 char *component; 159 struct stat statb; 160 int first; 161 int badstat; 162 163 TRACE(("docd(\"%s\", %d) called\n", dest, print)); 164 165 /* 166 * Check each component of the path. If we find a symlink or 167 * something we can't stat, clear curdir to force a getcwd() 168 * next time we get the value of the current directory. 169 */ 170 badstat = 0; 171 cdcomppath = stalloc(strlen(dest) + 1); 172 scopy(dest, cdcomppath); 173 STARTSTACKSTR(p); 174 if (*dest == '/') { 175 STPUTC('/', p); 176 cdcomppath++; 177 } 178 first = 1; 179 while ((q = getcomponent()) != NULL) { 180 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0')) 181 continue; 182 if (! first) 183 STPUTC('/', p); 184 first = 0; 185 component = q; 186 while (*q) 187 STPUTC(*q++, p); 188 if (equal(component, "..")) 189 continue; 190 STACKSTRNUL(p); 191 if ((lstat(stackblock(), &statb) < 0) 192 || (S_ISLNK(statb.st_mode))) { 193 /* print = 1; */ 194 badstat = 1; 195 break; 196 } 197 } 198 199 INTOFF; 200 if (chdir(dest) < 0) { 201 INTON; 202 return -1; 203 } 204 updatepwd(badstat ? NULL : dest); 205 INTON; 206 if (print && iflag == 1 && curdir) 207 out1fmt("%s\n", curdir); 208 return 0; 209 } 210 211 212 /* 213 * Get the next component of the path name pointed to by cdcomppath. 214 * This routine overwrites the string pointed to by cdcomppath. 215 */ 216 217 STATIC char * 218 getcomponent(void) 219 { 220 char *p; 221 char *start; 222 223 if ((p = cdcomppath) == NULL) 224 return NULL; 225 start = cdcomppath; 226 while (*p != '/' && *p != '\0') 227 p++; 228 if (*p == '\0') { 229 cdcomppath = NULL; 230 } else { 231 *p++ = '\0'; 232 cdcomppath = p; 233 } 234 return start; 235 } 236 237 238 239 /* 240 * Update curdir (the name of the current directory) in response to a 241 * cd command. We also call hashcd to let the routines in exec.c know 242 * that the current directory has changed. 243 */ 244 245 STATIC void 246 updatepwd(const char *dir) 247 { 248 char *new; 249 char *p; 250 251 hashcd(); /* update command hash table */ 252 253 /* 254 * If our argument is NULL, we don't know the current directory 255 * any more because we traversed a symbolic link or something 256 * we couldn't stat(). 257 */ 258 if (dir == NULL || curdir == NULL) { 259 if (prevdir) 260 ckfree(prevdir); 261 INTOFF; 262 prevdir = curdir; 263 curdir = NULL; 264 getpwd(1); 265 INTON; 266 if (curdir) 267 setvar("PWD", curdir, VEXPORT); 268 else 269 unsetvar("PWD", 0); 270 return; 271 } 272 cdcomppath = stalloc(strlen(dir) + 1); 273 scopy(dir, cdcomppath); 274 STARTSTACKSTR(new); 275 if (*dir != '/') { 276 p = curdir; 277 while (*p) 278 STPUTC(*p++, new); 279 if (p[-1] == '/') 280 STUNPUTC(new); 281 } 282 while ((p = getcomponent()) != NULL) { 283 if (equal(p, "..")) { 284 while (new > stackblock() && (STUNPUTC(new), *new) != '/'); 285 } else if (*p != '\0' && ! equal(p, ".")) { 286 STPUTC('/', new); 287 while (*p) 288 STPUTC(*p++, new); 289 } 290 } 291 if (new == stackblock()) 292 STPUTC('/', new); 293 STACKSTRNUL(new); 294 INTOFF; 295 if (prevdir) 296 ckfree(prevdir); 297 prevdir = curdir; 298 curdir = savestr(stackblock()); 299 setvar("PWD", curdir, VEXPORT); 300 INTON; 301 } 302 303 /* 304 * Posix says the default should be 'pwd -L' (as below), however 305 * the 'cd' command (above) does something much nearer to the 306 * posix 'cd -P' (not the posix default of 'cd -L'). 307 * If 'cd' is changed to support -P/L then the default here 308 * needs to be revisited if the historic behaviour is to be kept. 309 */ 310 311 int 312 pwdcmd(int argc, char **argv) 313 { 314 int i; 315 char opt = 'L'; 316 317 while ((i = nextopt("LP")) != '\0') 318 opt = i; 319 if (*argptr) 320 error("unexpected argument"); 321 322 if (opt == 'L') 323 getpwd(0); 324 else 325 find_curdir(0); 326 327 setvar("PWD", curdir, VEXPORT); 328 out1str(curdir); 329 out1c('\n'); 330 return 0; 331 } 332 333 334 335 void 336 initpwd(void) 337 { 338 getpwd(1); 339 if (curdir) 340 setvar("PWD", curdir, VEXPORT); 341 else 342 sh_warnx("Cannot determine current working directory"); 343 } 344 345 #define MAXPWD 256 346 347 /* 348 * Find out what the current directory is. If we already know the current 349 * directory, this routine returns immediately. 350 */ 351 void 352 getpwd(int noerror) 353 { 354 char *pwd; 355 struct stat stdot, stpwd; 356 static int first = 1; 357 358 if (curdir) 359 return; 360 361 if (first) { 362 first = 0; 363 pwd = getenv("PWD"); 364 if (pwd && *pwd == '/' && stat(".", &stdot) != -1 && 365 stat(pwd, &stpwd) != -1 && 366 stdot.st_dev == stpwd.st_dev && 367 stdot.st_ino == stpwd.st_ino) { 368 curdir = savestr(pwd); 369 return; 370 } 371 } 372 373 find_curdir(noerror); 374 375 return; 376 } 377 378 STATIC void 379 find_curdir(int noerror) 380 { 381 int i; 382 char *pwd; 383 384 /* 385 * Things are a bit complicated here; we could have just used 386 * getcwd, but traditionally getcwd is implemented using popen 387 * to /bin/pwd. This creates a problem for us, since we cannot 388 * keep track of the job if it is being ran behind our backs. 389 * So we re-implement getcwd(), and we suppress interrupts 390 * throughout the process. This is not completely safe, since 391 * the user can still break out of it by killing the pwd program. 392 * We still try to use getcwd for systems that we know have a 393 * c implementation of getcwd, that does not open a pipe to 394 * /bin/pwd. 395 */ 396 #if defined(__NetBSD__) || defined(__SVR4) 397 398 for (i = MAXPWD;; i *= 2) { 399 pwd = stalloc(i); 400 if (getcwd(pwd, i) != NULL) { 401 curdir = savestr(pwd); 402 return; 403 } 404 stunalloc(pwd); 405 if (errno == ERANGE) 406 continue; 407 if (!noerror) 408 error("getcwd() failed: %s", strerror(errno)); 409 return; 410 } 411 #else 412 { 413 char *p; 414 int status; 415 struct job *jp; 416 int pip[2]; 417 418 pwd = stalloc(MAXPWD); 419 INTOFF; 420 if (pipe(pip) < 0) 421 error("Pipe call failed"); 422 jp = makejob((union node *)NULL, 1); 423 if (forkshell(jp, (union node *)NULL, FORK_NOJOB) == 0) { 424 (void) close(pip[0]); 425 if (pip[1] != 1) { 426 close(1); 427 copyfd(pip[1], 1); 428 close(pip[1]); 429 } 430 (void) execl("/bin/pwd", "pwd", (char *)0); 431 error("Cannot exec /bin/pwd"); 432 } 433 (void) close(pip[1]); 434 pip[1] = -1; 435 p = pwd; 436 while ((i = read(pip[0], p, pwd + MAXPWD - p)) > 0 437 || (i == -1 && errno == EINTR)) { 438 if (i > 0) 439 p += i; 440 } 441 (void) close(pip[0]); 442 pip[0] = -1; 443 status = waitforjob(jp); 444 if (status != 0) 445 error((char *)0); 446 if (i < 0 || p == pwd || p[-1] != '\n') { 447 if (noerror) { 448 INTON; 449 return; 450 } 451 error("pwd command failed"); 452 } 453 p[-1] = '\0'; 454 INTON; 455 curdir = savestr(pwd); 456 return; 457 } 458 #endif 459 } 460