]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - bin/sh/cd.c
MFC r302371:
[FreeBSD/stable/8.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
67 static int cdlogical(char *);
68 static int cdphysical(char *);
69 static int docd(char *, int, int);
70 static char *getcomponent(void);
71 static char *findcwd(char *);
72 static void updatepwd(char *);
73 static char *getpwd2(void);
74
75 static char *curdir = NULL;     /* current working directory */
76 static char *prevdir;           /* previous working directory */
77 static char *cdcomppath;
78
79 int
80 cdcmd(int argc, char **argv)
81 {
82         const char *dest;
83         const char *path;
84         char *p;
85         struct stat statb;
86         int ch, phys, print = 0;
87         int errno1 = ENOENT;
88
89         optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
90         phys = Pflag;
91         while ((ch = getopt(argc, argv, "LP")) != -1) {
92                 switch (ch) {
93                 case 'L':
94                         phys = 0;
95                         break;
96                 case 'P':
97                         phys = 1;
98                         break;
99                 default:
100                         error("unknown option: -%c", optopt);
101                         break;
102                 }
103         }
104         argc -= optind;
105         argv += optind;
106
107         if (argc > 1)
108                 error("too many arguments");
109
110         if ((dest = *argv) == 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 == '/' || (path = bltinlookup("CDPATH", 1)) == NULL)
122                 path = nullstr;
123         while ((p = padvance(&path, dest)) != NULL) {
124                 if (stat(p, &statb) < 0) {
125                         if (errno != ENOENT)
126                                 errno1 = errno;
127                 } else if (!S_ISDIR(statb.st_mode))
128                         errno1 = ENOTDIR;
129                 else {
130                         if (!print) {
131                                 /*
132                                  * XXX - rethink
133                                  */
134                                 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
135                                         print = strcmp(p + 2, dest);
136                                 else
137                                         print = strcmp(p, dest);
138                         }
139                         if (docd(p, print, phys) >= 0)
140                                 return 0;
141                         if (errno != ENOENT)
142                                 errno1 = errno;
143                 }
144         }
145         error("%s: %s", dest, strerror(errno1));
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  */
155 static int
156 docd(char *dest, int print, int phys)
157 {
158
159         TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
160
161         /* If logical cd fails, fall back to physical. */
162         if ((phys || cdlogical(dest) < 0) && cdphysical(dest) < 0)
163                 return (-1);
164
165         if (print && iflag && curdir)
166                 out1fmt("%s\n", curdir);
167
168         return 0;
169 }
170
171 static int
172 cdlogical(char *dest)
173 {
174         char *p;
175         char *q;
176         char *component;
177         struct stat statb;
178         int first;
179         int badstat;
180
181         /*
182          *  Check each component of the path. If we find a symlink or
183          *  something we can't stat, clear curdir to force a getcwd()
184          *  next time we get the value of the current directory.
185          */
186         badstat = 0;
187         cdcomppath = stalloc(strlen(dest) + 1);
188         scopy(dest, cdcomppath);
189         STARTSTACKSTR(p);
190         if (*dest == '/') {
191                 STPUTC('/', p);
192                 cdcomppath++;
193         }
194         first = 1;
195         while ((q = getcomponent()) != NULL) {
196                 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
197                         continue;
198                 if (! first)
199                         STPUTC('/', p);
200                 first = 0;
201                 component = q;
202                 while (*q)
203                         STPUTC(*q++, p);
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;
214         if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
215                 INTON;
216                 return (-1);
217         }
218         updatepwd(p);
219         INTON;
220         return (0);
221 }
222
223 static int
224 cdphysical(char *dest)
225 {
226         char *p;
227
228         INTOFF;
229         if (chdir(dest) < 0 || (p = findcwd(NULL)) == NULL) {
230                 INTON;
231                 return (-1);
232         }
233         updatepwd(p);
234         INTON;
235         return (0);
236 }
237
238 /*
239  * Get the next component of the path name pointed to by cdcomppath.
240  * This routine overwrites the string pointed to by cdcomppath.
241  */
242 static char *
243 getcomponent(void)
244 {
245         char *p;
246         char *start;
247
248         if ((p = cdcomppath) == NULL)
249                 return NULL;
250         start = cdcomppath;
251         while (*p != '/' && *p != '\0')
252                 p++;
253         if (*p == '\0') {
254                 cdcomppath = NULL;
255         } else {
256                 *p++ = '\0';
257                 cdcomppath = p;
258         }
259         return start;
260 }
261
262
263 static char *
264 findcwd(char *dir)
265 {
266         char *new;
267         char *p;
268
269         /*
270          * If our argument is NULL, we don't know the current directory
271          * any more because we traversed a symbolic link or something
272          * we couldn't stat().
273          */
274         if (dir == NULL || curdir == NULL)
275                 return getpwd2();
276         cdcomppath = stalloc(strlen(dir) + 1);
277         scopy(dir, cdcomppath);
278         STARTSTACKSTR(new);
279         if (*dir != '/') {
280                 p = curdir;
281                 while (*p)
282                         STPUTC(*p++, new);
283                 if (p[-1] == '/')
284                         STUNPUTC(new);
285         }
286         while ((p = getcomponent()) != NULL) {
287                 if (equal(p, "..")) {
288                         while (new > stackblock() && (STUNPUTC(new), *new) != '/');
289                 } else if (*p != '\0' && ! equal(p, ".")) {
290                         STPUTC('/', new);
291                         while (*p)
292                                 STPUTC(*p++, new);
293                 }
294         }
295         if (new == stackblock())
296                 STPUTC('/', new);
297         STACKSTRNUL(new);
298         return stackblock();
299 }
300
301 /*
302  * Update curdir (the name of the current directory) in response to a
303  * cd command.  We also call hashcd to let the routines in exec.c know
304  * that the current directory has changed.
305  */
306 static void
307 updatepwd(char *dir)
308 {
309         hashcd();                               /* update command hash table */
310
311         if (prevdir)
312                 ckfree(prevdir);
313         prevdir = curdir;
314         curdir = savestr(dir);
315         setvar("PWD", curdir, VEXPORT);
316         setvar("OLDPWD", prevdir, VEXPORT);
317 }
318
319 int
320 pwdcmd(int argc, char **argv)
321 {
322         char *p;
323         int ch, phys;
324
325         optreset = 1; optind = 1; opterr = 0; /* initialize getopt */
326         phys = Pflag;
327         while ((ch = getopt(argc, argv, "LP")) != -1) {
328                 switch (ch) {
329                 case 'L':
330                         phys = 0;
331                         break;
332                 case 'P':
333                         phys = 1;
334                         break;
335                 default:
336                         error("unknown option: -%c", optopt);
337                         break;
338                 }
339         }
340         argc -= optind;
341         argv += optind;
342
343         if (argc != 0)
344                 error("too many arguments");
345
346         if (!phys && getpwd()) {
347                 out1str(curdir);
348                 out1c('\n');
349         } else {
350                 if ((p = getpwd2()) == NULL)
351                         error(".: %s", strerror(errno));
352                 out1str(p);
353                 out1c('\n');
354         }
355
356         return 0;
357 }
358
359 /*
360  * Get the current directory and cache the result in curdir.
361  */
362 char *
363 getpwd(void)
364 {
365         char *p;
366
367         if (curdir)
368                 return curdir;
369
370         p = getpwd2();
371         if (p != NULL)
372                 curdir = savestr(p);
373
374         return curdir;
375 }
376
377 #define MAXPWD 256
378
379 /*
380  * Return the current directory.
381  */
382 static char *
383 getpwd2(void)
384 {
385         struct stat stdot, stpwd;
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         pwd = getenv("PWD");
399         if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
400             stat(pwd, &stpwd) != -1 &&
401             stdot.st_dev == stpwd.st_dev &&
402             stdot.st_ino == stpwd.st_ino) {
403                 return pwd;
404         }
405         return NULL;
406 }