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