openat.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2013 Nicholas Marriott <nicholas.marriott@gmail.com>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
  13. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
  14. * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #include <errno.h>
  17. #include <fcntl.h>
  18. #include <stdarg.h>
  19. #include <unistd.h>
  20. #include "tmux.h"
  21. int
  22. openat(int fd, const char *path, int flags, ...)
  23. {
  24. mode_t mode;
  25. va_list ap;
  26. int dotfd, retval, saved_errno;
  27. if (flags & O_CREAT) {
  28. va_start(ap, flags);
  29. mode = va_arg(ap, mode_t);
  30. va_end(ap);
  31. } else
  32. mode = 0;
  33. dotfd = -1;
  34. if (fd != AT_FDCWD) {
  35. dotfd = open(".", O_RDONLY);
  36. if (dotfd == -1)
  37. return (-1);
  38. if (fchdir(fd) != 0) {
  39. saved_errno = errno;
  40. close(dotfd);
  41. errno = saved_errno;
  42. return (-1);
  43. }
  44. }
  45. retval = open(path, flags, mode);
  46. if (dotfd != -1) {
  47. if (fchdir(dotfd) != 0) {
  48. saved_errno = errno;
  49. close(retval);
  50. close(dotfd);
  51. errno = saved_errno;
  52. return (-1);
  53. }
  54. close(dotfd);
  55. }
  56. return (retval);
  57. }