OSUtils.hpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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: 2026-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 "../node/InetAddress.hpp"
  17. #include <map>
  18. #include <stdexcept>
  19. #include <stdint.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <time.h>
  24. #include <vector>
  25. #ifdef __WINDOWS__
  26. #include <shlwapi.h>
  27. #include <windows.h>
  28. #include <winsock2.h>
  29. #else
  30. #include <arpa/inet.h>
  31. #include <errno.h>
  32. #include <sys/stat.h>
  33. #include <sys/time.h>
  34. #include <unistd.h>
  35. #ifdef __LINUX__
  36. #include <sys/syscall.h>
  37. #endif
  38. #endif
  39. #ifndef OMIT_JSON_SUPPORT
  40. #include <nlohmann/json.hpp>
  41. #endif
  42. namespace ZeroTier {
  43. /**
  44. * Miscellaneous utility functions and global constants
  45. */
  46. class OSUtils {
  47. public:
  48. /**
  49. * Variant of snprintf that is portable and throws an exception
  50. *
  51. * This just wraps the local implementation whatever it's called, while
  52. * performing a few other checks and adding exceptions for overflow.
  53. *
  54. * @param buf Buffer to write to
  55. * @param len Length of buffer in bytes
  56. * @param fmt Format string
  57. * @param ... Format arguments
  58. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  59. */
  60. static unsigned int ztsnprintf(char* buf, unsigned int len, const char* fmt, ...);
  61. /**
  62. * Converts a uint64_t network ID into a string
  63. *
  64. * @param nwid network ID
  65. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  66. */
  67. static std::string networkIDStr(const uint64_t nwid);
  68. /**
  69. * Converts a uint64_t node ID into a string
  70. *
  71. * @param nid node ID
  72. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  73. */
  74. static std::string nodeIDStr(const uint64_t nid);
  75. #ifdef __UNIX_LIKE__
  76. /**
  77. * Close STDOUT_FILENO and STDERR_FILENO and replace them with output to given path
  78. *
  79. * This can be called after fork() and prior to exec() to suppress output
  80. * from a subprocess, such as auto-update.
  81. *
  82. * @param stdoutPath Path to file to use for stdout
  83. * @param stderrPath Path to file to use for stderr, or NULL for same as stdout (default)
  84. * @return True on success
  85. */
  86. static bool redirectUnixOutputs(const char* stdoutPath, const char* stderrPath = (const char*)0) throw();
  87. #endif // __UNIX_LIKE__
  88. /**
  89. * Delete a file
  90. *
  91. * @param path Path to delete
  92. * @return True if delete was successful
  93. */
  94. static inline bool rm(const char* path)
  95. {
  96. #ifdef __WINDOWS__
  97. return (DeleteFileA(path) != FALSE);
  98. #else
  99. return (unlink(path) == 0);
  100. #endif
  101. }
  102. static inline bool rm(const std::string& path)
  103. {
  104. return rm(path.c_str());
  105. }
  106. static inline bool mkdir(const char* path)
  107. {
  108. #ifdef __WINDOWS__
  109. if (::PathIsDirectoryA(path))
  110. return true;
  111. return (::CreateDirectoryA(path, NULL) == TRUE);
  112. #else
  113. if (::mkdir(path, 0755) != 0)
  114. return (errno == EEXIST);
  115. return true;
  116. #endif
  117. }
  118. static inline bool mkdir(const std::string& path)
  119. {
  120. return OSUtils::mkdir(path.c_str());
  121. }
  122. static inline bool rename(const char* o, const char* n)
  123. {
  124. #ifdef __WINDOWS__
  125. DeleteFileA(n);
  126. return (::rename(o, n) == 0);
  127. #else
  128. return (::rename(o, n) == 0);
  129. #endif
  130. }
  131. /**
  132. * List a directory's contents
  133. *
  134. * @param path Path to list
  135. * @param includeDirectories If true, include directories as well as files
  136. * @return Names of files in directory (without path prepended)
  137. */
  138. static std::vector<std::string> listDirectory(const char* path, bool includeDirectories = false);
  139. /**
  140. * Clean a directory of files whose last modified time is older than this
  141. *
  142. * This ignores directories, symbolic links, and other special files.
  143. *
  144. * @param olderThan Last modified older than timestamp (ms since epoch)
  145. * @return Number of cleaned files or negative on fatal error
  146. */
  147. static long cleanDirectory(const char* path, const int64_t olderThan);
  148. /**
  149. * Delete a directory and all its files and subdirectories recursively
  150. *
  151. * @param path Path to delete
  152. * @return True on success
  153. */
  154. static bool rmDashRf(const char* path);
  155. /**
  156. * Set modes on a file to something secure
  157. *
  158. * This locks a file so that only the owner can access it. What it actually
  159. * does varies by platform.
  160. *
  161. * @param path Path to lock
  162. * @param isDir True if this is a directory
  163. */
  164. static void lockDownFile(const char* path, bool isDir);
  165. /**
  166. * Get file last modification time
  167. *
  168. * Resolution is often only second, not millisecond, but the return is
  169. * always in ms for comparison against now().
  170. *
  171. * @param path Path to file to get time
  172. * @return Last modification time in ms since epoch or 0 if not found
  173. */
  174. static uint64_t getLastModified(const char* path);
  175. /**
  176. * @param path Path to check
  177. * @param followLinks Follow links (on platforms with that concept)
  178. * @return True if file or directory exists at path location
  179. */
  180. static bool fileExists(const char* path, bool followLinks = true);
  181. /**
  182. * @param path Path to file
  183. * @return File size or -1 if nonexistent or other failure
  184. */
  185. static int64_t getFileSize(const char* path);
  186. /**
  187. * Get IP (v4 and/or v6) addresses for a given host
  188. *
  189. * This is a blocking resolver.
  190. *
  191. * @param name Host name
  192. * @return IP addresses in InetAddress sort order or empty vector if not found
  193. */
  194. static std::vector<InetAddress> resolve(const char* name);
  195. /**
  196. * @return Current time in milliseconds since epoch
  197. */
  198. static inline int64_t now()
  199. {
  200. #ifdef __WINDOWS__
  201. FILETIME ft;
  202. SYSTEMTIME st;
  203. ULARGE_INTEGER tmp;
  204. GetSystemTime(&st);
  205. SystemTimeToFileTime(&st, &ft);
  206. tmp.LowPart = ft.dwLowDateTime;
  207. tmp.HighPart = ft.dwHighDateTime;
  208. return (int64_t)(((tmp.QuadPart - 116444736000000000LL) / 10000L) + st.wMilliseconds);
  209. #else
  210. struct timeval tv;
  211. gettimeofday(&tv, (struct timezone*)0);
  212. return ((1000LL * (int64_t)tv.tv_sec) + (int64_t)(tv.tv_usec / 1000));
  213. #endif
  214. };
  215. /**
  216. * Read the full contents of a file into a string buffer
  217. *
  218. * The buffer isn't cleared, so if it already contains data the file's data will
  219. * be appended.
  220. *
  221. * @param path Path of file to read
  222. * @param buf Buffer to fill
  223. * @return True if open and read successful
  224. */
  225. static bool readFile(const char* path, std::string& buf);
  226. /**
  227. * Write a block of data to disk, replacing any current file contents
  228. *
  229. * @param path Path to write
  230. * @param buf Buffer containing data
  231. * @param len Length of buffer
  232. * @return True if entire file was successfully written
  233. */
  234. static bool writeFile(const char* path, const void* buf, unsigned int len);
  235. /**
  236. * Split a string by delimiter, with optional escape and quote characters
  237. *
  238. * @param s String to split
  239. * @param sep One or more separators
  240. * @param esc Zero or more escape characters
  241. * @param quot Zero or more quote characters
  242. * @return Vector of tokens
  243. */
  244. static std::vector<std::string> split(const char* s, const char* const sep, const char* esc, const char* quot);
  245. /**
  246. * Write a block of data to disk, replacing any current file contents
  247. *
  248. * @param path Path to write
  249. * @param s Data to write
  250. * @return True if entire file was successfully written
  251. */
  252. static inline bool writeFile(const char* path, const std::string& s)
  253. {
  254. return writeFile(path, s.data(), (unsigned int)s.length());
  255. }
  256. /**
  257. * @param c ASCII character to convert
  258. * @return Lower case ASCII character or unchanged if not a letter
  259. */
  260. static inline char toLower(char c) throw()
  261. {
  262. return (char)OSUtils::TOLOWER_TABLE[(unsigned long)c];
  263. }
  264. /**
  265. * @return Platform default ZeroTier One home path
  266. */
  267. static std::string platformDefaultHomePath();
  268. #ifndef OMIT_JSON_SUPPORT
  269. static nlohmann::json jsonParse(const std::string& buf);
  270. static std::string jsonDump(const nlohmann::json& j, int indentation = 1);
  271. static uint64_t jsonInt(const nlohmann::json& jv, const uint64_t dfl);
  272. static double jsonDouble(const nlohmann::json& jv, const double dfl);
  273. static uint64_t jsonIntHex(const nlohmann::json& jv, const uint64_t dfl);
  274. static bool jsonBool(const nlohmann::json& jv, const bool dfl);
  275. static std::string jsonString(const nlohmann::json& jv, const char* dfl);
  276. static std::string jsonBinFromHex(const nlohmann::json& jv);
  277. #endif // OMIT_JSON_SUPPORT
  278. private:
  279. static const unsigned char TOLOWER_TABLE[256];
  280. };
  281. } // namespace ZeroTier
  282. #endif