Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / base / win / win_util.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/win/win_util.h"
6
7 #include <aclapi.h>
8 #include <cfgmgr32.h>
9 #include <lm.h>
10 #include <powrprof.h>
11 #include <shellapi.h>
12 #include <shlobj.h>
13 #include <shobjidl.h>  // Must be before propkey.
14 #include <initguid.h>
15 #include <propkey.h>
16 #include <propvarutil.h>
17 #include <sddl.h>
18 #include <setupapi.h>
19 #include <signal.h>
20 #include <stdlib.h>
21
22 #include "base/lazy_instance.h"
23 #include "base/logging.h"
24 #include "base/memory/scoped_ptr.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/threading/thread_restrictions.h"
28 #include "base/win/metro.h"
29 #include "base/win/registry.h"
30 #include "base/win/scoped_co_mem.h"
31 #include "base/win/scoped_handle.h"
32 #include "base/win/scoped_propvariant.h"
33 #include "base/win/windows_version.h"
34
35 namespace {
36
37 // Sets the value of |property_key| to |property_value| in |property_store|.
38 bool SetPropVariantValueForPropertyStore(
39     IPropertyStore* property_store,
40     const PROPERTYKEY& property_key,
41     const base::win::ScopedPropVariant& property_value) {
42   DCHECK(property_store);
43
44   HRESULT result = property_store->SetValue(property_key, property_value.get());
45   if (result == S_OK)
46     result = property_store->Commit();
47   return SUCCEEDED(result);
48 }
49
50 void __cdecl ForceCrashOnSigAbort(int) {
51   *((int*)0) = 0x1337;
52 }
53
54 const wchar_t kWindows8OSKRegPath[] =
55     L"Software\\Classes\\CLSID\\{054AAE20-4BEA-4347-8A35-64A533254A9D}"
56     L"\\LocalServer32";
57
58 // Returns true if a physical keyboard is detected on Windows 8 and up.
59 // Uses the Setup APIs to enumerate the attached keyboards and returns true
60 // if the keyboard count is more than 1. While this will work in most cases
61 // it won't work if there are devices which expose keyboard interfaces which
62 // are attached to the machine.
63 bool IsKeyboardPresentOnSlate() {
64   // This function is only supported for Windows 8 and up.
65   DCHECK(base::win::GetVersion() >= base::win::VERSION_WIN8);
66
67   // This function should be only invoked for machines with touch screens.
68   if ((GetSystemMetrics(SM_DIGITIZER) & NID_INTEGRATED_TOUCH)
69         != NID_INTEGRATED_TOUCH) {
70     return true;
71   }
72
73   const GUID KEYBOARD_CLASS_GUID =
74       { 0x4D36E96B, 0xE325,  0x11CE,
75           { 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 } };
76
77   // Query for all the keyboard devices.
78   HDEVINFO device_info =
79       SetupDiGetClassDevs(&KEYBOARD_CLASS_GUID, NULL, NULL, DIGCF_PRESENT);
80   if (device_info == INVALID_HANDLE_VALUE)
81     return false;
82
83   // Enumerate all keyboards and look for ACPI\PNP and HID\VID devices. If
84   // the count is more than 1 we assume that a keyboard is present. This is
85   // under the assumption that there will always be one keyboard device.
86   int keyboard_count = 0;
87   for (DWORD i = 0;; ++i) {
88     SP_DEVINFO_DATA device_info_data = { 0 };
89     device_info_data.cbSize = sizeof(device_info_data);
90     if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data))
91       break;
92     // Get the device ID.
93     wchar_t device_id[MAX_DEVICE_ID_LEN];
94     CONFIGRET status = CM_Get_Device_ID(device_info_data.DevInst,
95                                         device_id,
96                                         MAX_DEVICE_ID_LEN,
97                                         0);
98     if (status == CR_SUCCESS) {
99       // To reduce the scope of the hack we only look for PNP and HID
100       // keyboards.
101       if (StartsWith(L"ACPI\\PNP", device_id, false) ||
102           StartsWith(L"HID\\VID", device_id, false)) {
103         keyboard_count++;
104       }
105     }
106   }
107   // On a Windows machine, the API's always report 1 keyboard at least
108   // regardless of whether the machine has a keyboard attached or not.
109   // The heuristic we are using is to check the count and return true
110   // if the API's report more than one keyboard. Please note that this
111   // will break for non keyboard devices which expose a keyboard PDO.
112   return keyboard_count > 1;
113 }
114
115 }  // namespace
116
117 namespace base {
118 namespace win {
119
120 static bool g_crash_on_process_detach = false;
121
122 void GetNonClientMetrics(NONCLIENTMETRICS_XP* metrics) {
123   DCHECK(metrics);
124   metrics->cbSize = sizeof(*metrics);
125   const bool success = !!SystemParametersInfo(
126       SPI_GETNONCLIENTMETRICS,
127       metrics->cbSize,
128       reinterpret_cast<NONCLIENTMETRICS*>(metrics),
129       0);
130   DCHECK(success);
131 }
132
133 bool GetUserSidString(std::wstring* user_sid) {
134   // Get the current token.
135   HANDLE token = NULL;
136   if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
137     return false;
138   base::win::ScopedHandle token_scoped(token);
139
140   DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
141   scoped_ptr<BYTE[]> user_bytes(new BYTE[size]);
142   TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get());
143
144   if (!::GetTokenInformation(token, TokenUser, user, size, &size))
145     return false;
146
147   if (!user->User.Sid)
148     return false;
149
150   // Convert the data to a string.
151   wchar_t* sid_string;
152   if (!::ConvertSidToStringSid(user->User.Sid, &sid_string))
153     return false;
154
155   *user_sid = sid_string;
156
157   ::LocalFree(sid_string);
158
159   return true;
160 }
161
162 bool IsShiftPressed() {
163   return (::GetKeyState(VK_SHIFT) & 0x8000) == 0x8000;
164 }
165
166 bool IsCtrlPressed() {
167   return (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000;
168 }
169
170 bool IsAltPressed() {
171   return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000;
172 }
173
174 bool IsAltGrPressed() {
175   return (::GetKeyState(VK_MENU) & 0x8000) == 0x8000 &&
176       (::GetKeyState(VK_CONTROL) & 0x8000) == 0x8000;
177 }
178
179 bool UserAccountControlIsEnabled() {
180   // This can be slow if Windows ends up going to disk.  Should watch this key
181   // for changes and only read it once, preferably on the file thread.
182   //   http://code.google.com/p/chromium/issues/detail?id=61644
183   base::ThreadRestrictions::ScopedAllowIO allow_io;
184
185   base::win::RegKey key(HKEY_LOCAL_MACHINE,
186       L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
187       KEY_READ);
188   DWORD uac_enabled;
189   if (key.ReadValueDW(L"EnableLUA", &uac_enabled) != ERROR_SUCCESS)
190     return true;
191   // Users can set the EnableLUA value to something arbitrary, like 2, which
192   // Vista will treat as UAC enabled, so we make sure it is not set to 0.
193   return (uac_enabled != 0);
194 }
195
196 bool SetBooleanValueForPropertyStore(IPropertyStore* property_store,
197                                      const PROPERTYKEY& property_key,
198                                      bool property_bool_value) {
199   ScopedPropVariant property_value;
200   if (FAILED(InitPropVariantFromBoolean(property_bool_value,
201                                         property_value.Receive()))) {
202     return false;
203   }
204
205   return SetPropVariantValueForPropertyStore(property_store,
206                                              property_key,
207                                              property_value);
208 }
209
210 bool SetStringValueForPropertyStore(IPropertyStore* property_store,
211                                     const PROPERTYKEY& property_key,
212                                     const wchar_t* property_string_value) {
213   ScopedPropVariant property_value;
214   if (FAILED(InitPropVariantFromString(property_string_value,
215                                        property_value.Receive()))) {
216     return false;
217   }
218
219   return SetPropVariantValueForPropertyStore(property_store,
220                                              property_key,
221                                              property_value);
222 }
223
224 bool SetAppIdForPropertyStore(IPropertyStore* property_store,
225                               const wchar_t* app_id) {
226   // App id should be less than 64 chars and contain no space. And recommended
227   // format is CompanyName.ProductName[.SubProduct.ProductNumber].
228   // See http://msdn.microsoft.com/en-us/library/dd378459%28VS.85%29.aspx
229   DCHECK(lstrlen(app_id) < 64 && wcschr(app_id, L' ') == NULL);
230
231   return SetStringValueForPropertyStore(property_store,
232                                         PKEY_AppUserModel_ID,
233                                         app_id);
234 }
235
236 static const char16 kAutoRunKeyPath[] =
237     L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
238
239 bool AddCommandToAutoRun(HKEY root_key, const string16& name,
240                          const string16& command) {
241   base::win::RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE);
242   return (autorun_key.WriteValue(name.c_str(), command.c_str()) ==
243       ERROR_SUCCESS);
244 }
245
246 bool RemoveCommandFromAutoRun(HKEY root_key, const string16& name) {
247   base::win::RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_SET_VALUE);
248   return (autorun_key.DeleteValue(name.c_str()) == ERROR_SUCCESS);
249 }
250
251 bool ReadCommandFromAutoRun(HKEY root_key,
252                             const string16& name,
253                             string16* command) {
254   base::win::RegKey autorun_key(root_key, kAutoRunKeyPath, KEY_QUERY_VALUE);
255   return (autorun_key.ReadValue(name.c_str(), command) == ERROR_SUCCESS);
256 }
257
258 void SetShouldCrashOnProcessDetach(bool crash) {
259   g_crash_on_process_detach = crash;
260 }
261
262 bool ShouldCrashOnProcessDetach() {
263   return g_crash_on_process_detach;
264 }
265
266 void SetAbortBehaviorForCrashReporting() {
267   // Prevent CRT's abort code from prompting a dialog or trying to "report" it.
268   // Disabling the _CALL_REPORTFAULT behavior is important since otherwise it
269   // has the sideffect of clearing our exception filter, which means we
270   // don't get any crash.
271   _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
272
273   // Set a SIGABRT handler for good measure. We will crash even if the default
274   // is left in place, however this allows us to crash earlier. And it also
275   // lets us crash in response to code which might directly call raise(SIGABRT)
276   signal(SIGABRT, ForceCrashOnSigAbort);
277 }
278
279 bool IsTabletDevice() {
280   if (GetSystemMetrics(SM_MAXIMUMTOUCHES) == 0)
281     return false;
282
283   base::win::Version version = base::win::GetVersion();
284   if (version == base::win::VERSION_XP)
285     return (GetSystemMetrics(SM_TABLETPC) != 0);
286
287   // If the device is docked, the user is treating the device as a PC.
288   if (GetSystemMetrics(SM_SYSTEMDOCKED) != 0)
289     return false;
290
291   // PlatformRoleSlate was only added in Windows 8, but prior to Win8 it is
292   // still possible to check for a mobile power profile.
293   POWER_PLATFORM_ROLE role = PowerDeterminePlatformRole();
294   bool mobile_power_profile = (role == PlatformRoleMobile);
295   bool slate_power_profile = false;
296   if (version >= base::win::VERSION_WIN8)
297     slate_power_profile = (role == PlatformRoleSlate);
298
299   if (mobile_power_profile || slate_power_profile)
300     return (GetSystemMetrics(SM_CONVERTIBLESLATEMODE) == 0);
301
302   return false;
303 }
304
305 bool DisplayVirtualKeyboard() {
306   if (base::win::GetVersion() < base::win::VERSION_WIN8)
307     return false;
308
309   if (IsKeyboardPresentOnSlate())
310     return false;
311
312   static base::LazyInstance<string16>::Leaky osk_path =
313       LAZY_INSTANCE_INITIALIZER;
314
315   if (osk_path.Get().empty()) {
316     // We need to launch TabTip.exe from the location specified under the
317     // LocalServer32 key for the {{054AAE20-4BEA-4347-8A35-64A533254A9D}}
318     // CLSID.
319     // TabTip.exe is typically found at
320     // c:\program files\common files\microsoft shared\ink on English Windows.
321     // We don't want to launch TabTip.exe from
322     // c:\program files (x86)\common files\microsoft shared\ink. This path is
323     // normally found on 64 bit Windows.
324     base::win::RegKey key(HKEY_LOCAL_MACHINE,
325                           kWindows8OSKRegPath,
326                           KEY_READ | KEY_WOW64_64KEY);
327     DWORD osk_path_length = 1024;
328     if (key.ReadValue(NULL,
329                       WriteInto(&osk_path.Get(), osk_path_length),
330                       &osk_path_length,
331                       NULL) != ERROR_SUCCESS) {
332       DLOG(WARNING) << "Failed to read on screen keyboard path from registry";
333       return false;
334     }
335     size_t common_program_files_offset =
336         osk_path.Get().find(L"%CommonProgramFiles%");
337     // Typically the path to TabTip.exe read from the registry will start with
338     // %CommonProgramFiles% which needs to be replaced with the corrsponding
339     // expanded string.
340     // If the path does not begin with %CommonProgramFiles% we use it as is.
341     if (common_program_files_offset != string16::npos) {
342       // Preserve the beginning quote in the path.
343       osk_path.Get().erase(common_program_files_offset,
344                            wcslen(L"%CommonProgramFiles%"));
345       // The path read from the registry contains the %CommonProgramFiles%
346       // environment variable prefix. On 64 bit Windows the SHGetKnownFolderPath
347       // function returns the common program files path with the X86 suffix for
348       // the FOLDERID_ProgramFilesCommon value.
349       // To get the correct path to TabTip.exe we first read the environment
350       // variable CommonProgramW6432 which points to the desired common
351       // files path. Failing that we fallback to the SHGetKnownFolderPath API.
352
353       // We then replace the %CommonProgramFiles% value with the actual common
354       // files path found in the process.
355       string16 common_program_files_path;
356       scoped_ptr<wchar_t[]> common_program_files_wow6432;
357       DWORD buffer_size =
358           GetEnvironmentVariable(L"CommonProgramW6432", NULL, 0);
359       if (buffer_size) {
360         common_program_files_wow6432.reset(new wchar_t[buffer_size]);
361         GetEnvironmentVariable(L"CommonProgramW6432",
362                                common_program_files_wow6432.get(),
363                                buffer_size);
364         common_program_files_path = common_program_files_wow6432.get();
365         DCHECK(!common_program_files_path.empty());
366       } else {
367         base::win::ScopedCoMem<wchar_t> common_program_files;
368         if (FAILED(SHGetKnownFolderPath(FOLDERID_ProgramFilesCommon, 0, NULL,
369                                         &common_program_files))) {
370           return false;
371         }
372         common_program_files_path = common_program_files;
373       }
374
375       osk_path.Get().insert(1, common_program_files_path);
376     }
377   }
378
379   HINSTANCE ret = ::ShellExecuteW(NULL,
380                                   L"",
381                                   osk_path.Get().c_str(),
382                                   NULL,
383                                   NULL,
384                                   SW_SHOW);
385   return reinterpret_cast<int>(ret) > 32;
386 }
387
388 bool DismissVirtualKeyboard() {
389   if (base::win::GetVersion() < base::win::VERSION_WIN8)
390     return false;
391
392   // We dismiss the virtual keyboard by generating the ESC keystroke
393   // programmatically.
394   const wchar_t kOSKClassName[] = L"IPTip_Main_Window";
395   HWND osk = ::FindWindow(kOSKClassName, NULL);
396   if (::IsWindow(osk) && ::IsWindowEnabled(osk)) {
397     PostMessage(osk, WM_SYSCOMMAND, SC_CLOSE, 0);
398     return true;
399   }
400   return false;
401 }
402
403 typedef HWND (*MetroRootWindow) ();
404
405 enum DomainEnrollementState {UNKNOWN = -1, NOT_ENROLLED, ENROLLED};
406 static volatile long int g_domain_state = UNKNOWN;
407
408 bool IsEnrolledToDomain() {
409   // Doesn't make any sense to retry inside a user session because joining a
410   // domain will only kick in on a restart.
411   if (g_domain_state == UNKNOWN) {
412     LPWSTR domain;
413     NETSETUP_JOIN_STATUS join_status;
414     if(::NetGetJoinInformation(NULL, &domain, &join_status) != NERR_Success)
415       return false;
416     ::NetApiBufferFree(domain);
417     ::InterlockedCompareExchange(&g_domain_state,
418                                  join_status == ::NetSetupDomainName ?
419                                      ENROLLED : NOT_ENROLLED,
420                                  UNKNOWN);
421   }
422
423   return g_domain_state == ENROLLED;
424 }
425
426 void SetDomainStateForTesting(bool state) {
427   g_domain_state = state ? ENROLLED : NOT_ENROLLED;
428 }
429
430 bool MaybeHasSHA256Support() {
431   const base::win::OSInfo* os_info = base::win::OSInfo::GetInstance();
432
433   if (os_info->version() == base::win::VERSION_PRE_XP)
434     return false;  // Too old to have it and this OS is not supported anyway.
435
436   if (os_info->version() == base::win::VERSION_XP)
437     return os_info->service_pack().major >= 3;  // Windows XP SP3 has it.
438
439   // Assume it is missing in this case, although it may not be. This category
440   // includes Windows XP x64, and Windows Server, where a hotfix could be
441   // deployed.
442   if (os_info->version() == base::win::VERSION_SERVER_2003)
443     return false;
444
445   DCHECK(os_info->version() >= base::win::VERSION_VISTA);
446   return true;  // New enough to have SHA-256 support.
447 }
448
449 }  // namespace win
450 }  // namespace base
451
452 #ifdef _MSC_VER
453
454 // There are optimizer bugs in x86 VS2012 pre-Update 1.
455 #if _MSC_VER == 1700 && defined _M_IX86 && _MSC_FULL_VER < 170051106
456
457 #pragma message("Relevant defines:")
458 #define __STR2__(x) #x
459 #define __STR1__(x) __STR2__(x)
460 #define __PPOUT__(x) "#define " #x " " __STR1__(x)
461 #if defined(_M_IX86)
462   #pragma message(__PPOUT__(_M_IX86))
463 #endif
464 #if defined(_M_X64)
465   #pragma message(__PPOUT__(_M_X64))
466 #endif
467 #if defined(_MSC_FULL_VER)
468   #pragma message(__PPOUT__(_MSC_FULL_VER))
469 #endif
470
471 #pragma message("Visual Studio 2012 x86 must be updated to at least Update 1")
472 #error Must install Update 1 to Visual Studio 2012.
473 #endif
474
475 #endif  // _MSC_VER
476