1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_FRAME_CHROME_FRAME_ACTIVEX_BASE_H_
#define CHROME_FRAME_CHROME_FRAME_ACTIVEX_BASE_H_
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
// Copied min/max defs from windows headers to appease atlimage.h.
// TODO(slightlyoff): Figure out of more recent platform SDK's (> 6.1)
// undo the janky "#define NOMINMAX" train wreck. See:
// http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100703
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
#include <atlimage.h>
#undef max
#undef min
#include <shdeprecated.h> // for IBrowserService2
#include <shlguid.h>
#include <set>
#include <string>
#include "base/histogram.h"
#include "base/scoped_bstr_win.h"
#include "base/scoped_comptr_win.h"
#include "base/scoped_variant_win.h"
#include "base/string_util.h"
#include "grit/chrome_frame_resources.h"
#include "grit/chrome_frame_strings.h"
#include "chrome_frame/chrome_frame_plugin.h"
#include "chrome_frame/com_type_info_holder.h"
#include "chrome_frame/urlmon_url_request.h"
// Include without path to make GYP build see it.
#include "chrome_tab.h" // NOLINT
// Connection point class to support firing IChromeFrameEvents (dispinterface).
template<class T>
class ATL_NO_VTABLE ProxyDIChromeFrameEvents
: public IConnectionPointImpl<T, &DIID_DIChromeFrameEvents> {
public:
void FireMethodWithParams(ChromeFrameEventDispId dispid,
const VARIANT* params, size_t num_params) {
T* me = static_cast<T*>(this);
int connections = m_vec.GetSize();
for (int connection = 0; connection < connections; ++connection) {
me->Lock();
CComPtr<IUnknown> sink(m_vec.GetAt(connection));
me->Unlock();
DIChromeFrameEvents* events = static_cast<DIChromeFrameEvents*>(sink.p);
if (events) {
DISPPARAMS disp_params = {
const_cast<VARIANT*>(params),
NULL,
num_params,
0};
HRESULT hr = events->Invoke(static_cast<DISPID>(dispid),
DIID_DIChromeFrameEvents,
LOCALE_USER_DEFAULT, DISPATCH_METHOD,
&disp_params, NULL, NULL, NULL);
DLOG_IF(ERROR, FAILED(hr)) << "invoke(" << dispid << ") failed" <<
StringPrintf("0x%08X", hr);
}
}
}
void FireMethodWithParam(ChromeFrameEventDispId dispid,
const VARIANT& param) {
FireMethodWithParams(dispid, ¶m, 1);
}
void Fire_onload(IDispatch* event) {
VARIANT var = { VT_DISPATCH };
var.pdispVal = event;
FireMethodWithParam(CF_EVENT_DISPID_ONLOAD, var);
}
void Fire_onloaderror(IDispatch* event) {
VARIANT var = { VT_DISPATCH };
var.pdispVal = event;
FireMethodWithParam(CF_EVENT_DISPID_ONLOADERROR, var);
}
void Fire_onmessage(IDispatch* event) {
VARIANT var = { VT_DISPATCH };
var.pdispVal = event;
FireMethodWithParam(CF_EVENT_DISPID_ONMESSAGE, var);
}
void Fire_onreadystatechanged(long readystate) {
VARIANT var = { VT_I4 };
var.lVal = readystate;
FireMethodWithParam(CF_EVENT_DISPID_ONREADYSTATECHANGED, var);
}
void Fire_onprivatemessage(IDispatch* event, BSTR target) {
// Arguments in reverse order to the function declaration, because
// that's what DISPPARAMS requires.
VARIANT args[2] = { { VT_BSTR, }, {VT_DISPATCH, } };
args[0].bstrVal = target;
args[1].pdispVal = event;
FireMethodWithParams(CF_EVENT_DISPID_ONPRIVATEMESSAGE,
args,
arraysize(args));
}
void Fire_onextensionready(BSTR path, long response) {
// Arguments in reverse order to the function declaration, because
// that's what DISPPARAMS requires.
VARIANT args[2] = { { VT_I4, }, { VT_BSTR, } };
args[0].lVal = response;
args[1].bstrVal = path;
FireMethodWithParams(CF_EVENT_DISPID_ONEXTENSIONREADY,
args,
arraysize(args));
}
};
extern bool g_first_launch_by_process_;
// Common implementation for ActiveX and Active Document
template <class T, const CLSID& class_id>
class ATL_NO_VTABLE ChromeFrameActivexBase :
public CComObjectRootEx<CComSingleThreadModel>,
public IOleControlImpl<T>,
public IOleObjectImpl<T>,
public IOleInPlaceActiveObjectImpl<T>,
public IViewObjectExImpl<T>,
public IOleInPlaceObjectWindowlessImpl<T>,
public ISupportErrorInfo,
public IQuickActivateImpl<T>,
public com_util::IProvideClassInfo2Impl<class_id,
DIID_DIChromeFrameEvents>,
public com_util::IDispatchImpl<IChromeFrame>,
public IConnectionPointContainerImpl<T>,
public ProxyDIChromeFrameEvents<T>,
public IPropertyNotifySinkCP<T>,
public CComCoClass<T, &class_id>,
public CComControl<T>,
public ChromeFramePlugin<T> {
protected:
typedef std::set<ScopedComPtr<IDispatch> > EventHandlers;
typedef ChromeFrameActivexBase<T, class_id> Base;
public:
ChromeFrameActivexBase()
: ready_state_(READYSTATE_UNINITIALIZED),
worker_thread_("ChromeFrameWorker_Thread") {
m_bWindowOnly = TRUE;
}
~ChromeFrameActivexBase() {
}
DECLARE_OLEMISC_STATUS(OLEMISC_RECOMPOSEONRESIZE | OLEMISC_CANTLINKINSIDE |
OLEMISC_INSIDEOUT | OLEMISC_ACTIVATEWHENVISIBLE |
OLEMISC_SETCLIENTSITEFIRST)
DECLARE_NOT_AGGREGATABLE(T)
BEGIN_COM_MAP(ChromeFrameActivexBase)
COM_INTERFACE_ENTRY(IChromeFrame)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(IViewObjectEx)
COM_INTERFACE_ENTRY(IViewObject2)
COM_INTERFACE_ENTRY(IViewObject)
COM_INTERFACE_ENTRY(IOleInPlaceObjectWindowless)
COM_INTERFACE_ENTRY(IOleInPlaceObject)
COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless)
COM_INTERFACE_ENTRY(IOleInPlaceActiveObject)
COM_INTERFACE_ENTRY(IOleControl)
COM_INTERFACE_ENTRY(IOleObject)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(IQuickActivate)
COM_INTERFACE_ENTRY(IProvideClassInfo)
COM_INTERFACE_ENTRY(IProvideClassInfo2)
COM_INTERFACE_ENTRY_FUNC_BLIND(0, InterfaceNotSupported)
END_COM_MAP()
BEGIN_CONNECTION_POINT_MAP(T)
CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink)
CONNECTION_POINT_ENTRY(DIID_DIChromeFrameEvents)
END_CONNECTION_POINT_MAP()
BEGIN_MSG_MAP(ChromeFrameActivexBase)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
CHAIN_MSG_MAP(ChromeFramePlugin<T>)
CHAIN_MSG_MAP(CComControl<T>)
DEFAULT_REFLECTION_HANDLER()
END_MSG_MAP()
// IViewObjectEx
DECLARE_VIEW_STATUS(VIEWSTATUS_SOLIDBKGND | VIEWSTATUS_OPAQUE)
inline HRESULT IViewObject_Draw(DWORD draw_aspect, LONG index,
void* aspect_info, DVTARGETDEVICE* ptd, HDC info_dc, HDC dc,
LPCRECTL bounds, LPCRECTL win_bounds) {
// ATL ASSERTs if dwDrawAspect is DVASPECT_DOCPRINT, so we cheat.
DWORD aspect = draw_aspect;
if (aspect == DVASPECT_DOCPRINT)
aspect = DVASPECT_CONTENT;
return CComControl<T>::IViewObject_Draw(aspect, index, aspect_info, ptd,
info_dc, dc, bounds, win_bounds);
}
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct() {
if (!Initialize())
return E_OUTOFMEMORY;
// Set to true if this is the first launch by this process.
// Used to perform one time tasks.
if (g_first_launch_by_process_) {
g_first_launch_by_process_ = false;
UMA_HISTOGRAM_CUSTOM_COUNTS("ChromeFrame.IEVersion",
GetIEVersion(),
IE_INVALID,
IE_8,
IE_8 + 1);
}
return S_OK;
}
void FinalRelease() {
}
static HRESULT WINAPI InterfaceNotSupported(void* pv, REFIID riid, void** ppv,
DWORD dw) {
#ifndef NDEBUG
wchar_t buffer[64] = {0};
::StringFromGUID2(riid, buffer, arraysize(buffer));
DLOG(INFO) << "E_NOINTERFACE: " << buffer;
#endif
return E_NOINTERFACE;
}
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid) {
static const IID* interfaces[] = {
&IID_IChromeFrame,
&IID_IDispatch
};
for (int i = 0; i < arraysize(interfaces); ++i) {
if (InlineIsEqualGUID(*interfaces[i], riid))
return S_OK;
}
return S_FALSE;
}
// Called to draw our control when chrome hasn't been initialized.
virtual HRESULT OnDraw(ATL_DRAWINFO& draw_info) { // NO_LINT
if (NULL == draw_info.prcBounds) {
NOTREACHED();
return E_FAIL;
}
// Don't draw anything.
return S_OK;
}
// Used to setup the document_url_ member needed for completing navigation.
// Create external tab (possibly in incognito mode).
HRESULT IOleObject_SetClientSite(IOleClientSite* client_site) {
// If we currently have a document site pointer, release it.
doc_site_.Release();
if (client_site) {
doc_site_.QueryFrom(client_site);
}
return CComControlBase::IOleObject_SetClientSite(client_site);
}
bool HandleContextMenuCommand(UINT cmd) {
if (cmd == IDC_ABOUT_CHROME_FRAME) {
int tab_handle = automation_client_->tab()->handle();
OnOpenURL(tab_handle, GURL("about:version"), GURL(), NEW_WINDOW);
return true;
}
return false;
}
// Should connections initiated by this class try to block
// responses served with the X-Frame-Options header?
// ActiveX controls genereally will want to do this,
// returning true, while true top-level documents
// (ActiveDocument servers) will not. Your specialization
// of this template should implement this method based on how
// it "feels" from a security perspective. If it's hosted in another
// scriptable document, return true, else false.
bool is_frame_busting_enabled() const {
return true;
}
// Needed to support PostTask.
static bool ImplementsThreadSafeReferenceCounting() {
return true;
}
protected:
virtual void OnTabbedOut(int tab_handle, bool reverse) {
DCHECK(m_bInPlaceActive);
HWND parent = ::GetParent(m_hWnd);
::SetFocus(parent);
ScopedComPtr<IOleControlSite> control_site;
control_site.QueryFrom(m_spClientSite);
if (control_site)
control_site->OnFocus(FALSE);
}
virtual void OnOpenURL(int tab_handle, const GURL& url_to_open,
const GURL& referrer, int open_disposition) {
ScopedComPtr<IWebBrowser2> web_browser2;
DoQueryService(SID_SWebBrowserApp, m_spClientSite, web_browser2.Receive());
DCHECK(web_browser2);
ScopedVariant url;
// Check to see if the URL uses a "view-source:" prefix, if so, open it
// using chrome frame full tab mode by using 'cf:' protocol handler.
// Also change the disposition to NEW_WINDOW since IE6 doesn't have tabs.
if (url_to_open.has_scheme() && (url_to_open.SchemeIs("view-source") ||
url_to_open.SchemeIs("about"))) {
std::string chrome_url;
chrome_url.append("cf:");
chrome_url.append(url_to_open.spec());
url.Set(UTF8ToWide(chrome_url).c_str());
open_disposition = NEW_WINDOW;
} else {
url.Set(UTF8ToWide(url_to_open.spec()).c_str());
}
VARIANT flags = { VT_I4 };
V_I4(&flags) = 0;
IEVersion ie_version = GetIEVersion();
DCHECK(ie_version != NON_IE && ie_version != IE_UNSUPPORTED);
// Since IE6 doesn't support tabs, so we just use window instead.
if (ie_version == IE_6) {
if (open_disposition == NEW_FOREGROUND_TAB ||
open_disposition == NEW_BACKGROUND_TAB ||
open_disposition == NEW_WINDOW) {
V_I4(&flags) = navOpenInNewWindow;
} else if (open_disposition != CURRENT_TAB) {
NOTREACHED() << "Unsupported open disposition in IE6";
}
} else {
switch (open_disposition) {
case NEW_FOREGROUND_TAB:
V_I4(&flags) = navOpenInNewTab;
break;
case NEW_BACKGROUND_TAB:
V_I4(&flags) = navOpenInBackgroundTab;
break;
case NEW_WINDOW:
V_I4(&flags) = navOpenInNewWindow;
break;
default:
break;
}
}
// TODO(sanjeevr): The navOpenInNewWindow flag causes IE to open this
// in a new window ONLY if the user has specified
// "Always open popups in a new window". Otherwise it opens in a new tab.
// We need to investigate more and see if we can force IE to display the
// link in a new window. MSHTML uses the below code to force an open in a
// new window. But this logic also fails for us. Perhaps this flag is not
// honoured if the ActiveDoc is not MSHTML.
// Even the HLNF_DISABLEWINDOWRESTRICTIONS flag did not work.
// Start of MSHTML-like logic.
// CComQIPtr<ITargetFramePriv2> target_frame = web_browser2;
// if (target_frame) {
// CComPtr<IUri> uri;
// CreateUri(UTF8ToWide(open_url_command->url_.spec()).c_str(),
// Uri_CREATE_IE_SETTINGS, 0, &uri);
// CComPtr<IBindCtx> bind_ctx;
// CreateBindCtx(0, &bind_ctx);
// target_frame->AggregatedNavigation2(
// HLNF_TRUSTFIRSTDOWNLOAD|HLNF_OPENINNEWWINDOW, bind_ctx, NULL,
// L"No_Name", uri, L"");
// }
// End of MSHTML-like logic
VARIANT empty = ScopedVariant::kEmptyVariant;
ScopedVariant http_headers;
if (referrer.is_valid()) {
std::wstring referrer_header = L"Referer: ";
referrer_header += UTF8ToWide(referrer.spec());
referrer_header += L"\r\n\r\n";
http_headers.Set(referrer_header.c_str());
}
web_browser2->Navigate2(url.AsInput(), &flags, &empty, &empty,
http_headers.AsInput());
web_browser2->put_Visible(VARIANT_TRUE);
}
virtual void OnRequestStart(int tab_handle, int request_id,
const IPC::AutomationURLRequest& request_info) {
// The worker thread may have been stopped. This could happen if the
// ActiveX instance was reused.
if (!worker_thread_.message_loop()) {
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_UI;
worker_thread_.StartWithOptions(options);
worker_thread_.message_loop()->PostTask(
FROM_HERE, NewRunnableMethod(this, &Base::OnWorkerStart));
}
scoped_refptr<CComObject<UrlmonUrlRequest> > request;
if (base_url_request_.get() &&
GURL(base_url_request_->url()) == GURL(request_info.url)) {
request.swap(base_url_request_);
} else {
CComObject<UrlmonUrlRequest>* new_request = NULL;
CComObject<UrlmonUrlRequest>::CreateInstance(&new_request);
request = new_request;
}
DCHECK(request.get() != NULL);
if (request->Initialize(
automation_client_.get(), tab_handle, request_id, request_info.url,
request_info.method, request_info.referrer,
request_info.extra_request_headers, request_info.upload_data.get(),
static_cast<T*>(this)->is_frame_busting_enabled())) {
request->set_worker_thread(&worker_thread_);
// If Start is successful, it will add a self reference.
request->Start();
request->set_parent_window(m_hWnd);
}
}
virtual void OnRequestRead(int tab_handle, int request_id,
int bytes_to_read) {
automation_client_->ReadRequest(request_id, bytes_to_read);
}
virtual void OnRequestEnd(int tab_handle, int request_id,
const URLRequestStatus& status) {
automation_client_->RemoveRequest(request_id, true);
}
virtual void OnDownloadRequestInHost(int tab_handle, int request_id) {
DLOG(INFO) << "TODO: Let the host browser handle this download";
automation_client_->RemoveRequest(request_id, false);
}
virtual void OnSetCookieAsync(int tab_handle, const GURL& url,
const std::string& cookie) {
std::string name;
std::string data;
size_t name_end = cookie.find('=');
if (std::string::npos != name_end) {
name = cookie.substr(0, name_end);
data = cookie.substr(name_end + 1);
} else {
data = cookie;
}
BOOL ret = InternetSetCookieA(url.spec().c_str(), name.c_str(),
data.c_str());
DCHECK(ret) << "InternetSetcookie failed. Error: " << GetLastError();
}
virtual void OnAttachExternalTab(int tab_handle,
intptr_t cookie,
int disposition) {
std::string url;
url = StringPrintf("cf:attach_external_tab&%d&%d",
cookie, disposition);
OnOpenURL(tab_handle, GURL(url), GURL(), disposition);
}
LRESULT OnCreate(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled) { // NO_LINT
ModifyStyle(0, WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0);
automation_client_->SetParentWindow(m_hWnd);
// Only fire the 'interactive' ready state if we aren't there already.
if (ready_state_ < READYSTATE_INTERACTIVE) {
ready_state_ = READYSTATE_INTERACTIVE;
FireOnChanged(DISPID_READYSTATE);
}
return 0;
}
LRESULT OnDestroy(UINT message, WPARAM wparam, LPARAM lparam,
BOOL& handled) { // NO_LINT
if (worker_thread_.message_loop()) {
worker_thread_.message_loop()->PostTask(
FROM_HERE, NewRunnableMethod(this, &Base::OnWorkerStop));
if (automation_client_.get())
automation_client_->CleanupAsyncRequests();
worker_thread_.Stop();
}
return 0;
}
// ChromeFrameDelegate override
virtual void OnAutomationServerReady() {
ChromeFramePlugin<T>::OnAutomationServerReady();
ready_state_ = READYSTATE_COMPLETE;
FireOnChanged(DISPID_READYSTATE);
}
// ChromeFrameDelegate override
virtual void OnAutomationServerLaunchFailed(
AutomationLaunchResult reason, const std::string& server_version) {
ready_state_ = READYSTATE_UNINITIALIZED;
FireOnChanged(DISPID_READYSTATE);
}
// Overridden to take advantage of readystate prop changes and send those
// to potential listeners.
HRESULT FireOnChanged(DISPID dispid) {
if (dispid == DISPID_READYSTATE) {
Fire_onreadystatechanged(ready_state_);
}
return __super::FireOnChanged(dispid);
}
// IChromeFrame
// Property getter/setters for the src attribute, which contains a URL.
// The ChromeFrameActivex control initiates navigation to this URL
// when instantiated.
STDMETHOD(get_src)(BSTR* src) {
if (NULL == src) {
return E_POINTER;
}
*src = SysAllocString(url_);
return S_OK;
}
STDMETHOD(put_src)(BSTR src) {
if (src == NULL)
return E_INVALIDARG;
// Switch the src to UTF8 and try to expand to full URL
std::string src_utf8;
WideToUTF8(src, SysStringLen(src), &src_utf8);
std::string full_url = ResolveURL(GetDocumentUrl(), src_utf8);
if (full_url.empty()) {
return E_INVALIDARG;
}
// We can initiate navigation here even if ready_state is not complete.
// We do not have to set proxy, and AutomationClient will take care
// of navigation just after CreateExternalTab is done.
if (!automation_client_->InitiateNavigation(full_url,
GetDocumentUrl(),
is_privileged_)) {
// TODO(robertshield): Make InitiateNavigation return more useful
// error information.
return E_INVALIDARG;
}
// Save full URL in BSTR member
url_.Reset(::SysAllocString(UTF8ToWide(full_url).c_str()));
return S_OK;
}
STDMETHOD(get_onload)(VARIANT* onload_handler) {
if (NULL == onload_handler)
return E_INVALIDARG;
*onload_handler = onload_handler_.Copy();
return S_OK;
}
// Property setter for the onload attribute, which contains a
// javascript function to be invoked on successful navigation.
STDMETHOD(put_onload)(VARIANT onload_handler) {
if (V_VT(&onload_handler) != VT_DISPATCH) {
DLOG(WARNING) << "Invalid onload handler type: "
<< onload_handler.vt
<< " specified";
return E_INVALIDARG;
}
onload_handler_ = onload_handler;
return S_OK;
}
// Property getter/setters for the onloaderror attribute, which contains a
// javascript function to be invoked on navigation failure.
STDMETHOD(get_onloaderror)(VARIANT* onerror_handler) {
if (NULL == onerror_handler)
return E_INVALIDARG;
*onerror_handler = onerror_handler_.Copy();
return S_OK;
}
STDMETHOD(put_onloaderror)(VARIANT onerror_handler) {
if (V_VT(&onerror_handler) != VT_DISPATCH) {
DLOG(WARNING) << "Invalid onloaderror handler type: "
<< onerror_handler.vt
<< " specified";
return E_INVALIDARG;
}
onerror_handler_ = onerror_handler;
return S_OK;
}
// Property getter/setters for the onmessage attribute, which contains a
// javascript function to be invoked when we receive a message from the
// chrome frame.
STDMETHOD(put_onmessage)(VARIANT onmessage_handler) {
if (V_VT(&onmessage_handler) != VT_DISPATCH) {
DLOG(WARNING) << "Invalid onmessage handler type: "
<< onmessage_handler.vt
<< " specified";
return E_INVALIDARG;
}
onmessage_handler_ = onmessage_handler;
return S_OK;
}
STDMETHOD(get_onmessage)(VARIANT* onmessage_handler) {
if (NULL == onmessage_handler)
return E_INVALIDARG;
*onmessage_handler = onmessage_handler_.Copy();
return S_OK;
}
STDMETHOD(get_readyState)(long* ready_state) { // NOLINT
DLOG(INFO) << __FUNCTION__;
DCHECK(ready_state);
if (!ready_state)
return E_INVALIDARG;
*ready_state = ready_state_;
return S_OK;
}
// Property getter/setters for use_chrome_network flag. This flag
// indicates if chrome network stack is to be used for fetching
// network requests.
STDMETHOD(get_useChromeNetwork)(VARIANT_BOOL* use_chrome_network) {
if (!use_chrome_network)
return E_INVALIDARG;
*use_chrome_network =
automation_client_->use_chrome_network() ? VARIANT_TRUE : VARIANT_FALSE;
return S_OK;
}
STDMETHOD(put_useChromeNetwork)(VARIANT_BOOL use_chrome_network) {
if (!is_privileged_) {
DLOG(ERROR) << "Attempt to set useChromeNetwork in non-privileged mode";
return E_ACCESSDENIED;
}
automation_client_->set_use_chrome_network(
(VARIANT_FALSE != use_chrome_network));
return S_OK;
}
// Posts a message to the chrome frame.
STDMETHOD(postMessage)(BSTR message, VARIANT target) {
if (NULL == message) {
return E_INVALIDARG;
}
if (!automation_client_.get())
return E_FAIL;
std::string utf8_target;
if (target.vt == VT_BSTR) {
int len = ::SysStringLen(target.bstrVal);
if (len == 1 && target.bstrVal[0] == L'*') {
utf8_target = "*";
} else {
GURL resolved(target.bstrVal);
if (!resolved.is_valid()) {
Error(L"Unable to parse the specified target URL.");
return E_INVALIDARG;
}
utf8_target = resolved.spec();
}
} else {
utf8_target = "*";
}
std::string utf8_message;
WideToUTF8(message, ::SysStringLen(message), &utf8_message);
GURL url(GURL(document_url_).GetOrigin());
std::string origin(url.is_empty() ? "null" : url.spec());
if (!automation_client_->ForwardMessageFromExternalHost(utf8_message,
origin,
utf8_target)) {
Error(L"Failed to post message to chrome frame");
return E_FAIL;
}
return S_OK;
}
STDMETHOD(addEventListener)(BSTR event_type, IDispatch* listener,
VARIANT use_capture) {
EventHandlers* handlers = NULL;
HRESULT hr = GetHandlersForEvent(event_type, &handlers);
if (FAILED(hr))
return hr;
DCHECK(handlers != NULL);
handlers->insert(ScopedComPtr<IDispatch>(listener));
return hr;
}
STDMETHOD(removeEventListener)(BSTR event_type, IDispatch* listener,
VARIANT use_capture) {
EventHandlers* handlers = NULL;
HRESULT hr = GetHandlersForEvent(event_type, &handlers);
if (FAILED(hr))
return hr;
DCHECK(handlers != NULL);
std::remove(handlers->begin(), handlers->end(), listener);
return hr;
}
STDMETHOD(get_version)(BSTR* version) {
if (!automation_client_.get()) {
NOTREACHED();
return E_FAIL;
}
if (version == NULL) {
return E_INVALIDARG;
}
*version = SysAllocString(automation_client_->GetVersion().c_str());
return S_OK;
}
STDMETHOD(postPrivateMessage)(BSTR message, BSTR origin, BSTR target) {
if (NULL == message)
return E_INVALIDARG;
if (!is_privileged_) {
DLOG(ERROR) << "Attempt to postPrivateMessage in non-privileged mode";
return E_ACCESSDENIED;
}
DCHECK(automation_client_.get());
std::string utf8_message, utf8_origin, utf8_target;
WideToUTF8(message, ::SysStringLen(message), &utf8_message);
WideToUTF8(origin, ::SysStringLen(origin), &utf8_origin);
WideToUTF8(target, ::SysStringLen(target), &utf8_target);
if (!automation_client_->ForwardMessageFromExternalHost(utf8_message,
utf8_origin,
utf8_target)) {
Error(L"Failed to post message to chrome frame");
return E_FAIL;
}
return S_OK;
}
STDMETHOD(installExtension)(BSTR crx_path) {
DCHECK(automation_client_.get());
if (NULL == crx_path) {
NOTREACHED();
return E_INVALIDARG;
}
if (!is_privileged_) {
DLOG(ERROR) << "Attempt to installExtension in non-privileged mode";
return E_ACCESSDENIED;
}
FilePath::StringType crx_path_str(crx_path);
FilePath crx_file_path(crx_path_str);
automation_client_->InstallExtension(crx_file_path, NULL);
return S_OK;
}
STDMETHOD(loadExtension)(BSTR path) {
DCHECK(automation_client_.get());
if (NULL == path) {
NOTREACHED();
return E_INVALIDARG;
}
if (!is_privileged_) {
DLOG(ERROR) << "Attempt to loadExtension in non-privileged mode";
return E_ACCESSDENIED;
}
FilePath::StringType path_str(path);
FilePath file_path(path_str);
automation_client_->LoadExpandedExtension(file_path, NULL);
return S_OK;
}
// Returns the vector of event handlers for a given event (e.g. "load").
// If the event type isn't recognized, the function fills in a descriptive
// error (IErrorInfo) and returns E_INVALIDARG.
HRESULT GetHandlersForEvent(BSTR event_type, EventHandlers** handlers) {
DCHECK(handlers != NULL);
// TODO(tommi): make these if() statements data-driven.
HRESULT hr = S_OK;
const wchar_t* event_type_end = event_type + ::SysStringLen(event_type);
if (LowerCaseEqualsASCII(event_type, event_type_end, "message")) {
*handlers = &onmessage_;
} else if (LowerCaseEqualsASCII(event_type, event_type_end, "load")) {
*handlers = &onload_;
} else if (LowerCaseEqualsASCII(event_type, event_type_end, "loaderror")) {
*handlers = &onloaderror_;
} else if (LowerCaseEqualsASCII(event_type, event_type_end,
"readystatechanged")) {
*handlers = &onreadystatechanged_;
} else if (LowerCaseEqualsASCII(event_type, event_type_end,
"privatemessage")) {
// This event handler is only available in privileged mode.
if (is_privileged_) {
*handlers = &onprivatemessage_;
} else {
Error("Event type 'privatemessage' is privileged");
hr = E_ACCESSDENIED;
}
} else if (LowerCaseEqualsASCII(event_type, event_type_end,
"extensionready")) {
// This event handler is only available in privileged mode.
if (is_privileged_) {
*handlers = &onextensionready_;
} else {
Error("Event type 'extensionready' is privileged");
hr = E_ACCESSDENIED;
}
} else {
Error(StringPrintf("Event type '%ls' not found", event_type).c_str());
hr = E_INVALIDARG;
}
return hr;
}
// Gives the browser a chance to handle an accelerator that was
// sent to the out of proc chromium instance.
// Returns S_OK iff the accelerator was handled by the browser.
HRESULT AllowFrameToTranslateAccelerator(const MSG& msg) {
// Although IBrowserService2 is officially deprecated, it's still alive
// and well in IE7 and earlier. We have to use it here to correctly give
// the browser a chance to handle keyboard shortcuts.
// This happens automatically for activex components that have windows that
// belong to the current thread. In that circumstance IE owns the message
// loop and can walk the line of components allowing each participant the
// chance to handle the keystroke and eventually falls back to
// v_MayTranslateAccelerator. However in our case, the message loop is
// owned by the out-of-proc chromium instance so IE doesn't have a chance to
// fall back on its default behavior. Instead we give IE a chance to
// handle the shortcut here.
HRESULT hr = S_FALSE;
ScopedComPtr<IBrowserService2> bs2;
if (S_OK == DoQueryService(SID_STopLevelBrowser, m_spInPlaceSite,
bs2.Receive())) {
hr = bs2->v_MayTranslateAccelerator(const_cast<MSG*>(&msg));
} else {
// IE8 doesn't support IBrowserService2 unless you enable a special,
// undocumented flag with CoInternetSetFeatureEnabled and even then,
// the object you get back implements only a couple of methods of
// that interface... all the other entries in the vtable are NULL.
// In addition, the class that implements it is called
// ImpostorBrowserService2 :)
// IE8 does have a new interface though, presumably called
// ITabBrowserService or something that can be abbreviated to TBS.
// That interface has a method, TranslateAcceleratorTBS that does
// call the root MayTranslateAccelerator function, but alas the
// first argument to MayTranslateAccelerator is hard coded to FALSE
// which means that global accelerators are not handled and we're
// out of luck.
// A third thing that's notable with regards to IE8 is that
// none of the *MayTranslate* functions exist in a vtable inside
// ieframe.dll. I checked this by scanning for the address of
// those functions inside the dll and found none, which means that
// all calls to those functions are relative.
// So, for IE8, our approach is very simple. Just post the message
// to our parent window and IE will pick it up if it's an
// accelerator. We won't know for sure if the browser handled the
// keystroke or not.
::PostMessage(::GetParent(m_hWnd), msg.message, msg.wParam,
msg.lParam);
}
return hr;
}
virtual void OnAcceleratorPressed(int tab_handle, const MSG& accel_message) {
DCHECK(m_spInPlaceSite != NULL);
// Allow our host a chance to handle the accelerator.
// This catches things like Ctrl+F, Ctrl+O etc, but not browser
// accelerators such as F11, Ctrl+T etc.
// (see AllowFrameToTranslateAccelerator for those).
HRESULT hr = TranslateAccelerator(const_cast<MSG*>(&accel_message));
if (hr != S_OK)
hr = AllowFrameToTranslateAccelerator(accel_message);
DLOG(INFO) << __FUNCTION__ << " browser response: "
<< StringPrintf("0x%08x", hr);
if (hr != S_OK) {
// The WM_SYSCHAR message is not processed by the IOleControlSite
// implementation and the IBrowserService2::v_MayTranslateAccelerator
// implementation. We need to understand this better. That is for
// another day. For now we just post the WM_SYSCHAR message back to our
// parent which forwards it off to the frame. This should not cause major
// grief for Chrome as it does not need to handle WM_SYSCHAR accelerators
// when running in ChromeFrame mode.
// TODO(iyengar)
// Understand and fix WM_SYSCHAR handling
// We should probably unify the accelerator handling for the active
// document and the activex.
if (accel_message.message == WM_SYSCHAR) {
::PostMessage(GetParent(), WM_SYSCHAR, accel_message.wParam,
accel_message.lParam);
return;
}
}
// Last chance to handle the keystroke is to pass it to chromium.
// We do this last partially because there's no way for us to tell if
// chromium actually handled the keystroke, but also since the browser
// should have first dibs anyway.
if (hr != S_OK && automation_client_.get()) {
TabProxy* tab = automation_client_->tab();
if (tab) {
tab->ProcessUnhandledAccelerator(accel_message);
}
}
}
protected:
// The following functions are called to initialize and uninitialize the
// worker thread.
void OnWorkerStart() {
CoInitialize(NULL);
}
void OnWorkerStop() {
CoUninitialize();
}
ScopedBstr url_;
ScopedComPtr<IOleDocumentSite> doc_site_;
// For more information on the ready_state_ property see:
// http://msdn.microsoft.com/en-us/library/aa768179(VS.85).aspx#
READYSTATE ready_state_;
// The following members contain IDispatch interfaces representing the
// onload/onerror/onmessage handlers on the page.
ScopedVariant onload_handler_;
ScopedVariant onerror_handler_;
ScopedVariant onmessage_handler_;
EventHandlers onmessage_;
EventHandlers onloaderror_;
EventHandlers onload_;
EventHandlers onreadystatechanged_;
EventHandlers onprivatemessage_;
EventHandlers onextensionready_;
// The UrlmonUrlRequest instance instantiated for downloading the base URL.
scoped_refptr<CComObject<UrlmonUrlRequest> > base_url_request_;
base::Thread worker_thread_;
};
#endif // CHROME_FRAME_CHROME_FRAME_ACTIVEX_BASE_H_
|