readlink.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Stub for readlink().
  2. Copyright (C) 2003-2007, 2009-2013 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. #include <config.h>
  14. /* Specification. */
  15. #include <unistd.h>
  16. #include <errno.h>
  17. #include <string.h>
  18. #include <sys/stat.h>
  19. #if !HAVE_READLINK
  20. /* readlink() substitute for systems that don't have a readlink() function,
  21. such as DJGPP 2.03 and mingw32. */
  22. ssize_t
  23. readlink (const char *name, char *buf _GL_UNUSED,
  24. size_t bufsize _GL_UNUSED)
  25. {
  26. struct stat statbuf;
  27. /* In general we should use lstat() here, not stat(). But on platforms
  28. without symbolic links, lstat() - if it exists - would be equivalent to
  29. stat(), therefore we can use stat(). This saves us a configure check. */
  30. if (stat (name, &statbuf) >= 0)
  31. errno = EINVAL;
  32. return -1;
  33. }
  34. #else /* HAVE_READLINK */
  35. # undef readlink
  36. /* readlink() wrapper that uses correct types, for systems like cygwin
  37. 1.5.x where readlink returns int, and which rejects trailing slash,
  38. for Solaris 9. */
  39. ssize_t
  40. rpl_readlink (const char *name, char *buf, size_t bufsize)
  41. {
  42. # if READLINK_TRAILING_SLASH_BUG
  43. size_t len = strlen (name);
  44. if (len && name[len - 1] == '/')
  45. {
  46. /* Even if name without the slash is a symlink to a directory,
  47. both lstat() and stat() must resolve the trailing slash to
  48. the directory rather than the symlink. We can therefore
  49. safely use stat() to distinguish between EINVAL and
  50. ENOTDIR/ENOENT, avoiding extra overhead of rpl_lstat(). */
  51. struct stat st;
  52. if (stat (name, &st) == 0)
  53. errno = EINVAL;
  54. return -1;
  55. }
  56. # endif /* READLINK_TRAILING_SLASH_BUG */
  57. return readlink (name, buf, bufsize);
  58. }
  59. #endif /* HAVE_READLINK */