File: remote_debugging_server.cc

package info (click to toggle)
chromium 140.0.7339.80-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,193,064 kB
  • sloc: cpp: 35,092,386; ansic: 7,161,671; javascript: 4,199,703; python: 1,441,797; asm: 949,904; xml: 747,409; pascal: 187,748; perl: 88,691; sh: 88,248; objc: 79,953; sql: 52,714; cs: 44,599; fortran: 24,137; makefile: 22,114; tcl: 15,277; php: 13,980; yacc: 9,000; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (248 lines) | stat: -rw-r--r-- 9,320 bytes parent folder | download | duplicates (4)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/devtools/remote_debugging_server.h"

#include <memory>
#include <optional>
#include <utility>

#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/types/expected.h"
#include "build/branding_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/devtools/features.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.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 "net/base/filename_util.h"
#include "net/base/net_errors.h"
#include "net/log/net_log_source.h"
#include "net/socket/tcp_server_socket.h"
#include "third_party/abseil-cpp/absl/cleanup/cleanup.h"
#include "third_party/blink/public/public_buildflags.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

bool g_tethering_enabled = false;

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
bool g_enable_default_user_data_dir_check_for_chromium_branding_for_testing =
    false;
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)

const uint16_t kMinTetheringPort = 9333;
const uint16_t kMaxTetheringPort = 9444;
const int kBackLog = 10;

// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class DevToolsDebuggingUserDataDirStatus {
  kNotBeingDebugged = 0,
  kDebuggingRequestedWithNonDefaultUserDataDir = 1,
  kDebuggingRequestedWithDefaultUserDataDir = 2,
  kDebuggingRequestedErrorObtainingUserDataDir = 3,

  // New values go above here.
  kMaxValue = kDebuggingRequestedErrorObtainingUserDataDir,
};

class TCPServerSocketFactory
    : public content::DevToolsSocketFactory {
 public:
  explicit TCPServerSocketFactory(uint16_t port)
      : port_(port), last_tethering_port_(kMinTetheringPort) {}

  TCPServerSocketFactory(const TCPServerSocketFactory&) = delete;
  TCPServerSocketFactory& operator=(const TCPServerSocketFactory&) = delete;

 private:
  std::unique_ptr<net::ServerSocket> CreateLocalHostServerSocket(int port) {
    std::unique_ptr<net::ServerSocket> socket(
        new net::TCPServerSocket(nullptr, net::NetLogSource()));
    if (socket->ListenWithAddressAndPort(
            "127.0.0.1", port, kBackLog) == net::OK)
      return socket;
    if (socket->ListenWithAddressAndPort("::1", port, kBackLog) == net::OK)
      return socket;
    return nullptr;
  }

  // content::DevToolsSocketFactory.
  std::unique_ptr<net::ServerSocket> CreateForHttpServer() override {
    return CreateLocalHostServerSocket(port_);
  }

  std::unique_ptr<net::ServerSocket> CreateForTethering(
      std::string* name) override {
    if (!g_tethering_enabled) {
      return nullptr;
    }

    if (last_tethering_port_ == kMaxTetheringPort)
      last_tethering_port_ = kMinTetheringPort;
    uint16_t port = ++last_tethering_port_;
    *name = base::NumberToString(port);
    return CreateLocalHostServerSocket(port);
  }

  uint16_t port_;
  uint16_t last_tethering_port_;
};

// Returns true, or a reason why remote debugging is not allowed.
base::expected<bool, RemoteDebuggingServer::NotStartedReason>
IsRemoteDebuggingAllowed(const std::optional<bool>& is_default_user_data_dir,
                         PrefService* local_state) {
  if (!local_state->GetBoolean(prefs::kDevToolsRemoteDebuggingAllowed)) {
    return base::unexpected(
        RemoteDebuggingServer::NotStartedReason::kDisabledByPolicy);
  }
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
  constexpr bool default_user_data_dir_check_enabled = true;
#else
  const bool default_user_data_dir_check_enabled =
      g_enable_default_user_data_dir_check_for_chromium_branding_for_testing;
#endif

  if (default_user_data_dir_check_enabled &&
      is_default_user_data_dir.value_or(true)) {
    return base::unexpected(
        RemoteDebuggingServer::NotStartedReason::kDisabledByDefaultUserDataDir);
  }
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
  return true;
}

}  // namespace

RemoteDebuggingServer::RemoteDebuggingServer() = default;

// static
void RemoteDebuggingServer::EnableTetheringForDebug() {
  g_tethering_enabled = true;
}

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
// static
void RemoteDebuggingServer::EnableDefaultUserDataDirCheckForTesting() {
  g_enable_default_user_data_dir_check_for_chromium_branding_for_testing = true;
}
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)

// static
base::expected<std::unique_ptr<RemoteDebuggingServer>,
               RemoteDebuggingServer::NotStartedReason>
RemoteDebuggingServer::GetInstance(PrefService* local_state) {
  if (!local_state->GetBoolean(prefs::kDevToolsRemoteDebuggingAllowed)) {
    return base::unexpected(NotStartedReason::kDisabledByPolicy);
  }

  const base::CommandLine& command_line =
      *base::CommandLine::ForCurrentProcess();

  // Track whether debugging was requested. This determines the metric reported
  // on function exit.
  bool wanted_debugging = false;
  // Track whether debugging was started. This determines whether or not to
  // return an instance of the class.
  bool being_debugged = false;
  std::optional<bool> is_default_user_data_dir =
      chrome::IsUsingDefaultDataDirectory();

  absl::Cleanup record_histogram = [&wanted_debugging,
                                    &is_default_user_data_dir] {
    DevToolsDebuggingUserDataDirStatus status =
        DevToolsDebuggingUserDataDirStatus::kNotBeingDebugged;
    if (wanted_debugging) {
      status = DevToolsDebuggingUserDataDirStatus::
          kDebuggingRequestedErrorObtainingUserDataDir;
      if (is_default_user_data_dir.has_value()) {
        status = is_default_user_data_dir.value()
                     ? DevToolsDebuggingUserDataDirStatus::
                           kDebuggingRequestedWithDefaultUserDataDir
                     : DevToolsDebuggingUserDataDirStatus::
                           kDebuggingRequestedWithNonDefaultUserDataDir;
      }
    }
    base::UmaHistogramEnumeration("DevTools.DevToolsDebuggingUserDataDirStatus",
                                  status);
  };

  if (command_line.HasSwitch(switches::kRemoteDebuggingPipe)) {
    wanted_debugging = true;
    if (const auto maybe_allow_debugging =
            IsRemoteDebuggingAllowed(is_default_user_data_dir, local_state);
        !maybe_allow_debugging.has_value()) {
      return base::unexpected(maybe_allow_debugging.error());
    }
    being_debugged = true;
    content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler(
        base::BindOnce(&ChromeDevToolsManagerDelegate::CloseBrowserSoon));
  }

  std::string port_str =
      command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
  int port;
  if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
    base::FilePath output_dir;
    if (!port) {
      // The client requested an ephemeral port. Must write the selected
      // port to a well-known location in the profile directory to
      // bootstrap the connection process.
      bool result = base::PathService::Get(chrome::DIR_USER_DATA, &output_dir);
      DCHECK(result);
    }

    base::FilePath debug_frontend_dir;
    if (command_line.HasSwitch(::switches::kCustomDevtoolsFrontend)) {
      GURL custom_devtools_frontend_url(command_line.GetSwitchValueASCII(
          ::switches::kCustomDevtoolsFrontend));
      if (custom_devtools_frontend_url.SchemeIsFile()) {
        net::FileURLToFilePath(custom_devtools_frontend_url,
                               &debug_frontend_dir);
      }
    }
    wanted_debugging = true;
    if (const auto maybe_allow_debugging =
            IsRemoteDebuggingAllowed(is_default_user_data_dir, local_state);
        !maybe_allow_debugging.has_value()) {
      return base::unexpected(maybe_allow_debugging.error());
    }
    being_debugged = true;
    content::DevToolsAgentHost::StartRemoteDebuggingServer(
        std::make_unique<TCPServerSocketFactory>(port), output_dir,
        debug_frontend_dir);
  }

  if (being_debugged) {
    return base::WrapUnique(new RemoteDebuggingServer);
  }

  return base::unexpected(NotStartedReason::kNotRequested);
}

RemoteDebuggingServer::~RemoteDebuggingServer() {
  // Ensure Profile is alive, because the whole DevTools subsystem
  // accesses it during shutdown.
  DCHECK(g_browser_process->profile_manager());
  content::DevToolsAgentHost::StopRemoteDebuggingServer();
  content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler();
}