Home | History | Annotate | Line # | Download | only in sh
cd.c revision 1.1
      1 /*-
      2  * Copyright (c) 1991 The Regents of the University of California.
      3  * All rights reserved.
      4  *
      5  * This code is derived from software contributed to Berkeley by
      6  * Kenneth Almquist.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. All advertising materials mentioning features or use of this software
     17  *    must display the following acknowledgement:
     18  *	This product includes software developed by the University of
     19  *	California, Berkeley and its contributors.
     20  * 4. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  */
     36 
     37 #ifndef lint
     38 static char sccsid[] = "@(#)cd.c	5.2 (Berkeley) 3/13/91";
     39 #endif /* not lint */
     40 
     41 /*
     42  * The cd and pwd commands.
     43  */
     44 
     45 #include "shell.h"
     46 #include "var.h"
     47 #include "nodes.h"	/* for jobs.h */
     48 #include "jobs.h"
     49 #include "options.h"
     50 #include "output.h"
     51 #include "memalloc.h"
     52 #include "error.h"
     53 #include "mystring.h"
     54 #include <sys/types.h>
     55 #include <sys/stat.h>
     56 #include <errno.h>
     57 
     58 
     59 #ifdef __STDC__
     60 STATIC int docd(char *, int);
     61 STATIC void updatepwd(char *);
     62 STATIC void getpwd(void);
     63 STATIC char *getcomponent(void);
     64 #else
     65 STATIC int docd();
     66 STATIC void updatepwd();
     67 STATIC void getpwd();
     68 STATIC char *getcomponent();
     69 #endif
     70 
     71 
     72 char *curdir;			/* current working directory */
     73 STATIC char *cdcomppath;
     74 
     75 #if UDIR
     76 extern int didudir;		/* set if /u/logname expanded */
     77 #endif
     78 
     79 
     80 int
     81 cdcmd(argc, argv)  char **argv; {
     82 	char *dest;
     83 	char *path;
     84 	char *p;
     85 	struct stat statb;
     86 	char *padvance();
     87 
     88 	nextopt(nullstr);
     89 	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
     90 		error("HOME not set");
     91 	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
     92 		path = nullstr;
     93 	while ((p = padvance(&path, dest)) != NULL) {
     94 		if (stat(p, &statb) >= 0
     95 		 && (statb.st_mode & S_IFMT) == S_IFDIR
     96 		 && docd(p, strcmp(p, dest)) >= 0)
     97 			return 0;
     98 	}
     99 	error("can't cd to %s", dest);
    100 }
    101 
    102 
    103 /*
    104  * Actually do the chdir.  If the name refers to symbolic links, we
    105  * compute the actual directory name before doing the cd.  In an
    106  * interactive shell, print the directory name if "print" is nonzero
    107  * or if the name refers to a symbolic link.  We also print the name
    108  * if "/u/logname" was expanded in it, since this is similar to a
    109  * symbolic link.  (The check for this breaks if the user gives the
    110  * cd command some additional, unused arguments.)
    111  */
    112 
    113 #if SYMLINKS == 0
    114 STATIC int
    115 docd(dest, print)
    116 	char *dest;
    117 	{
    118 #if UDIR
    119 	if (didudir)
    120 		print = 1;
    121 #endif
    122 	INTOFF;
    123 	if (chdir(dest) < 0) {
    124 		INTON;
    125 		return -1;
    126 	}
    127 	updatepwd(dest);
    128 	INTON;
    129 #ifdef not
    130 	if (print && iflag)
    131 		out1fmt("%s\n", stackblock());
    132 #endif
    133 	return 0;
    134 }
    135 
    136 #else
    137 
    138 
    139 
    140 STATIC int
    141 docd(dest, print)
    142 	char *dest;
    143 	{
    144 	register char *p;
    145 	register char *q;
    146 	char *symlink;
    147 	char *component;
    148 	struct stat statb;
    149 	int first;
    150 	int i;
    151 
    152 	TRACE(("docd(\"%s\", %d) called\n", dest, print));
    153 #if UDIR
    154 	if (didudir)
    155 		print = 1;
    156 #endif
    157 
    158 top:
    159 	cdcomppath = dest;
    160 	STARTSTACKSTR(p);
    161 	if (*dest == '/') {
    162 		STPUTC('/', p);
    163 		cdcomppath++;
    164 	}
    165 	first = 1;
    166 	while ((q = getcomponent()) != NULL) {
    167 		if (q[0] == '\0' || q[0] == '.' && q[1] == '\0')
    168 			continue;
    169 		if (! first)
    170 			STPUTC('/', p);
    171 		first = 0;
    172 		component = q;
    173 		while (*q)
    174 			STPUTC(*q++, p);
    175 		if (equal(component, ".."))
    176 			continue;
    177 		STACKSTRNUL(p);
    178 		if (lstat(stackblock(), &statb) < 0)
    179 			error("lstat %s failed", stackblock());
    180 		if ((statb.st_mode & S_IFMT) != S_IFLNK)
    181 			continue;
    182 
    183 		/* Hit a symbolic link.  We have to start all over again. */
    184 		print = 1;
    185 		STPUTC('\0', p);
    186 		symlink = grabstackstr(p);
    187 		i = (int)statb.st_size + 2;		/* 2 for '/' and '\0' */
    188 		if (cdcomppath != NULL)
    189 			i += strlen(cdcomppath);
    190 		p = stalloc(i);
    191 		if (readlink(symlink, p, (int)statb.st_size) < 0) {
    192 			error("readlink %s failed", stackblock());
    193 		}
    194 		if (cdcomppath != NULL) {
    195 			p[(int)statb.st_size] = '/';
    196 			scopy(cdcomppath, p + (int)statb.st_size + 1);
    197 		} else {
    198 			p[(int)statb.st_size] = '\0';
    199 		}
    200 		if (p[0] != '/') {	/* relative path name */
    201 			char *r;
    202 			q = r = symlink;
    203 			while (*q) {
    204 				if (*q++ == '/')
    205 					r = q;
    206 			}
    207 			*r = '\0';
    208 			dest = stalloc(strlen(symlink) + strlen(p) + 1);
    209 			scopy(symlink, dest);
    210 			strcat(dest, p);
    211 		} else {
    212 			dest = p;
    213 		}
    214 		goto top;
    215 	}
    216 	STPUTC('\0', p);
    217 	p = grabstackstr(p);
    218 	INTOFF;
    219 	if (chdir(p) < 0) {
    220 		INTON;
    221 		return -1;
    222 	}
    223 	updatepwd(p);
    224 	INTON;
    225 #ifdef not
    226 	if (print && iflag)
    227 		out1fmt("%s\n", p);
    228 #endif
    229 	return 0;
    230 }
    231 #endif /* SYMLINKS */
    232 
    233 
    234 
    235 /*
    236  * Get the next component of the path name pointed to by cdcomppath.
    237  * This routine overwrites the string pointed to by cdcomppath.
    238  */
    239 
    240 STATIC char *
    241 getcomponent() {
    242 	register char *p;
    243 	char *start;
    244 
    245 	if ((p = cdcomppath) == NULL)
    246 		return NULL;
    247 	start = cdcomppath;
    248 	while (*p != '/' && *p != '\0')
    249 		p++;
    250 	if (*p == '\0') {
    251 		cdcomppath = NULL;
    252 	} else {
    253 		*p++ = '\0';
    254 		cdcomppath = p;
    255 	}
    256 	return start;
    257 }
    258 
    259 
    260 
    261 /*
    262  * Update curdir (the name of the current directory) in response to a
    263  * cd command.  We also call hashcd to let the routines in exec.c know
    264  * that the current directory has changed.
    265  */
    266 
    267 void hashcd();
    268 
    269 STATIC void
    270 updatepwd(dir)
    271 	char *dir;
    272 	{
    273 	char *new;
    274 	char *p;
    275 
    276 	hashcd();				/* update command hash table */
    277 	cdcomppath = stalloc(strlen(dir) + 1);
    278 	scopy(dir, cdcomppath);
    279 	STARTSTACKSTR(new);
    280 	if (*dir != '/') {
    281 		if (curdir == NULL)
    282 			return;
    283 		p = curdir;
    284 		while (*p)
    285 			STPUTC(*p++, new);
    286 		if (p[-1] == '/')
    287 			STUNPUTC(new);
    288 	}
    289 	while ((p = getcomponent()) != NULL) {
    290 		if (equal(p, "..")) {
    291 			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
    292 		} else if (*p != '\0' && ! equal(p, ".")) {
    293 			STPUTC('/', new);
    294 			while (*p)
    295 				STPUTC(*p++, new);
    296 		}
    297 	}
    298 	if (new == stackblock())
    299 		STPUTC('/', new);
    300 	STACKSTRNUL(new);
    301 	if (curdir)
    302 		ckfree(curdir);
    303 	curdir = savestr(stackblock());
    304 }
    305 
    306 
    307 
    308 int
    309 pwdcmd(argc, argv)  char **argv; {
    310 	getpwd();
    311 	out1str(curdir);
    312 	out1c('\n');
    313 	return 0;
    314 }
    315 
    316 
    317 
    318 /*
    319  * Run /bin/pwd to find out what the current directory is.  We suppress
    320  * interrupts throughout most of this, but the user can still break out
    321  * of it by killing the pwd program.  If we already know the current
    322  * directory, this routine returns immediately.
    323  */
    324 
    325 #define MAXPWD 256
    326 
    327 STATIC void
    328 getpwd() {
    329 	char buf[MAXPWD];
    330 	char *p;
    331 	int i;
    332 	int status;
    333 	struct job *jp;
    334 	int pip[2];
    335 
    336 	if (curdir)
    337 		return;
    338 	INTOFF;
    339 	if (pipe(pip) < 0)
    340 		error("Pipe call failed");
    341 	jp = makejob((union node *)NULL, 1);
    342 	if (forkshell(jp, (union node *)NULL, FORK_NOJOB) == 0) {
    343 		close(pip[0]);
    344 		if (pip[1] != 1) {
    345 			close(1);
    346 			copyfd(pip[1], 1);
    347 			close(pip[1]);
    348 		}
    349 		execl("/bin/pwd", "pwd", (char *)0);
    350 		error("Cannot exec /bin/pwd");
    351 	}
    352 	close(pip[1]);
    353 	pip[1] = -1;
    354 	p = buf;
    355 	while ((i = read(pip[0], p, buf + MAXPWD - p)) > 0
    356 	     || i == -1 && errno == EINTR) {
    357 		if (i > 0)
    358 			p += i;
    359 	}
    360 	close(pip[0]);
    361 	pip[0] = -1;
    362 	status = waitforjob(jp);
    363 	if (status != 0)
    364 		error((char *)0);
    365 	if (i < 0 || p == buf || p[-1] != '\n')
    366 		error("pwd command failed");
    367 	p[-1] = '\0';
    368 	curdir = savestr(buf);
    369 	INTON;
    370 }
    371