1 /*        $NetBSD: old_getcwd.c,v 1.3 2003/08/07 09:51:08 agc Exp $   */
2 
3 /*
4  * Copyright (c) 1989, 1991, 1993, 1995
5  *        The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Jan-Simon Pendry.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * This file copied from NetBSD's src/lib/libc/gen/getcwd.c 1.15, and edited
37  * to remove namespace stuff and the unused realpath function.
38  */
39 
40 
41 #include <sys/cdefs.h>
42 #if defined(LIBC_SCCS) && !defined(lint)
43 #if 0
44 static char sccsid[] = "@(#)getcwd.c    8.5 (Berkeley) 2/7/95";
45 #else
46 __RCSID("$NetBSD: old_getcwd.c,v 1.3 2003/08/07 09:51:08 agc Exp $");
47 #endif
48 #endif /* LIBC_SCCS and not lint */
49 
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 
53 #include <dirent.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 
61 #include "getcwd.h"
62 
63 #define   ISDOT(dp) \
64           (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
65               (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
66 
67 
68 #if defined(__SVR4) || defined(__svr4__)
69 #define d_fileno d_ino
70 #endif
71 
72 char *
old_getcwd(pt,size)73 old_getcwd(pt, size)
74           char *pt;
75           size_t size;
76 {
77           struct dirent *dp;
78           DIR *dir;
79           dev_t dev;
80           ino_t ino;
81           int first;
82           char *bpt, *bup;
83           struct stat s;
84           dev_t root_dev;
85           ino_t root_ino;
86           size_t ptsize, upsize;
87           int save_errno;
88           char *ept, *eup, *up;
89           size_t dlen;
90 
91           /*
92            * If no buffer specified by the user, allocate one as necessary.
93            * If a buffer is specified, the size has to be non-zero.  The path
94            * is built from the end of the buffer backwards.
95            */
96           if (pt) {
97                     ptsize = 0;
98                     if (!size) {
99                               errno = EINVAL;
100                               return (NULL);
101                     }
102                     ept = pt + size;
103           } else {
104                     if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
105                               return (NULL);
106                     ept = pt + ptsize;
107           }
108           bpt = ept - 1;
109           *bpt = '\0';
110 
111           /*
112            * Allocate bytes (1024 - malloc space) for the string of "../"'s.
113            * Should always be enough (it's 340 levels).  If it's not, allocate
114            * as necessary.  Special case the first stat, it's ".", not "..".
115            */
116           if ((up = malloc(upsize = 1024 - 4)) == NULL)
117                     goto err;
118           eup = up + MAXPATHLEN;
119           bup = up;
120           up[0] = '.';
121           up[1] = '\0';
122 
123           /* Save root values, so know when to stop. */
124           if (stat("/", &s))
125                     goto err;
126           root_dev = s.st_dev;
127           root_ino = s.st_ino;
128 
129           errno = 0;                              /* XXX readdir has no error return. */
130 
131           for (first = 1;; first = 0) {
132                     /* Stat the current level. */
133                     if (lstat(up, &s))
134                               goto err;
135 
136                     /* Save current node values. */
137                     ino = s.st_ino;
138                     dev = s.st_dev;
139 
140                     /* Check for reaching root. */
141                     if (root_dev == dev && root_ino == ino) {
142                               *--bpt = '/';
143                               /*
144                                * It's unclear that it's a requirement to copy the
145                                * path to the beginning of the buffer, but it's always
146                                * been that way and stuff would probably break.
147                                */
148                               memmove(pt, bpt,  (size_t)(ept - bpt));
149                               free(up);
150                               return (pt);
151                     }
152 
153                     /*
154                      * Build pointer to the parent directory, allocating memory
155                      * as necessary.  Max length is 3 for "../", the largest
156                      * possible component name, plus a trailing NULL.
157                      */
158                     if (bup + 3  + MAXNAMLEN + 1 >= eup) {
159                               if ((up = realloc(up, upsize *= 2)) == NULL)
160                                         goto err;
161                               bup = up;
162                               eup = up + upsize;
163                     }
164                     *bup++ = '.';
165                     *bup++ = '.';
166                     *bup = '\0';
167 
168                     /* Open and stat parent directory. */
169                     if (!(dir = opendir(up)) || fstat(dirfd(dir), &s))
170                               goto err;
171 
172                     /* Add trailing slash for next directory. */
173                     *bup++ = '/';
174 
175                     /*
176                      * If it's a mount point, have to stat each element because
177                      * the inode number in the directory is for the entry in the
178                      * parent directory, not the inode number of the mounted file.
179                      */
180                     save_errno = 0;
181                     if (s.st_dev == dev) {
182                               for (;;) {
183                                         if (!(dp = readdir(dir)))
184                                                   goto notfound;
185                                         if (dp->d_fileno == ino) {
186 #if defined(__SVR4) || defined(__svr4__)
187                                                   dlen = strlen(dp->d_name);
188 #else
189                                                   dlen = dp->d_namlen;
190 #endif
191                                                   break;
192                                         }
193                               }
194                     } else
195                               for (;;) {
196                                         if (!(dp = readdir(dir)))
197                                                   goto notfound;
198                                         if (ISDOT(dp))
199                                                   continue;
200 #if defined(__SVR4) || defined(__svr4__)
201                                         dlen = strlen(dp->d_name);
202 #else
203                                         dlen = dp->d_namlen;
204 #endif
205                                         memmove(bup, dp->d_name, dlen + 1);
206 
207                                         /* Save the first error for later. */
208                                         if (lstat(up, &s)) {
209                                                   if (!save_errno)
210                                                             save_errno = errno;
211                                                   errno = 0;
212                                                   continue;
213                                         }
214                                         if (s.st_dev == dev && s.st_ino == ino)
215                                                   break;
216                               }
217 
218                     /*
219                      * Check for length of the current name, preceding slash,
220                      * leading slash.
221                      */
222                     if (bpt - pt <= dlen + (first ? 1 : 2)) {
223                               size_t len, off;
224 
225                               if (!ptsize) {
226                                         errno = ERANGE;
227                                         goto err;
228                               }
229                               off = bpt - pt;
230                               len = ept - bpt;
231                               if ((pt = realloc(pt, ptsize *= 2)) == NULL)
232                                         goto err;
233                               bpt = pt + off;
234                               ept = pt + ptsize;
235                               memmove(ept - len, bpt, len);
236                               bpt = ept - len;
237                     }
238                     if (!first)
239                               *--bpt = '/';
240                     bpt -= dlen;
241                     memmove(bpt, dp->d_name, dlen);
242                     (void)closedir(dir);
243 
244                     /* Truncate any file name. */
245                     *bup = '\0';
246           }
247 
248 notfound:
249           /*
250            * If readdir set errno, use it, not any saved error; otherwise,
251            * didn't find the current directory in its parent directory, set
252            * errno to ENOENT.
253            */
254           if (!errno)
255                     errno = save_errno ? save_errno : ENOENT;
256           /* FALLTHROUGH */
257 err:
258           if (ptsize)
259                     free(pt);
260           free(up);
261           return (NULL);
262 }
263