blob: acc3d331deaa6ccaff92f429140e213c5a3f1ab6 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/win32.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
13#include <winsock2.h>
14#include <ws2tcpip.h>
15#include <algorithm>
16
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "rtc_base/arraysize.h"
Steve Anton10542f22019-01-11 09:11:00 -080018#include "rtc_base/byte_order.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/checks.h"
20#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "rtc_base/string_utils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022
23namespace rtc {
24
25// Helper function declarations for inet_ntop/inet_pton.
26static const char* inet_ntop_v4(const void* src, char* dst, socklen_t size);
27static const char* inet_ntop_v6(const void* src, char* dst, socklen_t size);
28static int inet_pton_v4(const char* src, void* dst);
29static int inet_pton_v6(const char* src, void* dst);
30
31// Implementation of inet_ntop (create a printable representation of an
32// ip address). XP doesn't have its own inet_ntop, and
33// WSAAddressToString requires both IPv6 to be installed and for Winsock
34// to be initialized.
Yves Gerey665174f2018-06-19 15:03:05 +020035const char* win32_inet_ntop(int af,
36 const void* src,
37 char* dst,
38 socklen_t size) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039 if (!src || !dst) {
deadbeef37f5ecf2017-02-27 14:06:41 -080040 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041 }
42 switch (af) {
43 case AF_INET: {
44 return inet_ntop_v4(src, dst, size);
45 }
46 case AF_INET6: {
47 return inet_ntop_v6(src, dst, size);
48 }
49 }
deadbeef37f5ecf2017-02-27 14:06:41 -080050 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000051}
52
53// As above, but for inet_pton. Implements inet_pton for v4 and v6.
54// Note that our inet_ntop will output normal 'dotted' v4 addresses only.
55int win32_inet_pton(int af, const char* src, void* dst) {
56 if (!src || !dst) {
57 return 0;
58 }
59 if (af == AF_INET) {
60 return inet_pton_v4(src, dst);
61 } else if (af == AF_INET6) {
62 return inet_pton_v6(src, dst);
63 }
64 return -1;
65}
66
67// Helper function for inet_ntop for IPv4 addresses.
68// Outputs "dotted-quad" decimal notation.
69const char* inet_ntop_v4(const void* src, char* dst, socklen_t size) {
70 if (size < INET_ADDRSTRLEN) {
deadbeef37f5ecf2017-02-27 14:06:41 -080071 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072 }
73 const struct in_addr* as_in_addr =
74 reinterpret_cast<const struct in_addr*>(src);
Niels Mölleraba06332018-10-16 15:14:15 +020075 snprintf(dst, size, "%d.%d.%d.%d", as_in_addr->S_un.S_un_b.s_b1,
76 as_in_addr->S_un.S_un_b.s_b2, as_in_addr->S_un.S_un_b.s_b3,
77 as_in_addr->S_un.S_un_b.s_b4);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000078 return dst;
79}
80
81// Helper function for inet_ntop for IPv6 addresses.
82const char* inet_ntop_v6(const void* src, char* dst, socklen_t size) {
83 if (size < INET6_ADDRSTRLEN) {
deadbeef37f5ecf2017-02-27 14:06:41 -080084 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085 }
Peter Boström0c4e06b2015-10-07 12:23:21 +020086 const uint16_t* as_shorts = reinterpret_cast<const uint16_t*>(src);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087 int runpos[8];
88 int current = 1;
guoweis@webrtc.orgb08f4042015-02-17 19:00:42 +000089 int max = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090 int maxpos = -1;
tfarina5237aaf2015-11-10 23:44:30 -080091 int run_array_size = arraysize(runpos);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092 // Run over the address marking runs of 0s.
93 for (int i = 0; i < run_array_size; ++i) {
94 if (as_shorts[i] == 0) {
95 runpos[i] = current;
96 if (current > max) {
97 maxpos = i;
98 max = current;
99 }
100 ++current;
101 } else {
102 runpos[i] = -1;
guoweis@webrtc.orgb08f4042015-02-17 19:00:42 +0000103 current = 1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104 }
105 }
106
guoweis@webrtc.orgb08f4042015-02-17 19:00:42 +0000107 if (max > 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000108 int tmpmax = maxpos;
109 // Run back through, setting -1 for all but the longest run.
110 for (int i = run_array_size - 1; i >= 0; i--) {
111 if (i > tmpmax) {
112 runpos[i] = -1;
113 } else if (runpos[i] == -1) {
114 // We're less than maxpos, we hit a -1, so the 'good' run is done.
115 // Setting tmpmax -1 means all remaining positions get set to -1.
116 tmpmax = -1;
117 }
118 }
119 }
120
121 char* cursor = dst;
122 // Print IPv4 compatible and IPv4 mapped addresses using the IPv4 helper.
123 // These addresses have an initial run of either eight zero-bytes followed
124 // by 0xFFFF, or an initial run of ten zero-bytes.
Yves Gerey665174f2018-06-19 15:03:05 +0200125 if (runpos[0] == 1 &&
126 (maxpos == 5 || (maxpos == 4 && as_shorts[5] == 0xFFFF))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000127 *cursor++ = ':';
128 *cursor++ = ':';
129 if (maxpos == 4) {
Niels Mölleraba06332018-10-16 15:14:15 +0200130 cursor += snprintf(cursor, INET6_ADDRSTRLEN - 2, "ffff:");
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131 }
132 const struct in_addr* as_v4 =
133 reinterpret_cast<const struct in_addr*>(&(as_shorts[6]));
134 inet_ntop_v4(as_v4, cursor,
135 static_cast<socklen_t>(INET6_ADDRSTRLEN - (cursor - dst)));
136 } else {
137 for (int i = 0; i < run_array_size; ++i) {
138 if (runpos[i] == -1) {
Niels Mölleraba06332018-10-16 15:14:15 +0200139 cursor += snprintf(cursor, INET6_ADDRSTRLEN - (cursor - dst), "%x",
140 NetworkToHost16(as_shorts[i]));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141 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 12:23:21 +0200216 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:26 +0000218 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").
Yves Gerey665174f2018-06-19 15:03:05 +0200223 if (*readcursor == ':' && *(readcursor + 1) == ':' &&
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000224 *(readcursor + 2) != 0) {
225 // Check for periods, which we'll take as a sign of v4 addresses.
226 const char* addrstart = readcursor + 2;
Niels Möllerd1892522018-10-17 13:39:01 +0200227 if (strchr(addrstart, '.')) {
228 const char* colon = strchr(addrstart, ':');
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229 if (colon) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200230 uint16_t a_short;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000231 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.
deadbeef966963a2017-05-08 11:35:56 -0700278 // If this number is greater than the number of available shorts, the
279 // address is malformed.
280 if (coloncount + 1 > addr_end - addr_cursor) {
281 return 0;
282 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000283 addr_cursor = addr_end - (coloncount + 1);
284 seencompressed = true;
285 }
286 } else {
287 ++readcursor;
288 }
289 } else {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200290 uint16_t word;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291 int bytesread = 0;
deadbeef966963a2017-05-08 11:35:56 -0700292 if (sscanf(readcursor, "%4hx%n", &word, &bytesread) != 1) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293 return 0;
294 } else {
295 *addr_cursor = HostToNetwork16(word);
296 ++addr_cursor;
297 readcursor += bytesread;
298 if (*readcursor != ':' && *readcursor != '\0') {
299 return 0;
300 }
301 }
302 }
303 }
304
305 if (*readcursor != '\0' || addr_cursor < addr_end) {
306 // Catches addresses too short or too long.
307 return 0;
308 }
309 memcpy(dst, &an_addr, sizeof(an_addr));
310 return 1;
311}
312
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313bool Utf8ToWindowsFilename(const std::string& utf8, std::wstring* filename) {
314 // TODO: Integrate into fileutils.h
315 // TODO: Handle wide and non-wide cases via TCHAR?
316 // TODO: Skip \\?\ processing if the length is not > MAX_PATH?
317 // TODO: Write unittests
318
319 // Convert to Utf16
deadbeef37f5ecf2017-02-27 14:06:41 -0800320 int wlen =
321 ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
322 static_cast<int>(utf8.length() + 1), nullptr, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323 if (0 == wlen) {
324 return false;
325 }
326 wchar_t* wfilename = STACK_ARRAY(wchar_t, wlen);
327 if (0 == ::MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(),
Yves Gerey665174f2018-06-19 15:03:05 +0200328 static_cast<int>(utf8.length() + 1), wfilename,
329 wlen)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330 return false;
331 }
332 // Replace forward slashes with backslashes
333 std::replace(wfilename, wfilename + wlen, L'/', L'\\');
Robin Raymondce1b1402018-11-22 20:10:11 -0500334#if defined(WINUWP)
335 // WinUWP sandboxed store applications require the paths to remain as
336 // relative paths.
337 filename->assign(wfilename);
338#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000339 // Convert to complete filename
Mirko Bonadei673f7e52019-03-25 09:01:02 +0100340 DWORD full_len = ::GetFullPathNameW(wfilename, 0, nullptr, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341 if (0 == full_len) {
342 return false;
343 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800344 wchar_t* filepart = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000345 wchar_t* full_filename = STACK_ARRAY(wchar_t, full_len + 6);
346 wchar_t* start = full_filename + 6;
Mirko Bonadei673f7e52019-03-25 09:01:02 +0100347 if (0 == ::GetFullPathNameW(wfilename, full_len, start, &filepart)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348 return false;
349 }
350 // Add long-path prefix
351 const wchar_t kLongPathPrefix[] = L"\\\\?\\UNC";
352 if ((start[0] != L'\\') || (start[1] != L'\\')) {
353 // Non-unc path: <pathname>
354 // Becomes: \\?\<pathname>
355 start -= 4;
nisseede5da42017-01-12 05:15:36 -0800356 RTC_DCHECK(start >= full_filename);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000357 memcpy(start, kLongPathPrefix, 4 * sizeof(wchar_t));
358 } else if (start[2] != L'?') {
359 // Unc path: \\<server>\<pathname>
360 // Becomes: \\?\UNC\<server>\<pathname>
361 start -= 6;
nisseede5da42017-01-12 05:15:36 -0800362 RTC_DCHECK(start >= full_filename);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363 memcpy(start, kLongPathPrefix, 7 * sizeof(wchar_t));
364 } else {
365 // Already in long-path form.
366 }
367 filename->assign(start);
Robin Raymondce1b1402018-11-22 20:10:11 -0500368#endif // defined(WINUWP)
369
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370 return true;
371}
372
Robin Raymondce1b1402018-11-22 20:10:11 -0500373// Windows UWP applications cannot obtain versioning information from
374// the sandbox with intention (as behehaviour based on OS versioning rather
375// than feature discovery / compilation flags is discoraged and Windows
376// 10 is living continously updated version unlike previous versions
377// of Windows).
378#if !defined(WINUWP)
379
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000380bool GetOsVersion(int* major, int* minor, int* build) {
381 OSVERSIONINFO info = {0};
382 info.dwOSVersionInfoSize = sizeof(info);
383 if (GetVersionEx(&info)) {
Yves Gerey665174f2018-06-19 15:03:05 +0200384 if (major)
385 *major = info.dwMajorVersion;
386 if (minor)
387 *minor = info.dwMinorVersion;
388 if (build)
389 *build = info.dwBuildNumber;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000390 return true;
391 }
392 return false;
393}
394
395bool GetCurrentProcessIntegrityLevel(int* level) {
396 bool ret = false;
397 HANDLE process = ::GetCurrentProcess(), token;
398 if (OpenProcessToken(process, TOKEN_QUERY | TOKEN_QUERY_SOURCE, &token)) {
399 DWORD size;
deadbeef37f5ecf2017-02-27 14:06:41 -0800400 if (!GetTokenInformation(token, TokenIntegrityLevel, nullptr, 0, &size) &&
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000401 GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000402 char* buf = STACK_ARRAY(char, size);
403 TOKEN_MANDATORY_LABEL* til =
404 reinterpret_cast<TOKEN_MANDATORY_LABEL*>(buf);
405 if (GetTokenInformation(token, TokenIntegrityLevel, til, size, &size)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000406 DWORD count = *GetSidSubAuthorityCount(til->Label.Sid);
407 *level = *GetSidSubAuthority(til->Label.Sid, count - 1);
408 ret = true;
409 }
410 }
411 CloseHandle(token);
412 }
413 return ret;
414}
André Susano Pinto5ec99852015-05-13 09:20:52 +0200415
Robin Raymondce1b1402018-11-22 20:10:11 -0500416#endif // !defined(WINUWP)
417
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000418} // namespace rtc