OSUtils.hpp 8.3 KB

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