Home | History | Annotate | Line # | Download | only in sh
cd.c revision 1.16
      1 /*	$NetBSD: cd.c,v 1.16 1996/06/25 16:40:06 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.16 1996/06/25 16:40:06 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 <unistd.h>
     51 #include <errno.h>
     52 
     53 /*
     54  * The cd and pwd commands.
     55  */
     56 
     57 #include "shell.h"
     58 #include "var.h"
     59 #include "nodes.h"	/* for jobs.h */
     60 #include "jobs.h"
     61 #include "options.h"
     62 #include "output.h"
     63 #include "memalloc.h"
     64 #include "error.h"
     65 #include "exec.h"
     66 #include "redir.h"
     67 #include "mystring.h"
     68 #include "show.h"
     69 #include "cd.h"
     70 
     71 STATIC int docd __P((char *, int));
     72 STATIC char *getcomponent __P((void));
     73 STATIC void updatepwd __P((char *));
     74 
     75 char *curdir = NULL;		/* current working directory */
     76 char *prevdir;			/* previous working directory */
     77 STATIC char *cdcomppath;
     78 
     79 int
     80 cdcmd(argc, argv)
     81 	int argc;
     82 	char **argv;
     83 {
     84 	char *dest;
     85 	char *path;
     86 	char *p;
     87 	struct stat statb;
     88 	int print = 0;
     89 
     90 	nextopt(nullstr);
     91 	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
     92 		error("HOME not set");
     93 	if (dest[0] == '-' && dest[1] == '\0') {
     94 		dest = prevdir ? prevdir : curdir;
     95 		print = 1;
     96 	}
     97 	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
     98 		path = nullstr;
     99 	while ((p = padvance(&path, dest)) != NULL) {
    100 		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
    101 			if (!print) {
    102 				/*
    103 				 * XXX - rethink
    104 				 */
    105 				if (p[0] == '.' && p[1] == '/')
    106 					p += 2;
    107 				print = strcmp(p, dest);
    108 			}
    109 			if (docd(p, print) >= 0)
    110 				return 0;
    111 
    112 		}
    113 	}
    114 	error("can't cd to %s", dest);
    115 	/*NOTREACHED*/
    116 	return 0;
    117 }
    118 
    119 
    120 /*
    121  * Actually do the chdir.  In an interactive shell, print the
    122  * directory name if "print" is nonzero.
    123  */
    124 
    125 STATIC int
    126 docd(dest, print)
    127 	char *dest;
    128 {
    129 
    130 	TRACE(("docd(\"%s\", %d) called\n", dest, print));
    131 	INTOFF;
    132 	if (chdir(dest) < 0) {
    133 		INTON;
    134 		return -1;
    135 	}
    136 	updatepwd(dest);
    137 	INTON;
    138 	if (print && iflag)
    139 		out1fmt("%s\n", stackblock());
    140 	return 0;
    141 }
    142 
    143 
    144 /*
    145  * Get the next component of the path name pointed to by cdcomppath.
    146  * This routine overwrites the string pointed to by cdcomppath.
    147  */
    148 
    149 STATIC char *
    150 getcomponent() {
    151 	register char *p;
    152 	char *start;
    153 
    154 	if ((p = cdcomppath) == NULL)
    155 		return NULL;
    156 	start = cdcomppath;
    157 	while (*p != '/' && *p != '\0')
    158 		p++;
    159 	if (*p == '\0') {
    160 		cdcomppath = NULL;
    161 	} else {
    162 		*p++ = '\0';
    163 		cdcomppath = p;
    164 	}
    165 	return start;
    166 }
    167 
    168 
    169 
    170 /*
    171  * Update curdir (the name of the current directory) in response to a
    172  * cd command.  We also call hashcd to let the routines in exec.c know
    173  * that the current directory has changed.
    174  */
    175 
    176 void hashcd();
    177 
    178 STATIC void
    179 updatepwd(dir)
    180 	char *dir;
    181 	{
    182 	char *new;
    183 	char *p;
    184 
    185 	hashcd();				/* update command hash table */
    186 	cdcomppath = stalloc(strlen(dir) + 1);
    187 	scopy(dir, cdcomppath);
    188 	STARTSTACKSTR(new);
    189 	if (*dir != '/') {
    190 		if (curdir == NULL)
    191 			return;
    192 		p = curdir;
    193 		while (*p)
    194 			STPUTC(*p++, new);
    195 		if (p[-1] == '/')
    196 			STUNPUTC(new);
    197 	}
    198 	while ((p = getcomponent()) != NULL) {
    199 		if (equal(p, "..")) {
    200 			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
    201 		} else if (*p != '\0' && ! equal(p, ".")) {
    202 			STPUTC('/', new);
    203 			while (*p)
    204 				STPUTC(*p++, new);
    205 		}
    206 	}
    207 	if (new == stackblock())
    208 		STPUTC('/', new);
    209 	STACKSTRNUL(new);
    210 	INTOFF;
    211 	if (prevdir)
    212 		ckfree(prevdir);
    213 	prevdir = curdir;
    214 	curdir = savestr(stackblock());
    215 	INTON;
    216 }
    217 
    218 
    219 
    220 int
    221 pwdcmd(argc, argv)
    222 	int argc;
    223 	char **argv;
    224 {
    225 	getpwd();
    226 	out1str(curdir);
    227 	out1c('\n');
    228 	return 0;
    229 }
    230 
    231 
    232 
    233 
    234 #define MAXPWD 256
    235 
    236 /*
    237  * Find out what the current directory is. If we already know the current
    238  * directory, this routine returns immediately.
    239  */
    240 void
    241 getpwd()
    242 {
    243 	char buf[MAXPWD];
    244 
    245 	if (curdir)
    246 		return;
    247 	/*
    248 	 * Things are a bit complicated here; we could have just used
    249 	 * getcwd, but traditionally getcwd is implemented using popen
    250 	 * to /bin/pwd. This creates a problem for us, since we cannot
    251 	 * keep track of the job if it is being ran behind our backs.
    252 	 * So we re-implement getcwd(), and we suppress interrupts
    253 	 * throughout the process. This is not completely safe, since
    254 	 * the user can still break out of it by killing the pwd program.
    255 	 * We still try to use getcwd for systems that we know have a
    256 	 * c implementation of getcwd, that does not open a pipe to
    257 	 * /bin/pwd.
    258 	 */
    259 #if defined(__NetBSD__) || defined(__svr4__)
    260 	if (getcwd(buf, sizeof(buf)) == NULL)
    261 		error("getcwd() failed");
    262 	curdir = savestr(buf);
    263 #else
    264 	{
    265 		char *p;
    266 		int i;
    267 		int status;
    268 		struct job *jp;
    269 		int pip[2];
    270 
    271 		INTOFF;
    272 		if (pipe(pip) < 0)
    273 			error("Pipe call failed");
    274 		jp = makejob((union node *)NULL, 1);
    275 		if (forkshell(jp, (union node *)NULL, FORK_NOJOB) == 0) {
    276 			(void) close(pip[0]);
    277 			if (pip[1] != 1) {
    278 				close(1);
    279 				copyfd(pip[1], 1);
    280 				close(pip[1]);
    281 			}
    282 			(void) execl("/bin/pwd", "pwd", (char *)0);
    283 			error("Cannot exec /bin/pwd");
    284 		}
    285 		(void) close(pip[1]);
    286 		pip[1] = -1;
    287 		p = buf;
    288 		while ((i = read(pip[0], p, buf + MAXPWD - p)) > 0
    289 		     || (i == -1 && errno == EINTR)) {
    290 			if (i > 0)
    291 				p += i;
    292 		}
    293 		(void) close(pip[0]);
    294 		pip[0] = -1;
    295 		status = waitforjob(jp);
    296 		if (status != 0)
    297 			error((char *)0);
    298 		if (i < 0 || p == buf || p[-1] != '\n')
    299 			error("pwd command failed");
    300 		p[-1] = '\0';
    301 	}
    302 	curdir = savestr(buf);
    303 	INTON;
    304 #endif
    305 }
    306