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