1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
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. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#include <sys/types.h>
36#include <sys/stat.h>
37#include <stdlib.h>
38#include <string.h>
39#include <unistd.h>
40#include <errno.h>
41#include <limits.h>
42
43/*
44 * The cd and pwd commands.
45 */
46
47#include "shell.h"
48#include "var.h"
49#include "nodes.h" /* for jobs.h */
50#include "jobs.h"
51#include "options.h"
52#include "output.h"
53#include "memalloc.h"
54#include "error.h"
55#include "exec.h"
56#include "redir.h"
57#include "mystring.h"
58#include "show.h"
59#include "cd.h"
60#include "builtins.h"
61
62static int cdlogical(char *);
63static int cdphysical(char *);
64static int docd(char *, int, int);
65static char *getcomponent(char **);
66static char *findcwd(char *);
67static void updatepwd(char *);
68static char *getpwd(void);
69static char *getpwd2(void);
70
71static char *curdir = NULL; /* current working directory */
72
73int
74cdcmd(int argc __unused, char **argv __unused)
75{
76 const char *dest;
77 const char *path;
78 char *p;
79 struct stat statb;
80 int ch, phys, print = 0, getcwderr = 0;
81 int rc;
82 int errno1 = ENOENT;
83
84 phys = Pflag;
85 while ((ch = nextopt("eLP")) != '\0') {
86 switch (ch) {
87 case 'e':
88 getcwderr = 1;
89 break;
90 case 'L':
91 phys = 0;
92 break;
93 case 'P':
94 phys = 1;
95 break;
96 }
97 }
98
99 if (*argptr != NULL && argptr[1] != NULL)
100 error("too many arguments");
101
102 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
103 error("HOME not set");
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 out1fmt("%s\n", curdir);
348 } else {
349 if ((p = getpwd2()) == NULL)
350 error(".: %s", strerror(errno));
351 out1fmt("%s\n", p);
352 }
353
354 return 0;
355}
356
357/*
358 * Get the current directory and cache the result in curdir.
359 */
360static char *
361getpwd(void)
362{
363 char *p;
364
365 if (curdir)
366 return curdir;
367
368 p = getpwd2();
369 if (p != NULL) {
370 INTOFF;
371 curdir = savestr(p);
372 INTON;
373 }
374
375 return curdir;
376}
377
378#define MAXPWD 256
379
380/*
381 * Return the current directory.
382 */
383static char *
384getpwd2(void)
385{
386 char *pwd;
387 int i;
388
389 for (i = MAXPWD;; i *= 2) {
390 pwd = stalloc(i);
391 if (getcwd(pwd, i) != NULL)
392 return pwd;
393 stunalloc(pwd);
394 if (errno != ERANGE)
395 break;
396 }
397
398 return NULL;
399}
400
401/*
402 * Initialize PWD in a new shell.
403 * If the shell is interactive, we need to warn if this fails.
404 */
405void
406pwd_init(int warn)
407{
408 char *pwd;
409 struct stat stdot, stpwd;
410
411 pwd = lookupvar("PWD");
412 if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
413 stat(pwd, &stpwd) != -1 &&
414 stdot.st_dev == stpwd.st_dev &&
415 stdot.st_ino == stpwd.st_ino) {
416 if (curdir)
417 ckfree(curdir);
418 curdir = savestr(pwd);
419 }
420 if (getpwd() == NULL && warn)
421 out2fmt_flush("sh: cannot determine working directory\n");
422 setvar("PWD", curdir, VEXPORT);
423}