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