694a94419e44eb412c5b1c40440c09a9c8633406
[dragonfly.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  * 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.
35  *
36  * @(#)cd.c     8.2 (Berkeley) 5/4/95
37  * $FreeBSD: head/bin/sh/cd.c 240541 2012-09-15 21:56:30Z jilles $
38  */
39
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 #include "builtins.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 *getpwd(void);
74 static char *getpwd2(void);
75
76 static char *curdir = NULL;     /* current working directory */
77 static char *prevdir;           /* previous working directory */
78 static char *cdcomppath;
79
80 int
81 cdcmd(int argc __unused, char **argv __unused)
82 {
83         const char *dest;
84         const char *path;
85         char *p;
86         struct stat statb;
87         int ch, phys, print = 0, getcwderr = 0;
88         int rc;
89         int errno1 = ENOENT;
90
91         phys = Pflag;
92         while ((ch = nextopt("eLP")) != '\0') {
93                 switch (ch) {
94                 case 'e':
95                         getcwderr = 1;
96                         break;
97                 case 'L':
98                         phys = 0;
99                         break;
100                 case 'P':
101                         phys = 1;
102                         break;
103                 }
104         }
105
106         if (*argptr != NULL && argptr[1] != NULL)
107                 error("too many arguments");
108
109         if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
110                 error("HOME not set");
111         if (*dest == '\0')
112                 dest = ".";
113         if (dest[0] == '-' && dest[1] == '\0') {
114                 dest = prevdir ? prevdir : curdir;
115                 if (dest)
116                         print = 1;
117                 else
118                         dest = ".";
119         }
120         if (dest[0] == '/' ||
121             (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
122             (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
123             (path = bltinlookup("CDPATH", 1)) == NULL)
124                 path = nullstr;
125         while ((p = padvance(&path, dest)) != NULL) {
126                 if (stat(p, &statb) < 0) {
127                         if (errno != ENOENT)
128                                 errno1 = errno;
129                 } else if (!S_ISDIR(statb.st_mode))
130                         errno1 = ENOTDIR;
131                 else {
132                         if (!print) {
133                                 /*
134                                  * XXX - rethink
135                                  */
136                                 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
137                                         print = strcmp(p + 2, dest);
138                                 else
139                                         print = strcmp(p, dest);
140                         }
141                         rc = docd(p, print, phys);
142                         if (rc >= 0)
143                                 return getcwderr ? rc : 0;
144                         if (errno != ENOENT)
145                                 errno1 = errno;
146                 }
147         }
148         error("%s: %s", dest, strerror(errno1));
149         /*NOTREACHED*/
150         return 0;
151 }
152
153
154 /*
155  * Actually change the directory.  In an interactive shell, print the
156  * directory name if "print" is nonzero.
157  */
158 static int
159 docd(char *dest, int print, int phys)
160 {
161         int rc;
162
163         TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
164
165         /* If logical cd fails, fall back to physical. */
166         if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
167                 return (-1);
168
169         if (print && iflag && curdir)
170                 out1fmt("%s\n", curdir);
171
172         return (rc);
173 }
174
175 static int
176 cdlogical(char *dest)
177 {
178         char *p;
179         char *q;
180         char *component;
181         struct stat statb;
182         int first;
183         int badstat;
184
185         /*
186          *  Check each component of the path. If we find a symlink or
187          *  something we can't stat, clear curdir to force a getcwd()
188          *  next time we get the value of the current directory.
189          */
190         badstat = 0;
191         cdcomppath = stalloc(strlen(dest) + 1);
192         scopy(dest, cdcomppath);
193         STARTSTACKSTR(p);
194         if (*dest == '/') {
195                 STPUTC('/', p);
196                 cdcomppath++;
197         }
198         first = 1;
199         while ((q = getcomponent()) != NULL) {
200                 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
201                         continue;
202                 if (! first)
203                         STPUTC('/', p);
204                 first = 0;
205                 component = q;
206                 STPUTS(q, p);
207                 if (equal(component, ".."))
208                         continue;
209                 STACKSTRNUL(p);
210                 if (lstat(stackblock(), &statb) < 0) {
211                         badstat = 1;
212                         break;
213                 }
214         }
215
216         INTOFF;
217         if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
218                 INTON;
219                 return (-1);
220         }
221         updatepwd(p);
222         INTON;
223         return (0);
224 }
225
226 static int
227 cdphysical(char *dest)
228 {
229         char *p;
230         int rc = 0;
231
232         INTOFF;
233         if (chdir(dest) < 0) {
234                 INTON;
235                 return (-1);
236         }
237         p = findcwd(NULL);
238         if (p == NULL) {
239                 warning("warning: failed to get name of current directory");
240                 rc = 1;
241         }
242         updatepwd(p);
243         INTON;
244         return (rc);
245 }
246
247 /*
248  * Get the next component of the path name pointed to by cdcomppath.
249  * This routine overwrites the string pointed to by cdcomppath.
250  */
251 static char *
252 getcomponent(void)
253 {
254         char *p;
255         char *start;
256
257         if ((p = cdcomppath) == NULL)
258                 return NULL;
259         start = cdcomppath;
260         while (*p != '/' && *p != '\0')
261                 p++;
262         if (*p == '\0') {
263                 cdcomppath = NULL;
264         } else {
265                 *p++ = '\0';
266                 cdcomppath = p;
267         }
268         return start;
269 }
270
271
272 static char *
273 findcwd(char *dir)
274 {
275         char *new;
276         char *p;
277
278         /*
279          * If our argument is NULL, we don't know the current directory
280          * any more because we traversed a symbolic link or something
281          * we couldn't stat().
282          */
283         if (dir == NULL || curdir == NULL)
284                 return getpwd2();
285         cdcomppath = stalloc(strlen(dir) + 1);
286         scopy(dir, cdcomppath);
287         STARTSTACKSTR(new);
288         if (*dir != '/') {
289                 STPUTS(curdir, new);
290                 if (STTOPC(new) == '/')
291                         STUNPUTC(new);
292         }
293         while ((p = getcomponent()) != NULL) {
294                 if (equal(p, "..")) {
295                         while (new > stackblock() && (STUNPUTC(new), *new) != '/');
296                 } else if (*p != '\0' && ! equal(p, ".")) {
297                         STPUTC('/', new);
298                         STPUTS(p, new);
299                 }
300         }
301         if (new == stackblock())
302                 STPUTC('/', new);
303         STACKSTRNUL(new);
304         return stackblock();
305 }
306
307 /*
308  * Update curdir (the name of the current directory) in response to a
309  * cd command.  We also call hashcd to let the routines in exec.c know
310  * that the current directory has changed.
311  */
312 static void
313 updatepwd(char *dir)
314 {
315         hashcd();                               /* update command hash table */
316
317         if (prevdir)
318                 ckfree(prevdir);
319         prevdir = curdir;
320         curdir = dir ? savestr(dir) : NULL;
321         setvar("PWD", curdir, VEXPORT);
322         setvar("OLDPWD", prevdir, VEXPORT);
323 }
324
325 int
326 pwdcmd(int argc __unused, char **argv __unused)
327 {
328         char *p;
329         int ch, phys;
330
331         phys = Pflag;
332         while ((ch = nextopt("LP")) != '\0') {
333                 switch (ch) {
334                 case 'L':
335                         phys = 0;
336                         break;
337                 case 'P':
338                         phys = 1;
339                         break;
340                 }
341         }
342
343         if (*argptr != NULL)
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 static 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         char *pwd;
386         int i;
387
388         for (i = MAXPWD;; i *= 2) {
389                 pwd = stalloc(i);
390                 if (getcwd(pwd, i) != NULL)
391                         return pwd;
392                 stunalloc(pwd);
393                 if (errno != ERANGE)
394                         break;
395         }
396
397         return NULL;
398 }
399
400 /*
401  * Initialize PWD in a new shell.
402  * If the shell is interactive, we need to warn if this fails.
403  */
404 void
405 pwd_init(int warn)
406 {
407         char *pwd;
408         struct stat stdot, stpwd;
409
410         pwd = lookupvar("PWD");
411         if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
412             stat(pwd, &stpwd) != -1 &&
413             stdot.st_dev == stpwd.st_dev &&
414             stdot.st_ino == stpwd.st_ino) {
415                 if (curdir)
416                         ckfree(curdir);
417                 curdir = savestr(pwd);
418         }
419         if (getpwd() == NULL && warn)
420                 out2fmt_flush("sh: cannot determine working directory\n");
421         setvar("PWD", curdir, VEXPORT);
422 }