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