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/process/launch.h"
22 #include "base/strings/string16.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_piece.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/sys_string_conversions.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/win/registry.h"
29 #include "base/win/windows_version.h"
30 #include "chrome/common/chrome_constants.h"
31 #include "chrome/common/chrome_switches.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 "components/variations/entropy_provider.h"
46 #include "grit/chrome_frame_resources.h"
47 #include "url/url_util.h"
49 using base::win::RegKey
;
53 const wchar_t kInternetSettings
[] =
54 L
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
56 const wchar_t kProtocolHandlers
[] =
57 L
"Software\\Classes\\Protocols\\Handler";
59 const wchar_t kRunOnce
[] =
60 L
"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
62 const wchar_t kRunKeyName
[] = L
"ChromeFrameHelper";
64 const wchar_t kChromeFrameHelperExe
[] = L
"chrome_frame_helper.exe";
65 const wchar_t kChromeFrameHelperStartupArg
[] = L
"--startup";
67 // Window class and window names.
68 // TODO(robertshield): These and other constants need to be refactored into
69 // a common chrome_frame_constants.h|cc and built into a separate lib
70 // (either chrome_frame_utils or make another one).
71 const wchar_t kChromeFrameHelperWindowClassName
[] =
72 L
"ChromeFrameHelperWindowClass";
73 const wchar_t kChromeFrameHelperWindowName
[] =
74 L
"ChromeFrameHelperWindowName";
76 // {0562BFC3-2550-45b4-BD8E-A310583D3A6F}
77 const GUID kChromeFrameProvider
=
78 { 0x562bfc3, 0x2550, 0x45b4,
79 { 0xbd, 0x8e, 0xa3, 0x10, 0x58, 0x3d, 0x3a, 0x6f } };
81 const wchar_t kPostPlatformUAKey
[] =
82 L
"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\"
83 L
"User Agent\\Post Platform";
84 const wchar_t kChromeFramePrefix
[] = L
"chromeframe/";
86 // See comments in DllGetClassObject.
87 LPFNGETCLASSOBJECT g_dll_get_class_object_redir_ptr
= NULL
;
89 // This function has the side effect of initializing an unprotected
90 // vector pointer inside GoogleUrl. If this is called during DLL loading,
91 // it has the effect of avoiding an initialization race on that pointer.
92 // TODO(siggi): fix GoogleUrl.
93 void InitGoogleUrl() {
94 static const char kDummyUrl
[] = "http://www.google.com";
96 url_util::IsStandard(kDummyUrl
,
97 url_parse::MakeRange(0, arraysize(kDummyUrl
)));
100 class ChromeTabModule
: public CAtlDllModuleT
<ChromeTabModule
> {
102 typedef CAtlDllModuleT
<ChromeTabModule
> ParentClass
;
104 ChromeTabModule() : do_system_registration_(true), crash_reporting_(NULL
) {}
106 DECLARE_LIBID(LIBID_ChromeTabLib
)
107 DECLARE_REGISTRY_APPID_RESOURCEID(IDR_CHROMETAB
,
108 "{FD9B1B31-F4D8-436A-8F4F-D3C2E36733D3}")
110 // Override to add our SYSTIME binary value to registry scripts.
111 // See chrome_frame_activex.rgs for usage.
112 virtual HRESULT
AddCommonRGSReplacements(IRegistrarBase
* registrar
) throw() {
113 HRESULT hr
= ParentClass::AddCommonRGSReplacements(registrar
);
116 SYSTEMTIME local_time
;
117 ::GetSystemTime(&local_time
);
118 std::string
hex(base::HexEncode(&local_time
, sizeof(local_time
)));
119 base::StringPiece
sp_hex(hex
);
120 hr
= registrar
->AddReplacement(L
"SYSTIME",
121 base::SysNativeMBToWide(sp_hex
).c_str());
122 DCHECK(SUCCEEDED(hr
));
126 base::FilePath app_path
=
127 chrome_launcher::GetChromeExecutablePath().DirName();
128 hr
= registrar
->AddReplacement(L
"CHROME_APPPATH",
129 app_path
.value().c_str());
130 DCHECK(SUCCEEDED(hr
));
134 hr
= registrar
->AddReplacement(L
"CHROME_APPNAME",
135 chrome::kBrowserProcessExecutableName
);
136 DCHECK(SUCCEEDED(hr
));
138 // Fill in VERSION from the VERSIONINFO stored in the DLL's resources.
139 scoped_ptr
<FileVersionInfo
> module_version_info(
140 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
141 DCHECK(module_version_info
!= NULL
);
142 std::wstring
file_version(module_version_info
->file_version());
143 hr
= registrar
->AddReplacement(L
"VERSION", file_version
.c_str());
144 DCHECK(SUCCEEDED(hr
));
148 // Add the directory of chrome_launcher.exe. This will be the same
149 // as the directory for the current DLL.
150 std::wstring module_dir
;
151 base::FilePath module_path
;
152 if (PathService::Get(base::FILE_MODULE
, &module_path
)) {
153 module_dir
= module_path
.DirName().value();
157 hr
= registrar
->AddReplacement(L
"CHROME_LAUNCHER_APPPATH",
159 DCHECK(SUCCEEDED(hr
));
163 // Add the filename of chrome_launcher.exe
164 hr
= registrar
->AddReplacement(L
"CHROME_LAUNCHER_APPNAME",
165 chrome_launcher::kLauncherExeBaseName
);
166 DCHECK(SUCCEEDED(hr
));
170 // Add the registry hive to use.
171 // Note: This is ugly as hell. I'd rather use the pMapEntries parameter
172 // to CAtlModule::UpdateRegistryFromResource, unfortunately we have a
173 // few components that are registered by calling their
174 // static T::UpdateRegistry() methods directly, which doesn't allow
175 // pMapEntries to be passed through :-(
176 if (do_system_registration_
) {
177 hr
= registrar
->AddReplacement(L
"HIVE", L
"HKLM");
179 hr
= registrar
->AddReplacement(L
"HIVE", L
"HKCU");
181 DCHECK(SUCCEEDED(hr
));
185 // Add the Chrome Frame CLSID.
186 wchar_t cf_clsid
[64];
187 StringFromGUID2(CLSID_ChromeFrame
, &cf_clsid
[0], arraysize(cf_clsid
));
188 hr
= registrar
->AddReplacement(L
"CHROME_FRAME_CLSID", &cf_clsid
[0]);
194 // The module is "locked" when an object takes a reference on it. The first
195 // time it is locked, take a reference on crash reporting to bind its lifetime
197 virtual LONG
Lock() throw() {
198 LONG result
= ParentClass::Lock();
200 DCHECK_EQ(crash_reporting_
,
201 static_cast<chrome_frame::ScopedCrashReporting
*>(NULL
));
202 crash_reporting_
= new chrome_frame::ScopedCrashReporting();
207 // The module is "unlocked" when an object that had a reference on it is
208 // destroyed. The last time it is unlocked, release the reference on crash
210 virtual LONG
Unlock() throw() {
211 LONG result
= ParentClass::Unlock();
213 DCHECK_NE(crash_reporting_
,
214 static_cast<chrome_frame::ScopedCrashReporting
*>(NULL
));
215 delete crash_reporting_
;
216 crash_reporting_
= NULL
;
221 // See comments in AddCommonRGSReplacements
222 bool do_system_registration_
;
225 // A scoper created when the module is initially locked and destroyed when it
226 // is finally unlocked. This is not a scoped_ptr since that could cause
227 // reporting to shut down at exit, which would lead to problems with the
229 chrome_frame::ScopedCrashReporting
* crash_reporting_
;
232 ChromeTabModule _AtlModule
;
234 base::AtExitManager
* g_exit_manager
= NULL
;
236 HRESULT
RefreshElevationPolicy() {
237 const wchar_t kIEFrameDll
[] = L
"ieframe.dll";
238 const char kIERefreshPolicy
[] = "IERefreshElevationPolicy";
239 HRESULT hr
= E_NOTIMPL
;
241 // Stick an SEH in the chain to prevent the VEH from picking up on first
242 // chance exceptions caused by loading ieframe.dll. Use the vanilla
243 // ExceptionBarrier to report any exceptions that do make their way to us
245 ExceptionBarrier barrier
;
247 HMODULE ieframe_module
= LoadLibrary(kIEFrameDll
);
248 if (ieframe_module
) {
249 typedef HRESULT (__stdcall
*IERefreshPolicy
)();
250 IERefreshPolicy ie_refresh_policy
= reinterpret_cast<IERefreshPolicy
>(
251 GetProcAddress(ieframe_module
, kIERefreshPolicy
));
253 if (ie_refresh_policy
) {
254 hr
= ie_refresh_policy();
256 hr
= HRESULT_FROM_WIN32(GetLastError());
259 FreeLibrary(ieframe_module
);
261 hr
= HRESULT_FROM_WIN32(GetLastError());
267 // Experimental boot prefetch optimization for Chrome Frame
269 // If chrome is warmed up during a single reboot, it gets paged
270 // in for subsequent reboots and the cold startup times essentially
271 // look like warm times thereafter! The 'warm up' is done by
272 // setting up a 'RunOnce' key during DLLRegisterServer of
273 // npchrome_frame.dll.
275 // This works because chrome prefetch becomes part of boot
276 // prefetch file ntosboot-b00dfaad.pf and paged in on subsequent
277 // reboots. As long as the sytem does not undergo significant
278 // memory pressure those pages remain in memory and we get pretty
279 // amazing startup times, down to about 300 ms from 1200 ms
282 // - Whether chrome frame is used or not, there's a read penalty
283 // (1200-300 =) 900 ms for every boot.
284 // - Heavy system memory usage after reboot will nullify the benefits
285 // but the user will still pay the cost.
286 // - Overall the time saved will always be less than total time spent
288 // - We are not sure when the chrome 'warm up' will age out from the
289 // boot prefetch file.
291 // The idea here is to try this out on chrome frame dev channel
292 // and see if it produces a significant drift in startup numbers.
293 HRESULT
SetupRunOnce() {
294 HRESULT result
= E_FAIL
;
296 string16 channel_name
;
297 if (base::win::GetVersion() < base::win::VERSION_VISTA
&&
298 GoogleUpdateSettings::GetChromeChannelAndModifiers(true, &channel_name
)) {
299 std::transform(channel_name
.begin(), channel_name
.end(),
300 channel_name
.begin(), tolower
);
301 // Use this only for the dev channel.
302 if (channel_name
.find(L
"dev") != string16::npos
) {
303 HKEY hive
= HKEY_CURRENT_USER
;
304 if (IsSystemProcess()) {
305 // For system installs, our updates will be running as SYSTEM which
306 // makes writing to a RunOnce key under HKCU not so terribly useful.
307 hive
= HKEY_LOCAL_MACHINE
;
311 LONG ret
= run_once
.Create(hive
, kRunOnce
, KEY_READ
| KEY_WRITE
);
312 if (ret
== ERROR_SUCCESS
) {
313 CommandLine
run_once_cmd(chrome_launcher::GetChromeExecutablePath());
314 run_once_cmd
.AppendSwitchASCII(switches::kAutomationClientChannelID
,
316 run_once_cmd
.AppendSwitch(switches::kChromeFrame
);
317 ret
= run_once
.WriteValue(L
"A",
318 run_once_cmd
.GetCommandLineString().c_str());
320 result
= HRESULT_FROM_WIN32(ret
);
325 // We're on a non-XP version of Windows or on a stable channel. Nothing
333 // Helper method called for user-level installs where we don't have admin
334 // permissions. Starts up the long running process and registers it to get it
335 // started at next boot.
336 HRESULT
SetupUserLevelHelper() {
339 // Remove existing run-at-startup entry.
340 base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER
, kRunKeyName
);
342 // Build the chrome_frame_helper command line.
343 base::FilePath module_path
;
344 base::FilePath helper_path
;
345 if (PathService::Get(base::FILE_MODULE
, &module_path
)) {
346 module_path
= module_path
.DirName();
347 helper_path
= module_path
.Append(kChromeFrameHelperExe
);
348 if (!base::PathExists(helper_path
)) {
349 // If we can't find the helper in the current directory, try looking
350 // one up (this is the layout in the build output folder).
351 module_path
= module_path
.DirName();
352 helper_path
= module_path
.Append(kChromeFrameHelperExe
);
353 DCHECK(base::PathExists(helper_path
)) <<
354 "Could not find chrome_frame_helper.exe.";
357 // Find window handle of existing instance.
358 HWND old_window
= FindWindow(kChromeFrameHelperWindowClassName
,
359 kChromeFrameHelperWindowName
);
361 if (base::PathExists(helper_path
)) {
362 std::wstring
helper_path_cmd(L
"\"");
363 helper_path_cmd
+= helper_path
.value();
364 helper_path_cmd
+= L
"\" ";
365 helper_path_cmd
+= kChromeFrameHelperStartupArg
;
367 // Add new run-at-startup entry.
368 if (!base::win::AddCommandToAutoRun(HKEY_CURRENT_USER
, kRunKeyName
,
371 LOG(ERROR
) << "Could not add helper process to auto run key.";
374 // Start new instance.
375 base::LaunchOptions options
;
376 options
.start_hidden
= true;
377 bool launched
= base::LaunchProcess(helper_path
.value(), options
, NULL
);
380 PLOG(DFATAL
) << "Could not launch helper process.";
383 // Kill old instance using window handle.
384 if (IsWindow(old_window
)) {
385 BOOL result
= PostMessage(old_window
, WM_CLOSE
, 0, 0);
387 PLOG(ERROR
) << "Failed to post close message to old helper process: ";
391 hr
= HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND
);
401 // To delete the user agent, set value to NULL.
402 // The is_system parameter indicates whether this is a per machine or a per
403 // user installation.
404 HRESULT
SetChromeFrameUA(bool is_system
, const wchar_t* value
) {
406 HKEY parent_hive
= is_system
? HKEY_LOCAL_MACHINE
: HKEY_CURRENT_USER
;
409 LONG reg_result
= ua_key
.Create(parent_hive
, kPostPlatformUAKey
,
410 KEY_READ
| KEY_WRITE
);
411 if (reg_result
== ERROR_SUCCESS
) {
412 // Make sure that we unregister ChromeFrame UA strings registered previously
413 wchar_t value_name
[MAX_PATH
+ 1] = {};
414 wchar_t value_data
[MAX_PATH
+ 1] = {};
416 DWORD value_index
= 0;
417 while (value_index
< ua_key
.GetValueCount()) {
418 DWORD name_size
= arraysize(value_name
);
419 DWORD value_size
= arraysize(value_data
);
421 LRESULT ret
= ::RegEnumValue(ua_key
.Handle(), value_index
, value_name
,
422 &name_size
, NULL
, &type
,
423 reinterpret_cast<BYTE
*>(value_data
),
425 if (ret
== ERROR_SUCCESS
) {
426 if (StartsWith(value_name
, kChromeFramePrefix
, false)) {
427 ua_key
.DeleteValue(value_name
);
436 std::wstring chrome_frame_ua_value_name
= kChromeFramePrefix
;
437 chrome_frame_ua_value_name
+= GetCurrentModuleVersion();
439 ua_key
.WriteValue(chrome_frame_ua_value_name
.c_str(), value
);
443 DLOG(ERROR
) << __FUNCTION__
<< ": " << kPostPlatformUAKey
444 << ", error code = " << reg_result
;
445 hr
= HRESULT_FROM_WIN32(reg_result
);
450 class SecurityDescBackup
{
452 explicit SecurityDescBackup(const std::wstring
& backup_key
)
453 : backup_key_name_(backup_key
) {}
454 ~SecurityDescBackup() {}
456 // Save given security descriptor to the backup key.
457 bool SaveSecurity(const CSecurityDesc
& sd
) {
459 if (!sd
.ToString(&str
))
462 RegKey
backup_key(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str(),
463 KEY_READ
| KEY_WRITE
);
464 if (backup_key
.Valid()) {
465 return backup_key
.WriteValue(NULL
, str
.GetString()) == ERROR_SUCCESS
;
471 // Restore security descriptor from backup key to given key name.
472 bool RestoreSecurity(const wchar_t* key_name
) {
474 if (!ReadBackupKey(&sddl
))
477 // Create security descriptor from string.
479 if (!sd
.FromString(sddl
.c_str()))
483 // Restore DACL and Owner of the key from saved security descriptor.
489 DWORD error
= ::SetNamedSecurityInfo(const_cast<wchar_t*>(key_name
),
490 SE_REGISTRY_KEY
, OWNER_SECURITY_INFORMATION
| DACL_SECURITY_INFORMATION
,
491 const_cast<SID
*>(owner
.GetPSID()), NULL
,
492 const_cast<ACL
*>(dacl
.GetPACL()), NULL
);
495 return (error
== ERROR_SUCCESS
);
499 // Read SDDL string from backup key
500 bool ReadBackupKey(std::wstring
* sddl
) {
501 RegKey
backup_key(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str(), KEY_READ
);
502 if (!backup_key
.Valid())
506 DWORD reg_type
= REG_NONE
;
507 if (backup_key
.ReadValue(NULL
, NULL
, &len
, ®_type
) != ERROR_SUCCESS
)
509 DCHECK_EQ(0u, len
% sizeof(wchar_t));
511 if ((len
== 0) || (reg_type
!= REG_SZ
))
514 size_t wchar_count
= 1 + len
/ sizeof(wchar_t);
515 if (backup_key
.ReadValue(NULL
, WriteInto(sddl
, wchar_count
), &len
,
516 ®_type
) != ERROR_SUCCESS
) {
523 void DeleteBackupKey() {
524 ::RegDeleteKey(HKEY_LOCAL_MACHINE
, backup_key_name_
.c_str());
527 std::wstring backup_key_name_
;
530 struct TokenWithPrivileges
{
531 TokenWithPrivileges() {
532 token_
.GetEffectiveToken(TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
);
533 token_
.GetUser(&user_
);
536 ~TokenWithPrivileges() {
537 token_
.EnableDisablePrivileges(take_ownership_
);
538 token_
.EnableDisablePrivileges(restore_
);
541 bool EnablePrivileges() {
542 if (take_ownership_
.GetCount() == 0)
543 if (!token_
.EnablePrivilege(L
"SeTakeOwnershipPrivilege",
547 if (restore_
.GetCount() == 0)
548 if (!token_
.EnablePrivilege(L
"SeRestorePrivilege", &restore_
))
554 const CSid
& GetUser() const {
560 CTokenPrivileges take_ownership_
;
561 CTokenPrivileges restore_
;
565 const wchar_t* const kMimeHandlerKeyValues
[] = {
566 L
"ChromeTab.ChromeActiveDocument",
567 L
"ChromeTab.ChromeActiveDocument.1",
570 // Returns true if the values are present or absent in |root_key|'s Secure Mime
571 // Handlers key based on |for_installed|. Returns false if the values are not as
572 // expected or if an error occurred.
573 bool MimeHandlerKeyIsConfigured(bool for_install
, HKEY root_key
) {
574 string16
key_name(kInternetSettings
);
575 key_name
.append(L
"\\Secure Mime Handlers");
576 RegKey
key(root_key
, key_name
.c_str(), KEY_QUERY_VALUE
);
580 for (size_t i
= 0; i
< arraysize(kMimeHandlerKeyValues
); ++i
) {
582 LONG result
= key
.ReadValueDW(kMimeHandlerKeyValues
[i
], &value
);
584 if (result
!= ERROR_SUCCESS
|| value
!= 1)
587 if (result
!= ERROR_FILE_NOT_FOUND
)
594 HRESULT
SetOrDeleteMimeHandlerKey(bool set
, HKEY root_key
) {
595 string16
key_name(kInternetSettings
);
596 key_name
.append(L
"\\Secure Mime Handlers");
597 RegKey
key(root_key
, key_name
.c_str(), KEY_SET_VALUE
);
601 HRESULT result
= S_OK
;
602 for (size_t i
= 0; i
< arraysize(kMimeHandlerKeyValues
); ++i
) {
603 LONG intermediate
= set
?
604 key
.WriteValue(kMimeHandlerKeyValues
[i
], 1) :
605 key
.DeleteValue(kMimeHandlerKeyValues
[i
]);
606 if (intermediate
!= ERROR_SUCCESS
&& result
== S_OK
)
607 result
= HRESULT_FROM_WIN32(intermediate
);
613 // Pin crash reporting by leaking a reference.
614 ignore_result(new chrome_frame::ScopedCrashReporting());
617 // Chrome Frame registration functions.
618 //-----------------------------------------------------------------------------
619 HRESULT
RegisterSecuredMimeHandler(bool enable
, bool is_system
) {
620 if (MimeHandlerKeyIsConfigured(enable
, HKEY_LOCAL_MACHINE
))
623 return SetOrDeleteMimeHandlerKey(enable
, HKEY_CURRENT_USER
);
624 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
625 return SetOrDeleteMimeHandlerKey(enable
, HKEY_LOCAL_MACHINE
);
627 std::wstring mime_key
= kInternetSettings
;
628 mime_key
.append(L
"\\Secure Mime Handlers");
629 std::wstring backup_key
= kInternetSettings
;
630 backup_key
.append(L
"\\__backup_SMH__");
631 std::wstring object_name
= L
"MACHINE\\";
632 object_name
.append(mime_key
);
634 TokenWithPrivileges token_
;
635 if (!token_
.EnablePrivileges())
636 return E_ACCESSDENIED
;
638 // If there is a backup key - something bad happened; try to restore
639 // security on "Secure Mime Handlers" from the backup.
640 SecurityDescBackup
backup(backup_key
);
641 backup
.RestoreSecurity(object_name
.c_str());
643 // Read old security descriptor of the Mime key first.
645 if (!AtlGetSecurityDescriptor(object_name
.c_str(), SE_REGISTRY_KEY
, &sd
)) {
649 backup
.SaveSecurity(sd
);
652 if (AtlSetOwnerSid(object_name
.c_str(), SE_REGISTRY_KEY
, token_
.GetUser())) {
655 sd
.GetDacl(&new_dacl
);
656 new_dacl
.AddAllowedAce(token_
.GetUser(), GENERIC_WRITE
| GENERIC_READ
);
657 if (AtlSetDacl(object_name
.c_str(), SE_REGISTRY_KEY
, new_dacl
)) {
658 hr
= SetOrDeleteMimeHandlerKey(enable
, HKEY_LOCAL_MACHINE
);
662 backup
.RestoreSecurity(object_name
.c_str());
666 HRESULT
RegisterActiveDoc(bool reg
, bool is_system
) {
667 // We have to call the static T::UpdateRegistry function instead of
668 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEDOC, reg)
669 // because there is specific OLEMISC replacement.
670 return ChromeActiveDocument::UpdateRegistry(reg
);
673 HRESULT
RegisterActiveX(bool reg
, bool is_system
) {
674 // We have to call the static T::UpdateRegistry function instead of
675 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEX, reg)
676 // because there is specific OLEMISC replacement.
677 return ChromeFrameActivex::UpdateRegistry(reg
);
680 HRESULT
RegisterElevationPolicy(bool reg
, bool is_system
) {
682 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
683 // Register the elevation policy. This must succeed for Chrome Frame to
684 // be able launch Chrome when running in low-integrity IE.
685 hr
= _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ELEVATION
, reg
);
687 // Ignore failures since old versions of IE 7 (e.g., 7.0.6000.16386, which
688 // shipped with Vista RTM) do not export IERefreshElevationPolicy.
689 RefreshElevationPolicy();
695 HRESULT
RegisterProtocol(bool reg
, bool is_system
) {
696 return _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEPROTOCOL
, reg
);
699 HRESULT
RegisterBhoClsid(bool reg
, bool is_system
) {
700 return Bho::UpdateRegistry(reg
);
703 HRESULT
RegisterBhoIE(bool reg
, bool is_system
) {
705 return _AtlModule
.UpdateRegistryFromResourceS(IDR_REGISTER_BHO
, reg
);
708 // Setup the long running process:
709 return SetupUserLevelHelper();
711 // Unschedule the user-level helper. Note that we don't kill it here
712 // so that during updates we don't have a time window with no running
713 // helper. Uninstalls and updates will explicitly kill the helper from
714 // within the installer. Unregister existing run-at-startup entry.
715 return base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER
,
716 kRunKeyName
) ? S_OK
: E_FAIL
;
721 HRESULT
RegisterTypeLib(bool reg
, bool is_system
) {
722 if (reg
&& !is_system
) {
723 // Enables the RegisterTypeLib Function function to override default
724 // registry mappings under Windows Vista Service Pack 1 (SP1),
725 // Windows Server 2008, and later operating system versions
726 typedef void (WINAPI
* OaEnablePerUserTypeLibReg
)(void);
727 OaEnablePerUserTypeLibReg per_user_typelib_func
=
728 reinterpret_cast<OaEnablePerUserTypeLibReg
>(
729 GetProcAddress(GetModuleHandle(L
"oleaut32.dll"),
730 "OaEnablePerUserTLibRegistration"));
731 if (per_user_typelib_func
) {
732 (*per_user_typelib_func
)();
736 UtilRegisterTypeLib(_AtlComModule
.m_hInstTypeLib
,
738 UtilUnRegisterTypeLib(_AtlComModule
.m_hInstTypeLib
,
742 HRESULT
RegisterLegacyNPAPICleanup(bool reg
, bool is_system
) {
744 _AtlModule
.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_NPAPI
, reg
);
745 UtilRemovePersistentNPAPIMarker();
751 HRESULT
RegisterAppId(bool reg
, bool is_system
) {
752 return _AtlModule
.UpdateRegistryAppId(reg
);
755 HRESULT
RegisterUserAgent(bool reg
, bool is_system
) {
757 return SetChromeFrameUA(is_system
, L
"1");
759 return SetChromeFrameUA(is_system
, NULL
);
763 enum RegistrationStepId
{
764 kStepSecuredMimeHandler
= 0,
767 kStepElevationPolicy
= 3,
770 kStepBhoRegistration
= 6,
771 kStepRegisterTypeLib
= 7,
772 kStepNpapiCleanup
= 8,
778 enum RegistrationFlags
{
781 GCF_PROTOCOL
= 0x0004,
783 BHO_REGISTRATION
= 0x0010,
789 // Mux the failure step into the hresult. We take only the first four bits
790 // and stick those into the top four bits of the facility code. We also set the
791 // Customer bit to be polite. Graphically, we write our error code to the
792 // bits marked with ^:
793 // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
794 // 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
795 // +---+-+-+-----------------------+-------------------------------+
796 // |Sev|C|R| Facility | Code |
797 // +---+-+-+-----------------------+-------------------------------+
799 // See http://msdn.microsoft.com/en-us/library/cc231198(PROT.10).aspx for
800 // more details on HRESULTS.
802 // The resulting error can be extracted by:
803 // error_code = (fiddled_hr & 0x07800000) >> 23
804 HRESULT
MuxErrorIntoHRESULT(HRESULT hr
, int error_code
) {
805 DCHECK_GE(error_code
, 0);
806 DCHECK_LT(error_code
, kStepEnd
);
807 COMPILE_ASSERT(kStepEnd
<= 0xF, update_error_muxing_too_many_steps
);
809 // Check that our four desired bits are clear.
810 // 0xF87FFFFF == 11111000011111111111111111111111
811 DCHECK_EQ(static_cast<HRESULT
>(hr
& 0xF87FFFFF), hr
);
813 HRESULT fiddled_hr
= ((error_code
& 0xF) << 23) | hr
;
814 fiddled_hr
|= 1 << 29; // Set the customer bit.
819 HRESULT
CustomRegistration(uint16 reg_flags
, bool reg
, bool is_system
) {
820 if (reg
&& (reg_flags
& (ACTIVEDOC
| ACTIVEX
)))
821 reg_flags
|= (TYPELIB
| GCF_PROTOCOL
);
823 // Set the flag that gets checked in AddCommonRGSReplacements before doing
824 // registration work.
825 _AtlModule
.do_system_registration_
= is_system
;
827 typedef HRESULT (*RegistrationFn
)(bool reg
, bool is_system
);
828 struct RegistrationStep
{
829 RegistrationStepId id
;
833 static const RegistrationStep registration_steps
[] = {
834 { kStepSecuredMimeHandler
, ACTIVEDOC
, &RegisterSecuredMimeHandler
},
835 { kStepActiveDoc
, ACTIVEDOC
, &RegisterActiveDoc
},
836 { kStepActiveX
, ACTIVEX
, &RegisterActiveX
},
837 { kStepElevationPolicy
, (ACTIVEDOC
| ACTIVEX
), &RegisterElevationPolicy
},
838 { kStepProtocol
, GCF_PROTOCOL
, &RegisterProtocol
},
839 { kStepBhoClsid
, BHO_CLSID
, &RegisterBhoClsid
},
840 { kStepBhoRegistration
, BHO_REGISTRATION
, &RegisterBhoIE
},
841 { kStepRegisterTypeLib
, TYPELIB
, &RegisterTypeLib
},
842 { kStepNpapiCleanup
, ALL
, &RegisterLegacyNPAPICleanup
},
843 { kStepAppId
, ALL
, &RegisterAppId
},
844 { kStepUserAgent
, ALL
, &RegisterUserAgent
}
849 bool rollback
= false;
850 int failure_step
= 0;
851 HRESULT step_hr
= S_OK
;
852 for (int step
= 0; step
< arraysize(registration_steps
); ++step
) {
853 if ((reg_flags
& registration_steps
[step
].condition
) != 0) {
854 step_hr
= registration_steps
[step
].func(reg
, is_system
);
855 if (FAILED(step_hr
)) {
856 // Store only the first failing HRESULT with the step value muxed in.
858 hr
= MuxErrorIntoHRESULT(step_hr
, step
);
861 // On registration if a step fails, we abort and rollback.
873 // Rollback the failing action and all preceding ones.
874 for (int step
= failure_step
; step
>= 0; --step
) {
875 registration_steps
[step
].func(!reg
, is_system
);
885 extern "C" BOOL WINAPI
DllMain(HINSTANCE instance
,
888 UNREFERENCED_PARAMETER(instance
);
889 if (reason
== DLL_PROCESS_ATTACH
) {
891 // Silence traces from the ATL registrar to reduce the log noise.
892 ATL::CTrace::s_trace
.ChangeCategory(atlTraceRegistrar
, 0,
893 ATLTRACESTATUS_DISABLED
);
897 g_exit_manager
= new base::AtExitManager();
898 CommandLine::Init(0, NULL
);
899 logging::LoggingSettings settings
;
900 settings
.logging_dest
= logging::LOG_TO_SYSTEM_DEBUG_LOG
;
901 logging::InitLogging(settings
);
903 // Log the same items as Chrome.
904 logging::SetLogItems(true, // enable_process_id
905 true, // enable_thread_id
906 false, // enable_timestamp
907 true); // enable_tickcount
909 DllRedirector
* dll_redirector
= DllRedirector::GetInstance();
910 DCHECK(dll_redirector
);
912 if (!dll_redirector
->RegisterAsFirstCFModule()) {
913 // Someone else was here first, try and get a pointer to their
914 // DllGetClassObject export:
915 g_dll_get_class_object_redir_ptr
=
916 dll_redirector
->GetDllGetClassObjectPtr();
917 DCHECK(g_dll_get_class_object_redir_ptr
!= NULL
)
918 << "Found CF module with no DllGetClassObject export.";
921 // Enable trace control and transport through event tracing for Windows.
922 logging::LogEventProvider::Initialize(kChromeFrameProvider
);
924 // Set a callback so that crash reporting can be pinned when the module is
926 chrome_frame::SetPinModuleCallback(&OnPinModule
);
927 } else if (reason
== DLL_PROCESS_DETACH
) {
928 DllRedirector
* dll_redirector
= DllRedirector::GetInstance();
929 DCHECK(dll_redirector
);
930 dll_redirector
->UnregisterAsFirstCFModule();
932 g_patch_helper
.UnpatchIfNeeded();
934 delete g_exit_manager
;
935 g_exit_manager
= NULL
;
937 return _AtlModule
.DllMain(reason
, reserved
);
940 // Used to determine whether the DLL can be unloaded by OLE
941 STDAPI
DllCanUnloadNow() {
942 return _AtlModule
.DllCanUnloadNow();
945 // Returns a class factory to create an object of the requested type
946 STDAPI
DllGetClassObject(REFCLSID rclsid
, REFIID riid
, LPVOID
* ppv
) {
947 chrome_frame::ScopedCrashReporting crash_reporting
;
949 // If we found another module present when we were loaded, then delegate to
951 if (g_dll_get_class_object_redir_ptr
) {
952 return g_dll_get_class_object_redir_ptr(rclsid
, riid
, ppv
);
955 // Enable sniffing and switching only if asked for BHO
956 // (we use BHO to get loaded in IE).
957 if (rclsid
== CLSID_ChromeFrameBHO
) {
958 g_patch_helper
.InitializeAndPatchProtocolsIfNeeded();
961 return _AtlModule
.DllGetClassObject(rclsid
, riid
, ppv
);
964 // DllRegisterServer - Adds entries to the system registry
965 STDAPI
DllRegisterServer() {
966 chrome_frame::ScopedCrashReporting crash_reporting
;
967 uint16 flags
= ACTIVEX
| ACTIVEDOC
| TYPELIB
| GCF_PROTOCOL
|
968 BHO_CLSID
| BHO_REGISTRATION
;
970 HRESULT hr
= CustomRegistration(flags
, true, true);
978 // DllUnregisterServer - Removes entries from the system registry
979 STDAPI
DllUnregisterServer() {
980 chrome_frame::ScopedCrashReporting crash_reporting
;
981 HRESULT hr
= CustomRegistration(ALL
, false, true);
985 // DllRegisterUserServer - Adds entries to the HKCU hive in the registry.
986 STDAPI
DllRegisterUserServer() {
987 chrome_frame::ScopedCrashReporting crash_reporting
;
988 UINT flags
= ACTIVEX
| ACTIVEDOC
| TYPELIB
| GCF_PROTOCOL
|
989 BHO_CLSID
| BHO_REGISTRATION
;
991 HRESULT hr
= CustomRegistration(flags
, TRUE
, false);
999 // DllUnregisterUserServer - Removes entries from the HKCU hive in the registry.
1000 STDAPI
DllUnregisterUserServer() {
1001 chrome_frame::ScopedCrashReporting crash_reporting
;
1002 HRESULT hr
= CustomRegistration(ALL
, FALSE
, false);
1006 // Object entries go here instead of with each object, so that we can move
1007 // the objects to a lib. Also reduces magic.
1008 OBJECT_ENTRY_AUTO(CLSID_ChromeFrameBHO
, Bho
)
1009 OBJECT_ENTRY_AUTO(__uuidof(ChromeActiveDocument
), ChromeActiveDocument
)
1010 OBJECT_ENTRY_AUTO(__uuidof(ChromeFrame
), ChromeFrameActivex
)
1011 OBJECT_ENTRY_AUTO(__uuidof(ChromeProtocol
), ChromeProtocol
)