freespace.c 1.2 KB

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