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