OSUtils.hpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_OSUTILS_HPP
  28. #define ZT_OSUTILS_HPP
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <stdint.h>
  32. #include <string.h>
  33. #include <time.h>
  34. #include <string>
  35. #include <stdexcept>
  36. #include <vector>
  37. #include <map>
  38. #include "../node/Constants.hpp"
  39. #include "../node/InetAddress.hpp"
  40. #ifdef __WINDOWS__
  41. #include <WinSock2.h>
  42. #include <Windows.h>
  43. #include <Shlwapi.h>
  44. #else
  45. #include <unistd.h>
  46. #include <errno.h>
  47. #include <sys/time.h>
  48. #include <sys/stat.h>
  49. #include <arpa/inet.h>
  50. #endif
  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. throw()
  90. {
  91. #ifdef __WINDOWS__
  92. if (::PathIsDirectoryA(path))
  93. return true;
  94. return (::CreateDirectoryA(path,NULL) == TRUE);
  95. #else
  96. if (::mkdir(path,0755) != 0)
  97. return (errno == EEXIST);
  98. return true;
  99. #endif
  100. }
  101. static inline bool mkdir(const std::string &path) throw() { return OSUtils::mkdir(path.c_str()); }
  102. /**
  103. * List a directory's contents
  104. *
  105. * This returns only files, not sub-directories.
  106. *
  107. * @param path Path to list
  108. * @return Names of files in directory
  109. */
  110. static std::vector<std::string> listDirectory(const char *path);
  111. /**
  112. * Set modes on a file to something secure
  113. *
  114. * This locks a file so that only the owner can access it. What it actually
  115. * does varies by platform.
  116. *
  117. * @param path Path to lock
  118. * @param isDir True if this is a directory
  119. */
  120. static void lockDownFile(const char *path,bool isDir);
  121. /**
  122. * Get file last modification time
  123. *
  124. * Resolution is often only second, not millisecond, but the return is
  125. * always in ms for comparison against now().
  126. *
  127. * @param path Path to file to get time
  128. * @return Last modification time in ms since epoch or 0 if not found
  129. */
  130. static uint64_t getLastModified(const char *path);
  131. /**
  132. * @param path Path to check
  133. * @param followLinks Follow links (on platforms with that concept)
  134. * @return True if file or directory exists at path location
  135. */
  136. static bool fileExists(const char *path,bool followLinks = true);
  137. /**
  138. * @param path Path to file
  139. * @return File size or -1 if nonexistent or other failure
  140. */
  141. static int64_t getFileSize(const char *path);
  142. /**
  143. * Get IP (v4 and/or v6) addresses for a given host
  144. *
  145. * This is a blocking resolver.
  146. *
  147. * @param name Host name
  148. * @return IP addresses in InetAddress sort order or empty vector if not found
  149. */
  150. static std::vector<InetAddress> resolve(const char *name);
  151. /**
  152. * @return Current time in milliseconds since epoch
  153. */
  154. static inline uint64_t now()
  155. throw()
  156. {
  157. #ifdef __WINDOWS__
  158. FILETIME ft;
  159. SYSTEMTIME st;
  160. ULARGE_INTEGER tmp;
  161. GetSystemTime(&st);
  162. SystemTimeToFileTime(&st,&ft);
  163. tmp.LowPart = ft.dwLowDateTime;
  164. tmp.HighPart = ft.dwHighDateTime;
  165. return ( ((tmp.QuadPart - 116444736000000000ULL) / 10000L) + st.wMilliseconds );
  166. #else
  167. struct timeval tv;
  168. gettimeofday(&tv,(struct timezone *)0);
  169. return ( (1000ULL * (uint64_t)tv.tv_sec) + (uint64_t)(tv.tv_usec / 1000) );
  170. #endif
  171. };
  172. /**
  173. * @return Current time in seconds since epoch, to the highest available resolution
  174. */
  175. static inline double nowf()
  176. throw()
  177. {
  178. #ifdef __WINDOWS__
  179. FILETIME ft;
  180. SYSTEMTIME st;
  181. ULARGE_INTEGER tmp;
  182. GetSystemTime(&st);
  183. SystemTimeToFileTime(&st,&ft);
  184. tmp.LowPart = ft.dwLowDateTime;
  185. tmp.HighPart = ft.dwHighDateTime;
  186. return (((double)(tmp.QuadPart - 116444736000000000ULL)) / 10000000.0);
  187. #else
  188. struct timeval tv;
  189. gettimeofday(&tv,(struct timezone *)0);
  190. return ( ((double)tv.tv_sec) + (((double)tv.tv_usec) / 1000000.0) );
  191. #endif
  192. }
  193. /**
  194. * Read the full contents of a file into a string buffer
  195. *
  196. * The buffer isn't cleared, so if it already contains data the file's data will
  197. * be appended.
  198. *
  199. * @param path Path of file to read
  200. * @param buf Buffer to fill
  201. * @return True if open and read successful
  202. */
  203. static bool readFile(const char *path,std::string &buf);
  204. /**
  205. * Write a block of data to disk, replacing any current file contents
  206. *
  207. * @param path Path to write
  208. * @param buf Buffer containing data
  209. * @param len Length of buffer
  210. * @return True if entire file was successfully written
  211. */
  212. static bool writeFile(const char *path,const void *buf,unsigned int len);
  213. /**
  214. * Write a block of data to disk, replacing any current file contents
  215. *
  216. * @param path Path to write
  217. * @param s Data to write
  218. * @return True if entire file was successfully written
  219. */
  220. static inline bool writeFile(const char *path,const std::string &s) { return writeFile(path,s.data(),(unsigned int)s.length()); }
  221. /**
  222. * @param c ASCII character to convert
  223. * @return Lower case ASCII character or unchanged if not a letter
  224. */
  225. static inline char toLower(char c) throw() { return (char)OSUtils::TOLOWER_TABLE[(unsigned long)c]; }
  226. private:
  227. static const unsigned char TOLOWER_TABLE[256];
  228. };
  229. } // namespace ZeroTier
  230. #endif