Set POSIX feature test macros to the correct value as mendated by SUS.
[dragonfly.git] / contrib / cvs-1.12.12 / 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 "memrchr.h"
34 #include "openat.h"
35
36 #ifndef O_DIRECTORY
37 # define O_DIRECTORY 0
38 #endif
39
40 #ifndef PATH_MAX
41 # error "compile this file only if your system defines PATH_MAX"
42 #endif
43
44 struct cd_buf
45 {
46   int fd;
47 };
48
49 static inline void
50 cdb_init (struct cd_buf *cdb)
51 {
52   cdb->fd = AT_FDCWD;
53 }
54
55 static inline int
56 cdb_fchdir (struct cd_buf const *cdb)
57 {
58   return fchdir (cdb->fd);
59 }
60
61 static inline void
62 cdb_free (struct cd_buf const *cdb)
63 {
64   if (0 <= cdb->fd)
65     {
66       bool close_fail = close (cdb->fd);
67       assert (! close_fail);
68     }
69 }
70
71 /* Given a file descriptor of an open directory (or AT_FDCWD), CDB->fd,
72    try to open the CDB->fd-relative directory, DIR.  If the open succeeds,
73    update CDB->fd with the resulting descriptor, close the incoming file
74    descriptor, and return zero.  Upon failure, return -1 and set errno.  */
75 static int
76 cdb_advance_fd (struct cd_buf *cdb, char const *dir)
77 {
78   int new_fd = openat (cdb->fd, dir, O_RDONLY | O_DIRECTORY);
79   if (new_fd < 0)
80     {
81       new_fd = openat (cdb->fd, dir, O_WRONLY | O_DIRECTORY);
82       if (new_fd < 0)
83         return -1;
84     }
85
86   cdb_free (cdb);
87   cdb->fd = new_fd;
88
89   return 0;
90 }
91
92 /* Return a pointer to the first non-slash in S.  */
93 static inline char *
94 find_non_slash (char const *s)
95 {
96   size_t n_slash = strspn (s, "/");
97   return (char *) s + n_slash;
98 }
99
100 /* This is a function much like chdir, but without the PATH_MAX limitation
101    on the length of the directory name.  A significant difference is that
102    it must be able to modify (albeit only temporarily) the directory
103    name.  It handles an arbitrarily long directory name by operating
104    on manageable portions of the name.  On systems without the openat
105    syscall, this means changing the working directory to more and more
106    `distant' points along the long directory name and then restoring
107    the working directory.  If any of those attempts to save or restore
108    the working directory fails, this function exits nonzero.
109
110    Note that this function may still fail with errno == ENAMETOOLONG, but
111    only if the specified directory name contains a component that is long
112    enough to provoke such a failure all by itself (e.g. if the component
113    has length PATH_MAX or greater on systems that define PATH_MAX).  */
114
115 int
116 chdir_long (char *dir)
117 {
118   int e = chdir (dir);
119   if (e == 0 || errno != ENAMETOOLONG)
120     return e;
121
122   {
123     size_t len = strlen (dir);
124     char *dir_end = dir + len;
125     struct cd_buf cdb;
126     size_t n_leading_slash;
127
128     cdb_init (&cdb);
129
130     /* If DIR is the empty string, then the chdir above
131        must have failed and set errno to ENOENT.  */
132     assert (0 < len);
133     assert (PATH_MAX <= len);
134
135     /* Count leading slashes.  */
136     n_leading_slash = strspn (dir, "/");
137
138     /* Handle any leading slashes as well as any name that matches
139        the regular expression, m!^//hostname[/]*! .  Handling this
140        prefix separately usually results in a single additional
141        cdb_advance_fd call, but it's worthwhile, since it makes the
142        code in the following loop cleaner.  */
143     if (n_leading_slash == 2)
144       {
145         int err;
146         /* Find next slash.
147            We already know that dir[2] is neither a slash nor '\0'.  */
148         char *slash = memchr (dir + 3, '/', dir_end - (dir + 3));
149         if (slash == NULL)
150           {
151             errno = ENAMETOOLONG;
152             return -1;
153           }
154         *slash = '\0';
155         err = cdb_advance_fd (&cdb, dir);
156         *slash = '/';
157         if (err != 0)
158           goto Fail;
159         dir = find_non_slash (slash + 1);
160       }
161     else if (n_leading_slash)
162       {
163         if (cdb_advance_fd (&cdb, "/") != 0)
164           goto Fail;
165         dir += n_leading_slash;
166       }
167
168     assert (*dir != '/');
169     assert (dir <= dir_end);
170
171     while (PATH_MAX <= dir_end - dir)
172       {
173         int err;
174         /* Find a slash that is PATH_MAX or fewer bytes away from dir.
175            I.e. see if there is a slash that will give us a name of
176            length PATH_MAX-1 or less.  */
177         char *slash = memrchr (dir, '/', PATH_MAX);
178         if (slash == NULL)
179           {
180             errno = ENAMETOOLONG;
181             return -1;
182           }
183
184         *slash = '\0';
185         assert (slash - dir < PATH_MAX);
186         err = cdb_advance_fd (&cdb, dir);
187         *slash = '/';
188         if (err != 0)
189           goto Fail;
190
191         dir = find_non_slash (slash + 1);
192       }
193
194     if (dir < dir_end)
195       {
196         if (cdb_advance_fd (&cdb, dir) != 0)
197           goto Fail;
198       }
199
200     if (cdb_fchdir (&cdb) != 0)
201       goto Fail;
202
203     cdb_free (&cdb);
204     return 0;
205
206    Fail:
207     {
208       int saved_errno = errno;
209       cdb_free (&cdb);
210       errno = saved_errno;
211       return -1;
212     }
213   }
214 }
215
216 #if TEST_CHDIR
217
218 # include <stdio.h>
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 -DHAVE_CONFIG_H -I.. -g -O -W -Wall chdir-long.c libfetish.a"
273 End:
274 */