1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  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. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#include <sys/types.h>
34#include <sys/stat.h>
35#include <stdlib.h>
36#include <string.h>
37#include <unistd.h>
38#include <errno.h>
39#include <limits.h>
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 "exec.h"
54#include "redir.h"
55#include "mystring.h"
56#include "show.h"
57#include "cd.h"
58#include "builtins.h"
59
60static int cdlogical(char *);
61static int cdphysical(char *);
62static int docd(char *, int, int);
63static char *getcomponent(char **);
64static char *findcwd(char *);
65static void updatepwd(char *);
66static char *getpwd(void);
67static char *getpwd2(void);
68
69static char *curdir = NULL;	/* current working directory */
70
71int
72cdcmd(int argc __unused, char **argv __unused)
73{
74	const char *dest;
75	const char *path;
76	char *p;
77	struct stat statb;
78	int ch, phys, print = 0, getcwderr = 0;
79	int rc;
80	int errno1 = ENOENT;
81
82	phys = Pflag;
83	while ((ch = nextopt("eLP")) != '\0') {
84		switch (ch) {
85		case 'e':
86			getcwderr = 1;
87			break;
88		case 'L':
89			phys = 0;
90			break;
91		case 'P':
92			phys = 1;
93			break;
94		}
95	}
96
97	if (*argptr != NULL && argptr[1] != NULL)
98		error("too many arguments");
99
100	if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
101		error("HOME not set");
102	if (*dest == '\0')
103		dest = ".";
104	if (dest[0] == '-' && dest[1] == '\0') {
105		dest = bltinlookup("OLDPWD", 1);
106		if (dest == NULL)
107			error("OLDPWD not set");
108		print = 1;
109	}
110	if (dest[0] == '/' ||
111	    (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
112	    (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
113	    (path = bltinlookup("CDPATH", 1)) == NULL)
114		path = "";
115	while ((p = padvance(&path, NULL, dest)) != NULL) {
116		if (stat(p, &statb) < 0) {
117			if (errno != ENOENT)
118				errno1 = errno;
119		} else if (!S_ISDIR(statb.st_mode))
120			errno1 = ENOTDIR;
121		else {
122			if (!print) {
123				/*
124				 * XXX - rethink
125				 */
126				if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
127					print = strcmp(p + 2, dest);
128				else
129					print = strcmp(p, dest);
130			}
131			rc = docd(p, print, phys);
132			if (rc >= 0)
133				return getcwderr ? rc : 0;
134			if (errno != ENOENT)
135				errno1 = errno;
136		}
137	}
138	error("%s: %s", dest, strerror(errno1));
139	/*NOTREACHED*/
140	return 0;
141}
142
143
144/*
145 * Actually change the directory.  In an interactive shell, print the
146 * directory name if "print" is nonzero.
147 */
148static int
149docd(char *dest, int print, int phys)
150{
151	int rc;
152
153	TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
154
155	/* If logical cd fails, fall back to physical. */
156	if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
157		return (-1);
158
159	if (print && iflag && curdir) {
160		out1fmt("%s\n", curdir);
161		/*
162		 * Ignore write errors to preserve the invariant that the
163		 * current directory is changed iff the exit status is 0
164		 * (or 1 if -e was given and the full pathname could not be
165		 * determined).
166		 */
167		flushout(out1);
168		outclearerror(out1);
169	}
170
171	return (rc);
172}
173
174static int
175cdlogical(char *dest)
176{
177	char *p;
178	char *q;
179	char *component;
180	char *path;
181	struct stat statb;
182	int first;
183	int badstat;
184
185	/*
186	 *  Check each component of the path. If we find a symlink or
187	 *  something we can't stat, clear curdir to force a getcwd()
188	 *  next time we get the value of the current directory.
189	 */
190	badstat = 0;
191	path = stsavestr(dest);
192	STARTSTACKSTR(p);
193	if (*dest == '/') {
194		STPUTC('/', p);
195		path++;
196	}
197	first = 1;
198	while ((q = getcomponent(&path)) != NULL) {
199		if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
200			continue;
201		if (! first)
202			STPUTC('/', p);
203		first = 0;
204		component = q;
205		STPUTS(q, p);
206		if (equal(component, ".."))
207			continue;
208		STACKSTRNUL(p);
209		if (lstat(stackblock(), &statb) < 0) {
210			badstat = 1;
211			break;
212		}
213	}
214
215	INTOFF;
216	if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
217		INTON;
218		return (-1);
219	}
220	updatepwd(p);
221	INTON;
222	return (0);
223}
224
225static int
226cdphysical(char *dest)
227{
228	char *p;
229	int rc = 0;
230
231	INTOFF;
232	if (chdir(dest) < 0) {
233		INTON;
234		return (-1);
235	}
236	p = findcwd(NULL);
237	if (p == NULL) {
238		warning("warning: failed to get name of current directory");
239		rc = 1;
240	}
241	updatepwd(p);
242	INTON;
243	return (rc);
244}
245
246/*
247 * Get the next component of the path name pointed to by *path.
248 * This routine overwrites *path and the string pointed to by it.
249 */
250static char *
251getcomponent(char **path)
252{
253	char *p;
254	char *start;
255
256	if ((p = *path) == NULL)
257		return NULL;
258	start = *path;
259	while (*p != '/' && *p != '\0')
260		p++;
261	if (*p == '\0') {
262		*path = NULL;
263	} else {
264		*p++ = '\0';
265		*path = p;
266	}
267	return start;
268}
269
270
271static char *
272findcwd(char *dir)
273{
274	char *new;
275	char *p;
276	char *path;
277
278	/*
279	 * If our argument is NULL, we don't know the current directory
280	 * any more because we traversed a symbolic link or something
281	 * we couldn't stat().
282	 */
283	if (dir == NULL || curdir == NULL)
284		return getpwd2();
285	path = stsavestr(dir);
286	STARTSTACKSTR(new);
287	if (*dir != '/') {
288		STPUTS(curdir, new);
289		if (STTOPC(new) == '/')
290			STUNPUTC(new);
291	}
292	while ((p = getcomponent(&path)) != NULL) {
293		if (equal(p, "..")) {
294			while (new > stackblock() && (STUNPUTC(new), *new) != '/');
295		} else if (*p != '\0' && ! equal(p, ".")) {
296			STPUTC('/', new);
297			STPUTS(p, new);
298		}
299	}
300	if (new == stackblock())
301		STPUTC('/', new);
302	STACKSTRNUL(new);
303	return stackblock();
304}
305
306/*
307 * Update curdir (the name of the current directory) in response to a
308 * cd command.  We also call hashcd to let the routines in exec.c know
309 * that the current directory has changed.
310 */
311static void
312updatepwd(char *dir)
313{
314	char *prevdir;
315
316	hashcd();				/* update command hash table */
317
318	setvar("PWD", dir, VEXPORT);
319	setvar("OLDPWD", curdir, VEXPORT);
320	prevdir = curdir;
321	curdir = dir ? savestr(dir) : NULL;
322	ckfree(prevdir);
323}
324
325int
326pwdcmd(int argc __unused, char **argv __unused)
327{
328	char *p;
329	int ch, phys;
330
331	phys = Pflag;
332	while ((ch = nextopt("LP")) != '\0') {
333		switch (ch) {
334		case 'L':
335			phys = 0;
336			break;
337		case 'P':
338			phys = 1;
339			break;
340		}
341	}
342
343	if (*argptr != NULL)
344		error("too many arguments");
345
346	if (!phys && getpwd()) {
347		out1str(curdir);
348		out1c('\n');
349	} else {
350		if ((p = getpwd2()) == NULL)
351			error(".: %s", strerror(errno));
352		out1str(p);
353		out1c('\n');
354	}
355
356	return 0;
357}
358
359/*
360 * Get the current directory and cache the result in curdir.
361 */
362static char *
363getpwd(void)
364{
365	char *p;
366
367	if (curdir)
368		return curdir;
369
370	p = getpwd2();
371	if (p != NULL) {
372		INTOFF;
373		curdir = savestr(p);
374		INTON;
375	}
376
377	return curdir;
378}
379
380#define MAXPWD 256
381
382/*
383 * Return the current directory.
384 */
385static char *
386getpwd2(void)
387{
388	char *pwd;
389	int i;
390
391	for (i = MAXPWD;; i *= 2) {
392		pwd = stalloc(i);
393		if (getcwd(pwd, i) != NULL)
394			return pwd;
395		stunalloc(pwd);
396		if (errno != ERANGE)
397			break;
398	}
399
400	return NULL;
401}
402
403/*
404 * Initialize PWD in a new shell.
405 * If the shell is interactive, we need to warn if this fails.
406 */
407void
408pwd_init(int warn)
409{
410	char *pwd;
411	struct stat stdot, stpwd;
412
413	pwd = lookupvar("PWD");
414	if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
415	    stat(pwd, &stpwd) != -1 &&
416	    stdot.st_dev == stpwd.st_dev &&
417	    stdot.st_ino == stpwd.st_ino) {
418		if (curdir)
419			ckfree(curdir);
420		curdir = savestr(pwd);
421	}
422	if (getpwd() == NULL && warn)
423		out2fmt_flush("sh: cannot determine working directory\n");
424	setvar("PWD", curdir, VEXPORT);
425}
426