OSUtils.hpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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: 2024-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 "../node/Constants.hpp"
  16. #include <cstdio>
  17. #include <cstdlib>
  18. #include <cstdint>
  19. #include <cstring>
  20. #include <cstdarg>
  21. #include <ctime>
  22. #include <stdexcept>
  23. #include <vector>
  24. #include <map>
  25. #ifndef __WINDOWS__
  26. #include <sys/time.h>
  27. #include <sys/stat.h>
  28. #include <unistd.h>
  29. #endif
  30. #ifndef OMIT_JSON_SUPPORT
  31. #include "../ext/json/json.hpp"
  32. #endif
  33. namespace ZeroTier {
  34. /**
  35. * Miscellaneous utility functions and global constants
  36. */
  37. class OSUtils
  38. {
  39. public:
  40. /**
  41. * Variant of snprintf that is portable and throws an exception
  42. *
  43. * This just wraps the local implementation whatever it's called, while
  44. * performing a few other checks and adding exceptions for overflow.
  45. *
  46. * @param buf Buffer to write to
  47. * @param len Length of buffer in bytes
  48. * @param fmt Format string
  49. * @param ... Format arguments
  50. * @throws std::length_error buf[] too short (buf[] will still be left null-terminated)
  51. */
  52. static unsigned int ztsnprintf(char *buf,unsigned int len,const char *fmt,...);
  53. #ifdef __UNIX_LIKE__
  54. /**
  55. * Close STDOUT_FILENO and STDERR_FILENO and replace them with output to given path
  56. *
  57. * This can be called after fork() and prior to exec() to suppress output
  58. * from a subprocess, such as auto-update.
  59. *
  60. * @param stdoutPath Path to file to use for stdout
  61. * @param stderrPath Path to file to use for stderr, or NULL for same as stdout (default)
  62. * @return True on success
  63. */
  64. static bool redirectUnixOutputs(const char *stdoutPath,const char *stderrPath = nullptr);
  65. #endif // __UNIX_LIKE__
  66. /**
  67. * Delete a file
  68. *
  69. * @param path Path to delete
  70. * @return True if delete was successful
  71. */
  72. static ZT_INLINE bool rm(const char *path)
  73. {
  74. #ifdef __WINDOWS__
  75. return (DeleteFileA(path) != FALSE);
  76. #else
  77. return (unlink(path) == 0);
  78. #endif
  79. }
  80. static ZT_INLINE bool rm(const std::string &path) { return rm(path.c_str()); }
  81. static ZT_INLINE bool mkdir(const char *path)
  82. {
  83. #ifdef __WINDOWS__
  84. if (::PathIsDirectoryA(path))
  85. return true;
  86. return (::CreateDirectoryA(path,NULL) == TRUE);
  87. #else
  88. if (::mkdir(path,0755) != 0)
  89. return (errno == EEXIST);
  90. return true;
  91. #endif
  92. }
  93. static ZT_INLINE bool mkdir(const std::string &path) { return OSUtils::mkdir(path.c_str()); }
  94. static ZT_INLINE bool rename(const char *o,const char *n)
  95. {
  96. #ifdef __WINDOWS__
  97. DeleteFileA(n);
  98. return (::rename(o,n) == 0);
  99. #else
  100. return (::rename(o,n) == 0);
  101. #endif
  102. }
  103. /**
  104. * List a directory's contents
  105. *
  106. * @param path Path to list
  107. * @param includeDirectories If true, include directories as well as files
  108. * @return Names of files in directory (without path prepended)
  109. */
  110. static std::vector<std::string> listDirectory(const char *path,bool includeDirectories = false);
  111. /**
  112. * Delete a directory and all its files and subdirectories recursively
  113. *
  114. * @param path Path to delete
  115. * @return True on success
  116. */
  117. static bool rmDashRf(const char *path);
  118. /**
  119. * Set modes on a file to something secure
  120. *
  121. * This locks a file so that only the owner can access it. What it actually
  122. * does varies by platform.
  123. *
  124. * @param path Path to lock
  125. * @param isDir True if this is a directory
  126. */
  127. static void lockDownFile(const char *path,bool isDir);
  128. /**
  129. * @param path Path to check
  130. * @param followLinks Follow links (on platforms with that concept)
  131. * @return True if file or directory exists at path location
  132. */
  133. static bool fileExists(const char *path,bool followLinks = true);
  134. /**
  135. * @return Current time in milliseconds since epoch
  136. */
  137. static ZT_INLINE int64_t now()
  138. {
  139. #ifdef __WINDOWS__
  140. FILETIME ft;
  141. SYSTEMTIME st;
  142. ULARGE_INTEGER tmp;
  143. GetSystemTime(&st);
  144. SystemTimeToFileTime(&st,&ft);
  145. tmp.LowPart = ft.dwLowDateTime;
  146. tmp.HighPart = ft.dwHighDateTime;
  147. return (int64_t)( ((tmp.QuadPart - 116444736000000000LL) / 10000L) + st.wMilliseconds );
  148. #else
  149. timeval tv;
  150. // #ifdef __LINUX__
  151. // syscall(SYS_gettimeofday,&tv,0); /* fix for musl libc broken gettimeofday bug */
  152. // #else
  153. gettimeofday(&tv,(struct timezone *)0);
  154. // #endif
  155. return ( (1000LL * (int64_t)tv.tv_sec) + (int64_t)(tv.tv_usec / 1000) );
  156. #endif
  157. };
  158. /**
  159. * Read the full contents of a file into a string buffer
  160. *
  161. * The buffer isn't cleared, so if it already contains data the file's data will
  162. * be appended.
  163. *
  164. * @param path Path of file to read
  165. * @param buf Buffer to fill
  166. * @return True if open and read successful
  167. */
  168. static bool readFile(const char *path,std::string &buf);
  169. /**
  170. * Write a block of data to disk, replacing any current file contents
  171. *
  172. * @param path Path to write
  173. * @param buf Buffer containing data
  174. * @param len Length of buffer
  175. * @return True if entire file was successfully written
  176. */
  177. static bool writeFile(const char *path,const void *buf,unsigned int len);
  178. /**
  179. * Split a string by delimiter, with optional escape and quote characters
  180. *
  181. * @param s String to split
  182. * @param sep One or more separators
  183. * @param esc Zero or more escape characters
  184. * @param quot Zero or more quote characters
  185. * @return Vector of tokens
  186. */
  187. static std::vector<std::string> split(const char *s,const char *sep,const char *esc,const char *quot);
  188. /**
  189. * Write a block of data to disk, replacing any current file contents
  190. *
  191. * @param path Path to write
  192. * @param s Data to write
  193. * @return True if entire file was successfully written
  194. */
  195. static ZT_INLINE bool writeFile(const char *path,const std::string &s) { return writeFile(path,s.data(),(unsigned int)s.length()); }
  196. /**
  197. * @return Platform default ZeroTier One home path
  198. */
  199. static std::string platformDefaultHomePath();
  200. #ifndef OMIT_JSON_SUPPORT
  201. static nlohmann::json jsonParse(const std::string &buf);
  202. static std::string jsonDump(const nlohmann::json &j,int indentation = 1);
  203. static uint64_t jsonInt(const nlohmann::json &jv,uint64_t dfl);
  204. static uint64_t jsonIntHex(const nlohmann::json &jv,uint64_t dfl);
  205. static bool jsonBool(const nlohmann::json &jv,bool dfl);
  206. static std::string jsonString(const nlohmann::json &jv,const char *dfl);
  207. #endif // OMIT_JSON_SUPPORT
  208. };
  209. } // namespace ZeroTier
  210. #endif