1 /* Work around a bug of lstat on some systems 2 3 Copyright (C) 1997-1999, 2000-2006, 2008 Free Software Foundation, Inc. 4 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. 9 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. 14 15 You should have received a copy of the GNU General Public License 16 along with this program. If not, see <http://www.gnu.org/licenses/>. */ 17 18 /* written by Jim Meyering */ 19 20 #include <config.h> 21 22 /* Get the original definition of open. It might be defined as a macro. */ 23 #define __need_system_sys_stat_h 24 #include <sys/types.h> 25 #include <sys/stat.h> 26 #undef __need_system_sys_stat_h 27 28 static inline int 29 orig_lstat (const char *filename, struct stat *buf) 30 { 31 return lstat (filename, buf); 32 } 33 34 /* Specification. */ 35 #include <sys/stat.h> 36 37 #include <string.h> 38 #include <errno.h> 39 40 /* lstat works differently on Linux and Solaris systems. POSIX (see 41 `pathname resolution' in the glossary) requires that programs like 42 `ls' take into consideration the fact that FILE has a trailing slash 43 when FILE is a symbolic link. On Linux and Solaris 10 systems, the 44 lstat function already has the desired semantics (in treating 45 `lstat ("symlink/", sbuf)' just like `lstat ("symlink/.", sbuf)', 46 but on Solaris 9 and earlier it does not. 47 48 If FILE has a trailing slash and specifies a symbolic link, 49 then use stat() to get more info on the referent of FILE. 50 If the referent is a non-directory, then set errno to ENOTDIR 51 and return -1. Otherwise, return stat's result. */ 52 53 int 54 rpl_lstat (const char *file, struct stat *sbuf) 55 { 56 size_t len; 57 int lstat_result = orig_lstat (file, sbuf); 58 59 if (lstat_result != 0 || !S_ISLNK (sbuf->st_mode)) 60 return lstat_result; 61 62 len = strlen (file); 63 if (len == 0 || file[len - 1] != '/') 64 return 0; 65 66 /* FILE refers to a symbolic link and the name ends with a slash. 67 Call stat() to get info about the link's referent. */ 68 69 /* If stat fails, then we do the same. */ 70 if (stat (file, sbuf) != 0) 71 return -1; 72 73 /* If FILE references a directory, return 0. */ 74 if (S_ISDIR (sbuf->st_mode)) 75 return 0; 76 77 /* Here, we know stat succeeded and FILE references a non-directory. 78 But it was specified via a name including a trailing slash. 79 Fail with errno set to ENOTDIR to indicate the contradiction. */ 80 errno = ENOTDIR; 81 return -1; 82 } 83