Add retry function to AccountManagerHelper when called from foreground
[chromium-blink-merge.git] / chrome_frame / chrome_tab.cc
blob2611d69c1c92273bdc632aa6d56c9da47b555706
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>
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/metrics/field_trial.h"
20 #include "base/path_service.h"
21 #include "base/string16.h"
22 #include "base/string_number_conversions.h"
23 #include "base/string_piece.h"
24 #include "base/string_util.h"
25 #include "base/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/metrics_service.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;
50 namespace {
51 // This function has the side effect of initializing an unprotected
52 // vector pointer inside GoogleUrl. If this is called during DLL loading,
53 // it has the effect of avoiding an initialization race on that pointer.
54 // TODO(siggi): fix GoogleUrl.
55 void InitGoogleUrl() {
56 static const char kDummyUrl[] = "http://www.google.com";
58 url_util::IsStandard(kDummyUrl,
59 url_parse::MakeRange(0, arraysize(kDummyUrl)));
62 const wchar_t kInternetSettings[] =
63 L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
65 const wchar_t kProtocolHandlers[] =
66 L"Software\\Classes\\Protocols\\Handler";
68 const wchar_t kRunOnce[] =
69 L"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
71 const wchar_t kRunKeyName[] = L"ChromeFrameHelper";
73 const wchar_t kChromeFrameHelperExe[] = L"chrome_frame_helper.exe";
74 const wchar_t kChromeFrameHelperStartupArg[] = L"--startup";
76 // Window class and window names.
77 // TODO(robertshield): These and other constants need to be refactored into
78 // a common chrome_frame_constants.h|cc and built into a separate lib
79 // (either chrome_frame_utils or make another one).
80 const wchar_t kChromeFrameHelperWindowClassName[] =
81 L"ChromeFrameHelperWindowClass";
82 const wchar_t kChromeFrameHelperWindowName[] =
83 L"ChromeFrameHelperWindowName";
85 // {0562BFC3-2550-45b4-BD8E-A310583D3A6F}
86 static const GUID kChromeFrameProvider =
87 { 0x562bfc3, 0x2550, 0x45b4,
88 { 0xbd, 0x8e, 0xa3, 0x10, 0x58, 0x3d, 0x3a, 0x6f } };
90 const wchar_t kPostPlatformUAKey[] =
91 L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\"
92 L"User Agent\\Post Platform";
93 const wchar_t kChromeFramePrefix[] = L"chromeframe/";
95 // See comments in DllGetClassObject.
96 LPFNGETCLASSOBJECT g_dll_get_class_object_redir_ptr = NULL;
98 class ChromeTabModule : public CAtlDllModuleT<ChromeTabModule> {
99 public:
100 typedef CAtlDllModuleT<ChromeTabModule> ParentClass;
102 ChromeTabModule() : do_system_registration_(true) {}
104 DECLARE_LIBID(LIBID_ChromeTabLib)
105 DECLARE_REGISTRY_APPID_RESOURCEID(IDR_CHROMETAB,
106 "{FD9B1B31-F4D8-436A-8F4F-D3C2E36733D3}")
108 // Override to add our SYSTIME binary value to registry scripts.
109 // See chrome_frame_activex.rgs for usage.
110 virtual HRESULT AddCommonRGSReplacements(IRegistrarBase* registrar) throw() {
111 HRESULT hr = ParentClass::AddCommonRGSReplacements(registrar);
113 if (SUCCEEDED(hr)) {
114 SYSTEMTIME local_time;
115 ::GetSystemTime(&local_time);
116 std::string hex(base::HexEncode(&local_time, sizeof(local_time)));
117 base::StringPiece sp_hex(hex);
118 hr = registrar->AddReplacement(L"SYSTIME",
119 base::SysNativeMBToWide(sp_hex).c_str());
120 DCHECK(SUCCEEDED(hr));
123 if (SUCCEEDED(hr)) {
124 FilePath app_path =
125 chrome_launcher::GetChromeExecutablePath().DirName();
126 hr = registrar->AddReplacement(L"CHROME_APPPATH",
127 app_path.value().c_str());
128 DCHECK(SUCCEEDED(hr));
131 if (SUCCEEDED(hr)) {
132 hr = registrar->AddReplacement(L"CHROME_APPNAME",
133 chrome::kBrowserProcessExecutableName);
134 DCHECK(SUCCEEDED(hr));
136 // Fill in VERSION from the VERSIONINFO stored in the DLL's resources.
137 scoped_ptr<FileVersionInfo> module_version_info(
138 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
139 DCHECK(module_version_info != NULL);
140 std::wstring file_version(module_version_info->file_version());
141 hr = registrar->AddReplacement(L"VERSION", file_version.c_str());
142 DCHECK(SUCCEEDED(hr));
145 if (SUCCEEDED(hr)) {
146 // Add the directory of chrome_launcher.exe. This will be the same
147 // as the directory for the current DLL.
148 std::wstring module_dir;
149 FilePath module_path;
150 if (PathService::Get(base::FILE_MODULE, &module_path)) {
151 module_dir = module_path.DirName().value();
152 } else {
153 NOTREACHED();
155 hr = registrar->AddReplacement(L"CHROME_LAUNCHER_APPPATH",
156 module_dir.c_str());
157 DCHECK(SUCCEEDED(hr));
160 if (SUCCEEDED(hr)) {
161 // Add the filename of chrome_launcher.exe
162 hr = registrar->AddReplacement(L"CHROME_LAUNCHER_APPNAME",
163 chrome_launcher::kLauncherExeBaseName);
164 DCHECK(SUCCEEDED(hr));
167 if (SUCCEEDED(hr)) {
168 // Add the registry hive to use.
169 // Note: This is ugly as hell. I'd rather use the pMapEntries parameter
170 // to CAtlModule::UpdateRegistryFromResource, unfortunately we have a
171 // few components that are registered by calling their
172 // static T::UpdateRegistry() methods directly, which doesn't allow
173 // pMapEntries to be passed through :-(
174 if (do_system_registration_) {
175 hr = registrar->AddReplacement(L"HIVE", L"HKLM");
176 } else {
177 hr = registrar->AddReplacement(L"HIVE", L"HKCU");
179 DCHECK(SUCCEEDED(hr));
182 if (SUCCEEDED(hr)) {
183 // Add the Chrome Frame CLSID.
184 wchar_t cf_clsid[64];
185 StringFromGUID2(CLSID_ChromeFrame, &cf_clsid[0], arraysize(cf_clsid));
186 hr = registrar->AddReplacement(L"CHROME_FRAME_CLSID", &cf_clsid[0]);
189 return hr;
192 // See comments in AddCommonRGSReplacements
193 bool do_system_registration_;
196 ChromeTabModule _AtlModule;
198 base::AtExitManager* g_exit_manager = NULL;
199 base::FieldTrialList* g_field_trial_list = NULL;
201 HRESULT RefreshElevationPolicy() {
202 const wchar_t kIEFrameDll[] = L"ieframe.dll";
203 const char kIERefreshPolicy[] = "IERefreshElevationPolicy";
204 HRESULT hr = E_NOTIMPL;
206 // Stick an SEH in the chain to prevent the VEH from picking up on first
207 // chance exceptions caused by loading ieframe.dll. Use the vanilla
208 // ExceptionBarrier to report any exceptions that do make their way to us
209 // though.
210 ExceptionBarrier barrier;
212 HMODULE ieframe_module = LoadLibrary(kIEFrameDll);
213 if (ieframe_module) {
214 typedef HRESULT (__stdcall *IERefreshPolicy)();
215 IERefreshPolicy ie_refresh_policy = reinterpret_cast<IERefreshPolicy>(
216 GetProcAddress(ieframe_module, kIERefreshPolicy));
218 if (ie_refresh_policy) {
219 hr = ie_refresh_policy();
220 } else {
221 hr = HRESULT_FROM_WIN32(GetLastError());
224 FreeLibrary(ieframe_module);
225 } else {
226 hr = HRESULT_FROM_WIN32(GetLastError());
229 return hr;
232 // Experimental boot prefetch optimization for Chrome Frame
234 // If chrome is warmed up during a single reboot, it gets paged
235 // in for subsequent reboots and the cold startup times essentially
236 // look like warm times thereafter! The 'warm up' is done by
237 // setting up a 'RunOnce' key during DLLRegisterServer of
238 // npchrome_frame.dll.
240 // This works because chrome prefetch becomes part of boot
241 // prefetch file ntosboot-b00dfaad.pf and paged in on subsequent
242 // reboots. As long as the sytem does not undergo significant
243 // memory pressure those pages remain in memory and we get pretty
244 // amazing startup times, down to about 300 ms from 1200 ms
246 // The downside is:
247 // - Whether chrome frame is used or not, there's a read penalty
248 // (1200-300 =) 900 ms for every boot.
249 // - Heavy system memory usage after reboot will nullify the benefits
250 // but the user will still pay the cost.
251 // - Overall the time saved will always be less than total time spent
252 // paging in chrome
253 // - We are not sure when the chrome 'warm up' will age out from the
254 // boot prefetch file.
256 // The idea here is to try this out on chrome frame dev channel
257 // and see if it produces a significant drift in startup numbers.
258 HRESULT SetupRunOnce() {
259 HRESULT result = E_FAIL;
261 string16 channel_name;
262 if (base::win::GetVersion() < base::win::VERSION_VISTA &&
263 GoogleUpdateSettings::GetChromeChannelAndModifiers(true, &channel_name)) {
264 std::transform(channel_name.begin(), channel_name.end(),
265 channel_name.begin(), tolower);
266 // Use this only for the dev channel.
267 if (channel_name.find(L"dev") != string16::npos) {
268 HKEY hive = HKEY_CURRENT_USER;
269 if (IsSystemProcess()) {
270 // For system installs, our updates will be running as SYSTEM which
271 // makes writing to a RunOnce key under HKCU not so terribly useful.
272 hive = HKEY_LOCAL_MACHINE;
275 RegKey run_once;
276 LONG ret = run_once.Create(hive, kRunOnce, KEY_READ | KEY_WRITE);
277 if (ret == ERROR_SUCCESS) {
278 CommandLine run_once_cmd(chrome_launcher::GetChromeExecutablePath());
279 run_once_cmd.AppendSwitchASCII(switches::kAutomationClientChannelID,
280 "0");
281 run_once_cmd.AppendSwitch(switches::kChromeFrame);
282 ret = run_once.WriteValue(L"A",
283 run_once_cmd.GetCommandLineString().c_str());
285 result = HRESULT_FROM_WIN32(ret);
286 } else {
287 result = S_FALSE;
289 } else {
290 // We're on a non-XP version of Windows or on a stable channel. Nothing
291 // needs doing.
292 result = S_FALSE;
295 return result;
298 // Helper method called for user-level installs where we don't have admin
299 // permissions. Starts up the long running process and registers it to get it
300 // started at next boot.
301 HRESULT SetupUserLevelHelper() {
302 HRESULT hr = S_OK;
304 // Remove existing run-at-startup entry.
305 base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER, kRunKeyName);
307 // Build the chrome_frame_helper command line.
308 FilePath module_path;
309 FilePath helper_path;
310 if (PathService::Get(base::FILE_MODULE, &module_path)) {
311 module_path = module_path.DirName();
312 helper_path = module_path.Append(kChromeFrameHelperExe);
313 if (!file_util::PathExists(helper_path)) {
314 // If we can't find the helper in the current directory, try looking
315 // one up (this is the layout in the build output folder).
316 module_path = module_path.DirName();
317 helper_path = module_path.Append(kChromeFrameHelperExe);
318 DCHECK(file_util::PathExists(helper_path)) <<
319 "Could not find chrome_frame_helper.exe.";
322 // Find window handle of existing instance.
323 HWND old_window = FindWindow(kChromeFrameHelperWindowClassName,
324 kChromeFrameHelperWindowName);
326 if (file_util::PathExists(helper_path)) {
327 std::wstring helper_path_cmd(L"\"");
328 helper_path_cmd += helper_path.value();
329 helper_path_cmd += L"\" ";
330 helper_path_cmd += kChromeFrameHelperStartupArg;
332 // Add new run-at-startup entry.
333 if (!base::win::AddCommandToAutoRun(HKEY_CURRENT_USER, kRunKeyName,
334 helper_path_cmd)) {
335 hr = E_FAIL;
336 LOG(ERROR) << "Could not add helper process to auto run key.";
339 // Start new instance.
340 base::LaunchOptions options;
341 options.start_hidden = true;
342 bool launched = base::LaunchProcess(helper_path.value(), options, NULL);
343 if (!launched) {
344 hr = E_FAIL;
345 PLOG(DFATAL) << "Could not launch helper process.";
348 // Kill old instance using window handle.
349 if (IsWindow(old_window)) {
350 BOOL result = PostMessage(old_window, WM_CLOSE, 0, 0);
351 if (!result) {
352 PLOG(ERROR) << "Failed to post close message to old helper process: ";
355 } else {
356 hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
358 } else {
359 hr = E_UNEXPECTED;
360 NOTREACHED();
363 return hr;
366 // To delete the user agent, set value to NULL.
367 // The is_system parameter indicates whether this is a per machine or a per
368 // user installation.
369 HRESULT SetChromeFrameUA(bool is_system, const wchar_t* value) {
370 HRESULT hr = E_FAIL;
371 HKEY parent_hive = is_system ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
373 RegKey ua_key;
374 LONG reg_result = ua_key.Create(parent_hive, kPostPlatformUAKey,
375 KEY_READ | KEY_WRITE);
376 if (reg_result == ERROR_SUCCESS) {
377 // Make sure that we unregister ChromeFrame UA strings registered previously
378 wchar_t value_name[MAX_PATH + 1] = {};
379 wchar_t value_data[MAX_PATH + 1] = {};
381 DWORD value_index = 0;
382 while (value_index < ua_key.GetValueCount()) {
383 DWORD name_size = arraysize(value_name);
384 DWORD value_size = arraysize(value_data);
385 DWORD type = 0;
386 LRESULT ret = ::RegEnumValue(ua_key.Handle(), value_index, value_name,
387 &name_size, NULL, &type,
388 reinterpret_cast<BYTE*>(value_data),
389 &value_size);
390 if (ret == ERROR_SUCCESS) {
391 if (StartsWith(value_name, kChromeFramePrefix, false)) {
392 ua_key.DeleteValue(value_name);
393 } else {
394 ++value_index;
396 } else {
397 break;
401 std::wstring chrome_frame_ua_value_name = kChromeFramePrefix;
402 chrome_frame_ua_value_name += GetCurrentModuleVersion();
403 if (value) {
404 ua_key.WriteValue(chrome_frame_ua_value_name.c_str(), value);
406 hr = S_OK;
407 } else {
408 DLOG(ERROR) << __FUNCTION__ << ": " << kPostPlatformUAKey
409 << ", error code = " << reg_result;
410 hr = HRESULT_FROM_WIN32(reg_result);
412 return hr;
415 class SecurityDescBackup {
416 public:
417 explicit SecurityDescBackup(const std::wstring& backup_key)
418 : backup_key_name_(backup_key) {}
419 ~SecurityDescBackup() {}
421 // Save given security descriptor to the backup key.
422 bool SaveSecurity(const CSecurityDesc& sd) {
423 CString str;
424 if (!sd.ToString(&str))
425 return false;
427 RegKey backup_key(HKEY_LOCAL_MACHINE, backup_key_name_.c_str(),
428 KEY_READ | KEY_WRITE);
429 if (backup_key.Valid()) {
430 return backup_key.WriteValue(NULL, str.GetString()) == ERROR_SUCCESS;
433 return false;
436 // Restore security descriptor from backup key to given key name.
437 bool RestoreSecurity(const wchar_t* key_name) {
438 std::wstring sddl;
439 if (!ReadBackupKey(&sddl))
440 return false;
442 // Create security descriptor from string.
443 CSecurityDesc sd;
444 if (!sd.FromString(sddl.c_str()))
445 return false;
447 bool result = true;
448 // Restore DACL and Owner of the key from saved security descriptor.
449 CDacl dacl;
450 CSid owner;
451 sd.GetDacl(&dacl);
452 sd.GetOwner(&owner);
454 DWORD error = ::SetNamedSecurityInfo(const_cast<wchar_t*>(key_name),
455 SE_REGISTRY_KEY, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
456 const_cast<SID*>(owner.GetPSID()), NULL,
457 const_cast<ACL*>(dacl.GetPACL()), NULL);
459 DeleteBackupKey();
460 return (error == ERROR_SUCCESS);
463 private:
464 // Read SDDL string from backup key
465 bool ReadBackupKey(std::wstring* sddl) {
466 RegKey backup_key(HKEY_LOCAL_MACHINE, backup_key_name_.c_str(), KEY_READ);
467 if (!backup_key.Valid())
468 return false;
470 DWORD len = 0;
471 DWORD reg_type = REG_NONE;
472 if (backup_key.ReadValue(NULL, NULL, &len, &reg_type) != ERROR_SUCCESS)
473 return false;
474 DCHECK_EQ(0u, len % sizeof(wchar_t));
476 if ((len == 0) || (reg_type != REG_SZ))
477 return false;
479 size_t wchar_count = 1 + len / sizeof(wchar_t);
480 if (backup_key.ReadValue(NULL, WriteInto(sddl, wchar_count), &len,
481 &reg_type) != ERROR_SUCCESS) {
482 return false;
485 return true;
488 void DeleteBackupKey() {
489 ::RegDeleteKey(HKEY_LOCAL_MACHINE, backup_key_name_.c_str());
492 std::wstring backup_key_name_;
495 struct TokenWithPrivileges {
496 TokenWithPrivileges() {
497 token_.GetEffectiveToken(TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY);
498 token_.GetUser(&user_);
501 ~TokenWithPrivileges() {
502 token_.EnableDisablePrivileges(take_ownership_);
503 token_.EnableDisablePrivileges(restore_);
506 bool EnablePrivileges() {
507 if (take_ownership_.GetCount() == 0)
508 if (!token_.EnablePrivilege(L"SeTakeOwnershipPrivilege",
509 &take_ownership_))
510 return false;
512 if (restore_.GetCount() == 0)
513 if (!token_.EnablePrivilege(L"SeRestorePrivilege", &restore_))
514 return false;
516 return true;
519 const CSid& GetUser() const {
520 return user_;
523 private:
524 CAccessToken token_;
525 CTokenPrivileges take_ownership_;
526 CTokenPrivileges restore_;
527 CSid user_;
530 HRESULT SetOrDeleteMimeHandlerKey(bool set, HKEY root_key) {
531 std::wstring key_name = kInternetSettings;
532 key_name.append(L"\\Secure Mime Handlers");
533 RegKey key(root_key, key_name.c_str(), KEY_READ | KEY_WRITE);
534 if (!key.Valid())
535 return false;
537 LONG result1 = ERROR_SUCCESS;
538 LONG result2 = ERROR_SUCCESS;
539 if (set) {
540 result1 = key.WriteValue(L"ChromeTab.ChromeActiveDocument", 1);
541 result2 = key.WriteValue(L"ChromeTab.ChromeActiveDocument.1", 1);
542 } else {
543 result1 = key.DeleteValue(L"ChromeTab.ChromeActiveDocument");
544 result2 = key.DeleteValue(L"ChromeTab.ChromeActiveDocument.1");
547 return result1 != ERROR_SUCCESS ? HRESULT_FROM_WIN32(result1) :
548 HRESULT_FROM_WIN32(result2);
551 // Chrome Frame registration functions.
552 //-----------------------------------------------------------------------------
553 HRESULT RegisterSecuredMimeHandler(bool enable, bool is_system) {
554 if (!is_system) {
555 return SetOrDeleteMimeHandlerKey(enable, HKEY_CURRENT_USER);
556 } else if (base::win::GetVersion() < base::win::VERSION_VISTA) {
557 return SetOrDeleteMimeHandlerKey(enable, HKEY_LOCAL_MACHINE);
560 std::wstring mime_key = kInternetSettings;
561 mime_key.append(L"\\Secure Mime Handlers");
562 std::wstring backup_key = kInternetSettings;
563 backup_key.append(L"\\__backup_SMH__");
564 std::wstring object_name = L"MACHINE\\";
565 object_name.append(mime_key);
567 TokenWithPrivileges token_;
568 if (!token_.EnablePrivileges())
569 return E_ACCESSDENIED;
571 // If there is a backup key - something bad happened; try to restore
572 // security on "Secure Mime Handlers" from the backup.
573 SecurityDescBackup backup(backup_key);
574 backup.RestoreSecurity(object_name.c_str());
576 // Read old security descriptor of the Mime key first.
577 CSecurityDesc sd;
578 if (!AtlGetSecurityDescriptor(object_name.c_str(), SE_REGISTRY_KEY, &sd)) {
579 return E_FAIL;
582 backup.SaveSecurity(sd);
583 HRESULT hr = E_FAIL;
584 // set new owner
585 if (AtlSetOwnerSid(object_name.c_str(), SE_REGISTRY_KEY, token_.GetUser())) {
586 // set new dacl
587 CDacl new_dacl;
588 sd.GetDacl(&new_dacl);
589 new_dacl.AddAllowedAce(token_.GetUser(), GENERIC_WRITE | GENERIC_READ);
590 if (AtlSetDacl(object_name.c_str(), SE_REGISTRY_KEY, new_dacl)) {
591 hr = SetOrDeleteMimeHandlerKey(enable, HKEY_LOCAL_MACHINE);
595 backup.RestoreSecurity(object_name.c_str());
596 return hr;
599 HRESULT RegisterActiveDoc(bool reg, bool is_system) {
600 // We have to call the static T::UpdateRegistry function instead of
601 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEDOC, reg)
602 // because there is specific OLEMISC replacement.
603 return ChromeActiveDocument::UpdateRegistry(reg);
606 HRESULT RegisterActiveX(bool reg, bool is_system) {
607 // We have to call the static T::UpdateRegistry function instead of
608 // _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ACTIVEX, reg)
609 // because there is specific OLEMISC replacement.
610 return ChromeFrameActivex::UpdateRegistry(reg);
613 HRESULT RegisterElevationPolicy(bool reg, bool is_system) {
614 HRESULT hr = S_OK;
615 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
616 // Register the elevation policy. This must succeed for Chrome Frame to
617 // be able launch Chrome when running in low-integrity IE.
618 hr = _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_ELEVATION, reg);
619 if (SUCCEEDED(hr)) {
620 // Ignore failures since old versions of IE 7 (e.g., 7.0.6000.16386, which
621 // shipped with Vista RTM) do not export IERefreshElevationPolicy.
622 RefreshElevationPolicy();
625 return hr;
628 HRESULT RegisterProtocol(bool reg, bool is_system) {
629 return _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEPROTOCOL, reg);
632 HRESULT RegisterBhoClsid(bool reg, bool is_system) {
633 return Bho::UpdateRegistry(reg);
636 HRESULT RegisterBhoIE(bool reg, bool is_system) {
637 if (is_system) {
638 return _AtlModule.UpdateRegistryFromResourceS(IDR_REGISTER_BHO, reg);
639 } else {
640 if (reg) {
641 // Setup the long running process:
642 return SetupUserLevelHelper();
643 } else {
644 // Unschedule the user-level helper. Note that we don't kill it here
645 // so that during updates we don't have a time window with no running
646 // helper. Uninstalls and updates will explicitly kill the helper from
647 // within the installer. Unregister existing run-at-startup entry.
648 return base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER,
649 kRunKeyName) ? S_OK : E_FAIL;
654 HRESULT RegisterTypeLib(bool reg, bool is_system) {
655 if (reg && !is_system) {
656 // Enables the RegisterTypeLib Function function to override default
657 // registry mappings under Windows Vista Service Pack 1 (SP1),
658 // Windows Server 2008, and later operating system versions
659 typedef void (WINAPI* OaEnablePerUserTypeLibReg)(void);
660 OaEnablePerUserTypeLibReg per_user_typelib_func =
661 reinterpret_cast<OaEnablePerUserTypeLibReg>(
662 GetProcAddress(GetModuleHandle(L"oleaut32.dll"),
663 "OaEnablePerUserTLibRegistration"));
664 if (per_user_typelib_func) {
665 (*per_user_typelib_func)();
668 return reg ?
669 UtilRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
670 NULL, !is_system) :
671 UtilUnRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
672 NULL, !is_system);
675 HRESULT RegisterLegacyNPAPICleanup(bool reg, bool is_system) {
676 if (!reg) {
677 _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_NPAPI, reg);
678 UtilRemovePersistentNPAPIMarker();
680 // Ignore failures.
681 return S_OK;
684 HRESULT RegisterAppId(bool reg, bool is_system) {
685 return _AtlModule.UpdateRegistryAppId(reg);
688 HRESULT RegisterUserAgent(bool reg, bool is_system) {
689 if (reg) {
690 return SetChromeFrameUA(is_system, L"1");
691 } else {
692 return SetChromeFrameUA(is_system, NULL);
696 enum RegistrationStepId {
697 kStepSecuredMimeHandler = 0,
698 kStepActiveDoc = 1,
699 kStepActiveX = 2,
700 kStepElevationPolicy = 3,
701 kStepProtocol = 4,
702 kStepBhoClsid = 5,
703 kStepBhoRegistration = 6,
704 kStepRegisterTypeLib = 7,
705 kStepNpapiCleanup = 8,
706 kStepAppId = 9,
707 kStepUserAgent = 10,
708 kStepEnd = 11
711 enum RegistrationFlags {
712 ACTIVEX = 0x0001,
713 ACTIVEDOC = 0x0002,
714 GCF_PROTOCOL = 0x0004,
715 BHO_CLSID = 0x0008,
716 BHO_REGISTRATION = 0x0010,
717 TYPELIB = 0x0020,
719 ALL = 0xFFFF
722 // Mux the failure step into the hresult. We take only the first four bits
723 // and stick those into the top four bits of the facility code. We also set the
724 // Customer bit to be polite. Graphically, we write our error code to the
725 // bits marked with ^:
726 // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
727 // 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
728 // +---+-+-+-----------------------+-------------------------------+
729 // |Sev|C|R| Facility | Code |
730 // +---+-+-+-----------------------+-------------------------------+
731 // ^ ^ ^ ^ ^
732 // See http://msdn.microsoft.com/en-us/library/cc231198(PROT.10).aspx for
733 // more details on HRESULTS.
735 // The resulting error can be extracted by:
736 // error_code = (fiddled_hr & 0x07800000) >> 23
737 HRESULT MuxErrorIntoHRESULT(HRESULT hr, int error_code) {
738 DCHECK_GE(error_code, 0);
739 DCHECK_LT(error_code, kStepEnd);
740 COMPILE_ASSERT(kStepEnd <= 0xF, update_error_muxing_too_many_steps);
742 // Check that our four desired bits are clear.
743 // 0xF87FFFFF == 11111000011111111111111111111111
744 DCHECK_EQ(static_cast<HRESULT>(hr & 0xF87FFFFF), hr);
746 HRESULT fiddled_hr = ((error_code & 0xF) << 23) | hr;
747 fiddled_hr |= 1 << 29; // Set the customer bit.
749 return fiddled_hr;
752 HRESULT CustomRegistration(uint16 reg_flags, bool reg, bool is_system) {
753 if (reg && (reg_flags & (ACTIVEDOC | ACTIVEX)))
754 reg_flags |= (TYPELIB | GCF_PROTOCOL);
756 // Set the flag that gets checked in AddCommonRGSReplacements before doing
757 // registration work.
758 _AtlModule.do_system_registration_ = is_system;
760 typedef HRESULT (*RegistrationFn)(bool reg, bool is_system);
761 struct RegistrationStep {
762 RegistrationStepId id;
763 uint16 condition;
764 RegistrationFn func;
766 static const RegistrationStep registration_steps[] = {
767 { kStepSecuredMimeHandler, ACTIVEDOC, &RegisterSecuredMimeHandler },
768 { kStepActiveDoc, ACTIVEDOC, &RegisterActiveDoc },
769 { kStepActiveX, ACTIVEX, &RegisterActiveX },
770 { kStepElevationPolicy, (ACTIVEDOC | ACTIVEX), &RegisterElevationPolicy },
771 { kStepProtocol, GCF_PROTOCOL, &RegisterProtocol },
772 { kStepBhoClsid, BHO_CLSID, &RegisterBhoClsid },
773 { kStepBhoRegistration, BHO_REGISTRATION, &RegisterBhoIE },
774 { kStepRegisterTypeLib, TYPELIB, &RegisterTypeLib },
775 { kStepNpapiCleanup, ALL, &RegisterLegacyNPAPICleanup },
776 { kStepAppId, ALL, &RegisterAppId },
777 { kStepUserAgent, ALL, &RegisterUserAgent }
780 HRESULT hr = S_OK;
782 bool rollback = false;
783 int failure_step = 0;
784 HRESULT step_hr = S_OK;
785 for (int step = 0; step < arraysize(registration_steps); ++step) {
786 if ((reg_flags & registration_steps[step].condition) != 0) {
787 step_hr = registration_steps[step].func(reg, is_system);
788 if (FAILED(step_hr)) {
789 // Store only the first failing HRESULT with the step value muxed in.
790 if (hr == S_OK) {
791 hr = MuxErrorIntoHRESULT(step_hr, step);
794 // On registration if a step fails, we abort and rollback.
795 if (reg) {
796 rollback = true;
797 failure_step = step;
798 break;
804 if (rollback) {
805 DCHECK(reg);
806 // Rollback the failing action and all preceding ones.
807 for (int step = failure_step; step >= 0; --step) {
808 registration_steps[step].func(!reg, is_system);
812 return hr;
815 } // namespace
817 // DLL Entry Point
818 extern "C" BOOL WINAPI DllMain(HINSTANCE instance,
819 DWORD reason,
820 LPVOID reserved) {
821 UNREFERENCED_PARAMETER(instance);
822 if (reason == DLL_PROCESS_ATTACH) {
823 #ifndef NDEBUG
824 // Silence traces from the ATL registrar to reduce the log noise.
825 ATL::CTrace::s_trace.ChangeCategory(atlTraceRegistrar, 0,
826 ATLTRACESTATUS_DISABLED);
827 #endif
828 InitGoogleUrl();
830 g_exit_manager = new base::AtExitManager();
831 CommandLine::Init(0, NULL);
832 InitializeCrashReporting();
833 logging::InitLogging(
834 NULL,
835 logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
836 logging::LOCK_LOG_FILE,
837 logging::DELETE_OLD_LOG_FILE,
838 logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
840 // Log the same items as Chrome.
841 logging::SetLogItems(true, // enable_process_id
842 true, // enable_thread_id
843 false, // enable_timestamp
844 true); // enable_tickcount
846 DllRedirector* dll_redirector = DllRedirector::GetInstance();
847 DCHECK(dll_redirector);
849 if (!dll_redirector->RegisterAsFirstCFModule()) {
850 // Someone else was here first, try and get a pointer to their
851 // DllGetClassObject export:
852 g_dll_get_class_object_redir_ptr =
853 dll_redirector->GetDllGetClassObjectPtr();
854 DCHECK(g_dll_get_class_object_redir_ptr != NULL)
855 << "Found CF module with no DllGetClassObject export.";
858 // Enable trace control and transport through event tracing for Windows.
859 logging::LogEventProvider::Initialize(kChromeFrameProvider);
861 // Initialize the field test infrastructure. Must be done somewhere that
862 // can only get called once. For Chrome Frame, that is here.
863 g_field_trial_list = new base::FieldTrialList(
864 new metrics::SHA1EntropyProvider(MetricsService::GetClientID()));
865 } else if (reason == DLL_PROCESS_DETACH) {
866 delete g_field_trial_list;
867 g_field_trial_list = NULL;
869 DllRedirector* dll_redirector = DllRedirector::GetInstance();
870 DCHECK(dll_redirector);
871 dll_redirector->UnregisterAsFirstCFModule();
873 g_patch_helper.UnpatchIfNeeded();
875 delete g_exit_manager;
876 g_exit_manager = NULL;
878 ShutdownCrashReporting();
880 return _AtlModule.DllMain(reason, reserved);
883 // Used to determine whether the DLL can be unloaded by OLE
884 STDAPI DllCanUnloadNow() {
885 return _AtlModule.DllCanUnloadNow();
888 // Returns a class factory to create an object of the requested type
889 STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) {
890 // If we found another module present when we were loaded, then delegate to
891 // that:
892 if (g_dll_get_class_object_redir_ptr) {
893 return g_dll_get_class_object_redir_ptr(rclsid, riid, ppv);
896 // Enable sniffing and switching only if asked for BHO
897 // (we use BHO to get loaded in IE).
898 if (rclsid == CLSID_ChromeFrameBHO) {
899 g_patch_helper.InitializeAndPatchProtocolsIfNeeded();
902 return _AtlModule.DllGetClassObject(rclsid, riid, ppv);
905 // DllRegisterServer - Adds entries to the system registry
906 STDAPI DllRegisterServer() {
907 uint16 flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
908 BHO_CLSID | BHO_REGISTRATION;
910 HRESULT hr = CustomRegistration(flags, true, true);
911 if (SUCCEEDED(hr)) {
912 SetupRunOnce();
915 return hr;
918 // DllUnregisterServer - Removes entries from the system registry
919 STDAPI DllUnregisterServer() {
920 HRESULT hr = CustomRegistration(ALL, false, true);
921 return hr;
924 // DllRegisterUserServer - Adds entries to the HKCU hive in the registry.
925 STDAPI DllRegisterUserServer() {
926 UINT flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
927 BHO_CLSID | BHO_REGISTRATION;
929 HRESULT hr = CustomRegistration(flags, TRUE, false);
930 if (SUCCEEDED(hr)) {
931 SetupRunOnce();
934 return hr;
937 // DllUnregisterUserServer - Removes entries from the HKCU hive in the registry.
938 STDAPI DllUnregisterUserServer() {
939 HRESULT hr = CustomRegistration(ALL, FALSE, false);
940 return hr;
943 // Object entries go here instead of with each object, so that we can move
944 // the objects to a lib. Also reduces magic.
945 OBJECT_ENTRY_AUTO(CLSID_ChromeFrameBHO, Bho)
946 OBJECT_ENTRY_AUTO(__uuidof(ChromeActiveDocument), ChromeActiveDocument)
947 OBJECT_ENTRY_AUTO(__uuidof(ChromeFrame), ChromeFrameActivex)
948 OBJECT_ENTRY_AUTO(__uuidof(ChromeProtocol), ChromeProtocol)