1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/devtools/remote_debugging_server.h"
7 #include "base/lazy_instance.h"
8 #include "base/path_service.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "chrome/browser/devtools/browser_list_tabcontents_provider.h"
11 #include "chrome/common/chrome_paths.h"
12 #include "content/public/browser/devtools_http_handler.h"
13 #include "net/base/net_errors.h"
14 #include "net/socket/tcp_server_socket.h"
18 base::LazyInstance
<bool>::Leaky g_tethering_enabled
= LAZY_INSTANCE_INITIALIZER
;
20 const uint16 kMinTetheringPort
= 9333;
21 const uint16 kMaxTetheringPort
= 9444;
22 const int kBackLog
= 10;
24 class TCPServerSocketFactory
25 : public content::DevToolsHttpHandler::ServerSocketFactory
{
27 TCPServerSocketFactory(const std::string
& address
, uint16 port
)
30 last_tethering_port_(kMinTetheringPort
) {
34 // content::DevToolsHttpHandler::ServerSocketFactory.
35 scoped_ptr
<net::ServerSocket
> CreateForHttpServer() override
{
36 scoped_ptr
<net::ServerSocket
> socket(
37 new net::TCPServerSocket(nullptr, net::NetLog::Source()));
38 if (socket
->ListenWithAddressAndPort(address_
, port_
, kBackLog
) != net::OK
)
39 return scoped_ptr
<net::ServerSocket
>();
44 scoped_ptr
<net::ServerSocket
> CreateForTethering(std::string
* name
) override
{
45 if (!g_tethering_enabled
.Get())
46 return scoped_ptr
<net::ServerSocket
>();
48 if (last_tethering_port_
== kMaxTetheringPort
)
49 last_tethering_port_
= kMinTetheringPort
;
50 uint16 port
= ++last_tethering_port_
;
51 *name
= base::IntToString(port
);
52 scoped_ptr
<net::TCPServerSocket
> socket(
53 new net::TCPServerSocket(nullptr, net::NetLog::Source()));
54 if (socket
->ListenWithAddressAndPort("127.0.0.1", port
, kBackLog
) !=
56 return scoped_ptr
<net::ServerSocket
>();
63 uint16 last_tethering_port_
;
65 DISALLOW_COPY_AND_ASSIGN(TCPServerSocketFactory
);
71 void RemoteDebuggingServer::EnableTetheringForDebug() {
72 g_tethering_enabled
.Get() = true;
75 RemoteDebuggingServer::RemoteDebuggingServer(
76 chrome::HostDesktopType host_desktop_type
,
77 const std::string
& ip
,
79 base::FilePath output_dir
;
81 // The client requested an ephemeral port. Must write the selected
82 // port to a well-known location in the profile directory to
83 // bootstrap the connection process.
84 bool result
= PathService::Get(chrome::DIR_USER_DATA
, &output_dir
);
88 devtools_http_handler_
.reset(content::DevToolsHttpHandler::Start(
89 make_scoped_ptr(new TCPServerSocketFactory(ip
, port
)),
91 new BrowserListTabContentsProvider(host_desktop_type
),
95 RemoteDebuggingServer::~RemoteDebuggingServer() {