1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* Work around platform bugs in stat.
4    Copyright (C) 2009-2019 Free Software Foundation, Inc.
5 
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10 
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
18 
19 /* Written by Eric Blake and Bruno Haible.  */
20 
21 /* If the user's config.h happens to include <sys/stat.h>, let it include only
22    the system's <sys/stat.h> here, so that orig_stat doesn't recurse to
23    rpl_stat.  */
24 #define __need_system_sys_stat_h
25 #include <config.h>
26 
27 /* Get the original definition of stat.  It might be defined as a macro.  */
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #undef __need_system_sys_stat_h
31 
32 #if defined _WIN32 && ! defined __CYGWIN__
33 # define WINDOWS_NATIVE
34 #endif
35 
36 #if !defined WINDOWS_NATIVE
37 
38 static int
orig_stat(const char * filename,struct stat * buf)39 orig_stat (const char *filename, struct stat *buf)
40 {
41   return stat (filename, buf);
42 }
43 
44 #endif
45 
46 /* Specification.  */
47 /* Write "sys/stat.h" here, not <sys/stat.h>, otherwise OSF/1 5.1 DTK cc
48    eliminates this include because of the preliminary #include <sys/stat.h>
49    above.  */
50 #include "sys/stat.h"
51 
52 #include "stat-time.h"
53 
54 #include <errno.h>
55 #include <limits.h>
56 #include <stdbool.h>
57 #include <string.h>
58 #include "filename.h"
59 #include "malloca.h"
60 #include "verify.h"
61 
62 #ifdef WINDOWS_NATIVE
63 # define WIN32_LEAN_AND_MEAN
64 # include <windows.h>
65 # include "stat-w32.h"
66 #endif
67 
68 #ifdef WINDOWS_NATIVE
69 /* Return TRUE if the given file name denotes an UNC root.  */
70 static BOOL
is_unc_root(const char * rname)71 is_unc_root (const char *rname)
72 {
73   /* Test whether it has the syntax '\\server\share'.  */
74   if (ISSLASH (rname[0]) && ISSLASH (rname[1]))
75     {
76       /* It starts with two slashes.  Find the next slash.  */
77       const char *p = rname + 2;
78       const char *q = p;
79       while (*q != '\0' && !ISSLASH (*q))
80         q++;
81       if (q > p && *q != '\0')
82         {
83           /* Found the next slash at q.  */
84           q++;
85           const char *r = q;
86           while (*r != '\0' && !ISSLASH (*r))
87             r++;
88           if (r > q && *r == '\0')
89             return TRUE;
90         }
91     }
92   return FALSE;
93 }
94 #endif
95 
96 /* Store information about NAME into ST.  Work around bugs with
97    trailing slashes.  Mingw has other bugs (such as st_ino always
98    being 0 on success) which this wrapper does not work around.  But
99    at least this implementation provides the ability to emulate fchdir
100    correctly.  */
101 
102 int
rpl_stat(char const * name,struct stat * buf)103 rpl_stat (char const *name, struct stat *buf)
104 {
105 #ifdef WINDOWS_NATIVE
106   /* Fill the fields ourselves, because the original stat function returns
107      values for st_atime, st_mtime, st_ctime that depend on the current time
108      zone.  See
109      <https://lists.gnu.org/r/bug-gnulib/2017-04/msg00134.html>  */
110   /* XXX Should we convert to wchar_t* and prepend '\\?\', in order to work
111      around length limitations
112      <https://msdn.microsoft.com/en-us/library/aa365247.aspx> ?  */
113 
114   /* POSIX <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>
115      specifies: "More than two leading <slash> characters shall be treated as
116      a single <slash> character."  */
117   if (ISSLASH (name[0]) && ISSLASH (name[1]) && ISSLASH (name[2]))
118     {
119       name += 2;
120       while (ISSLASH (name[1]))
121         name++;
122     }
123 
124   size_t len = strlen (name);
125   size_t drive_prefix_len = (HAS_DEVICE (name) ? 2 : 0);
126 
127   /* Remove trailing slashes (except the very first one, at position
128      drive_prefix_len), but remember their presence.  */
129   size_t rlen;
130   bool check_dir = false;
131 
132   rlen = len;
133   while (rlen > drive_prefix_len && ISSLASH (name[rlen-1]))
134     {
135       check_dir = true;
136       if (rlen == drive_prefix_len + 1)
137         break;
138       rlen--;
139     }
140 
141   /* Handle '' and 'C:'.  */
142   if (!check_dir && rlen == drive_prefix_len)
143     {
144       errno = ENOENT;
145       return -1;
146     }
147 
148   /* Handle '\\'.  */
149   if (rlen == 1 && ISSLASH (name[0]) && len >= 2)
150     {
151       errno = ENOENT;
152       return -1;
153     }
154 
155   const char *rname;
156   char *malloca_rname;
157   if (rlen == len)
158     {
159       rname = name;
160       malloca_rname = NULL;
161     }
162   else
163     {
164       malloca_rname = malloca (rlen + 1);
165       if (malloca_rname == NULL)
166         {
167           errno = ENOMEM;
168           return -1;
169         }
170       memcpy (malloca_rname, name, rlen);
171       malloca_rname[rlen] = '\0';
172       rname = malloca_rname;
173     }
174 
175   /* There are two ways to get at the requested information:
176        - by scanning the parent directory and examining the relevant
177          directory entry,
178        - by opening the file directly.
179      The first approach fails for root directories (e.g. 'C:\') and
180      UNC root directories (e.g. '\\server\share').
181      The second approach fails for some system files (e.g. 'C:\pagefile.sys'
182      and 'C:\hiberfil.sys'): ERROR_SHARING_VIOLATION.
183      The second approach gives more information (in particular, correct
184      st_dev, st_ino, st_nlink fields).
185      So we use the second approach and, as a fallback except for root and
186      UNC root directories, also the first approach.  */
187   {
188     int ret;
189 
190     {
191       /* Approach based on the file.  */
192 
193       /* Open a handle to the file.
194          CreateFile
195          <https://msdn.microsoft.com/en-us/library/aa363858.aspx>
196          <https://msdn.microsoft.com/en-us/library/aa363874.aspx>  */
197       HANDLE h =
198         CreateFile (rname,
199                     FILE_READ_ATTRIBUTES,
200                     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
201                     NULL,
202                     OPEN_EXISTING,
203                     /* FILE_FLAG_POSIX_SEMANTICS (treat file names that differ only
204                        in case as different) makes sense only when applied to *all*
205                        filesystem operations.  */
206                     FILE_FLAG_BACKUP_SEMANTICS /* | FILE_FLAG_POSIX_SEMANTICS */,
207                     NULL);
208       if (h != INVALID_HANDLE_VALUE)
209         {
210           ret = _gl_fstat_by_handle (h, rname, buf);
211           CloseHandle (h);
212           goto done;
213         }
214     }
215 
216     /* Test for root and UNC root directories.  */
217     if ((rlen == drive_prefix_len + 1 && ISSLASH (rname[drive_prefix_len]))
218         || is_unc_root (rname))
219       goto failed;
220 
221     /* Fallback.  */
222     {
223       /* Approach based on the directory entry.  */
224 
225       if (strchr (rname, '?') != NULL || strchr (rname, '*') != NULL)
226         {
227           /* Other Windows API functions would fail with error
228              ERROR_INVALID_NAME.  */
229           if (malloca_rname != NULL)
230             freea (malloca_rname);
231           errno = ENOENT;
232           return -1;
233         }
234 
235       /* Get the details about the directory entry.  This can be done through
236          FindFirstFile
237          <https://msdn.microsoft.com/en-us/library/aa364418.aspx>
238          <https://msdn.microsoft.com/en-us/library/aa365740.aspx>
239          or through
240          FindFirstFileEx with argument FindExInfoBasic
241          <https://msdn.microsoft.com/en-us/library/aa364419.aspx>
242          <https://msdn.microsoft.com/en-us/library/aa364415.aspx>
243          <https://msdn.microsoft.com/en-us/library/aa365740.aspx>  */
244       WIN32_FIND_DATA info;
245       HANDLE h = FindFirstFile (rname, &info);
246       if (h == INVALID_HANDLE_VALUE)
247         goto failed;
248 
249       /* Test for error conditions before starting to fill *buf.  */
250       if (sizeof (buf->st_size) <= 4 && info.nFileSizeHigh > 0)
251         {
252           FindClose (h);
253           if (malloca_rname != NULL)
254             freea (malloca_rname);
255           errno = EOVERFLOW;
256           return -1;
257         }
258 
259 # if _GL_WINDOWS_STAT_INODES
260       buf->st_dev = 0;
261 #  if _GL_WINDOWS_STAT_INODES == 2
262       buf->st_ino._gl_ino[0] = buf->st_ino._gl_ino[1] = 0;
263 #  else /* _GL_WINDOWS_STAT_INODES == 1 */
264       buf->st_ino = 0;
265 #  endif
266 # else
267       /* st_ino is not wide enough for identifying a file on a device.
268          Without st_ino, st_dev is pointless.  */
269       buf->st_dev = 0;
270       buf->st_ino = 0;
271 # endif
272 
273       /* st_mode.  */
274       unsigned int mode =
275         /* XXX How to handle FILE_ATTRIBUTE_REPARSE_POINT ?  */
276         ((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? _S_IFDIR | S_IEXEC_UGO : _S_IFREG)
277         | S_IREAD_UGO
278         | ((info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0 : S_IWRITE_UGO);
279       if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
280         {
281           /* Determine whether the file is executable by looking at the file
282              name suffix.  */
283           if (info.nFileSizeHigh > 0 || info.nFileSizeLow > 0)
284             {
285               const char *last_dot = NULL;
286               const char *p;
287               for (p = info.cFileName; *p != '\0'; p++)
288                 if (*p == '.')
289                   last_dot = p;
290               if (last_dot != NULL)
291                 {
292                   const char *suffix = last_dot + 1;
293                   if (_stricmp (suffix, "exe") == 0
294                       || _stricmp (suffix, "bat") == 0
295                       || _stricmp (suffix, "cmd") == 0
296                       || _stricmp (suffix, "com") == 0)
297                     mode |= S_IEXEC_UGO;
298                 }
299             }
300         }
301       buf->st_mode = mode;
302 
303       /* st_nlink.  Ignore hard links here.  */
304       buf->st_nlink = 1;
305 
306       /* There's no easy way to map the Windows SID concept to an integer.  */
307       buf->st_uid = 0;
308       buf->st_gid = 0;
309 
310       /* st_rdev is irrelevant for normal files and directories.  */
311       buf->st_rdev = 0;
312 
313       /* st_size.  */
314       if (sizeof (buf->st_size) <= 4)
315         /* Range check already done above.  */
316         buf->st_size = info.nFileSizeLow;
317       else
318         buf->st_size = ((long long) info.nFileSizeHigh << 32) | (long long) info.nFileSizeLow;
319 
320       /* st_atime, st_mtime, st_ctime.  */
321 # if _GL_WINDOWS_STAT_TIMESPEC
322       buf->st_atim = _gl_convert_FILETIME_to_timespec (&info.ftLastAccessTime);
323       buf->st_mtim = _gl_convert_FILETIME_to_timespec (&info.ftLastWriteTime);
324       buf->st_ctim = _gl_convert_FILETIME_to_timespec (&info.ftCreationTime);
325 # else
326       buf->st_atime = _gl_convert_FILETIME_to_POSIX (&info.ftLastAccessTime);
327       buf->st_mtime = _gl_convert_FILETIME_to_POSIX (&info.ftLastWriteTime);
328       buf->st_ctime = _gl_convert_FILETIME_to_POSIX (&info.ftCreationTime);
329 # endif
330 
331       FindClose (h);
332 
333       ret = 0;
334     }
335 
336    done:
337     if (ret >= 0 && check_dir && !S_ISDIR (buf->st_mode))
338       {
339         errno = ENOTDIR;
340         ret = -1;
341       }
342     if (malloca_rname != NULL)
343       {
344         int saved_errno = errno;
345         freea (malloca_rname);
346         errno = saved_errno;
347       }
348     return ret;
349   }
350 
351  failed:
352   {
353     DWORD error = GetLastError ();
354     #if 0
355     fprintf (stderr, "rpl_stat error 0x%x\n", (unsigned int) error);
356     #endif
357 
358     if (malloca_rname != NULL)
359       freea (malloca_rname);
360 
361     switch (error)
362       {
363       /* Some of these errors probably cannot happen with the specific flags
364          that we pass to CreateFile.  But who knows...  */
365       case ERROR_FILE_NOT_FOUND: /* The last component of rname does not exist.  */
366       case ERROR_PATH_NOT_FOUND: /* Some directory component in rname does not exist.  */
367       case ERROR_BAD_PATHNAME:   /* rname is such as '\\server'.  */
368       case ERROR_BAD_NET_NAME:   /* rname is such as '\\server\nonexistentshare'.  */
369       case ERROR_INVALID_NAME:   /* rname contains wildcards, misplaced colon, etc.  */
370       case ERROR_DIRECTORY:
371         errno = ENOENT;
372         break;
373 
374       case ERROR_ACCESS_DENIED:  /* rname is such as 'C:\System Volume Information\foo'.  */
375       case ERROR_SHARING_VIOLATION: /* rname is such as 'C:\pagefile.sys' (second approach only).  */
376                                     /* XXX map to EACCESS or EPERM? */
377         errno = EACCES;
378         break;
379 
380       case ERROR_OUTOFMEMORY:
381         errno = ENOMEM;
382         break;
383 
384       case ERROR_WRITE_PROTECT:
385         errno = EROFS;
386         break;
387 
388       case ERROR_WRITE_FAULT:
389       case ERROR_READ_FAULT:
390       case ERROR_GEN_FAILURE:
391         errno = EIO;
392         break;
393 
394       case ERROR_BUFFER_OVERFLOW:
395       case ERROR_FILENAME_EXCED_RANGE:
396         errno = ENAMETOOLONG;
397         break;
398 
399       case ERROR_DELETE_PENDING: /* XXX map to EACCESS or EPERM? */
400         errno = EPERM;
401         break;
402 
403       default:
404         errno = EINVAL;
405         break;
406       }
407 
408     return -1;
409   }
410 #else
411   int result = orig_stat (name, buf);
412   if (result == 0)
413     {
414 # if REPLACE_FUNC_STAT_FILE
415       /* Solaris 9 mistakenly succeeds when given a non-directory with a
416          trailing slash.  */
417       if (!S_ISDIR (buf->st_mode))
418         {
419           size_t len = strlen (name);
420           if (ISSLASH (name[len - 1]))
421             {
422               errno = ENOTDIR;
423               return -1;
424             }
425         }
426 # endif /* REPLACE_FUNC_STAT_FILE */
427       result = stat_time_normalize (result, buf);
428     }
429   return result;
430 #endif
431 }
432