OSUtils.hpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 "../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 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 a human-readable format
  179. */
  180. static inline std::string humanReadableTimestamp()
  181. {
  182. time_t rawtime;
  183. struct tm * timeinfo;
  184. char buffer [80];
  185. time (&rawtime);
  186. timeinfo = localtime (&rawtime);
  187. strftime (buffer,80,"%F %T",timeinfo);
  188. return std::string(buffer);
  189. }
  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) { return writeFile(path,s.data(),(unsigned int)s.length()); }
  248. /**
  249. * @param c ASCII character to convert
  250. * @return Lower case ASCII character or unchanged if not a letter
  251. */
  252. static inline char toLower(char c) throw() { return (char)OSUtils::TOLOWER_TABLE[(unsigned long)c]; }
  253. /**
  254. * @return Platform default ZeroTier One home path
  255. */
  256. static std::string platformDefaultHomePath();
  257. #ifndef OMIT_JSON_SUPPORT
  258. static nlohmann::json jsonParse(const std::string &buf);
  259. static std::string jsonDump(const nlohmann::json &j,int indentation = 1);
  260. static uint64_t jsonInt(const nlohmann::json &jv,const uint64_t dfl);
  261. static double jsonDouble(const nlohmann::json &jv,const double dfl);
  262. static uint64_t jsonIntHex(const nlohmann::json &jv,const uint64_t dfl);
  263. static bool jsonBool(const nlohmann::json &jv,const bool dfl);
  264. static std::string jsonString(const nlohmann::json &jv,const char *dfl);
  265. static std::string jsonBinFromHex(const nlohmann::json &jv);
  266. #endif // OMIT_JSON_SUPPORT
  267. private:
  268. static const unsigned char TOLOWER_TABLE[256];
  269. };
  270. } // namespace ZeroTier
  271. #endif