sh: Show errno messages in cd.
[dragonfly.git] / bin / sh / cd.c
CommitLineData
984263bc
MD
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. 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.
1de703da
MD
35 *
36 * @(#)cd.c 8.2 (Berkeley) 5/4/95
72cbf401 37 * $FreeBSD: src/bin/sh/cd.c,v 1.47 2011/05/25 21:38:16 jilles Exp $
984263bc
MD
38 */
39
984263bc
MD
40#include <sys/types.h>
41#include <sys/stat.h>
42#include <stdlib.h>
43#include <string.h>
44#include <unistd.h>
45#include <errno.h>
46#include <limits.h>
47
48/*
49 * The cd and pwd commands.
50 */
51
52#include "shell.h"
53#include "var.h"
54#include "nodes.h" /* for jobs.h */
55#include "jobs.h"
56#include "options.h"
57#include "output.h"
58#include "memalloc.h"
59#include "error.h"
60#include "exec.h"
61#include "redir.h"
62#include "mystring.h"
63#include "show.h"
64#include "cd.h"
65
99512ac4
PA
66static int cdlogical(char *);
67static int cdphysical(char *);
68static int docd(char *, int, int);
69static char *getcomponent(void);
70static char *findcwd(char *);
71static void updatepwd(char *);
72static char *getpwd(void);
73static char *getpwd2(void);
984263bc 74
99512ac4
PA
75static char *curdir = NULL; /* current working directory */
76static char *prevdir; /* previous working directory */
77static char *cdcomppath;
984263bc
MD
78
79int
80cdcmd(int argc, char **argv)
81{
492efe05
CP
82 const char *dest;
83 const char *path;
984263bc
MD
84 char *p;
85 struct stat statb;
8c603ea4
PA
86 int ch, phys, print = 0, getcwderr = 0;
87 int rc;
72cbf401 88 int errno1 = ENOENT;
984263bc
MD
89
90 optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
91 phys = Pflag;
8c603ea4 92 while ((ch = getopt(argc, argv, "eLP")) != -1) {
984263bc 93 switch (ch) {
8c603ea4
PA
94 case 'e':
95 getcwderr = 1;
96 break;
984263bc
MD
97 case 'L':
98 phys = 0;
99 break;
100 case 'P':
101 phys = 1;
102 break;
103 default:
104 error("unknown option: -%c", optopt);
105 break;
106 }
107 }
108 argc -= optind;
109 argv += optind;
110
111 if (argc > 1)
112 error("too many arguments");
113
114 if ((dest = *argv) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
115 error("HOME not set");
116 if (*dest == '\0')
117 dest = ".";
118 if (dest[0] == '-' && dest[1] == '\0') {
119 dest = prevdir ? prevdir : curdir;
120 if (dest)
121 print = 1;
122 else
123 dest = ".";
124 }
125 if (*dest == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
126 path = nullstr;
127 while ((p = padvance(&path, dest)) != NULL) {
128 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
129 if (!print) {
130 /*
131 * XXX - rethink
132 */
133 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
27be99cb
PA
134 print = strcmp(p + 2, dest);
135 else
136 print = strcmp(p, dest);
984263bc 137 }
8c603ea4
PA
138 rc = docd(p, print, phys);
139 if (rc >= 0)
140 return getcwderr ? rc : 0;
72cbf401
PA
141 if (errno != ENOENT)
142 errno1 = errno;
984263bc
MD
143 }
144 }
72cbf401 145 error("%s: %s", dest, strerror(errno1));
984263bc
MD
146 /*NOTREACHED*/
147 return 0;
148}
149
150
151/*
152 * Actually change the directory. In an interactive shell, print the
153 * directory name if "print" is nonzero.
154 */
99512ac4 155static int
984263bc
MD
156docd(char *dest, int print, int phys)
157{
8c603ea4 158 int rc;
984263bc
MD
159
160 TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
161
162 /* If logical cd fails, fall back to physical. */
8c603ea4 163 if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
984263bc
MD
164 return (-1);
165
166 if (print && iflag && curdir)
167 out1fmt("%s\n", curdir);
168
8c603ea4 169 return (rc);
984263bc
MD
170}
171
99512ac4 172static int
984263bc
MD
173cdlogical(char *dest)
174{
175 char *p;
176 char *q;
177 char *component;
178 struct stat statb;
179 int first;
180 int badstat;
181
182 /*
183 * Check each component of the path. If we find a symlink or
184 * something we can't stat, clear curdir to force a getcwd()
185 * next time we get the value of the current directory.
186 */
187 badstat = 0;
188 cdcomppath = stalloc(strlen(dest) + 1);
189 scopy(dest, cdcomppath);
190 STARTSTACKSTR(p);
191 if (*dest == '/') {
192 STPUTC('/', p);
193 cdcomppath++;
194 }
195 first = 1;
196 while ((q = getcomponent()) != NULL) {
197 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
198 continue;
199 if (! first)
200 STPUTC('/', p);
201 first = 0;
202 component = q;
99512ac4 203 STPUTS(q, p);
984263bc
MD
204 if (equal(component, ".."))
205 continue;
206 STACKSTRNUL(p);
207 if (lstat(stackblock(), &statb) < 0) {
208 badstat = 1;
209 break;
210 }
211 }
212
213 INTOFF;
99512ac4 214 if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
984263bc
MD
215 INTON;
216 return (-1);
217 }
99512ac4 218 updatepwd(p);
984263bc
MD
219 INTON;
220 return (0);
221}
222
99512ac4 223static int
984263bc
MD
224cdphysical(char *dest)
225{
99512ac4 226 char *p;
8c603ea4 227 int rc = 0;
984263bc
MD
228
229 INTOFF;
99512ac4 230 if (chdir(dest) < 0) {
984263bc
MD
231 INTON;
232 return (-1);
233 }
99512ac4 234 p = findcwd(NULL);
8c603ea4 235 if (p == NULL) {
99512ac4 236 warning("warning: failed to get name of current directory");
8c603ea4
PA
237 rc = 1;
238 }
99512ac4 239 updatepwd(p);
984263bc 240 INTON;
8c603ea4 241 return (rc);
984263bc
MD
242}
243
244/*
245 * Get the next component of the path name pointed to by cdcomppath.
246 * This routine overwrites the string pointed to by cdcomppath.
247 */
99512ac4 248static char *
984263bc
MD
249getcomponent(void)
250{
251 char *p;
252 char *start;
253
254 if ((p = cdcomppath) == NULL)
255 return NULL;
256 start = cdcomppath;
257 while (*p != '/' && *p != '\0')
258 p++;
259 if (*p == '\0') {
260 cdcomppath = NULL;
261 } else {
262 *p++ = '\0';
263 cdcomppath = p;
264 }
265 return start;
266}
267
268
99512ac4
PA
269static char *
270findcwd(char *dir)
984263bc
MD
271{
272 char *new;
273 char *p;
274
984263bc
MD
275 /*
276 * If our argument is NULL, we don't know the current directory
277 * any more because we traversed a symbolic link or something
278 * we couldn't stat().
279 */
99512ac4
PA
280 if (dir == NULL || curdir == NULL)
281 return getpwd2();
984263bc
MD
282 cdcomppath = stalloc(strlen(dir) + 1);
283 scopy(dir, cdcomppath);
284 STARTSTACKSTR(new);
285 if (*dir != '/') {
99512ac4
PA
286 STPUTS(curdir, new);
287 if (STTOPC(new) == '/')
984263bc
MD
288 STUNPUTC(new);
289 }
290 while ((p = getcomponent()) != NULL) {
291 if (equal(p, "..")) {
292 while (new > stackblock() && (STUNPUTC(new), *new) != '/');
293 } else if (*p != '\0' && ! equal(p, ".")) {
294 STPUTC('/', new);
99512ac4 295 STPUTS(p, new);
984263bc
MD
296 }
297 }
298 if (new == stackblock())
299 STPUTC('/', new);
300 STACKSTRNUL(new);
99512ac4
PA
301 return stackblock();
302}
303
304/*
305 * Update curdir (the name of the current directory) in response to a
306 * cd command. We also call hashcd to let the routines in exec.c know
307 * that the current directory has changed.
308 */
309static void
310updatepwd(char *dir)
311{
312 hashcd(); /* update command hash table */
313
984263bc
MD
314 if (prevdir)
315 ckfree(prevdir);
316 prevdir = curdir;
99512ac4 317 curdir = dir ? savestr(dir) : NULL;
984263bc
MD
318 setvar("PWD", curdir, VEXPORT);
319 setvar("OLDPWD", prevdir, VEXPORT);
984263bc
MD
320}
321
322int
323pwdcmd(int argc, char **argv)
324{
99512ac4 325 char *p;
984263bc
MD
326 int ch, phys;
327
328 optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
329 phys = Pflag;
330 while ((ch = getopt(argc, argv, "LP")) != -1) {
331 switch (ch) {
332 case 'L':
333 phys = 0;
334 break;
335 case 'P':
336 phys = 1;
337 break;
338 default:
339 error("unknown option: -%c", optopt);
340 break;
341 }
342 }
343 argc -= optind;
344 argv += optind;
345
346 if (argc != 0)
347 error("too many arguments");
348
349 if (!phys && getpwd()) {
350 out1str(curdir);
351 out1c('\n');
352 } else {
99512ac4 353 if ((p = getpwd2()) == NULL)
984263bc 354 error(".: %s", strerror(errno));
99512ac4 355 out1str(p);
984263bc
MD
356 out1c('\n');
357 }
358
359 return 0;
360}
361
362/*
99512ac4 363 * Get the current directory and cache the result in curdir.
984263bc 364 */
99512ac4 365static char *
984263bc
MD
366getpwd(void)
367{
99512ac4 368 char *p;
984263bc
MD
369
370 if (curdir)
371 return curdir;
99512ac4
PA
372
373 p = getpwd2();
374 if (p != NULL)
375 curdir = savestr(p);
984263bc
MD
376
377 return curdir;
378}
99512ac4
PA
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}