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