]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - bin/sh/cd.c
Copy head (r256279) to stable/10 as part of the 10.0-RELEASE cycle.
[FreeBSD/stable/10.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 __unused, char **argv __unused)
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         phys = Pflag;
93         while ((ch = nextopt("eLP")) != '\0') {
94                 switch (ch) {
95                 case 'e':
96                         getcwderr = 1;
97                         break;
98                 case 'L':
99                         phys = 0;
100                         break;
101                 case 'P':
102                         phys = 1;
103                         break;
104                 }
105         }
106
107         if (*argptr != NULL && argptr[1] != NULL)
108                 error("too many arguments");
109
110         if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
111                 error("HOME not set");
112         if (*dest == '\0')
113                 dest = ".";
114         if (dest[0] == '-' && dest[1] == '\0') {
115                 dest = prevdir ? prevdir : curdir;
116                 if (dest)
117                         print = 1;
118                 else
119                         dest = ".";
120         }
121         if (dest[0] == '/' ||
122             (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
123             (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
124             (path = bltinlookup("CDPATH", 1)) == NULL)
125                 path = nullstr;
126         while ((p = padvance(&path, dest)) != NULL) {
127                 if (stat(p, &statb) < 0) {
128                         if (errno != ENOENT)
129                                 errno1 = errno;
130                 } else if (!S_ISDIR(statb.st_mode))
131                         errno1 = ENOTDIR;
132                 else {
133                         if (!print) {
134                                 /*
135                                  * XXX - rethink
136                                  */
137                                 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
138                                         print = strcmp(p + 2, dest);
139                                 else
140                                         print = strcmp(p, dest);
141                         }
142                         rc = docd(p, print, phys);
143                         if (rc >= 0)
144                                 return getcwderr ? rc : 0;
145                         if (errno != ENOENT)
146                                 errno1 = errno;
147                 }
148         }
149         error("%s: %s", dest, strerror(errno1));
150         /*NOTREACHED*/
151         return 0;
152 }
153
154
155 /*
156  * Actually change the directory.  In an interactive shell, print the
157  * directory name if "print" is nonzero.
158  */
159 static int
160 docd(char *dest, int print, int phys)
161 {
162         int rc;
163
164         TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
165
166         /* If logical cd fails, fall back to physical. */
167         if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
168                 return (-1);
169
170         if (print && iflag && curdir)
171                 out1fmt("%s\n", curdir);
172
173         return (rc);
174 }
175
176 static int
177 cdlogical(char *dest)
178 {
179         char *p;
180         char *q;
181         char *component;
182         struct stat statb;
183         int first;
184         int badstat;
185
186         /*
187          *  Check each component of the path. If we find a symlink or
188          *  something we can't stat, clear curdir to force a getcwd()
189          *  next time we get the value of the current directory.
190          */
191         badstat = 0;
192         cdcomppath = stalloc(strlen(dest) + 1);
193         scopy(dest, cdcomppath);
194         STARTSTACKSTR(p);
195         if (*dest == '/') {
196                 STPUTC('/', p);
197                 cdcomppath++;
198         }
199         first = 1;
200         while ((q = getcomponent()) != NULL) {
201                 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
202                         continue;
203                 if (! first)
204                         STPUTC('/', p);
205                 first = 0;
206                 component = q;
207                 STPUTS(q, p);
208                 if (equal(component, ".."))
209                         continue;
210                 STACKSTRNUL(p);
211                 if (lstat(stackblock(), &statb) < 0) {
212                         badstat = 1;
213                         break;
214                 }
215         }
216
217         INTOFF;
218         if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
219                 INTON;
220                 return (-1);
221         }
222         updatepwd(p);
223         INTON;
224         return (0);
225 }
226
227 static int
228 cdphysical(char *dest)
229 {
230         char *p;
231         int rc = 0;
232
233         INTOFF;
234         if (chdir(dest) < 0) {
235                 INTON;
236                 return (-1);
237         }
238         p = findcwd(NULL);
239         if (p == NULL) {
240                 warning("warning: failed to get name of current directory");
241                 rc = 1;
242         }
243         updatepwd(p);
244         INTON;
245         return (rc);
246 }
247
248 /*
249  * Get the next component of the path name pointed to by cdcomppath.
250  * This routine overwrites the string pointed to by cdcomppath.
251  */
252 static char *
253 getcomponent(void)
254 {
255         char *p;
256         char *start;
257
258         if ((p = cdcomppath) == NULL)
259                 return NULL;
260         start = cdcomppath;
261         while (*p != '/' && *p != '\0')
262                 p++;
263         if (*p == '\0') {
264                 cdcomppath = NULL;
265         } else {
266                 *p++ = '\0';
267                 cdcomppath = p;
268         }
269         return start;
270 }
271
272
273 static char *
274 findcwd(char *dir)
275 {
276         char *new;
277         char *p;
278
279         /*
280          * If our argument is NULL, we don't know the current directory
281          * any more because we traversed a symbolic link or something
282          * we couldn't stat().
283          */
284         if (dir == NULL || curdir == NULL)
285                 return getpwd2();
286         cdcomppath = stalloc(strlen(dir) + 1);
287         scopy(dir, cdcomppath);
288         STARTSTACKSTR(new);
289         if (*dir != '/') {
290                 STPUTS(curdir, new);
291                 if (STTOPC(new) == '/')
292                         STUNPUTC(new);
293         }
294         while ((p = getcomponent()) != NULL) {
295                 if (equal(p, "..")) {
296                         while (new > stackblock() && (STUNPUTC(new), *new) != '/');
297                 } else if (*p != '\0' && ! equal(p, ".")) {
298                         STPUTC('/', new);
299                         STPUTS(p, new);
300                 }
301         }
302         if (new == stackblock())
303                 STPUTC('/', new);
304         STACKSTRNUL(new);
305         return stackblock();
306 }
307
308 /*
309  * Update curdir (the name of the current directory) in response to a
310  * cd command.  We also call hashcd to let the routines in exec.c know
311  * that the current directory has changed.
312  */
313 static void
314 updatepwd(char *dir)
315 {
316         hashcd();                               /* update command hash table */
317
318         if (prevdir)
319                 ckfree(prevdir);
320         prevdir = curdir;
321         curdir = dir ? savestr(dir) : NULL;
322         setvar("PWD", curdir, VEXPORT);
323         setvar("OLDPWD", prevdir, VEXPORT);
324 }
325
326 int
327 pwdcmd(int argc __unused, char **argv __unused)
328 {
329         char *p;
330         int ch, phys;
331
332         phys = Pflag;
333         while ((ch = nextopt("LP")) != '\0') {
334                 switch (ch) {
335                 case 'L':
336                         phys = 0;
337                         break;
338                 case 'P':
339                         phys = 1;
340                         break;
341                 }
342         }
343
344         if (*argptr != NULL)
345                 error("too many arguments");
346
347         if (!phys && getpwd()) {
348                 out1str(curdir);
349                 out1c('\n');
350         } else {
351                 if ((p = getpwd2()) == NULL)
352                         error(".: %s", strerror(errno));
353                 out1str(p);
354                 out1c('\n');
355         }
356
357         return 0;
358 }
359
360 /*
361  * Get the current directory and cache the result in curdir.
362  */
363 static char *
364 getpwd(void)
365 {
366         char *p;
367
368         if (curdir)
369                 return curdir;
370
371         p = getpwd2();
372         if (p != NULL)
373                 curdir = savestr(p);
374
375         return curdir;
376 }
377
378 #define MAXPWD 256
379
380 /*
381  * Return the current directory.
382  */
383 static char *
384 getpwd2(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  */
405 void
406 pwd_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 }