You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

473 lines
15 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/base/win32.h"
  28. #include <winsock2.h>
  29. #include <ws2tcpip.h>
  30. #include <algorithm>
  31. #include "talk/base/basictypes.h"
  32. #include "talk/base/byteorder.h"
  33. #include "talk/base/common.h"
  34. #include "talk/base/logging.h"
  35. namespace talk_base {
  36. // Helper function declarations for inet_ntop/inet_pton.
  37. static const char* inet_ntop_v4(const void* src, char* dst, socklen_t size);
  38. static const char* inet_ntop_v6(const void* src, char* dst, socklen_t size);
  39. static int inet_pton_v4(const char* src, void* dst);
  40. static int inet_pton_v6(const char* src, void* dst);
  41. // Implementation of inet_ntop (create a printable representation of an
  42. // ip address). XP doesn't have its own inet_ntop, and
  43. // WSAAddressToString requires both IPv6 to be installed and for Winsock
  44. // to be initialized.
  45. const char* win32_inet_ntop(int af, const void *src,
  46. char* dst, socklen_t size) {
  47. if (!src || !dst) {
  48. return NULL;
  49. }
  50. switch (af) {
  51. case AF_INET: {
  52. return inet_ntop_v4(src, dst, size);
  53. }
  54. case AF_INET6: {
  55. return inet_ntop_v6(src, dst, size);
  56. }
  57. }
  58. return NULL;
  59. }
  60. // As above, but for inet_pton. Implements inet_pton for v4 and v6.
  61. // Note that our inet_ntop will output normal 'dotted' v4 addresses only.
  62. int win32_inet_pton(int af, const char* src, void* dst) {
  63. if (!src || !dst) {
  64. return 0;
  65. }
  66. if (af == AF_INET) {
  67. return inet_pton_v4(src, dst);
  68. } else if (af == AF_INET6) {
  69. return inet_pton_v6(src, dst);
  70. }
  71. return -1;
  72. }
  73. // Helper function for inet_ntop for IPv4 addresses.
  74. // Outputs "dotted-quad" decimal notation.
  75. const char* inet_ntop_v4(const void* src, char* dst, socklen_t size) {
  76. if (size < INET_ADDRSTRLEN) {
  77. return NULL;
  78. }
  79. const struct in_addr* as_in_addr =
  80. reinterpret_cast<const struct in_addr*>(src);
  81. talk_base::sprintfn(dst, size, "%d.%d.%d.%d",
  82. as_in_addr->S_un.S_un_b.s_b1,
  83. as_in_addr->S_un.S_un_b.s_b2,
  84. as_in_addr->S_un.S_un_b.s_b3,
  85. as_in_addr->S_un.S_un_b.s_b4);
  86. return dst;
  87. }
  88. // Helper function for inet_ntop for IPv6 addresses.
  89. const char* inet_ntop_v6(const void* src, char* dst, socklen_t size) {
  90. if (size < INET6_ADDRSTRLEN) {
  91. return NULL;
  92. }
  93. const uint16* as_shorts =
  94. reinterpret_cast<const uint16*>(src);
  95. int runpos[8];
  96. int current = 1;
  97. int max = 1;
  98. int maxpos = -1;
  99. int run_array_size = ARRAY_SIZE(runpos);
  100. // Run over the address marking runs of 0s.
  101. for (int i = 0; i < run_array_size; ++i) {
  102. if (as_shorts[i] == 0) {
  103. runpos[i] = current;
  104. if (current > max) {
  105. maxpos = i;
  106. max = current;
  107. }
  108. ++current;
  109. } else {
  110. runpos[i] = -1;
  111. current =1;
  112. }
  113. }
  114. if (max > 1) {
  115. int tmpmax = maxpos;
  116. // Run back through, setting -1 for all but the longest run.
  117. for (int i = run_array_size - 1; i >= 0; i--) {
  118. if (i > tmpmax) {
  119. runpos[i] = -1;
  120. } else if (runpos[i] == -1) {
  121. // We're less than maxpos, we hit a -1, so the 'good' run is done.
  122. // Setting tmpmax -1 means all remaining positions get set to -1.
  123. tmpmax = -1;
  124. }
  125. }
  126. }
  127. char* cursor = dst;
  128. // Print IPv4 compatible and IPv4 mapped addresses using the IPv4 helper.
  129. // These addresses have an initial run of either eight zero-bytes followed
  130. // by 0xFFFF, or an initial run of ten zero-bytes.
  131. if (runpos[0] == 1 && (maxpos == 5 ||
  132. (maxpos == 4 && as_shorts[5] == 0xFFFF))) {
  133. *cursor++ = ':';
  134. *cursor++ = ':';
  135. if (maxpos == 4) {
  136. cursor += talk_base::sprintfn(cursor, INET6_ADDRSTRLEN - 2, "ffff:");
  137. }
  138. const struct in_addr* as_v4 =
  139. reinterpret_cast<const struct in_addr*>(&(as_shorts[6]));
  140. inet_ntop_v4(as_v4, cursor,
  141. static_cast<socklen_t>(INET6_ADDRSTRLEN - (cursor - dst)));
  142. } else {
  143. for (int i = 0; i < run_array_size; ++i) {
  144. if (runpos[i] == -1) {
  145. cursor += talk_base::sprintfn(cursor,
  146. INET6_ADDRSTRLEN - (cursor - dst),
  147. "%x", NetworkToHost16(as_shorts[i]));
  148. if (i != 7 && runpos[i + 1] != 1) {
  149. *cursor++ = ':';
  150. }
  151. } else if (runpos[i] == 1) {
  152. // Entered the run; print the colons and skip the run.
  153. *cursor++ = ':';
  154. *cursor++ = ':';
  155. i += (max - 1);
  156. }
  157. }
  158. }
  159. return dst;
  160. }
  161. // Helper function for inet_pton for IPv4 addresses.
  162. // |src| points to a character string containing an IPv4 network address in
  163. // dotted-decimal format, "ddd.ddd.ddd.ddd", where ddd is a decimal number
  164. // of up to three digits in the range 0 to 255.
  165. // The address is converted and copied to dst,
  166. // which must be sizeof(struct in_addr) (4) bytes (32 bits) long.
  167. int inet_pton_v4(const char* src, void* dst) {
  168. const int kIpv4AddressSize = 4;
  169. int found = 0;
  170. const char* src_pos = src;
  171. unsigned char result[kIpv4AddressSize] = {0};
  172. while (*src_pos != '\0') {
  173. // strtol won't treat whitespace characters in the begining as an error,
  174. // so check to ensure this is started with digit before passing to strtol.
  175. if (!isdigit(*src_pos)) {
  176. return 0;
  177. }
  178. char* end_pos;
  179. long value = strtol(src_pos, &end_pos, 10);
  180. if (value < 0 || value > 255 || src_pos == end_pos) {
  181. return 0;
  182. }
  183. ++found;
  184. if (found > kIpv4AddressSize) {
  185. return 0;
  186. }
  187. result[found - 1] = static_cast<unsigned char>(value);
  188. src_pos = end_pos;
  189. if (*src_pos == '.') {
  190. // There's more.
  191. ++src_pos;
  192. } else if (*src_pos != '\0') {
  193. // If it's neither '.' nor '\0' then return fail.
  194. return 0;
  195. }
  196. }
  197. if (found != kIpv4AddressSize) {
  198. return 0;
  199. }
  200. memcpy(dst, result, sizeof(result));
  201. return 1;
  202. }
  203. // Helper function for inet_pton for IPv6 addresses.
  204. int inet_pton_v6(const char* src, void* dst) {
  205. // sscanf will pick any other invalid chars up, but it parses 0xnnnn as hex.
  206. // Check for literal x in the input string.
  207. const char* readcursor = src;
  208. char c = *readcursor++;
  209. while (c) {
  210. if (c == 'x') {
  211. return 0;
  212. }
  213. c = *readcursor++;
  214. }
  215. readcursor = src;
  216. struct in6_addr an_addr;
  217. memset(&an_addr, 0, sizeof(an_addr));
  218. uint16* addr_cursor = reinterpret_cast<uint16*>(&an_addr.s6_addr[0]);
  219. uint16* addr_end = reinterpret_cast<uint16*>(&an_addr.s6_addr[16]);
  220. bool seencompressed = false;
  221. // Addresses that start with "::" (i.e., a run of initial zeros) or
  222. // "::ffff:" can potentially be IPv4 mapped or compatibility addresses.
  223. // These have dotted-style IPv4 addresses on the end (e.g. "::192.168.7.1").
  224. if (*readcursor == ':' && *(readcursor+1) == ':' &&
  225. *(readcursor + 2) != 0) {
  226. // Check for periods, which we'll take as a sign of v4 addresses.
  227. const char* addrstart = readcursor + 2;
  228. if (talk_base::strchr(addrstart, ".")) {
  229. const char* colon = talk_base::strchr(addrstart, "::");
  230. if (colon) {
  231. uint16 a_short;
  232. int bytesread = 0;
  233. if (sscanf(addrstart, "%hx%n", &a_short, &bytesread) != 1 ||
  234. a_short != 0xFFFF || bytesread != 4) {
  235. // Colons + periods means has to be ::ffff:a.b.c.d. But it wasn't.
  236. return 0;
  237. } else {
  238. an_addr.s6_addr[10] = 0xFF;
  239. an_addr.s6_addr[11] = 0xFF;
  240. addrstart = colon + 1;
  241. }
  242. }
  243. struct in_addr v4;
  244. if (inet_pton_v4(addrstart, &v4.s_addr)) {
  245. memcpy(&an_addr.s6_addr[12], &v4, sizeof(v4));
  246. memcpy(dst, &an_addr, sizeof(an_addr));
  247. return 1;
  248. } else {
  249. // Invalid v4 address.
  250. return 0;
  251. }
  252. }
  253. }
  254. // For addresses without a trailing IPv4 component ('normal' IPv6 addresses).
  255. while (*readcursor != 0 && addr_cursor < addr_end) {
  256. if (*readcursor == ':') {
  257. if (*(readcursor + 1) == ':') {
  258. if (seencompressed) {
  259. // Can only have one compressed run of zeroes ("::") per address.
  260. return 0;
  261. }
  262. // Hit a compressed run. Count colons to figure out how much of the
  263. // address is skipped.
  264. readcursor += 2;
  265. const char* coloncounter = readcursor;
  266. int coloncount = 0;
  267. if (*coloncounter == 0) {
  268. // Special case - trailing ::.
  269. addr_cursor = addr_end;
  270. } else {
  271. while (*coloncounter) {
  272. if (*coloncounter == ':') {
  273. ++coloncount;
  274. }
  275. ++coloncounter;
  276. }
  277. // (coloncount + 1) is the number of shorts left in the address.
  278. addr_cursor = addr_end - (coloncount + 1);
  279. seencompressed = true;
  280. }
  281. } else {
  282. ++readcursor;
  283. }
  284. } else {
  285. uint16 word;
  286. int bytesread = 0;
  287. if (sscanf(readcursor, "%hx%n", &word, &bytesread) != 1) {
  288. return 0;
  289. } else {
  290. *addr_cursor = HostToNetwork16(word);
  291. ++addr_cursor;
  292. readcursor += bytesread;
  293. if (*readcursor != ':' && *readcursor != '\0') {
  294. return 0;
  295. }
  296. }
  297. }
  298. }
  299. if (*readcursor != '\0' || addr_cursor < addr_end) {
  300. // Catches addresses too short or too long.
  301. return 0;
  302. }
  303. memcpy(dst, &an_addr, sizeof(an_addr));
  304. return 1;
  305. }
  306. //
  307. // Unix time is in seconds relative to 1/1/1970. So we compute the windows
  308. // FILETIME of that time/date, then we add/subtract in appropriate units to
  309. // convert to/from unix time.
  310. // The units of FILETIME are 100ns intervals, so by multiplying by or dividing
  311. // by 10000000, we can convert to/from seconds.
  312. //
  313. // FileTime = UnixTime*10000000 + FileTime(1970)
  314. // UnixTime = (FileTime-FileTime(1970))/10000000
  315. //
  316. void FileTimeToUnixTime(const FILETIME& ft, time_t* ut) {
  317. ASSERT(NULL != ut);
  318. // FILETIME has an earlier date base than time_t (1/1/1970), so subtract off
  319. // the difference.
  320. SYSTEMTIME base_st;
  321. memset(&base_st, 0, sizeof(base_st));
  322. base_st.wDay = 1;
  323. base_st.wMonth = 1;
  324. base_st.wYear = 1970;
  325. FILETIME base_ft;
  326. SystemTimeToFileTime(&base_st, &base_ft);
  327. ULARGE_INTEGER base_ul, current_ul;
  328. memcpy(&base_ul, &base_ft, sizeof(FILETIME));
  329. memcpy(&current_ul, &ft, sizeof(FILETIME));
  330. // Divide by big number to convert to seconds, then subtract out the 1970
  331. // base date value.
  332. const ULONGLONG RATIO = 10000000;
  333. *ut = static_cast<time_t>((current_ul.QuadPart - base_ul.QuadPart) / RATIO);
  334. }
  335. void UnixTimeToFileTime(const time_t& ut, FILETIME* ft) {
  336. ASSERT(NULL != ft);
  337. // FILETIME has an earlier date base than time_t (1/1/1970), so add in
  338. // the difference.
  339. SYSTEMTIME base_st;
  340. memset(&base_st, 0, sizeof(base_st));
  341. base_st.wDay = 1;
  342. base_st.wMonth = 1;
  343. base_st.wYear = 1970;
  344. FILETIME base_ft;
  345. SystemTimeToFileTime(&base_st, &base_ft);
  346. ULARGE_INTEGER base_ul;
  347. memcpy(&base_ul, &base_ft, sizeof(FILETIME));
  348. // Multiply by big number to convert to 100ns units, then add in the 1970
  349. // base date value.
  350. const ULONGLONG RATIO = 10000000;
  351. ULARGE_INTEGER current_ul;
  352. current_ul.QuadPart = base_ul.QuadPart + static_cast<int64>(ut) * RATIO;
  353. memcpy(ft, &current_ul, sizeof(FILETIME));
  354. }
  355. bool Utf8ToWindowsFilename(const std::string& utf8, std::wstring* filename) {
  356. // TODO: Integrate into fileutils.h
  357. // TODO: Handle wide and non-wide cases via TCHAR?
  358. // TODO: Skip \\?\ processing if the length is not > MAX_PATH?
  359. // TODO: Write unittests
  360. // Convert to Utf16
  361. int wlen = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
  362. static_cast<int>(utf8.length() + 1), NULL,
  363. 0);
  364. if (0 == wlen) {
  365. return false;
  366. }
  367. wchar_t* wfilename = STACK_ARRAY(wchar_t, wlen);
  368. if (0 == ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
  369. static_cast<int>(utf8.length() + 1),
  370. wfilename, wlen)) {
  371. return false;
  372. }
  373. // Replace forward slashes with backslashes
  374. std::replace(wfilename, wfilename + wlen, L'/', L'\\');
  375. // Convert to complete filename
  376. DWORD full_len = ::GetFullPathName(wfilename, 0, NULL, NULL);
  377. if (0 == full_len) {
  378. return false;
  379. }
  380. wchar_t* filepart = NULL;
  381. wchar_t* full_filename = STACK_ARRAY(wchar_t, full_len + 6);
  382. wchar_t* start = full_filename + 6;
  383. if (0 == ::GetFullPathName(wfilename, full_len, start, &filepart)) {
  384. return false;
  385. }
  386. // Add long-path prefix
  387. const wchar_t kLongPathPrefix[] = L"\\\\?\\UNC";
  388. if ((start[0] != L'\\') || (start[1] != L'\\')) {
  389. // Non-unc path: <pathname>
  390. // Becomes: \\?\<pathname>
  391. start -= 4;
  392. ASSERT(start >= full_filename);
  393. memcpy(start, kLongPathPrefix, 4 * sizeof(wchar_t));
  394. } else if (start[2] != L'?') {
  395. // Unc path: \\<server>\<pathname>
  396. // Becomes: \\?\UNC\<server>\<pathname>
  397. start -= 6;
  398. ASSERT(start >= full_filename);
  399. memcpy(start, kLongPathPrefix, 7 * sizeof(wchar_t));
  400. } else {
  401. // Already in long-path form.
  402. }
  403. filename->assign(start);
  404. return true;
  405. }
  406. bool GetOsVersion(int* major, int* minor, int* build) {
  407. OSVERSIONINFO info = {0};
  408. info.dwOSVersionInfoSize = sizeof(info);
  409. if (GetVersionEx(&info)) {
  410. if (major) *major = info.dwMajorVersion;
  411. if (minor) *minor = info.dwMinorVersion;
  412. if (build) *build = info.dwBuildNumber;
  413. return true;
  414. }
  415. return false;
  416. }
  417. bool GetCurrentProcessIntegrityLevel(int* level) {
  418. bool ret = false;
  419. HANDLE process = ::GetCurrentProcess(), token;
  420. if (OpenProcessToken(process, TOKEN_QUERY | TOKEN_QUERY_SOURCE, &token)) {
  421. DWORD size;
  422. if (!GetTokenInformation(token, TokenIntegrityLevel, NULL, 0, &size) &&
  423. GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  424. char* buf = STACK_ARRAY(char, size);
  425. TOKEN_MANDATORY_LABEL* til =
  426. reinterpret_cast<TOKEN_MANDATORY_LABEL*>(buf);
  427. if (GetTokenInformation(token, TokenIntegrityLevel, til, size, &size)) {
  428. DWORD count = *GetSidSubAuthorityCount(til->Label.Sid);
  429. *level = *GetSidSubAuthority(til->Label.Sid, count - 1);
  430. ret = true;
  431. }
  432. }
  433. CloseHandle(token);
  434. }
  435. return ret;
  436. }
  437. } // namespace talk_base