1 /* Target directory operands for coreutils
3 Copyright 2004-2024 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
20 #define TARGETDIR_INLINE _GL_EXTERN_INLINE
21 #include <targetdir.h>
23 #include <attribute.h>
31 enum { O_PATHSEARCH
= O_PATH
};
33 enum { O_PATHSEARCH
= O_SEARCH
};
36 /* Must F designate the working directory? */
38 ATTRIBUTE_PURE
static bool
39 must_be_working_directory (char const *f
)
41 /* Return true for ".", "./.", ".///./", etc. */
54 /* Return a file descriptor open to FILE, for use in openat.
55 As an optimization, return AT_FDCWD if FILE must be the working directory.
56 As a side effect, possibly set *ST to the file's status.
57 Fail and set errno if FILE is not a directory.
58 On failure return -2 if AT_FDCWD is -1, -1 otherwise. */
61 target_directory_operand (char const *file
, struct stat
*st
)
63 if (must_be_working_directory (file
))
70 /* On old systems without O_DIRECTORY, like Solaris 10, check with
71 stat first lest we try to open a fifo for example and hang. */
74 stat_result
= stat (file
, st
);
77 try_to_open
= S_ISDIR (st
->st_mode
);
82 /* On EOVERFLOW failure, give up on checking, as there is no
83 easy way to check. This should be rare. */
84 try_to_open
= errno
== EOVERFLOW
;
90 fd
= open (file
, O_PATHSEARCH
| O_DIRECTORY
);
92 /* On platforms lacking O_PATH, using O_SEARCH | O_DIRECTORY to
93 open an overly-protected non-directory can fail with either
94 EACCES or ENOTDIR. Prefer ENOTDIR as it makes for better
96 if (O_PATHSEARCH
== O_SEARCH
&& fd
< 0 && errno
== EACCES
)
97 errno
= (((O_DIRECTORY
? stat (file
, st
) : stat_result
) == 0
98 && !S_ISDIR (st
->st_mode
))
102 if (!O_DIRECTORY
&& 0 <= fd
)
104 /* On old systems like Solaris 10 double check type,
105 to ensure we've opened a directory. */
107 if (fstat (fd
, st
) == 0
108 ? !S_ISDIR (st
->st_mode
) && (err
= ENOTDIR
, true)
109 : (err
= errno
) != EOVERFLOW
)
117 return fd
- (AT_FDCWD
== -1 && fd
< 0);