OSUtils.hpp 8.4 KB

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