Replace FTS in the history_service with a brute force text search.
[chromium-blink-merge.git] / chrome_frame / chrome_tab.cc
bloba563dedd379d3d11a4b0b0f342efe17e2f9b4a0b
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/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/strings/string16.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_piece.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/sys_string_conversions.h"
26 #include "base/strings/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;
50 namespace {
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> {
100 public:
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);
114 if (SUCCEEDED(hr)) {
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));
124 if (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));
132 if (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));
146 if (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();
153 } else {
154 NOTREACHED();
156 hr = registrar->AddReplacement(L"CHROME_LAUNCHER_APPPATH",
157 module_dir.c_str());
158 DCHECK(SUCCEEDED(hr));
161 if (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));
168 if (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");
177 } else {
178 hr = registrar->AddReplacement(L"HIVE", L"HKCU");
180 DCHECK(SUCCEEDED(hr));
183 if (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]);
190 return hr;
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
195 // to the module.
196 virtual LONG Lock() throw() {
197 LONG result = ParentClass::Lock();
198 if (result == 1) {
199 DCHECK_EQ(crash_reporting_,
200 static_cast<chrome_frame::ScopedCrashReporting*>(NULL));
201 crash_reporting_ = new chrome_frame::ScopedCrashReporting();
203 return result;
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
208 // reporting.
209 virtual LONG Unlock() throw() {
210 LONG result = ParentClass::Unlock();
211 if (!result) {
212 DCHECK_NE(crash_reporting_,
213 static_cast<chrome_frame::ScopedCrashReporting*>(NULL));
214 delete crash_reporting_;
215 crash_reporting_ = NULL;
217 return result;
220 // See comments in AddCommonRGSReplacements
221 bool do_system_registration_;
223 private:
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
227 // loader lock.
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
243 // though.
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();
254 } else {
255 hr = HRESULT_FROM_WIN32(GetLastError());
258 FreeLibrary(ieframe_module);
259 } else {
260 hr = HRESULT_FROM_WIN32(GetLastError());
263 return hr;
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
280 // The downside is:
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
286 // paging in chrome
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;
309 RegKey run_once;
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,
314 "0");
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);
320 } else {
321 result = S_FALSE;
323 } else {
324 // We're on a non-XP version of Windows or on a stable channel. Nothing
325 // needs doing.
326 result = S_FALSE;
329 return result;
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() {
336 HRESULT hr = S_OK;
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,
368 helper_path_cmd)) {
369 hr = E_FAIL;
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);
377 if (!launched) {
378 hr = E_FAIL;
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);
385 if (!result) {
386 PLOG(ERROR) << "Failed to post close message to old helper process: ";
389 } else {
390 hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
392 } else {
393 hr = E_UNEXPECTED;
394 NOTREACHED();
397 return hr;
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) {
404 HRESULT hr = E_FAIL;
405 HKEY parent_hive = is_system ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
407 RegKey ua_key;
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);
419 DWORD type = 0;
420 LRESULT ret = ::RegEnumValue(ua_key.Handle(), value_index, value_name,
421 &name_size, NULL, &type,
422 reinterpret_cast<BYTE*>(value_data),
423 &value_size);
424 if (ret == ERROR_SUCCESS) {
425 if (StartsWith(value_name, kChromeFramePrefix, false)) {
426 ua_key.DeleteValue(value_name);
427 } else {
428 ++value_index;
430 } else {
431 break;
435 std::wstring chrome_frame_ua_value_name = kChromeFramePrefix;
436 chrome_frame_ua_value_name += GetCurrentModuleVersion();
437 if (value) {
438 ua_key.WriteValue(chrome_frame_ua_value_name.c_str(), value);
440 hr = S_OK;
441 } else {
442 DLOG(ERROR) << __FUNCTION__ << ": " << kPostPlatformUAKey
443 << ", error code = " << reg_result;
444 hr = HRESULT_FROM_WIN32(reg_result);
446 return hr;
449 class SecurityDescBackup {
450 public:
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) {
457 CString str;
458 if (!sd.ToString(&str))
459 return false;
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;
467 return false;
470 // Restore security descriptor from backup key to given key name.
471 bool RestoreSecurity(const wchar_t* key_name) {
472 std::wstring sddl;
473 if (!ReadBackupKey(&sddl))
474 return false;
476 // Create security descriptor from string.
477 CSecurityDesc sd;
478 if (!sd.FromString(sddl.c_str()))
479 return false;
481 bool result = true;
482 // Restore DACL and Owner of the key from saved security descriptor.
483 CDacl dacl;
484 CSid owner;
485 sd.GetDacl(&dacl);
486 sd.GetOwner(&owner);
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);
493 DeleteBackupKey();
494 return (error == ERROR_SUCCESS);
497 private:
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())
502 return false;
504 DWORD len = 0;
505 DWORD reg_type = REG_NONE;
506 if (backup_key.ReadValue(NULL, NULL, &len, &reg_type) != ERROR_SUCCESS)
507 return false;
508 DCHECK_EQ(0u, len % sizeof(wchar_t));
510 if ((len == 0) || (reg_type != REG_SZ))
511 return false;
513 size_t wchar_count = 1 + len / sizeof(wchar_t);
514 if (backup_key.ReadValue(NULL, WriteInto(sddl, wchar_count), &len,
515 &reg_type) != ERROR_SUCCESS) {
516 return false;
519 return true;
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",
543 &take_ownership_))
544 return false;
546 if (restore_.GetCount() == 0)
547 if (!token_.EnablePrivilege(L"SeRestorePrivilege", &restore_))
548 return false;
550 return true;
553 const CSid& GetUser() const {
554 return user_;
557 private:
558 CAccessToken token_;
559 CTokenPrivileges take_ownership_;
560 CTokenPrivileges restore_;
561 CSid user_;
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);
568 if (!key.Valid())
569 return false;
571 LONG result1 = ERROR_SUCCESS;
572 LONG result2 = ERROR_SUCCESS;
573 if (set) {
574 result1 = key.WriteValue(L"ChromeTab.ChromeActiveDocument", 1);
575 result2 = key.WriteValue(L"ChromeTab.ChromeActiveDocument.1", 1);
576 } else {
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);
585 void OnPinModule() {
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) {
593 if (!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.
616 CSecurityDesc sd;
617 if (!AtlGetSecurityDescriptor(object_name.c_str(), SE_REGISTRY_KEY, &sd)) {
618 return E_FAIL;
621 backup.SaveSecurity(sd);
622 HRESULT hr = E_FAIL;
623 // set new owner
624 if (AtlSetOwnerSid(object_name.c_str(), SE_REGISTRY_KEY, token_.GetUser())) {
625 // set new dacl
626 CDacl new_dacl;
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());
635 return hr;
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) {
653 HRESULT hr = S_OK;
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);
658 if (SUCCEEDED(hr)) {
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();
664 return hr;
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) {
676 if (is_system) {
677 return _AtlModule.UpdateRegistryFromResourceS(IDR_REGISTER_BHO, reg);
678 } else {
679 if (reg) {
680 // Setup the long running process:
681 return SetupUserLevelHelper();
682 } else {
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)();
707 return reg ?
708 UtilRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
709 NULL, !is_system) :
710 UtilUnRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
711 NULL, !is_system);
714 HRESULT RegisterLegacyNPAPICleanup(bool reg, bool is_system) {
715 if (!reg) {
716 _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_NPAPI, reg);
717 UtilRemovePersistentNPAPIMarker();
719 // Ignore failures.
720 return S_OK;
723 HRESULT RegisterAppId(bool reg, bool is_system) {
724 return _AtlModule.UpdateRegistryAppId(reg);
727 HRESULT RegisterUserAgent(bool reg, bool is_system) {
728 if (reg) {
729 return SetChromeFrameUA(is_system, L"1");
730 } else {
731 return SetChromeFrameUA(is_system, NULL);
735 enum RegistrationStepId {
736 kStepSecuredMimeHandler = 0,
737 kStepActiveDoc = 1,
738 kStepActiveX = 2,
739 kStepElevationPolicy = 3,
740 kStepProtocol = 4,
741 kStepBhoClsid = 5,
742 kStepBhoRegistration = 6,
743 kStepRegisterTypeLib = 7,
744 kStepNpapiCleanup = 8,
745 kStepAppId = 9,
746 kStepUserAgent = 10,
747 kStepEnd = 11
750 enum RegistrationFlags {
751 ACTIVEX = 0x0001,
752 ACTIVEDOC = 0x0002,
753 GCF_PROTOCOL = 0x0004,
754 BHO_CLSID = 0x0008,
755 BHO_REGISTRATION = 0x0010,
756 TYPELIB = 0x0020,
758 ALL = 0xFFFF
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 // +---+-+-+-----------------------+-------------------------------+
770 // ^ ^ ^ ^ ^
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.
788 return fiddled_hr;
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;
802 uint16 condition;
803 RegistrationFn func;
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 }
819 HRESULT hr = S_OK;
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.
829 if (hr == S_OK) {
830 hr = MuxErrorIntoHRESULT(step_hr, step);
833 // On registration if a step fails, we abort and rollback.
834 if (reg) {
835 rollback = true;
836 failure_step = step;
837 break;
843 if (rollback) {
844 DCHECK(reg);
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);
851 return hr;
854 } // namespace
856 // DLL Entry Point
857 extern "C" BOOL WINAPI DllMain(HINSTANCE instance,
858 DWORD reason,
859 LPVOID reserved) {
860 UNREFERENCED_PARAMETER(instance);
861 if (reason == DLL_PROCESS_ATTACH) {
862 #ifndef NDEBUG
863 // Silence traces from the ATL registrar to reduce the log noise.
864 ATL::CTrace::s_trace.ChangeCategory(atlTraceRegistrar, 0,
865 ATLTRACESTATUS_DISABLED);
866 #endif
867 InitGoogleUrl();
869 g_exit_manager = new base::AtExitManager();
870 CommandLine::Init(0, NULL);
871 logging::LoggingSettings settings;
872 settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
873 logging::InitLogging(settings);
875 // Log the same items as Chrome.
876 logging::SetLogItems(true, // enable_process_id
877 true, // enable_thread_id
878 false, // enable_timestamp
879 true); // enable_tickcount
881 DllRedirector* dll_redirector = DllRedirector::GetInstance();
882 DCHECK(dll_redirector);
884 if (!dll_redirector->RegisterAsFirstCFModule()) {
885 // Someone else was here first, try and get a pointer to their
886 // DllGetClassObject export:
887 g_dll_get_class_object_redir_ptr =
888 dll_redirector->GetDllGetClassObjectPtr();
889 DCHECK(g_dll_get_class_object_redir_ptr != NULL)
890 << "Found CF module with no DllGetClassObject export.";
893 // Enable trace control and transport through event tracing for Windows.
894 logging::LogEventProvider::Initialize(kChromeFrameProvider);
896 // Set a callback so that crash reporting can be pinned when the module is
897 // pinned.
898 chrome_frame::SetPinModuleCallback(&OnPinModule);
899 } else if (reason == DLL_PROCESS_DETACH) {
900 DllRedirector* dll_redirector = DllRedirector::GetInstance();
901 DCHECK(dll_redirector);
902 dll_redirector->UnregisterAsFirstCFModule();
904 g_patch_helper.UnpatchIfNeeded();
906 delete g_exit_manager;
907 g_exit_manager = NULL;
909 return _AtlModule.DllMain(reason, reserved);
912 // Used to determine whether the DLL can be unloaded by OLE
913 STDAPI DllCanUnloadNow() {
914 return _AtlModule.DllCanUnloadNow();
917 // Returns a class factory to create an object of the requested type
918 STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) {
919 chrome_frame::ScopedCrashReporting crash_reporting;
921 // If we found another module present when we were loaded, then delegate to
922 // that:
923 if (g_dll_get_class_object_redir_ptr) {
924 return g_dll_get_class_object_redir_ptr(rclsid, riid, ppv);
927 // Enable sniffing and switching only if asked for BHO
928 // (we use BHO to get loaded in IE).
929 if (rclsid == CLSID_ChromeFrameBHO) {
930 g_patch_helper.InitializeAndPatchProtocolsIfNeeded();
933 return _AtlModule.DllGetClassObject(rclsid, riid, ppv);
936 // DllRegisterServer - Adds entries to the system registry
937 STDAPI DllRegisterServer() {
938 chrome_frame::ScopedCrashReporting crash_reporting;
939 uint16 flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
940 BHO_CLSID | BHO_REGISTRATION;
942 HRESULT hr = CustomRegistration(flags, true, true);
943 if (SUCCEEDED(hr)) {
944 SetupRunOnce();
947 return hr;
950 // DllUnregisterServer - Removes entries from the system registry
951 STDAPI DllUnregisterServer() {
952 chrome_frame::ScopedCrashReporting crash_reporting;
953 HRESULT hr = CustomRegistration(ALL, false, true);
954 return hr;
957 // DllRegisterUserServer - Adds entries to the HKCU hive in the registry.
958 STDAPI DllRegisterUserServer() {
959 chrome_frame::ScopedCrashReporting crash_reporting;
960 UINT flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
961 BHO_CLSID | BHO_REGISTRATION;
963 HRESULT hr = CustomRegistration(flags, TRUE, false);
964 if (SUCCEEDED(hr)) {
965 SetupRunOnce();
968 return hr;
971 // DllUnregisterUserServer - Removes entries from the HKCU hive in the registry.
972 STDAPI DllUnregisterUserServer() {
973 chrome_frame::ScopedCrashReporting crash_reporting;
974 HRESULT hr = CustomRegistration(ALL, FALSE, false);
975 return hr;
978 // Object entries go here instead of with each object, so that we can move
979 // the objects to a lib. Also reduces magic.
980 OBJECT_ENTRY_AUTO(CLSID_ChromeFrameBHO, Bho)
981 OBJECT_ENTRY_AUTO(__uuidof(ChromeActiveDocument), ChromeActiveDocument)
982 OBJECT_ENTRY_AUTO(__uuidof(ChromeFrame), ChromeFrameActivex)
983 OBJECT_ENTRY_AUTO(__uuidof(ChromeProtocol), ChromeProtocol)