Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(501)

Side by Side Diff: third_party/libjingle/overrides/talk/base/win32.cc

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

Powered by Google App Engine
This is Rietveld 408576698