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.
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>
13 #include "base/at_exit.h"
14 #include "base/basictypes.h"
15 #include "base/command_line.h"
16 #include "base/file_util.h"
17 #include "base/file_version_info.h"
18 #include "base/logging.h"
19 #include "base/logging_win.h"
20 #include "base/path_service.h"
21 #include "base/string16.h"
22 #include "base/string_number_conversions.h"
23 #include "base/string_util.h"
24 #include "base/strings/string_piece.h"
25 #include "base/strings/sys_string_conversions.h"
26 #include "base/utf_string_conversions.h"
27 #include "base/win/registry.h"
28 #include "base/win/windows_version.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/common/chrome_switches.h"
31 #include "chrome/common/metrics/entropy_provider.h"
32 #include "chrome/installer/util/google_update_settings.h"
33 #include "chrome_frame/bho.h"
34 #include "chrome_frame/chrome_active_document.h"
35 #include "chrome_frame/chrome_frame_activex.h"
36 #include "chrome_frame/chrome_frame_automation.h"
37 #include "chrome_frame/chrome_frame_reporting.h"
38 #include "chrome_frame/chrome_launcher_utils.h"
39 #include "chrome_frame/chrome_protocol.h"
40 #include "chrome_frame/dll_redirector.h"
41 #include "chrome_frame/exception_barrier.h"
42 #include "chrome_frame/pin_module.h"
43 #include "chrome_frame/resource.h"
44 #include "chrome_frame/utils.h"
45 #include "googleurl/src/url_util.h"
46 #include "grit/chrome_frame_resources.h"
48 using base::win::RegKey
;
52 const wchar_t kInternetSettings
[] =
53 L
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
55 const wchar_t kProtocolHandlers
[] =
56 L
"Software\\Classes\\Protocols\\Handler";
58 const wchar_t kRunOnce
[] =
59 L
"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
61 const wchar_t kRunKeyName
[] = L
"ChromeFrameHelper";
63 const wchar_t kChromeFrameHelperExe
[] = L
"chrome_frame_helper.exe";
64 const wchar_t kChromeFrameHelperStartupArg
[] = L
"--startup";
66 // Window class and window names.
67 // TODO(robertshield): These and other constants need to be refactored into
68 // a common chrome_frame_constants.h|cc and built into a separate lib
69 // (either chrome_frame_utils or make another one).
70 const wchar_t kChromeFrameHelperWindowClassName
[] =
71 L
"ChromeFrameHelperWindowClass";
72 const wchar_t kChromeFrameHelperWindowName
[] =
73 L
"ChromeFrameHelperWindowName";
75 // {0562BFC3-2550-45b4-BD8E-A310583D3A6F}
76 const GUID kChromeFrameProvider
=
77 { 0x562bfc3, 0x2550, 0x45b4,
78 { 0xbd, 0x8e, 0xa3, 0x10, 0x58, 0x3d, 0x3a, 0x6f } };
80 const wchar_t kPostPlatformUAKey
[] =
81 L
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\"
82 L
"User Agent\\Post Platform";
83 const wchar_t kChromeFramePrefix
[] = L
"chromeframe/";
85 // See comments in DllGetClassObject.
86 LPFNGETCLASSOBJECT g_dll_get_class_object_redir_ptr
= NULL
;
88 // This function has the side effect of initializing an unprotected
89 // vector pointer inside GoogleUrl. If this is called during DLL loading,
90 // it has the effect of avoiding an initialization race on that pointer.
91 // TODO(siggi): fix GoogleUrl.
92 void InitGoogleUrl() {
93 static const char kDummyUrl
[] = "http://www.google.com";
95 url_util::IsStandard(kDummyUrl
,
96 url_parse::MakeRange(0, arraysize(kDummyUrl
)));
99 class ChromeTabModule
: public CAtlDllModuleT
<ChromeTabModule
> {
101 typedef CAtlDllModuleT
<ChromeTabModule
> ParentClass
;
103 ChromeTabModule() : do_system_registration_(true), crash_reporting_(NULL
) {}
105 DECLARE_LIBID(LIBID_ChromeTabLib
)
106 DECLARE_REGISTRY_APPID_RESOURCEID(IDR_CHROMETAB
,
107 "{FD9B1B31-F4D8-436A-8F4F-D3C2E36733D3}")
109 // Override to add our SYSTIME binary value to registry scripts.
110 // See chrome_frame_activex.rgs for usage.
111 virtual HRESULT
AddCommonRGSReplacements(IRegistrarBase
* registrar
) throw() {
112 HRESULT hr
= ParentClass::AddCommonRGSReplacements(registrar
);
115 SYSTEMTIME local_time
;
116 ::GetSystemTime(&local_time
);
117 std::string
hex(base::HexEncode(&local_time
, sizeof(local_time
)));
118 base::StringPiece
sp_hex(hex
);
119 hr
= registrar
->AddReplacement(L
"SYSTIME",
120 base::SysNativeMBToWide(sp_hex
).c_str());
121 DCHECK(SUCCEEDED(hr
));
125 base::FilePath app_path
=
126 chrome_launcher::GetChromeExecutablePath().DirName();
127 hr
= registrar
->AddReplacement(L
"CHROME_APPPATH",
128 app_path
.value().c_str());
129 DCHECK(SUCCEEDED(hr
));
133 hr
= registrar
->AddReplacement(L
"CHROME_APPNAME",
134 chrome::kBrowserProcessExecutableName
);
135 DCHECK(SUCCEEDED(hr
));
137 // Fill in VERSION from the VERSIONINFO stored in the DLL's resources.
138 scoped_ptr
<FileVersionInfo
> module_version_info(
139 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
140 DCHECK(module_version_info
!= NULL
);
141 std::wstring
file_version(module_version_info
->file_version());
142 hr
= registrar
->AddReplacement(L
"VERSION", file_version
.c_str());
143 DCHECK(SUCCEEDED(hr
));
147 // Add the directory of chrome_launcher.exe. This will be the same
148 // as the directory for the current DLL.
149 std::wstring module_dir
;
150 base::FilePath module_path
;
151 if (PathService::Get(base::FILE_MODULE
, &module_path
)) {
152 module_dir
= module_path
.DirName().value();
156 hr
= registrar
->AddReplacement(L
"CHROME_LAUNCHER_APPPATH",
158 DCHECK(SUCCEEDED(hr
));
162 // Add the filename of chrome_launcher.exe
163 hr
= registrar
->AddReplacement(L
"CHROME_LAUNCHER_APPNAME",
164 chrome_launcher::kLauncherExeBaseName
);
165 DCHECK(SUCCEEDED(hr
));
169 // Add the registry hive to use.
170 // Note: This is ugly as hell. I'd rather use the pMapEntries parameter
171 // to CAtlModule::UpdateRegistryFromResource, unfortunately we have a
172 // few components that are registered by calling their
173 // static T::UpdateRegistry() methods directly, which doesn't allow
174 // pMapEntries to be passed through :-(
175 if (do_system_registration_
) {
176 hr
= registrar
->AddReplacement(L
"HIVE", L
"HKLM");
178 hr
= registrar
->AddReplacement(L
"HIVE", L
"HKCU");
180 DCHECK(SUCCEEDED(hr
));
184 // Add the Chrome Frame CLSID.
185 wchar_t cf_clsid
[64];
186 StringFromGUID2(CLSID_ChromeFrame
, &cf_clsid
[0], arraysize(cf_clsid
));
187 hr
= registrar
->AddReplacement(L
"CHROME_FRAME_CLSID", &cf_clsid
[0]);
193 // The module is "locked" when an object takes a reference on it. The first
194 // time it is locked, take a reference on crash reporting to bind its lifetime
196 virtual LONG
Lock() throw() {
197 LONG result
= ParentClass::Lock();
199 DCHECK_EQ(crash_reporting_
,
200 static_cast<chrome_frame::ScopedCrashReporting
*>(NULL
));
201 crash_reporting_
= new chrome_frame::ScopedCrashReporting();
206 // The module is "unlocked" when an object that had a reference on it is
207 // destroyed. The last time it is unlocked, release the reference on crash
209 virtual LONG
Unlock() throw() {
210 LONG result
= ParentClass::Unlock();
212 DCHECK_NE(crash_reporting_
,
213 static_cast<chrome_frame::ScopedCrashReporting
*>(NULL
));
214 delete crash_reporting_
;
215 crash_reporting_
= NULL
;
220 // See comments in AddCommonRGSReplacements
221 bool do_system_registration_
;
224 // A scoper created when the module is initially locked and destroyed when it
225 // is finally unlocked. This is not a scoped_ptr since that could cause
226 // reporting to shut down at exit, which would lead to problems with the
228 chrome_frame::ScopedCrashReporting
* crash_reporting_
;
231 ChromeTabModule _AtlModule
;
233 base::AtExitManager
* g_exit_manager
= NULL
;
235 HRESULT
RefreshElevationPolicy() {
236 const wchar_t kIEFrameDll
[] = L
"ieframe.dll";
237 const char kIERefreshPolicy
[] = "IERefreshElevationPolicy";
238 HRESULT hr
= E_NOTIMPL
;
240 // Stick an SEH in the chain to prevent the VEH from picking up on first
241 // chance exceptions caused by loading ieframe.dll. Use the vanilla
242 // ExceptionBarrier to report any exceptions that do make their way to us
244 ExceptionBarrier barrier
;
246 HMODULE ieframe_module
= LoadLibrary(kIEFrameDll
);
247 if (ieframe_module
) {
248 typedef HRESULT (__stdcall
*IERefreshPolicy
)();
249 IERefreshPolicy ie_refresh_policy
= reinterpret_cast<IERefreshPolicy
>(
250 GetProcAddress(ieframe_module
, kIERefreshPolicy
));
252 if (ie_refresh_policy
) {
253 hr
= ie_refresh_policy();
255 hr
= HRESULT_FROM_WIN32(GetLastError());
258 FreeLibrary(ieframe_module
);
260 hr
= HRESULT_FROM_WIN32(GetLastError());
266 // Experimental boot prefetch optimization for Chrome Frame
268 // If chrome is warmed up during a single reboot, it gets paged
269 // in for subsequent reboots and the cold startup times essentially
270 // look like warm times thereafter! The 'warm up' is done by
271 // setting up a 'RunOnce' key during DLLRegisterServer of
272 // npchrome_frame.dll.
274 // This works because chrome prefetch becomes part of boot
275 // prefetch file ntosboot-b00dfaad.pf and paged in on subsequent
276 // reboots. As long as the sytem does not undergo significant
277 // memory pressure those pages remain in memory and we get pretty
278 // amazing startup times, down to about 300 ms from 1200 ms
281 // - Whether chrome frame is used or not, there's a read penalty
282 // (1200-300 =) 900 ms for every boot.
283 // - Heavy system memory usage after reboot will nullify the benefits
284 // but the user will still pay the cost.
285 // - Overall the time saved will always be less than total time spent
287 // - We are not sure when the chrome 'warm up' will age out from the
288 // boot prefetch file.
290 // The idea here is to try this out on chrome frame dev channel
291 // and see if it produces a significant drift in startup numbers.
292 HRESULT
SetupRunOnce() {
293 HRESULT result
= E_FAIL
;
295 string16 channel_name
;
296 if (base::win::GetVersion() < base::win::VERSION_VISTA
&&
297 GoogleUpdateSettings::GetChromeChannelAndModifiers(true, &channel_name
)) {
298 std::transform(channel_name
.begin(), channel_name
.end(),
299 channel_name
.begin(), tolower
);
300 // Use this only for the dev channel.
301 if (channel_name
.find(L
"dev") != string16::npos
) {
302 HKEY hive
= HKEY_CURRENT_USER
;
303 if (IsSystemProcess()) {
304 // For system installs, our updates will be running as SYSTEM which
305 // makes writing to a RunOnce key under HKCU not so terribly useful.
306 hive
= HKEY_LOCAL_MACHINE
;
310 LONG ret
= run_once
.Create(hive
, kRunOnce
, KEY_READ
| KEY_WRITE
);
311 if (ret
== ERROR_SUCCESS
) {
312 CommandLine
run_once_cmd(chrome_launcher::GetChromeExecutablePath());
313 run_once_cmd
.AppendSwitchASCII(switches::kAutomationClientChannelID
,
315 run_once_cmd
.AppendSwitch(switches::kChromeFrame
);
316 ret
= run_once
.WriteValue(L
"A",
317 run_once_cmd
.GetCommandLineString().c_str());
319 result
= HRESULT_FROM_WIN32(ret
);
324 // We're on a non-XP version of Windows or on a stable channel. Nothing
332 // Helper method called for user-level installs where we don't have admin
333 // permissions. Starts up the long running process and registers it to get it
334 // started at next boot.
335 HRESULT
SetupUserLevelHelper() {
338 // Remove existing run-at-startup entry.
339 base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER
, kRunKeyName
);
341 // Build the chrome_frame_helper command line.
342 base::FilePath module_path
;
343 base::FilePath helper_path
;
344 if (PathService::Get(base::FILE_MODULE
, &module_path
)) {
345 module_path
= module_path
.DirName();
346 helper_path
= module_path
.Append(kChromeFrameHelperExe
);
347 if (!file_util::PathExists(helper_path
)) {
348 // If we can't find the helper in the current directory, try looking
349 // one up (this is the layout in the build output folder).
350 module_path
= module_path
.DirName();
351 helper_path
= module_path
.Append(kChromeFrameHelperExe
);
352 DCHECK(file_util::PathExists(helper_path
)) <<
353 "Could not find chrome_frame_helper.exe.";
356 // Find window handle of existing instance.
357 HWND old_window
= FindWindow(kChromeFrameHelperWindowClassName
,
358 kChromeFrameHelperWindowName
);
360 if (file_util::PathExists(helper_path
)) {
361 std::wstring
helper_path_cmd(L
"\"");
362 helper_path_cmd
+= helper_path
.value();
363 helper_path_cmd
+= L
"\" ";
364 helper_path_cmd
+= kChromeFrameHelperStartupArg
;
366 // Add new run-at-startup entry.
367 if (!base::win::AddCommandToAutoRun(HKEY_CURRENT_USER
, kRunKeyName
,
370 LOG(ERROR
) << "Could not add helper process to auto run key.";
373 // Start new instance.
374 base::LaunchOptions options
;
375 options
.start_hidden
= true;
376 bool launched
= base::LaunchProcess(helper_path
.value(), options
, NULL
);
379 PLOG(DFATAL
) << "Could not launch helper process.";
382 // Kill old instance using window handle.
383 if (IsWindow(old_window
)) {
384 BOOL result
= PostMessage(old_window
, WM_CLOSE
, 0, 0);
386 PLOG(ERROR
) << "Failed to post close message to old helper process: ";
390 hr
= HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND
);
400 // To delete the user agent, set value to NULL.
401 // The is_system parameter indicates whether this is a per machine or a per
402 // user installation.
403 HRESULT
SetChromeFrameUA(bool is_system
, const wchar_t* value
) {
405 HKEY parent_hive
= is_system
? HKEY_LOCAL_MACHINE
: HKEY_CURRENT_USER
;
408 LONG reg_result
= ua_key
.Create(parent_hive
, kPostPlatformUAKey
,
409 KEY_READ
| KEY_WRITE
);
410 if (reg_result
== ERROR_SUCCESS
) {
411 // Make sure that we unregister ChromeFrame UA strings registered previously
412 wchar_t value_name
[MAX_PATH
+ 1] = {};
413 wchar_t value_data
[MAX_PATH
+ 1] = {};
415 DWORD value_index
= 0;
416 while (value_index
< ua_key
.GetValueCount()) {
417 DWORD name_size
= arraysize(value_name
);
418 DWORD value_size
= arraysize(value_data
);
420 LRESULT ret
= ::RegEnumValue(ua_key
.Handle(), value_index
, value_name
,
421 &name_size
, NULL
, &type
,
422 reinterpret_cast<BYTE
*>(value_data
),
424 if (ret
== ERROR_SUCCESS
) {
425 if (StartsWith(value_name
, kChromeFramePrefix
, false)) {
426 ua_key
.DeleteValue(value_name
);
435 std::wstring chrome_frame_ua_value_name
= kChromeFramePrefix
;
436 chrome_frame_ua_value_name
+= GetCurrentModuleVersion();
438 ua_key
.WriteValue(chrome_frame_ua_value_name
.c_str(), value
);
442 DLOG(ERROR
) << __FUNCTION__
<< ": " << kPostPlatformUAKey
443 << ", error code = " << reg_result
;
444 hr
= HRESULT_FROM_WIN32(reg_result
);
449 class SecurityDescBackup
{
451 explicit SecurityDescBackup(const std::wstring
& backup_key
)
452 : backup_key_name_(backup_key
) {}
453 ~SecurityDescBackup() {}
455 // Save given security descriptor to the backup key.
456 bool SaveSecurity(const CSecurityDesc
& sd
) {
458 if (!sd
.ToString(&str
))
461 RegKey
backup_key(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str(),
462 KEY_READ
| KEY_WRITE
);
463 if (backup_key
.Valid()) {
464 return backup_key
.WriteValue(NULL
, str
.GetString()) == ERROR_SUCCESS
;
470 // Restore security descriptor from backup key to given key name.
471 bool RestoreSecurity(const wchar_t* key_name
) {
473 if (!ReadBackupKey(&sddl
))
476 // Create security descriptor from string.
478 if (!sd
.FromString(sddl
.c_str()))
482 // Restore DACL and Owner of the key from saved security descriptor.
488 DWORD error
= ::SetNamedSecurityInfo(const_cast<wchar_t*>(key_name
),
489 SE_REGISTRY_KEY
, OWNER_SECURITY_INFORMATION
| DACL_SECURITY_INFORMATION
,
490 const_cast<SID
*>(owner
.GetPSID()), NULL
,
491 const_cast<ACL
*>(dacl
.GetPACL()), NULL
);
494 return (error
== ERROR_SUCCESS
);
498 // Read SDDL string from backup key
499 bool ReadBackupKey(std::wstring
* sddl
) {
500 RegKey
backup_key(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str(), KEY_READ
);
501 if (!backup_key
.Valid())
505 DWORD reg_type
= REG_NONE
;
506 if (backup_key
.ReadValue(NULL
, NULL
, &len
, ®_type
) != ERROR_SUCCESS
)
508 DCHECK_EQ(0u, len
% sizeof(wchar_t));
510 if ((len
== 0) || (reg_type
!= REG_SZ
))
513 size_t wchar_count
= 1 + len
/ sizeof(wchar_t);
514 if (backup_key
.ReadValue(NULL
, WriteInto(sddl
, wchar_count
), &len
,
515 ®_type
) != ERROR_SUCCESS
) {
522 void DeleteBackupKey() {
523 ::RegDeleteKey(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str());
526 std::wstring backup_key_name_
;
529 struct TokenWithPrivileges
{
530 TokenWithPrivileges() {
531 token_
.GetEffectiveToken(TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
);
532 token_
.GetUser(&user_
);
535 ~TokenWithPrivileges() {
536 token_
.EnableDisablePrivileges(take_ownership_
);
537 token_
.EnableDisablePrivileges(restore_
);
540 bool EnablePrivileges() {
541 if (take_ownership_
.GetCount() == 0)
542 if (!token_
.EnablePrivilege(L
"SeTakeOwnershipPrivilege",
546 if (restore_
.GetCount() == 0)
547 if (!token_
.EnablePrivilege(L
"SeRestorePrivilege", &restore_
))
553 const CSid
& GetUser() const {
559 CTokenPrivileges take_ownership_
;
560 CTokenPrivileges restore_
;
564 HRESULT
SetOrDeleteMimeHandlerKey(bool set
, HKEY root_key
) {
565 std::wstring key_name
= kInternetSettings
;
566 key_name
.append(L
"\\Secure Mime Handlers");
567 RegKey
key(root_key
, key_name
.c_str(), KEY_READ
| KEY_WRITE
);
571 LONG result1
= ERROR_SUCCESS
;
572 LONG result2
= ERROR_SUCCESS
;
574 result1
= key
.WriteValue(L
"ChromeTab.ChromeActiveDocument", 1);
575 result2
= key
.WriteValue(L
"ChromeTab.ChromeActiveDocument.1", 1);
577 result1
= key
.DeleteValue(L
"ChromeTab.ChromeActiveDocument");
578 result2
= key
.DeleteValue(L
"ChromeTab.ChromeActiveDocument.1");
581 return result1
!= ERROR_SUCCESS
? HRESULT_FROM_WIN32(result1
) :
582 HRESULT_FROM_WIN32(result2
);
586 // Pin crash reporting by leaking a reference.
587 ignore_result(new chrome_frame::ScopedCrashReporting());
590 // Chrome Frame registration functions.
591 //-----------------------------------------------------------------------------
592 HRESULT
RegisterSecuredMimeHandler(bool enable
, bool is_system
) {
594 return SetOrDeleteMimeHandlerKey(enable
, HKEY_CURRENT_USER
);
595 } else if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
596 return SetOrDeleteMimeHandlerKey(enable
, HKEY_LOCAL_MACHINE
);
599 std::wstring mime_key
= kInternetSettings
;
600 mime_key
.append(L
"\\Secure Mime Handlers");
601 std::wstring backup_key
= kInternetSettings
;
602 backup_key
.append(L
"\\__backup_SMH__");
603 std::wstring object_name
= L
"MACHINE\\";
604 object_name
.append(mime_key
);
606 TokenWithPrivileges token_
;
607 if (!token_
.EnablePrivileges())
608 return E_ACCESSDENIED
;
610 // If there is a backup key - something bad happened; try to restore
611 // security on "Secure Mime Handlers" from the backup.
612 SecurityDescBackup
backup(backup_key
);
613 backup
.RestoreSecurity(object_name
.c_str());
615 // Read old security descriptor of the Mime key first.
617 if (!AtlGetSecurityDescriptor(object_name
.c_str(), SE_REGISTRY_KEY
, &sd
)) {
621 backup
.SaveSecurity(sd
);
624 if (AtlSetOwnerSid(object_name
.c_str(), SE_REGISTRY_KEY
, token_
.GetUser())) {
627 sd
.GetDacl(&new_dacl
);
628 new_dacl
.AddAllowedAce(token_
.GetUser(), GENERIC_WRITE
| GENERIC_READ
);
629 if (AtlSetDacl(object_name
.c_str(), SE_REGISTRY_KEY
, new_dacl
)) {
630 hr
= SetOrDeleteMimeHandlerKey(enable
, HKEY_LOCAL_MACHINE
);
634 backup
.RestoreSecurity(object_name
.c_str());
638 HRESULT
RegisterActiveDoc(bool reg
, bool is_system
) {
639 // We have to call the static T::UpdateRegistry function instead of
640 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEDOC, reg)
641 // because there is specific OLEMISC replacement.
642 return ChromeActiveDocument::UpdateRegistry(reg
);
645 HRESULT
RegisterActiveX(bool reg
, bool is_system
) {
646 // We have to call the static T::UpdateRegistry function instead of
647 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEX, reg)
648 // because there is specific OLEMISC replacement.
649 return ChromeFrameActivex::UpdateRegistry(reg
);
652 HRESULT
RegisterElevationPolicy(bool reg
, bool is_system
) {
654 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
655 // Register the elevation policy. This must succeed for Chrome Frame to
656 // be able launch Chrome when running in low-integrity IE.
657 hr
= _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ELEVATION
, reg
);
659 // Ignore failures since old versions of IE 7 (e.g., 7.0.6000.16386, which
660 // shipped with Vista RTM) do not export IERefreshElevationPolicy.
661 RefreshElevationPolicy();
667 HRESULT
RegisterProtocol(bool reg
, bool is_system
) {
668 return _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEPROTOCOL
, reg
);
671 HRESULT
RegisterBhoClsid(bool reg
, bool is_system
) {
672 return Bho::UpdateRegistry(reg
);
675 HRESULT
RegisterBhoIE(bool reg
, bool is_system
) {
677 return _AtlModule
.UpdateRegistryFromResourceS(IDR_REGISTER_BHO
, reg
);
680 // Setup the long running process:
681 return SetupUserLevelHelper();
683 // Unschedule the user-level helper. Note that we don't kill it here
684 // so that during updates we don't have a time window with no running
685 // helper. Uninstalls and updates will explicitly kill the helper from
686 // within the installer. Unregister existing run-at-startup entry.
687 return base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER
,
688 kRunKeyName
) ? S_OK
: E_FAIL
;
693 HRESULT
RegisterTypeLib(bool reg
, bool is_system
) {
694 if (reg
&& !is_system
) {
695 // Enables the RegisterTypeLib Function function to override default
696 // registry mappings under Windows Vista Service Pack 1 (SP1),
697 // Windows Server 2008, and later operating system versions
698 typedef void (WINAPI
* OaEnablePerUserTypeLibReg
)(void);
699 OaEnablePerUserTypeLibReg per_user_typelib_func
=
700 reinterpret_cast<OaEnablePerUserTypeLibReg
>(
701 GetProcAddress(GetModuleHandle(L
"oleaut32.dll"),
702 "OaEnablePerUserTLibRegistration"));
703 if (per_user_typelib_func
) {
704 (*per_user_typelib_func
)();
708 UtilRegisterTypeLib(_AtlComModule
.m_hInstTypeLib
,
710 UtilUnRegisterTypeLib(_AtlComModule
.m_hInstTypeLib
,
714 HRESULT
RegisterLegacyNPAPICleanup(bool reg
, bool is_system
) {
716 _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_NPAPI
, reg
);
717 UtilRemovePersistentNPAPIMarker();
723 HRESULT
RegisterAppId(bool reg
, bool is_system
) {
724 return _AtlModule
.UpdateRegistryAppId(reg
);
727 HRESULT
RegisterUserAgent(bool reg
, bool is_system
) {
729 return SetChromeFrameUA(is_system
, L
"1");
731 return SetChromeFrameUA(is_system
, NULL
);
735 enum RegistrationStepId
{
736 kStepSecuredMimeHandler
= 0,
739 kStepElevationPolicy
= 3,
742 kStepBhoRegistration
= 6,
743 kStepRegisterTypeLib
= 7,
744 kStepNpapiCleanup
= 8,
750 enum RegistrationFlags
{
753 GCF_PROTOCOL
= 0x0004,
755 BHO_REGISTRATION
= 0x0010,
761 // Mux the failure step into the hresult. We take only the first four bits
762 // and stick those into the top four bits of the facility code. We also set the
763 // Customer bit to be polite. Graphically, we write our error code to the
764 // bits marked with ^:
765 // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
766 // 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
767 // +---+-+-+-----------------------+-------------------------------+
768 // |Sev|C|R| Facility | Code |
769 // +---+-+-+-----------------------+-------------------------------+
771 // See http://msdn.microsoft.com/en-us/library/cc231198(PROT.10).aspx for
772 // more details on HRESULTS.
774 // The resulting error can be extracted by:
775 // error_code = (fiddled_hr & 0x07800000) >> 23
776 HRESULT
MuxErrorIntoHRESULT(HRESULT hr
, int error_code
) {
777 DCHECK_GE(error_code
, 0);
778 DCHECK_LT(error_code
, kStepEnd
);
779 COMPILE_ASSERT(kStepEnd
<= 0xF, update_error_muxing_too_many_steps
);
781 // Check that our four desired bits are clear.
782 // 0xF87FFFFF == 11111000011111111111111111111111
783 DCHECK_EQ(static_cast<HRESULT
>(hr
& 0xF87FFFFF), hr
);
785 HRESULT fiddled_hr
= ((error_code
& 0xF) << 23) | hr
;
786 fiddled_hr
|= 1 << 29; // Set the customer bit.
791 HRESULT
CustomRegistration(uint16 reg_flags
, bool reg
, bool is_system
) {
792 if (reg
&& (reg_flags
& (ACTIVEDOC
| ACTIVEX
)))
793 reg_flags
|= (TYPELIB
| GCF_PROTOCOL
);
795 // Set the flag that gets checked in AddCommonRGSReplacements before doing
796 // registration work.
797 _AtlModule
.do_system_registration_
= is_system
;
799 typedef HRESULT (*RegistrationFn
)(bool reg
, bool is_system
);
800 struct RegistrationStep
{
801 RegistrationStepId id
;
805 static const RegistrationStep registration_steps
[] = {
806 { kStepSecuredMimeHandler
, ACTIVEDOC
, &RegisterSecuredMimeHandler
},
807 { kStepActiveDoc
, ACTIVEDOC
, &RegisterActiveDoc
},
808 { kStepActiveX
, ACTIVEX
, &RegisterActiveX
},
809 { kStepElevationPolicy
, (ACTIVEDOC
| ACTIVEX
), &RegisterElevationPolicy
},
810 { kStepProtocol
, GCF_PROTOCOL
, &RegisterProtocol
},
811 { kStepBhoClsid
, BHO_CLSID
, &RegisterBhoClsid
},
812 { kStepBhoRegistration
, BHO_REGISTRATION
, &RegisterBhoIE
},
813 { kStepRegisterTypeLib
, TYPELIB
, &RegisterTypeLib
},
814 { kStepNpapiCleanup
, ALL
, &RegisterLegacyNPAPICleanup
},
815 { kStepAppId
, ALL
, &RegisterAppId
},
816 { kStepUserAgent
, ALL
, &RegisterUserAgent
}
821 bool rollback
= false;
822 int failure_step
= 0;
823 HRESULT step_hr
= S_OK
;
824 for (int step
= 0; step
< arraysize(registration_steps
); ++step
) {
825 if ((reg_flags
& registration_steps
[step
].condition
) != 0) {
826 step_hr
= registration_steps
[step
].func(reg
, is_system
);
827 if (FAILED(step_hr
)) {
828 // Store only the first failing HRESULT with the step value muxed in.
830 hr
= MuxErrorIntoHRESULT(step_hr
, step
);
833 // On registration if a step fails, we abort and rollback.
845 // Rollback the failing action and all preceding ones.
846 for (int step
= failure_step
; step
>= 0; --step
) {
847 registration_steps
[step
].func(!reg
, is_system
);
857 extern "C" BOOL WINAPI
DllMain(HINSTANCE instance
,
860 UNREFERENCED_PARAMETER(instance
);
861 if (reason
== DLL_PROCESS_ATTACH
) {
863 // Silence traces from the ATL registrar to reduce the log noise.
864 ATL::CTrace::s_trace
.ChangeCategory(atlTraceRegistrar
, 0,
865 ATLTRACESTATUS_DISABLED
);
869 g_exit_manager
= new base::AtExitManager();
870 CommandLine::Init(0, NULL
);
871 logging::InitLogging(
873 logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG
,
874 logging::LOCK_LOG_FILE
,
875 logging::DELETE_OLD_LOG_FILE
,
876 logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS
);
878 // Log the same items as Chrome.
879 logging::SetLogItems(true, // enable_process_id
880 true, // enable_thread_id
881 false, // enable_timestamp
882 true); // enable_tickcount
884 DllRedirector
* dll_redirector
= DllRedirector::GetInstance();
885 DCHECK(dll_redirector
);
887 if (!dll_redirector
->RegisterAsFirstCFModule()) {
888 // Someone else was here first, try and get a pointer to their
889 // DllGetClassObject export:
890 g_dll_get_class_object_redir_ptr
=
891 dll_redirector
->GetDllGetClassObjectPtr();
892 DCHECK(g_dll_get_class_object_redir_ptr
!= NULL
)
893 << "Found CF module with no DllGetClassObject export.";
896 // Enable trace control and transport through event tracing for Windows.
897 logging::LogEventProvider::Initialize(kChromeFrameProvider
);
899 // Set a callback so that crash reporting can be pinned when the module is
901 chrome_frame::SetPinModuleCallback(&OnPinModule
);
902 } else if (reason
== DLL_PROCESS_DETACH
) {
903 DllRedirector
* dll_redirector
= DllRedirector::GetInstance();
904 DCHECK(dll_redirector
);
905 dll_redirector
->UnregisterAsFirstCFModule();
907 g_patch_helper
.UnpatchIfNeeded();
909 delete g_exit_manager
;
910 g_exit_manager
= NULL
;
912 return _AtlModule
.DllMain(reason
, reserved
);
915 // Used to determine whether the DLL can be unloaded by OLE
916 STDAPI
DllCanUnloadNow() {
917 return _AtlModule
.DllCanUnloadNow();
920 // Returns a class factory to create an object of the requested type
921 STDAPI
DllGetClassObject(REFCLSID rclsid
, REFIID riid
, LPVOID
* ppv
) {
922 chrome_frame::ScopedCrashReporting crash_reporting
;
924 // If we found another module present when we were loaded, then delegate to
926 if (g_dll_get_class_object_redir_ptr
) {
927 return g_dll_get_class_object_redir_ptr(rclsid
, riid
, ppv
);
930 // Enable sniffing and switching only if asked for BHO
931 // (we use BHO to get loaded in IE).
932 if (rclsid
== CLSID_ChromeFrameBHO
) {
933 g_patch_helper
.InitializeAndPatchProtocolsIfNeeded();
936 return _AtlModule
.DllGetClassObject(rclsid
, riid
, ppv
);
939 // DllRegisterServer - Adds entries to the system registry
940 STDAPI
DllRegisterServer() {
941 chrome_frame::ScopedCrashReporting crash_reporting
;
942 uint16 flags
= ACTIVEX
| ACTIVEDOC
| TYPELIB
| GCF_PROTOCOL
|
943 BHO_CLSID
| BHO_REGISTRATION
;
945 HRESULT hr
= CustomRegistration(flags
, true, true);
953 // DllUnregisterServer - Removes entries from the system registry
954 STDAPI
DllUnregisterServer() {
955 chrome_frame::ScopedCrashReporting crash_reporting
;
956 HRESULT hr
= CustomRegistration(ALL
, false, true);
960 // DllRegisterUserServer - Adds entries to the HKCU hive in the registry.
961 STDAPI
DllRegisterUserServer() {
962 chrome_frame::ScopedCrashReporting crash_reporting
;
963 UINT flags
= ACTIVEX
| ACTIVEDOC
| TYPELIB
| GCF_PROTOCOL
|
964 BHO_CLSID
| BHO_REGISTRATION
;
966 HRESULT hr
= CustomRegistration(flags
, TRUE
, false);
974 // DllUnregisterUserServer - Removes entries from the HKCU hive in the registry.
975 STDAPI
DllUnregisterUserServer() {
976 chrome_frame::ScopedCrashReporting crash_reporting
;
977 HRESULT hr
= CustomRegistration(ALL
, FALSE
, false);
981 // Object entries go here instead of with each object, so that we can move
982 // the objects to a lib. Also reduces magic.
983 OBJECT_ENTRY_AUTO(CLSID_ChromeFrameBHO
, Bho
)
984 OBJECT_ENTRY_AUTO(__uuidof(ChromeActiveDocument
), ChromeActiveDocument
)
985 OBJECT_ENTRY_AUTO(__uuidof(ChromeFrame
), ChromeFrameActivex
)
986 OBJECT_ENTRY_AUTO(__uuidof(ChromeProtocol
), ChromeProtocol
)