]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - bin/sh/cd.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.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) {
134                         if (errno != ENOENT)
135                                 errno1 = errno;
136                 } else if (!S_ISDIR(statb.st_mode))
137                         errno1 = ENOTDIR;
138                 else {
139                         if (!print) {
140                                 /*
141                                  * XXX - rethink
142                                  */
143                                 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
144                                         print = strcmp(p + 2, dest);
145                                 else
146                                         print = strcmp(p, dest);
147                         }
148                         rc = docd(p, print, phys);
149                         if (rc >= 0)
150                                 return getcwderr ? rc : 0;
151                         if (errno != ENOENT)
152                                 errno1 = errno;
153                 }
154         }
155         error("%s: %s", dest, strerror(errno1));
156         /*NOTREACHED*/
157         return 0;
158 }
159
160
161 /*
162  * Actually change the directory.  In an interactive shell, print the
163  * directory name if "print" is nonzero.
164  */
165 static int
166 docd(char *dest, int print, int phys)
167 {
168         int rc;
169
170         TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
171
172         /* If logical cd fails, fall back to physical. */
173         if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
174                 return (-1);
175
176         if (print && iflag && curdir)
177                 out1fmt("%s\n", curdir);
178
179         return (rc);
180 }
181
182 static int
183 cdlogical(char *dest)
184 {
185         char *p;
186         char *q;
187         char *component;
188         struct stat statb;
189         int first;
190         int badstat;
191
192         /*
193          *  Check each component of the path. If we find a symlink or
194          *  something we can't stat, clear curdir to force a getcwd()
195          *  next time we get the value of the current directory.
196          */
197         badstat = 0;
198         cdcomppath = stalloc(strlen(dest) + 1);
199         scopy(dest, cdcomppath);
200         STARTSTACKSTR(p);
201         if (*dest == '/') {
202                 STPUTC('/', p);
203                 cdcomppath++;
204         }
205         first = 1;
206         while ((q = getcomponent()) != NULL) {
207                 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
208                         continue;
209                 if (! first)
210                         STPUTC('/', p);
211                 first = 0;
212                 component = q;
213                 STPUTS(q, p);
214                 if (equal(component, ".."))
215                         continue;
216                 STACKSTRNUL(p);
217                 if (lstat(stackblock(), &statb) < 0) {
218                         badstat = 1;
219                         break;
220                 }
221         }
222
223         INTOFF;
224         if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
225                 INTON;
226                 return (-1);
227         }
228         updatepwd(p);
229         INTON;
230         return (0);
231 }
232
233 static int
234 cdphysical(char *dest)
235 {
236         char *p;
237         int rc = 0;
238
239         INTOFF;
240         if (chdir(dest) < 0) {
241                 INTON;
242                 return (-1);
243         }
244         p = findcwd(NULL);
245         if (p == NULL) {
246                 warning("warning: failed to get name of current directory");
247                 rc = 1;
248         }
249         updatepwd(p);
250         INTON;
251         return (rc);
252 }
253
254 /*
255  * Get the next component of the path name pointed to by cdcomppath.
256  * This routine overwrites the string pointed to by cdcomppath.
257  */
258 static char *
259 getcomponent(void)
260 {
261         char *p;
262         char *start;
263
264         if ((p = cdcomppath) == NULL)
265                 return NULL;
266         start = cdcomppath;
267         while (*p != '/' && *p != '\0')
268                 p++;
269         if (*p == '\0') {
270                 cdcomppath = NULL;
271         } else {
272                 *p++ = '\0';
273                 cdcomppath = p;
274         }
275         return start;
276 }
277
278
279 static char *
280 findcwd(char *dir)
281 {
282         char *new;
283         char *p;
284
285         /*
286          * If our argument is NULL, we don't know the current directory
287          * any more because we traversed a symbolic link or something
288          * we couldn't stat().
289          */
290         if (dir == NULL || curdir == NULL)
291                 return getpwd2();
292         cdcomppath = stalloc(strlen(dir) + 1);
293         scopy(dir, cdcomppath);
294         STARTSTACKSTR(new);
295         if (*dir != '/') {
296                 STPUTS(curdir, new);
297                 if (STTOPC(new) == '/')
298                         STUNPUTC(new);
299         }
300         while ((p = getcomponent()) != NULL) {
301                 if (equal(p, "..")) {
302                         while (new > stackblock() && (STUNPUTC(new), *new) != '/');
303                 } else if (*p != '\0' && ! equal(p, ".")) {
304                         STPUTC('/', new);
305                         STPUTS(p, new);
306                 }
307         }
308         if (new == stackblock())
309                 STPUTC('/', new);
310         STACKSTRNUL(new);
311         return stackblock();
312 }
313
314 /*
315  * Update curdir (the name of the current directory) in response to a
316  * cd command.  We also call hashcd to let the routines in exec.c know
317  * that the current directory has changed.
318  */
319 static void
320 updatepwd(char *dir)
321 {
322         hashcd();                               /* update command hash table */
323
324         if (prevdir)
325                 ckfree(prevdir);
326         prevdir = curdir;
327         curdir = dir ? savestr(dir) : NULL;
328         setvar("PWD", curdir, VEXPORT);
329         setvar("OLDPWD", prevdir, VEXPORT);
330 }
331
332 int
333 pwdcmd(int argc, char **argv)
334 {
335         char *p;
336         int ch, phys;
337
338         optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
339         phys = Pflag;
340         while ((ch = getopt(argc, argv, "LP")) != -1) {
341                 switch (ch) {
342                 case 'L':
343                         phys = 0;
344                         break;
345                 case 'P':
346                         phys = 1;
347                         break;
348                 default:
349                         error("unknown option: -%c", optopt);
350                         break;
351                 }
352         }
353         argc -= optind;
354         argv += optind;
355
356         if (argc != 0)
357                 error("too many arguments");
358
359         if (!phys && getpwd()) {
360                 out1str(curdir);
361                 out1c('\n');
362         } else {
363                 if ((p = getpwd2()) == NULL)
364                         error(".: %s", strerror(errno));
365                 out1str(p);
366                 out1c('\n');
367         }
368
369         return 0;
370 }
371
372 /*
373  * Get the current directory and cache the result in curdir.
374  */
375 static char *
376 getpwd(void)
377 {
378         char *p;
379
380         if (curdir)
381                 return curdir;
382
383         p = getpwd2();
384         if (p != NULL)
385                 curdir = savestr(p);
386
387         return curdir;
388 }
389
390 #define MAXPWD 256
391
392 /*
393  * Return the current directory.
394  */
395 static char *
396 getpwd2(void)
397 {
398         char *pwd;
399         int i;
400
401         for (i = MAXPWD;; i *= 2) {
402                 pwd = stalloc(i);
403                 if (getcwd(pwd, i) != NULL)
404                         return pwd;
405                 stunalloc(pwd);
406                 if (errno != ERANGE)
407                         break;
408         }
409
410         return NULL;
411 }
412
413 /*
414  * Initialize PWD in a new shell.
415  * If the shell is interactive, we need to warn if this fails.
416  */
417 void
418 pwd_init(int warn)
419 {
420         char *pwd;
421         struct stat stdot, stpwd;
422
423         pwd = lookupvar("PWD");
424         if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
425             stat(pwd, &stpwd) != -1 &&
426             stdot.st_dev == stpwd.st_dev &&
427             stdot.st_ino == stpwd.st_ino) {
428                 if (curdir)
429                         ckfree(curdir);
430                 curdir = savestr(pwd);
431         }
432         if (getpwd() == NULL && warn)
433                 out2fmt_flush("sh: cannot determine working directory\n");
434         setvar("PWD", curdir, VEXPORT);
435 }