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