OSUtils.hpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_OSUTILS_HPP
  14. #define ZT_OSUTILS_HPP
  15. #include "../core/Constants.hpp"
  16. #include "../core/Containers.hpp"
  17. #include <stdarg.h>
  18. #include <time.h>
  19. #ifndef __WINDOWS__
  20. #include <sys/time.h>
  21. #include <sys/stat.h>
  22. #include <unistd.h>
  23. #include <errno.h>
  24. #endif
  25. #ifdef __APPLE__
  26. #include <mach/mach.h>
  27. #include <mach/clock.h>
  28. #include <mach/mach_time.h>
  29. #endif
  30. namespace ZeroTier {
  31. /**
  32. * Miscellaneous utility functions and global constants
  33. */
  34. class OSUtils
  35. {
  36. private:
  37. #ifdef __APPLE__
  38. static clock_serv_t s_machRealtimeClock;
  39. #endif
  40. public:
  41. /**
  42. * Variant of snprintf that is portable and throws an exception
  43. *
  44. * This just wraps the local implementation whatever it's called, while
  45. * performing a few other checks and adding exceptions for overflow.
  46. *
  47. * @param buf Buffer to write to
  48. * @param len Length of buffer in bytes
  49. * @param fmt Format string
  50. * @param ... Format arguments
  51. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  52. */
  53. static unsigned int ztsnprintf(char *buf,unsigned int len,const char *fmt,...);
  54. #ifdef __UNIX_LIKE__
  55. /**
  56. * Close STDOUT_FILENO and STDERR_FILENO and replace them with output to given path
  57. *
  58. * This can be called after fork() and prior to exec() to suppress output
  59. * from a subprocess, such as auto-update.
  60. *
  61. * @param stdoutPath Path to file to use for stdout
  62. * @param stderrPath Path to file to use for stderr, or NULL for same as stdout (default)
  63. * @return True on success
  64. */
  65. static bool redirectUnixOutputs(const char *stdoutPath,const char *stderrPath = nullptr);
  66. #endif // __UNIX_LIKE__
  67. /**
  68. * Delete a file
  69. *
  70. * @param path Path to delete
  71. * @return True if delete was successful
  72. */
  73. static ZT_INLINE bool rm(const char *path)
  74. {
  75. #ifdef __WINDOWS__
  76. return (DeleteFileA(path) != FALSE);
  77. #else
  78. return (unlink(path) == 0);
  79. #endif
  80. }
  81. static ZT_INLINE bool mkdir(const char *path)
  82. {
  83. #ifdef __WINDOWS__
  84. if (::PathIsDirectoryA(path))
  85. return true;
  86. return (::CreateDirectoryA(path,NULL) == TRUE);
  87. #else
  88. if (::mkdir(path,0755) != 0)
  89. return (errno == EEXIST);
  90. return true;
  91. #endif
  92. }
  93. static ZT_INLINE bool rename(const char *o,const char *n)
  94. {
  95. #ifdef __WINDOWS__
  96. DeleteFileA(n);
  97. return (::rename(o,n) == 0);
  98. #else
  99. return (::rename(o,n) == 0);
  100. #endif
  101. }
  102. /**
  103. * List a directory's contents
  104. *
  105. * @param path Path to list
  106. * @param includeDirectories If true, include directories as well as files
  107. * @return Names of files in directory (without path prepended)
  108. */
  109. static ZeroTier::Vector<ZeroTier::String> listDirectory(const char *path,bool includeDirectories = false);
  110. /**
  111. * Delete a directory and all its files and subdirectories recursively
  112. *
  113. * @param path Path to delete
  114. * @return True on success
  115. */
  116. static bool rmDashRf(const char *path);
  117. /**
  118. * Set modes on a file to something secure
  119. *
  120. * This locks a file so that only the owner can access it. What it actually
  121. * does varies by platform.
  122. *
  123. * @param path Path to lock
  124. * @param isDir True if this is a directory
  125. */
  126. static void lockDownFile(const char *path,bool isDir);
  127. /**
  128. * @param path Path to check
  129. * @param followLinks Follow links (on platforms with that concept)
  130. * @return True if file or directory exists at path location
  131. */
  132. static bool fileExists(const char *path,bool followLinks = true);
  133. /**
  134. * @return Current time in milliseconds since epoch
  135. */
  136. static ZT_INLINE int64_t now()
  137. {
  138. #ifdef __WINDOWS__
  139. FILETIME ft;
  140. GetSystemTimeAsFileTime(&ft);
  141. return (((LONGLONG)ft.dwLowDateTime + ((LONGLONG)(ft.dwHighDateTime) << 32)) / 10000LL) - 116444736000000000LL;
  142. #else
  143. #ifdef __LINUX__
  144. timespec ts;
  145. #ifdef CLOCK_REALTIME_COARSE
  146. clock_gettime(CLOCK_REALTIME_COARSE,&ts);
  147. #else
  148. clock_gettime(CLOCK_REALTIME,&ts);
  149. #endif
  150. return ( (1000LL * (int64_t)ts.tv_sec) + ((int64_t)(ts.tv_nsec / 1000000)) );
  151. #else
  152. #ifdef __APPLE__
  153. mach_timespec_t mts;
  154. clock_get_time(s_machRealtimeClock,&mts);
  155. return ( (1000LL * (int64_t)mts.tv_sec) + ((int64_t)(mts.tv_nsec / 1000000)) );
  156. #else
  157. timeval tv;
  158. gettimeofday(&tv,(struct timezone *)0);
  159. return ( (1000LL * (int64_t)tv.tv_sec) + (int64_t)(tv.tv_usec / 1000) );
  160. #endif
  161. #endif
  162. #endif
  163. };
  164. /**
  165. * Read the full contents of a file into a string buffer
  166. *
  167. * The buffer isn't cleared, so if it already contains data the file's data will
  168. * be appended.
  169. *
  170. * @param path Path of file to read
  171. * @param buf Buffer to fill
  172. * @return True if open and read successful
  173. */
  174. static bool readFile(const char *path,ZeroTier::String &buf);
  175. /**
  176. * Write a block of data to disk, replacing any current file contents
  177. *
  178. * @param path Path to write
  179. * @param buf Buffer containing data
  180. * @param len Length of buffer
  181. * @return True if entire file was successfully written
  182. */
  183. static bool writeFile(const char *path,const void *buf,unsigned int len);
  184. /**
  185. * Split a string by delimiter, with optional escape and quote characters
  186. *
  187. * @param s String to split
  188. * @param sep One or more separators
  189. * @param esc Zero or more escape characters
  190. * @param quot Zero or more quote characters
  191. * @return Vector of tokens
  192. */
  193. static ZeroTier::Vector<ZeroTier::String> split(const char *s,const char *sep,const char *esc,const char *quot);
  194. /**
  195. * Write a block of data to disk, replacing any current file contents
  196. *
  197. * @param path Path to write
  198. * @param s Data to write
  199. * @return True if entire file was successfully written
  200. */
  201. static ZT_INLINE bool writeFile(const char *path,const ZeroTier::String &s) { return writeFile(path,s.data(),(unsigned int)s.length()); }
  202. /**
  203. * @return Platform default ZeroTier One home path
  204. */
  205. static ZeroTier::String platformDefaultHomePath();
  206. };
  207. } // namespace ZeroTier
  208. #endif