Home | History | Annotate | Line # | Download | only in sh
cd.c revision 1.38
      1 /*	$NetBSD: cd.c,v 1.38 2005/11/26 21:44:43 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.38 2005/11/26 21:44:43 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(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(0);
    339 	setvar("PWD", curdir, VEXPORT);
    340 }
    341 
    342 #define MAXPWD 256
    343 
    344 /*
    345  * Find out what the current directory is. If we already know the current
    346  * directory, this routine returns immediately.
    347  */
    348 void
    349 getpwd(int noerror)
    350 {
    351 	char *pwd;
    352 	struct stat stdot, stpwd;
    353 	static int first = 1;
    354 
    355 	if (curdir)
    356 		return;
    357 
    358 	if (first) {
    359 		first = 0;
    360 		pwd = getenv("PWD");
    361 		if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
    362 		    stat(pwd, &stpwd) != -1 &&
    363 		    stdot.st_dev == stpwd.st_dev &&
    364 		    stdot.st_ino == stpwd.st_ino) {
    365 			curdir = savestr(pwd);
    366 			return;
    367 		}
    368 	}
    369 
    370 	find_curdir(noerror);
    371 
    372 	return;
    373 }
    374 
    375 STATIC void
    376 find_curdir(int noerror)
    377 {
    378 	int i;
    379 	char *pwd;
    380 
    381 	/*
    382 	 * Things are a bit complicated here; we could have just used
    383 	 * getcwd, but traditionally getcwd is implemented using popen
    384 	 * to /bin/pwd. This creates a problem for us, since we cannot
    385 	 * keep track of the job if it is being ran behind our backs.
    386 	 * So we re-implement getcwd(), and we suppress interrupts
    387 	 * throughout the process. This is not completely safe, since
    388 	 * the user can still break out of it by killing the pwd program.
    389 	 * We still try to use getcwd for systems that we know have a
    390 	 * c implementation of getcwd, that does not open a pipe to
    391 	 * /bin/pwd.
    392 	 */
    393 #if defined(__NetBSD__) || defined(__SVR4)
    394 
    395 	for (i = MAXPWD;; i *= 2) {
    396 		pwd = stalloc(i);
    397 		if (getcwd(pwd, i) != NULL) {
    398 			curdir = savestr(pwd);
    399 			return;
    400 		}
    401 		stunalloc(pwd);
    402 		if (errno == ERANGE)
    403 			continue;
    404 		if (!noerror)
    405 			error("getcwd() failed: %s", strerror(errno));
    406 		return;
    407 	}
    408 #else
    409 	{
    410 		char *p;
    411 		int status;
    412 		struct job *jp;
    413 		int pip[2];
    414 
    415 		pwd = stalloc(MAXPWD);
    416 		INTOFF;
    417 		if (pipe(pip) < 0)
    418 			error("Pipe call failed");
    419 		jp = makejob((union node *)NULL, 1);
    420 		if (forkshell(jp, (union node *)NULL, FORK_NOJOB) == 0) {
    421 			(void) close(pip[0]);
    422 			if (pip[1] != 1) {
    423 				close(1);
    424 				copyfd(pip[1], 1);
    425 				close(pip[1]);
    426 			}
    427 			(void) execl("/bin/pwd", "pwd", (char *)0);
    428 			error("Cannot exec /bin/pwd");
    429 		}
    430 		(void) close(pip[1]);
    431 		pip[1] = -1;
    432 		p = pwd;
    433 		while ((i = read(pip[0], p, pwd + MAXPWD - p)) > 0
    434 		     || (i == -1 && errno == EINTR)) {
    435 			if (i > 0)
    436 				p += i;
    437 		}
    438 		(void) close(pip[0]);
    439 		pip[0] = -1;
    440 		status = waitforjob(jp);
    441 		if (status != 0)
    442 			error((char *)0);
    443 		if (i < 0 || p == pwd || p[-1] != '\n') {
    444 			if (noerror) {
    445 				INTON;
    446 				return;
    447 			}
    448 			error("pwd command failed");
    449 		}
    450 		p[-1] = '\0';
    451 		INTON;
    452 		curdir = savestr(pwd);
    453 		return;
    454 	}
    455 #endif
    456 }
    457