1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
fuchsia_web / webengine / browser / web_engine_devtools_controller.cc [blame]
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fuchsia_web/webengine/browser/web_engine_devtools_controller.h"
#include <fuchsia/web/cpp/fidl.h>
#include <lib/fidl/cpp/interface_ptr_set.h>
#include <lib/sys/cpp/component_context.h>
#include <optional>
#include <vector>
#include "base/command_line.h"
#include "base/containers/flat_set.h"
#include "base/fuchsia/process_context.h"
#include "base/fuchsia/scoped_service_binding.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_tokenizer.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_socket_factory.h"
#include "content/public/common/content_switches.h"
#include "fuchsia_web/webengine/switches.h"
#include "net/base/net_errors.h"
#include "net/base/port_util.h"
#include "net/socket/tcp_server_socket.h"
namespace {
using OnDevToolsPortChanged = base::OnceCallback<void(uint16_t)>;
class DevToolsSocketFactory : public content::DevToolsSocketFactory {
public:
DevToolsSocketFactory(OnDevToolsPortChanged on_devtools_port,
net::IPEndPoint ip_end_point)
: on_devtools_port_(std::move(on_devtools_port)),
ip_end_point_(std::move(ip_end_point)) {}
~DevToolsSocketFactory() override = default;
DevToolsSocketFactory(const DevToolsSocketFactory&) = delete;
DevToolsSocketFactory& operator=(const DevToolsSocketFactory&) = delete;
// content::DevToolsSocketFactory implementation.
std::unique_ptr<net::ServerSocket> CreateForHttpServer() override {
const int kTcpListenBackLog = 5;
auto socket =
std::make_unique<net::TCPServerSocket>(nullptr, net::NetLogSource());
int error = socket->Listen(ip_end_point_, kTcpListenBackLog,
/*ipv6_only=*/std::nullopt);
if (error != net::OK) {
LOG(WARNING) << "Failed to start the HTTP debugger service. "
<< net::ErrorToString(error);
std::move(on_devtools_port_).Run(0);
return nullptr;
}
net::IPEndPoint end_point;
socket->GetLocalAddress(&end_point);
std::move(on_devtools_port_).Run(end_point.port());
return socket;
}
std::unique_ptr<net::ServerSocket> CreateForTethering(
std::string* out_name) override {
return nullptr;
}
private:
OnDevToolsPortChanged on_devtools_port_;
net::IPEndPoint ip_end_point_;
};
void StartRemoteDebuggingServer(OnDevToolsPortChanged on_devtools_port,
net::IPEndPoint ip_end_point) {
const base::FilePath kDisableActivePortOutputDirectory{};
const base::FilePath kDisableDebugOutput{};
content::DevToolsAgentHost::StartRemoteDebuggingServer(
std::make_unique<DevToolsSocketFactory>(std::move(on_devtools_port),
ip_end_point),
kDisableActivePortOutputDirectory, kDisableDebugOutput);
}
class NoopController : public WebEngineDevToolsController {
public:
NoopController() = default;
~NoopController() override = default;
NoopController(const NoopController&) = delete;
NoopController& operator=(const NoopController&) = delete;
// WebEngineDevToolsController implementation:
bool OnFrameCreated(content::WebContents* contents,
bool user_debugging) override {
return !user_debugging;
}
void OnFrameLoaded(content::WebContents* contents) override {}
void OnFrameDestroyed(content::WebContents* contents) override {}
content::DevToolsAgentHost::List RemoteDebuggingTargets() override {
return {};
}
void GetDevToolsPort(base::OnceCallback<void(uint16_t)> callback) override {
std::move(callback).Run(0);
}
};
// "User-mode" makes DevTools accessible to remote devices for Frames specified
// by the web_instance owner. The controller, which starts DevTools when the
// first Frame is created, and shuts it down when no debuggable Frames remain.
class UserModeController : public WebEngineDevToolsController {
public:
explicit UserModeController(uint16_t server_port)
: ip_endpoint_(net::IPAddress::IPv6AllZeros(), server_port) {}
~UserModeController() override {
if (is_remote_debugging_started_) {
content::DevToolsAgentHost::StopRemoteDebuggingServer();
}
}
UserModeController(const UserModeController&) = delete;
UserModeController& operator=(const UserModeController&) = delete;
// WebEngineDevToolsController implementation:
bool OnFrameCreated(content::WebContents* contents,
bool user_debugging) override {
if (user_debugging) {
debuggable_contents_.insert(contents);
UpdateRemoteDebuggingServer();
}
return true;
}
void OnFrameLoaded(content::WebContents* contents) override {}
void OnFrameDestroyed(content::WebContents* contents) override {
debuggable_contents_.erase(contents);
UpdateRemoteDebuggingServer();
}
content::DevToolsAgentHost::List RemoteDebuggingTargets() override {
DCHECK(is_remote_debugging_started_);
content::DevToolsAgentHost::List enabled_hosts;
for (content::WebContents* contents : debuggable_contents_) {
enabled_hosts.push_back(
content::DevToolsAgentHost::GetOrCreateFor(contents));
}
return enabled_hosts;
}
void GetDevToolsPort(base::OnceCallback<void(uint16_t)> callback) override {
get_port_callbacks_.emplace_back(std::move(callback));
MaybeNotifyGetPortCallbacks();
}
private:
// Starts or stops the remote debugging server, if necessary
void UpdateRemoteDebuggingServer() {
bool need_remote_debugging = !debuggable_contents_.empty();
if (need_remote_debugging == is_remote_debugging_started_)
return;
is_remote_debugging_started_ = need_remote_debugging;
if (need_remote_debugging) {
StartRemoteDebuggingServer(
base::BindOnce(&UserModeController::OnDevToolsPortChanged,
base::Unretained(this)),
ip_endpoint_);
} else {
content::DevToolsAgentHost::StopRemoteDebuggingServer();
devtools_port_.reset();
}
}
void OnDevToolsPortChanged(uint16_t port) {
devtools_port_ = port;
MaybeNotifyGetPortCallbacks();
}
void MaybeNotifyGetPortCallbacks() {
if (!devtools_port_.has_value())
return;
for (auto& callback : get_port_callbacks_)
std::move(callback).Run(devtools_port_.value());
get_port_callbacks_.clear();
}
const net::IPEndPoint ip_endpoint_;
// True if the remote debugging server is started.
bool is_remote_debugging_started_ = false;
// Currently active DevTools port. Set to 0 on service startup error.
std::optional<uint16_t> devtools_port_;
// Set of Frames' content::WebContents which are remotely debuggable.
base::flat_set<content::WebContents*> debuggable_contents_;
std::vector<base::OnceCallback<void(uint16_t)>> get_port_callbacks_;
};
// "Debug-mode" is used for on-device testing, and makes all Frames available
// for debugging by clients on the same device. DevTools is only reported when
// the first Frame finishes loading its main document, so that the
// DevToolsPerContextListeners can start interacting with it immediately.
class DebugModeController : public WebEngineDevToolsController,
public fuchsia::web::Debug {
public:
DebugModeController()
: DebugModeController(
net::IPEndPoint(net::IPAddress::IPv4Localhost(), 0)) {}
~DebugModeController() override {
content::DevToolsAgentHost::StopRemoteDebuggingServer();
}
DebugModeController(const DebugModeController&) = delete;
DebugModeController& operator=(const DebugModeController&) = delete;
// DevToolsController implementation:
bool OnFrameCreated(content::WebContents* contents,
bool user_debugging) override {
return !user_debugging;
}
void OnFrameLoaded(content::WebContents* contents) override {
if (!frame_loaded_) {
frame_loaded_ = true;
MaybeSendRemoteDebuggingCallbacks();
}
}
void OnFrameDestroyed(content::WebContents* contents) override {}
content::DevToolsAgentHost::List RemoteDebuggingTargets() override {
return content::DevToolsAgentHost::GetOrCreateAll();
}
void GetDevToolsPort(base::OnceCallback<void(uint16_t)> callback) override {
std::move(callback).Run(0);
}
protected:
explicit DebugModeController(net::IPEndPoint ip_endpoint)
: ip_endpoint_(std::move(ip_endpoint)),
binding_(base::ComponentContextForProcess()->outgoing().get(), this) {
// Immediately start the service.
StartRemoteDebuggingServer(
base::BindOnce(&DebugModeController::OnDevToolsPortChanged,
base::Unretained(this)),
ip_endpoint_);
}
virtual void OnDevToolsPortChanged(uint16_t port) {
devtools_port_ = port;
MaybeSendRemoteDebuggingCallbacks();
}
// Currently active DevTools port. Set to 0 on service startup error.
std::optional<uint16_t> devtools_port_;
private:
// fuchsia::web::Debug implementation.
void EnableDevTools(
fidl::InterfaceHandle<fuchsia::web::DevToolsListener> listener_handle,
EnableDevToolsCallback callback) override {
// Each web-instance has a single DevTools "context", so create a new
// per-context channel, and pass it to |listener| immediately.
fuchsia::web::DevToolsPerContextListenerPtr context_listener;
auto listener = listener_handle.Bind();
listener->OnContextDevToolsAvailable(context_listener.NewRequest());
// Notify the per-context listener immediately, if the port is ready.
if (frame_loaded_ && devtools_port_)
context_listener->OnHttpPortOpen(devtools_port_.value());
devtools_listeners_.AddInterfacePtr(std::move(context_listener));
}
void MaybeSendRemoteDebuggingCallbacks() {
if (!frame_loaded_ || !devtools_port_)
return;
// If |devtools_port_| is zero then DevTools failed to initialize, and
// all listener connections should be closed to indicate failure.
if (devtools_port_.value() == 0) {
devtools_listeners_.CloseAll();
return;
}
for (const auto& listener : devtools_listeners_.ptrs()) {
listener->get()->OnHttpPortOpen(devtools_port_.value());
}
}
const net::IPEndPoint ip_endpoint_;
bool frame_loaded_ = false;
fidl::InterfacePtrSet<fuchsia::web::DevToolsPerContextListener>
devtools_listeners_;
const base::ScopedServiceBinding<fuchsia::web::Debug> binding_;
};
// "Mixed-mode" is used when both user and debug remote debugging are active at
// the same time. The service is enabled for the lifespan of the web_instance.
class MixedModeController : public DebugModeController {
public:
explicit MixedModeController(uint16_t server_port)
: DebugModeController(
net::IPEndPoint(net::IPAddress::IPv6AllZeros(), server_port)) {}
~MixedModeController() override = default;
// WebEngineDevToolsController overrides:
bool OnFrameCreated(content::WebContents* contents,
bool user_debugging) override {
return true;
}
void GetDevToolsPort(base::OnceCallback<void(uint16_t)> callback) override {
get_port_callbacks_.emplace_back(std::move(callback));
MaybeNotifyGetPortCallbacks();
}
// DebugModeController overrides:
void OnDevToolsPortChanged(uint16_t port) override {
DebugModeController::OnDevToolsPortChanged(port);
MaybeNotifyGetPortCallbacks();
}
void MaybeNotifyGetPortCallbacks() {
if (!devtools_port_)
return;
for (auto& callback : get_port_callbacks_)
std::move(callback).Run(devtools_port_.value());
get_port_callbacks_.clear();
}
std::vector<base::OnceCallback<void(uint16_t)>> get_port_callbacks_;
};
} // namespace
// static
std::unique_ptr<WebEngineDevToolsController>
WebEngineDevToolsController::CreateFromCommandLine(
const base::CommandLine& command_line) {
std::optional<uint16_t> devtools_port;
if (command_line.HasSwitch(switches::kRemoteDebuggingPort)) {
// Set up DevTools to listen on all network routes on the command-line
// provided port.
std::string command_line_port_value =
command_line.GetSwitchValueASCII(switches::kRemoteDebuggingPort);
int parsed_port = 0;
// The command-line option can only be provided by the ContextProvider
// process, it should not fail to parse to an int.
bool parsed = base::StringToInt(command_line_port_value, &parsed_port);
DCHECK(parsed);
if (parsed_port != 0 &&
(!net::IsPortValid(parsed_port) || net::IsWellKnownPort(parsed_port))) {
LOG(WARNING) << "Invalid HTTP debugger service port number "
<< command_line_port_value;
} else {
devtools_port = parsed_port;
}
}
bool enable_debug_mode =
command_line.HasSwitch(switches::kEnableRemoteDebugMode);
if (devtools_port) {
if (enable_debug_mode) {
return std::make_unique<MixedModeController>(devtools_port.value());
} else {
return std::make_unique<UserModeController>(devtools_port.value());
}
} else if (enable_debug_mode) {
return std::make_unique<DebugModeController>();
} else {
return std::make_unique<NoopController>();
}
}