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