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