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