OSUtils.hpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. namespace ZeroTier {
  43. /**
  44. * Miscellaneous utility functions and global constants
  45. */
  46. class OSUtils
  47. {
  48. public:
  49. #ifdef __UNIX_LIKE__
  50. /**
  51. * Close STDOUT_FILENO and STDERR_FILENO and replace them with output to given path
  52. *
  53. * This can be called after fork() and prior to exec() to suppress output
  54. * from a subprocess, such as auto-update.
  55. *
  56. * @param stdoutPath Path to file to use for stdout
  57. * @param stderrPath Path to file to use for stderr, or NULL for same as stdout (default)
  58. * @return True on success
  59. */
  60. static bool redirectUnixOutputs(const char *stdoutPath,const char *stderrPath = (const char *)0)
  61. throw();
  62. #endif // __UNIX_LIKE__
  63. /**
  64. * Delete a file
  65. *
  66. * @param path Path to delete
  67. * @return True if delete was successful
  68. */
  69. static inline bool rm(const char *path)
  70. throw()
  71. {
  72. #ifdef __WINDOWS__
  73. return (DeleteFileA(path) != FALSE);
  74. #else
  75. return (unlink(path) == 0);
  76. #endif
  77. }
  78. static inline bool rm(const std::string &path) throw() { return rm(path.c_str()); }
  79. static inline bool mkdir(const char *path)
  80. {
  81. #ifdef __WINDOWS__
  82. if (::PathIsDirectoryA(path))
  83. return true;
  84. return (::CreateDirectoryA(path,NULL) == TRUE);
  85. #else
  86. if (::mkdir(path,0755) != 0)
  87. return (errno == EEXIST);
  88. return true;
  89. #endif
  90. }
  91. static inline bool mkdir(const std::string &path) throw() { return OSUtils::mkdir(path.c_str()); }
  92. /**
  93. * List a directory's contents
  94. *
  95. * This returns only files, not sub-directories.
  96. *
  97. * @param path Path to list
  98. * @return Names of files in directory
  99. */
  100. static std::vector<std::string> listDirectory(const char *path);
  101. /**
  102. * Set modes on a file to something secure
  103. *
  104. * This locks a file so that only the owner can access it. What it actually
  105. * does varies by platform.
  106. *
  107. * @param path Path to lock
  108. * @param isDir True if this is a directory
  109. */
  110. static void lockDownFile(const char *path,bool isDir);
  111. /**
  112. * Get file last modification time
  113. *
  114. * Resolution is often only second, not millisecond, but the return is
  115. * always in ms for comparison against now().
  116. *
  117. * @param path Path to file to get time
  118. * @return Last modification time in ms since epoch or 0 if not found
  119. */
  120. static uint64_t getLastModified(const char *path);
  121. /**
  122. * @param path Path to check
  123. * @param followLinks Follow links (on platforms with that concept)
  124. * @return True if file or directory exists at path location
  125. */
  126. static bool fileExists(const char *path,bool followLinks = true);
  127. /**
  128. * @param path Path to file
  129. * @return File size or -1 if nonexistent or other failure
  130. */
  131. static int64_t getFileSize(const char *path);
  132. /**
  133. * Get IP (v4 and/or v6) addresses for a given host
  134. *
  135. * This is a blocking resolver.
  136. *
  137. * @param name Host name
  138. * @return IP addresses in InetAddress sort order or empty vector if not found
  139. */
  140. static std::vector<InetAddress> resolve(const char *name);
  141. /**
  142. * @return Current time in milliseconds since epoch
  143. */
  144. static inline uint64_t now()
  145. throw()
  146. {
  147. #ifdef __WINDOWS__
  148. FILETIME ft;
  149. SYSTEMTIME st;
  150. ULARGE_INTEGER tmp;
  151. GetSystemTime(&st);
  152. SystemTimeToFileTime(&st,&ft);
  153. tmp.LowPart = ft.dwLowDateTime;
  154. tmp.HighPart = ft.dwHighDateTime;
  155. return ( ((tmp.QuadPart - 116444736000000000ULL) / 10000L) + st.wMilliseconds );
  156. #else
  157. struct timeval tv;
  158. gettimeofday(&tv,(struct timezone *)0);
  159. return ( (1000ULL * (uint64_t)tv.tv_sec) + (uint64_t)(tv.tv_usec / 1000) );
  160. #endif
  161. };
  162. /**
  163. * @return Current time in seconds since epoch, to the highest available resolution
  164. */
  165. static inline double nowf()
  166. throw()
  167. {
  168. #ifdef __WINDOWS__
  169. FILETIME ft;
  170. SYSTEMTIME st;
  171. ULARGE_INTEGER tmp;
  172. GetSystemTime(&st);
  173. SystemTimeToFileTime(&st,&ft);
  174. tmp.LowPart = ft.dwLowDateTime;
  175. tmp.HighPart = ft.dwHighDateTime;
  176. return (((double)(tmp.QuadPart - 116444736000000000ULL)) / 10000000.0);
  177. #else
  178. struct timeval tv;
  179. gettimeofday(&tv,(struct timezone *)0);
  180. return ( ((double)tv.tv_sec) + (((double)tv.tv_usec) / 1000000.0) );
  181. #endif
  182. }
  183. /**
  184. * Read the full contents of a file into a string buffer
  185. *
  186. * The buffer isn't cleared, so if it already contains data the file's data will
  187. * be appended.
  188. *
  189. * @param path Path of file to read
  190. * @param buf Buffer to fill
  191. * @return True if open and read successful
  192. */
  193. static bool readFile(const char *path,std::string &buf);
  194. /**
  195. * Write a block of data to disk, replacing any current file contents
  196. *
  197. * @param path Path to write
  198. * @param buf Buffer containing data
  199. * @param len Length of buffer
  200. * @return True if entire file was successfully written
  201. */
  202. static bool writeFile(const char *path,const void *buf,unsigned int len);
  203. /**
  204. * Write a block of data to disk, replacing any current file contents
  205. *
  206. * @param path Path to write
  207. * @param s Data to write
  208. * @return True if entire file was successfully written
  209. */
  210. static inline bool writeFile(const char *path,const std::string &s) { return writeFile(path,s.data(),(unsigned int)s.length()); }
  211. /**
  212. * @param c ASCII character to convert
  213. * @return Lower case ASCII character or unchanged if not a letter
  214. */
  215. static inline char toLower(char c) throw() { return (char)OSUtils::TOLOWER_TABLE[(unsigned long)c]; }
  216. private:
  217. static const unsigned char TOLOWER_TABLE[256];
  218. };
  219. } // namespace ZeroTier
  220. #endif