OSUtils.hpp 7.7 KB

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