1 /* Open a descriptor to a file.
2    Copyright (C) 2007-2021 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 <https://www.gnu.org/licenses/>.  */
16 
17 /* Written by Bruno Haible <bruno@clisp.org>, 2007.  */
18 
19 /* If the user's config.h happens to include <fcntl.h>, let it include only
20    the system's <fcntl.h> here, so that orig_open doesn't recurse to
21    rpl_open.  */
22 #define __need_system_fcntl_h
23 #include <config.h>
24 
25 /* Get the original definition of open.  It might be defined as a macro.  */
26 #include <fcntl.h>
27 #include <sys/types.h>
28 #undef __need_system_fcntl_h
29 
30 static int
orig_open(const char * filename,int flags,mode_t mode)31 orig_open (const char *filename, int flags, mode_t mode)
32 {
33 #if defined _WIN32 && !defined __CYGWIN__
34   return _open (filename, flags, mode);
35 #else
36   return open (filename, flags, mode);
37 #endif
38 }
39 
40 /* Specification.  */
41 /* Write "fcntl.h" here, not <fcntl.h>, otherwise OSF/1 5.1 DTK cc eliminates
42    this include because of the preliminary #include <fcntl.h> above.  */
43 #include "fcntl.h"
44 
45 #include "cloexec.h"
46 
47 #include <errno.h>
48 #include <stdarg.h>
49 #include <string.h>
50 #include <sys/types.h>
51 #include <sys/stat.h>
52 #include <unistd.h>
53 
54 #ifndef REPLACE_OPEN_DIRECTORY
55 # define REPLACE_OPEN_DIRECTORY 0
56 #endif
57 
58 int
open(const char * filename,int flags,...)59 open (const char *filename, int flags, ...)
60 {
61   /* 0 = unknown, 1 = yes, -1 = no.  */
62 #if GNULIB_defined_O_CLOEXEC
63   int have_cloexec = -1;
64 #else
65   static int have_cloexec;
66 #endif
67 
68   mode_t mode;
69   int fd;
70 
71   mode = 0;
72   if (flags & O_CREAT)
73     {
74       va_list arg;
75       va_start (arg, flags);
76 
77       /* We have to use PROMOTED_MODE_T instead of mode_t, otherwise GCC 4
78          creates crashing code when 'mode_t' is smaller than 'int'.  */
79       mode = va_arg (arg, PROMOTED_MODE_T);
80 
81       va_end (arg);
82     }
83 
84 #if GNULIB_defined_O_NONBLOCK
85   /* The only known platform that lacks O_NONBLOCK is mingw, but it
86      also lacks named pipes and Unix sockets, which are the only two
87      file types that require non-blocking handling in open().
88      Therefore, it is safe to ignore O_NONBLOCK here.  It is handy
89      that mingw also lacks openat(), so that is also covered here.  */
90   flags &= ~O_NONBLOCK;
91 #endif
92 
93 #if defined _WIN32 && ! defined __CYGWIN__
94   if (strcmp (filename, "/dev/null") == 0)
95     filename = "NUL";
96 #endif
97 
98 #if OPEN_TRAILING_SLASH_BUG
99   /* Fail if one of O_CREAT, O_WRONLY, O_RDWR is specified and the filename
100      ends in a slash, as POSIX says such a filename must name a directory
101      <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>:
102        "A pathname that contains at least one non-<slash> character and that
103         ends with one or more trailing <slash> characters shall not be resolved
104         successfully unless the last pathname component before the trailing
105         <slash> characters names an existing directory"
106      If the named file already exists as a directory, then
107        - if O_CREAT is specified, open() must fail because of the semantics
108          of O_CREAT,
109        - if O_WRONLY or O_RDWR is specified, open() must fail because POSIX
110          <https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html>
111          says that it fails with errno = EISDIR in this case.
112      If the named file does not exist or does not name a directory, then
113        - if O_CREAT is specified, open() must fail since open() cannot create
114          directories,
115        - if O_WRONLY or O_RDWR is specified, open() must fail because the
116          file does not contain a '.' directory.  */
117   if ((flags & O_CREAT)
118       || (flags & O_ACCMODE) == O_RDWR
119       || (flags & O_ACCMODE) == O_WRONLY)
120     {
121       size_t len = strlen (filename);
122       if (len > 0 && filename[len - 1] == '/')
123         {
124           errno = EISDIR;
125           return -1;
126         }
127     }
128 #endif
129 
130   fd = orig_open (filename,
131                   flags & ~(have_cloexec < 0 ? O_CLOEXEC : 0), mode);
132 
133   if (flags & O_CLOEXEC)
134     {
135       if (! have_cloexec)
136         {
137           if (0 <= fd)
138             have_cloexec = 1;
139           else if (errno == EINVAL)
140             {
141               fd = orig_open (filename, flags & ~O_CLOEXEC, mode);
142               have_cloexec = -1;
143             }
144         }
145       if (have_cloexec < 0 && 0 <= fd)
146         set_cloexec_flag (fd, true);
147     }
148 
149 
150 #if REPLACE_FCHDIR
151   /* Implementing fchdir and fdopendir requires the ability to open a
152      directory file descriptor.  If open doesn't support that (as on
153      mingw), we use a dummy file that behaves the same as directories
154      on Linux (ie. always reports EOF on attempts to read()), and
155      override fstat() in fchdir.c to hide the fact that we have a
156      dummy.  */
157   if (REPLACE_OPEN_DIRECTORY && fd < 0 && errno == EACCES
158       && ((flags & O_ACCMODE) == O_RDONLY
159           || (O_SEARCH != O_RDONLY && (flags & O_ACCMODE) == O_SEARCH)))
160     {
161       struct stat statbuf;
162       if (stat (filename, &statbuf) == 0 && S_ISDIR (statbuf.st_mode))
163         {
164           /* Maximum recursion depth of 1.  */
165           fd = open ("/dev/null", flags, mode);
166           if (0 <= fd)
167             fd = _gl_register_fd (fd, filename);
168         }
169       else
170         errno = EACCES;
171     }
172 #endif
173 
174 #if OPEN_TRAILING_SLASH_BUG
175   /* If the filename ends in a slash and fd does not refer to a directory,
176      then fail.
177      Rationale: POSIX says such a filename must name a directory
178      <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>:
179        "A pathname that contains at least one non-<slash> character and that
180         ends with one or more trailing <slash> characters shall not be resolved
181         successfully unless the last pathname component before the trailing
182         <slash> characters names an existing directory"
183      If the named file without the slash is not a directory, open() must fail
184      with ENOTDIR.  */
185   if (fd >= 0)
186     {
187       /* We know len is positive, since open did not fail with ENOENT.  */
188       size_t len = strlen (filename);
189       if (filename[len - 1] == '/')
190         {
191           struct stat statbuf;
192 
193           if (fstat (fd, &statbuf) >= 0 && !S_ISDIR (statbuf.st_mode))
194             {
195               close (fd);
196               errno = ENOTDIR;
197               return -1;
198             }
199         }
200     }
201 #endif
202 
203 #if REPLACE_FCHDIR
204   if (!REPLACE_OPEN_DIRECTORY && 0 <= fd)
205     fd = _gl_register_fd (fd, filename);
206 #endif
207 
208   return fd;
209 }
210