xref: /dragonfly/contrib/grep/lib/chdir-long.c (revision 279dd846)
1 /* provide a chdir function that tries not to fail due to ENAMETOOLONG
2    Copyright (C) 2004-2014 Free Software Foundation, Inc.
3 
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16 
17 /* written by Jim Meyering */
18 
19 #include <config.h>
20 
21 #include "chdir-long.h"
22 
23 #include <assert.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <stdbool.h>
28 #include <string.h>
29 #include <stdio.h>
30 
31 #ifndef PATH_MAX
32 # error "compile this file only if your system defines PATH_MAX"
33 #endif
34 
35 /* The results of openat() in this file are not leaked to any
36    single-threaded code that could use stdio.
37    FIXME - if the kernel ever adds support for multi-thread safety for
38    avoiding standard fds, then we should use openat_safer.  */
39 
40 struct cd_buf
41 {
42   int fd;
43 };
44 
45 static void
46 cdb_init (struct cd_buf *cdb)
47 {
48   cdb->fd = AT_FDCWD;
49 }
50 
51 static int
52 cdb_fchdir (struct cd_buf const *cdb)
53 {
54   return fchdir (cdb->fd);
55 }
56 
57 static void
58 cdb_free (struct cd_buf const *cdb)
59 {
60   if (0 <= cdb->fd)
61     {
62       bool close_fail = close (cdb->fd);
63       assert (! close_fail);
64     }
65 }
66 
67 /* Given a file descriptor of an open directory (or AT_FDCWD), CDB->fd,
68    try to open the CDB->fd-relative directory, DIR.  If the open succeeds,
69    update CDB->fd with the resulting descriptor, close the incoming file
70    descriptor, and return zero.  Upon failure, return -1 and set errno.  */
71 static int
72 cdb_advance_fd (struct cd_buf *cdb, char const *dir)
73 {
74   int new_fd = openat (cdb->fd, dir,
75                        O_SEARCH | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);
76   if (new_fd < 0)
77     return -1;
78 
79   cdb_free (cdb);
80   cdb->fd = new_fd;
81 
82   return 0;
83 }
84 
85 /* Return a pointer to the first non-slash in S.  */
86 static char * _GL_ATTRIBUTE_PURE
87 find_non_slash (char const *s)
88 {
89   size_t n_slash = strspn (s, "/");
90   return (char *) s + n_slash;
91 }
92 
93 /* This is a function much like chdir, but without the PATH_MAX limitation
94    on the length of the directory name.  A significant difference is that
95    it must be able to modify (albeit only temporarily) the directory
96    name.  It handles an arbitrarily long directory name by operating
97    on manageable portions of the name.  On systems without the openat
98    syscall, this means changing the working directory to more and more
99    "distant" points along the long directory name and then restoring
100    the working directory.  If any of those attempts to save or restore
101    the working directory fails, this function exits nonzero.
102 
103    Note that this function may still fail with errno == ENAMETOOLONG, but
104    only if the specified directory name contains a component that is long
105    enough to provoke such a failure all by itself (e.g. if the component
106    has length PATH_MAX or greater on systems that define PATH_MAX).  */
107 
108 int
109 chdir_long (char *dir)
110 {
111   int e = chdir (dir);
112   if (e == 0 || errno != ENAMETOOLONG)
113     return e;
114 
115   {
116     size_t len = strlen (dir);
117     char *dir_end = dir + len;
118     struct cd_buf cdb;
119     size_t n_leading_slash;
120 
121     cdb_init (&cdb);
122 
123     /* If DIR is the empty string, then the chdir above
124        must have failed and set errno to ENOENT.  */
125     assert (0 < len);
126     assert (PATH_MAX <= len);
127 
128     /* Count leading slashes.  */
129     n_leading_slash = strspn (dir, "/");
130 
131     /* Handle any leading slashes as well as any name that matches
132        the regular expression, m!^//hostname[/]*! .  Handling this
133        prefix separately usually results in a single additional
134        cdb_advance_fd call, but it's worthwhile, since it makes the
135        code in the following loop cleaner.  */
136     if (n_leading_slash == 2)
137       {
138         int err;
139         /* Find next slash.
140            We already know that dir[2] is neither a slash nor '\0'.  */
141         char *slash = memchr (dir + 3, '/', dir_end - (dir + 3));
142         if (slash == NULL)
143           {
144             errno = ENAMETOOLONG;
145             return -1;
146           }
147         *slash = '\0';
148         err = cdb_advance_fd (&cdb, dir);
149         *slash = '/';
150         if (err != 0)
151           goto Fail;
152         dir = find_non_slash (slash + 1);
153       }
154     else if (n_leading_slash)
155       {
156         if (cdb_advance_fd (&cdb, "/") != 0)
157           goto Fail;
158         dir += n_leading_slash;
159       }
160 
161     assert (*dir != '/');
162     assert (dir <= dir_end);
163 
164     while (PATH_MAX <= dir_end - dir)
165       {
166         int err;
167         /* Find a slash that is PATH_MAX or fewer bytes away from dir.
168            I.e. see if there is a slash that will give us a name of
169            length PATH_MAX-1 or less.  */
170         char *slash = memrchr (dir, '/', PATH_MAX);
171         if (slash == NULL)
172           {
173             errno = ENAMETOOLONG;
174             return -1;
175           }
176 
177         *slash = '\0';
178         assert (slash - dir < PATH_MAX);
179         err = cdb_advance_fd (&cdb, dir);
180         *slash = '/';
181         if (err != 0)
182           goto Fail;
183 
184         dir = find_non_slash (slash + 1);
185       }
186 
187     if (dir < dir_end)
188       {
189         if (cdb_advance_fd (&cdb, dir) != 0)
190           goto Fail;
191       }
192 
193     if (cdb_fchdir (&cdb) != 0)
194       goto Fail;
195 
196     cdb_free (&cdb);
197     return 0;
198 
199    Fail:
200     {
201       int saved_errno = errno;
202       cdb_free (&cdb);
203       errno = saved_errno;
204       return -1;
205     }
206   }
207 }
208 
209 #if TEST_CHDIR
210 
211 # include "closeout.h"
212 # include "error.h"
213 
214 char *program_name;
215 
216 int
217 main (int argc, char *argv[])
218 {
219   char *line = NULL;
220   size_t n = 0;
221   int len;
222 
223   program_name = argv[0];
224   atexit (close_stdout);
225 
226   len = getline (&line, &n, stdin);
227   if (len < 0)
228     {
229       int saved_errno = errno;
230       if (feof (stdin))
231         exit (0);
232 
233       error (EXIT_FAILURE, saved_errno,
234              "reading standard input");
235     }
236   else if (len == 0)
237     exit (0);
238 
239   if (line[len-1] == '\n')
240     line[len-1] = '\0';
241 
242   if (chdir_long (line) != 0)
243     error (EXIT_FAILURE, errno,
244            "chdir_long failed: %s", line);
245 
246   if (argc <= 1)
247     {
248       /* Using 'pwd' here makes sense only if it is a robust implementation,
249          like the one in coreutils after the 2004-04-19 changes.  */
250       char const *cmd = "pwd";
251       execlp (cmd, (char *) NULL);
252       error (EXIT_FAILURE, errno, "%s", cmd);
253     }
254 
255   fclose (stdin);
256   fclose (stderr);
257 
258   exit (EXIT_SUCCESS);
259 }
260 #endif
261 
262 /*
263 Local Variables:
264 compile-command: "gcc -DTEST_CHDIR=1 -g -O -W -Wall chdir-long.c libcoreutils.a"
265 End:
266 */
267