File: http_server.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (288 lines) | stat: -rw-r--r-- 10,413 bytes parent folder | download | duplicates (6)
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif

#include "chrome/test/chromedriver/server/http_server.h"

#include "base/strings/string_util.h"
#include "base/task/single_thread_task_runner.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/network_interfaces.h"
#include "net/base/sys_addrinfo.h"
#include "url/gurl.h"

namespace {

// Maximum message size between app and ChromeDriver. Data larger than 150 MB
// or so can cause crashes in Chrome (https://crbug.com/890854), so there is no
// need to support messages that are too large.
const int kBufferSize = 256 * 1024 * 1024;  // 256 MB
const char kAnyHostPattern[] = "*";

int ListenOnIPv4(net::ServerSocket* socket, uint16_t port, bool allow_remote) {
  std::string binding_ip = net::IPAddress::IPv4Localhost().ToString();
  if (allow_remote)
    binding_ip = net::IPAddress::IPv4AllZeros().ToString();
  return socket->ListenWithAddressAndPort(binding_ip, port, 5);
}

int ListenOnIPv6(net::ServerSocket* socket, uint16_t port, bool allow_remote) {
  std::string binding_ip = net::IPAddress::IPv6Localhost().ToString();
  if (allow_remote)
    binding_ip = net::IPAddress::IPv6AllZeros().ToString();
  return socket->ListenWithAddressAndPort(binding_ip, port, 5);
}

// Heuristic to check if hostname is fully qualified
bool IsSimple(const std::string& hostname) {
  return hostname.find('.') == std::string::npos;
}

bool IsMatch(const std::string& system_host, const std::string& hostname) {
  return hostname == system_host ||
         (base::StartsWith(system_host, hostname) && IsSimple(hostname) &&
          system_host[hostname.size()] == '.');
}

void GetCanonicalHostName(std::vector<std::string>* canonical_host_names) {
  struct addrinfo hints, *info = nullptr, *p;
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_CANONNAME;

  auto hostname = net::GetHostName();
  int gai_result;
  if ((gai_result = getaddrinfo(hostname.c_str(), "http", &hints, &info)) !=
      0) {
    LOG(ERROR) << "GetCanonicalHostName Error hostname: " << hostname;
  }
  for (p = info; p != nullptr; p = p->ai_next) {
    if (p->ai_canonname != hostname)
      canonical_host_names->emplace_back(p->ai_canonname);
  }

  if (canonical_host_names->empty())
    canonical_host_names->emplace_back(hostname);

  freeaddrinfo(info);
  return;
}

bool HostIsSafeToServe(GURL host_url,
                       std::string host_header_value,
                       const std::vector<net::IPAddress>& whitelisted_ips,
                       const std::vector<std::string>& allowed_origins) {
  auto host = host_url.host();
  // Check if the origin is in the allowed origins.
  for (const std::string& allowed_origin : allowed_origins) {
    if (allowed_origin == kAnyHostPattern) {
      // Allow any host origin in case of `allowed-origins` contains `*`.
      return true;
    }
    if (allowed_origin == host) {
      // Allow host from `allowed-origins`.
      return true;
    }
  }

  net::IPAddress host_address = net::IPAddress();
  if (ParseURLHostnameToAddress(host, &host_address)) {
    net::NetworkInterfaceList list;
    if (net::GetNetworkList(&list,
                            net::INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES)) {
      for (const auto& network_interface : list) {
        if (network_interface.address == host_address) {
          return true;
        }
      }

      LOG(ERROR) << "Rejecting request with host: " << host_header_value
                 << " address: " << host_address.ToString();
      return false;
    }
    return true;
  }

  static std::vector<std::string> canonical_host_names;
  GetCanonicalHostName(&canonical_host_names);
  for (const auto& system_host : canonical_host_names) {
    if (IsMatch(system_host, host)) {
      return true;
    }
  }

  LOG(ERROR) << "Unable find match for host: " << host_header_value;
  return false;
}

bool RequestIsSafeToServe(const net::HttpServerRequestInfo& info,
                          bool allow_remote,
                          const std::vector<net::IPAddress>& whitelisted_ips,
                          const std::vector<std::string>& allowed_origins) {
  std::string origin_header_value = info.GetHeaderValue("origin");
  std::string host_header_value = info.GetHeaderValue("host");
  bool is_origin_set = !origin_header_value.empty();
  GURL origin_url(origin_header_value);
  bool is_origin_local = is_origin_set && net::IsLocalhost(origin_url);
  bool is_host_set = !host_header_value.empty();
  GURL host_url("http://" + host_header_value);
  bool is_host_local = is_host_set && net::IsLocalhost(host_url);

  // If origin is localhost, then host needs to be localhost as well.
  if (is_origin_local && !is_host_local) {
    LOG(ERROR) << "Rejecting request with localhost origin but host: "
               << host_header_value;
    return false;
  }

  if (!allow_remote) {
    // If remote is not allowed, both origin and host header need to be
    // localhost or not specified.
    if (is_origin_set && !is_origin_local) {
      LOG(ERROR) << "Rejecting request with non-local origin: "
                 << origin_header_value;
      return false;
    }

    if (is_host_set && !is_host_local) {
      LOG(ERROR) << "Rejecting request with non-local host: "
                 << host_header_value;
      return false;
    }
  } else {
    if (is_origin_set && !is_origin_local) {
      // Check against allowed list where empty allowed list is special case to
      // allow all. Disallow any other non-local origin.
      bool allow_all = whitelisted_ips.empty();
      if (!allow_all) {
        LOG(ERROR) << "Rejecting request with origin set: "
                   << origin_header_value;
        return false;
      }
    }

    if (is_host_set && !is_host_local) {
      return HostIsSafeToServe(host_url, host_header_value, whitelisted_ips,
                               allowed_origins);
    }
  }

  return true;
}

}  // namespace

HttpServer::HttpServer(const std::string& url_base,
                       const std::vector<net::IPAddress>& whitelisted_ips,
                       const std::vector<std::string>& allowed_origins,
                       const HttpRequestHandlerFunc& handle_request_func,
                       base::WeakPtr<HttpHandler> handler,
                       scoped_refptr<base::SingleThreadTaskRunner> cmd_runner)
    : url_base_(url_base),
      handle_request_func_(handle_request_func),
      allow_remote_(false),
      whitelisted_ips_(whitelisted_ips),
      allowed_origins_(allowed_origins),
      handler_(handler),
      cmd_runner_(cmd_runner) {}

int HttpServer::Start(uint16_t port, bool allow_remote, bool use_ipv4) {
  allow_remote_ = allow_remote;
  std::unique_ptr<net::ServerSocket> server_socket(
      new net::TCPServerSocket(nullptr, net::NetLogSource()));
  int status = use_ipv4 ? ListenOnIPv4(server_socket.get(), port, allow_remote)
                        : ListenOnIPv6(server_socket.get(), port, allow_remote);

  if (status != net::OK) {
    VLOG(0) << "listen on " << (use_ipv4 ? "IPv4" : "IPv6")
            << " failed with error " << net::ErrorToShortString(status);
    return status;
  }
  server_ = std::make_unique<net::HttpServer>(std::move(server_socket), this);
  return server_->GetLocalAddress(&local_address_);
}

const net::IPEndPoint& HttpServer::LocalAddress() const {
  return local_address_;
}

void HttpServer::OnConnect(int connection_id) {
  server_->SetSendBufferSize(connection_id, kBufferSize);
  server_->SetReceiveBufferSize(connection_id, kBufferSize);
}

void HttpServer::OnHttpRequest(int connection_id,
                               const net::HttpServerRequestInfo& info) {
  if (!RequestIsSafeToServe(info, allow_remote_, whitelisted_ips_,
                            allowed_origins_)) {
    server_->Send500(connection_id,
                     "Host header or origin header is specified and is not "
                     "whitelisted or localhost.",
                     TRAFFIC_ANNOTATION_FOR_TESTS);
    return;
  }
  handle_request_func_.Run(
      info, base::BindRepeating(&HttpServer::OnResponse,
                                weak_factory_.GetWeakPtr(), connection_id,
                                !info.HasHeaderValue("connection", "close")));
}

HttpServer::~HttpServer() = default;

void HttpServer::OnWebSocketRequest(int connection_id,
                                    const net::HttpServerRequestInfo& info) {
  cmd_runner_->PostTask(
      FROM_HERE, base::BindOnce(&HttpHandler::OnWebSocketRequest, handler_,
                                this, connection_id, info));
}

void HttpServer::OnWebSocketMessage(int connection_id, std::string data) {
  cmd_runner_->PostTask(
      FROM_HERE, base::BindOnce(&HttpHandler::OnWebSocketMessage, handler_,
                                this, connection_id, data));
}

void HttpServer::OnClose(int connection_id) {
  cmd_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&HttpHandler::OnClose, handler_, this, connection_id));
}

void HttpServer::Close(int connection_id) {
  server_->Close(connection_id);
}

void HttpServer::SendOverWebSocket(int connection_id, const std::string& data) {
  server_->SendOverWebSocket(connection_id, data, TRAFFIC_ANNOTATION_FOR_TESTS);
}

void HttpServer::AcceptWebSocket(int connection_id,
                                 const net::HttpServerRequestInfo& request) {
  server_->AcceptWebSocket(connection_id, request,
                           TRAFFIC_ANNOTATION_FOR_TESTS);
}

void HttpServer::SendResponse(
    int connection_id,
    const net::HttpServerResponseInfo& response,
    const net::NetworkTrafficAnnotationTag& traffic_annotation) {
  server_->SendResponse(connection_id, response, traffic_annotation);
}

void HttpServer::OnResponse(
    int connection_id,
    bool keep_alive,
    std::unique_ptr<net::HttpServerResponseInfo> response) {
  if (!keep_alive)
    response->AddHeader("Connection", "close");
  server_->SendResponse(connection_id, *response, TRAFFIC_ANNOTATION_FOR_TESTS);
  // Don't need to call server_->Close(), since SendResponse() will handle
  // this for us.
}