OSUtils.hpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 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 <stdexcept>
  34. #include <vector>
  35. #include <map>
  36. #include "../node/Constants.hpp"
  37. #include "../node/InetAddress.hpp"
  38. #ifdef __WINDOWS__
  39. #include <WinSock2.h>
  40. #include <Windows.h>
  41. #include <Shlwapi.h>
  42. #else
  43. #include <unistd.h>
  44. #include <errno.h>
  45. #include <sys/time.h>
  46. #include <sys/stat.h>
  47. #include <arpa/inet.h>
  48. #ifdef __LINUX__
  49. #include <sys/syscall.h>
  50. #endif
  51. #endif
  52. #ifndef OMIT_JSON_SUPPORT
  53. #include "../ext/json/json.hpp"
  54. #endif
  55. namespace ZeroTier {
  56. /**
  57. * Miscellaneous utility functions and global constants
  58. */
  59. class OSUtils
  60. {
  61. public:
  62. /**
  63. * Variant of snprintf that is portable and throws an exception
  64. *
  65. * This just wraps the local implementation whatever it's called, while
  66. * performing a few other checks and adding exceptions for overflow.
  67. *
  68. * @param buf Buffer to write to
  69. * @param len Length of buffer in bytes
  70. * @param fmt Format string
  71. * @param ... Format arguments
  72. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  73. */
  74. static unsigned int ztsnprintf(char *buf,unsigned int len,const char *fmt,...);
  75. #ifdef __UNIX_LIKE__
  76. /**
  77. * Close STDOUT_FILENO and STDERR_FILENO and replace them with output to given path
  78. *
  79. * This can be called after fork() and prior to exec() to suppress output
  80. * from a subprocess, such as auto-update.
  81. *
  82. * @param stdoutPath Path to file to use for stdout
  83. * @param stderrPath Path to file to use for stderr, or NULL for same as stdout (default)
  84. * @return True on success
  85. */
  86. static bool redirectUnixOutputs(const char *stdoutPath,const char *stderrPath = (const char *)0)
  87. throw();
  88. #endif // __UNIX_LIKE__
  89. /**
  90. * Delete a file
  91. *
  92. * @param path Path to delete
  93. * @return True if delete was successful
  94. */
  95. static inline bool rm(const char *path)
  96. {
  97. #ifdef __WINDOWS__
  98. return (DeleteFileA(path) != FALSE);
  99. #else
  100. return (unlink(path) == 0);
  101. #endif
  102. }
  103. static inline bool rm(const std::string &path) { return rm(path.c_str()); }
  104. static inline bool mkdir(const char *path)
  105. {
  106. #ifdef __WINDOWS__
  107. if (::PathIsDirectoryA(path))
  108. return true;
  109. return (::CreateDirectoryA(path,NULL) == TRUE);
  110. #else
  111. if (::mkdir(path,0755) != 0)
  112. return (errno == EEXIST);
  113. return true;
  114. #endif
  115. }
  116. static inline bool mkdir(const std::string &path) { return OSUtils::mkdir(path.c_str()); }
  117. static inline bool rename(const char *o,const char *n)
  118. {
  119. #ifdef __WINDOWS__
  120. DeleteFileA(n);
  121. return (::rename(o,n) == 0);
  122. #else
  123. return (::rename(o,n) == 0);
  124. #endif
  125. }
  126. /**
  127. * List a directory's contents
  128. *
  129. * @param path Path to list
  130. * @param includeDirectories If true, include directories as well as files
  131. * @return Names of files in directory (without path prepended)
  132. */
  133. static std::vector<std::string> listDirectory(const char *path,bool includeDirectories = false);
  134. /**
  135. * Clean a directory of files whose last modified time is older than this
  136. *
  137. * This ignores directories, symbolic links, and other special files.
  138. *
  139. * @param olderThan Last modified older than timestamp (ms since epoch)
  140. * @return Number of cleaned files or negative on fatal error
  141. */
  142. static long cleanDirectory(const char *path,const int64_t olderThan);
  143. /**
  144. * Delete a directory and all its files and subdirectories recursively
  145. *
  146. * @param path Path to delete
  147. * @return True on success
  148. */
  149. static bool rmDashRf(const char *path);
  150. /**
  151. * Set modes on a file to something secure
  152. *
  153. * This locks a file so that only the owner can access it. What it actually
  154. * does varies by platform.
  155. *
  156. * @param path Path to lock
  157. * @param isDir True if this is a directory
  158. */
  159. static void lockDownFile(const char *path,bool isDir);
  160. /**
  161. * Get file last modification time
  162. *
  163. * Resolution is often only second, not millisecond, but the return is
  164. * always in ms for comparison against now().
  165. *
  166. * @param path Path to file to get time
  167. * @return Last modification time in ms since epoch or 0 if not found
  168. */
  169. static uint64_t getLastModified(const char *path);
  170. /**
  171. * @param path Path to check
  172. * @param followLinks Follow links (on platforms with that concept)
  173. * @return True if file or directory exists at path location
  174. */
  175. static bool fileExists(const char *path,bool followLinks = true);
  176. /**
  177. * @param path Path to file
  178. * @return File size or -1 if nonexistent or other failure
  179. */
  180. static int64_t getFileSize(const char *path);
  181. /**
  182. * Get full DNS TXT results
  183. *
  184. * @param name DNS FQDN
  185. * @return TXT record result(s) or empty on error or not found
  186. */
  187. static std::vector<std::string> resolveTxt(const char *name);
  188. /**
  189. * @return Current time in milliseconds since epoch
  190. */
  191. static inline int64_t now()
  192. {
  193. #ifdef __WINDOWS__
  194. FILETIME ft;
  195. SYSTEMTIME st;
  196. ULARGE_INTEGER tmp;
  197. GetSystemTime(&st);
  198. SystemTimeToFileTime(&st,&ft);
  199. tmp.LowPart = ft.dwLowDateTime;
  200. tmp.HighPart = ft.dwHighDateTime;
  201. return (int64_t)( ((tmp.QuadPart - 116444736000000000LL) / 10000L) + st.wMilliseconds );
  202. #else
  203. struct timeval tv;
  204. #ifdef __LINUX__
  205. syscall(SYS_gettimeofday,&tv,0); /* fix for musl libc broken gettimeofday bug */
  206. #else
  207. gettimeofday(&tv,(struct timezone *)0);
  208. #endif
  209. return ( (1000LL * (int64_t)tv.tv_sec) + (int64_t)(tv.tv_usec / 1000) );
  210. #endif
  211. };
  212. /**
  213. * Read the full contents of a file into a string buffer
  214. *
  215. * The buffer isn't cleared, so if it already contains data the file's data will
  216. * be appended.
  217. *
  218. * @param path Path of file to read
  219. * @param buf Buffer to fill
  220. * @return True if open and read successful
  221. */
  222. static bool readFile(const char *path,std::string &buf);
  223. /**
  224. * Write a block of data to disk, replacing any current file contents
  225. *
  226. * @param path Path to write
  227. * @param buf Buffer containing data
  228. * @param len Length of buffer
  229. * @return True if entire file was successfully written
  230. */
  231. static bool writeFile(const char *path,const void *buf,unsigned int len);
  232. /**
  233. * Split a string by delimiter, with optional escape and quote characters
  234. *
  235. * @param s String to split
  236. * @param sep One or more separators
  237. * @param esc Zero or more escape characters
  238. * @param quot Zero or more quote characters
  239. * @return Vector of tokens
  240. */
  241. static std::vector<std::string> split(const char *s,const char *const sep,const char *esc,const char *quot);
  242. /**
  243. * Trim whitespace from beginning and end of string
  244. */
  245. static inline std::string trimString(const std::string &s)
  246. {
  247. unsigned long end = (unsigned long)s.length();
  248. while (end) {
  249. char c = s[end - 1];
  250. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  251. --end;
  252. else break;
  253. }
  254. unsigned long start = 0;
  255. while (start < end) {
  256. char c = s[start];
  257. if ((c == ' ')||(c == '\r')||(c == '\n')||(!c)||(c == '\t'))
  258. ++start;
  259. else break;
  260. }
  261. return s.substr(start,end - start);
  262. }
  263. /**
  264. * Write a block of data to disk, replacing any current file contents
  265. *
  266. * @param path Path to write
  267. * @param s Data to write
  268. * @return True if entire file was successfully written
  269. */
  270. static inline bool writeFile(const char *path,const std::string &s) { return writeFile(path,s.data(),(unsigned int)s.length()); }
  271. /**
  272. * @param c ASCII character to convert
  273. * @return Lower case ASCII character or unchanged if not a letter
  274. */
  275. static inline char toLower(char c) throw() { return (char)OSUtils::TOLOWER_TABLE[(unsigned long)c]; }
  276. /**
  277. * @return Platform default ZeroTier One home path
  278. */
  279. static std::string platformDefaultHomePath();
  280. #ifndef OMIT_JSON_SUPPORT
  281. static nlohmann::json jsonParse(const std::string &buf);
  282. static std::string jsonDump(const nlohmann::json &j,int indentation = 1);
  283. static uint64_t jsonInt(const nlohmann::json &jv,const uint64_t dfl);
  284. static uint64_t jsonIntHex(const nlohmann::json &jv,const uint64_t dfl);
  285. static bool jsonBool(const nlohmann::json &jv,const bool dfl);
  286. static std::string jsonString(const nlohmann::json &jv,const char *dfl);
  287. static std::string jsonBinFromHex(const nlohmann::json &jv);
  288. #endif // OMIT_JSON_SUPPORT
  289. private:
  290. static const unsigned char TOLOWER_TABLE[256];
  291. };
  292. } // namespace ZeroTier
  293. #endif