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 // Implements the Chrome Extensions Debugger API.
7 #include "chrome/browser/extensions/api/debugger/debugger_api.h"
12 #include "base/command_line.h"
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/memory/singleton.h"
17 #include "base/scoped_observer.h"
18 #include "base/stl_util.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/values.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/devtools/devtools_target_impl.h"
24 #include "chrome/browser/extensions/api/debugger/debugger_api_constants.h"
25 #include "chrome/browser/extensions/extension_service.h"
26 #include "chrome/browser/extensions/extension_tab_util.h"
27 #include "chrome/browser/infobars/infobar_service.h"
28 #include "chrome/browser/profiles/profile.h"
29 #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
30 #include "chrome/common/chrome_switches.h"
31 #include "chrome/grit/generated_resources.h"
32 #include "components/infobars/core/confirm_infobar_delegate.h"
33 #include "components/infobars/core/infobar.h"
34 #include "content/public/browser/devtools_agent_host.h"
35 #include "content/public/browser/devtools_http_handler.h"
36 #include "content/public/browser/notification_service.h"
37 #include "content/public/browser/notification_source.h"
38 #include "content/public/browser/render_process_host.h"
39 #include "content/public/browser/render_view_host.h"
40 #include "content/public/browser/render_widget_host.h"
41 #include "content/public/browser/web_contents.h"
42 #include "content/public/common/content_client.h"
43 #include "content/public/common/url_utils.h"
44 #include "extensions/browser/event_router.h"
45 #include "extensions/browser/extension_host.h"
46 #include "extensions/browser/extension_registry.h"
47 #include "extensions/browser/extension_registry_observer.h"
48 #include "extensions/browser/extension_system.h"
49 #include "extensions/common/constants.h"
50 #include "extensions/common/error_utils.h"
51 #include "extensions/common/extension.h"
52 #include "extensions/common/manifest_constants.h"
53 #include "extensions/common/permissions/permissions_data.h"
54 #include "extensions/common/switches.h"
55 #include "ui/base/l10n/l10n_util.h"
57 using content::DevToolsAgentHost;
58 using content::DevToolsHttpHandler;
59 using content::RenderProcessHost;
60 using content::RenderViewHost;
61 using content::RenderWidgetHost;
62 using content::WebContents;
64 namespace keys = debugger_api_constants;
65 namespace Attach = extensions::api::debugger::Attach;
66 namespace Detach = extensions::api::debugger::Detach;
67 namespace OnDetach = extensions::api::debugger::OnDetach;
68 namespace OnEvent = extensions::api::debugger::OnEvent;
69 namespace SendCommand = extensions::api::debugger::SendCommand;
71 namespace extensions {
72 class ExtensionRegistry;
74 // ExtensionDevToolsClientHost ------------------------------------------------
76 class ExtensionDevToolsClientHost : public content::DevToolsAgentHostClient,
77 public content::NotificationObserver,
78 public ExtensionRegistryObserver {
80 ExtensionDevToolsClientHost(Profile* profile,
81 DevToolsAgentHost* agent_host,
82 const std::string& extension_id,
83 const std::string& extension_name,
84 const Debuggee& debuggee,
85 infobars::InfoBar* infobar);
87 virtual ~ExtensionDevToolsClientHost();
89 const std::string& extension_id() { return extension_id_; }
90 DevToolsAgentHost* agent_host() { return agent_host_.get(); }
92 void SendMessageToBackend(DebuggerSendCommandFunction* function,
93 const std::string& method,
94 SendCommand::Params::CommandParams* command_params);
96 // Marks connection as to-be-terminated by the user.
97 void MarkAsDismissed();
99 // DevToolsAgentHostClient interface.
100 virtual void AgentHostClosed(
101 DevToolsAgentHost* agent_host,
102 bool replaced_with_another_client) OVERRIDE;
103 virtual void DispatchProtocolMessage(
104 DevToolsAgentHost* agent_host,
105 const std::string& message) OVERRIDE;
108 void SendDetachedEvent();
110 // content::NotificationObserver implementation.
111 virtual void Observe(int type,
112 const content::NotificationSource& source,
113 const content::NotificationDetails& details) OVERRIDE;
115 // ExtensionRegistryObserver implementation.
116 virtual void OnExtensionUnloaded(
117 content::BrowserContext* browser_context,
118 const Extension* extension,
119 UnloadedExtensionInfo::Reason reason) OVERRIDE;
122 scoped_refptr<DevToolsAgentHost> agent_host_;
123 std::string extension_id_;
125 content::NotificationRegistrar registrar_;
126 int last_request_id_;
127 typedef std::map<int, scoped_refptr<DebuggerSendCommandFunction> >
129 PendingRequests pending_requests_;
130 infobars::InfoBar* infobar_;
131 OnDetach::Reason detach_reason_;
133 // Listen to extension unloaded notification.
134 ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
135 extension_registry_observer_;
137 DISALLOW_COPY_AND_ASSIGN(ExtensionDevToolsClientHost);
140 // The member function declarations come after the other class declarations, so
141 // they can call members on them.
146 // Helpers --------------------------------------------------------------------
148 void CopyDebuggee(Debuggee* dst, const Debuggee& src) {
150 dst->tab_id.reset(new int(*src.tab_id));
151 if (src.extension_id)
152 dst->extension_id.reset(new std::string(*src.extension_id));
154 dst->target_id.reset(new std::string(*src.target_id));
158 // ExtensionDevToolsInfoBarDelegate -------------------------------------------
160 class ExtensionDevToolsInfoBarDelegate : public ConfirmInfoBarDelegate {
162 // Creates an extension dev tools infobar and delegate and adds the infobar to
163 // the InfoBarService associated with |rvh|. Returns the infobar if it was
164 // successfully added.
165 static infobars::InfoBar* Create(WebContents* web_contents,
166 const std::string& client_name);
168 void set_client_host(ExtensionDevToolsClientHost* client_host) {
169 client_host_ = client_host;
173 explicit ExtensionDevToolsInfoBarDelegate(const std::string& client_name);
174 virtual ~ExtensionDevToolsInfoBarDelegate();
176 // ConfirmInfoBarDelegate:
177 virtual void InfoBarDismissed() OVERRIDE;
178 virtual Type GetInfoBarType() const OVERRIDE;
179 virtual bool ShouldExpireInternal(
180 const NavigationDetails& details) const OVERRIDE;
181 virtual base::string16 GetMessageText() const OVERRIDE;
182 virtual int GetButtons() const OVERRIDE;
183 virtual bool Cancel() OVERRIDE;
185 std::string client_name_;
186 ExtensionDevToolsClientHost* client_host_;
188 DISALLOW_COPY_AND_ASSIGN(ExtensionDevToolsInfoBarDelegate);
192 infobars::InfoBar* ExtensionDevToolsInfoBarDelegate::Create(
193 WebContents* web_contents,
194 const std::string& client_name) {
198 InfoBarService* infobar_service =
199 InfoBarService::FromWebContents(web_contents);
200 if (!infobar_service)
203 return infobar_service->AddInfoBar(ConfirmInfoBarDelegate::CreateInfoBar(
204 scoped_ptr<ConfirmInfoBarDelegate>(
205 new ExtensionDevToolsInfoBarDelegate(client_name))));
208 ExtensionDevToolsInfoBarDelegate::ExtensionDevToolsInfoBarDelegate(
209 const std::string& client_name)
210 : ConfirmInfoBarDelegate(),
211 client_name_(client_name),
215 ExtensionDevToolsInfoBarDelegate::~ExtensionDevToolsInfoBarDelegate() {
218 void ExtensionDevToolsInfoBarDelegate::InfoBarDismissed() {
220 client_host_->MarkAsDismissed();
223 infobars::InfoBarDelegate::Type
224 ExtensionDevToolsInfoBarDelegate::GetInfoBarType() const {
228 bool ExtensionDevToolsInfoBarDelegate::ShouldExpireInternal(
229 const NavigationDetails& details) const {
233 base::string16 ExtensionDevToolsInfoBarDelegate::GetMessageText() const {
234 return l10n_util::GetStringFUTF16(IDS_DEV_TOOLS_INFOBAR_LABEL,
235 base::UTF8ToUTF16(client_name_));
238 int ExtensionDevToolsInfoBarDelegate::GetButtons() const {
239 return BUTTON_CANCEL;
242 bool ExtensionDevToolsInfoBarDelegate::Cancel() {
248 // AttachedClientHosts --------------------------------------------------------
250 class AttachedClientHosts {
252 AttachedClientHosts();
253 ~AttachedClientHosts();
255 // Returns the singleton instance of this class.
256 static AttachedClientHosts* GetInstance();
258 void Add(ExtensionDevToolsClientHost* client_host);
259 void Remove(ExtensionDevToolsClientHost* client_host);
260 ExtensionDevToolsClientHost* Lookup(DevToolsAgentHost* agent_host,
261 const std::string& extension_id);
264 typedef std::set<ExtensionDevToolsClientHost*> ClientHosts;
265 ClientHosts client_hosts_;
267 DISALLOW_COPY_AND_ASSIGN(AttachedClientHosts);
270 AttachedClientHosts::AttachedClientHosts() {
273 AttachedClientHosts::~AttachedClientHosts() {
277 AttachedClientHosts* AttachedClientHosts::GetInstance() {
278 return Singleton<AttachedClientHosts>::get();
281 void AttachedClientHosts::Add(ExtensionDevToolsClientHost* client_host) {
282 client_hosts_.insert(client_host);
285 void AttachedClientHosts::Remove(ExtensionDevToolsClientHost* client_host) {
286 client_hosts_.erase(client_host);
289 ExtensionDevToolsClientHost* AttachedClientHosts::Lookup(
290 DevToolsAgentHost* agent_host,
291 const std::string& extension_id) {
292 for (ClientHosts::iterator it = client_hosts_.begin();
293 it != client_hosts_.end(); ++it) {
294 ExtensionDevToolsClientHost* client_host = *it;
295 if (client_host->agent_host() == agent_host &&
296 client_host->extension_id() == extension_id)
305 // ExtensionDevToolsClientHost ------------------------------------------------
307 ExtensionDevToolsClientHost::ExtensionDevToolsClientHost(
309 DevToolsAgentHost* agent_host,
310 const std::string& extension_id,
311 const std::string& extension_name,
312 const Debuggee& debuggee,
313 infobars::InfoBar* infobar)
315 agent_host_(agent_host),
316 extension_id_(extension_id),
319 detach_reason_(OnDetach::REASON_TARGET_CLOSED),
320 extension_registry_observer_(this) {
321 CopyDebuggee(&debuggee_, debuggee);
323 AttachedClientHosts::GetInstance()->Add(this);
325 // ExtensionRegistryObserver listen extension unloaded and detach debugger
327 extension_registry_observer_.Add(ExtensionRegistry::Get(profile_));
329 // RVH-based agents disconnect from their clients when the app is terminating
330 // but shared worker-based agents do not.
331 // Disconnect explicitly to make sure that |this| observer is not leaked.
332 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
333 content::NotificationService::AllSources());
335 // Attach to debugger and tell it we are ready.
336 agent_host_->AttachClient(this);
339 static_cast<ExtensionDevToolsInfoBarDelegate*>(
340 infobar_->delegate())->set_client_host(this);
343 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED,
344 content::Source<InfoBarService>(
345 InfoBarService::FromWebContents(agent_host_->GetWebContents())));
349 ExtensionDevToolsClientHost::~ExtensionDevToolsClientHost() {
350 // Ensure calling RemoveInfoBar() below won't result in Observe() trying to
352 registrar_.RemoveAll();
355 static_cast<ExtensionDevToolsInfoBarDelegate*>(
356 infobar_->delegate())->set_client_host(NULL);
357 InfoBarService* infobar_service =
358 InfoBarService::FromWebContents(agent_host_->GetWebContents());
359 infobar_service->RemoveInfoBar(infobar_);
361 AttachedClientHosts::GetInstance()->Remove(this);
364 // DevToolsAgentHostClient implementation.
365 void ExtensionDevToolsClientHost::AgentHostClosed(
366 DevToolsAgentHost* agent_host, bool replaced_with_another_client) {
367 DCHECK(agent_host == agent_host_.get());
368 if (replaced_with_another_client)
369 detach_reason_ = OnDetach::REASON_REPLACED_WITH_DEVTOOLS;
374 void ExtensionDevToolsClientHost::Close() {
375 agent_host_->DetachClient();
379 void ExtensionDevToolsClientHost::SendMessageToBackend(
380 DebuggerSendCommandFunction* function,
381 const std::string& method,
382 SendCommand::Params::CommandParams* command_params) {
383 base::DictionaryValue protocol_request;
384 int request_id = ++last_request_id_;
385 pending_requests_[request_id] = function;
386 protocol_request.SetInteger("id", request_id);
387 protocol_request.SetString("method", method);
388 if (command_params) {
389 protocol_request.Set("params",
390 command_params->additional_properties.DeepCopy());
393 std::string json_args;
394 base::JSONWriter::Write(&protocol_request, &json_args);
395 agent_host_->DispatchProtocolMessage(json_args);
398 void ExtensionDevToolsClientHost::MarkAsDismissed() {
399 detach_reason_ = OnDetach::REASON_CANCELED_BY_USER;
402 void ExtensionDevToolsClientHost::SendDetachedEvent() {
403 if (!EventRouter::Get(profile_))
406 scoped_ptr<base::ListValue> args(OnDetach::Create(debuggee_,
408 scoped_ptr<Event> event(new Event(OnDetach::kEventName, args.Pass()));
409 event->restrict_to_browser_context = profile_;
410 EventRouter::Get(profile_)
411 ->DispatchEventToExtension(extension_id_, event.Pass());
414 void ExtensionDevToolsClientHost::OnExtensionUnloaded(
415 content::BrowserContext* browser_context,
416 const Extension* extension,
417 UnloadedExtensionInfo::Reason reason) {
418 if (extension->id() == extension_id_)
422 void ExtensionDevToolsClientHost::Observe(
424 const content::NotificationSource& source,
425 const content::NotificationDetails& details) {
427 case chrome::NOTIFICATION_APP_TERMINATING:
430 case chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED:
431 if (content::Details<infobars::InfoBar::RemovedDetails>(details)->first ==
443 void ExtensionDevToolsClientHost::DispatchProtocolMessage(
444 DevToolsAgentHost* agent_host, const std::string& message) {
445 DCHECK(agent_host == agent_host_.get());
446 if (!EventRouter::Get(profile_))
449 scoped_ptr<base::Value> result(base::JSONReader::Read(message));
450 if (!result->IsType(base::Value::TYPE_DICTIONARY))
452 base::DictionaryValue* dictionary =
453 static_cast<base::DictionaryValue*>(result.get());
456 if (!dictionary->GetInteger("id", &id)) {
457 std::string method_name;
458 if (!dictionary->GetString("method", &method_name))
461 OnEvent::Params params;
462 base::DictionaryValue* params_value;
463 if (dictionary->GetDictionary("params", ¶ms_value))
464 params.additional_properties.Swap(params_value);
466 scoped_ptr<base::ListValue> args(
467 OnEvent::Create(debuggee_, method_name, params));
468 scoped_ptr<Event> event(new Event(OnEvent::kEventName, args.Pass()));
469 event->restrict_to_browser_context = profile_;
470 EventRouter::Get(profile_)
471 ->DispatchEventToExtension(extension_id_, event.Pass());
473 DebuggerSendCommandFunction* function = pending_requests_[id].get();
477 function->SendResponseBody(dictionary);
478 pending_requests_.erase(id);
483 // DebuggerFunction -----------------------------------------------------------
485 DebuggerFunction::DebuggerFunction()
486 : client_host_(NULL) {
489 DebuggerFunction::~DebuggerFunction() {
492 void DebuggerFunction::FormatErrorMessage(const std::string& format) {
493 if (debuggee_.tab_id)
494 error_ = ErrorUtils::FormatErrorMessage(
495 format, keys::kTabTargetType, base::IntToString(*debuggee_.tab_id));
496 else if (debuggee_.extension_id)
497 error_ = ErrorUtils::FormatErrorMessage(
498 format, keys::kBackgroundPageTargetType, *debuggee_.extension_id);
500 error_ = ErrorUtils::FormatErrorMessage(
501 format, keys::kOpaqueTargetType, *debuggee_.target_id);
504 bool DebuggerFunction::InitAgentHost() {
505 if (debuggee_.tab_id) {
506 WebContents* web_contents = NULL;
507 bool result = ExtensionTabUtil::GetTabById(*debuggee_.tab_id,
514 if (result && web_contents) {
515 // TODO(rdevlin.cronin) This should definitely be GetLastCommittedURL().
516 GURL url = web_contents->GetVisibleURL();
517 if (PermissionsData::IsRestrictedUrl(url, url, extension(), &error_))
519 agent_host_ = DevToolsAgentHost::GetOrCreateFor(web_contents);
521 } else if (debuggee_.extension_id) {
522 ExtensionHost* extension_host =
523 ExtensionSystem::Get(GetProfile())
525 ->GetBackgroundHostForExtension(*debuggee_.extension_id);
526 if (extension_host) {
527 if (PermissionsData::IsRestrictedUrl(extension_host->GetURL(),
528 extension_host->GetURL(),
534 DevToolsAgentHost::GetOrCreateFor(extension_host->host_contents());
536 } else if (debuggee_.target_id) {
537 agent_host_ = DevToolsAgentHost::GetForId(*debuggee_.target_id);
539 error_ = keys::kInvalidTargetError;
543 if (!agent_host_.get()) {
544 FormatErrorMessage(keys::kNoTargetError);
550 bool DebuggerFunction::InitClientHost() {
551 if (!InitAgentHost())
554 client_host_ = AttachedClientHosts::GetInstance()->Lookup(agent_host_.get(),
558 FormatErrorMessage(keys::kNotAttachedError);
565 // DebuggerAttachFunction -----------------------------------------------------
567 DebuggerAttachFunction::DebuggerAttachFunction() {
570 DebuggerAttachFunction::~DebuggerAttachFunction() {
573 bool DebuggerAttachFunction::RunAsync() {
574 scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
575 EXTENSION_FUNCTION_VALIDATE(params.get());
577 CopyDebuggee(&debuggee_, params->target);
578 if (!InitAgentHost())
581 if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
582 params->required_version)) {
583 error_ = ErrorUtils::FormatErrorMessage(
584 keys::kProtocolVersionNotSupportedError,
585 params->required_version);
589 if (agent_host_->IsAttached()) {
590 FormatErrorMessage(keys::kAlreadyAttachedError);
594 infobars::InfoBar* infobar = NULL;
595 if (!CommandLine::ForCurrentProcess()->
596 HasSwitch(::switches::kSilentDebuggerExtensionAPI)) {
597 // Do not attach to the target if for any reason the infobar cannot be shown
598 // for this WebContents instance.
599 infobar = ExtensionDevToolsInfoBarDelegate::Create(
600 agent_host_->GetWebContents(), extension()->name());
602 error_ = ErrorUtils::FormatErrorMessage(
603 keys::kSilentDebuggingRequired,
604 ::switches::kSilentDebuggerExtensionAPI);
609 new ExtensionDevToolsClientHost(GetProfile(),
620 // DebuggerDetachFunction -----------------------------------------------------
622 DebuggerDetachFunction::DebuggerDetachFunction() {
625 DebuggerDetachFunction::~DebuggerDetachFunction() {
628 bool DebuggerDetachFunction::RunAsync() {
629 scoped_ptr<Detach::Params> params(Detach::Params::Create(*args_));
630 EXTENSION_FUNCTION_VALIDATE(params.get());
632 CopyDebuggee(&debuggee_, params->target);
633 if (!InitClientHost())
636 client_host_->Close();
642 // DebuggerSendCommandFunction ------------------------------------------------
644 DebuggerSendCommandFunction::DebuggerSendCommandFunction() {
647 DebuggerSendCommandFunction::~DebuggerSendCommandFunction() {
650 bool DebuggerSendCommandFunction::RunAsync() {
651 scoped_ptr<SendCommand::Params> params(SendCommand::Params::Create(*args_));
652 EXTENSION_FUNCTION_VALIDATE(params.get());
654 CopyDebuggee(&debuggee_, params->target);
655 if (!InitClientHost())
658 client_host_->SendMessageToBackend(this, params->method,
659 params->command_params.get());
663 void DebuggerSendCommandFunction::SendResponseBody(
664 base::DictionaryValue* response) {
665 base::Value* error_body;
666 if (response->Get("error", &error_body)) {
667 base::JSONWriter::Write(error_body, &error_);
672 base::DictionaryValue* result_body;
673 SendCommand::Results::Result result;
674 if (response->GetDictionary("result", &result_body))
675 result.additional_properties.Swap(result_body);
677 results_ = SendCommand::Results::Create(result);
682 // DebuggerGetTargetsFunction -------------------------------------------------
686 const char kTargetIdField[] = "id";
687 const char kTargetTypeField[] = "type";
688 const char kTargetTitleField[] = "title";
689 const char kTargetAttachedField[] = "attached";
690 const char kTargetUrlField[] = "url";
691 const char kTargetFaviconUrlField[] = "faviconUrl";
692 const char kTargetTypePage[] = "page";
693 const char kTargetTypeBackgroundPage[] = "background_page";
694 const char kTargetTypeWorker[] = "worker";
695 const char kTargetTypeOther[] = "other";
696 const char kTargetTabIdField[] = "tabId";
697 const char kTargetExtensionIdField[] = "extensionId";
699 base::Value* SerializeTarget(const DevToolsTargetImpl& target) {
700 base::DictionaryValue* dictionary = new base::DictionaryValue();
702 dictionary->SetString(kTargetIdField, target.GetId());
703 dictionary->SetString(kTargetTitleField, target.GetTitle());
704 dictionary->SetBoolean(kTargetAttachedField, target.IsAttached());
705 dictionary->SetString(kTargetUrlField, target.GetURL().spec());
707 std::string type = target.GetType();
708 if (type == kTargetTypePage) {
709 dictionary->SetInteger(kTargetTabIdField, target.GetTabId());
710 } else if (type == kTargetTypeBackgroundPage) {
711 dictionary->SetString(kTargetExtensionIdField, target.GetExtensionId());
712 } else if (type != kTargetTypeWorker) {
713 // DevToolsTargetImpl may support more types than the debugger API.
714 type = kTargetTypeOther;
716 dictionary->SetString(kTargetTypeField, type);
718 GURL favicon_url = target.GetFaviconURL();
719 if (favicon_url.is_valid())
720 dictionary->SetString(kTargetFaviconUrlField, favicon_url.spec());
727 DebuggerGetTargetsFunction::DebuggerGetTargetsFunction() {
730 DebuggerGetTargetsFunction::~DebuggerGetTargetsFunction() {
733 bool DebuggerGetTargetsFunction::RunAsync() {
734 DevToolsTargetImpl::EnumerateAllTargets(
735 base::Bind(&DebuggerGetTargetsFunction::SendTargetList, this));
739 void DebuggerGetTargetsFunction::SendTargetList(
740 const std::vector<DevToolsTargetImpl*>& target_list) {
741 scoped_ptr<base::ListValue> result(new base::ListValue());
742 for (size_t i = 0; i < target_list.size(); ++i)
743 result->Append(SerializeTarget(*target_list[i]));
744 STLDeleteContainerPointers(target_list.begin(), target_list.end());
745 SetResult(result.release());
749 } // namespace extensions