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