OSUtils.hpp 6.9 KB

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