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 #include "chrome_frame/bho.h"
9 #include "base/file_path.h"
10 #include "base/logging.h"
11 #include "base/path_service.h"
12 #include "base/string_util.h"
13 #include "base/stringprintf.h"
14 #include "base/time.h"
15 #include "base/win/scoped_bstr.h"
16 #include "chrome_frame/buggy_bho_handling.h"
17 #include "chrome_frame/crash_reporting/crash_metrics.h"
18 #include "chrome_frame/extra_system_apis.h"
19 #include "chrome_frame/html_utils.h"
20 #include "chrome_frame/http_negotiate.h"
21 #include "chrome_frame/metrics_service.h"
22 #include "chrome_frame/protocol_sink_wrap.h"
23 #include "chrome_frame/ready_mode/ready_mode.h"
24 #include "chrome_frame/urlmon_moniker.h"
25 #include "chrome_frame/utils.h"
26 #include "chrome_frame/vtable_patch_manager.h"
28 static const int kIBrowserServiceOnHttpEquivIndex
= 30;
29 static const DWORD kMaxHttpConnections
= 6;
31 PatchHelper g_patch_helper
;
33 BEGIN_VTABLE_PATCHES(IBrowserService
)
34 VTABLE_PATCH_ENTRY(kIBrowserServiceOnHttpEquivIndex
, Bho::OnHttpEquiv
)
37 _ATL_FUNC_INFO
Bho::kBeforeNavigate2Info
= {
38 CC_STDCALL
, VT_EMPTY
, 7, {
40 VT_VARIANT
| VT_BYREF
,
41 VT_VARIANT
| VT_BYREF
,
42 VT_VARIANT
| VT_BYREF
,
43 VT_VARIANT
| VT_BYREF
,
44 VT_VARIANT
| VT_BYREF
,
49 _ATL_FUNC_INFO
Bho::kNavigateComplete2Info
= {
50 CC_STDCALL
, VT_EMPTY
, 2, {
56 _ATL_FUNC_INFO
Bho::kDocumentCompleteInfo
= {
57 CC_STDCALL
, VT_EMPTY
, 2, {
66 HRESULT
Bho::FinalConstruct() {
70 void Bho::FinalRelease() {
73 STDMETHODIMP
Bho::SetSite(IUnknown
* site
) {
76 base::TimeTicks start
= base::TimeTicks::Now();
77 base::win::ScopedComPtr
<IWebBrowser2
> web_browser2
;
78 web_browser2
.QueryFrom(site
);
80 hr
= DispEventAdvise(web_browser2
, &DIID_DWebBrowserEvents2
);
81 DCHECK(SUCCEEDED(hr
)) << "DispEventAdvise failed. Error: " << hr
;
84 if (g_patch_helper
.state() == PatchHelper::PATCH_IBROWSER
) {
85 base::win::ScopedComPtr
<IBrowserService
> browser_service
;
86 hr
= DoQueryService(SID_SShellBrowser
, site
, browser_service
.Receive());
87 DCHECK(browser_service
) << "DoQueryService - SID_SShellBrowser failed."
88 << " Site: " << site
<< " Error: " << hr
;
89 if (browser_service
) {
90 g_patch_helper
.PatchBrowserService(browser_service
);
91 DCHECK(SUCCEEDED(hr
)) << "vtable_patch::PatchInterfaceMethods failed."
92 << " Site: " << site
<< " Error: " << hr
;
95 // Save away our BHO instance in TLS which enables it to be referenced by
96 // our active document/activex instances to query referrer and other
97 // information for a URL.
99 RegisterThreadInstance();
100 MetricsService::Start();
102 if (!IncreaseWinInetConnections(kMaxHttpConnections
)) {
103 DLOG(WARNING
) << "Failed to bump up HTTP connections. Error:"
107 base::TimeDelta delta
= base::TimeTicks::Now() - start
;
108 UMA_HISTOGRAM_TIMES("ChromeFrame.BhoLoadSetSite", delta
);
110 UnregisterThreadInstance();
111 buggy_bho::BuggyBhoTls::DestroyInstance();
112 base::win::ScopedComPtr
<IWebBrowser2
> web_browser2
;
113 web_browser2
.QueryFrom(m_spUnkSite
);
114 DispEventUnadvise(web_browser2
, &DIID_DWebBrowserEvents2
);
118 return IObjectWithSiteImpl
<Bho
>::SetSite(site
);
121 STDMETHODIMP
Bho::BeforeNavigate2(IDispatch
* dispatch
, VARIANT
* url
,
122 VARIANT
* flags
, VARIANT
* target_frame_name
, VARIANT
* post_data
,
123 VARIANT
* headers
, VARIANT_BOOL
* cancel
) {
124 if (!url
|| url
->vt
!= VT_BSTR
|| url
->bstrVal
== NULL
) {
125 DLOG(WARNING
) << "Invalid URL passed in";
129 base::win::ScopedComPtr
<IWebBrowser2
> web_browser2
;
131 web_browser2
.QueryFrom(dispatch
);
134 NOTREACHED() << "Can't find WebBrowser2 with given dispatch";
138 DVLOG(1) << "BeforeNavigate2: " << url
->bstrVal
;
140 base::win::ScopedComPtr
<IBrowserService
> browser_service
;
141 DoQueryService(SID_SShellBrowser
, web_browser2
, browser_service
.Receive());
142 if (!browser_service
|| !CheckForCFNavigation(browser_service
, false)) {
143 // TODO(tommi): Remove? Isn't this done below by calling set_referrer("")?
147 VARIANT_BOOL is_top_level
= VARIANT_FALSE
;
148 web_browser2
->get_TopLevelContainer(&is_top_level
);
150 set_url(url
->bstrVal
);
152 set_post_data(post_data
);
153 set_headers(headers
);
158 STDMETHODIMP_(void) Bho::NavigateComplete2(IDispatch
* dispatch
, VARIANT
* url
) {
159 DVLOG(1) << __FUNCTION__
;
162 STDMETHODIMP_(void) Bho::DocumentComplete(IDispatch
* dispatch
, VARIANT
* url
) {
163 DVLOG(1) << __FUNCTION__
;
165 base::win::ScopedComPtr
<IWebBrowser2
> web_browser2
;
167 web_browser2
.QueryFrom(dispatch
);
170 VARIANT_BOOL is_top_level
= VARIANT_FALSE
;
171 web_browser2
->get_TopLevelContainer(&is_top_level
);
173 CrashMetricsReporter::GetInstance()->IncrementMetric(
174 CrashMetricsReporter::NAVIGATION_COUNT
);
181 // See comments in Bho::OnHttpEquiv for details.
182 void ClearDocumentContents(IUnknown
* browser
) {
183 base::win::ScopedComPtr
<IWebBrowser2
> web_browser2
;
184 if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp
, browser
,
185 web_browser2
.Receive()))) {
186 base::win::ScopedComPtr
<IDispatch
> doc_disp
;
187 web_browser2
->get_Document(doc_disp
.Receive());
188 base::win::ScopedComPtr
<IHTMLDocument2
> doc
;
189 if (doc_disp
&& SUCCEEDED(doc
.QueryFrom(doc_disp
))) {
190 SAFEARRAY
* sa
= ::SafeArrayCreateVector(VT_UI1
, 0, 0);
192 ::SafeArrayDestroy(sa
);
197 // Returns true if the currently loaded document in the browser has
198 // any embedded items such as a frame or an iframe.
199 bool DocumentHasEmbeddedItems(IUnknown
* browser
) {
200 bool has_embedded_items
= false;
202 base::win::ScopedComPtr
<IWebBrowser2
> web_browser2
;
203 base::win::ScopedComPtr
<IDispatch
> document
;
204 if (SUCCEEDED(DoQueryService(SID_SWebBrowserApp
, browser
,
205 web_browser2
.Receive())) &&
206 SUCCEEDED(web_browser2
->get_Document(document
.Receive()))) {
207 base::win::ScopedComPtr
<IOleContainer
> container
;
208 if (SUCCEEDED(container
.QueryFrom(document
))) {
209 base::win::ScopedComPtr
<IEnumUnknown
> enumerator
;
210 container
->EnumObjects(OLECONTF_EMBEDDINGS
, enumerator
.Receive());
212 base::win::ScopedComPtr
<IUnknown
> unk
;
214 while (!has_embedded_items
&&
215 SUCCEEDED(enumerator
->Next(1, unk
.Receive(), &fetched
))
217 // If a top level document has embedded iframes then the theory is
218 // that first the top level document finishes loading and then the
219 // iframes load. We should only treat an embedded element as an
220 // iframe if it supports the IWebBrowser interface.
221 base::win::ScopedComPtr
<IWebBrowser2
> embedded_web_browser2
;
222 if (SUCCEEDED(embedded_web_browser2
.QueryFrom(unk
))) {
223 // If we initiate a top level navigation then at times MSHTML
224 // creates a temporary IWebBrowser2 interface which basically shows
225 // up as a temporary iframe in the parent document. It is not clear
226 // as to how we can detect this. I tried the usual stuff like
227 // getting to the parent IHTMLWindow2 interface. They all end up
228 // pointing to dummy tear off interfaces owned by MSHTML.
229 // As a temporary workaround, we found that the location url in
230 // this case is about:blank. We now check for the same and don't
231 // treat it as an iframe. This should be fine in most cases as we
232 // hit this code only when the actual page has a meta tag. However
233 // this would break for cases like the initial src url for an
234 // iframe pointing to about:blank and the page then writing to it
235 // via document.write.
237 // Revisit this and come up with a better approach.
238 base::win::ScopedBstr location_url
;
239 embedded_web_browser2
->get_LocationURL(location_url
.Receive());
241 std::wstring location_url_string
;
242 location_url_string
.assign(location_url
, location_url
.Length());
244 if (!LowerCaseEqualsASCII(location_url_string
, "about:blank")) {
245 has_embedded_items
= true;
256 return has_embedded_items
;
261 HRESULT
Bho::OnHttpEquiv(IBrowserService_OnHttpEquiv_Fn original_httpequiv
,
262 IBrowserService
* browser
, IShellView
* shell_view
, BOOL done
,
263 VARIANT
* in_arg
, VARIANT
* out_arg
) {
264 DVLOG(1) << __FUNCTION__
<< " done:" << done
;
266 // OnHttpEquiv with 'done' set to TRUE is called for all pages.
267 // 0 or more calls with done set to FALSE are made.
268 // When done is FALSE, the current moniker may not represent the page
269 // being navigated to so we always have to wait for done to be TRUE
270 // before re-initiating the navigation.
272 if (!done
&& in_arg
&& VT_BSTR
== V_VT(in_arg
)) {
273 if (StrStrI(V_BSTR(in_arg
), kChromeContentPrefix
)) {
274 // OnHttpEquiv is invoked for meta tags within sub frames as well.
275 // We want to switch renderers only for the top level frame.
276 // The theory here is that if there are any existing embedded items
277 // (frames or iframes) in the current document, then the http-equiv
278 // notification is coming from those and not the top level document.
279 // The embedded items should only be created once the top level
280 // doc has been created.
281 if (!DocumentHasEmbeddedItems(browser
)) {
282 NavigationManager
* mgr
= NavigationManager::GetThreadInstance();
284 DVLOG(1) << "Found tag in page. Marking browser."
285 << base::StringPrintf(" tid=0x%08X", ::GetCurrentThreadId());
287 // TODO(tommi): See if we can't figure out a cleaner way to avoid
288 // this. For some documents we can hit a problem here. When we
289 // attempt to navigate the document again in CF, mshtml can "complete"
290 // the current navigation (if all data is available) and fire off
291 // script events such as onload and even render the page.
292 // This will happen inside NavigateBrowserToMoniker below.
293 // To work around this, we clear the contents of the document before
294 // opening it up in CF.
295 ClearDocumentContents(browser
);
296 mgr
->NavigateToCurrentUrlInCF(browser
);
302 return original_httpequiv(browser
, shell_view
, done
, in_arg
, out_arg
);
306 void Bho::ProcessOptInUrls(IWebBrowser2
* browser
, BSTR url
) {
307 if (!browser
|| !url
) {
313 // This check must already have been made.
314 VARIANT_BOOL is_top_level
= VARIANT_FALSE
;
315 browser
->get_TopLevelContainer(&is_top_level
);
316 DCHECK(is_top_level
);
319 std::wstring
current_url(url
, SysStringLen(url
));
320 if (IsValidUrlScheme(GURL(current_url
), false)) {
321 bool cf_protocol
= StartsWith(current_url
, kChromeProtocolPrefix
, false);
322 if (!cf_protocol
&& IsChrome(RendererTypeForUrl(current_url
))) {
323 DVLOG(1) << "Opt-in URL. Switching to cf.";
324 base::win::ScopedComPtr
<IBrowserService
> browser_service
;
325 DoQueryService(SID_SShellBrowser
, browser
, browser_service
.Receive());
326 DCHECK(browser_service
) << "DoQueryService - SID_SShellBrowser failed.";
327 MarkBrowserOnThreadForCFNavigation(browser_service
);
332 bool PatchHelper::InitializeAndPatchProtocolsIfNeeded() {
335 _pAtlModule
->m_csStaticDataInitAndTypeInfo
.Lock();
337 if (state_
== UNKNOWN
) {
338 g_trans_hooks
.InstallHooks();
339 HttpNegotiatePatch::Initialize();
340 state_
= PATCH_PROTOCOL
;
344 _pAtlModule
->m_csStaticDataInitAndTypeInfo
.Unlock();
349 void PatchHelper::PatchBrowserService(IBrowserService
* browser_service
) {
350 DCHECK(state_
== PATCH_IBROWSER
);
351 if (!IS_PATCHED(IBrowserService
)) {
352 vtable_patch::PatchInterfaceMethods(browser_service
,
353 IBrowserService_PatchInfo
);
357 void PatchHelper::UnpatchIfNeeded() {
358 if (state_
== PATCH_PROTOCOL
) {
359 g_trans_hooks
.RevertHooks();
360 HttpNegotiatePatch::Uninitialize();