cd.c revision 200956
11556Srgrimes/*-
21556Srgrimes * Copyright (c) 1991, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
41556Srgrimes *
51556Srgrimes * This code is derived from software contributed to Berkeley by
61556Srgrimes * Kenneth Almquist.
71556Srgrimes *
81556Srgrimes * Redistribution and use in source and binary forms, with or without
91556Srgrimes * modification, are permitted provided that the following conditions
101556Srgrimes * are met:
111556Srgrimes * 1. Redistributions of source code must retain the above copyright
121556Srgrimes *    notice, this list of conditions and the following disclaimer.
131556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141556Srgrimes *    notice, this list of conditions and the following disclaimer in the
151556Srgrimes *    documentation and/or other materials provided with the distribution.
161556Srgrimes * 4. Neither the name of the University nor the names of its contributors
171556Srgrimes *    may be used to endorse or promote products derived from this software
181556Srgrimes *    without specific prior written permission.
191556Srgrimes *
201556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301556Srgrimes * SUCH DAMAGE.
311556Srgrimes */
321556Srgrimes
331556Srgrimes#ifndef lint
3436150Scharnier#if 0
3536150Scharnierstatic char sccsid[] = "@(#)cd.c	8.2 (Berkeley) 5/4/95";
3636150Scharnier#endif
371556Srgrimes#endif /* not lint */
3899110Sobrien#include <sys/cdefs.h>
3999110Sobrien__FBSDID("$FreeBSD: head/bin/sh/cd.c 200956 2009-12-24 18:41:14Z jilles $");
401556Srgrimes
4117987Speter#include <sys/types.h>
4217987Speter#include <sys/stat.h>
4317987Speter#include <stdlib.h>
4420425Ssteve#include <string.h>
4517987Speter#include <unistd.h>
4617987Speter#include <errno.h>
47100661Stjr#include <limits.h>
4817987Speter
491556Srgrimes/*
501556Srgrimes * The cd and pwd commands.
511556Srgrimes */
521556Srgrimes
531556Srgrimes#include "shell.h"
541556Srgrimes#include "var.h"
551556Srgrimes#include "nodes.h"	/* for jobs.h */
561556Srgrimes#include "jobs.h"
571556Srgrimes#include "options.h"
581556Srgrimes#include "output.h"
591556Srgrimes#include "memalloc.h"
601556Srgrimes#include "error.h"
6120425Ssteve#include "exec.h"
6217987Speter#include "redir.h"
631556Srgrimes#include "mystring.h"
6417987Speter#include "show.h"
6520425Ssteve#include "cd.h"
661556Srgrimes
6797092StjrSTATIC int cdlogical(char *);
6897092StjrSTATIC int cdphysical(char *);
6997092StjrSTATIC int docd(char *, int, int);
7090111SimpSTATIC char *getcomponent(void);
71176521SstefanfSTATIC char *findcwd(char *);
72176521SstefanfSTATIC void updatepwd(char *);
73199631SstefanfSTATIC char *getpwd2(void);
741556Srgrimes
75117261SddsSTATIC char *curdir = NULL;	/* current working directory */
76117261SddsSTATIC char *prevdir;		/* previous working directory */
771556SrgrimesSTATIC char *cdcomppath;
781556Srgrimes
791556Srgrimesint
8097092Stjrcdcmd(int argc, char **argv)
8117987Speter{
821556Srgrimes	char *dest;
83200956Sjilles	const char *path;
841556Srgrimes	char *p;
851556Srgrimes	struct stat statb;
8697092Stjr	int ch, phys, print = 0;
871556Srgrimes
88100663Stjr	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
89100664Stjr	phys = Pflag;
9097092Stjr	while ((ch = getopt(argc, argv, "LP")) != -1) {
9197092Stjr		switch (ch) {
9297092Stjr		case 'L':
9397092Stjr			phys = 0;
9497092Stjr			break;
9597092Stjr		case 'P':
9697092Stjr			phys = 1;
9797092Stjr			break;
9897092Stjr		default:
9997092Stjr			error("unknown option: -%c", optopt);
10097092Stjr			break;
10197092Stjr		}
10297092Stjr	}
10397092Stjr	argc -= optind;
10497092Stjr	argv += optind;
10597092Stjr
10697092Stjr	if (argc > 1)
10797092Stjr		error("too many arguments");
10897092Stjr
10997092Stjr	if ((dest = *argv) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
1101556Srgrimes		error("HOME not set");
1115234Sbde	if (*dest == '\0')
1125234Sbde		dest = ".";
1131556Srgrimes	if (dest[0] == '-' && dest[1] == '\0') {
1141556Srgrimes		dest = prevdir ? prevdir : curdir;
11512273Speter		if (dest)
11612273Speter			print = 1;
11712273Speter		else
11812273Speter			dest = ".";
1191556Srgrimes	}
1201556Srgrimes	if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
1211556Srgrimes		path = nullstr;
1221556Srgrimes	while ((p = padvance(&path, dest)) != NULL) {
12317987Speter		if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1241556Srgrimes			if (!print) {
1251556Srgrimes				/*
1261556Srgrimes				 * XXX - rethink
1271556Srgrimes				 */
12838886Stegge				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
129159551Sstefanf					print = strcmp(p + 2, dest);
130159551Sstefanf				else
131159551Sstefanf					print = strcmp(p, dest);
1321556Srgrimes			}
13397092Stjr			if (docd(p, print, phys) >= 0)
1341556Srgrimes				return 0;
1351556Srgrimes		}
1361556Srgrimes	}
1371556Srgrimes	error("can't cd to %s", dest);
13817987Speter	/*NOTREACHED*/
13917987Speter	return 0;
1401556Srgrimes}
1411556Srgrimes
1421556Srgrimes
1431556Srgrimes/*
14497092Stjr * Actually change the directory.  In an interactive shell, print the
14520774Ssteve * directory name if "print" is nonzero.
1461556Srgrimes */
1471556SrgrimesSTATIC int
14897092Stjrdocd(char *dest, int print, int phys)
14920425Ssteve{
15097092Stjr
15197092Stjr	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
15297092Stjr
15397092Stjr	/* If logical cd fails, fall back to physical. */
15497092Stjr	if ((phys || cdlogical(dest) < 0) && cdphysical(dest) < 0)
15597092Stjr		return (-1);
15697092Stjr
15797092Stjr	if (print && iflag && curdir)
15897092Stjr		out1fmt("%s\n", curdir);
15997092Stjr
16097092Stjr	return 0;
16197092Stjr}
16297092Stjr
16397092StjrSTATIC int
16497092Stjrcdlogical(char *dest)
16597092Stjr{
16638886Stegge	char *p;
16738886Stegge	char *q;
16838886Stegge	char *component;
16938886Stegge	struct stat statb;
17038886Stegge	int first;
17138886Stegge	int badstat;
17220425Ssteve
17338886Stegge	/*
17438886Stegge	 *  Check each component of the path. If we find a symlink or
17538886Stegge	 *  something we can't stat, clear curdir to force a getcwd()
17638886Stegge	 *  next time we get the value of the current directory.
17738886Stegge	 */
17838886Stegge	badstat = 0;
17938886Stegge	cdcomppath = stalloc(strlen(dest) + 1);
18038886Stegge	scopy(dest, cdcomppath);
18138886Stegge	STARTSTACKSTR(p);
18238886Stegge	if (*dest == '/') {
18338886Stegge		STPUTC('/', p);
18438886Stegge		cdcomppath++;
18538886Stegge	}
18638886Stegge	first = 1;
18738886Stegge	while ((q = getcomponent()) != NULL) {
18838886Stegge		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
18938886Stegge			continue;
19038886Stegge		if (! first)
19138886Stegge			STPUTC('/', p);
19238886Stegge		first = 0;
19338886Stegge		component = q;
19438886Stegge		while (*q)
19538886Stegge			STPUTC(*q++, p);
19638886Stegge		if (equal(component, ".."))
19738886Stegge			continue;
19838886Stegge		STACKSTRNUL(p);
19997092Stjr		if (lstat(stackblock(), &statb) < 0) {
20038886Stegge			badstat = 1;
20138886Stegge			break;
20238886Stegge		}
20338886Stegge	}
20438886Stegge
2051556Srgrimes	INTOFF;
206176521Sstefanf	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
2071556Srgrimes		INTON;
20897092Stjr		return (-1);
2091556Srgrimes	}
210176521Sstefanf	updatepwd(p);
2111556Srgrimes	INTON;
21297092Stjr	return (0);
2131556Srgrimes}
2141556Srgrimes
21597092StjrSTATIC int
21697092Stjrcdphysical(char *dest)
21797092Stjr{
218176521Sstefanf	char *p;
2191556Srgrimes
22097092Stjr	INTOFF;
221176521Sstefanf	if (chdir(dest) < 0 || (p = findcwd(NULL)) == NULL) {
22297092Stjr		INTON;
22397092Stjr		return (-1);
22497092Stjr	}
225176521Sstefanf	updatepwd(p);
22697092Stjr	INTON;
22797092Stjr	return (0);
22897092Stjr}
22997092Stjr
2301556Srgrimes/*
2311556Srgrimes * Get the next component of the path name pointed to by cdcomppath.
2321556Srgrimes * This routine overwrites the string pointed to by cdcomppath.
2331556Srgrimes */
2341556SrgrimesSTATIC char *
23590111Simpgetcomponent(void)
23620774Ssteve{
23725222Ssteve	char *p;
2381556Srgrimes	char *start;
2391556Srgrimes
2401556Srgrimes	if ((p = cdcomppath) == NULL)
2411556Srgrimes		return NULL;
2421556Srgrimes	start = cdcomppath;
2431556Srgrimes	while (*p != '/' && *p != '\0')
2441556Srgrimes		p++;
2451556Srgrimes	if (*p == '\0') {
2461556Srgrimes		cdcomppath = NULL;
2471556Srgrimes	} else {
2481556Srgrimes		*p++ = '\0';
2491556Srgrimes		cdcomppath = p;
2501556Srgrimes	}
2511556Srgrimes	return start;
2521556Srgrimes}
2531556Srgrimes
2541556Srgrimes
255176521SstefanfSTATIC char *
256176521Sstefanffindcwd(char *dir)
25720774Ssteve{
2581556Srgrimes	char *new;
2591556Srgrimes	char *p;
2601556Srgrimes
26138886Stegge	/*
26238886Stegge	 * If our argument is NULL, we don't know the current directory
26338886Stegge	 * any more because we traversed a symbolic link or something
26438886Stegge	 * we couldn't stat().
26538886Stegge	 */
266199631Sstefanf	if (dir == NULL || curdir == NULL)
267199631Sstefanf		return getpwd2();
2681556Srgrimes	cdcomppath = stalloc(strlen(dir) + 1);
2691556Srgrimes	scopy(dir, cdcomppath);
2701556Srgrimes	STARTSTACKSTR(new);
2711556Srgrimes	if (*dir != '/') {
2721556Srgrimes		p = curdir;
2731556Srgrimes		while (*p)
2741556Srgrimes			STPUTC(*p++, new);
2751556Srgrimes		if (p[-1] == '/')
2761556Srgrimes			STUNPUTC(new);
2771556Srgrimes	}
2781556Srgrimes	while ((p = getcomponent()) != NULL) {
2791556Srgrimes		if (equal(p, "..")) {
2801556Srgrimes			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
2811556Srgrimes		} else if (*p != '\0' && ! equal(p, ".")) {
2821556Srgrimes			STPUTC('/', new);
2831556Srgrimes			while (*p)
2841556Srgrimes				STPUTC(*p++, new);
2851556Srgrimes		}
2861556Srgrimes	}
2871556Srgrimes	if (new == stackblock())
2881556Srgrimes		STPUTC('/', new);
2891556Srgrimes	STACKSTRNUL(new);
290176521Sstefanf	return stackblock();
291176521Sstefanf}
292176521Sstefanf
293176521Sstefanf/*
294176521Sstefanf * Update curdir (the name of the current directory) in response to a
295176521Sstefanf * cd command.  We also call hashcd to let the routines in exec.c know
296176521Sstefanf * that the current directory has changed.
297176521Sstefanf */
298176521SstefanfSTATIC void
299176521Sstefanfupdatepwd(char *dir)
300176521Sstefanf{
301176521Sstefanf	hashcd();				/* update command hash table */
302176521Sstefanf
30338886Stegge	if (prevdir)
30438886Stegge		ckfree(prevdir);
30538886Stegge	prevdir = curdir;
306176521Sstefanf	curdir = savestr(dir);
30786176Stegge	setvar("PWD", curdir, VEXPORT);
30886176Stegge	setvar("OLDPWD", prevdir, VEXPORT);
3091556Srgrimes}
3101556Srgrimes
3111556Srgrimesint
312100660Stjrpwdcmd(int argc, char **argv)
31317987Speter{
314199631Sstefanf	char *p;
31597092Stjr	int ch, phys;
3161556Srgrimes
317100663Stjr	optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
318100664Stjr	phys = Pflag;
31997092Stjr	while ((ch = getopt(argc, argv, "LP")) != -1) {
32097092Stjr		switch (ch) {
32197092Stjr		case 'L':
32297092Stjr			phys = 0;
32397092Stjr			break;
32497092Stjr		case 'P':
32597092Stjr			phys = 1;
32697092Stjr			break;
32797092Stjr		default:
32897092Stjr			error("unknown option: -%c", optopt);
32997092Stjr			break;
33097092Stjr		}
33197092Stjr	}
33297092Stjr	argc -= optind;
33397092Stjr	argv += optind;
3341556Srgrimes
33597092Stjr	if (argc != 0)
33697092Stjr		error("too many arguments");
33738886Stegge
33897092Stjr	if (!phys && getpwd()) {
33997092Stjr		out1str(curdir);
34097092Stjr		out1c('\n');
34197092Stjr	} else {
342199631Sstefanf		if ((p = getpwd2()) == NULL)
34397092Stjr			error(".: %s", strerror(errno));
344199631Sstefanf		out1str(p);
34597092Stjr		out1c('\n');
34697092Stjr	}
34738886Stegge
34897092Stjr	return 0;
34997092Stjr}
35038886Stegge
3511556Srgrimes/*
352176521Sstefanf * Get the current directory and cache the result in curdir.
3531556Srgrimes */
35420774Sstevechar *
35590111Simpgetpwd(void)
35620425Ssteve{
357176521Sstefanf	char *p;
35838886Stegge
3591556Srgrimes	if (curdir)
36038886Stegge		return curdir;
361176521Sstefanf
362199631Sstefanf	p = getpwd2();
363176521Sstefanf	if (p != NULL)
364176521Sstefanf		curdir = savestr(p);
365176521Sstefanf
366176521Sstefanf	return curdir;
367176521Sstefanf}
368176521Sstefanf
369199631Sstefanf#define MAXPWD 256
370199631Sstefanf
371176521Sstefanf/*
372176521Sstefanf * Return the current directory.
373176521Sstefanf */
374176521SstefanfSTATIC char *
375199631Sstefanfgetpwd2(void)
376176521Sstefanf{
377199631Sstefanf	struct stat stdot, stpwd;
378199631Sstefanf	char *pwd;
379199631Sstefanf	int i;
38038886Stegge
381199631Sstefanf	for (i = MAXPWD;; i *= 2) {
382199631Sstefanf		pwd = stalloc(i);
383199631Sstefanf		if (getcwd(pwd, i) != NULL)
384176521Sstefanf			return pwd;
385199631Sstefanf		stunalloc(pwd);
386199631Sstefanf		if (errno != ERANGE)
387199631Sstefanf			break;
38838886Stegge	}
389199631Sstefanf
390199631Sstefanf	pwd = getenv("PWD");
391199631Sstefanf	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
392199631Sstefanf	    stat(pwd, &stpwd) != -1 &&
393199631Sstefanf	    stdot.st_dev == stpwd.st_dev &&
394199631Sstefanf	    stdot.st_ino == stpwd.st_ino) {
395199631Sstefanf		return pwd;
396199631Sstefanf	}
397199631Sstefanf	return NULL;
3981556Srgrimes}
399