blob: 2611d69c1c92273bdc632aa6d56c9da47b555706 [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"
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"
47
48using base::win::RegKey;
49
50namespace {
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.
55void InitGoogleUrl() {
56 static const char kDummyUrl[] = "http://www.google.com";
57
58 url_util::IsStandard(kDummyUrl,
59 url_parse::MakeRange(0, arraysize(kDummyUrl)));
60}
61
62const wchar_t kInternetSettings[] =
63 L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
64
65const wchar_t kProtocolHandlers[] =
66 L"Software\\Classes\\Protocols\\Handler";
67
68const wchar_t kRunOnce[] =
69 L"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
70
71const wchar_t kRunKeyName[] = L"ChromeFrameHelper";
72
73const wchar_t kChromeFrameHelperExe[] = L"chrome_frame_helper.exe";
74const wchar_t kChromeFrameHelperStartupArg[] = L"--startup";
75
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).
80const wchar_t kChromeFrameHelperWindowClassName[] =
81 L"ChromeFrameHelperWindowClass";
82const wchar_t kChromeFrameHelperWindowName[] =
83 L"ChromeFrameHelperWindowName";
84
85// {0562BFC3-2550-45b4-BD8E-A310583D3A6F}
86static const GUID kChromeFrameProvider =
87 { 0x562bfc3, 0x2550, 0x45b4,
88 { 0xbd, 0x8e, 0xa3, 0x10, 0x58, 0x3d, 0x3a, 0x6f } };
89
90const wchar_t kPostPlatformUAKey[] =
91 L"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\"
92 L"User Agent\\Post Platform";
93const wchar_t kChromeFramePrefix[] = L"chromeframe/";
94
95// See comments in DllGetClassObject.
96LPFNGETCLASSOBJECT g_dll_get_class_object_redir_ptr = NULL;
97
98class ChromeTabModule : public CAtlDllModuleT<ChromeTabModule> {
99 public:
100 typedef CAtlDllModuleT<ChromeTabModule> ParentClass;
101
102 ChromeTabModule() : do_system_registration_(true) {}
103
104 DECLARE_LIBID(LIBID_ChromeTabLib)
105 DECLARE_REGISTRY_APPID_RESOURCEID(IDR_CHROMETAB,
106 "{FD9B1B31-F4D8-436A-8F4F-D3C2E36733D3}")
107
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);
112
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));
121 }
122
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));
129 }
130
131 if (SUCCEEDED(hr)) {
132 hr = registrar->AddReplacement(L"CHROME_APPNAME",
133 chrome::kBrowserProcessExecutableName);
134 DCHECK(SUCCEEDED(hr));
135
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));
143 }
144
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();
154 }
155 hr = registrar->AddReplacement(L"CHROME_LAUNCHER_APPPATH",
156 module_dir.c_str());
157 DCHECK(SUCCEEDED(hr));
158 }
159
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));
165 }
166
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");
178 }
179 DCHECK(SUCCEEDED(hr));
180 }
181
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]);
187 }
188
189 return hr;
190 }
191
192 // See comments in AddCommonRGSReplacements
193 bool do_system_registration_;
194};
195
196ChromeTabModule _AtlModule;
197
198base::AtExitManager* g_exit_manager = NULL;
199base::FieldTrialList* g_field_trial_list = NULL;
200
201HRESULT RefreshElevationPolicy() {
202 const wchar_t kIEFrameDll[] = L"ieframe.dll";
203 const char kIERefreshPolicy[] = "IERefreshElevationPolicy";
204 HRESULT hr = E_NOTIMPL;
205
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;
211
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));
217
218 if (ie_refresh_policy) {
219 hr = ie_refresh_policy();
220 } else {
221 hr = HRESULT_FROM_WIN32(GetLastError());
222 }
223
224 FreeLibrary(ieframe_module);
225 } else {
226 hr = HRESULT_FROM_WIN32(GetLastError());
227 }
228
229 return hr;
230}
231
232// Experimental boot prefetch optimization for Chrome Frame
233//
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.
239//
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
245//
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.
255//
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.
258HRESULT SetupRunOnce() {
259 HRESULT result = E_FAIL;
260
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;
273 }
274
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());
284 }
285 result = HRESULT_FROM_WIN32(ret);
286 } else {
287 result = S_FALSE;
288 }
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;
293 }
294
295 return result;
296}
297
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.
301HRESULT SetupUserLevelHelper() {
302 HRESULT hr = S_OK;
303
304 // Remove existing run-at-startup entry.
305 base::win::RemoveCommandFromAutoRun(HKEY_CURRENT_USER, kRunKeyName);
306
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.";
320 }
321
322 // Find window handle of existing instance.
323 HWND old_window = FindWindow(kChromeFrameHelperWindowClassName,
324 kChromeFrameHelperWindowName);
325
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;
331
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.";
337 }
338
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.";
346 }
347
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: ";
353 }
354 }
355 } else {
356 hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
357 }
358 } else {
359 hr = E_UNEXPECTED;
360 NOTREACHED();
361 }
362
363 return hr;
364}
365
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.
369HRESULT 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;
372
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] = {};
380
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;
395 }
396 } else {
397 break;
398 }
399 }
400
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);
405 }
406 hr = S_OK;
407 } else {
408 DLOG(ERROR) << __FUNCTION__ << ": " << kPostPlatformUAKey
409 << ", error code = " << reg_result;
410 hr = HRESULT_FROM_WIN32(reg_result);
411 }
412 return hr;
413}
414
415class SecurityDescBackup {
416 public:
417 explicit SecurityDescBackup(const std::wstring& backup_key)
418 : backup_key_name_(backup_key) {}
419 ~SecurityDescBackup() {}
420
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;
426
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;
431 }
432
433 return false;
434 }
435
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;
441
442 // Create security descriptor from string.
443 CSecurityDesc sd;
444 if (!sd.FromString(sddl.c_str()))
445 return false;
446
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);
453
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);
458
459 DeleteBackupKey();
460 return (error == ERROR_SUCCESS);
461 }
462
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;
469
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));
475
476 if ((len == 0) || (reg_type != REG_SZ))
477 return false;
478
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;
483 }
484
485 return true;
486 }
487
488 void DeleteBackupKey() {
489 ::RegDeleteKey(HKEY_LOCAL_MACHINE, backup_key_name_.c_str());
490 }
491
492 std::wstring backup_key_name_;
493};
494
495struct TokenWithPrivileges {
496 TokenWithPrivileges() {
497 token_.GetEffectiveToken(TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY);
498 token_.GetUser(&user_);
499 }
500
501 ~TokenWithPrivileges() {
502 token_.EnableDisablePrivileges(take_ownership_);
503 token_.EnableDisablePrivileges(restore_);
504 }
505
506 bool EnablePrivileges() {
507 if (take_ownership_.GetCount() == 0)
508 if (!token_.EnablePrivilege(L"SeTakeOwnershipPrivilege",
509 &take_ownership_))
510 return false;
511
512 if (restore_.GetCount() == 0)
513 if (!token_.EnablePrivilege(L"SeRestorePrivilege", &restore_))
514 return false;
515
516 return true;
517 }
518
519 const CSid& GetUser() const {
520 return user_;
521 }
522
523 private:
524 CAccessToken token_;
525 CTokenPrivileges take_ownership_;
526 CTokenPrivileges restore_;
527 CSid user_;
528};
529
530HRESULT 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;
536
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");
545 }
546
547 return result1 != ERROR_SUCCESS ? HRESULT_FROM_WIN32(result1) :
548 HRESULT_FROM_WIN32(result2);
549}
550
551// Chrome Frame registration functions.
552//-----------------------------------------------------------------------------
553HRESULT 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);
558 }
559
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);
566
567 TokenWithPrivileges token_;
568 if (!token_.EnablePrivileges())
569 return E_ACCESSDENIED;
570
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());
575
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;
580 }
581
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);
592 }
593 }
594
595 backup.RestoreSecurity(object_name.c_str());
596 return hr;
597}
598
599HRESULT 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);
604}
605
606HRESULT 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);
611}
612
613HRESULT 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();
623 }
624 }
625 return hr;
626}
627
628HRESULT RegisterProtocol(bool reg, bool is_system) {
629 return _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEPROTOCOL, reg);
630}
631
632HRESULT RegisterBhoClsid(bool reg, bool is_system) {
633 return Bho::UpdateRegistry(reg);
634}
635
636HRESULT 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;
650 }
651 }
652}
653
654HRESULT 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)();
666 }
667 }
668 return reg ?
669 UtilRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
670 NULL, !is_system) :
671 UtilUnRegisterTypeLib(_AtlComModule.m_hInstTypeLib,
672 NULL, !is_system);
673}
674
675HRESULT RegisterLegacyNPAPICleanup(bool reg, bool is_system) {
676 if (!reg) {
677 _AtlModule.UpdateRegistryFromResourceS(IDR_CHROMEFRAME_NPAPI, reg);
678 UtilRemovePersistentNPAPIMarker();
679 }
680 // Ignore failures.
681 return S_OK;
682}
683
684HRESULT RegisterAppId(bool reg, bool is_system) {
685 return _AtlModule.UpdateRegistryAppId(reg);
686}
687
688HRESULT RegisterUserAgent(bool reg, bool is_system) {
689 if (reg) {
690 return SetChromeFrameUA(is_system, L"1");
691 } else {
692 return SetChromeFrameUA(is_system, NULL);
693 }
694}
695
696enum 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
709};
710
711enum RegistrationFlags {
712 ACTIVEX = 0x0001,
713 ACTIVEDOC = 0x0002,
714 GCF_PROTOCOL = 0x0004,
715 BHO_CLSID = 0x0008,
716 BHO_REGISTRATION = 0x0010,
717 TYPELIB = 0x0020,
718
719 ALL = 0xFFFF
720};
721
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.
734//
735// The resulting error can be extracted by:
736// error_code = (fiddled_hr & 0x07800000) >> 23
737HRESULT 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);
741
742 // Check that our four desired bits are clear.
743 // 0xF87FFFFF == 11111000011111111111111111111111
744 DCHECK_EQ(static_cast<HRESULT>(hr & 0xF87FFFFF), hr);
745
746 HRESULT fiddled_hr = ((error_code & 0xF) << 23) | hr;
747 fiddled_hr |= 1 << 29; // Set the customer bit.
748
749 return fiddled_hr;
750}
751
752HRESULT CustomRegistration(uint16 reg_flags, bool reg, bool is_system) {
753 if (reg && (reg_flags & (ACTIVEDOC | ACTIVEX)))
754 reg_flags |= (TYPELIB | GCF_PROTOCOL);
755
756 // Set the flag that gets checked in AddCommonRGSReplacements before doing
757 // registration work.
758 _AtlModule.do_system_registration_ = is_system;
759
760 typedef HRESULT (*RegistrationFn)(bool reg, bool is_system);
761 struct RegistrationStep {
762 RegistrationStepId id;
763 uint16 condition;
764 RegistrationFn func;
765 };
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 }
778 };
779
780 HRESULT hr = S_OK;
781
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);
792 }
793
794 // On registration if a step fails, we abort and rollback.
795 if (reg) {
796 rollback = true;
797 failure_step = step;
798 break;
799 }
800 }
801 }
802 }
803
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);
809 }
810 }
811
812 return hr;
813}
814
815} // namespace
816
817// DLL Entry Point
818extern "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();
829
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);
839
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
845
846 DllRedirector* dll_redirector = DllRedirector::GetInstance();
847 DCHECK(dll_redirector);
848
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.";
856 }
857
858 // Enable trace control and transport through event tracing for Windows.
859 logging::LogEventProvider::Initialize(kChromeFrameProvider);
860
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;
868
869 DllRedirector* dll_redirector = DllRedirector::GetInstance();
870 DCHECK(dll_redirector);
871 dll_redirector->UnregisterAsFirstCFModule();
872
873 g_patch_helper.UnpatchIfNeeded();
874
875 delete g_exit_manager;
876 g_exit_manager = NULL;
877
878 ShutdownCrashReporting();
879 }
880 return _AtlModule.DllMain(reason, reserved);
881}
882
883// Used to determine whether the DLL can be unloaded by OLE
884STDAPI DllCanUnloadNow() {
885 return _AtlModule.DllCanUnloadNow();
886}
887
888// Returns a class factory to create an object of the requested type
889STDAPI 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);
894 }
895
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();
900 }
901
902 return _AtlModule.DllGetClassObject(rclsid, riid, ppv);
903}
904
905// DllRegisterServer - Adds entries to the system registry
906STDAPI DllRegisterServer() {
907 uint16 flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
908 BHO_CLSID | BHO_REGISTRATION;
909
910 HRESULT hr = CustomRegistration(flags, true, true);
911 if (SUCCEEDED(hr)) {
912 SetupRunOnce();
913 }
914
915 return hr;
916}
917
918// DllUnregisterServer - Removes entries from the system registry
919STDAPI DllUnregisterServer() {
920 HRESULT hr = CustomRegistration(ALL, false, true);
921 return hr;
922}
923
924// DllRegisterUserServer - Adds entries to the HKCU hive in the registry.
925STDAPI DllRegisterUserServer() {
926 UINT flags = ACTIVEX | ACTIVEDOC | TYPELIB | GCF_PROTOCOL |
927 BHO_CLSID | BHO_REGISTRATION;
928
929 HRESULT hr = CustomRegistration(flags, TRUE, false);
930 if (SUCCEEDED(hr)) {
931 SetupRunOnce();
932 }
933
934 return hr;
935}
936
937// DllUnregisterUserServer - Removes entries from the HKCU hive in the registry.
938STDAPI DllUnregisterUserServer() {
939 HRESULT hr = CustomRegistration(ALL, FALSE, false);
940 return hr;
941}
942
943// Object entries go here instead of with each object, so that we can move
944// the objects to a lib. Also reduces magic.
945OBJECT_ENTRY_AUTO(CLSID_ChromeFrameBHO, Bho)
946OBJECT_ENTRY_AUTO(__uuidof(ChromeActiveDocument), ChromeActiveDocument)
947OBJECT_ENTRY_AUTO(__uuidof(ChromeFrame), ChromeFrameActivex)
948OBJECT_ENTRY_AUTO(__uuidof(ChromeProtocol), ChromeProtocol)