OSUtils.hpp 8.3 KB

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