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