1 // Copyright (c) 2010 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 #include "chrome_frame/chrome_frame_activex.h"
12 #include "base/basictypes.h"
13 #include "base/command_line.h"
14 #include "base/file_util.h"
15 #include "base/logging.h"
16 #include "base/path_service.h"
17 #include "base/process_util.h"
18 #include "base/scoped_bstr_win.h"
19 #include "base/singleton.h"
20 #include "base/string_util.h"
21 #include "base/trace_event.h"
22 #include "chrome/common/chrome_constants.h"
23 #include "chrome/common/chrome_switches.h"
24 #include "chrome/test/automation/tab_proxy.h"
25 #include "googleurl/src/gurl.h"
26 #include "chrome_frame/utils.h"
30 // Class used to maintain a mapping from top-level windows to ChromeFrameActivex
32 class TopLevelWindowMapping
{
34 typedef std::vector
<HWND
> WindowList
;
36 static TopLevelWindowMapping
* instance() {
37 return Singleton
<TopLevelWindowMapping
>::get();
40 // Add |cf_window| to the set of windows registered under |top_window|.
41 void AddMapping(HWND top_window
, HWND cf_window
) {
42 top_window_map_lock_
.Lock();
43 top_window_map_
[top_window
].push_back(cf_window
);
44 top_window_map_lock_
.Unlock();
47 // Return the set of Chrome-Frame instances under |window|.
48 WindowList
GetInstances(HWND window
) {
49 top_window_map_lock_
.Lock();
50 WindowList list
= top_window_map_
[window
];
51 top_window_map_lock_
.Unlock();
56 // Constructor is private as this class it to be used as a singleton.
57 // See static method instance().
58 TopLevelWindowMapping() {}
60 friend struct DefaultSingletonTraits
<TopLevelWindowMapping
>;
62 typedef std::map
<HWND
, WindowList
> TopWindowMap
;
63 TopWindowMap top_window_map_
;
65 CComAutoCriticalSection top_window_map_lock_
;
67 DISALLOW_COPY_AND_ASSIGN(TopLevelWindowMapping
);
70 // Message pump hook function that monitors for WM_MOVE and WM_MOVING
71 // messages on a top-level window, and passes notification to the appropriate
72 // Chrome-Frame instances.
73 LRESULT CALLBACK
TopWindowProc(int code
, WPARAM wparam
, LPARAM lparam
) {
74 CWPSTRUCT
*info
= reinterpret_cast<CWPSTRUCT
*>(lparam
);
75 const UINT
&message
= info
->message
;
76 const HWND
&message_hwnd
= info
->hwnd
;
81 TopLevelWindowMapping::WindowList cf_instances
=
82 TopLevelWindowMapping::instance()->GetInstances(message_hwnd
);
83 TopLevelWindowMapping::WindowList::iterator
84 iter(cf_instances
.begin()), end(cf_instances
.end());
85 for (;iter
!= end
; ++iter
) {
86 PostMessage(*iter
, WM_HOST_MOVED_NOTIFICATION
, NULL
, NULL
);
94 return CallNextHookEx(0, code
, wparam
, lparam
);
97 HHOOK
InstallLocalWindowHook(HWND window
) {
101 DWORD proc_thread
= ::GetWindowThreadProcessId(window
, NULL
);
105 // Note that this hook is installed as a LOCAL hook.
106 return ::SetWindowsHookEx(WH_CALLWNDPROC
,
112 } // unnamed namespace
114 ChromeFrameActivex::ChromeFrameActivex()
115 : chrome_wndproc_hook_(NULL
) {
116 TRACE_EVENT_BEGIN("chromeframe.createactivex", this, "");
119 HRESULT
ChromeFrameActivex::FinalConstruct() {
120 HRESULT hr
= Base::FinalConstruct();
124 // No need to call FireOnChanged at this point since nobody will be listening.
125 ready_state_
= READYSTATE_LOADING
;
129 ChromeFrameActivex::~ChromeFrameActivex() {
130 // We expect these to be released during a call to SetClientSite(NULL).
131 DCHECK_EQ(0u, onmessage_
.size());
132 DCHECK_EQ(0u, onloaderror_
.size());
133 DCHECK_EQ(0u, onload_
.size());
134 DCHECK_EQ(0u, onreadystatechanged_
.size());
135 DCHECK_EQ(0u, onextensionready_
.size());
137 if (chrome_wndproc_hook_
) {
138 BOOL unhook_success
= ::UnhookWindowsHookEx(chrome_wndproc_hook_
);
139 DCHECK(unhook_success
);
142 // ChromeFramePlugin::Uninitialize()
143 Base::Uninitialize();
145 TRACE_EVENT_END("chromeframe.createactivex", this, "");
148 LRESULT
ChromeFrameActivex::OnCreate(UINT message
, WPARAM wparam
, LPARAM lparam
,
150 Base::OnCreate(message
, wparam
, lparam
, handled
);
151 // Install the notification hook on the top-level window, so that we can
152 // be notified on move events. Note that the return value is not checked.
153 // This hook is installed here, as opposed to during IOleObject_SetClientSite
154 // because m_hWnd has not yet been assigned during the SetSite call.
155 InstallTopLevelHook(m_spClientSite
);
159 LRESULT
ChromeFrameActivex::OnHostMoved(UINT message
, WPARAM wparam
,
160 LPARAM lparam
, BOOL
& handled
) {
165 HRESULT
ChromeFrameActivex::GetContainingDocument(IHTMLDocument2
** doc
) {
166 ScopedComPtr
<IOleContainer
> container
;
167 HRESULT hr
= m_spClientSite
->GetContainer(container
.Receive());
169 hr
= container
.QueryInterface(doc
);
173 HRESULT
ChromeFrameActivex::GetDocumentWindow(IHTMLWindow2
** window
) {
174 ScopedComPtr
<IHTMLDocument2
> document
;
175 HRESULT hr
= GetContainingDocument(document
.Receive());
177 hr
= document
->get_parentWindow(window
);
181 void ChromeFrameActivex::OnLoad(int tab_handle
, const GURL
& gurl
) {
182 ScopedComPtr
<IDispatch
> event
;
183 std::string url
= gurl
.spec();
184 if (SUCCEEDED(CreateDomEvent("event", url
, "", event
.Receive())))
187 FireEvent(onload_
, url
);
188 Base::OnLoad(tab_handle
, gurl
);
191 void ChromeFrameActivex::OnLoadFailed(int error_code
, const std::string
& url
) {
192 ScopedComPtr
<IDispatch
> event
;
193 if (SUCCEEDED(CreateDomEvent("event", url
, "", event
.Receive())))
194 Fire_onloaderror(event
);
196 FireEvent(onloaderror_
, url
);
197 Base::OnLoadFailed(error_code
, url
);
200 void ChromeFrameActivex::OnMessageFromChromeFrame(int tab_handle
,
201 const std::string
& message
,
202 const std::string
& origin
,
203 const std::string
& target
) {
204 DLOG(INFO
) << __FUNCTION__
;
206 if (target
.compare("*") != 0) {
209 if (is_privileged_
) {
210 // Forward messages if the control is in privileged mode.
211 ScopedComPtr
<IDispatch
> message_event
;
212 if (SUCCEEDED(CreateDomEvent("message", message
, origin
,
213 message_event
.Receive()))) {
214 ScopedBstr
target_bstr(UTF8ToWide(target
).c_str());
215 Fire_onprivatemessage(message_event
, target_bstr
);
217 FireEvent(onprivatemessage_
, message_event
, target_bstr
);
220 if (HaveSameOrigin(target
, document_url_
)) {
223 DLOG(WARNING
) << "Dropping posted message since target doesn't match "
224 "the current document's origin. target=" << target
;
232 ScopedComPtr
<IDispatch
> message_event
;
233 if (SUCCEEDED(CreateDomEvent("message", message
, origin
,
234 message_event
.Receive()))) {
235 Fire_onmessage(message_event
);
237 FireEvent(onmessage_
, message_event
);
239 ScopedVariant event_var
;
240 event_var
.Set(static_cast<IDispatch
*>(message_event
));
241 InvokeScriptFunction(onmessage_handler_
, event_var
.AsInput());
245 void ChromeFrameActivex::OnAutomationServerLaunchFailed(
246 AutomationLaunchResult reason
, const std::string
& server_version
) {
247 Base::OnAutomationServerLaunchFailed(reason
, server_version
);
249 if (reason
== AUTOMATION_VERSION_MISMATCH
) {
250 DisplayVersionMismatchWarning(m_hWnd
, server_version
);
254 void ChromeFrameActivex::OnExtensionInstalled(
255 const FilePath
& path
,
257 AutomationMsg_ExtensionResponseValues response
) {
258 ScopedBstr
path_str(path
.value().c_str());
259 Fire_onextensionready(path_str
, response
);
262 void ChromeFrameActivex::OnGetEnabledExtensionsComplete(
264 const std::vector
<FilePath
>& extension_directories
) {
265 SAFEARRAY
* sa
= ::SafeArrayCreateVector(VT_BSTR
, 0,
266 extension_directories
.size());
267 sa
->fFeatures
= sa
->fFeatures
| FADF_BSTR
;
270 for (size_t i
= 0; i
< extension_directories
.size(); ++i
) {
271 LONG index
= static_cast<LONG
>(i
);
272 ::SafeArrayPutElement(sa
, &index
, reinterpret_cast<void*>(
273 CComBSTR(extension_directories
[i
].value().c_str()).Detach()));
276 Fire_ongetenabledextensionscomplete(sa
);
277 ::SafeArrayUnlock(sa
);
278 ::SafeArrayDestroy(sa
);
281 void ChromeFrameActivex::OnChannelError() {
282 Fire_onchannelerror();
285 HRESULT
ChromeFrameActivex::OnDraw(ATL_DRAWINFO
& draw_info
) { // NOLINT
287 int dc_type
= ::GetObjectType(draw_info
.hicTargetDev
);
288 if (dc_type
== OBJ_ENHMETADC
) {
289 RECT print_bounds
= {0};
290 print_bounds
.left
= draw_info
.prcBounds
->left
;
291 print_bounds
.right
= draw_info
.prcBounds
->right
;
292 print_bounds
.top
= draw_info
.prcBounds
->top
;
293 print_bounds
.bottom
= draw_info
.prcBounds
->bottom
;
295 automation_client_
->Print(draw_info
.hdcDraw
, print_bounds
);
297 hr
= Base::OnDraw(draw_info
);
303 STDMETHODIMP
ChromeFrameActivex::Load(IPropertyBag
* bag
, IErrorLog
* error_log
) {
306 const wchar_t* event_props
[] = {
310 (L
"onreadystatechanged"),
313 ScopedComPtr
<IHTMLObjectElement
> obj_element
;
314 GetObjectElement(obj_element
.Receive());
316 ScopedBstr object_id
;
317 GetObjectScriptId(obj_element
, object_id
.Receive());
319 ScopedComPtr
<IHTMLElement2
> element
;
320 element
.QueryFrom(obj_element
);
323 for (int i
= 0; SUCCEEDED(hr
) && i
< arraysize(event_props
); ++i
) {
324 ScopedBstr
prop(event_props
[i
]);
326 if (SUCCEEDED(bag
->Read(prop
, value
.Receive(), error_log
))) {
327 if (value
.type() != VT_BSTR
||
328 FAILED(hr
= CreateScriptBlockForEvent(element
, object_id
,
329 V_BSTR(&value
), prop
))) {
330 DLOG(ERROR
) << "Failed to create script block for " << prop
331 << StringPrintf(L
"hr=0x%08X, vt=%i", hr
, value
.type());
333 DLOG(INFO
) << "script block created for event " << prop
<<
334 StringPrintf(" (0x%08X)", hr
) << " connections: " <<
335 ProxyDIChromeFrameEvents
<ChromeFrameActivex
>::m_vec
.GetSize();
338 DLOG(INFO
) << "event property " << prop
<< " not in property bag";
343 if (SUCCEEDED(bag
->Read(StackBstr(L
"src"), src
.Receive(), error_log
))) {
344 if (src
.type() == VT_BSTR
) {
345 hr
= put_src(V_BSTR(&src
));
346 DCHECK(hr
!= E_UNEXPECTED
);
350 ScopedVariant use_chrome_network
;
351 if (SUCCEEDED(bag
->Read(StackBstr(L
"useChromeNetwork"),
352 use_chrome_network
.Receive(), error_log
))) {
353 VariantChangeType(use_chrome_network
.AsInput(),
354 use_chrome_network
.AsInput(),
356 if (use_chrome_network
.type() == VT_BOOL
) {
357 hr
= put_useChromeNetwork(V_BOOL(&use_chrome_network
));
358 DCHECK(hr
!= E_UNEXPECTED
);
362 DLOG_IF(ERROR
, FAILED(hr
))
363 << StringPrintf("Failed to load property bag: 0x%08X", hr
);
368 const wchar_t g_activex_insecure_content_error
[] = {
369 L
"data:text/html,<html><body><b>ChromeFrame Security Error<br><br>"
370 L
"Cannot navigate to HTTP url when document URL is HTTPS</body></html>"};
372 STDMETHODIMP
ChromeFrameActivex::put_src(BSTR src
) {
373 GURL
document_url(GetDocumentUrl());
374 if (document_url
.SchemeIsSecure()) {
375 GURL
source_url(src
);
376 if (!source_url
.SchemeIsSecure()) {
377 Base::put_src(ScopedBstr(g_activex_insecure_content_error
));
378 return E_ACCESSDENIED
;
381 return Base::put_src(src
);
384 HRESULT
ChromeFrameActivex::IOleObject_SetClientSite(
385 IOleClientSite
* client_site
) {
386 HRESULT hr
= Base::IOleObject_SetClientSite(client_site
);
387 if (FAILED(hr
) || !client_site
) {
388 EventHandlers
* handlers
[] = {
392 &onreadystatechanged_
,
396 for (int i
= 0; i
< arraysize(handlers
); ++i
)
397 handlers
[i
]->clear();
399 // Drop privileged mode on uninitialization.
400 is_privileged_
= false;
402 ScopedComPtr
<IHTMLDocument2
> document
;
403 GetContainingDocument(document
.Receive());
406 if (SUCCEEDED(document
->get_URL(url
.Receive())))
407 WideToUTF8(url
, url
.Length(), &document_url_
);
410 // Probe to see whether the host implements the privileged service.
411 ScopedComPtr
<IChromeFramePrivileged
> service
;
412 HRESULT service_hr
= DoQueryService(SID_ChromeFramePrivileged
,
415 if (SUCCEEDED(service_hr
) && service
) {
416 // Does the host want privileged mode?
417 boolean wants_privileged
= false;
418 service_hr
= service
->GetWantsPrivileged(&wants_privileged
);
420 if (SUCCEEDED(service_hr
) && wants_privileged
)
421 is_privileged_
= true;
423 url_fetcher_
->set_privileged_mode(is_privileged_
);
426 std::wstring chrome_extra_arguments
;
427 std::wstring
profile_name(GetHostProcessName(false));
428 if (is_privileged_
) {
429 // Does the host want to provide extra arguments?
430 ScopedBstr extra_arguments_arg
;
431 service_hr
= service
->GetChromeExtraArguments(
432 extra_arguments_arg
.Receive());
433 if (S_OK
== service_hr
&& extra_arguments_arg
)
434 chrome_extra_arguments
.assign(extra_arguments_arg
,
435 extra_arguments_arg
.Length());
437 ScopedBstr automated_functions_arg
;
438 service_hr
= service
->GetExtensionApisToAutomate(
439 automated_functions_arg
.Receive());
440 if (S_OK
== service_hr
&& automated_functions_arg
) {
441 std::string
automated_functions(
442 WideToASCII(static_cast<BSTR
>(automated_functions_arg
)));
443 functions_enabled_
.clear();
444 // SplitString writes one empty entry for blank strings, so we need this
445 // to allow specifying zero automation of API functions.
446 if (!automated_functions
.empty())
447 SplitString(automated_functions
, ',', &functions_enabled_
);
450 ScopedBstr profile_name_arg
;
451 service_hr
= service
->GetChromeProfileName(profile_name_arg
.Receive());
452 if (S_OK
== service_hr
&& profile_name_arg
)
453 profile_name
.assign(profile_name_arg
, profile_name_arg
.Length());
456 std::string utf8_url
;
458 WideToUTF8(url_
, url_
.Length(), &utf8_url
);
461 url_fetcher_
->set_frame_busting(!is_privileged_
);
462 automation_client_
->SetUrlFetcher(url_fetcher_
.get());
463 if (!InitializeAutomation(profile_name
, chrome_extra_arguments
,
464 IsIEInPrivate(), true, GURL(utf8_url
),
466 DLOG(ERROR
) << "Failed to navigate to url:" << utf8_url
;
474 HRESULT
ChromeFrameActivex::GetObjectScriptId(IHTMLObjectElement
* object_elem
,
476 DCHECK(object_elem
!= NULL
);
481 ScopedComPtr
<IHTMLElement
> elem
;
482 hr
= elem
.QueryFrom(object_elem
);
484 hr
= elem
->get_id(id
);
491 HRESULT
ChromeFrameActivex::GetObjectElement(IHTMLObjectElement
** element
) {
492 DCHECK(m_spClientSite
);
496 ScopedComPtr
<IOleControlSite
> site
;
497 HRESULT hr
= site
.QueryFrom(m_spClientSite
);
499 ScopedComPtr
<IDispatch
> disp
;
500 hr
= site
->GetExtendedControl(disp
.Receive());
502 hr
= disp
.QueryInterface(element
);
511 HRESULT
ChromeFrameActivex::CreateScriptBlockForEvent(
512 IHTMLElement2
* insert_after
, BSTR instance_id
, BSTR script
,
514 DCHECK(insert_after
);
515 DCHECK_GT(::SysStringLen(event_name
), 0UL); // should always have this
517 // This might be 0 if not specified in the HTML document.
518 if (!::SysStringLen(instance_id
)) {
519 // TODO(tommi): Should we give ourselves an ID if this happens?
520 NOTREACHED() << "Need to handle this";
524 ScopedComPtr
<IHTMLDocument2
> document
;
525 HRESULT hr
= GetContainingDocument(document
.Receive());
527 ScopedComPtr
<IHTMLElement
> element
, new_element
;
528 document
->createElement(StackBstr(L
"script"), element
.Receive());
530 ScopedComPtr
<IHTMLScriptElement
> script_element
;
531 if (SUCCEEDED(hr
= script_element
.QueryFrom(element
))) {
532 script_element
->put_htmlFor(instance_id
);
533 script_element
->put_event(event_name
);
534 script_element
->put_text(script
);
536 hr
= insert_after
->insertAdjacentElement(StackBstr(L
"afterEnd"),
538 new_element
.Receive());
546 void ChromeFrameActivex::FireEvent(const EventHandlers
& handlers
,
547 const std::string
& arg
) {
548 if (handlers
.size()) {
549 ScopedComPtr
<IDispatch
> event
;
550 if (SUCCEEDED(CreateDomEvent("event", arg
, "", event
.Receive()))) {
551 FireEvent(handlers
, event
);
556 void ChromeFrameActivex::FireEvent(const EventHandlers
& handlers
,
558 DCHECK(event
!= NULL
);
559 VARIANT arg
= { VT_DISPATCH
};
560 arg
.pdispVal
= event
;
561 DISPPARAMS params
= { &arg
, NULL
, 1, 0 };
562 for (EventHandlers::const_iterator it
= handlers
.begin();
563 it
!= handlers
.end();
565 HRESULT hr
= (*it
)->Invoke(DISPID_VALUE
, IID_NULL
, LOCALE_USER_DEFAULT
,
566 DISPATCH_METHOD
, ¶ms
, NULL
, NULL
, NULL
);
567 // 0x80020101 == SCRIPT_E_REPORTED.
568 // When the script we're invoking has an error, we get this error back.
569 DLOG_IF(ERROR
, FAILED(hr
) && hr
!= 0x80020101)
570 << StringPrintf(L
"Failed to invoke script: 0x%08X", hr
);
574 void ChromeFrameActivex::FireEvent(const EventHandlers
& handlers
,
575 IDispatch
* event
, BSTR target
) {
576 DCHECK(event
!= NULL
);
577 // Arguments in reverse order to event handler function declaration,
578 // because that's what DISPPARAMS requires.
579 VARIANT args
[2] = { { VT_BSTR
}, { VT_DISPATCH
}, };
580 args
[0].bstrVal
= target
;
581 args
[1].pdispVal
= event
;
582 DISPPARAMS params
= { args
, NULL
, arraysize(args
), 0 };
583 for (EventHandlers::const_iterator it
= handlers
.begin();
584 it
!= handlers
.end();
586 HRESULT hr
= (*it
)->Invoke(DISPID_VALUE
, IID_NULL
, LOCALE_USER_DEFAULT
,
587 DISPATCH_METHOD
, ¶ms
, NULL
, NULL
, NULL
);
588 // 0x80020101 == SCRIPT_E_REPORTED.
589 // When the script we're invoking has an error, we get this error back.
590 DLOG_IF(ERROR
, FAILED(hr
) && hr
!= 0x80020101)
591 << StringPrintf(L
"Failed to invoke script: 0x%08X", hr
);
595 HRESULT
ChromeFrameActivex::InstallTopLevelHook(IOleClientSite
* client_site
) {
596 // Get the parent window of the site, and install our hook on the topmost
597 // window of the parent.
598 ScopedComPtr
<IOleWindow
> ole_window
;
599 HRESULT hr
= ole_window
.QueryFrom(client_site
);
604 hr
= ole_window
->GetWindow(&parent_wnd
);
608 HWND top_window
= ::GetAncestor(parent_wnd
, GA_ROOT
);
609 chrome_wndproc_hook_
= InstallLocalWindowHook(top_window
);
610 if (chrome_wndproc_hook_
)
611 TopLevelWindowMapping::instance()->AddMapping(top_window
, m_hWnd
);
613 return chrome_wndproc_hook_
? S_OK
: E_FAIL
;
616 HRESULT
ChromeFrameActivex::registerBhoIfNeeded() {
618 NOTREACHED() << "Invalid client site";
622 if (NavigationManager::GetThreadInstance() != NULL
) {
623 DLOG(INFO
) << "BHO already loaded";
627 ScopedComPtr
<IWebBrowser2
> web_browser2
;
628 HRESULT hr
= DoQueryService(SID_SWebBrowserApp
, m_spUnkSite
,
629 web_browser2
.Receive());
630 if (FAILED(hr
) || web_browser2
.get() == NULL
) {
631 DLOG(WARNING
) << "Failed to get IWebBrowser2 from client site. Error:"
632 << StringPrintf(" 0x%08X", hr
);
636 wchar_t bho_class_id_as_string
[MAX_PATH
] = {0};
637 StringFromGUID2(CLSID_ChromeFrameBHO
, bho_class_id_as_string
,
638 arraysize(bho_class_id_as_string
));
640 ScopedComPtr
<IObjectWithSite
> bho
;
641 hr
= bho
.CreateInstance(CLSID_ChromeFrameBHO
, NULL
, CLSCTX_INPROC_SERVER
);
643 NOTREACHED() << "Failed to register ChromeFrame BHO. Error:"
644 << StringPrintf(" 0x%08X", hr
);
648 hr
= bho
->SetSite(web_browser2
);
650 NOTREACHED() << "ChromeFrame BHO SetSite failed. Error:"
651 << StringPrintf(" 0x%08X", hr
);
655 web_browser2
->PutProperty(ScopedBstr(bho_class_id_as_string
),