freespace.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file freespace.c
  7. *
  8. * \brief Find the available disk space on the current volume.
  9. **/
  10. #include "lib/fs/files.h"
  11. #include "lib/cc/torint.h"
  12. #ifdef HAVE_SYS_STATVFS_H
  13. #include <sys/statvfs.h>
  14. #endif
  15. #ifdef _WIN32
  16. #include <windows.h>
  17. #endif
  18. #include <errno.h>
  19. #include <string.h>
  20. /** Return the amount of free disk space we have permission to use, in
  21. * bytes. Return -1 if the amount of free space can't be determined. */
  22. int64_t
  23. tor_get_avail_disk_space(const char *path)
  24. {
  25. #ifdef HAVE_STATVFS
  26. struct statvfs st;
  27. int r;
  28. memset(&st, 0, sizeof(st));
  29. r = statvfs(path, &st);
  30. if (r < 0)
  31. return -1;
  32. int64_t result = st.f_bavail;
  33. if (st.f_frsize) {
  34. result *= st.f_frsize;
  35. } else if (st.f_bsize) {
  36. result *= st.f_bsize;
  37. } else {
  38. return -1;
  39. }
  40. return result;
  41. #elif defined(_WIN32)
  42. ULARGE_INTEGER freeBytesAvail;
  43. BOOL ok;
  44. ok = GetDiskFreeSpaceEx(path, &freeBytesAvail, NULL, NULL);
  45. if (!ok) {
  46. return -1;
  47. }
  48. return (int64_t)freeBytesAvail.QuadPart;
  49. #else
  50. (void)path;
  51. errno = ENOSYS;
  52. return -1;
  53. #endif /* defined(HAVE_STATVFS) || ... */
  54. }