OSUtils.hpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*
  2. * Copyright (c)2019 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: 2023-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 "../ext/json/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 full DNS TXT results
  170. *
  171. * @param name DNS FQDN
  172. * @return TXT record result(s) or empty on error or not found
  173. */
  174. static std::vector<std::string> resolveTxt(const char *name);
  175. /**
  176. * @return Current time in milliseconds since epoch
  177. */
  178. static inline int64_t now()
  179. {
  180. #ifdef __WINDOWS__
  181. FILETIME ft;
  182. SYSTEMTIME st;
  183. ULARGE_INTEGER tmp;
  184. GetSystemTime(&st);
  185. SystemTimeToFileTime(&st,&ft);
  186. tmp.LowPart = ft.dwLowDateTime;
  187. tmp.HighPart = ft.dwHighDateTime;
  188. return (int64_t)( ((tmp.QuadPart - 116444736000000000LL) / 10000L) + st.wMilliseconds );
  189. #else
  190. struct timeval tv;
  191. #ifdef __LINUX__
  192. syscall(SYS_gettimeofday,&tv,0); /* fix for musl libc broken gettimeofday bug */
  193. #else
  194. gettimeofday(&tv,(struct timezone *)0);
  195. #endif
  196. return ( (1000LL * (int64_t)tv.tv_sec) + (int64_t)(tv.tv_usec / 1000) );
  197. #endif
  198. };
  199. /**
  200. * Read the full contents of a file into a string buffer
  201. *
  202. * The buffer isn't cleared, so if it already contains data the file's data will
  203. * be appended.
  204. *
  205. * @param path Path of file to read
  206. * @param buf Buffer to fill
  207. * @return True if open and read successful
  208. */
  209. static bool readFile(const char *path,std::string &buf);
  210. /**
  211. * Write a block of data to disk, replacing any current file contents
  212. *
  213. * @param path Path to write
  214. * @param buf Buffer containing data
  215. * @param len Length of buffer
  216. * @return True if entire file was successfully written
  217. */
  218. static bool writeFile(const char *path,const void *buf,unsigned int len);
  219. /**
  220. * Split a string by delimiter, with optional escape and quote characters
  221. *
  222. * @param s String to split
  223. * @param sep One or more separators
  224. * @param esc Zero or more escape characters
  225. * @param quot Zero or more quote characters
  226. * @return Vector of tokens
  227. */
  228. static std::vector<std::string> split(const char *s,const char *const sep,const char *esc,const char *quot);
  229. /**
  230. * Trim whitespace from beginning and end of string
  231. */
  232. static inline std::string trimString(const std::string &s)
  233. {
  234. unsigned long end = (unsigned long)s.length();
  235. while (end) {
  236. char c = s[end - 1];
  237. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  238. --end;
  239. else break;
  240. }
  241. unsigned long start = 0;
  242. while (start < end) {
  243. char c = s[start];
  244. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  245. ++start;
  246. else break;
  247. }
  248. return s.substr(start,end - start);
  249. }
  250. /**
  251. * Write a block of data to disk, replacing any current file contents
  252. *
  253. * @param path Path to write
  254. * @param s Data to write
  255. * @return True if entire file was successfully written
  256. */
  257. static inline bool writeFile(const char *path,const std::string &s) { return writeFile(path,s.data(),(unsigned int)s.length()); }
  258. /**
  259. * @param c ASCII character to convert
  260. * @return Lower case ASCII character or unchanged if not a letter
  261. */
  262. static inline char toLower(char c) throw() { return (char)OSUtils::TOLOWER_TABLE[(unsigned long)c]; }
  263. /**
  264. * @return Platform default ZeroTier One home path
  265. */
  266. static std::string platformDefaultHomePath();
  267. #ifndef OMIT_JSON_SUPPORT
  268. static nlohmann::json jsonParse(const std::string &buf);
  269. static std::string jsonDump(const nlohmann::json &j,int indentation = 1);
  270. static uint64_t jsonInt(const nlohmann::json &jv,const uint64_t dfl);
  271. static uint64_t jsonIntHex(const nlohmann::json &jv,const uint64_t dfl);
  272. static bool jsonBool(const nlohmann::json &jv,const bool dfl);
  273. static std::string jsonString(const nlohmann::json &jv,const char *dfl);
  274. static std::string jsonBinFromHex(const nlohmann::json &jv);
  275. #endif // OMIT_JSON_SUPPORT
  276. private:
  277. static const unsigned char TOLOWER_TABLE[256];
  278. };
  279. } // namespace ZeroTier
  280. #endif