Save errno for logging before potentially overwriting it.
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.cc
blob83729afb8191f52196cd636d9d02df87d551fa03
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 "content/browser/renderer_host/render_view_host_impl.h"
7 #include <set>
8 #include <string>
9 #include <utility>
10 #include <vector>
12 #include "base/callback.h"
13 #include "base/command_line.h"
14 #include "base/debug/trace_event.h"
15 #include "base/i18n/rtl.h"
16 #include "base/json/json_reader.h"
17 #include "base/lazy_instance.h"
18 #include "base/message_loop.h"
19 #include "base/metrics/histogram.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/time.h"
24 #include "base/values.h"
25 #include "content/browser/child_process_security_policy_impl.h"
26 #include "content/browser/cross_site_request_manager.h"
27 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
28 #include "content/browser/gpu/gpu_surface_tracker.h"
29 #include "content/browser/host_zoom_map_impl.h"
30 #include "content/browser/renderer_host/dip_util.h"
31 #include "content/browser/renderer_host/render_process_host_impl.h"
32 #include "content/browser/renderer_host/render_view_host_delegate.h"
33 #include "content/common/accessibility_messages.h"
34 #include "content/common/browser_plugin/browser_plugin_messages.h"
35 #include "content/common/desktop_notification_messages.h"
36 #include "content/common/drag_messages.h"
37 #include "content/common/input_messages.h"
38 #include "content/common/inter_process_time_ticks_converter.h"
39 #include "content/common/speech_recognition_messages.h"
40 #include "content/common/swapped_out_messages.h"
41 #include "content/common/view_messages.h"
42 #include "content/port/browser/render_view_host_delegate_view.h"
43 #include "content/port/browser/render_widget_host_view_port.h"
44 #include "content/public/browser/browser_accessibility_state.h"
45 #include "content/public/browser/browser_context.h"
46 #include "content/public/browser/browser_message_filter.h"
47 #include "content/public/browser/content_browser_client.h"
48 #include "content/public/browser/dom_operation_notification_details.h"
49 #include "content/public/browser/native_web_keyboard_event.h"
50 #include "content/public/browser/notification_details.h"
51 #include "content/public/browser/notification_service.h"
52 #include "content/public/browser/notification_types.h"
53 #include "content/public/browser/power_save_blocker.h"
54 #include "content/public/browser/render_view_host_observer.h"
55 #include "content/public/browser/user_metrics.h"
56 #include "content/public/common/bindings_policy.h"
57 #include "content/public/common/content_constants.h"
58 #include "content/public/common/content_switches.h"
59 #include "content/public/common/context_menu_params.h"
60 #include "content/public/common/result_codes.h"
61 #include "content/public/common/url_constants.h"
62 #include "content/public/common/url_utils.h"
63 #include "net/base/net_util.h"
64 #include "net/url_request/url_request_context_getter.h"
65 #include "third_party/skia/include/core/SkBitmap.h"
66 #include "ui/gfx/image/image_skia.h"
67 #include "ui/gfx/native_widget_types.h"
68 #include "ui/shell_dialogs/selected_file_info.h"
69 #include "ui/snapshot/snapshot.h"
70 #include "webkit/browser/fileapi/isolated_context.h"
71 #include "webkit/common/webdropdata.h"
73 #if defined(OS_MACOSX)
74 #include "content/browser/renderer_host/popup_menu_helper_mac.h"
75 #elif defined(OS_ANDROID)
76 #include "media/base/android/media_player_manager.h"
77 #endif
79 using base::TimeDelta;
80 using WebKit::WebConsoleMessage;
81 using WebKit::WebDragOperation;
82 using WebKit::WebDragOperationNone;
83 using WebKit::WebDragOperationsMask;
84 using WebKit::WebInputEvent;
85 using WebKit::WebMediaPlayerAction;
86 using WebKit::WebPluginAction;
88 namespace content {
89 namespace {
91 // Delay to wait on closing the WebContents for a beforeunload/unload handler to
92 // fire.
93 const int kUnloadTimeoutMS = 1000;
95 // Translate a WebKit text direction into a base::i18n one.
96 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
97 WebKit::WebTextDirection dir) {
98 switch (dir) {
99 case WebKit::WebTextDirectionLeftToRight:
100 return base::i18n::LEFT_TO_RIGHT;
101 case WebKit::WebTextDirectionRightToLeft:
102 return base::i18n::RIGHT_TO_LEFT;
103 default:
104 NOTREACHED();
105 return base::i18n::UNKNOWN_DIRECTION;
109 base::LazyInstance<std::vector<RenderViewHost::CreatedCallback> >
110 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
112 } // namespace
114 ///////////////////////////////////////////////////////////////////////////////
115 // RenderViewHost, public:
117 // static
118 RenderViewHost* RenderViewHost::FromID(int render_process_id,
119 int render_view_id) {
120 RenderWidgetHost* widget =
121 RenderWidgetHost::FromID(render_process_id, render_view_id);
122 if (!widget || !widget->IsRenderView())
123 return NULL;
124 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(widget));
127 // static
128 RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) {
129 DCHECK(rwh->IsRenderView());
130 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(rwh));
133 // static
134 void RenderViewHost::FilterURL(const RenderProcessHost* process,
135 bool empty_allowed,
136 GURL* url) {
137 RenderViewHostImpl::FilterURL(ChildProcessSecurityPolicyImpl::GetInstance(),
138 process, empty_allowed, url);
141 ///////////////////////////////////////////////////////////////////////////////
142 // RenderViewHostImpl, public:
144 // static
145 RenderViewHostImpl* RenderViewHostImpl::FromID(int render_process_id,
146 int render_view_id) {
147 return static_cast<RenderViewHostImpl*>(
148 RenderViewHost::FromID(render_process_id, render_view_id));
151 RenderViewHostImpl::RenderViewHostImpl(
152 SiteInstance* instance,
153 RenderViewHostDelegate* delegate,
154 RenderWidgetHostDelegate* widget_delegate,
155 int routing_id,
156 int main_frame_routing_id,
157 bool swapped_out,
158 SessionStorageNamespace* session_storage)
159 : RenderWidgetHostImpl(widget_delegate, instance->GetProcess(), routing_id),
160 delegate_(delegate),
161 instance_(static_cast<SiteInstanceImpl*>(instance)),
162 waiting_for_drag_context_response_(false),
163 enabled_bindings_(0),
164 navigations_suspended_(false),
165 has_accessed_initial_document_(false),
166 is_swapped_out_(swapped_out),
167 is_subframe_(false),
168 main_frame_id_(-1),
169 run_modal_reply_msg_(NULL),
170 run_modal_opener_id_(MSG_ROUTING_NONE),
171 is_waiting_for_beforeunload_ack_(false),
172 is_waiting_for_unload_ack_(false),
173 has_timed_out_on_unload_(false),
174 unload_ack_is_for_cross_site_transition_(false),
175 are_javascript_messages_suppressed_(false),
176 sudden_termination_allowed_(false),
177 session_storage_namespace_(
178 static_cast<SessionStorageNamespaceImpl*>(session_storage)),
179 render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING) {
180 DCHECK(session_storage_namespace_.get());
181 DCHECK(instance_.get());
182 CHECK(delegate_); // http://crbug.com/82827
184 if (main_frame_routing_id == MSG_ROUTING_NONE)
185 main_frame_routing_id = GetProcess()->GetNextRoutingID();
187 main_render_frame_host_.reset(
188 new RenderFrameHostImpl(this, main_frame_routing_id, is_swapped_out_));
190 GetProcess()->EnableSendQueue();
192 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
193 g_created_callbacks.Get().at(i).Run(this);
195 #if defined(OS_ANDROID)
196 media_player_manager_ = media::MediaPlayerManager::Create(this);
197 #endif
200 RenderViewHostImpl::~RenderViewHostImpl() {
201 FOR_EACH_OBSERVER(
202 RenderViewHostObserver, observers_, RenderViewHostDestruction());
204 ClearPowerSaveBlockers();
206 GetDelegate()->RenderViewDeleted(this);
208 // Be sure to clean up any leftover state from cross-site requests.
209 CrossSiteRequestManager::GetInstance()->SetHasPendingCrossSiteRequest(
210 GetProcess()->GetID(), GetRoutingID(), false);
213 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
214 return delegate_;
217 SiteInstance* RenderViewHostImpl::GetSiteInstance() const {
218 return instance_.get();
221 bool RenderViewHostImpl::CreateRenderView(
222 const string16& frame_name,
223 int opener_route_id,
224 int32 max_page_id) {
225 TRACE_EVENT0("renderer_host", "RenderViewHostImpl::CreateRenderView");
226 DCHECK(!IsRenderViewLive()) << "Creating view twice";
228 // The process may (if we're sharing a process with another host that already
229 // initialized it) or may not (we have our own process or the old process
230 // crashed) have been initialized. Calling Init multiple times will be
231 // ignored, so this is safe.
232 if (!GetProcess()->Init())
233 return false;
234 DCHECK(GetProcess()->HasConnection());
235 DCHECK(GetProcess()->GetBrowserContext());
237 renderer_initialized_ = true;
239 GpuSurfaceTracker::Get()->SetSurfaceHandle(
240 surface_id(), GetCompositingSurface());
242 // Ensure the RenderView starts with a next_page_id larger than any existing
243 // page ID it might be asked to render.
244 int32 next_page_id = 1;
245 if (max_page_id > -1)
246 next_page_id = max_page_id + 1;
248 ViewMsg_New_Params params;
249 params.renderer_preferences =
250 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
251 params.web_preferences = delegate_->GetWebkitPrefs();
252 params.view_id = GetRoutingID();
253 params.main_frame_routing_id = main_render_frame_host_->routing_id();
254 params.surface_id = surface_id();
255 params.session_storage_namespace_id = session_storage_namespace_->id();
256 params.frame_name = frame_name;
257 // Ensure the RenderView sets its opener correctly.
258 params.opener_route_id = opener_route_id;
259 params.swapped_out = is_swapped_out_;
260 params.next_page_id = next_page_id;
261 GetWebScreenInfo(&params.screen_info);
262 params.accessibility_mode = accessibility_mode();
263 params.allow_partial_swap = !GetProcess()->IsGuest();
265 Send(new ViewMsg_New(params));
267 // If it's enabled, tell the renderer to set up the Javascript bindings for
268 // sending messages back to the browser.
269 if (GetProcess()->IsGuest())
270 DCHECK_EQ(0, enabled_bindings_);
271 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
272 // Let our delegate know that we created a RenderView.
273 delegate_->RenderViewCreated(this);
275 FOR_EACH_OBSERVER(
276 RenderViewHostObserver, observers_, RenderViewHostInitialized());
278 return true;
281 bool RenderViewHostImpl::IsRenderViewLive() const {
282 return GetProcess()->HasConnection() && renderer_initialized_;
285 bool RenderViewHostImpl::IsSubframe() const {
286 return is_subframe_;
289 void RenderViewHostImpl::SyncRendererPrefs() {
290 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(),
291 delegate_->GetRendererPrefs(
292 GetProcess()->GetBrowserContext())));
295 void RenderViewHostImpl::Navigate(const ViewMsg_Navigate_Params& params) {
296 TRACE_EVENT0("renderer_host", "RenderViewHostImpl::Navigate");
297 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
298 // so do not grant them the ability to request additional URLs.
299 if (!GetProcess()->IsGuest()) {
300 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
301 GetProcess()->GetID(), params.url);
302 if (params.url.SchemeIs(chrome::kDataScheme) &&
303 params.base_url_for_data_url.SchemeIs(chrome::kFileScheme)) {
304 // If 'data:' is used, and we have a 'file:' base url, grant access to
305 // local files.
306 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
307 GetProcess()->GetID(), params.base_url_for_data_url);
311 // Only send the message if we aren't suspended at the start of a cross-site
312 // request.
313 if (navigations_suspended_) {
314 // Shouldn't be possible to have a second navigation while suspended, since
315 // navigations will only be suspended during a cross-site request. If a
316 // second navigation occurs, WebContentsImpl will cancel this pending RVH
317 // create a new pending RVH.
318 DCHECK(!suspended_nav_params_.get());
319 suspended_nav_params_.reset(new ViewMsg_Navigate_Params(params));
320 } else {
321 // Get back to a clean state, in case we start a new navigation without
322 // completing a RVH swap or unload handler.
323 SetSwappedOut(false);
325 Send(new ViewMsg_Navigate(GetRoutingID(), params));
328 // Force the throbber to start. We do this because WebKit's "started
329 // loading" message will be received asynchronously from the UI of the
330 // browser. But we want to keep the throbber in sync with what's happening
331 // in the UI. For example, we want to start throbbing immediately when the
332 // user naivgates even if the renderer is delayed. There is also an issue
333 // with the throbber starting because the WebUI (which controls whether the
334 // favicon is displayed) happens synchronously. If the start loading
335 // messages was asynchronous, then the default favicon would flash in.
337 // WebKit doesn't send throb notifications for JavaScript URLs, so we
338 // don't want to either.
339 if (!params.url.SchemeIs(chrome::kJavaScriptScheme))
340 delegate_->DidStartLoading(this);
342 FOR_EACH_OBSERVER(RenderViewHostObserver, observers_, Navigate(params.url));
345 void RenderViewHostImpl::NavigateToURL(const GURL& url) {
346 ViewMsg_Navigate_Params params;
347 params.page_id = -1;
348 params.pending_history_list_offset = -1;
349 params.current_history_list_offset = -1;
350 params.current_history_list_length = 0;
351 params.url = url;
352 params.transition = PAGE_TRANSITION_LINK;
353 params.navigation_type = ViewMsg_Navigate_Type::NORMAL;
354 Navigate(params);
357 void RenderViewHostImpl::SetNavigationsSuspended(
358 bool suspend,
359 const base::TimeTicks& proceed_time) {
360 // This should only be called to toggle the state.
361 DCHECK(navigations_suspended_ != suspend);
363 navigations_suspended_ = suspend;
364 if (!suspend && suspended_nav_params_) {
365 // There's navigation message params waiting to be sent. Now that we're not
366 // suspended anymore, resume navigation by sending them. If we were swapped
367 // out, we should also stop filtering out the IPC messages now.
368 SetSwappedOut(false);
370 DCHECK(!proceed_time.is_null());
371 suspended_nav_params_->browser_navigation_start = proceed_time;
372 Send(new ViewMsg_Navigate(GetRoutingID(), *suspended_nav_params_.get()));
373 suspended_nav_params_.reset();
377 void RenderViewHostImpl::CancelSuspendedNavigations() {
378 // Clear any state if a pending navigation is canceled or pre-empted.
379 if (suspended_nav_params_)
380 suspended_nav_params_.reset();
381 navigations_suspended_ = false;
384 void RenderViewHostImpl::FirePageBeforeUnload(bool for_cross_site_transition) {
385 if (!IsRenderViewLive()) {
386 // This RenderViewHostImpl doesn't have a live renderer, so just
387 // skip running the onbeforeunload handler.
388 is_waiting_for_beforeunload_ack_ = true; // Checked by OnShouldCloseACK.
389 unload_ack_is_for_cross_site_transition_ = for_cross_site_transition;
390 base::TimeTicks now = base::TimeTicks::Now();
391 OnShouldCloseACK(true, now, now);
392 return;
395 // This may be called more than once (if the user clicks the tab close button
396 // several times, or if she clicks the tab close button then the browser close
397 // button), and we only send the message once.
398 if (is_waiting_for_beforeunload_ack_) {
399 // Some of our close messages could be for the tab, others for cross-site
400 // transitions. We always want to think it's for closing the tab if any
401 // of the messages were, since otherwise it might be impossible to close
402 // (if there was a cross-site "close" request pending when the user clicked
403 // the close button). We want to keep the "for cross site" flag only if
404 // both the old and the new ones are also for cross site.
405 unload_ack_is_for_cross_site_transition_ =
406 unload_ack_is_for_cross_site_transition_ && for_cross_site_transition;
407 } else {
408 // Start the hang monitor in case the renderer hangs in the beforeunload
409 // handler.
410 is_waiting_for_beforeunload_ack_ = true;
411 unload_ack_is_for_cross_site_transition_ = for_cross_site_transition;
412 // Increment the in-flight event count, to ensure that input events won't
413 // cancel the timeout timer.
414 increment_in_flight_event_count();
415 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
416 send_should_close_start_time_ = base::TimeTicks::Now();
417 Send(new ViewMsg_ShouldClose(GetRoutingID()));
421 void RenderViewHostImpl::SwapOut() {
422 // This will be set back to false in OnSwapOutACK, just before we replace
423 // this RVH with the pending RVH.
424 is_waiting_for_unload_ack_ = true;
425 // Start the hang monitor in case the renderer hangs in the unload handler.
426 // Increment the in-flight event count, to ensure that input events won't
427 // cancel the timeout timer.
428 increment_in_flight_event_count();
429 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
431 if (IsRenderViewLive()) {
432 Send(new ViewMsg_SwapOut(GetRoutingID()));
433 } else {
434 // This RenderViewHost doesn't have a live renderer, so just skip the unload
435 // event.
436 OnSwappedOut(true);
440 void RenderViewHostImpl::OnSwapOutACK() {
441 OnSwappedOut(false);
444 void RenderViewHostImpl::OnSwappedOut(bool timed_out) {
445 // Stop the hang monitor now that the unload handler has finished.
446 decrement_in_flight_event_count();
447 StopHangMonitorTimeout();
448 is_waiting_for_unload_ack_ = false;
449 has_timed_out_on_unload_ = timed_out;
450 delegate_->SwappedOut(this);
453 void RenderViewHostImpl::WasSwappedOut() {
454 // Don't bother reporting hung state anymore.
455 StopHangMonitorTimeout();
457 // If we have timed out on running the unload handler, we consider
458 // the process hung and we should terminate it if there are no other tabs
459 // using the process. If there are other views using this process, the
460 // unresponsive renderer timeout will catch it.
461 bool hung = has_timed_out_on_unload_;
463 // Now that we're no longer the active RVH in the tab, start filtering out
464 // most IPC messages. Usually the renderer will have stopped sending
465 // messages as of OnSwapOutACK. However, we may have timed out waiting
466 // for that message, and additional IPC messages may keep streaming in.
467 // We filter them out, as long as that won't cause problems (e.g., we
468 // still allow synchronous messages through).
469 SetSwappedOut(true);
471 // If we are not running the renderer in process and no other tab is using
472 // the hung process, consider it eligible to be killed, assuming it is a real
473 // process (unit tests don't have real processes).
474 if (hung) {
475 base::ProcessHandle process_handle = GetProcess()->GetHandle();
476 int views = 0;
478 // Count the number of widget hosts for the process, which is equivalent to
479 // views using the process as of this writing.
480 RenderWidgetHost::List widgets = RenderWidgetHost::GetRenderWidgetHosts();
481 for (size_t i = 0; i < widgets.size(); ++i) {
482 if (widgets[i]->GetProcess()->GetID() == GetProcess()->GetID())
483 ++views;
486 if (!RenderProcessHost::run_renderer_in_process() &&
487 process_handle && views <= 1) {
488 // The process can safely be terminated, only if WebContents sets
489 // SuddenTerminationAllowed, which indicates that the timer has expired.
490 // This is not the case if we load data URLs or about:blank. The reason
491 // is that those have no network requests and this code is hit without
492 // setting the unresponsiveness timer. This allows a corner case where a
493 // navigation to a data URL will leave a process running, if the
494 // beforeunload handler completes fine, but the unload handler hangs.
495 // At this time, the complexity to solve this edge case is not worthwhile.
496 if (SuddenTerminationAllowed()) {
497 // We should kill the process, but for now, just log the data so we can
498 // diagnose the kill rate and investigate if separate timer is needed.
499 // http://crbug.com/104346.
501 // Log a histogram point to help us diagnose how many of those kills
502 // we have performed. 1 is the enum value for RendererType Normal for
503 // the histogram.
504 UMA_HISTOGRAM_PERCENTAGE(
505 "BrowserRenderProcessHost.ChildKillsUnresponsive", 1);
510 // Inform the renderer that it can exit if no one else is using it.
511 Send(new ViewMsg_WasSwappedOut(GetRoutingID()));
514 void RenderViewHostImpl::ClosePage() {
515 // Start the hang monitor in case the renderer hangs in the unload handler.
516 is_waiting_for_unload_ack_ = true;
517 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
519 if (IsRenderViewLive()) {
520 // Since we are sending an IPC message to the renderer, increase the event
521 // count to prevent the hang monitor timeout from being stopped by input
522 // event acknowledgements.
523 increment_in_flight_event_count();
525 // TODO(creis): Should this be moved to Shutdown? It may not be called for
526 // RenderViewHosts that have been swapped out.
527 NotificationService::current()->Notify(
528 NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
529 Source<RenderViewHost>(this),
530 NotificationService::NoDetails());
532 Send(new ViewMsg_ClosePage(GetRoutingID()));
533 } else {
534 // This RenderViewHost doesn't have a live renderer, so just skip the unload
535 // event and close the page.
536 ClosePageIgnoringUnloadEvents();
540 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
541 StopHangMonitorTimeout();
542 is_waiting_for_beforeunload_ack_ = false;
543 is_waiting_for_unload_ack_ = false;
545 sudden_termination_allowed_ = true;
546 delegate_->Close(this);
549 bool RenderViewHostImpl::HasPendingCrossSiteRequest() {
550 return CrossSiteRequestManager::GetInstance()->HasPendingCrossSiteRequest(
551 GetProcess()->GetID(), GetRoutingID());
554 void RenderViewHostImpl::SetHasPendingCrossSiteRequest(
555 bool has_pending_request) {
556 CrossSiteRequestManager::GetInstance()->SetHasPendingCrossSiteRequest(
557 GetProcess()->GetID(), GetRoutingID(), has_pending_request);
560 #if defined(OS_ANDROID)
561 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
562 float x,
563 float y) {
564 Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
565 request_id, x, y));
568 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
569 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
571 #endif
573 void RenderViewHostImpl::DragTargetDragEnter(
574 const WebDropData& drop_data,
575 const gfx::Point& client_pt,
576 const gfx::Point& screen_pt,
577 WebDragOperationsMask operations_allowed,
578 int key_modifiers) {
579 const int renderer_id = GetProcess()->GetID();
580 ChildProcessSecurityPolicyImpl* policy =
581 ChildProcessSecurityPolicyImpl::GetInstance();
583 // The URL could have been cobbled together from any highlighted text string,
584 // and can't be interpreted as a capability.
585 WebDropData filtered_data(drop_data);
586 FilterURL(policy, GetProcess(), true, &filtered_data.url);
588 // The filenames vector, on the other hand, does represent a capability to
589 // access the given files.
590 fileapi::IsolatedContext::FileInfoSet files;
591 for (std::vector<WebDropData::FileInfo>::iterator iter(
592 filtered_data.filenames.begin());
593 iter != filtered_data.filenames.end(); ++iter) {
594 // A dragged file may wind up as the value of an input element, or it
595 // may be used as the target of a navigation instead. We don't know
596 // which will happen at this point, so generously grant both access
597 // and request permissions to the specific file to cover both cases.
598 // We do not give it the permission to request all file:// URLs.
599 base::FilePath path =
600 base::FilePath::FromUTF8Unsafe(UTF16ToUTF8(iter->path));
602 // Make sure we have the same display_name as the one we register.
603 if (iter->display_name.empty()) {
604 std::string name;
605 files.AddPath(path, &name);
606 iter->display_name = UTF8ToUTF16(name);
607 } else {
608 files.AddPathWithName(path, UTF16ToUTF8(iter->display_name));
611 policy->GrantRequestSpecificFileURL(renderer_id,
612 net::FilePathToFileURL(path));
614 // If the renderer already has permission to read these paths, we don't need
615 // to re-grant them. This prevents problems with DnD for files in the CrOS
616 // file manager--the file manager already had read/write access to those
617 // directories, but dragging a file would cause the read/write access to be
618 // overwritten with read-only access, making them impossible to delete or
619 // rename until the renderer was killed.
620 if (!policy->CanReadFile(renderer_id, path)) {
621 policy->GrantReadFile(renderer_id, path);
622 // Allow dragged directories to be enumerated by the child process.
623 // Note that we can't tell a file from a directory at this point.
624 policy->GrantReadDirectory(renderer_id, path);
628 fileapi::IsolatedContext* isolated_context =
629 fileapi::IsolatedContext::GetInstance();
630 DCHECK(isolated_context);
631 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
632 files);
633 if (!filesystem_id.empty()) {
634 // Grant the permission iff the ID is valid.
635 policy->GrantReadFileSystem(renderer_id, filesystem_id);
637 filtered_data.filesystem_id = UTF8ToUTF16(filesystem_id);
639 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
640 screen_pt, operations_allowed,
641 key_modifiers));
644 void RenderViewHostImpl::DragTargetDragOver(
645 const gfx::Point& client_pt,
646 const gfx::Point& screen_pt,
647 WebDragOperationsMask operations_allowed,
648 int key_modifiers) {
649 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
650 operations_allowed, key_modifiers));
653 void RenderViewHostImpl::DragTargetDragLeave() {
654 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
657 void RenderViewHostImpl::DragTargetDrop(
658 const gfx::Point& client_pt,
659 const gfx::Point& screen_pt,
660 int key_modifiers) {
661 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
662 key_modifiers));
665 void RenderViewHostImpl::DesktopNotificationPermissionRequestDone(
666 int callback_context) {
667 Send(new DesktopNotificationMsg_PermissionRequestDone(
668 GetRoutingID(), callback_context));
671 void RenderViewHostImpl::DesktopNotificationPostDisplay(int callback_context) {
672 Send(new DesktopNotificationMsg_PostDisplay(GetRoutingID(),
673 callback_context));
676 void RenderViewHostImpl::DesktopNotificationPostError(int notification_id,
677 const string16& message) {
678 Send(new DesktopNotificationMsg_PostError(
679 GetRoutingID(), notification_id, message));
682 void RenderViewHostImpl::DesktopNotificationPostClose(int notification_id,
683 bool by_user) {
684 Send(new DesktopNotificationMsg_PostClose(
685 GetRoutingID(), notification_id, by_user));
688 void RenderViewHostImpl::DesktopNotificationPostClick(int notification_id) {
689 Send(new DesktopNotificationMsg_PostClick(GetRoutingID(), notification_id));
692 void RenderViewHostImpl::ExecuteJavascriptInWebFrame(
693 const string16& frame_xpath,
694 const string16& jscript) {
695 Send(new ViewMsg_ScriptEvalRequest(GetRoutingID(), frame_xpath, jscript,
696 0, false));
699 void RenderViewHostImpl::ExecuteJavascriptInWebFrameCallbackResult(
700 const string16& frame_xpath,
701 const string16& jscript,
702 const JavascriptResultCallback& callback) {
703 static int next_id = 1;
704 int key = next_id++;
705 Send(new ViewMsg_ScriptEvalRequest(GetRoutingID(), frame_xpath, jscript,
706 key, true));
707 javascript_callbacks_.insert(std::make_pair(key, callback));
710 void RenderViewHostImpl::JavaScriptDialogClosed(IPC::Message* reply_msg,
711 bool success,
712 const string16& user_input) {
713 GetProcess()->SetIgnoreInputEvents(false);
714 bool is_waiting =
715 is_waiting_for_beforeunload_ack_ || is_waiting_for_unload_ack_;
717 // If we are executing as part of (before)unload event handling, we don't
718 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
719 // leave the current page. In this case, use the regular timeout value used
720 // during the (before)unload handling.
721 if (is_waiting) {
722 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
723 success ? kUnloadTimeoutMS : hung_renderer_delay_ms_));
726 ViewHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
727 success, user_input);
728 Send(reply_msg);
730 // If we are waiting for an unload or beforeunload ack and the user has
731 // suppressed messages, kill the tab immediately; a page that's spamming
732 // alerts in onbeforeunload is presumably malicious, so there's no point in
733 // continuing to run its script and dragging out the process.
734 // This must be done after sending the reply since RenderView can't close
735 // correctly while waiting for a response.
736 if (is_waiting && are_javascript_messages_suppressed_)
737 delegate_->RendererUnresponsive(this, is_waiting);
740 void RenderViewHostImpl::DragSourceEndedAt(
741 int client_x, int client_y, int screen_x, int screen_y,
742 WebDragOperation operation) {
743 Send(new DragMsg_SourceEndedOrMoved(
744 GetRoutingID(),
745 gfx::Point(client_x, client_y),
746 gfx::Point(screen_x, screen_y),
747 true, operation));
750 void RenderViewHostImpl::DragSourceMovedTo(
751 int client_x, int client_y, int screen_x, int screen_y) {
752 Send(new DragMsg_SourceEndedOrMoved(
753 GetRoutingID(),
754 gfx::Point(client_x, client_y),
755 gfx::Point(screen_x, screen_y),
756 false, WebDragOperationNone));
759 void RenderViewHostImpl::DragSourceSystemDragEnded() {
760 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
763 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
764 // Ensure we aren't granting WebUI bindings to a process that has already
765 // been used for non-privileged views.
766 if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
767 GetProcess()->HasConnection() &&
768 !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
769 GetProcess()->GetID())) {
770 // This process has no bindings yet. Make sure it does not have more
771 // than this single active view.
772 RenderProcessHostImpl* process =
773 static_cast<RenderProcessHostImpl*>(GetProcess());
774 if (process->GetActiveViewCount() > 1)
775 return;
778 // Never grant any bindings to browser plugin guests.
779 if (GetProcess()->IsGuest()) {
780 NOTREACHED() << "Never grant bindings to a guest process.";
781 return;
784 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
785 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
786 GetProcess()->GetID());
789 enabled_bindings_ |= bindings_flags;
790 if (renderer_initialized_)
791 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
794 int RenderViewHostImpl::GetEnabledBindings() const {
795 return enabled_bindings_;
798 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
799 const std::string& value) {
800 // This is a sanity check before telling the renderer to enable the property.
801 // It could lie and send the corresponding IPC messages anyway, but we will
802 // not act on them if enabled_bindings_ doesn't agree. If we get here without
803 // WebUI bindings, kill the renderer process.
804 if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
805 Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
806 } else {
807 RecordAction(UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
808 base::KillProcess(
809 GetProcess()->GetHandle(), content::RESULT_CODE_KILLED, false);
813 void RenderViewHostImpl::GotFocus() {
814 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
816 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
817 if (view)
818 view->GotFocus();
821 void RenderViewHostImpl::LostCapture() {
822 RenderWidgetHostImpl::LostCapture();
823 delegate_->LostCapture();
826 void RenderViewHostImpl::LostMouseLock() {
827 RenderWidgetHostImpl::LostMouseLock();
828 delegate_->LostMouseLock();
831 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
832 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
835 void RenderViewHostImpl::FilesSelectedInChooser(
836 const std::vector<ui::SelectedFileInfo>& files,
837 int permissions) {
838 // Grant the security access requested to the given files.
839 for (size_t i = 0; i < files.size(); ++i) {
840 const ui::SelectedFileInfo& file = files[i];
841 ChildProcessSecurityPolicyImpl::GetInstance()->GrantPermissionsForFile(
842 GetProcess()->GetID(), file.local_path, permissions);
844 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
847 void RenderViewHostImpl::DirectoryEnumerationFinished(
848 int request_id,
849 const std::vector<base::FilePath>& files) {
850 // Grant the security access requested to the given files.
851 for (std::vector<base::FilePath>::const_iterator file = files.begin();
852 file != files.end(); ++file) {
853 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
854 GetProcess()->GetID(), *file);
856 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
857 request_id,
858 files));
861 void RenderViewHostImpl::LoadStateChanged(
862 const GURL& url,
863 const net::LoadStateWithParam& load_state,
864 uint64 upload_position,
865 uint64 upload_size) {
866 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
869 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
870 return sudden_termination_allowed_ ||
871 GetProcess()->SuddenTerminationAllowed();
874 ///////////////////////////////////////////////////////////////////////////////
875 // RenderViewHostImpl, IPC message handlers:
877 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
878 if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
879 return true;
881 // Filter out most IPC messages if this renderer is swapped out.
882 // We still want to handle certain ACKs to keep our state consistent.
883 if (is_swapped_out_) {
884 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
885 // If this is a synchronous message and we decided not to handle it,
886 // we must send an error reply, or else the renderer will be stuck
887 // and won't respond to future requests.
888 if (msg.is_sync()) {
889 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
890 reply->set_reply_error();
891 Send(reply);
893 // Don't continue looking for someone to handle it.
894 return true;
898 ObserverListBase<RenderViewHostObserver>::Iterator it(observers_);
899 RenderViewHostObserver* observer;
900 while ((observer = it.GetNext()) != NULL) {
901 if (observer->OnMessageReceived(msg))
902 return true;
905 if (delegate_->OnMessageReceived(this, msg))
906 return true;
908 // TODO(jochen): Consider removing message handlers that only add a this
909 // pointer and forward the messages to the RenderViewHostDelegate. The
910 // respective delegates can handle the messages themselves in their
911 // OnMessageReceived implementation.
912 bool handled = true;
913 bool msg_is_ok = true;
914 IPC_BEGIN_MESSAGE_MAP_EX(RenderViewHostImpl, msg, msg_is_ok)
915 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView)
916 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget)
917 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget,
918 OnShowFullscreenWidget)
919 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunModal, OnRunModal)
920 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
921 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewGone, OnRenderViewGone)
922 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStartProvisionalLoadForFrame,
923 OnDidStartProvisionalLoadForFrame)
924 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRedirectProvisionalLoad,
925 OnDidRedirectProvisionalLoad)
926 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFailProvisionalLoadWithError,
927 OnDidFailProvisionalLoadWithError)
928 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_FrameNavigate, OnNavigate(msg))
929 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState)
930 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTitle, OnUpdateTitle)
931 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateEncoding, OnUpdateEncoding)
932 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL)
933 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateInspectorSetting,
934 OnUpdateInspectorSetting)
935 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
936 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
937 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStartLoading, OnDidStartLoading)
938 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStopLoading, OnDidStopLoading)
939 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeLoadProgress,
940 OnDidChangeLoadProgress)
941 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisownOpener, OnDidDisownOpener)
942 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
943 OnDocumentAvailableInMainFrame)
944 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentOnLoadCompletedInMainFrame,
945 OnDocumentOnLoadCompletedInMainFrame)
946 IPC_MESSAGE_HANDLER(ViewHostMsg_ContextMenu, OnContextMenu)
947 IPC_MESSAGE_HANDLER(ViewHostMsg_ToggleFullscreen, OnToggleFullscreen)
948 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenURL, OnOpenURL)
949 IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
950 OnDidContentsPreferredSizeChange)
951 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollOffset,
952 OnDidChangeScrollOffset)
953 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollbarsForMainFrame,
954 OnDidChangeScrollbarsForMainFrame)
955 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame,
956 OnDidChangeScrollOffsetPinningForMainFrame)
957 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeNumWheelEvents,
958 OnDidChangeNumWheelEvents)
959 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
960 OnRouteCloseEvent)
961 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteMessageEvent, OnRouteMessageEvent)
962 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunJavaScriptMessage,
963 OnRunJavaScriptMessage)
964 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunBeforeUnloadConfirm,
965 OnRunBeforeUnloadConfirm)
966 IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging)
967 IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
968 IPC_MESSAGE_HANDLER(DragHostMsg_TargetDrop_ACK, OnTargetDropACK)
969 IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
970 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
971 IPC_MESSAGE_HANDLER(ViewHostMsg_AddMessageToConsole, OnAddMessageToConsole)
972 IPC_MESSAGE_HANDLER(ViewHostMsg_ShouldClose_ACK, OnShouldCloseACK)
973 IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK)
974 IPC_MESSAGE_HANDLER(ViewHostMsg_SwapOut_ACK, OnSwapOutACK)
975 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
976 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
977 OnSelectionBoundsChanged)
978 IPC_MESSAGE_HANDLER(ViewHostMsg_ScriptEvalResponse, OnScriptEvalResponse)
979 IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
980 IPC_MESSAGE_HANDLER(ViewHostMsg_MediaNotification, OnMediaNotification)
981 IPC_MESSAGE_HANDLER(ViewHostMsg_GetWindowSnapshot, OnGetWindowSnapshot)
982 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_RequestPermission,
983 OnRequestDesktopNotificationPermission)
984 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show,
985 OnShowDesktopNotification)
986 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel,
987 OnCancelDesktopNotification)
988 #if defined(OS_MACOSX) || defined(OS_ANDROID)
989 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowPopup, OnShowPopup)
990 #endif
991 IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
992 IPC_MESSAGE_HANDLER(ViewHostMsg_DidAccessInitialDocument,
993 OnDidAccessInitialDocument)
994 IPC_MESSAGE_HANDLER(ViewHostMsg_DomOperationResponse,
995 OnDomOperationResponse)
996 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Notifications,
997 OnAccessibilityNotifications)
998 // Have the super handle all other messages.
999 IPC_MESSAGE_UNHANDLED(
1000 handled = RenderWidgetHostImpl::OnMessageReceived(msg))
1001 IPC_END_MESSAGE_MAP_EX()
1003 if (!msg_is_ok) {
1004 // The message had a handler, but its de-serialization failed.
1005 // Kill the renderer.
1006 RecordAction(UserMetricsAction("BadMessageTerminate_RVH"));
1007 GetProcess()->ReceivedBadMessage();
1010 return handled;
1013 void RenderViewHostImpl::Shutdown() {
1014 // If we are being run modally (see RunModal), then we need to cleanup.
1015 if (run_modal_reply_msg_) {
1016 Send(run_modal_reply_msg_);
1017 run_modal_reply_msg_ = NULL;
1018 RenderViewHostImpl* opener =
1019 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1020 if (opener) {
1021 opener->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
1022 hung_renderer_delay_ms_));
1023 // Balance out the decrement when we got created.
1024 opener->increment_in_flight_event_count();
1026 run_modal_opener_id_ = MSG_ROUTING_NONE;
1029 RenderWidgetHostImpl::Shutdown();
1032 bool RenderViewHostImpl::IsRenderView() const {
1033 return true;
1036 void RenderViewHostImpl::CreateNewWindow(
1037 int route_id,
1038 int main_frame_route_id,
1039 const ViewHostMsg_CreateWindow_Params& params,
1040 SessionStorageNamespace* session_storage_namespace) {
1041 ViewHostMsg_CreateWindow_Params validated_params(params);
1042 ChildProcessSecurityPolicyImpl* policy =
1043 ChildProcessSecurityPolicyImpl::GetInstance();
1044 FilterURL(policy, GetProcess(), false, &validated_params.target_url);
1045 FilterURL(policy, GetProcess(), false, &validated_params.opener_url);
1046 FilterURL(policy, GetProcess(), true,
1047 &validated_params.opener_security_origin);
1049 delegate_->CreateNewWindow(route_id, main_frame_route_id,
1050 validated_params, session_storage_namespace);
1053 void RenderViewHostImpl::CreateNewWidget(int route_id,
1054 WebKit::WebPopupType popup_type) {
1055 delegate_->CreateNewWidget(route_id, popup_type);
1058 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
1059 delegate_->CreateNewFullscreenWidget(route_id);
1062 void RenderViewHostImpl::OnShowView(int route_id,
1063 WindowOpenDisposition disposition,
1064 const gfx::Rect& initial_pos,
1065 bool user_gesture) {
1066 if (!is_swapped_out_) {
1067 delegate_->ShowCreatedWindow(
1068 route_id, disposition, initial_pos, user_gesture);
1070 Send(new ViewMsg_Move_ACK(route_id));
1073 void RenderViewHostImpl::OnShowWidget(int route_id,
1074 const gfx::Rect& initial_pos) {
1075 if (!is_swapped_out_)
1076 delegate_->ShowCreatedWidget(route_id, initial_pos);
1077 Send(new ViewMsg_Move_ACK(route_id));
1080 void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) {
1081 if (!is_swapped_out_)
1082 delegate_->ShowCreatedFullscreenWidget(route_id);
1083 Send(new ViewMsg_Move_ACK(route_id));
1086 void RenderViewHostImpl::OnRunModal(int opener_id, IPC::Message* reply_msg) {
1087 DCHECK(!run_modal_reply_msg_);
1088 run_modal_reply_msg_ = reply_msg;
1089 run_modal_opener_id_ = opener_id;
1091 RecordAction(UserMetricsAction("ShowModalDialog"));
1093 RenderViewHostImpl* opener =
1094 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1095 if (opener) {
1096 opener->StopHangMonitorTimeout();
1097 // The ack for the mouse down won't come until the dialog closes, so fake it
1098 // so that we don't get a timeout.
1099 opener->decrement_in_flight_event_count();
1102 // TODO(darin): Bug 1107929: Need to inform our delegate to show this view in
1103 // an app-modal fashion.
1106 void RenderViewHostImpl::OnRenderViewReady() {
1107 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1108 SendScreenRects();
1109 WasResized();
1110 delegate_->RenderViewReady(this);
1113 void RenderViewHostImpl::OnRenderViewGone(int status, int exit_code) {
1114 // Keep the termination status so we can get at it later when we
1115 // need to know why it died.
1116 render_view_termination_status_ =
1117 static_cast<base::TerminationStatus>(status);
1119 // Reset state.
1120 ClearPowerSaveBlockers();
1121 main_frame_id_ = -1;
1123 // Our base class RenderWidgetHost needs to reset some stuff.
1124 RendererExited(render_view_termination_status_, exit_code);
1126 delegate_->RenderViewTerminated(this,
1127 static_cast<base::TerminationStatus>(status),
1128 exit_code);
1131 void RenderViewHostImpl::OnDidStartProvisionalLoadForFrame(
1132 int64 frame_id,
1133 int64 parent_frame_id,
1134 bool is_main_frame,
1135 const GURL& url) {
1136 delegate_->DidStartProvisionalLoadForFrame(
1137 this, frame_id, parent_frame_id, is_main_frame, url);
1140 void RenderViewHostImpl::OnDidRedirectProvisionalLoad(
1141 int32 page_id,
1142 const GURL& source_url,
1143 const GURL& target_url) {
1144 delegate_->DidRedirectProvisionalLoad(
1145 this, page_id, source_url, target_url);
1148 void RenderViewHostImpl::OnDidFailProvisionalLoadWithError(
1149 const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
1150 delegate_->DidFailProvisionalLoadWithError(this, params);
1153 // Called when the renderer navigates. For every frame loaded, we'll get this
1154 // notification containing parameters identifying the navigation.
1156 // Subframes are identified by the page transition type. For subframes loaded
1157 // as part of a wider page load, the page_id will be the same as for the top
1158 // level frame. If the user explicitly requests a subframe navigation, we will
1159 // get a new page_id because we need to create a new navigation entry for that
1160 // action.
1161 void RenderViewHostImpl::OnNavigate(const IPC::Message& msg) {
1162 // Read the parameters out of the IPC message directly to avoid making another
1163 // copy when we filter the URLs.
1164 PickleIterator iter(msg);
1165 ViewHostMsg_FrameNavigate_Params validated_params;
1166 if (!IPC::ParamTraits<ViewHostMsg_FrameNavigate_Params>::
1167 Read(&msg, &iter, &validated_params))
1168 return;
1170 // If we're waiting for a cross-site beforeunload ack from this renderer and
1171 // we receive a Navigate message from the main frame, then the renderer was
1172 // navigating already and sent it before hearing the ViewMsg_Stop message.
1173 // We do not want to cancel the pending navigation in this case, since the
1174 // old page will soon be stopped. Instead, treat this as a beforeunload ack
1175 // to allow the pending navigation to continue.
1176 if (is_waiting_for_beforeunload_ack_ &&
1177 unload_ack_is_for_cross_site_transition_ &&
1178 PageTransitionIsMainFrame(validated_params.transition)) {
1179 OnShouldCloseACK(true, send_should_close_start_time_,
1180 base::TimeTicks::Now());
1181 return;
1184 // If we're waiting for an unload ack from this renderer and we receive a
1185 // Navigate message, then the renderer was navigating before it received the
1186 // unload request. It will either respond to the unload request soon or our
1187 // timer will expire. Either way, we should ignore this message, because we
1188 // have already committed to closing this renderer.
1189 if (is_waiting_for_unload_ack_)
1190 return;
1192 // Cache the main frame id, so we can use it for creating the frame tree
1193 // root node when needed.
1194 if (PageTransitionIsMainFrame(validated_params.transition)) {
1195 if (main_frame_id_ == -1) {
1196 main_frame_id_ = validated_params.frame_id;
1197 } else {
1198 // TODO(nasko): We plan to remove the usage of frame_id in navigation
1199 // and move to routing ids. This is in place to ensure that a
1200 // renderer is not misbehaving and sending us incorrect data.
1201 DCHECK_EQ(main_frame_id_, validated_params.frame_id);
1204 RenderProcessHost* process = GetProcess();
1206 // Attempts to commit certain off-limits URL should be caught more strictly
1207 // than our FilterURL checks below. If a renderer violates this policy, it
1208 // should be killed.
1209 if (!CanCommitURL(validated_params.url)) {
1210 VLOG(1) << "Blocked URL " << validated_params.url.spec();
1211 validated_params.url = GURL(kAboutBlankURL);
1212 RecordAction(UserMetricsAction("CanCommitURL_BlockedAndKilled"));
1213 // Kills the process.
1214 process->ReceivedBadMessage();
1217 // Now that something has committed, we don't need to track whether the
1218 // initial page has been accessed.
1219 has_accessed_initial_document_ = false;
1221 ChildProcessSecurityPolicyImpl* policy =
1222 ChildProcessSecurityPolicyImpl::GetInstance();
1223 // Without this check, an evil renderer can trick the browser into creating
1224 // a navigation entry for a banned URL. If the user clicks the back button
1225 // followed by the forward button (or clicks reload, or round-trips through
1226 // session restore, etc), we'll think that the browser commanded the
1227 // renderer to load the URL and grant the renderer the privileges to request
1228 // the URL. To prevent this attack, we block the renderer from inserting
1229 // banned URLs into the navigation controller in the first place.
1230 FilterURL(policy, process, false, &validated_params.url);
1231 FilterURL(policy, process, true, &validated_params.referrer.url);
1232 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
1233 it != validated_params.redirects.end(); ++it) {
1234 FilterURL(policy, process, false, &(*it));
1236 FilterURL(policy, process, true, &validated_params.searchable_form_url);
1237 FilterURL(policy, process, true, &validated_params.password_form.origin);
1238 FilterURL(policy, process, true, &validated_params.password_form.action);
1240 // Without this check, the renderer can trick the browser into using
1241 // filenames it can't access in a future session restore.
1242 if (!CanAccessFilesOfPageState(validated_params.page_state)) {
1243 GetProcess()->ReceivedBadMessage();
1244 return;
1247 delegate_->DidNavigate(this, validated_params);
1250 void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) {
1251 // Without this check, the renderer can trick the browser into using
1252 // filenames it can't access in a future session restore.
1253 if (!CanAccessFilesOfPageState(state)) {
1254 GetProcess()->ReceivedBadMessage();
1255 return;
1258 delegate_->UpdateState(this, page_id, state);
1261 void RenderViewHostImpl::OnUpdateTitle(
1262 int32 page_id,
1263 const string16& title,
1264 WebKit::WebTextDirection title_direction) {
1265 if (title.length() > kMaxTitleChars) {
1266 NOTREACHED() << "Renderer sent too many characters in title.";
1267 return;
1270 delegate_->UpdateTitle(this, page_id, title,
1271 WebTextDirectionToChromeTextDirection(
1272 title_direction));
1275 void RenderViewHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1276 delegate_->UpdateEncoding(this, encoding_name);
1279 void RenderViewHostImpl::OnUpdateTargetURL(int32 page_id, const GURL& url) {
1280 if (!is_swapped_out_)
1281 delegate_->UpdateTargetURL(page_id, url);
1283 // Send a notification back to the renderer that we are ready to
1284 // receive more target urls.
1285 Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1288 void RenderViewHostImpl::OnUpdateInspectorSetting(
1289 const std::string& key, const std::string& value) {
1290 GetContentClient()->browser()->UpdateInspectorSetting(
1291 this, key, value);
1294 void RenderViewHostImpl::OnClose() {
1295 // If the renderer is telling us to close, it has already run the unload
1296 // events, and we can take the fast path.
1297 ClosePageIgnoringUnloadEvents();
1300 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1301 if (!is_swapped_out_)
1302 delegate_->RequestMove(pos);
1303 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1306 void RenderViewHostImpl::OnDidStartLoading() {
1307 delegate_->DidStartLoading(this);
1310 void RenderViewHostImpl::OnDidStopLoading() {
1311 delegate_->DidStopLoading(this);
1314 void RenderViewHostImpl::OnDidChangeLoadProgress(double load_progress) {
1315 delegate_->DidChangeLoadProgress(load_progress);
1318 void RenderViewHostImpl::OnDidDisownOpener() {
1319 delegate_->DidDisownOpener(this);
1322 void RenderViewHostImpl::OnDocumentAvailableInMainFrame() {
1323 delegate_->DocumentAvailableInMainFrame(this);
1326 void RenderViewHostImpl::OnDocumentOnLoadCompletedInMainFrame(
1327 int32 page_id) {
1328 delegate_->DocumentOnLoadCompletedInMainFrame(this, page_id);
1331 void RenderViewHostImpl::OnContextMenu(const ContextMenuParams& params) {
1332 // Validate the URLs in |params|. If the renderer can't request the URLs
1333 // directly, don't show them in the context menu.
1334 ContextMenuParams validated_params(params);
1335 RenderProcessHost* process = GetProcess();
1336 ChildProcessSecurityPolicyImpl* policy =
1337 ChildProcessSecurityPolicyImpl::GetInstance();
1339 // We don't validate |unfiltered_link_url| so that this field can be used
1340 // when users want to copy the original link URL.
1341 FilterURL(policy, process, true, &validated_params.link_url);
1342 FilterURL(policy, process, true, &validated_params.src_url);
1343 FilterURL(policy, process, false, &validated_params.page_url);
1344 FilterURL(policy, process, true, &validated_params.frame_url);
1346 delegate_->ShowContextMenu(validated_params);
1349 void RenderViewHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1350 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1351 delegate_->ToggleFullscreenMode(enter_fullscreen);
1352 WasResized();
1355 void RenderViewHostImpl::OnOpenURL(
1356 const ViewHostMsg_OpenURL_Params& params) {
1357 GURL validated_url(params.url);
1358 FilterURL(ChildProcessSecurityPolicyImpl::GetInstance(),
1359 GetProcess(), false, &validated_url);
1361 delegate_->RequestOpenURL(
1362 this, validated_url, params.referrer, params.disposition, params.frame_id,
1363 params.is_cross_site_redirect);
1366 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1367 const gfx::Size& new_size) {
1368 delegate_->UpdatePreferredSize(new_size);
1371 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1372 delegate_->ResizeDueToAutoResize(new_size);
1375 void RenderViewHostImpl::OnDidChangeScrollOffset() {
1376 if (view_)
1377 view_->ScrollOffsetChanged();
1380 void RenderViewHostImpl::OnDidChangeScrollbarsForMainFrame(
1381 bool has_horizontal_scrollbar, bool has_vertical_scrollbar) {
1382 if (view_)
1383 view_->SetHasHorizontalScrollbar(has_horizontal_scrollbar);
1386 void RenderViewHostImpl::OnDidChangeScrollOffsetPinningForMainFrame(
1387 bool is_pinned_to_left, bool is_pinned_to_right) {
1388 if (view_)
1389 view_->SetScrollOffsetPinning(is_pinned_to_left, is_pinned_to_right);
1392 void RenderViewHostImpl::OnDidChangeNumWheelEvents(int count) {
1395 void RenderViewHostImpl::OnSelectionChanged(const string16& text,
1396 size_t offset,
1397 const ui::Range& range) {
1398 if (view_)
1399 view_->SelectionChanged(text, offset, range);
1402 void RenderViewHostImpl::OnSelectionBoundsChanged(
1403 const ViewHostMsg_SelectionBounds_Params& params) {
1404 if (view_) {
1405 view_->SelectionBoundsChanged(params);
1409 void RenderViewHostImpl::OnRouteCloseEvent() {
1410 // Have the delegate route this to the active RenderViewHost.
1411 delegate_->RouteCloseEvent(this);
1414 void RenderViewHostImpl::OnRouteMessageEvent(
1415 const ViewMsg_PostMessage_Params& params) {
1416 // Give to the delegate to route to the active RenderViewHost.
1417 delegate_->RouteMessageEvent(this, params);
1420 void RenderViewHostImpl::OnRunJavaScriptMessage(
1421 const string16& message,
1422 const string16& default_prompt,
1423 const GURL& frame_url,
1424 JavaScriptMessageType type,
1425 IPC::Message* reply_msg) {
1426 // While a JS message dialog is showing, tabs in the same process shouldn't
1427 // process input events.
1428 GetProcess()->SetIgnoreInputEvents(true);
1429 StopHangMonitorTimeout();
1430 delegate_->RunJavaScriptMessage(this, message, default_prompt, frame_url,
1431 type, reply_msg,
1432 &are_javascript_messages_suppressed_);
1435 void RenderViewHostImpl::OnRunBeforeUnloadConfirm(const GURL& frame_url,
1436 const string16& message,
1437 bool is_reload,
1438 IPC::Message* reply_msg) {
1439 // While a JS before unload dialog is showing, tabs in the same process
1440 // shouldn't process input events.
1441 GetProcess()->SetIgnoreInputEvents(true);
1442 StopHangMonitorTimeout();
1443 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1446 void RenderViewHostImpl::OnStartDragging(
1447 const WebDropData& drop_data,
1448 WebDragOperationsMask drag_operations_mask,
1449 const SkBitmap& bitmap,
1450 const gfx::Vector2d& bitmap_offset_in_dip,
1451 const DragEventSourceInfo& event_info) {
1452 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1453 if (!view)
1454 return;
1456 WebDropData filtered_data(drop_data);
1457 RenderProcessHost* process = GetProcess();
1458 ChildProcessSecurityPolicyImpl* policy =
1459 ChildProcessSecurityPolicyImpl::GetInstance();
1461 // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1462 if (!filtered_data.url.SchemeIs(chrome::kJavaScriptScheme))
1463 FilterURL(policy, process, true, &filtered_data.url);
1464 FilterURL(policy, process, false, &filtered_data.html_base_url);
1465 // Filter out any paths that the renderer didn't have access to. This prevents
1466 // the following attack on a malicious renderer:
1467 // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1468 // doesn't have read permissions for.
1469 // 2. We initiate a native DnD operation.
1470 // 3. DnD operation immediately ends since mouse is not held down. DnD events
1471 // still fire though, which causes read permissions to be granted to the
1472 // renderer for any file paths in the drop.
1473 filtered_data.filenames.clear();
1474 for (std::vector<WebDropData::FileInfo>::const_iterator it =
1475 drop_data.filenames.begin();
1476 it != drop_data.filenames.end(); ++it) {
1477 base::FilePath path(base::FilePath::FromUTF8Unsafe(UTF16ToUTF8(it->path)));
1478 if (policy->CanReadFile(GetProcess()->GetID(), path))
1479 filtered_data.filenames.push_back(*it);
1481 ui::ScaleFactor scale_factor = GetScaleFactorForView(GetView());
1482 gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale_factor));
1483 view->StartDragging(filtered_data, drag_operations_mask, image,
1484 bitmap_offset_in_dip, event_info);
1487 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1488 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1489 if (view)
1490 view->UpdateDragCursor(current_op);
1493 void RenderViewHostImpl::OnTargetDropACK() {
1494 NotificationService::current()->Notify(
1495 NOTIFICATION_RENDER_VIEW_HOST_DID_RECEIVE_DRAG_TARGET_DROP_ACK,
1496 Source<RenderViewHost>(this),
1497 NotificationService::NoDetails());
1500 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1501 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1502 if (view)
1503 view->TakeFocus(reverse);
1506 void RenderViewHostImpl::OnFocusedNodeChanged(bool is_editable_node) {
1507 NotificationService::current()->Notify(
1508 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1509 Source<RenderViewHost>(this),
1510 Details<const bool>(&is_editable_node));
1513 void RenderViewHostImpl::OnAddMessageToConsole(
1514 int32 level,
1515 const string16& message,
1516 int32 line_no,
1517 const string16& source_id) {
1518 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
1519 return;
1520 // Pass through log level only on WebUI pages to limit console spew.
1521 int32 resolved_level = HasWebUIScheme(delegate_->GetURL()) ? level : 0;
1523 if (resolved_level >= ::logging::GetMinLogLevel()) {
1524 logging::LogMessage("CONSOLE", line_no, resolved_level).stream() << "\"" <<
1525 message << "\", source: " << source_id << " (" << line_no << ")";
1529 void RenderViewHostImpl::AddObserver(RenderViewHostObserver* observer) {
1530 observers_.AddObserver(observer);
1533 void RenderViewHostImpl::RemoveObserver(RenderViewHostObserver* observer) {
1534 observers_.RemoveObserver(observer);
1537 void RenderViewHostImpl::OnUserGesture() {
1538 delegate_->OnUserGesture();
1541 void RenderViewHostImpl::OnShouldCloseACK(
1542 bool proceed,
1543 const base::TimeTicks& renderer_before_unload_start_time,
1544 const base::TimeTicks& renderer_before_unload_end_time) {
1545 decrement_in_flight_event_count();
1546 StopHangMonitorTimeout();
1547 // If this renderer navigated while the beforeunload request was in flight, we
1548 // may have cleared this state in OnNavigate, in which case we can ignore
1549 // this message.
1550 if (!is_waiting_for_beforeunload_ack_ || is_swapped_out_)
1551 return;
1553 is_waiting_for_beforeunload_ack_ = false;
1555 RenderViewHostDelegate::RendererManagement* management_delegate =
1556 delegate_->GetRendererManagementDelegate();
1557 if (management_delegate) {
1558 base::TimeTicks before_unload_end_time;
1559 if (!send_should_close_start_time_.is_null() &&
1560 !renderer_before_unload_start_time.is_null() &&
1561 !renderer_before_unload_end_time.is_null()) {
1562 // When passing TimeTicks across process boundaries, we need to compensate
1563 // for any skew between the processes. Here we are converting the
1564 // renderer's notion of before_unload_end_time to TimeTicks in the browser
1565 // process. See comments in inter_process_time_ticks_converter.h for more.
1566 InterProcessTimeTicksConverter converter(
1567 LocalTimeTicks::FromTimeTicks(send_should_close_start_time_),
1568 LocalTimeTicks::FromTimeTicks(base::TimeTicks::Now()),
1569 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
1570 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1571 LocalTimeTicks browser_before_unload_end_time =
1572 converter.ToLocalTimeTicks(
1573 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1574 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
1576 management_delegate->ShouldClosePage(
1577 unload_ack_is_for_cross_site_transition_, proceed,
1578 before_unload_end_time);
1581 // If canceled, notify the delegate to cancel its pending navigation entry.
1582 if (!proceed)
1583 delegate_->DidCancelLoading();
1586 void RenderViewHostImpl::OnClosePageACK() {
1587 decrement_in_flight_event_count();
1588 ClosePageIgnoringUnloadEvents();
1591 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1592 delegate_->RendererUnresponsive(
1593 this, is_waiting_for_beforeunload_ack_ || is_waiting_for_unload_ack_);
1596 void RenderViewHostImpl::NotifyRendererResponsive() {
1597 delegate_->RendererResponsive(this);
1600 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1601 bool last_unlocked_by_target) {
1602 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1605 bool RenderViewHostImpl::IsFullscreen() const {
1606 return delegate_->IsFullscreenForCurrentTab();
1609 void RenderViewHostImpl::OnFocus() {
1610 // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1611 // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1612 delegate_->Activate();
1615 void RenderViewHostImpl::OnBlur() {
1616 delegate_->Deactivate();
1619 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1620 return delegate_->GetRootWindowResizerRect();
1623 void RenderViewHostImpl::ForwardMouseEvent(
1624 const WebKit::WebMouseEvent& mouse_event) {
1626 // We make a copy of the mouse event because
1627 // RenderWidgetHost::ForwardMouseEvent will delete |mouse_event|.
1628 WebKit::WebMouseEvent event_copy(mouse_event);
1629 RenderWidgetHostImpl::ForwardMouseEvent(event_copy);
1631 switch (event_copy.type) {
1632 case WebInputEvent::MouseMove:
1633 delegate_->HandleMouseMove();
1634 break;
1635 case WebInputEvent::MouseLeave:
1636 delegate_->HandleMouseLeave();
1637 break;
1638 case WebInputEvent::MouseDown:
1639 delegate_->HandleMouseDown();
1640 break;
1641 case WebInputEvent::MouseWheel:
1642 if (ignore_input_events())
1643 delegate_->OnIgnoredUIEvent();
1644 break;
1645 case WebInputEvent::MouseUp:
1646 delegate_->HandleMouseUp();
1647 default:
1648 // For now, we don't care about the rest.
1649 break;
1653 void RenderViewHostImpl::OnPointerEventActivate() {
1654 delegate_->HandlePointerActivate();
1657 void RenderViewHostImpl::ForwardKeyboardEvent(
1658 const NativeWebKeyboardEvent& key_event) {
1659 if (ignore_input_events()) {
1660 if (key_event.type == WebInputEvent::RawKeyDown)
1661 delegate_->OnIgnoredUIEvent();
1662 return;
1664 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1667 #if defined(OS_ANDROID)
1668 void RenderViewHostImpl::DidSelectPopupMenuItems(
1669 const std::vector<int>& selected_indices) {
1670 Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), false,
1671 selected_indices));
1674 void RenderViewHostImpl::DidCancelPopupMenu() {
1675 Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), true,
1676 std::vector<int>()));
1678 #endif
1680 #if defined(OS_MACOSX)
1681 void RenderViewHostImpl::DidSelectPopupMenuItem(int selected_index) {
1682 Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), selected_index));
1685 void RenderViewHostImpl::DidCancelPopupMenu() {
1686 Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), -1));
1688 #endif
1690 void RenderViewHostImpl::SendOrientationChangeEvent(int orientation) {
1691 Send(new ViewMsg_OrientationChangeEvent(GetRoutingID(), orientation));
1694 void RenderViewHostImpl::ToggleSpeechInput() {
1695 Send(new InputTagSpeechMsg_ToggleSpeechInput(GetRoutingID()));
1698 bool RenderViewHostImpl::CanCommitURL(const GURL& url) {
1699 // TODO(creis): We should also check for WebUI pages here. Also, when the
1700 // out-of-process iframes implementation is ready, we should check for
1701 // cross-site URLs that are not allowed to commit in this process.
1703 // Give the client a chance to disallow URLs from committing.
1704 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1707 void RenderViewHostImpl::FilterURL(ChildProcessSecurityPolicyImpl* policy,
1708 const RenderProcessHost* process,
1709 bool empty_allowed,
1710 GURL* url) {
1711 if (empty_allowed && url->is_empty())
1712 return;
1714 // The browser process should never hear the swappedout:// URL from any
1715 // of the renderer's messages. Check for this in debug builds, but don't
1716 // let it crash a release browser.
1717 DCHECK(GURL(kSwappedOutURL) != *url);
1719 if (!url->is_valid()) {
1720 // Have to use about:blank for the denied case, instead of an empty GURL.
1721 // This is because the browser treats navigation to an empty GURL as a
1722 // navigation to the home page. This is often a privileged page
1723 // (chrome://newtab/) which is exactly what we don't want.
1724 *url = GURL(kAboutBlankURL);
1725 RecordAction(UserMetricsAction("FilterURLTermiate_Invalid"));
1726 return;
1729 if (url->SchemeIs(chrome::kAboutScheme)) {
1730 // The renderer treats all URLs in the about: scheme as being about:blank.
1731 // Canonicalize about: URLs to about:blank.
1732 *url = GURL(kAboutBlankURL);
1733 RecordAction(UserMetricsAction("FilterURLTermiate_About"));
1736 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1737 // cannot swap processes or grant bindings.
1738 bool non_web_url_in_guest = process->IsGuest() &&
1739 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1741 if (non_web_url_in_guest || !policy->CanRequestURL(process->GetID(), *url)) {
1742 // If this renderer is not permitted to request this URL, we invalidate the
1743 // URL. This prevents us from storing the blocked URL and becoming confused
1744 // later.
1745 VLOG(1) << "Blocked URL " << url->spec();
1746 *url = GURL(kAboutBlankURL);
1747 RecordAction(UserMetricsAction("FilterURLTermiate_Blocked"));
1751 void RenderViewHost::AddCreatedCallback(const CreatedCallback& callback) {
1752 g_created_callbacks.Get().push_back(callback);
1755 void RenderViewHost::RemoveCreatedCallback(const CreatedCallback& callback) {
1756 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
1757 if (g_created_callbacks.Get().at(i).Equals(callback)) {
1758 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
1759 return;
1764 void RenderViewHostImpl::SetAltErrorPageURL(const GURL& url) {
1765 Send(new ViewMsg_SetAltErrorPageURL(GetRoutingID(), url));
1768 void RenderViewHostImpl::ExitFullscreen() {
1769 RejectMouseLockOrUnlockIfNecessary();
1770 // We need to notify the contents that its fullscreen state has changed. This
1771 // is done as part of the resize message.
1772 WasResized();
1775 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1776 return delegate_->GetWebkitPrefs();
1779 void RenderViewHostImpl::DisownOpener() {
1780 // This should only be called when swapped out.
1781 DCHECK(is_swapped_out_);
1783 Send(new ViewMsg_DisownOpener(GetRoutingID()));
1786 void RenderViewHostImpl::SetAccessibilityCallbackForTesting(
1787 const base::Callback<void(AccessibilityNotification)>& callback) {
1788 accessibility_testing_callback_ = callback;
1791 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1792 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1795 void RenderViewHostImpl::NotifyTimezoneChange() {
1796 Send(new ViewMsg_TimezoneChange(GetRoutingID()));
1799 void RenderViewHostImpl::ClearFocusedNode() {
1800 Send(new ViewMsg_ClearFocusedNode(GetRoutingID()));
1803 void RenderViewHostImpl::SetZoomLevel(double level) {
1804 Send(new ViewMsg_SetZoomLevel(GetRoutingID(), level));
1807 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1808 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1811 void RenderViewHostImpl::ReloadFrame() {
1812 Send(new ViewMsg_ReloadFrame(GetRoutingID()));
1815 void RenderViewHostImpl::Find(int request_id,
1816 const string16& search_text,
1817 const WebKit::WebFindOptions& options) {
1818 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
1821 void RenderViewHostImpl::InsertCSS(const string16& frame_xpath,
1822 const std::string& css) {
1823 Send(new ViewMsg_CSSInsertRequest(GetRoutingID(), frame_xpath, css));
1826 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1827 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1830 void RenderViewHostImpl::EnablePreferredSizeMode() {
1831 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1834 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1835 const gfx::Size& max_size) {
1836 SetShouldAutoResize(true);
1837 Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1840 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1841 SetShouldAutoResize(false);
1842 Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1845 void RenderViewHostImpl::ExecuteCustomContextMenuCommand(
1846 int action, const CustomContextMenuContext& context) {
1847 Send(new ViewMsg_CustomContextMenuAction(GetRoutingID(), context, action));
1850 void RenderViewHostImpl::NotifyContextMenuClosed(
1851 const CustomContextMenuContext& context) {
1852 Send(new ViewMsg_ContextMenuClosed(GetRoutingID(), context));
1855 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1856 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1859 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1860 const gfx::Point& location, const WebKit::WebMediaPlayerAction& action) {
1861 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1864 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1865 const gfx::Point& location, const WebKit::WebPluginAction& action) {
1866 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1869 void RenderViewHostImpl::DisassociateFromPopupCount() {
1870 Send(new ViewMsg_DisassociateFromPopupCount(GetRoutingID()));
1873 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1874 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1877 void RenderViewHostImpl::StopFinding(StopFindAction action) {
1878 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
1881 void RenderViewHostImpl::OnAccessibilityNotifications(
1882 const std::vector<AccessibilityHostMsg_NotificationParams>& params) {
1883 if (view_ && !is_swapped_out_)
1884 view_->OnAccessibilityNotifications(params);
1886 // Always send an ACK or the renderer can be in a bad state.
1887 Send(new AccessibilityMsg_Notifications_ACK(GetRoutingID()));
1889 // The rest of this code is just for testing; bail out if we're not
1890 // in that mode.
1891 if (accessibility_testing_callback_.is_null())
1892 return;
1894 for (unsigned i = 0; i < params.size(); i++) {
1895 const AccessibilityHostMsg_NotificationParams& param = params[i];
1896 AccessibilityNotification src_type = param.notification_type;
1897 if (src_type == AccessibilityNotificationLayoutComplete ||
1898 src_type == AccessibilityNotificationLoadComplete) {
1899 MakeAccessibilityNodeDataTree(param.nodes, &accessibility_tree_);
1901 accessibility_testing_callback_.Run(src_type);
1905 void RenderViewHostImpl::OnScriptEvalResponse(int id,
1906 const base::ListValue& result) {
1907 const base::Value* result_value;
1908 if (!result.Get(0, &result_value)) {
1909 // Programming error or rogue renderer.
1910 NOTREACHED() << "Got bad arguments for OnScriptEvalResponse";
1911 return;
1914 std::map<int, JavascriptResultCallback>::iterator it =
1915 javascript_callbacks_.find(id);
1916 if (it != javascript_callbacks_.end()) {
1917 // ExecuteJavascriptInWebFrameCallbackResult was used; do callback.
1918 it->second.Run(result_value);
1919 javascript_callbacks_.erase(it);
1920 } else {
1921 NOTREACHED() << "Received script response for unknown request";
1925 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1926 bool remember,
1927 const GURL& url) {
1928 HostZoomMapImpl* host_zoom_map = static_cast<HostZoomMapImpl*>(
1929 HostZoomMap::GetForBrowserContext(GetProcess()->GetBrowserContext()));
1930 if (remember) {
1931 host_zoom_map->
1932 SetZoomLevelForHost(net::GetHostOrSpecFromURL(url), zoom_level);
1933 } else {
1934 host_zoom_map->SetTemporaryZoomLevel(
1935 GetProcess()->GetID(), GetRoutingID(), zoom_level);
1939 void RenderViewHostImpl::OnMediaNotification(int64 player_cookie,
1940 bool has_video,
1941 bool has_audio,
1942 bool is_playing) {
1943 // Chrome OS does its own detection of audio and video.
1944 #if !defined(OS_CHROMEOS)
1945 if (is_playing) {
1946 scoped_ptr<PowerSaveBlocker> blocker;
1947 if (has_video) {
1948 blocker = PowerSaveBlocker::Create(
1949 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
1950 "Playing video");
1951 } else if (has_audio) {
1952 blocker = PowerSaveBlocker::Create(
1953 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
1954 "Playing audio");
1957 if (blocker)
1958 power_save_blockers_[player_cookie] = blocker.release();
1959 } else {
1960 delete power_save_blockers_[player_cookie];
1961 power_save_blockers_.erase(player_cookie);
1963 #endif
1966 void RenderViewHostImpl::OnRequestDesktopNotificationPermission(
1967 const GURL& source_origin, int callback_context) {
1968 GetContentClient()->browser()->RequestDesktopNotificationPermission(
1969 source_origin, callback_context, GetProcess()->GetID(), GetRoutingID());
1972 void RenderViewHostImpl::OnShowDesktopNotification(
1973 const ShowDesktopNotificationHostMsgParams& params) {
1974 // Disallow HTML notifications from javascript: and file: schemes as this
1975 // allows unwanted cross-domain access.
1976 GURL url = params.contents_url;
1977 if (params.is_html &&
1978 (url.SchemeIs(chrome::kJavaScriptScheme) ||
1979 url.SchemeIs(chrome::kFileScheme))) {
1980 return;
1983 GetContentClient()->browser()->ShowDesktopNotification(
1984 params, GetProcess()->GetID(), GetRoutingID(), false);
1987 void RenderViewHostImpl::OnCancelDesktopNotification(int notification_id) {
1988 GetContentClient()->browser()->CancelDesktopNotification(
1989 GetProcess()->GetID(), GetRoutingID(), notification_id);
1992 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1993 delegate_->RunFileChooser(this, params);
1996 void RenderViewHostImpl::OnDidAccessInitialDocument() {
1997 has_accessed_initial_document_ = true;
1998 delegate_->DidAccessInitialDocument();
2001 void RenderViewHostImpl::OnDomOperationResponse(
2002 const std::string& json_string, int automation_id) {
2003 DomOperationNotificationDetails details(json_string, automation_id);
2004 NotificationService::current()->Notify(
2005 NOTIFICATION_DOM_OPERATION_RESPONSE,
2006 Source<RenderViewHost>(this),
2007 Details<DomOperationNotificationDetails>(&details));
2010 void RenderViewHostImpl::OnGetWindowSnapshot(const int snapshot_id) {
2011 std::vector<unsigned char> png;
2013 // This feature is behind the kEnableGpuBenchmarking command line switch
2014 // because it poses security concerns and should only be used for testing.
2015 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
2016 if (command_line.HasSwitch(switches::kEnableGpuBenchmarking)) {
2017 gfx::Rect view_bounds = GetView()->GetViewBounds();
2018 gfx::Rect snapshot_bounds(view_bounds.size());
2019 gfx::Size snapshot_size = snapshot_bounds.size();
2021 if (ui::GrabViewSnapshot(GetView()->GetNativeView(),
2022 &png, snapshot_bounds)) {
2023 Send(new ViewMsg_WindowSnapshotCompleted(
2024 GetRoutingID(), snapshot_id, snapshot_size, png));
2025 return;
2029 Send(new ViewMsg_WindowSnapshotCompleted(
2030 GetRoutingID(), snapshot_id, gfx::Size(), png));
2033 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2034 void RenderViewHostImpl::OnShowPopup(
2035 const ViewHostMsg_ShowPopup_Params& params) {
2036 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
2037 if (view) {
2038 view->ShowPopupMenu(params.bounds,
2039 params.item_height,
2040 params.item_font_size,
2041 params.selected_item,
2042 params.popup_items,
2043 params.right_aligned,
2044 params.allow_multiple_selection);
2047 #endif
2049 void RenderViewHostImpl::SetSwappedOut(bool is_swapped_out) {
2050 is_swapped_out_ = is_swapped_out;
2052 // Whenever we change swap out state, we should not be waiting for
2053 // beforeunload or unload acks. We clear them here to be safe, since they
2054 // can cause navigations to be ignored in OnNavigate.
2055 is_waiting_for_beforeunload_ack_ = false;
2056 is_waiting_for_unload_ack_ = false;
2057 has_timed_out_on_unload_ = false;
2060 void RenderViewHostImpl::ClearPowerSaveBlockers() {
2061 STLDeleteValues(&power_save_blockers_);
2064 bool RenderViewHostImpl::CanAccessFilesOfPageState(
2065 const PageState& state) const {
2066 ChildProcessSecurityPolicyImpl* policy =
2067 ChildProcessSecurityPolicyImpl::GetInstance();
2069 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
2070 for (std::vector<base::FilePath>::const_iterator file = file_paths.begin();
2071 file != file_paths.end(); ++file) {
2072 if (!policy->CanReadFile(GetProcess()->GetID(), *file))
2073 return false;
2075 return true;
2078 } // namespace content