blob: 6e09829153f7a3e4cc65e7f0818eb78450a45608 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:261/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/base/win32.h"
12
13#include <winsock2.h>
14#include <ws2tcpip.h>
15#include <algorithm>
16
17#include "webrtc/base/basictypes.h"
18#include "webrtc/base/byteorder.h"
19#include "webrtc/base/common.h"
20#include "webrtc/base/logging.h"
21
22namespace rtc {
23
24// Helper function declarations for inet_ntop/inet_pton.
25static const char* inet_ntop_v4(const void* src, char* dst, socklen_t size);
26static const char* inet_ntop_v6(const void* src, char* dst, socklen_t size);
27static int inet_pton_v4(const char* src, void* dst);
28static int inet_pton_v6(const char* src, void* dst);
29
30// Implementation of inet_ntop (create a printable representation of an
31// ip address). XP doesn't have its own inet_ntop, and
32// WSAAddressToString requires both IPv6 to be installed and for Winsock
33// to be initialized.
34const char* win32_inet_ntop(int af, const void *src,
35 char* dst, socklen_t size) {
36 if (!src || !dst) {
37 return NULL;
38 }
39 switch (af) {
40 case AF_INET: {
41 return inet_ntop_v4(src, dst, size);
42 }
43 case AF_INET6: {
44 return inet_ntop_v6(src, dst, size);
45 }
46 }
47 return NULL;
48}
49
50// As above, but for inet_pton. Implements inet_pton for v4 and v6.
51// Note that our inet_ntop will output normal 'dotted' v4 addresses only.
52int win32_inet_pton(int af, const char* src, void* dst) {
53 if (!src || !dst) {
54 return 0;
55 }
56 if (af == AF_INET) {
57 return inet_pton_v4(src, dst);
58 } else if (af == AF_INET6) {
59 return inet_pton_v6(src, dst);
60 }
61 return -1;
62}
63
64// Helper function for inet_ntop for IPv4 addresses.
65// Outputs "dotted-quad" decimal notation.
66const char* inet_ntop_v4(const void* src, char* dst, socklen_t size) {
67 if (size < INET_ADDRSTRLEN) {
68 return NULL;
69 }
70 const struct in_addr* as_in_addr =
71 reinterpret_cast<const struct in_addr*>(src);
72 rtc::sprintfn(dst, size, "%d.%d.%d.%d",
73 as_in_addr->S_un.S_un_b.s_b1,
74 as_in_addr->S_un.S_un_b.s_b2,
75 as_in_addr->S_un.S_un_b.s_b3,
76 as_in_addr->S_un.S_un_b.s_b4);
77 return dst;
78}
79
80// Helper function for inet_ntop for IPv6 addresses.
81const char* inet_ntop_v6(const void* src, char* dst, socklen_t size) {
82 if (size < INET6_ADDRSTRLEN) {
83 return NULL;
84 }
Peter Boström0c4e06b2015-10-07 10:23:2185 const uint16_t* as_shorts = reinterpret_cast<const uint16_t*>(src);
henrike@webrtc.orgf0488722014-05-13 18:00:2686 int runpos[8];
87 int current = 1;
guoweis@webrtc.orgb08f4042015-02-17 19:00:4288 int max = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:2689 int maxpos = -1;
90 int run_array_size = ARRAY_SIZE(runpos);
91 // Run over the address marking runs of 0s.
92 for (int i = 0; i < run_array_size; ++i) {
93 if (as_shorts[i] == 0) {
94 runpos[i] = current;
95 if (current > max) {
96 maxpos = i;
97 max = current;
98 }
99 ++current;
100 } else {
101 runpos[i] = -1;
guoweis@webrtc.orgb08f4042015-02-17 19:00:42102 current = 1;
henrike@webrtc.orgf0488722014-05-13 18:00:26103 }
104 }
105
guoweis@webrtc.orgb08f4042015-02-17 19:00:42106 if (max > 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26107 int tmpmax = maxpos;
108 // Run back through, setting -1 for all but the longest run.
109 for (int i = run_array_size - 1; i >= 0; i--) {
110 if (i > tmpmax) {
111 runpos[i] = -1;
112 } else if (runpos[i] == -1) {
113 // We're less than maxpos, we hit a -1, so the 'good' run is done.
114 // Setting tmpmax -1 means all remaining positions get set to -1.
115 tmpmax = -1;
116 }
117 }
118 }
119
120 char* cursor = dst;
121 // Print IPv4 compatible and IPv4 mapped addresses using the IPv4 helper.
122 // These addresses have an initial run of either eight zero-bytes followed
123 // by 0xFFFF, or an initial run of ten zero-bytes.
124 if (runpos[0] == 1 && (maxpos == 5 ||
125 (maxpos == 4 && as_shorts[5] == 0xFFFF))) {
126 *cursor++ = ':';
127 *cursor++ = ':';
128 if (maxpos == 4) {
129 cursor += rtc::sprintfn(cursor, INET6_ADDRSTRLEN - 2, "ffff:");
130 }
131 const struct in_addr* as_v4 =
132 reinterpret_cast<const struct in_addr*>(&(as_shorts[6]));
133 inet_ntop_v4(as_v4, cursor,
134 static_cast<socklen_t>(INET6_ADDRSTRLEN - (cursor - dst)));
135 } else {
136 for (int i = 0; i < run_array_size; ++i) {
137 if (runpos[i] == -1) {
138 cursor += rtc::sprintfn(cursor,
139 INET6_ADDRSTRLEN - (cursor - dst),
140 "%x", NetworkToHost16(as_shorts[i]));
141 if (i != 7 && runpos[i + 1] != 1) {
142 *cursor++ = ':';
143 }
144 } else if (runpos[i] == 1) {
145 // Entered the run; print the colons and skip the run.
146 *cursor++ = ':';
147 *cursor++ = ':';
148 i += (max - 1);
149 }
150 }
151 }
152 return dst;
153}
154
155// Helper function for inet_pton for IPv4 addresses.
156// |src| points to a character string containing an IPv4 network address in
157// dotted-decimal format, "ddd.ddd.ddd.ddd", where ddd is a decimal number
158// of up to three digits in the range 0 to 255.
159// The address is converted and copied to dst,
160// which must be sizeof(struct in_addr) (4) bytes (32 bits) long.
161int inet_pton_v4(const char* src, void* dst) {
162 const int kIpv4AddressSize = 4;
163 int found = 0;
164 const char* src_pos = src;
165 unsigned char result[kIpv4AddressSize] = {0};
166
167 while (*src_pos != '\0') {
168 // strtol won't treat whitespace characters in the begining as an error,
169 // so check to ensure this is started with digit before passing to strtol.
170 if (!isdigit(*src_pos)) {
171 return 0;
172 }
173 char* end_pos;
174 long value = strtol(src_pos, &end_pos, 10);
175 if (value < 0 || value > 255 || src_pos == end_pos) {
176 return 0;
177 }
178 ++found;
179 if (found > kIpv4AddressSize) {
180 return 0;
181 }
182 result[found - 1] = static_cast<unsigned char>(value);
183 src_pos = end_pos;
184 if (*src_pos == '.') {
185 // There's more.
186 ++src_pos;
187 } else if (*src_pos != '\0') {
188 // If it's neither '.' nor '\0' then return fail.
189 return 0;
190 }
191 }
192 if (found != kIpv4AddressSize) {
193 return 0;
194 }
195 memcpy(dst, result, sizeof(result));
196 return 1;
197}
198
199// Helper function for inet_pton for IPv6 addresses.
200int inet_pton_v6(const char* src, void* dst) {
201 // sscanf will pick any other invalid chars up, but it parses 0xnnnn as hex.
202 // Check for literal x in the input string.
203 const char* readcursor = src;
204 char c = *readcursor++;
205 while (c) {
206 if (c == 'x') {
207 return 0;
208 }
209 c = *readcursor++;
210 }
211 readcursor = src;
212
213 struct in6_addr an_addr;
214 memset(&an_addr, 0, sizeof(an_addr));
215
Peter Boström0c4e06b2015-10-07 10:23:21216 uint16_t* addr_cursor = reinterpret_cast<uint16_t*>(&an_addr.s6_addr[0]);
217 uint16_t* addr_end = reinterpret_cast<uint16_t*>(&an_addr.s6_addr[16]);
henrike@webrtc.orgf0488722014-05-13 18:00:26218 bool seencompressed = false;
219
220 // Addresses that start with "::" (i.e., a run of initial zeros) or
221 // "::ffff:" can potentially be IPv4 mapped or compatibility addresses.
222 // These have dotted-style IPv4 addresses on the end (e.g. "::192.168.7.1").
223 if (*readcursor == ':' && *(readcursor+1) == ':' &&
224 *(readcursor + 2) != 0) {
225 // Check for periods, which we'll take as a sign of v4 addresses.
226 const char* addrstart = readcursor + 2;
227 if (rtc::strchr(addrstart, ".")) {
228 const char* colon = rtc::strchr(addrstart, "::");
229 if (colon) {
Peter Boström0c4e06b2015-10-07 10:23:21230 uint16_t a_short;
henrike@webrtc.orgf0488722014-05-13 18:00:26231 int bytesread = 0;
232 if (sscanf(addrstart, "%hx%n", &a_short, &bytesread) != 1 ||
233 a_short != 0xFFFF || bytesread != 4) {
234 // Colons + periods means has to be ::ffff:a.b.c.d. But it wasn't.
235 return 0;
236 } else {
237 an_addr.s6_addr[10] = 0xFF;
238 an_addr.s6_addr[11] = 0xFF;
239 addrstart = colon + 1;
240 }
241 }
242 struct in_addr v4;
243 if (inet_pton_v4(addrstart, &v4.s_addr)) {
244 memcpy(&an_addr.s6_addr[12], &v4, sizeof(v4));
245 memcpy(dst, &an_addr, sizeof(an_addr));
246 return 1;
247 } else {
248 // Invalid v4 address.
249 return 0;
250 }
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 {
Peter Boström0c4e06b2015-10-07 10:23:21285 uint16_t word;
henrike@webrtc.orgf0488722014-05-13 18:00:26286 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
300 if (*readcursor != '\0' || addr_cursor < addr_end) {
301 // Catches addresses too short or too long.
302 return 0;
303 }
304 memcpy(dst, &an_addr, sizeof(an_addr));
305 return 1;
306}
307
308//
309// Unix time is in seconds relative to 1/1/1970. So we compute the windows
310// FILETIME of that time/date, then we add/subtract in appropriate units to
311// convert to/from unix time.
312// The units of FILETIME are 100ns intervals, so by multiplying by or dividing
313// by 10000000, we can convert to/from seconds.
314//
315// FileTime = UnixTime*10000000 + FileTime(1970)
316// UnixTime = (FileTime-FileTime(1970))/10000000
317//
318
319void FileTimeToUnixTime(const FILETIME& ft, time_t* ut) {
320 ASSERT(NULL != ut);
321
322 // FILETIME has an earlier date base than time_t (1/1/1970), so subtract off
323 // the difference.
324 SYSTEMTIME base_st;
325 memset(&base_st, 0, sizeof(base_st));
326 base_st.wDay = 1;
327 base_st.wMonth = 1;
328 base_st.wYear = 1970;
329
330 FILETIME base_ft;
331 SystemTimeToFileTime(&base_st, &base_ft);
332
333 ULARGE_INTEGER base_ul, current_ul;
334 memcpy(&base_ul, &base_ft, sizeof(FILETIME));
335 memcpy(&current_ul, &ft, sizeof(FILETIME));
336
337 // Divide by big number to convert to seconds, then subtract out the 1970
338 // base date value.
339 const ULONGLONG RATIO = 10000000;
340 *ut = static_cast<time_t>((current_ul.QuadPart - base_ul.QuadPart) / RATIO);
341}
342
343void UnixTimeToFileTime(const time_t& ut, FILETIME* ft) {
344 ASSERT(NULL != ft);
345
346 // FILETIME has an earlier date base than time_t (1/1/1970), so add in
347 // the difference.
348 SYSTEMTIME base_st;
349 memset(&base_st, 0, sizeof(base_st));
350 base_st.wDay = 1;
351 base_st.wMonth = 1;
352 base_st.wYear = 1970;
353
354 FILETIME base_ft;
355 SystemTimeToFileTime(&base_st, &base_ft);
356
357 ULARGE_INTEGER base_ul;
358 memcpy(&base_ul, &base_ft, sizeof(FILETIME));
359
360 // Multiply by big number to convert to 100ns units, then add in the 1970
361 // base date value.
362 const ULONGLONG RATIO = 10000000;
363 ULARGE_INTEGER current_ul;
Peter Boström0c4e06b2015-10-07 10:23:21364 current_ul.QuadPart = base_ul.QuadPart + static_cast<int64_t>(ut) * RATIO;
henrike@webrtc.orgf0488722014-05-13 18:00:26365 memcpy(ft, &current_ul, sizeof(FILETIME));
366}
367
368bool Utf8ToWindowsFilename(const std::string& utf8, std::wstring* filename) {
369 // TODO: Integrate into fileutils.h
370 // TODO: Handle wide and non-wide cases via TCHAR?
371 // TODO: Skip \\?\ processing if the length is not > MAX_PATH?
372 // TODO: Write unittests
373
374 // Convert to Utf16
375 int wlen = ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
376 static_cast<int>(utf8.length() + 1), NULL,
377 0);
378 if (0 == wlen) {
379 return false;
380 }
381 wchar_t* wfilename = STACK_ARRAY(wchar_t, wlen);
382 if (0 == ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
383 static_cast<int>(utf8.length() + 1),
384 wfilename, wlen)) {
385 return false;
386 }
387 // Replace forward slashes with backslashes
388 std::replace(wfilename, wfilename + wlen, L'/', L'\\');
389 // Convert to complete filename
390 DWORD full_len = ::GetFullPathName(wfilename, 0, NULL, NULL);
391 if (0 == full_len) {
392 return false;
393 }
394 wchar_t* filepart = NULL;
395 wchar_t* full_filename = STACK_ARRAY(wchar_t, full_len + 6);
396 wchar_t* start = full_filename + 6;
397 if (0 == ::GetFullPathName(wfilename, full_len, start, &filepart)) {
398 return false;
399 }
400 // Add long-path prefix
401 const wchar_t kLongPathPrefix[] = L"\\\\?\\UNC";
402 if ((start[0] != L'\\') || (start[1] != L'\\')) {
403 // Non-unc path: <pathname>
404 // Becomes: \\?\<pathname>
405 start -= 4;
406 ASSERT(start >= full_filename);
407 memcpy(start, kLongPathPrefix, 4 * sizeof(wchar_t));
408 } else if (start[2] != L'?') {
409 // Unc path: \\<server>\<pathname>
410 // Becomes: \\?\UNC\<server>\<pathname>
411 start -= 6;
412 ASSERT(start >= full_filename);
413 memcpy(start, kLongPathPrefix, 7 * sizeof(wchar_t));
414 } else {
415 // Already in long-path form.
416 }
417 filename->assign(start);
418 return true;
419}
420
421bool GetOsVersion(int* major, int* minor, int* build) {
422 OSVERSIONINFO info = {0};
423 info.dwOSVersionInfoSize = sizeof(info);
424 if (GetVersionEx(&info)) {
425 if (major) *major = info.dwMajorVersion;
426 if (minor) *minor = info.dwMinorVersion;
427 if (build) *build = info.dwBuildNumber;
428 return true;
429 }
430 return false;
431}
432
433bool GetCurrentProcessIntegrityLevel(int* level) {
434 bool ret = false;
435 HANDLE process = ::GetCurrentProcess(), token;
436 if (OpenProcessToken(process, TOKEN_QUERY | TOKEN_QUERY_SOURCE, &token)) {
437 DWORD size;
438 if (!GetTokenInformation(token, TokenIntegrityLevel, NULL, 0, &size) &&
439 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
440
441 char* buf = STACK_ARRAY(char, size);
442 TOKEN_MANDATORY_LABEL* til =
443 reinterpret_cast<TOKEN_MANDATORY_LABEL*>(buf);
444 if (GetTokenInformation(token, TokenIntegrityLevel, til, size, &size)) {
445
446 DWORD count = *GetSidSubAuthorityCount(til->Label.Sid);
447 *level = *GetSidSubAuthority(til->Label.Sid, count - 1);
448 ret = true;
449 }
450 }
451 CloseHandle(token);
452 }
453 return ret;
454}
André Susano Pinto5ec99852015-05-13 07:20:52455
henrike@webrtc.orgf0488722014-05-13 18:00:26456} // namespace rtc