1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/guest_view/web_view/web_view_guest.h"
6
7 #include "base/message_loop/message_loop.h"
8 #include "base/strings/stringprintf.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "chrome/browser/chrome_notification_types.h"
11 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
12 #include "chrome/browser/extensions/api/web_request/web_request_api.h"
13 #include "chrome/browser/extensions/api/webview/webview_api.h"
14 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
15 #include "chrome/browser/extensions/extension_renderer_state.h"
16 #include "chrome/browser/extensions/menu_manager.h"
17 #include "chrome/browser/extensions/script_executor.h"
18 #include "chrome/browser/favicon/favicon_tab_helper.h"
19 #include "chrome/browser/geolocation/geolocation_permission_context.h"
20 #include "chrome/browser/geolocation/geolocation_permission_context_factory.h"
21 #include "chrome/browser/guest_view/guest_view_constants.h"
22 #include "chrome/browser/guest_view/guest_view_manager.h"
23 #include "chrome/browser/guest_view/web_view/web_view_constants.h"
24 #include "chrome/browser/guest_view/web_view/web_view_permission_types.h"
25 #include "chrome/browser/renderer_context_menu/context_menu_delegate.h"
26 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
27 #include "chrome/browser/ui/pdf/pdf_tab_helper.h"
28 #include "chrome/common/chrome_version_info.h"
29 #include "chrome/common/render_messages.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "content/public/browser/child_process_security_policy.h"
32 #include "content/public/browser/host_zoom_map.h"
33 #include "content/public/browser/native_web_keyboard_event.h"
34 #include "content/public/browser/navigation_entry.h"
35 #include "content/public/browser/notification_details.h"
36 #include "content/public/browser/notification_service.h"
37 #include "content/public/browser/notification_source.h"
38 #include "content/public/browser/notification_types.h"
39 #include "content/public/browser/render_process_host.h"
40 #include "content/public/browser/render_view_host.h"
41 #include "content/public/browser/resource_request_details.h"
42 #include "content/public/browser/site_instance.h"
43 #include "content/public/browser/storage_partition.h"
44 #include "content/public/browser/user_metrics.h"
45 #include "content/public/browser/web_contents.h"
46 #include "content/public/browser/web_contents_delegate.h"
47 #include "content/public/common/media_stream_request.h"
48 #include "content/public/common/page_zoom.h"
49 #include "content/public/common/result_codes.h"
50 #include "content/public/common/stop_find_action.h"
51 #include "content/public/common/url_constants.h"
52 #include "extensions/common/constants.h"
53 #include "ipc/ipc_message_macros.h"
54 #include "net/base/escape.h"
55 #include "net/base/net_errors.h"
56 #include "third_party/WebKit/public/web/WebFindOptions.h"
57 #include "ui/base/models/simple_menu_model.h"
58
59 #if defined(ENABLE_PRINTING)
60 #if defined(ENABLE_FULL_PRINTING)
61 #include "chrome/browser/printing/print_preview_message_handler.h"
62 #include "chrome/browser/printing/print_view_manager.h"
63 #else
64 #include "chrome/browser/printing/print_view_manager_basic.h"
65 #endif // defined(ENABLE_FULL_PRINTING)
66 #endif // defined(ENABLE_PRINTING)
67
68 #if defined(ENABLE_PLUGINS)
69 #include "chrome/browser/guest_view/web_view/plugin_permission_helper.h"
70 #endif
71
72 #if defined(OS_CHROMEOS)
73 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
74 #endif
75
76 using base::UserMetricsAction;
77 using content::RenderFrameHost;
78 using content::WebContents;
79
80 namespace {
81
WindowOpenDispositionToString(WindowOpenDisposition window_open_disposition)82 std::string WindowOpenDispositionToString(
83 WindowOpenDisposition window_open_disposition) {
84 switch (window_open_disposition) {
85 case IGNORE_ACTION:
86 return "ignore";
87 case SAVE_TO_DISK:
88 return "save_to_disk";
89 case CURRENT_TAB:
90 return "current_tab";
91 case NEW_BACKGROUND_TAB:
92 return "new_background_tab";
93 case NEW_FOREGROUND_TAB:
94 return "new_foreground_tab";
95 case NEW_WINDOW:
96 return "new_window";
97 case NEW_POPUP:
98 return "new_popup";
99 default:
100 NOTREACHED() << "Unknown Window Open Disposition";
101 return "ignore";
102 }
103 }
104
TerminationStatusToString(base::TerminationStatus status)105 static std::string TerminationStatusToString(base::TerminationStatus status) {
106 switch (status) {
107 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
108 return "normal";
109 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
110 case base::TERMINATION_STATUS_STILL_RUNNING:
111 return "abnormal";
112 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
113 return "killed";
114 case base::TERMINATION_STATUS_PROCESS_CRASHED:
115 #if defined(OS_ANDROID)
116 case base::TERMINATION_STATUS_OOM_PROTECTED:
117 #endif
118 return "crashed";
119 case base::TERMINATION_STATUS_MAX_ENUM:
120 break;
121 }
122 NOTREACHED() << "Unknown Termination Status.";
123 return "unknown";
124 }
125
PermissionTypeToString(WebViewPermissionType type)126 static std::string PermissionTypeToString(WebViewPermissionType type) {
127 switch (type) {
128 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
129 return webview::kPermissionTypeDownload;
130 case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
131 return webview::kPermissionTypeFileSystem;
132 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
133 return webview::kPermissionTypeGeolocation;
134 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
135 return webview::kPermissionTypeDialog;
136 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
137 return webview::kPermissionTypeLoadPlugin;
138 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
139 return webview::kPermissionTypeMedia;
140 case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
141 return webview::kPermissionTypeNewWindow;
142 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
143 return webview::kPermissionTypePointerLock;
144 default:
145 NOTREACHED();
146 return std::string();
147 }
148 }
149
GetStoragePartitionIdFromSiteURL(const GURL & site_url)150 std::string GetStoragePartitionIdFromSiteURL(const GURL& site_url) {
151 const std::string& partition_id = site_url.query();
152 bool persist_storage = site_url.path().find("persist") != std::string::npos;
153 return (persist_storage ? webview::kPersistPrefix : "") + partition_id;
154 }
155
RemoveWebViewEventListenersOnIOThread(void * profile,const std::string & extension_id,int embedder_process_id,int view_instance_id)156 void RemoveWebViewEventListenersOnIOThread(
157 void* profile,
158 const std::string& extension_id,
159 int embedder_process_id,
160 int view_instance_id) {
161 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
162 ExtensionWebRequestEventRouter::GetInstance()->RemoveWebViewEventListeners(
163 profile,
164 extension_id,
165 embedder_process_id,
166 view_instance_id);
167 }
168
AttachWebViewHelpers(WebContents * contents)169 void AttachWebViewHelpers(WebContents* contents) {
170 FaviconTabHelper::CreateForWebContents(contents);
171 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
172 contents);
173 #if defined(ENABLE_PLUGINS)
174 PluginPermissionHelper::CreateForWebContents(contents);
175 #endif
176 #if defined(ENABLE_PRINTING)
177 #if defined(ENABLE_FULL_PRINTING)
178 printing::PrintViewManager::CreateForWebContents(contents);
179 printing::PrintPreviewMessageHandler::CreateForWebContents(contents);
180 #else
181 printing::PrintViewManagerBasic::CreateForWebContents(contents);
182 #endif // defined(ENABLE_FULL_PRINTING)
183 #endif // defined(ENABLE_PRINTING)
184 PDFTabHelper::CreateForWebContents(contents);
185 }
186
187 } // namespace
188
WebViewGuest(int guest_instance_id,WebContents * guest_web_contents,const std::string & embedder_extension_id)189 WebViewGuest::WebViewGuest(int guest_instance_id,
190 WebContents* guest_web_contents,
191 const std::string& embedder_extension_id)
192 : GuestView<WebViewGuest>(guest_instance_id),
193 script_executor_(new extensions::ScriptExecutor(guest_web_contents,
194 &script_observers_)),
195 pending_context_menu_request_id_(0),
196 next_permission_request_id_(0),
197 is_overriding_user_agent_(false),
198 main_frame_id_(0),
199 chromevox_injected_(false),
200 find_helper_(this),
201 javascript_dialog_helper_(this) {
202 Init(guest_web_contents, embedder_extension_id);
203 notification_registrar_.Add(
204 this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
205 content::Source<WebContents>(guest_web_contents));
206
207 notification_registrar_.Add(
208 this, content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT,
209 content::Source<WebContents>(guest_web_contents));
210
211 #if defined(OS_CHROMEOS)
212 chromeos::AccessibilityManager* accessibility_manager =
213 chromeos::AccessibilityManager::Get();
214 CHECK(accessibility_manager);
215 accessibility_subscription_ = accessibility_manager->RegisterCallback(
216 base::Bind(&WebViewGuest::OnAccessibilityStatusChanged,
217 base::Unretained(this)));
218 #endif
219
220 AttachWebViewHelpers(guest_web_contents);
221 }
222
223 // static
GetGuestPartitionConfigForSite(const GURL & site,std::string * partition_domain,std::string * partition_name,bool * in_memory)224 bool WebViewGuest::GetGuestPartitionConfigForSite(
225 const GURL& site,
226 std::string* partition_domain,
227 std::string* partition_name,
228 bool* in_memory) {
229 if (!site.SchemeIs(content::kGuestScheme))
230 return false;
231
232 // Since guest URLs are only used for packaged apps, there must be an app
233 // id in the URL.
234 CHECK(site.has_host());
235 *partition_domain = site.host();
236 // Since persistence is optional, the path must either be empty or the
237 // literal string.
238 *in_memory = (site.path() != "/persist");
239 // The partition name is user supplied value, which we have encoded when the
240 // URL was created, so it needs to be decoded.
241 *partition_name =
242 net::UnescapeURLComponent(site.query(), net::UnescapeRule::NORMAL);
243 return true;
244 }
245
246 // static
247 const char WebViewGuest::Type[] = "webview";
248
249 // static
GetViewInstanceId(WebContents * contents)250 int WebViewGuest::GetViewInstanceId(WebContents* contents) {
251 WebViewGuest* guest = FromWebContents(contents);
252 if (!guest)
253 return guestview::kInstanceIDNone;
254
255 return guest->view_instance_id();
256 }
257
258 // static
ParsePartitionParam(const base::DictionaryValue * extra_params,std::string * storage_partition_id,bool * persist_storage)259 void WebViewGuest::ParsePartitionParam(
260 const base::DictionaryValue* extra_params,
261 std::string* storage_partition_id,
262 bool* persist_storage) {
263 std::string partition_str;
264 if (!extra_params->GetString(webview::kStoragePartitionId, &partition_str)) {
265 return;
266 }
267
268 // Since the "persist:" prefix is in ASCII, StartsWith will work fine on
269 // UTF-8 encoded |partition_id|. If the prefix is a match, we can safely
270 // remove the prefix without splicing in the middle of a multi-byte codepoint.
271 // We can use the rest of the string as UTF-8 encoded one.
272 if (StartsWithASCII(partition_str, "persist:", true)) {
273 size_t index = partition_str.find(":");
274 CHECK(index != std::string::npos);
275 // It is safe to do index + 1, since we tested for the full prefix above.
276 *storage_partition_id = partition_str.substr(index + 1);
277
278 if (storage_partition_id->empty()) {
279 // TODO(lazyboy): Better way to deal with this error.
280 return;
281 }
282 *persist_storage = true;
283 } else {
284 *storage_partition_id = partition_str;
285 *persist_storage = false;
286 }
287 }
288
289 // static
RecordUserInitiatedUMA(const PermissionResponseInfo & info,bool allow)290 void WebViewGuest::RecordUserInitiatedUMA(const PermissionResponseInfo& info,
291 bool allow) {
292 if (allow) {
293 // Note that |allow| == true means the embedder explicitly allowed the
294 // request. For some requests they might still fail. An example of such
295 // scenario would be: an embedder allows geolocation request but doesn't
296 // have geolocation access on its own.
297 switch (info.permission_type) {
298 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
299 content::RecordAction(
300 UserMetricsAction("WebView.PermissionAllow.Download"));
301 break;
302 case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
303 content::RecordAction(
304 UserMetricsAction("WebView.PermissionAllow.FileSystem"));
305 break;
306 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
307 content::RecordAction(
308 UserMetricsAction("WebView.PermissionAllow.Geolocation"));
309 break;
310 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
311 content::RecordAction(
312 UserMetricsAction("WebView.PermissionAllow.JSDialog"));
313 break;
314 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
315 content::RecordAction(
316 UserMetricsAction("WebView.Guest.PermissionAllow.PluginLoad"));
317 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
318 content::RecordAction(
319 UserMetricsAction("WebView.PermissionAllow.Media"));
320 break;
321 case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
322 content::RecordAction(
323 UserMetricsAction("BrowserPlugin.PermissionAllow.NewWindow"));
324 break;
325 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
326 content::RecordAction(
327 UserMetricsAction("WebView.PermissionAllow.PointerLock"));
328 break;
329 default:
330 break;
331 }
332 } else {
333 switch (info.permission_type) {
334 case WEB_VIEW_PERMISSION_TYPE_DOWNLOAD:
335 content::RecordAction(
336 UserMetricsAction("WebView.PermissionDeny.Download"));
337 break;
338 case WEB_VIEW_PERMISSION_TYPE_FILESYSTEM:
339 content::RecordAction(
340 UserMetricsAction("WebView.PermissionDeny.FileSystem"));
341 break;
342 case WEB_VIEW_PERMISSION_TYPE_GEOLOCATION:
343 content::RecordAction(
344 UserMetricsAction("WebView.PermissionDeny.Geolocation"));
345 break;
346 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG:
347 content::RecordAction(
348 UserMetricsAction("WebView.PermissionDeny.JSDialog"));
349 break;
350 case WEB_VIEW_PERMISSION_TYPE_LOAD_PLUGIN:
351 content::RecordAction(
352 UserMetricsAction("WebView.Guest.PermissionDeny.PluginLoad"));
353 break;
354 case WEB_VIEW_PERMISSION_TYPE_MEDIA:
355 content::RecordAction(
356 UserMetricsAction("WebView.PermissionDeny.Media"));
357 break;
358 case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW:
359 content::RecordAction(
360 UserMetricsAction("BrowserPlugin.PermissionDeny.NewWindow"));
361 break;
362 case WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK:
363 content::RecordAction(
364 UserMetricsAction("WebView.PermissionDeny.PointerLock"));
365 break;
366 default:
367 break;
368 }
369 }
370 }
371
372 // static
MenuModelToValue(const ui::SimpleMenuModel & menu_model)373 scoped_ptr<base::ListValue> WebViewGuest::MenuModelToValue(
374 const ui::SimpleMenuModel& menu_model) {
375 scoped_ptr<base::ListValue> items(new base::ListValue());
376 for (int i = 0; i < menu_model.GetItemCount(); ++i) {
377 base::DictionaryValue* item_value = new base::DictionaryValue();
378 // TODO(lazyboy): We need to expose some kind of enum equivalent of
379 // |command_id| instead of plain integers.
380 item_value->SetInteger(webview::kMenuItemCommandId,
381 menu_model.GetCommandIdAt(i));
382 item_value->SetString(webview::kMenuItemLabel, menu_model.GetLabelAt(i));
383 items->Append(item_value);
384 }
385 return items.Pass();
386 }
387
DidAttachToEmbedder()388 void WebViewGuest::DidAttachToEmbedder() {
389 std::string name;
390 if (extra_params()->GetString(webview::kName, &name)) {
391 // If the guest window's name is empty, then the WebView tag's name is
392 // assigned. Otherwise, the guest window's name takes precedence over the
393 // WebView tag's name.
394 if (name_.empty())
395 name_ = name;
396 }
397 ReportFrameNameChange(name_);
398
399 std::string user_agent_override;
400 if (extra_params()->GetString(webview::kParameterUserAgentOverride,
401 &user_agent_override)) {
402 SetUserAgentOverride(user_agent_override);
403 } else {
404 SetUserAgentOverride("");
405 }
406
407 std::string src;
408 if (extra_params()->GetString("src", &src) && !src.empty())
409 NavigateGuest(src);
410
411 if (GetOpener()) {
412 // We need to do a navigation here if the target URL has changed between
413 // the time the WebContents was created and the time it was attached.
414 // We also need to do an initial navigation if a RenderView was never
415 // created for the new window in cases where there is no referrer.
416 PendingWindowMap::iterator it =
417 GetOpener()->pending_new_windows_.find(this);
418 if (it != GetOpener()->pending_new_windows_.end()) {
419 const NewWindowInfo& new_window_info = it->second;
420 if (new_window_info.changed || !guest_web_contents()->HasOpener())
421 NavigateGuest(new_window_info.url.spec());
422 } else {
423 NOTREACHED();
424 }
425
426 // Once a new guest is attached to the DOM of the embedder page, then the
427 // lifetime of the new guest is no longer managed by the opener guest.
428 GetOpener()->pending_new_windows_.erase(this);
429 }
430 }
431
DidStopLoading()432 void WebViewGuest::DidStopLoading() {
433 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
434 DispatchEvent(new GuestViewBase::Event(webview::kEventLoadStop, args.Pass()));
435 }
436
EmbedderDestroyed()437 void WebViewGuest::EmbedderDestroyed() {
438 // TODO(fsamuel): WebRequest event listeners for <webview> should survive
439 // reparenting of a <webview> within a single embedder. Right now, we keep
440 // around the browser state for the listener for the lifetime of the embedder.
441 // Ideally, the lifetime of the listeners should match the lifetime of the
442 // <webview> DOM node. Once http://crbug.com/156219 is resolved we can move
443 // the call to RemoveWebViewEventListenersOnIOThread back to
444 // WebViewGuest::WebContentsDestroyed.
445 content::BrowserThread::PostTask(
446 content::BrowserThread::IO,
447 FROM_HERE,
448 base::Bind(
449 &RemoveWebViewEventListenersOnIOThread,
450 browser_context(), embedder_extension_id(),
451 embedder_render_process_id(),
452 view_instance_id()));
453 }
454
GuestDestroyed()455 void WebViewGuest::GuestDestroyed() {
456 // Clean up custom context menu items for this guest.
457 extensions::MenuManager* menu_manager = extensions::MenuManager::Get(
458 Profile::FromBrowserContext(browser_context()));
459 menu_manager->RemoveAllContextItems(extensions::MenuItem::ExtensionKey(
460 embedder_extension_id(), view_instance_id()));
461
462 RemoveWebViewFromExtensionRendererState(web_contents());
463 }
464
IsDragAndDropEnabled() const465 bool WebViewGuest::IsDragAndDropEnabled() const {
466 return true;
467 }
468
WillDestroy()469 void WebViewGuest::WillDestroy() {
470 if (!attached() && GetOpener())
471 GetOpener()->pending_new_windows_.erase(this);
472 DestroyUnattachedWindows();
473 }
474
AddMessageToConsole(WebContents * source,int32 level,const base::string16 & message,int32 line_no,const base::string16 & source_id)475 bool WebViewGuest::AddMessageToConsole(WebContents* source,
476 int32 level,
477 const base::string16& message,
478 int32 line_no,
479 const base::string16& source_id) {
480 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
481 // Log levels are from base/logging.h: LogSeverity.
482 args->SetInteger(webview::kLevel, level);
483 args->SetString(webview::kMessage, message);
484 args->SetInteger(webview::kLine, line_no);
485 args->SetString(webview::kSourceId, source_id);
486 DispatchEvent(
487 new GuestViewBase::Event(webview::kEventConsoleMessage, args.Pass()));
488 return true;
489 }
490
CloseContents(WebContents * source)491 void WebViewGuest::CloseContents(WebContents* source) {
492 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
493 DispatchEvent(new GuestViewBase::Event(webview::kEventClose, args.Pass()));
494 }
495
FindReply(WebContents * source,int request_id,int number_of_matches,const gfx::Rect & selection_rect,int active_match_ordinal,bool final_update)496 void WebViewGuest::FindReply(WebContents* source,
497 int request_id,
498 int number_of_matches,
499 const gfx::Rect& selection_rect,
500 int active_match_ordinal,
501 bool final_update) {
502 find_helper_.FindReply(request_id, number_of_matches, selection_rect,
503 active_match_ordinal, final_update);
504 }
505
HandleContextMenu(const content::ContextMenuParams & params)506 bool WebViewGuest::HandleContextMenu(
507 const content::ContextMenuParams& params) {
508 ContextMenuDelegate* menu_delegate =
509 ContextMenuDelegate::FromWebContents(guest_web_contents());
510 DCHECK(menu_delegate);
511
512 pending_menu_ = menu_delegate->BuildMenu(guest_web_contents(), params);
513
514 // Pass it to embedder.
515 int request_id = ++pending_context_menu_request_id_;
516 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
517 scoped_ptr<base::ListValue> items =
518 MenuModelToValue(pending_menu_->menu_model());
519 args->Set(webview::kContextMenuItems, items.release());
520 args->SetInteger(webview::kRequestId, request_id);
521 DispatchEvent(new GuestViewBase::Event(webview::kEventContextMenu,
522 args.Pass()));
523 return true;
524 }
525
HandleKeyboardEvent(WebContents * source,const content::NativeWebKeyboardEvent & event)526 void WebViewGuest::HandleKeyboardEvent(
527 WebContents* source,
528 const content::NativeWebKeyboardEvent& event) {
529 if (!attached())
530 return;
531
532 if (HandleKeyboardShortcuts(event))
533 return;
534
535 // Send the unhandled keyboard events back to the embedder to reprocess them.
536 // TODO(fsamuel): This introduces the possibility of out-of-order keyboard
537 // events because the guest may be arbitrarily delayed when responding to
538 // keyboard events. In that time, the embedder may have received and processed
539 // additional key events. This needs to be fixed as soon as possible.
540 // See http://crbug.com/229882.
541 embedder_web_contents()->GetDelegate()->HandleKeyboardEvent(
542 web_contents(), event);
543 }
544
LoadProgressChanged(content::WebContents * source,double progress)545 void WebViewGuest::LoadProgressChanged(content::WebContents* source,
546 double progress) {
547 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
548 args->SetString(guestview::kUrl, guest_web_contents()->GetURL().spec());
549 args->SetDouble(webview::kProgress, progress);
550 DispatchEvent(
551 new GuestViewBase::Event(webview::kEventLoadProgress, args.Pass()));
552 }
553
LoadAbort(bool is_top_level,const GURL & url,const std::string & error_type)554 void WebViewGuest::LoadAbort(bool is_top_level,
555 const GURL& url,
556 const std::string& error_type) {
557 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
558 args->SetBoolean(guestview::kIsTopLevel, is_top_level);
559 args->SetString(guestview::kUrl, url.possibly_invalid_spec());
560 args->SetString(guestview::kReason, error_type);
561 DispatchEvent(
562 new GuestViewBase::Event(webview::kEventLoadAbort, args.Pass()));
563 }
564
OnUpdateFrameName(bool is_top_level,const std::string & name)565 void WebViewGuest::OnUpdateFrameName(bool is_top_level,
566 const std::string& name) {
567 if (!is_top_level)
568 return;
569
570 if (name_ == name)
571 return;
572
573 ReportFrameNameChange(name);
574 }
575
CreateNewGuestWindow(const content::OpenURLParams & params)576 WebViewGuest* WebViewGuest::CreateNewGuestWindow(
577 const content::OpenURLParams& params) {
578 GuestViewManager* guest_manager =
579 GuestViewManager::FromBrowserContext(browser_context());
580 // Allocate a new instance ID for the new guest.
581 int instance_id = guest_manager->GetNextInstanceID();
582
583 // Set the attach params to use the same partition as the opener.
584 // We pull the partition information from the site's URL, which is of the
585 // form guest://site/{persist}?{partition_name}.
586 const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
587 scoped_ptr<base::DictionaryValue> create_params(extra_params()->DeepCopy());
588 const std::string storage_partition_id =
589 GetStoragePartitionIdFromSiteURL(site_url);
590 create_params->SetString(webview::kStoragePartitionId, storage_partition_id);
591
592 WebContents* new_guest_web_contents =
593 guest_manager->CreateGuest(guest_web_contents()->GetSiteInstance(),
594 instance_id,
595 create_params.Pass());
596 WebViewGuest* new_guest =
597 WebViewGuest::FromWebContents(new_guest_web_contents);
598 new_guest->SetOpener(this);
599
600 // Take ownership of |new_guest|.
601 pending_new_windows_.insert(
602 std::make_pair(new_guest, NewWindowInfo(params.url, std::string())));
603
604 // Request permission to show the new window.
605 RequestNewWindowPermission(params.disposition, gfx::Rect(),
606 params.user_gesture,
607 new_guest->guest_web_contents());
608
609 return new_guest;
610 }
611
612 // TODO(fsamuel): Find a reliable way to test the 'responsive' and
613 // 'unresponsive' events.
RendererResponsive(content::WebContents * source)614 void WebViewGuest::RendererResponsive(content::WebContents* source) {
615 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
616 args->SetInteger(webview::kProcessId,
617 guest_web_contents()->GetRenderProcessHost()->GetID());
618 DispatchEvent(
619 new GuestViewBase::Event(webview::kEventResponsive, args.Pass()));
620 }
621
RendererUnresponsive(content::WebContents * source)622 void WebViewGuest::RendererUnresponsive(content::WebContents* source) {
623 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
624 args->SetInteger(webview::kProcessId,
625 guest_web_contents()->GetRenderProcessHost()->GetID());
626 DispatchEvent(
627 new GuestViewBase::Event(webview::kEventUnresponsive, args.Pass()));
628 }
629
Observe(int type,const content::NotificationSource & source,const content::NotificationDetails & details)630 void WebViewGuest::Observe(int type,
631 const content::NotificationSource& source,
632 const content::NotificationDetails& details) {
633 switch (type) {
634 case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: {
635 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
636 guest_web_contents());
637 if (content::Source<WebContents>(source).ptr() == guest_web_contents())
638 LoadHandlerCalled();
639 break;
640 }
641 case content::NOTIFICATION_RESOURCE_RECEIVED_REDIRECT: {
642 DCHECK_EQ(content::Source<WebContents>(source).ptr(),
643 guest_web_contents());
644 content::ResourceRedirectDetails* resource_redirect_details =
645 content::Details<content::ResourceRedirectDetails>(details).ptr();
646 bool is_top_level =
647 resource_redirect_details->resource_type == ResourceType::MAIN_FRAME;
648 LoadRedirect(resource_redirect_details->url,
649 resource_redirect_details->new_url,
650 is_top_level);
651 break;
652 }
653 default:
654 NOTREACHED() << "Unexpected notification sent.";
655 break;
656 }
657 }
658
GetZoom()659 double WebViewGuest::GetZoom() {
660 return current_zoom_factor_;
661 }
662
Find(const base::string16 & search_text,const blink::WebFindOptions & options,scoped_refptr<extensions::WebviewFindFunction> find_function)663 void WebViewGuest::Find(
664 const base::string16& search_text,
665 const blink::WebFindOptions& options,
666 scoped_refptr<extensions::WebviewFindFunction> find_function) {
667 find_helper_.Find(guest_web_contents(), search_text, options, find_function);
668 }
669
StopFinding(content::StopFindAction action)670 void WebViewGuest::StopFinding(content::StopFindAction action) {
671 find_helper_.CancelAllFindSessions();
672 guest_web_contents()->StopFinding(action);
673 }
674
Go(int relative_index)675 void WebViewGuest::Go(int relative_index) {
676 guest_web_contents()->GetController().GoToOffset(relative_index);
677 }
678
Reload()679 void WebViewGuest::Reload() {
680 // TODO(fsamuel): Don't check for repost because we don't want to show
681 // Chromium's repost warning. We might want to implement a separate API
682 // for registering a callback if a repost is about to happen.
683 guest_web_contents()->GetController().Reload(false);
684 }
685
RequestFileSystemPermission(const GURL & url,bool allowed_by_default,const base::Callback<void (bool)> & callback)686 void WebViewGuest::RequestFileSystemPermission(
687 const GURL& url,
688 bool allowed_by_default,
689 const base::Callback<void(bool)>& callback) {
690 base::DictionaryValue request_info;
691 request_info.Set(guestview::kUrl, base::Value::CreateStringValue(url.spec()));
692 RequestPermission(
693 WEB_VIEW_PERMISSION_TYPE_FILESYSTEM,
694 request_info,
695 base::Bind(&WebViewGuest::OnWebViewFileSystemPermissionResponse,
696 base::Unretained(this),
697 callback),
698 allowed_by_default);
699 }
700
OnWebViewFileSystemPermissionResponse(const base::Callback<void (bool)> & callback,bool allow,const std::string & user_input)701 void WebViewGuest::OnWebViewFileSystemPermissionResponse(
702 const base::Callback<void(bool)>& callback,
703 bool allow,
704 const std::string& user_input) {
705 callback.Run(allow && attached());
706 }
707
RequestGeolocationPermission(int bridge_id,const GURL & requesting_frame,bool user_gesture,const base::Callback<void (bool)> & callback)708 void WebViewGuest::RequestGeolocationPermission(
709 int bridge_id,
710 const GURL& requesting_frame,
711 bool user_gesture,
712 const base::Callback<void(bool)>& callback) {
713 base::DictionaryValue request_info;
714 request_info.Set(guestview::kUrl,
715 base::Value::CreateStringValue(requesting_frame.spec()));
716 request_info.Set(guestview::kUserGesture,
717 base::Value::CreateBooleanValue(user_gesture));
718
719 // It is safe to hold an unretained pointer to WebViewGuest because this
720 // callback is called from WebViewGuest::SetPermission.
721 const PermissionResponseCallback permission_callback =
722 base::Bind(&WebViewGuest::OnWebViewGeolocationPermissionResponse,
723 base::Unretained(this),
724 bridge_id,
725 user_gesture,
726 callback);
727 int request_id = RequestPermission(
728 WEB_VIEW_PERMISSION_TYPE_GEOLOCATION,
729 request_info,
730 permission_callback,
731 false /* allowed_by_default */);
732 bridge_id_to_request_id_map_[bridge_id] = request_id;
733 }
734
OnWebViewGeolocationPermissionResponse(int bridge_id,bool user_gesture,const base::Callback<void (bool)> & callback,bool allow,const std::string & user_input)735 void WebViewGuest::OnWebViewGeolocationPermissionResponse(
736 int bridge_id,
737 bool user_gesture,
738 const base::Callback<void(bool)>& callback,
739 bool allow,
740 const std::string& user_input) {
741 // The <webview> embedder has allowed the permission. We now need to make sure
742 // that the embedder has geolocation permission.
743 RemoveBridgeID(bridge_id);
744
745 if (!allow || !attached()) {
746 callback.Run(false);
747 return;
748 }
749
750 Profile* profile = Profile::FromBrowserContext(browser_context());
751 GeolocationPermissionContextFactory::GetForProfile(profile)->
752 RequestGeolocationPermission(
753 embedder_web_contents(),
754 // The geolocation permission request here is not initiated
755 // through WebGeolocationPermissionRequest. We are only interested
756 // in the fact whether the embedder/app has geolocation
757 // permission. Therefore we use an invalid |bridge_id|.
758 -1,
759 embedder_web_contents()->GetLastCommittedURL(),
760 user_gesture,
761 callback,
762 NULL);
763 }
764
CancelGeolocationPermissionRequest(int bridge_id)765 void WebViewGuest::CancelGeolocationPermissionRequest(int bridge_id) {
766 int request_id = RemoveBridgeID(bridge_id);
767 RequestMap::iterator request_itr =
768 pending_permission_requests_.find(request_id);
769
770 if (request_itr == pending_permission_requests_.end())
771 return;
772
773 pending_permission_requests_.erase(request_itr);
774 }
775
OnWebViewMediaPermissionResponse(const content::MediaStreamRequest & request,const content::MediaResponseCallback & callback,bool allow,const std::string & user_input)776 void WebViewGuest::OnWebViewMediaPermissionResponse(
777 const content::MediaStreamRequest& request,
778 const content::MediaResponseCallback& callback,
779 bool allow,
780 const std::string& user_input) {
781 if (!allow || !attached()) {
782 // Deny the request.
783 callback.Run(content::MediaStreamDevices(),
784 content::MEDIA_DEVICE_INVALID_STATE,
785 scoped_ptr<content::MediaStreamUI>());
786 return;
787 }
788 if (!embedder_web_contents()->GetDelegate())
789 return;
790
791 embedder_web_contents()->GetDelegate()->
792 RequestMediaAccessPermission(embedder_web_contents(), request, callback);
793 }
794
OnWebViewDownloadPermissionResponse(const base::Callback<void (bool)> & callback,bool allow,const std::string & user_input)795 void WebViewGuest::OnWebViewDownloadPermissionResponse(
796 const base::Callback<void(bool)>& callback,
797 bool allow,
798 const std::string& user_input) {
799 callback.Run(allow && attached());
800 }
801
OnWebViewPointerLockPermissionResponse(const base::Callback<void (bool)> & callback,bool allow,const std::string & user_input)802 void WebViewGuest::OnWebViewPointerLockPermissionResponse(
803 const base::Callback<void(bool)>& callback,
804 bool allow,
805 const std::string& user_input) {
806 callback.Run(allow && attached());
807 }
808
SetPermission(int request_id,PermissionResponseAction action,const std::string & user_input)809 WebViewGuest::SetPermissionResult WebViewGuest::SetPermission(
810 int request_id,
811 PermissionResponseAction action,
812 const std::string& user_input) {
813 RequestMap::iterator request_itr =
814 pending_permission_requests_.find(request_id);
815
816 if (request_itr == pending_permission_requests_.end())
817 return SET_PERMISSION_INVALID;
818
819 const PermissionResponseInfo& info = request_itr->second;
820 bool allow = (action == ALLOW) ||
821 ((action == DEFAULT) && info.allowed_by_default);
822
823 info.callback.Run(allow, user_input);
824
825 // Only record user initiated (i.e. non-default) actions.
826 if (action != DEFAULT)
827 RecordUserInitiatedUMA(info, allow);
828
829 pending_permission_requests_.erase(request_itr);
830
831 return allow ? SET_PERMISSION_ALLOWED : SET_PERMISSION_DENIED;
832 }
833
SetUserAgentOverride(const std::string & user_agent_override)834 void WebViewGuest::SetUserAgentOverride(
835 const std::string& user_agent_override) {
836 if (!attached())
837 return;
838 is_overriding_user_agent_ = !user_agent_override.empty();
839 if (is_overriding_user_agent_) {
840 content::RecordAction(UserMetricsAction("WebView.Guest.OverrideUA"));
841 }
842 guest_web_contents()->SetUserAgentOverride(user_agent_override);
843 }
844
Stop()845 void WebViewGuest::Stop() {
846 guest_web_contents()->Stop();
847 }
848
Terminate()849 void WebViewGuest::Terminate() {
850 content::RecordAction(UserMetricsAction("WebView.Guest.Terminate"));
851 base::ProcessHandle process_handle =
852 guest_web_contents()->GetRenderProcessHost()->GetHandle();
853 if (process_handle)
854 base::KillProcess(process_handle, content::RESULT_CODE_KILLED, false);
855 }
856
ClearData(const base::Time remove_since,uint32 removal_mask,const base::Closure & callback)857 bool WebViewGuest::ClearData(const base::Time remove_since,
858 uint32 removal_mask,
859 const base::Closure& callback) {
860 content::RecordAction(UserMetricsAction("WebView.Guest.ClearData"));
861 content::StoragePartition* partition =
862 content::BrowserContext::GetStoragePartition(
863 guest_web_contents()->GetBrowserContext(),
864 guest_web_contents()->GetSiteInstance());
865
866 if (!partition)
867 return false;
868
869 partition->ClearData(
870 removal_mask,
871 content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL,
872 GURL(),
873 content::StoragePartition::OriginMatcherFunction(),
874 remove_since,
875 base::Time::Now(),
876 callback);
877 return true;
878 }
879
880 // static
FileSystemAccessedAsync(int render_process_id,int render_frame_id,int request_id,const GURL & url,bool blocked_by_policy)881 void WebViewGuest::FileSystemAccessedAsync(int render_process_id,
882 int render_frame_id,
883 int request_id,
884 const GURL& url,
885 bool blocked_by_policy) {
886 WebViewGuest* guest =
887 WebViewGuest::FromFrameID(render_process_id, render_frame_id);
888 DCHECK(guest);
889 guest->RequestFileSystemPermission(
890 url,
891 !blocked_by_policy,
892 base::Bind(&WebViewGuest::FileSystemAccessedAsyncResponse,
893 render_process_id,
894 render_frame_id,
895 request_id,
896 url));
897 }
898
899 // static
FileSystemAccessedAsyncResponse(int render_process_id,int render_frame_id,int request_id,const GURL & url,bool allowed)900 void WebViewGuest::FileSystemAccessedAsyncResponse(int render_process_id,
901 int render_frame_id,
902 int request_id,
903 const GURL& url,
904 bool allowed) {
905 TabSpecificContentSettings::FileSystemAccessed(
906 render_process_id, render_frame_id, url, !allowed);
907 content::RenderFrameHost* render_frame_host =
908 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
909 if (!render_frame_host)
910 return;
911 render_frame_host->Send(
912 new ChromeViewMsg_RequestFileSystemAccessAsyncResponse(
913 render_frame_id, request_id, allowed));
914 }
915
916 // static
FileSystemAccessedSync(int render_process_id,int render_frame_id,const GURL & url,bool blocked_by_policy,IPC::Message * reply_msg)917 void WebViewGuest::FileSystemAccessedSync(int render_process_id,
918 int render_frame_id,
919 const GURL& url,
920 bool blocked_by_policy,
921 IPC::Message* reply_msg) {
922 WebViewGuest* guest =
923 WebViewGuest::FromFrameID(render_process_id, render_frame_id);
924 DCHECK(guest);
925 guest->RequestFileSystemPermission(
926 url,
927 !blocked_by_policy,
928 base::Bind(&WebViewGuest::FileSystemAccessedSyncResponse,
929 render_process_id,
930 render_frame_id,
931 url,
932 reply_msg));
933 }
934
935 // static
FileSystemAccessedSyncResponse(int render_process_id,int render_frame_id,const GURL & url,IPC::Message * reply_msg,bool allowed)936 void WebViewGuest::FileSystemAccessedSyncResponse(int render_process_id,
937 int render_frame_id,
938 const GURL& url,
939 IPC::Message* reply_msg,
940 bool allowed) {
941 TabSpecificContentSettings::FileSystemAccessed(
942 render_process_id, render_frame_id, url, !allowed);
943 ChromeViewHostMsg_RequestFileSystemAccessSync::WriteReplyParams(reply_msg,
944 allowed);
945 content::RenderFrameHost* render_frame_host =
946 content::RenderFrameHost::FromID(render_process_id, render_frame_id);
947 if (!render_frame_id)
948 return;
949 render_frame_host->Send(reply_msg);
950 }
951
~WebViewGuest()952 WebViewGuest::~WebViewGuest() {
953 }
954
DidCommitProvisionalLoadForFrame(int64 frame_id,const base::string16 & frame_unique_name,bool is_main_frame,const GURL & url,content::PageTransition transition_type,content::RenderViewHost * render_view_host)955 void WebViewGuest::DidCommitProvisionalLoadForFrame(
956 int64 frame_id,
957 const base::string16& frame_unique_name,
958 bool is_main_frame,
959 const GURL& url,
960 content::PageTransition transition_type,
961 content::RenderViewHost* render_view_host) {
962 find_helper_.CancelAllFindSessions();
963
964 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
965 args->SetString(guestview::kUrl, url.spec());
966 args->SetBoolean(guestview::kIsTopLevel, is_main_frame);
967 args->SetInteger(webview::kInternalCurrentEntryIndex,
968 guest_web_contents()->GetController().GetCurrentEntryIndex());
969 args->SetInteger(webview::kInternalEntryCount,
970 guest_web_contents()->GetController().GetEntryCount());
971 args->SetInteger(webview::kInternalProcessId,
972 guest_web_contents()->GetRenderProcessHost()->GetID());
973 DispatchEvent(
974 new GuestViewBase::Event(webview::kEventLoadCommit, args.Pass()));
975
976 // Update the current zoom factor for the new page.
977 current_zoom_factor_ = content::ZoomLevelToZoomFactor(
978 content::HostZoomMap::GetZoomLevel(guest_web_contents()));
979
980 if (is_main_frame) {
981 chromevox_injected_ = false;
982 main_frame_id_ = frame_id;
983 }
984 }
985
DidFailProvisionalLoad(int64 frame_id,const base::string16 & frame_unique_name,bool is_main_frame,const GURL & validated_url,int error_code,const base::string16 & error_description,content::RenderViewHost * render_view_host)986 void WebViewGuest::DidFailProvisionalLoad(
987 int64 frame_id,
988 const base::string16& frame_unique_name,
989 bool is_main_frame,
990 const GURL& validated_url,
991 int error_code,
992 const base::string16& error_description,
993 content::RenderViewHost* render_view_host) {
994 // Translate the |error_code| into an error string.
995 std::string error_type(net::ErrorToString(error_code));
996 DCHECK(StartsWithASCII(error_type, "net::", true));
997 error_type.erase(0, 5);
998 LoadAbort(is_main_frame, validated_url, error_type);
999 }
1000
DidStartProvisionalLoadForFrame(int64 frame_id,int64 parent_frame_id,bool is_main_frame,const GURL & validated_url,bool is_error_page,bool is_iframe_srcdoc,content::RenderViewHost * render_view_host)1001 void WebViewGuest::DidStartProvisionalLoadForFrame(
1002 int64 frame_id,
1003 int64 parent_frame_id,
1004 bool is_main_frame,
1005 const GURL& validated_url,
1006 bool is_error_page,
1007 bool is_iframe_srcdoc,
1008 content::RenderViewHost* render_view_host) {
1009 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1010 args->SetString(guestview::kUrl, validated_url.spec());
1011 args->SetBoolean(guestview::kIsTopLevel, is_main_frame);
1012 DispatchEvent(
1013 new GuestViewBase::Event(webview::kEventLoadStart, args.Pass()));
1014 }
1015
DocumentLoadedInFrame(int64 frame_id,content::RenderViewHost * render_view_host)1016 void WebViewGuest::DocumentLoadedInFrame(
1017 int64 frame_id,
1018 content::RenderViewHost* render_view_host) {
1019 if (frame_id == main_frame_id_)
1020 InjectChromeVoxIfNeeded(render_view_host);
1021 }
1022
OnMessageReceived(const IPC::Message & message,RenderFrameHost * render_frame_host)1023 bool WebViewGuest::OnMessageReceived(const IPC::Message& message,
1024 RenderFrameHost* render_frame_host) {
1025 bool handled = true;
1026 IPC_BEGIN_MESSAGE_MAP(WebViewGuest, message)
1027 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdateFrameName, OnUpdateFrameName)
1028 IPC_MESSAGE_UNHANDLED(handled = false)
1029 IPC_END_MESSAGE_MAP()
1030 return handled;
1031 }
1032
RenderProcessGone(base::TerminationStatus status)1033 void WebViewGuest::RenderProcessGone(base::TerminationStatus status) {
1034 // Cancel all find sessions in progress.
1035 find_helper_.CancelAllFindSessions();
1036
1037 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1038 args->SetInteger(webview::kProcessId,
1039 guest_web_contents()->GetRenderProcessHost()->GetID());
1040 args->SetString(webview::kReason, TerminationStatusToString(status));
1041 DispatchEvent(new GuestViewBase::Event(webview::kEventExit, args.Pass()));
1042 }
1043
UserAgentOverrideSet(const std::string & user_agent)1044 void WebViewGuest::UserAgentOverrideSet(const std::string& user_agent) {
1045 if (!attached())
1046 return;
1047 content::NavigationController& controller =
1048 guest_web_contents()->GetController();
1049 content::NavigationEntry* entry = controller.GetVisibleEntry();
1050 if (!entry)
1051 return;
1052 entry->SetIsOverridingUserAgent(!user_agent.empty());
1053 guest_web_contents()->GetController().Reload(false);
1054 }
1055
RenderViewReady()1056 void WebViewGuest::RenderViewReady() {
1057 // The guest RenderView should always live in an isolated guest process.
1058 CHECK(guest_web_contents()->GetRenderProcessHost()->IsIsolatedGuest());
1059 Send(new ChromeViewMsg_SetName(guest_web_contents()->GetRoutingID(), name_));
1060 }
1061
ReportFrameNameChange(const std::string & name)1062 void WebViewGuest::ReportFrameNameChange(const std::string& name) {
1063 name_ = name;
1064 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1065 args->SetString(webview::kName, name);
1066 DispatchEvent(
1067 new GuestViewBase::Event(webview::kEventFrameNameChanged, args.Pass()));
1068 }
1069
LoadHandlerCalled()1070 void WebViewGuest::LoadHandlerCalled() {
1071 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1072 DispatchEvent(
1073 new GuestViewBase::Event(webview::kEventContentLoad, args.Pass()));
1074 }
1075
LoadRedirect(const GURL & old_url,const GURL & new_url,bool is_top_level)1076 void WebViewGuest::LoadRedirect(const GURL& old_url,
1077 const GURL& new_url,
1078 bool is_top_level) {
1079 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1080 args->SetBoolean(guestview::kIsTopLevel, is_top_level);
1081 args->SetString(webview::kNewURL, new_url.spec());
1082 args->SetString(webview::kOldURL, old_url.spec());
1083 DispatchEvent(
1084 new GuestViewBase::Event(webview::kEventLoadRedirect, args.Pass()));
1085 }
1086
AddWebViewToExtensionRendererState()1087 void WebViewGuest::AddWebViewToExtensionRendererState() {
1088 const GURL& site_url = guest_web_contents()->GetSiteInstance()->GetSiteURL();
1089 std::string partition_domain;
1090 std::string partition_id;
1091 bool in_memory;
1092 if (!GetGuestPartitionConfigForSite(
1093 site_url, &partition_domain, &partition_id, &in_memory)) {
1094 NOTREACHED();
1095 return;
1096 }
1097 DCHECK(embedder_extension_id() == partition_domain);
1098
1099 ExtensionRendererState::WebViewInfo web_view_info;
1100 web_view_info.embedder_process_id = embedder_render_process_id();
1101 web_view_info.instance_id = view_instance_id();
1102 web_view_info.partition_id = partition_id;
1103 web_view_info.embedder_extension_id = embedder_extension_id();
1104
1105 content::BrowserThread::PostTask(
1106 content::BrowserThread::IO,
1107 FROM_HERE,
1108 base::Bind(&ExtensionRendererState::AddWebView,
1109 base::Unretained(ExtensionRendererState::GetInstance()),
1110 guest_web_contents()->GetRenderProcessHost()->GetID(),
1111 guest_web_contents()->GetRoutingID(),
1112 web_view_info));
1113 }
1114
1115 // static
RemoveWebViewFromExtensionRendererState(WebContents * web_contents)1116 void WebViewGuest::RemoveWebViewFromExtensionRendererState(
1117 WebContents* web_contents) {
1118 content::BrowserThread::PostTask(
1119 content::BrowserThread::IO, FROM_HERE,
1120 base::Bind(
1121 &ExtensionRendererState::RemoveWebView,
1122 base::Unretained(ExtensionRendererState::GetInstance()),
1123 web_contents->GetRenderProcessHost()->GetID(),
1124 web_contents->GetRoutingID()));
1125 }
1126
SizeChanged(const gfx::Size & old_size,const gfx::Size & new_size)1127 void WebViewGuest::SizeChanged(const gfx::Size& old_size,
1128 const gfx::Size& new_size) {
1129 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1130 args->SetInteger(webview::kOldHeight, old_size.height());
1131 args->SetInteger(webview::kOldWidth, old_size.width());
1132 args->SetInteger(webview::kNewHeight, new_size.height());
1133 args->SetInteger(webview::kNewWidth, new_size.width());
1134 DispatchEvent(
1135 new GuestViewBase::Event(webview::kEventSizeChanged, args.Pass()));
1136 }
1137
RequestMediaAccessPermission(content::WebContents * source,const content::MediaStreamRequest & request,const content::MediaResponseCallback & callback)1138 void WebViewGuest::RequestMediaAccessPermission(
1139 content::WebContents* source,
1140 const content::MediaStreamRequest& request,
1141 const content::MediaResponseCallback& callback) {
1142 base::DictionaryValue request_info;
1143 request_info.Set(
1144 guestview::kUrl,
1145 base::Value::CreateStringValue(request.security_origin.spec()));
1146 RequestPermission(WEB_VIEW_PERMISSION_TYPE_MEDIA,
1147 request_info,
1148 base::Bind(&WebViewGuest::OnWebViewMediaPermissionResponse,
1149 base::Unretained(this),
1150 request,
1151 callback),
1152 false /* allowed_by_default */);
1153 }
1154
CanDownload(content::RenderViewHost * render_view_host,const GURL & url,const std::string & request_method,const base::Callback<void (bool)> & callback)1155 void WebViewGuest::CanDownload(
1156 content::RenderViewHost* render_view_host,
1157 const GURL& url,
1158 const std::string& request_method,
1159 const base::Callback<void(bool)>& callback) {
1160 base::DictionaryValue request_info;
1161 request_info.Set(
1162 guestview::kUrl,
1163 base::Value::CreateStringValue(url.spec()));
1164 RequestPermission(
1165 WEB_VIEW_PERMISSION_TYPE_DOWNLOAD,
1166 request_info,
1167 base::Bind(&WebViewGuest::OnWebViewDownloadPermissionResponse,
1168 base::Unretained(this),
1169 callback),
1170 false /* allowed_by_default */);
1171 }
1172
RequestPointerLockPermission(bool user_gesture,bool last_unlocked_by_target,const base::Callback<void (bool)> & callback)1173 void WebViewGuest::RequestPointerLockPermission(
1174 bool user_gesture,
1175 bool last_unlocked_by_target,
1176 const base::Callback<void(bool)>& callback) {
1177 base::DictionaryValue request_info;
1178 request_info.Set(guestview::kUserGesture,
1179 base::Value::CreateBooleanValue(user_gesture));
1180 request_info.Set(webview::kLastUnlockedBySelf,
1181 base::Value::CreateBooleanValue(last_unlocked_by_target));
1182 request_info.Set(guestview::kUrl,
1183 base::Value::CreateStringValue(
1184 guest_web_contents()->GetLastCommittedURL().spec()));
1185
1186 RequestPermission(
1187 WEB_VIEW_PERMISSION_TYPE_POINTER_LOCK,
1188 request_info,
1189 base::Bind(&WebViewGuest::OnWebViewPointerLockPermissionResponse,
1190 base::Unretained(this),
1191 callback),
1192 false /* allowed_by_default */);
1193 }
1194
WillAttachToEmbedder()1195 void WebViewGuest::WillAttachToEmbedder() {
1196 // We must install the mapping from guests to WebViews prior to resuming
1197 // suspended resource loads so that the WebRequest API will catch resource
1198 // requests.
1199 AddWebViewToExtensionRendererState();
1200 }
1201
1202 content::JavaScriptDialogManager*
GetJavaScriptDialogManager()1203 WebViewGuest::GetJavaScriptDialogManager() {
1204 return &javascript_dialog_helper_;
1205 }
1206
OpenColorChooser(WebContents * web_contents,SkColor color,const std::vector<content::ColorSuggestion> & suggestions)1207 content::ColorChooser* WebViewGuest::OpenColorChooser(
1208 WebContents* web_contents,
1209 SkColor color,
1210 const std::vector<content::ColorSuggestion>& suggestions) {
1211 if (!attached() || !embedder_web_contents()->GetDelegate())
1212 return NULL;
1213 return embedder_web_contents()->GetDelegate()->OpenColorChooser(
1214 web_contents, color, suggestions);
1215 }
1216
RunFileChooser(WebContents * web_contents,const content::FileChooserParams & params)1217 void WebViewGuest::RunFileChooser(WebContents* web_contents,
1218 const content::FileChooserParams& params) {
1219 if (!attached() || !embedder_web_contents()->GetDelegate())
1220 return;
1221
1222 embedder_web_contents()->GetDelegate()->RunFileChooser(web_contents, params);
1223 }
1224
NavigateGuest(const std::string & src)1225 void WebViewGuest::NavigateGuest(const std::string& src) {
1226 GURL url = ResolveURL(src);
1227
1228 // Do not allow navigating a guest to schemes other than known safe schemes.
1229 // This will block the embedder trying to load unwanted schemes, e.g.
1230 // chrome://settings.
1231 bool scheme_is_blocked =
1232 (!content::ChildProcessSecurityPolicy::GetInstance()->IsWebSafeScheme(
1233 url.scheme()) &&
1234 !url.SchemeIs(url::kAboutScheme)) ||
1235 url.SchemeIs(url::kJavaScriptScheme);
1236 if (scheme_is_blocked || !url.is_valid()) {
1237 std::string error_type(net::ErrorToString(net::ERR_ABORTED));
1238 DCHECK(StartsWithASCII(error_type, "net::", true));
1239 error_type.erase(0, 5);
1240 LoadAbort(true /* is_top_level */, url, error_type);
1241 return;
1242 }
1243
1244 GURL validated_url(url);
1245 guest_web_contents()->GetRenderProcessHost()->
1246 FilterURL(false, &validated_url);
1247 // As guests do not swap processes on navigation, only navigations to
1248 // normal web URLs are supported. No protocol handlers are installed for
1249 // other schemes (e.g., WebUI or extensions), and no permissions or bindings
1250 // can be granted to the guest process.
1251 LoadURLWithParams(validated_url,
1252 content::Referrer(),
1253 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
1254 guest_web_contents());
1255 }
1256
1257 #if defined(OS_CHROMEOS)
OnAccessibilityStatusChanged(const chromeos::AccessibilityStatusEventDetails & details)1258 void WebViewGuest::OnAccessibilityStatusChanged(
1259 const chromeos::AccessibilityStatusEventDetails& details) {
1260 if (details.notification_type == chromeos::ACCESSIBILITY_MANAGER_SHUTDOWN) {
1261 accessibility_subscription_.reset();
1262 } else if (details.notification_type ==
1263 chromeos::ACCESSIBILITY_TOGGLE_SPOKEN_FEEDBACK) {
1264 if (details.enabled)
1265 InjectChromeVoxIfNeeded(guest_web_contents()->GetRenderViewHost());
1266 else
1267 chromevox_injected_ = false;
1268 }
1269 }
1270 #endif
1271
InjectChromeVoxIfNeeded(content::RenderViewHost * render_view_host)1272 void WebViewGuest::InjectChromeVoxIfNeeded(
1273 content::RenderViewHost* render_view_host) {
1274 #if defined(OS_CHROMEOS)
1275 if (!chromevox_injected_) {
1276 chromeos::AccessibilityManager* manager =
1277 chromeos::AccessibilityManager::Get();
1278 if (manager && manager->IsSpokenFeedbackEnabled()) {
1279 manager->InjectChromeVox(render_view_host);
1280 chromevox_injected_ = true;
1281 }
1282 }
1283 #endif
1284 }
1285
RemoveBridgeID(int bridge_id)1286 int WebViewGuest::RemoveBridgeID(int bridge_id) {
1287 std::map<int, int>::iterator bridge_itr =
1288 bridge_id_to_request_id_map_.find(bridge_id);
1289 if (bridge_itr == bridge_id_to_request_id_map_.end())
1290 return webview::kInvalidPermissionRequestID;
1291
1292 int request_id = bridge_itr->second;
1293 bridge_id_to_request_id_map_.erase(bridge_itr);
1294 return request_id;
1295 }
1296
RequestPermission(WebViewPermissionType permission_type,const base::DictionaryValue & request_info,const PermissionResponseCallback & callback,bool allowed_by_default)1297 int WebViewGuest::RequestPermission(
1298 WebViewPermissionType permission_type,
1299 const base::DictionaryValue& request_info,
1300 const PermissionResponseCallback& callback,
1301 bool allowed_by_default) {
1302 // If there are too many pending permission requests then reject this request.
1303 if (pending_permission_requests_.size() >=
1304 webview::kMaxOutstandingPermissionRequests) {
1305 // Let the stack unwind before we deny the permission request so that
1306 // objects held by the permission request are not destroyed immediately
1307 // after creation. This is to allow those same objects to be accessed again
1308 // in the same scope without fear of use after freeing.
1309 base::MessageLoop::current()->PostTask(
1310 FROM_HERE,
1311 base::Bind(&PermissionResponseCallback::Run,
1312 base::Owned(new PermissionResponseCallback(callback)),
1313 allowed_by_default,
1314 std::string()));
1315 return webview::kInvalidPermissionRequestID;
1316 }
1317
1318 int request_id = next_permission_request_id_++;
1319 pending_permission_requests_[request_id] =
1320 PermissionResponseInfo(callback, permission_type, allowed_by_default);
1321 scoped_ptr<base::DictionaryValue> args(request_info.DeepCopy());
1322 args->SetInteger(webview::kRequestId, request_id);
1323 switch (permission_type) {
1324 case WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW: {
1325 DispatchEvent(
1326 new GuestViewBase::Event(webview::kEventNewWindow, args.Pass()));
1327 break;
1328 }
1329 case WEB_VIEW_PERMISSION_TYPE_JAVASCRIPT_DIALOG: {
1330 DispatchEvent(
1331 new GuestViewBase::Event(webview::kEventDialog, args.Pass()));
1332 break;
1333 }
1334 default: {
1335 args->SetString(webview::kPermission,
1336 PermissionTypeToString(permission_type));
1337 DispatchEvent(new GuestViewBase::Event(webview::kEventPermissionRequest,
1338 args.Pass()));
1339 break;
1340 }
1341 }
1342 return request_id;
1343 }
1344
HandleKeyboardShortcuts(const content::NativeWebKeyboardEvent & event)1345 bool WebViewGuest::HandleKeyboardShortcuts(
1346 const content::NativeWebKeyboardEvent& event) {
1347 if (event.type != blink::WebInputEvent::RawKeyDown)
1348 return false;
1349
1350 // If the user hits the escape key without any modifiers then unlock the
1351 // mouse if necessary.
1352 if ((event.windowsKeyCode == ui::VKEY_ESCAPE) &&
1353 !(event.modifiers & blink::WebInputEvent::InputModifiers)) {
1354 return guest_web_contents()->GotResponseToLockMouseRequest(false);
1355 }
1356
1357 #if defined(OS_MACOSX)
1358 if (event.modifiers != blink::WebInputEvent::MetaKey)
1359 return false;
1360
1361 if (event.windowsKeyCode == ui::VKEY_OEM_4) {
1362 Go(-1);
1363 return true;
1364 }
1365
1366 if (event.windowsKeyCode == ui::VKEY_OEM_6) {
1367 Go(1);
1368 return true;
1369 }
1370 #else
1371 if (event.windowsKeyCode == ui::VKEY_BROWSER_BACK) {
1372 Go(-1);
1373 return true;
1374 }
1375
1376 if (event.windowsKeyCode == ui::VKEY_BROWSER_FORWARD) {
1377 Go(1);
1378 return true;
1379 }
1380 #endif
1381
1382 return false;
1383 }
1384
PermissionResponseInfo()1385 WebViewGuest::PermissionResponseInfo::PermissionResponseInfo()
1386 : permission_type(WEB_VIEW_PERMISSION_TYPE_UNKNOWN),
1387 allowed_by_default(false) {
1388 }
1389
PermissionResponseInfo(const PermissionResponseCallback & callback,WebViewPermissionType permission_type,bool allowed_by_default)1390 WebViewGuest::PermissionResponseInfo::PermissionResponseInfo(
1391 const PermissionResponseCallback& callback,
1392 WebViewPermissionType permission_type,
1393 bool allowed_by_default)
1394 : callback(callback),
1395 permission_type(permission_type),
1396 allowed_by_default(allowed_by_default) {
1397 }
1398
~PermissionResponseInfo()1399 WebViewGuest::PermissionResponseInfo::~PermissionResponseInfo() {
1400 }
1401
ShowContextMenu(int request_id,const MenuItemVector * items)1402 void WebViewGuest::ShowContextMenu(int request_id,
1403 const MenuItemVector* items) {
1404 if (!pending_menu_.get())
1405 return;
1406
1407 // Make sure this was the correct request.
1408 if (request_id != pending_context_menu_request_id_)
1409 return;
1410
1411 // TODO(lazyboy): Implement.
1412 DCHECK(!items);
1413
1414 ContextMenuDelegate* menu_delegate =
1415 ContextMenuDelegate::FromWebContents(guest_web_contents());
1416 menu_delegate->ShowMenu(pending_menu_.Pass());
1417 }
1418
SetName(const std::string & name)1419 void WebViewGuest::SetName(const std::string& name) {
1420 if (name_ == name)
1421 return;
1422 name_ = name;
1423
1424 Send(new ChromeViewMsg_SetName(routing_id(), name_));
1425 }
1426
SetZoom(double zoom_factor)1427 void WebViewGuest::SetZoom(double zoom_factor) {
1428 double zoom_level = content::ZoomFactorToZoomLevel(zoom_factor);
1429 content::HostZoomMap::SetZoomLevel(guest_web_contents(), zoom_level);
1430
1431 scoped_ptr<base::DictionaryValue> args(new base::DictionaryValue());
1432 args->SetDouble(webview::kOldZoomFactor, current_zoom_factor_);
1433 args->SetDouble(webview::kNewZoomFactor, zoom_factor);
1434 DispatchEvent(
1435 new GuestViewBase::Event(webview::kEventZoomChange, args.Pass()));
1436
1437 current_zoom_factor_ = zoom_factor;
1438 }
1439
AddNewContents(content::WebContents * source,content::WebContents * new_contents,WindowOpenDisposition disposition,const gfx::Rect & initial_pos,bool user_gesture,bool * was_blocked)1440 void WebViewGuest::AddNewContents(content::WebContents* source,
1441 content::WebContents* new_contents,
1442 WindowOpenDisposition disposition,
1443 const gfx::Rect& initial_pos,
1444 bool user_gesture,
1445 bool* was_blocked) {
1446 if (was_blocked)
1447 *was_blocked = false;
1448 RequestNewWindowPermission(disposition,
1449 initial_pos,
1450 user_gesture,
1451 new_contents);
1452 }
1453
OpenURLFromTab(content::WebContents * source,const content::OpenURLParams & params)1454 content::WebContents* WebViewGuest::OpenURLFromTab(
1455 content::WebContents* source,
1456 const content::OpenURLParams& params) {
1457 // If the guest wishes to navigate away prior to attachment then we save the
1458 // navigation to perform upon attachment. Navigation initializes a lot of
1459 // state that assumes an embedder exists, such as RenderWidgetHostViewGuest.
1460 // Navigation also resumes resource loading which we don't want to allow
1461 // until attachment.
1462 if (!attached()) {
1463 WebViewGuest* opener = GetOpener();
1464 PendingWindowMap::iterator it =
1465 opener->pending_new_windows_.find(this);
1466 if (it == opener->pending_new_windows_.end())
1467 return NULL;
1468 const NewWindowInfo& info = it->second;
1469 NewWindowInfo new_window_info(params.url, info.name);
1470 new_window_info.changed = new_window_info.url != info.url;
1471 it->second = new_window_info;
1472 return NULL;
1473 }
1474 if (params.disposition == CURRENT_TAB) {
1475 // This can happen for cross-site redirects.
1476 LoadURLWithParams(params.url, params.referrer, params.transition, source);
1477 return source;
1478 }
1479
1480 return CreateNewGuestWindow(params)->guest_web_contents();
1481 }
1482
WebContentsCreated(WebContents * source_contents,int opener_render_frame_id,const base::string16 & frame_name,const GURL & target_url,content::WebContents * new_contents)1483 void WebViewGuest::WebContentsCreated(WebContents* source_contents,
1484 int opener_render_frame_id,
1485 const base::string16& frame_name,
1486 const GURL& target_url,
1487 content::WebContents* new_contents) {
1488 WebViewGuest* guest = WebViewGuest::FromWebContents(new_contents);
1489 CHECK(guest);
1490 guest->SetOpener(this);
1491 std::string guest_name = base::UTF16ToUTF8(frame_name);
1492 guest->name_ = guest_name;
1493 pending_new_windows_.insert(
1494 std::make_pair(guest, NewWindowInfo(target_url, guest_name)));
1495 }
1496
LoadURLWithParams(const GURL & url,const content::Referrer & referrer,content::PageTransition transition_type,content::WebContents * web_contents)1497 void WebViewGuest::LoadURLWithParams(const GURL& url,
1498 const content::Referrer& referrer,
1499 content::PageTransition transition_type,
1500 content::WebContents* web_contents) {
1501 content::NavigationController::LoadURLParams load_url_params(url);
1502 load_url_params.referrer = referrer;
1503 load_url_params.transition_type = transition_type;
1504 load_url_params.extra_headers = std::string();
1505 if (is_overriding_user_agent_) {
1506 load_url_params.override_user_agent =
1507 content::NavigationController::UA_OVERRIDE_TRUE;
1508 }
1509 web_contents->GetController().LoadURLWithParams(load_url_params);
1510 }
1511
RequestNewWindowPermission(WindowOpenDisposition disposition,const gfx::Rect & initial_bounds,bool user_gesture,content::WebContents * new_contents)1512 void WebViewGuest::RequestNewWindowPermission(
1513 WindowOpenDisposition disposition,
1514 const gfx::Rect& initial_bounds,
1515 bool user_gesture,
1516 content::WebContents* new_contents) {
1517 WebViewGuest* guest = WebViewGuest::FromWebContents(new_contents);
1518 if (!guest)
1519 return;
1520 PendingWindowMap::iterator it = pending_new_windows_.find(guest);
1521 if (it == pending_new_windows_.end())
1522 return;
1523 const NewWindowInfo& new_window_info = it->second;
1524
1525 // Retrieve the opener partition info if we have it.
1526 const GURL& site_url = new_contents->GetSiteInstance()->GetSiteURL();
1527 std::string storage_partition_id = GetStoragePartitionIdFromSiteURL(site_url);
1528
1529 base::DictionaryValue request_info;
1530 request_info.Set(webview::kInitialHeight,
1531 base::Value::CreateIntegerValue(initial_bounds.height()));
1532 request_info.Set(webview::kInitialWidth,
1533 base::Value::CreateIntegerValue(initial_bounds.width()));
1534 request_info.Set(webview::kTargetURL,
1535 base::Value::CreateStringValue(new_window_info.url.spec()));
1536 request_info.Set(webview::kName,
1537 base::Value::CreateStringValue(new_window_info.name));
1538 request_info.Set(webview::kWindowID,
1539 base::Value::CreateIntegerValue(guest->guest_instance_id()));
1540 // We pass in partition info so that window-s created through newwindow
1541 // API can use it to set their partition attribute.
1542 request_info.Set(webview::kStoragePartitionId,
1543 base::Value::CreateStringValue(storage_partition_id));
1544 request_info.Set(webview::kWindowOpenDisposition,
1545 base::Value::CreateStringValue(
1546 WindowOpenDispositionToString(disposition)));
1547
1548 RequestPermission(WEB_VIEW_PERMISSION_TYPE_NEW_WINDOW,
1549 request_info,
1550 base::Bind(&WebViewGuest::OnWebViewNewWindowResponse,
1551 base::Unretained(this),
1552 guest->guest_instance_id()),
1553 false /* allowed_by_default */);
1554 }
1555
DestroyUnattachedWindows()1556 void WebViewGuest::DestroyUnattachedWindows() {
1557 // Destroy() reaches in and removes the WebViewGuest from its opener's
1558 // pending_new_windows_ set. To avoid mutating the set while iterating, we
1559 // create a copy of the pending new windows set and iterate over the copy.
1560 PendingWindowMap pending_new_windows(pending_new_windows_);
1561 // Clean up unattached new windows opened by this guest.
1562 for (PendingWindowMap::const_iterator it = pending_new_windows.begin();
1563 it != pending_new_windows.end(); ++it) {
1564 it->first->Destroy();
1565 }
1566 // All pending windows should be removed from the set after Destroy() is
1567 // called on all of them.
1568 DCHECK(pending_new_windows_.empty());
1569 }
1570
ResolveURL(const std::string & src)1571 GURL WebViewGuest::ResolveURL(const std::string& src) {
1572 if (!in_extension()) {
1573 NOTREACHED();
1574 return GURL(src);
1575 }
1576
1577 GURL default_url(base::StringPrintf("%s://%s/",
1578 extensions::kExtensionScheme,
1579 embedder_extension_id().c_str()));
1580 return default_url.Resolve(src);
1581 }
1582
OnWebViewNewWindowResponse(int new_window_instance_id,bool allow,const std::string & user_input)1583 void WebViewGuest::OnWebViewNewWindowResponse(
1584 int new_window_instance_id,
1585 bool allow,
1586 const std::string& user_input) {
1587 WebViewGuest* guest =
1588 WebViewGuest::From(embedder_render_process_id(), new_window_instance_id);
1589 if (!guest)
1590 return;
1591
1592 if (!allow)
1593 guest->Destroy();
1594 }
1595