blob: a0af6e3d882ce5c0069ea254a74a116f1c4fca78 [file] [log] [blame]
Torne (Richard Coles)58218062012-11-14 11:43:16 +00001// 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.
4
5// chrome_tab.cc : Implementation of DLL Exports.
6
7// Need to include this before the ATL headers below.
8#include "chrome_frame/chrome_tab.h"
9
10#include <atlsecurity.h>
11#include <objbase.h>
12
13#include "base/at_exit.h"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000014#include "base/basictypes.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000015#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"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000020#include "base/path_service.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010021#include "base/strings/string16.h"
22#include "base/strings/string_number_conversions.h"
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +010023#include "base/strings/string_piece.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010024#include "base/strings/string_util.h"
Torne (Richard Coles)c2e0dbd2013-05-09 18:35:53 +010025#include "base/strings/sys_string_conversions.h"
Torne (Richard Coles)868fa2f2013-06-11 10:57:03 +010026#include "base/strings/utf_string_conversions.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000027#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"
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000042#include "chrome_frame/pin_module.h"
Torne (Richard Coles)58218062012-11-14 11:43:16 +000043#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"
47
48using base::win::RegKey;
49
50namespace {
Torne (Richard Coles)58218062012-11-14 11:43:16 +000051
52const wchar_t kInternetSettings[] =
53 L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
54
55const wchar_t kProtocolHandlers[] =
56 L"Software\\Classes\\Protocols\\Handler";
57
58const wchar_t kRunOnce[] =
59 L"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
60
61const wchar_t kRunKeyName[] = L"ChromeFrameHelper";
62
63const wchar_t kChromeFrameHelperExe[] = L"chrome_frame_helper.exe";
64const wchar_t kChromeFrameHelperStartupArg[] = L"--startup";
65
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).
70const wchar_t kChromeFrameHelperWindowClassName[] =
71 L"ChromeFrameHelperWindowClass";
72const wchar_t kChromeFrameHelperWindowName[] =
73 L"ChromeFrameHelperWindowName";
74
75// {0562BFC3-2550-45b4-BD8E-A310583D3A6F}
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000076const GUID kChromeFrameProvider =
Torne (Richard Coles)58218062012-11-14 11:43:16 +000077 { 0x562bfc3, 0x2550, 0x45b4,
78 { 0xbd, 0x8e, 0xa3, 0x10, 0x58, 0x3d, 0x3a, 0x6f } };
79
80const wchar_t kPostPlatformUAKey[] =
81 L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\"
82 L"User Agent\\Post Platform";
83const wchar_t kChromeFramePrefix[] = L"chromeframe/";
84
85// See comments in DllGetClassObject.
86LPFNGETCLASSOBJECT g_dll_get_class_object_redir_ptr = NULL;
87
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +000088// 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.
92void InitGoogleUrl() {
93 static const char kDummyUrl[] = "http://www.google.com";
94
95 url_util::IsStandard(kDummyUrl,
96 url_parse::MakeRange(0, arraysize(kDummyUrl)));
97}
98
Torne (Richard Coles)58218062012-11-14 11:43:16 +000099class ChromeTabModule : public CAtlDllModuleT<ChromeTabModule> {
100 public:
101 typedef CAtlDllModuleT<ChromeTabModule> ParentClass;
102
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000103 ChromeTabModule() : do_system_registration_(true), crash_reporting_(NULL) {}
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000104
105 DECLARE_LIBID(LIBID_ChromeTabLib)
106 DECLARE_REGISTRY_APPID_RESOURCEID(IDR_CHROMETAB,
107 "{FD9B1B31-F4D8-436A-8F4F-D3C2E36733D3}")
108
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);
113
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));
122 }
123
124 if (SUCCEEDED(hr)) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000125 base::FilePath app_path =
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000126 chrome_launcher::GetChromeExecutablePath().DirName();
127 hr = registrar->AddReplacement(L"CHROME_APPPATH",
128 app_path.value().c_str());
129 DCHECK(SUCCEEDED(hr));
130 }
131
132 if (SUCCEEDED(hr)) {
133 hr = registrar->AddReplacement(L"CHROME_APPNAME",
134 chrome::kBrowserProcessExecutableName);
135 DCHECK(SUCCEEDED(hr));
136
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));
144 }
145
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;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000150 base::FilePath module_path;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000151 if (PathService::Get(base::FILE_MODULE, &module_path)) {
152 module_dir = module_path.DirName().value();
153 } else {
154 NOTREACHED();
155 }
156 hr = registrar->AddReplacement(L"CHROME_LAUNCHER_APPPATH",
157 module_dir.c_str());
158 DCHECK(SUCCEEDED(hr));
159 }
160
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));
166 }
167
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");
179 }
180 DCHECK(SUCCEEDED(hr));
181 }
182
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]);
188 }
189
190 return hr;
191 }
192
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000193 // 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();
202 }
203 return result;
204 }
205
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;
216 }
217 return result;
218 }
219
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000220 // See comments in AddCommonRGSReplacements
221 bool do_system_registration_;
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000222
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_;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000229};
230
231ChromeTabModule _AtlModule;
232
233base::AtExitManager* g_exit_manager = NULL;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000234
235HRESULT RefreshElevationPolicy() {
236 const wchar_t kIEFrameDll[] = L"ieframe.dll";
237 const char kIERefreshPolicy[] = "IERefreshElevationPolicy";
238 HRESULT hr = E_NOTIMPL;
239
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;
245
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));
251
252 if (ie_refresh_policy) {
253 hr = ie_refresh_policy();
254 } else {
255 hr = HRESULT_FROM_WIN32(GetLastError());
256 }
257
258 FreeLibrary(ieframe_module);
259 } else {
260 hr = HRESULT_FROM_WIN32(GetLastError());
261 }
262
263 return hr;
264}
265
266// Experimental boot prefetch optimization for Chrome Frame
267//
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.
273//
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
279//
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.
289//
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.
292HRESULT SetupRunOnce() {
293 HRESULT result = E_FAIL;
294
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;
307 }
308
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());
318 }
319 result = HRESULT_FROM_WIN32(ret);
320 } else {
321 result = S_FALSE;
322 }
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;
327 }
328
329 return result;
330}
331
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.
335HRESULT SetupUserLevelHelper() {
336 HRESULT hr = S_OK;
337
338 // Remove existing run-at-startup entry.
339 base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER, kRunKeyName);
340
341 // Build the chrome_frame_helper command line.
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000342 base::FilePath module_path;
343 base::FilePath helper_path;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000344 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.";
354 }
355
356 // Find window handle of existing instance.
357 HWND old_window = FindWindow(kChromeFrameHelperWindowClassName,
358 kChromeFrameHelperWindowName);
359
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;
365
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.";
371 }
372
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.";
380 }
381
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: ";
387 }
388 }
389 } else {
390 hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
391 }
392 } else {
393 hr = E_UNEXPECTED;
394 NOTREACHED();
395 }
396
397 return hr;
398}
399
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.
403HRESULT 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;
406
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] = {};
414
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;
429 }
430 } else {
431 break;
432 }
433 }
434
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);
439 }
440 hr = S_OK;
441 } else {
442 DLOG(ERROR) << __FUNCTION__ << ": " << kPostPlatformUAKey
443 << ", error code = " << reg_result;
444 hr = HRESULT_FROM_WIN32(reg_result);
445 }
446 return hr;
447}
448
449class SecurityDescBackup {
450 public:
451 explicit SecurityDescBackup(const std::wstring& backup_key)
452 : backup_key_name_(backup_key) {}
453 ~SecurityDescBackup() {}
454
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;
460
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;
465 }
466
467 return false;
468 }
469
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;
475
476 // Create security descriptor from string.
477 CSecurityDesc sd;
478 if (!sd.FromString(sddl.c_str()))
479 return false;
480
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);
487
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);
492
493 DeleteBackupKey();
494 return (error == ERROR_SUCCESS);
495 }
496
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;
503
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));
509
510 if ((len == 0) || (reg_type != REG_SZ))
511 return false;
512
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;
517 }
518
519 return true;
520 }
521
522 void DeleteBackupKey() {
523 ::RegDeleteKey(HKEY_LOCAL_MACHINE, backup_key_name_.c_str());
524 }
525
526 std::wstring backup_key_name_;
527};
528
529struct TokenWithPrivileges {
530 TokenWithPrivileges() {
531 token_.GetEffectiveToken(TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY);
532 token_.GetUser(&user_);
533 }
534
535 ~TokenWithPrivileges() {
536 token_.EnableDisablePrivileges(take_ownership_);
537 token_.EnableDisablePrivileges(restore_);
538 }
539
540 bool EnablePrivileges() {
541 if (take_ownership_.GetCount() == 0)
542 if (!token_.EnablePrivilege(L"SeTakeOwnershipPrivilege",
543 &take_ownership_))
544 return false;
545
546 if (restore_.GetCount() == 0)
547 if (!token_.EnablePrivilege(L"SeRestorePrivilege", &restore_))
548 return false;
549
550 return true;
551 }
552
553 const CSid& GetUser() const {
554 return user_;
555 }
556
557 private:
558 CAccessToken token_;
559 CTokenPrivileges take_ownership_;
560 CTokenPrivileges restore_;
561 CSid user_;
562};
563
564HRESULT 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;
570
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");
579 }
580
581 return result1 != ERROR_SUCCESS ? HRESULT_FROM_WIN32(result1) :
582 HRESULT_FROM_WIN32(result2);
583}
584
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000585void OnPinModule() {
586 // Pin crash reporting by leaking a reference.
587 ignore_result(new chrome_frame::ScopedCrashReporting());
588}
589
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000590// Chrome Frame registration functions.
591//-----------------------------------------------------------------------------
592HRESULT 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);
597 }
598
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);
605
606 TokenWithPrivileges token_;
607 if (!token_.EnablePrivileges())
608 return E_ACCESSDENIED;
609
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());
614
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;
619 }
620
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);
631 }
632 }
633
634 backup.RestoreSecurity(object_name.c_str());
635 return hr;
636}
637
638HRESULT 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);
643}
644
645HRESULT 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);
650}
651
652HRESULT 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();
662 }
663 }
664 return hr;
665}
666
667HRESULT RegisterProtocol(bool reg, bool is_system) {
668 return _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEPROTOCOL, reg);
669}
670
671HRESULT RegisterBhoClsid(bool reg, bool is_system) {
672 return Bho::UpdateRegistry(reg);
673}
674
675HRESULT 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;
689 }
690 }
691}
692
693HRESULT 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)();
705 }
706 }
707 return reg ?
708 UtilRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
709 NULL, !is_system) :
710 UtilUnRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
711 NULL, !is_system);
712}
713
714HRESULT RegisterLegacyNPAPICleanup(bool reg, bool is_system) {
715 if (!reg) {
716 _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_NPAPI, reg);
717 UtilRemovePersistentNPAPIMarker();
718 }
719 // Ignore failures.
720 return S_OK;
721}
722
723HRESULT RegisterAppId(bool reg, bool is_system) {
724 return _AtlModule.UpdateRegistryAppId(reg);
725}
726
727HRESULT RegisterUserAgent(bool reg, bool is_system) {
728 if (reg) {
729 return SetChromeFrameUA(is_system, L"1");
730 } else {
731 return SetChromeFrameUA(is_system, NULL);
732 }
733}
734
735enum 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
748};
749
750enum RegistrationFlags {
751 ACTIVEX = 0x0001,
752 ACTIVEDOC = 0x0002,
753 GCF_PROTOCOL = 0x0004,
754 BHO_CLSID = 0x0008,
755 BHO_REGISTRATION = 0x0010,
756 TYPELIB = 0x0020,
757
758 ALL = 0xFFFF
759};
760
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.
773//
774// The resulting error can be extracted by:
775// error_code = (fiddled_hr & 0x07800000) >> 23
776HRESULT 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);
780
781 // Check that our four desired bits are clear.
782 // 0xF87FFFFF == 11111000011111111111111111111111
783 DCHECK_EQ(static_cast<HRESULT>(hr & 0xF87FFFFF), hr);
784
785 HRESULT fiddled_hr = ((error_code & 0xF) << 23) | hr;
786 fiddled_hr |= 1 << 29; // Set the customer bit.
787
788 return fiddled_hr;
789}
790
791HRESULT CustomRegistration(uint16 reg_flags, bool reg, bool is_system) {
792 if (reg && (reg_flags & (ACTIVEDOC | ACTIVEX)))
793 reg_flags |= (TYPELIB | GCF_PROTOCOL);
794
795 // Set the flag that gets checked in AddCommonRGSReplacements before doing
796 // registration work.
797 _AtlModule.do_system_registration_ = is_system;
798
799 typedef HRESULT (*RegistrationFn)(bool reg, bool is_system);
800 struct RegistrationStep {
801 RegistrationStepId id;
802 uint16 condition;
803 RegistrationFn func;
804 };
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 }
817 };
818
819 HRESULT hr = S_OK;
820
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);
831 }
832
833 // On registration if a step fails, we abort and rollback.
834 if (reg) {
835 rollback = true;
836 failure_step = step;
837 break;
838 }
839 }
840 }
841 }
842
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);
848 }
849 }
850
851 return hr;
852}
853
854} // namespace
855
856// DLL Entry Point
857extern "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();
868
869 g_exit_manager = new base::AtExitManager();
870 CommandLine::Init(0, NULL);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000871 logging::InitLogging(
872 NULL,
873 logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
874 logging::LOCK_LOG_FILE,
875 logging::DELETE_OLD_LOG_FILE,
876 logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
877
878 // Log the same items as Chrome.
879 logging::SetLogItems(true, // enable_process_id
880 true, // enable_thread_id
881 false, // enable_timestamp
882 true); // enable_tickcount
883
884 DllRedirector* dll_redirector = DllRedirector::GetInstance();
885 DCHECK(dll_redirector);
886
887 if (!dll_redirector->RegisterAsFirstCFModule()) {
888 // Someone else was here first, try and get a pointer to their
889 // DllGetClassObject export:
890 g_dll_get_class_object_redir_ptr =
891 dll_redirector->GetDllGetClassObjectPtr();
892 DCHECK(g_dll_get_class_object_redir_ptr != NULL)
893 << "Found CF module with no DllGetClassObject export.";
894 }
895
896 // Enable trace control and transport through event tracing for Windows.
897 logging::LogEventProvider::Initialize(kChromeFrameProvider);
898
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000899 // Set a callback so that crash reporting can be pinned when the module is
900 // pinned.
901 chrome_frame::SetPinModuleCallback(&OnPinModule);
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000902 } else if (reason == DLL_PROCESS_DETACH) {
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000903 DllRedirector* dll_redirector = DllRedirector::GetInstance();
904 DCHECK(dll_redirector);
905 dll_redirector->UnregisterAsFirstCFModule();
906
907 g_patch_helper.UnpatchIfNeeded();
908
909 delete g_exit_manager;
910 g_exit_manager = NULL;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000911 }
912 return _AtlModule.DllMain(reason, reserved);
913}
914
915// Used to determine whether the DLL can be unloaded by OLE
916STDAPI DllCanUnloadNow() {
917 return _AtlModule.DllCanUnloadNow();
918}
919
920// Returns a class factory to create an object of the requested type
921STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000922 chrome_frame::ScopedCrashReporting crash_reporting;
923
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000924 // If we found another module present when we were loaded, then delegate to
925 // that:
926 if (g_dll_get_class_object_redir_ptr) {
927 return g_dll_get_class_object_redir_ptr(rclsid, riid, ppv);
928 }
929
930 // Enable sniffing and switching only if asked for BHO
931 // (we use BHO to get loaded in IE).
932 if (rclsid == CLSID_ChromeFrameBHO) {
933 g_patch_helper.InitializeAndPatchProtocolsIfNeeded();
934 }
935
936 return _AtlModule.DllGetClassObject(rclsid, riid, ppv);
937}
938
939// DllRegisterServer - Adds entries to the system registry
940STDAPI DllRegisterServer() {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000941 chrome_frame::ScopedCrashReporting crash_reporting;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000942 uint16 flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
943 BHO_CLSID | BHO_REGISTRATION;
944
945 HRESULT hr = CustomRegistration(flags, true, true);
946 if (SUCCEEDED(hr)) {
947 SetupRunOnce();
948 }
949
950 return hr;
951}
952
953// DllUnregisterServer - Removes entries from the system registry
954STDAPI DllUnregisterServer() {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000955 chrome_frame::ScopedCrashReporting crash_reporting;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000956 HRESULT hr = CustomRegistration(ALL, false, true);
957 return hr;
958}
959
960// DllRegisterUserServer - Adds entries to the HKCU hive in the registry.
961STDAPI DllRegisterUserServer() {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000962 chrome_frame::ScopedCrashReporting crash_reporting;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000963 UINT flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
964 BHO_CLSID | BHO_REGISTRATION;
965
966 HRESULT hr = CustomRegistration(flags, TRUE, false);
967 if (SUCCEEDED(hr)) {
968 SetupRunOnce();
969 }
970
971 return hr;
972}
973
974// DllUnregisterUserServer - Removes entries from the HKCU hive in the registry.
975STDAPI DllUnregisterUserServer() {
Torne (Richard Coles)2a99a7e2013-03-28 15:31:22 +0000976 chrome_frame::ScopedCrashReporting crash_reporting;
Torne (Richard Coles)58218062012-11-14 11:43:16 +0000977 HRESULT hr = CustomRegistration(ALL, FALSE, false);
978 return hr;
979}
980
981// Object entries go here instead of with each object, so that we can move
982// the objects to a lib. Also reduces magic.
983OBJECT_ENTRY_AUTO(CLSID_ChromeFrameBHO, Bho)
984OBJECT_ENTRY_AUTO(__uuidof(ChromeActiveDocument), ChromeActiveDocument)
985OBJECT_ENTRY_AUTO(__uuidof(ChromeFrame), ChromeFrameActivex)
986OBJECT_ENTRY_AUTO(__uuidof(ChromeProtocol), ChromeProtocol)