OSUtils.hpp 7.9 KB

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