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