opendir.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org>
  3. *
  4. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  5. */
  6. #include <errno.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <sys/types.h>
  10. #include <fcntl.h>
  11. #include <unistd.h>
  12. #include <sys/dir.h>
  13. #include <sys/stat.h>
  14. #include "dirstream.h"
  15. libc_hidden_proto(opendir)
  16. libc_hidden_proto(open)
  17. libc_hidden_proto(fcntl)
  18. libc_hidden_proto(close)
  19. libc_hidden_proto(stat)
  20. /* opendir just makes an open() call - it return NULL if it fails
  21. * (open sets errno), otherwise it returns a DIR * pointer.
  22. */
  23. DIR *opendir(const char *name)
  24. {
  25. int fd;
  26. struct stat statbuf;
  27. DIR *ptr;
  28. #ifndef O_DIRECTORY
  29. /* O_DIRECTORY is linux specific and has been around since like 2.1.x */
  30. if (stat(name, &statbuf))
  31. return NULL;
  32. if (!S_ISDIR(statbuf.st_mode)) {
  33. __set_errno(ENOTDIR);
  34. return NULL;
  35. }
  36. # define O_DIRECTORY 0
  37. #endif
  38. if ((fd = open(name, O_RDONLY|O_NDELAY|O_DIRECTORY)) < 0)
  39. return NULL;
  40. /* Note: we should check to make sure that between the stat() and open()
  41. * call, 'name' didnt change on us, but that's only if O_DIRECTORY isnt
  42. * defined and since Linux has supported it for like ever, i'm not going
  43. * to worry about it right now (if ever). */
  44. if (fstat(fd, &statbuf) < 0)
  45. goto close_and_ret;
  46. /* According to POSIX, directory streams should be closed when
  47. * exec. From "Anna Pluzhnikov" <besp@midway.uchicago.edu>.
  48. */
  49. if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
  50. int saved_errno;
  51. close_and_ret:
  52. saved_errno = errno;
  53. close(fd);
  54. __set_errno(saved_errno);
  55. return NULL;
  56. }
  57. if (!(ptr = malloc(sizeof(*ptr))))
  58. goto nomem_close_and_ret;
  59. ptr->dd_fd = fd;
  60. ptr->dd_nextloc = ptr->dd_size = ptr->dd_nextoff = 0;
  61. ptr->dd_max = statbuf.st_blksize;
  62. if (ptr->dd_max < 512)
  63. ptr->dd_max = 512;
  64. if (!(ptr->dd_buf = calloc(1, ptr->dd_max))) {
  65. free(ptr);
  66. nomem_close_and_ret:
  67. close(fd);
  68. __set_errno(ENOMEM);
  69. return NULL;
  70. }
  71. __pthread_mutex_init(&(ptr->dd_lock), NULL);
  72. return ptr;
  73. }
  74. libc_hidden_def(opendir)