chromeos: dbus: add Bluetooth properties support
[chromium-blink-merge.git] / chrome_frame / chrome_tab.cc
blob6e0373bac0e034be0edefd3b3515d4e7d2d30964
1 // Copyright (c) 2011 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.
5 // chrome_tab.cc : Implementation of DLL Exports.
7 // Need to include this before the ATL headers below.
8 #include "chrome_frame/chrome_tab.h"
10 #include <atlsecurity.h>
11 #include <objbase.h>
13 #include "base/at_exit.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/file_version_info.h"
17 #include "base/logging.h"
18 #include "base/logging_win.h"
19 #include "base/path_service.h"
20 #include "base/string16.h"
21 #include "base/string_number_conversions.h"
22 #include "base/string_piece.h"
23 #include "base/string_util.h"
24 #include "base/sys_string_conversions.h"
25 #include "base/win/registry.h"
26 #include "base/win/windows_version.h"
27 #include "chrome/common/chrome_constants.h"
28 #include "chrome/common/chrome_switches.h"
29 #include "chrome/installer/util/google_update_settings.h"
30 #include "chrome_frame/bho.h"
31 #include "chrome_frame/chrome_active_document.h"
32 #include "chrome_frame/chrome_frame_activex.h"
33 #include "chrome_frame/chrome_frame_automation.h"
34 #include "chrome_frame/chrome_frame_reporting.h"
35 #include "chrome_frame/chrome_launcher_utils.h"
36 #include "chrome_frame/chrome_protocol.h"
37 #include "chrome_frame/dll_redirector.h"
38 #include "chrome_frame/exception_barrier.h"
39 #include "chrome_frame/resource.h"
40 #include "chrome_frame/utils.h"
41 #include "googleurl/src/url_util.h"
42 #include "grit/chrome_frame_resources.h"
44 using base::win::RegKey;
46 namespace {
47 // This function has the side effect of initializing an unprotected
48 // vector pointer inside GoogleUrl. If this is called during DLL loading,
49 // it has the effect of avoiding an initialization race on that pointer.
50 // TODO(siggi): fix GoogleUrl.
51 void InitGoogleUrl() {
52 static const char kDummyUrl[] = "http://www.google.com";
54 url_util::IsStandard(kDummyUrl,
55 url_parse::MakeRange(0, arraysize(kDummyUrl)));
58 const wchar_t kInternetSettings[] =
59 L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
61 const wchar_t kProtocolHandlers[] =
62 L"Software\\Classes\\Protocols\\Handler";
64 const wchar_t kRunOnce[] =
65 L"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
67 const wchar_t kRunKeyName[] = L"ChromeFrameHelper";
69 const wchar_t kChromeFrameHelperExe[] = L"chrome_frame_helper.exe";
70 const wchar_t kChromeFrameHelperStartupArg[] = L"--startup";
72 // Window class and window names.
73 // TODO(robertshield): These and other constants need to be refactored into
74 // a common chrome_frame_constants.h|cc and built into a separate lib
75 // (either chrome_frame_utils or make another one).
76 const wchar_t kChromeFrameHelperWindowClassName[] =
77 L"ChromeFrameHelperWindowClass";
78 const wchar_t kChromeFrameHelperWindowName[] =
79 L"ChromeFrameHelperWindowName";
81 // {0562BFC3-2550-45b4-BD8E-A310583D3A6F}
82 static const GUID kChromeFrameProvider =
83 { 0x562bfc3, 0x2550, 0x45b4,
84 { 0xbd, 0x8e, 0xa3, 0x10, 0x58, 0x3d, 0x3a, 0x6f } };
86 const wchar_t kPostPlatformUAKey[] =
87 L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\"
88 L"User Agent\\Post Platform";
89 const wchar_t kChromeFramePrefix[] = L"chromeframe/";
91 // See comments in DllGetClassObject.
92 LPFNGETCLASSOBJECT g_dll_get_class_object_redir_ptr = NULL;
94 class ChromeTabModule : public CAtlDllModuleT<ChromeTabModule> {
95 public:
96 typedef CAtlDllModuleT<ChromeTabModule> ParentClass;
98 ChromeTabModule() : do_system_registration_(true) {}
100 DECLARE_LIBID(LIBID_ChromeTabLib)
101 DECLARE_REGISTRY_APPID_RESOURCEID(IDR_CHROMETAB,
102 "{FD9B1B31-F4D8-436A-8F4F-D3C2E36733D3}")
104 // Override to add our SYSTIME binary value to registry scripts.
105 // See chrome_frame_activex.rgs for usage.
106 virtual HRESULT AddCommonRGSReplacements(IRegistrarBase* registrar) throw() {
107 HRESULT hr = ParentClass::AddCommonRGSReplacements(registrar);
109 if (SUCCEEDED(hr)) {
110 SYSTEMTIME local_time;
111 ::GetSystemTime(&local_time);
112 std::string hex(base::HexEncode(&local_time, sizeof(local_time)));
113 base::StringPiece sp_hex(hex);
114 hr = registrar->AddReplacement(L"SYSTIME",
115 base::SysNativeMBToWide(sp_hex).c_str());
116 DCHECK(SUCCEEDED(hr));
119 if (SUCCEEDED(hr)) {
120 FilePath app_path =
121 chrome_launcher::GetChromeExecutablePath().DirName();
122 hr = registrar->AddReplacement(L"CHROME_APPPATH",
123 app_path.value().c_str());
124 DCHECK(SUCCEEDED(hr));
127 if (SUCCEEDED(hr)) {
128 hr = registrar->AddReplacement(L"CHROME_APPNAME",
129 chrome::kBrowserProcessExecutableName);
130 DCHECK(SUCCEEDED(hr));
132 // Fill in VERSION from the VERSIONINFO stored in the DLL's resources.
133 scoped_ptr<FileVersionInfo> module_version_info(
134 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
135 DCHECK(module_version_info != NULL);
136 std::wstring file_version(module_version_info->file_version());
137 hr = registrar->AddReplacement(L"VERSION", file_version.c_str());
138 DCHECK(SUCCEEDED(hr));
141 if (SUCCEEDED(hr)) {
142 // Add the directory of chrome_launcher.exe. This will be the same
143 // as the directory for the current DLL.
144 std::wstring module_dir;
145 FilePath module_path;
146 if (PathService::Get(base::FILE_MODULE, &module_path)) {
147 module_dir = module_path.DirName().value();
148 } else {
149 NOTREACHED();
151 hr = registrar->AddReplacement(L"CHROME_LAUNCHER_APPPATH",
152 module_dir.c_str());
153 DCHECK(SUCCEEDED(hr));
156 if (SUCCEEDED(hr)) {
157 // Add the filename of chrome_launcher.exe
158 hr = registrar->AddReplacement(L"CHROME_LAUNCHER_APPNAME",
159 chrome_launcher::kLauncherExeBaseName);
160 DCHECK(SUCCEEDED(hr));
163 if (SUCCEEDED(hr)) {
164 // Add the registry hive to use.
165 // Note: This is ugly as hell. I'd rather use the pMapEntries parameter
166 // to CAtlModule::UpdateRegistryFromResource, unfortunately we have a
167 // few components that are registered by calling their
168 // static T::UpdateRegistry() methods directly, which doesn't allow
169 // pMapEntries to be passed through :-(
170 if (do_system_registration_) {
171 hr = registrar->AddReplacement(L"HIVE", L"HKLM");
172 } else {
173 hr = registrar->AddReplacement(L"HIVE", L"HKCU");
175 DCHECK(SUCCEEDED(hr));
178 if (SUCCEEDED(hr)) {
179 // Add the Chrome Frame CLSID.
180 wchar_t cf_clsid[64];
181 StringFromGUID2(CLSID_ChromeFrame, &cf_clsid[0], arraysize(cf_clsid));
182 hr = registrar->AddReplacement(L"CHROME_FRAME_CLSID", &cf_clsid[0]);
185 return hr;
188 // See comments in AddCommonRGSReplacements
189 bool do_system_registration_;
192 ChromeTabModule _AtlModule;
194 base::AtExitManager* g_exit_manager = NULL;
197 HRESULT RefreshElevationPolicy() {
198 const wchar_t kIEFrameDll[] = L"ieframe.dll";
199 const char kIERefreshPolicy[] = "IERefreshElevationPolicy";
200 HRESULT hr = E_NOTIMPL;
202 // Stick an SEH in the chain to prevent the VEH from picking up on first
203 // chance exceptions caused by loading ieframe.dll. Use the vanilla
204 // ExceptionBarrier to report any exceptions that do make their way to us
205 // though.
206 ExceptionBarrier barrier;
208 HMODULE ieframe_module = LoadLibrary(kIEFrameDll);
209 if (ieframe_module) {
210 typedef HRESULT (__stdcall *IERefreshPolicy)();
211 IERefreshPolicy ie_refresh_policy = reinterpret_cast<IERefreshPolicy>(
212 GetProcAddress(ieframe_module, kIERefreshPolicy));
214 if (ie_refresh_policy) {
215 hr = ie_refresh_policy();
216 } else {
217 hr = HRESULT_FROM_WIN32(GetLastError());
220 FreeLibrary(ieframe_module);
221 } else {
222 hr = HRESULT_FROM_WIN32(GetLastError());
225 return hr;
228 // Experimental boot prefetch optimization for Chrome Frame
230 // If chrome is warmed up during a single reboot, it gets paged
231 // in for subsequent reboots and the cold startup times essentially
232 // look like warm times thereafter! The 'warm up' is done by
233 // setting up a 'RunOnce' key during DLLRegisterServer of
234 // npchrome_frame.dll.
236 // This works because chrome prefetch becomes part of boot
237 // prefetch file ntosboot-b00dfaad.pf and paged in on subsequent
238 // reboots. As long as the sytem does not undergo significant
239 // memory pressure those pages remain in memory and we get pretty
240 // amazing startup times, down to about 300 ms from 1200 ms
242 // The downside is:
243 // - Whether chrome frame is used or not, there's a read penalty
244 // (1200-300 =) 900 ms for every boot.
245 // - Heavy system memory usage after reboot will nullify the benefits
246 // but the user will still pay the cost.
247 // - Overall the time saved will always be less than total time spent
248 // paging in chrome
249 // - We are not sure when the chrome 'warm up' will age out from the
250 // boot prefetch file.
252 // The idea here is to try this out on chrome frame dev channel
253 // and see if it produces a significant drift in startup numbers.
254 HRESULT SetupRunOnce() {
255 HRESULT result = E_FAIL;
257 string16 channel_name;
258 if (base::win::GetVersion() < base::win::VERSION_VISTA &&
259 GoogleUpdateSettings::GetChromeChannelAndModifiers(true, &channel_name)) {
260 std::transform(channel_name.begin(), channel_name.end(),
261 channel_name.begin(), tolower);
262 // Use this only for the dev channel.
263 if (channel_name.find(L"dev") != string16::npos) {
264 HKEY hive = HKEY_CURRENT_USER;
265 if (IsSystemProcess()) {
266 // For system installs, our updates will be running as SYSTEM which
267 // makes writing to a RunOnce key under HKCU not so terribly useful.
268 hive = HKEY_LOCAL_MACHINE;
271 RegKey run_once;
272 LONG ret = run_once.Create(hive, kRunOnce, KEY_READ | KEY_WRITE);
273 if (ret == ERROR_SUCCESS) {
274 CommandLine run_once_cmd(chrome_launcher::GetChromeExecutablePath());
275 run_once_cmd.AppendSwitchASCII(switches::kAutomationClientChannelID,
276 "0");
277 run_once_cmd.AppendSwitch(switches::kChromeFrame);
278 ret = run_once.WriteValue(L"A",
279 run_once_cmd.GetCommandLineString().c_str());
281 result = HRESULT_FROM_WIN32(ret);
282 } else {
283 result = S_FALSE;
285 } else {
286 // We're on a non-XP version of Windows or on a stable channel. Nothing
287 // needs doing.
288 result = S_FALSE;
291 return result;
294 // Helper method called for user-level installs where we don't have admin
295 // permissions. Starts up the long running process and registers it to get it
296 // started at next boot.
297 HRESULT SetupUserLevelHelper() {
298 HRESULT hr = S_OK;
300 // Remove existing run-at-startup entry.
301 base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER, kRunKeyName);
303 // Build the chrome_frame_helper command line.
304 FilePath module_path;
305 FilePath helper_path;
306 if (PathService::Get(base::FILE_MODULE, &module_path)) {
307 module_path = module_path.DirName();
308 helper_path = module_path.Append(kChromeFrameHelperExe);
309 if (!file_util::PathExists(helper_path)) {
310 // If we can't find the helper in the current directory, try looking
311 // one up (this is the layout in the build output folder).
312 module_path = module_path.DirName();
313 helper_path = module_path.Append(kChromeFrameHelperExe);
314 DCHECK(file_util::PathExists(helper_path)) <<
315 "Could not find chrome_frame_helper.exe.";
318 // Find window handle of existing instance.
319 HWND old_window = FindWindow(kChromeFrameHelperWindowClassName,
320 kChromeFrameHelperWindowName);
322 if (file_util::PathExists(helper_path)) {
323 std::wstring helper_path_cmd(L"\"");
324 helper_path_cmd += helper_path.value();
325 helper_path_cmd += L"\" ";
326 helper_path_cmd += kChromeFrameHelperStartupArg;
328 // Add new run-at-startup entry.
329 if (!base::win::AddCommandToAutoRun(HKEY_CURRENT_USER, kRunKeyName,
330 helper_path_cmd)) {
331 hr = E_FAIL;
332 LOG(ERROR) << "Could not add helper process to auto run key.";
335 // Start new instance.
336 base::LaunchOptions options;
337 options.start_hidden = true;
338 bool launched = base::LaunchProcess(helper_path.value(), options, NULL);
339 if (!launched) {
340 hr = E_FAIL;
341 PLOG(DFATAL) << "Could not launch helper process.";
344 // Kill old instance using window handle.
345 if (IsWindow(old_window)) {
346 BOOL result = PostMessage(old_window, WM_CLOSE, 0, 0);
347 if (!result) {
348 PLOG(ERROR) << "Failed to post close message to old helper process: ";
351 } else {
352 hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
354 } else {
355 hr = E_UNEXPECTED;
356 NOTREACHED();
359 return hr;
362 // To delete the user agent, set value to NULL.
363 // The is_system parameter indicates whether this is a per machine or a per
364 // user installation.
365 HRESULT SetChromeFrameUA(bool is_system, const wchar_t* value) {
366 HRESULT hr = E_FAIL;
367 HKEY parent_hive = is_system ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
369 RegKey ua_key;
370 LONG reg_result = ua_key.Create(parent_hive, kPostPlatformUAKey,
371 KEY_READ | KEY_WRITE);
372 if (reg_result == ERROR_SUCCESS) {
373 // Make sure that we unregister ChromeFrame UA strings registered previously
374 wchar_t value_name[MAX_PATH + 1] = {};
375 wchar_t value_data[MAX_PATH + 1] = {};
377 DWORD value_index = 0;
378 while (value_index < ua_key.GetValueCount()) {
379 DWORD name_size = arraysize(value_name);
380 DWORD value_size = arraysize(value_data);
381 DWORD type = 0;
382 LRESULT ret = ::RegEnumValue(ua_key.Handle(), value_index, value_name,
383 &name_size, NULL, &type,
384 reinterpret_cast<BYTE*>(value_data),
385 &value_size);
386 if (ret == ERROR_SUCCESS) {
387 if (StartsWith(value_name, kChromeFramePrefix, false)) {
388 ua_key.DeleteValue(value_name);
389 } else {
390 ++value_index;
392 } else {
393 break;
397 std::wstring chrome_frame_ua_value_name = kChromeFramePrefix;
398 chrome_frame_ua_value_name += GetCurrentModuleVersion();
399 if (value) {
400 ua_key.WriteValue(chrome_frame_ua_value_name.c_str(), value);
402 hr = S_OK;
403 } else {
404 DLOG(ERROR) << __FUNCTION__ << ": " << kPostPlatformUAKey
405 << ", error code = " << reg_result;
406 hr = HRESULT_FROM_WIN32(reg_result);
408 return hr;
411 class SecurityDescBackup {
412 public:
413 explicit SecurityDescBackup(const std::wstring& backup_key)
414 : backup_key_name_(backup_key) {}
415 ~SecurityDescBackup() {}
417 // Save given security descriptor to the backup key.
418 bool SaveSecurity(const CSecurityDesc& sd) {
419 CString str;
420 if (!sd.ToString(&str))
421 return false;
423 RegKey backup_key(HKEY_LOCAL_MACHINE, backup_key_name_.c_str(),
424 KEY_READ | KEY_WRITE);
425 if (backup_key.Valid()) {
426 return backup_key.WriteValue(NULL, str.GetString()) == ERROR_SUCCESS;
429 return false;
432 // Restore security descriptor from backup key to given key name.
433 bool RestoreSecurity(const wchar_t* key_name) {
434 std::wstring sddl;
435 if (!ReadBackupKey(&sddl))
436 return false;
438 // Create security descriptor from string.
439 CSecurityDesc sd;
440 if (!sd.FromString(sddl.c_str()))
441 return false;
443 bool result = true;
444 // Restore DACL and Owner of the key from saved security descriptor.
445 CDacl dacl;
446 CSid owner;
447 sd.GetDacl(&dacl);
448 sd.GetOwner(&owner);
450 DWORD error = ::SetNamedSecurityInfo(const_cast<wchar_t*>(key_name),
451 SE_REGISTRY_KEY, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
452 const_cast<SID*>(owner.GetPSID()), NULL,
453 const_cast<ACL*>(dacl.GetPACL()), NULL);
455 DeleteBackupKey();
456 return (error == ERROR_SUCCESS);
459 private:
460 // Read SDDL string from backup key
461 bool ReadBackupKey(std::wstring* sddl) {
462 RegKey backup_key(HKEY_LOCAL_MACHINE, backup_key_name_.c_str(), KEY_READ);
463 if (!backup_key.Valid())
464 return false;
466 DWORD len = 0;
467 DWORD reg_type = REG_NONE;
468 if (backup_key.ReadValue(NULL, NULL, &len, &reg_type) != ERROR_SUCCESS)
469 return false;
470 DCHECK_EQ(0u, len % sizeof(wchar_t));
472 if ((len == 0) || (reg_type != REG_SZ))
473 return false;
475 size_t wchar_count = 1 + len / sizeof(wchar_t);
476 if (backup_key.ReadValue(NULL, WriteInto(sddl, wchar_count), &len,
477 &reg_type) != ERROR_SUCCESS) {
478 return false;
481 return true;
484 void DeleteBackupKey() {
485 ::RegDeleteKey(HKEY_LOCAL_MACHINE, backup_key_name_.c_str());
488 std::wstring backup_key_name_;
491 struct TokenWithPrivileges {
492 TokenWithPrivileges() {
493 token_.GetEffectiveToken(TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY);
494 token_.GetUser(&user_);
497 ~TokenWithPrivileges() {
498 token_.EnableDisablePrivileges(take_ownership_);
499 token_.EnableDisablePrivileges(restore_);
502 bool EnablePrivileges() {
503 if (take_ownership_.GetCount() == 0)
504 if (!token_.EnablePrivilege(L"SeTakeOwnershipPrivilege",
505 &take_ownership_))
506 return false;
508 if (restore_.GetCount() == 0)
509 if (!token_.EnablePrivilege(L"SeRestorePrivilege", &restore_))
510 return false;
512 return true;
515 const CSid& GetUser() const {
516 return user_;
519 private:
520 CAccessToken token_;
521 CTokenPrivileges take_ownership_;
522 CTokenPrivileges restore_;
523 CSid user_;
526 HRESULT SetOrDeleteMimeHandlerKey(bool set, HKEY root_key) {
527 std::wstring key_name = kInternetSettings;
528 key_name.append(L"\\Secure Mime Handlers");
529 RegKey key(root_key, key_name.c_str(), KEY_READ | KEY_WRITE);
530 if (!key.Valid())
531 return false;
533 LONG result1 = ERROR_SUCCESS;
534 LONG result2 = ERROR_SUCCESS;
535 if (set) {
536 result1 = key.WriteValue(L"ChromeTab.ChromeActiveDocument", 1);
537 result2 = key.WriteValue(L"ChromeTab.ChromeActiveDocument.1", 1);
538 } else {
539 result1 = key.DeleteValue(L"ChromeTab.ChromeActiveDocument");
540 result2 = key.DeleteValue(L"ChromeTab.ChromeActiveDocument.1");
543 return result1 != ERROR_SUCCESS ? HRESULT_FROM_WIN32(result1) :
544 HRESULT_FROM_WIN32(result2);
547 // Chrome Frame registration functions.
548 //-----------------------------------------------------------------------------
549 HRESULT RegisterSecuredMimeHandler(bool enable, bool is_system) {
550 if (!is_system) {
551 return SetOrDeleteMimeHandlerKey(enable, HKEY_CURRENT_USER);
552 } else if (base::win::GetVersion() < base::win::VERSION_VISTA) {
553 return SetOrDeleteMimeHandlerKey(enable, HKEY_LOCAL_MACHINE);
556 std::wstring mime_key = kInternetSettings;
557 mime_key.append(L"\\Secure Mime Handlers");
558 std::wstring backup_key = kInternetSettings;
559 backup_key.append(L"\\__backup_SMH__");
560 std::wstring object_name = L"MACHINE\\";
561 object_name.append(mime_key);
563 TokenWithPrivileges token_;
564 if (!token_.EnablePrivileges())
565 return E_ACCESSDENIED;
567 // If there is a backup key - something bad happened; try to restore
568 // security on "Secure Mime Handlers" from the backup.
569 SecurityDescBackup backup(backup_key);
570 backup.RestoreSecurity(object_name.c_str());
572 // Read old security descriptor of the Mime key first.
573 CSecurityDesc sd;
574 if (!AtlGetSecurityDescriptor(object_name.c_str(), SE_REGISTRY_KEY, &sd)) {
575 return E_FAIL;
578 backup.SaveSecurity(sd);
579 HRESULT hr = E_FAIL;
580 // set new owner
581 if (AtlSetOwnerSid(object_name.c_str(), SE_REGISTRY_KEY, token_.GetUser())) {
582 // set new dacl
583 CDacl new_dacl;
584 sd.GetDacl(&new_dacl);
585 new_dacl.AddAllowedAce(token_.GetUser(), GENERIC_WRITE | GENERIC_READ);
586 if (AtlSetDacl(object_name.c_str(), SE_REGISTRY_KEY, new_dacl)) {
587 hr = SetOrDeleteMimeHandlerKey(enable, HKEY_LOCAL_MACHINE);
591 backup.RestoreSecurity(object_name.c_str());
592 return hr;
595 HRESULT RegisterActiveDoc(bool reg, bool is_system) {
596 // We have to call the static T::UpdateRegistry function instead of
597 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEDOC, reg)
598 // because there is specific OLEMISC replacement.
599 return ChromeActiveDocument::UpdateRegistry(reg);
602 HRESULT RegisterActiveX(bool reg, bool is_system) {
603 // We have to call the static T::UpdateRegistry function instead of
604 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEX, reg)
605 // because there is specific OLEMISC replacement.
606 return ChromeFrameActivex::UpdateRegistry(reg);
609 HRESULT RegisterElevationPolicy(bool reg, bool is_system) {
610 HRESULT hr = S_OK;
611 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
612 // Register the elevation policy. This must succeed for Chrome Frame to
613 // be able launch Chrome when running in low-integrity IE.
614 hr = _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ELEVATION, reg);
615 if (SUCCEEDED(hr)) {
616 // Ignore failures since old versions of IE 7 (e.g., 7.0.6000.16386, which
617 // shipped with Vista RTM) do not export IERefreshElevationPolicy.
618 RefreshElevationPolicy();
621 return hr;
624 HRESULT RegisterProtocol(bool reg, bool is_system) {
625 return _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEPROTOCOL, reg);
628 HRESULT RegisterBhoClsid(bool reg, bool is_system) {
629 return Bho::UpdateRegistry(reg);
632 HRESULT RegisterBhoIE(bool reg, bool is_system) {
633 if (is_system) {
634 return _AtlModule.UpdateRegistryFromResourceS(IDR_REGISTER_BHO, reg);
635 } else {
636 if (reg) {
637 // Setup the long running process:
638 return SetupUserLevelHelper();
639 } else {
640 // Unschedule the user-level helper. Note that we don't kill it here
641 // so that during updates we don't have a time window with no running
642 // helper. Uninstalls and updates will explicitly kill the helper from
643 // within the installer. Unregister existing run-at-startup entry.
644 return base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER,
645 kRunKeyName) ? S_OK : E_FAIL;
650 HRESULT RegisterTypeLib(bool reg, bool is_system) {
651 if (reg && !is_system) {
652 // Enables the RegisterTypeLib Function function to override default
653 // registry mappings under Windows Vista Service Pack 1 (SP1),
654 // Windows Server 2008, and later operating system versions
655 typedef void (WINAPI* OaEnablePerUserTypeLibReg)(void);
656 OaEnablePerUserTypeLibReg per_user_typelib_func =
657 reinterpret_cast<OaEnablePerUserTypeLibReg>(
658 GetProcAddress(GetModuleHandle(L"oleaut32.dll"),
659 "OaEnablePerUserTLibRegistration"));
660 if (per_user_typelib_func) {
661 (*per_user_typelib_func)();
664 return reg ?
665 UtilRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
666 NULL, !is_system) :
667 UtilUnRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
668 NULL, !is_system);
671 HRESULT RegisterLegacyNPAPICleanup(bool reg, bool is_system) {
672 if (!reg) {
673 _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_NPAPI, reg);
674 UtilRemovePersistentNPAPIMarker();
676 // Ignore failures.
677 return S_OK;
680 HRESULT RegisterAppId(bool reg, bool is_system) {
681 return _AtlModule.UpdateRegistryAppId(reg);
684 HRESULT RegisterUserAgent(bool reg, bool is_system) {
685 if (reg) {
686 return SetChromeFrameUA(is_system, L"1");
687 } else {
688 return SetChromeFrameUA(is_system, NULL);
692 enum RegistrationStepId {
693 kStepSecuredMimeHandler = 0,
694 kStepActiveDoc = 1,
695 kStepActiveX = 2,
696 kStepElevationPolicy = 3,
697 kStepProtocol = 4,
698 kStepBhoClsid = 5,
699 kStepBhoRegistration = 6,
700 kStepRegisterTypeLib = 7,
701 kStepNpapiCleanup = 8,
702 kStepAppId = 9,
703 kStepUserAgent = 10,
704 kStepEnd = 11
707 enum RegistrationFlags {
708 ACTIVEX = 0x0001,
709 ACTIVEDOC = 0x0002,
710 GCF_PROTOCOL = 0x0004,
711 BHO_CLSID = 0x0008,
712 BHO_REGISTRATION = 0x0010,
713 TYPELIB = 0x0020,
715 ALL = 0xFFFF
718 // Mux the failure step into the hresult. We take only the first four bits
719 // and stick those into the top four bits of the facility code. We also set the
720 // Customer bit to be polite. Graphically, we write our error code to the
721 // bits marked with ^:
722 // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
723 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
724 // +---+-+-+-----------------------+-------------------------------+
725 // |Sev|C|R| Facility | Code |
726 // +---+-+-+-----------------------+-------------------------------+
727 // ^ ^ ^ ^ ^
728 // See http://msdn.microsoft.com/en-us/library/cc231198(PROT.10).aspx for
729 // more details on HRESULTS.
731 // The resulting error can be extracted by:
732 // error_code = (fiddled_hr & 0x07800000) >> 23
733 HRESULT MuxErrorIntoHRESULT(HRESULT hr, int error_code) {
734 DCHECK_GE(error_code, 0);
735 DCHECK_LT(error_code, kStepEnd);
736 COMPILE_ASSERT(kStepEnd <= 0xF, update_error_muxing_too_many_steps);
738 // Check that our four desired bits are clear.
739 // 0xF87FFFFF == 11111000011111111111111111111111
740 DCHECK_EQ(static_cast<HRESULT>(hr & 0xF87FFFFF), hr);
742 HRESULT fiddled_hr = ((error_code & 0xF) << 23) | hr;
743 fiddled_hr |= 1 << 29; // Set the customer bit.
745 return fiddled_hr;
748 HRESULT CustomRegistration(uint16 reg_flags, bool reg, bool is_system) {
749 if (reg && (reg_flags & (ACTIVEDOC | ACTIVEX)))
750 reg_flags |= (TYPELIB | GCF_PROTOCOL);
752 // Set the flag that gets checked in AddCommonRGSReplacements before doing
753 // registration work.
754 _AtlModule.do_system_registration_ = is_system;
756 typedef HRESULT (*RegistrationFn)(bool reg, bool is_system);
757 struct RegistrationStep {
758 RegistrationStepId id;
759 uint16 condition;
760 RegistrationFn func;
762 static const RegistrationStep registration_steps[] = {
763 { kStepSecuredMimeHandler, ACTIVEDOC, &RegisterSecuredMimeHandler },
764 { kStepActiveDoc, ACTIVEDOC, &RegisterActiveDoc },
765 { kStepActiveX, ACTIVEX, &RegisterActiveX },
766 { kStepElevationPolicy, (ACTIVEDOC | ACTIVEX), &RegisterElevationPolicy },
767 { kStepProtocol, GCF_PROTOCOL, &RegisterProtocol },
768 { kStepBhoClsid, BHO_CLSID, &RegisterBhoClsid },
769 { kStepBhoRegistration, BHO_REGISTRATION, &RegisterBhoIE },
770 { kStepRegisterTypeLib, TYPELIB, &RegisterTypeLib },
771 { kStepNpapiCleanup, ALL, &RegisterLegacyNPAPICleanup },
772 { kStepAppId, ALL, &RegisterAppId },
773 { kStepUserAgent, ALL, &RegisterUserAgent }
776 HRESULT hr = S_OK;
778 bool rollback = false;
779 int failure_step = 0;
780 HRESULT step_hr = S_OK;
781 for (int step = 0; step < arraysize(registration_steps); ++step) {
782 if ((reg_flags & registration_steps[step].condition) != 0) {
783 step_hr = registration_steps[step].func(reg, is_system);
784 if (FAILED(step_hr)) {
785 // Store only the first failing HRESULT with the step value muxed in.
786 if (hr == S_OK) {
787 hr = MuxErrorIntoHRESULT(step_hr, step);
790 // On registration if a step fails, we abort and rollback.
791 if (reg) {
792 rollback = true;
793 failure_step = step;
794 break;
800 if (rollback) {
801 DCHECK(reg);
802 // Rollback the failing action and all preceding ones.
803 for (int step = failure_step; step >= 0; --step) {
804 registration_steps[step].func(!reg, is_system);
808 return hr;
811 } // namespace
813 // DLL Entry Point
814 extern "C" BOOL WINAPI DllMain(HINSTANCE instance,
815 DWORD reason,
816 LPVOID reserved) {
817 UNREFERENCED_PARAMETER(instance);
818 if (reason == DLL_PROCESS_ATTACH) {
819 #ifndef NDEBUG
820 // Silence traces from the ATL registrar to reduce the log noise.
821 ATL::CTrace::s_trace.ChangeCategory(atlTraceRegistrar, 0,
822 ATLTRACESTATUS_DISABLED);
823 #endif
824 InitGoogleUrl();
826 g_exit_manager = new base::AtExitManager();
827 CommandLine::Init(0, NULL);
828 InitializeCrashReporting();
829 logging::InitLogging(
830 NULL,
831 logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
832 logging::LOCK_LOG_FILE,
833 logging::DELETE_OLD_LOG_FILE,
834 logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
836 DllRedirector* dll_redirector = DllRedirector::GetInstance();
837 DCHECK(dll_redirector);
839 if (!dll_redirector->RegisterAsFirstCFModule()) {
840 // Someone else was here first, try and get a pointer to their
841 // DllGetClassObject export:
842 g_dll_get_class_object_redir_ptr =
843 dll_redirector->GetDllGetClassObjectPtr();
844 DCHECK(g_dll_get_class_object_redir_ptr != NULL)
845 << "Found CF module with no DllGetClassObject export.";
848 // Enable ETW logging.
849 logging::LogEventProvider::Initialize(kChromeFrameProvider);
850 } else if (reason == DLL_PROCESS_DETACH) {
851 DllRedirector* dll_redirector = DllRedirector::GetInstance();
852 DCHECK(dll_redirector);
854 dll_redirector->UnregisterAsFirstCFModule();
855 g_patch_helper.UnpatchIfNeeded();
856 delete g_exit_manager;
857 g_exit_manager = NULL;
858 ShutdownCrashReporting();
860 return _AtlModule.DllMain(reason, reserved);
863 // Used to determine whether the DLL can be unloaded by OLE
864 STDAPI DllCanUnloadNow() {
865 return _AtlModule.DllCanUnloadNow();
868 // Returns a class factory to create an object of the requested type
869 STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) {
870 // If we found another module present when we were loaded, then delegate to
871 // that:
872 if (g_dll_get_class_object_redir_ptr) {
873 return g_dll_get_class_object_redir_ptr(rclsid, riid, ppv);
876 // Enable sniffing and switching only if asked for BHO
877 // (we use BHO to get loaded in IE).
878 if (rclsid == CLSID_ChromeFrameBHO) {
879 g_patch_helper.InitializeAndPatchProtocolsIfNeeded();
882 return _AtlModule.DllGetClassObject(rclsid, riid, ppv);
885 // DllRegisterServer - Adds entries to the system registry
886 STDAPI DllRegisterServer() {
887 uint16 flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
888 BHO_CLSID | BHO_REGISTRATION;
890 HRESULT hr = CustomRegistration(flags, true, true);
891 if (SUCCEEDED(hr)) {
892 SetupRunOnce();
895 return hr;
898 // DllUnregisterServer - Removes entries from the system registry
899 STDAPI DllUnregisterServer() {
900 HRESULT hr = CustomRegistration(ALL, false, true);
901 return hr;
904 // DllRegisterUserServer - Adds entries to the HKCU hive in the registry.
905 STDAPI DllRegisterUserServer() {
906 UINT flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
907 BHO_CLSID | BHO_REGISTRATION;
909 HRESULT hr = CustomRegistration(flags, TRUE, false);
910 if (SUCCEEDED(hr)) {
911 SetupRunOnce();
914 return hr;
917 // DllUnregisterUserServer - Removes entries from the HKCU hive in the registry.
918 STDAPI DllUnregisterUserServer() {
919 HRESULT hr = CustomRegistration(ALL, FALSE, false);
920 return hr;
923 // Object entries go here instead of with each object, so that we can move
924 // the objects to a lib. Also reduces magic.
925 OBJECT_ENTRY_AUTO(CLSID_ChromeFrameBHO, Bho)
926 OBJECT_ENTRY_AUTO(__uuidof(ChromeActiveDocument), ChromeActiveDocument)
927 OBJECT_ENTRY_AUTO(__uuidof(ChromeFrame), ChromeFrameActivex)
928 OBJECT_ENTRY_AUTO(__uuidof(ChromeProtocol), ChromeProtocol)