File: websocket_factory.cc

package info (click to toggle)
chromium 145.0.7632.159-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 5,976,224 kB
  • sloc: cpp: 36,198,469; ansic: 7,634,080; javascript: 3,564,060; python: 1,649,622; xml: 838,470; asm: 717,087; pascal: 185,708; sh: 88,786; perl: 88,718; objc: 79,984; sql: 59,811; cs: 42,452; fortran: 24,101; makefile: 21,144; tcl: 15,277; php: 14,022; yacc: 9,066; ruby: 7,553; awk: 3,720; lisp: 3,233; lex: 1,328; ada: 727; jsp: 228; sed: 36
file content (170 lines) | stat: -rw-r--r-- 6,271 bytes parent folder | download | duplicates (3)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "services/network/websocket_factory.h"

#include "base/functional/bind.h"
#include "mojo/public/cpp/bindings/message.h"
#include "net/base/isolation_info.h"
#include "net/base/url_util.h"
#include "net/storage_access_api/status.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/network_context.h"
#include "services/network/network_service.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/websocket.h"
#include "url/origin.h"
#include "url/url_constants.h"

namespace network {

namespace {

bool IsValidSubprotocolCharacter(char character) {
  constexpr auto kMinimumProtocolCharacter = '!';  // U+0021.
  constexpr auto kMaximumProtocolCharacter = '~';  // U+007E.
  // Set to true if character does not matches "separators" ABNF defined in
  // RFC2616. SP and HT are excluded since the range check excludes them.
  const bool is_separator =
      character == '"' || character == '(' || character == ')' ||
      character == ',' || character == '/' ||
      (character >= ':' &&
       character <=
           '@')  // U+003A - U+0040 (':', ';', '<', '=', '>', '?', '@').
      || (character >= '[' &&
          character <= ']')  // U+005B - U+005D ('[', '\\', ']').
      || character == '{' || character == '}';
  return character >= kMinimumProtocolCharacter &&
         character <= kMaximumProtocolCharacter && !is_separator;
}

bool IsValidSubprotocolString(const std::string& protocol) {
  if (protocol.empty()) {
    return false;
  }
  return std::ranges::all_of(protocol, IsValidSubprotocolCharacter);
}

bool IsValidProtocols(const std::vector<std::string>& requested_protocols) {
  // Fail if not all elements in |protocols| are valid.
  if (!std::ranges::all_of(requested_protocols, IsValidSubprotocolString)) {
    return false;
  }

  // Fail if there're duplicated elements in |protocols|.
  std::vector<std::string> protocols = requested_protocols;
  std::ranges::sort(protocols);
  if (std::ranges::adjacent_find(protocols) != protocols.end()) {
    return false;
  }

  return true;
}

}  // namespace

WebSocketFactory::WebSocketFactory(NetworkContext* context)
    : context_(context) {}

WebSocketFactory::~WebSocketFactory() {
  // Subtle: This is important to avoid WebSocketFactory::Remove calls during
  // `connections_` destruction.
  WebSocketSet connections = std::move(connections_);
}

void WebSocketFactory::CreateWebSocket(
    const GURL& url,
    const std::vector<std::string>& requested_protocols,
    const net::SiteForCookies& site_for_cookies,
    net::StorageAccessApiStatus storage_access_api_status,
    const net::IsolationInfo& isolation_info,
    std::vector<mojom::HttpHeaderPtr> additional_headers,
    int32_t process_id,
    const url::Origin& origin,
    network::mojom::ClientSecurityStatePtr client_security_state,
    uint32_t options,
    net::NetworkTrafficAnnotationTag traffic_annotation,
    mojo::PendingRemote<mojom::WebSocketHandshakeClient> handshake_client,
    mojo::PendingRemote<mojom::URLLoaderNetworkServiceObserver>
        url_loader_network_observer,
    mojo::PendingRemote<mojom::WebSocketAuthenticationHandler> auth_handler,
    mojo::PendingRemote<mojom::TrustedHeaderClient> header_client,
    const std::optional<base::UnguessableToken>& throttling_profile_id) {
  if (isolation_info.request_type() !=
      net::IsolationInfo::RequestType::kOther) {
    mojo::ReportBadMessage(
        "WebSocket's IsolationInfo::RequestType must be kOther");
    return;
  }

  if (!url.SchemeIsWSOrWSS()) {
    mojo::ReportBadMessage("Invalid scheme.");
    return;
  }

  if (!IsValidProtocols(requested_protocols)) {
    mojo::ReportBadMessage("Invalid protocols.");
    return;
  }

  // If `require_network_anonymization_key` is set, `isolation_info` must not be
  // empty.
  if (context_->require_network_anonymization_key()) {
    DCHECK(!isolation_info.IsEmpty());
  }

  if (throttler_.HasTooManyPendingConnections(process_id)) {
    // Too many websockets!
    mojo::Remote<mojom::WebSocketHandshakeClient> handshake_client_remote(
        std::move(handshake_client));
    handshake_client_remote->OnFailure("Insufficient resources",
                                       net::ERR_INSUFFICIENT_RESOURCES, -1);
    handshake_client_remote.reset();
    return;
  }
  if (isolation_info.nonce().has_value() &&
      !context_->IsNetworkForNonceAndUrlAllowed(*isolation_info.nonce(), url)) {
    mojo::Remote<mojom::WebSocketHandshakeClient> handshake_client_remote(
        std::move(handshake_client));
    handshake_client_remote->OnFailure("Network access revoked",
                                       net::ERR_NETWORK_ACCESS_REVOKED, -1);
    handshake_client_remote.reset();
    return;
  }
  WebSocket::HasRawHeadersAccess has_raw_headers_access(
      context_->network_service()->HasRawHeadersAccess(
          process_id, net::ChangeWebSocketSchemeToHttpScheme(url)));
  connections_.insert(std::make_unique<WebSocket>(
      this, url, requested_protocols, site_for_cookies,
      storage_access_api_status, isolation_info, std::move(additional_headers),
      origin, std::move(client_security_state), options, traffic_annotation,
      has_raw_headers_access, std::move(handshake_client),
      std::move(url_loader_network_observer), std::move(auth_handler),
      std::move(header_client),
      throttler_.IssuePendingConnectionTracker(process_id),
      throttler_.CalculateDelay(process_id), throttling_profile_id));
}

net::URLRequestContext* WebSocketFactory::GetURLRequestContext() {
  return context_->url_request_context();
}

void WebSocketFactory::Remove(WebSocket* impl) {
  auto it = connections_.find(impl);
  if (it == connections_.end()) {
    // This is possible when this function is called inside the WebSocket
    // destructor.
    return;
  }
  connections_.erase(it);
}

void WebSocketFactory::RemoveIfNonceMatches(
    const base::UnguessableToken& nonce) {
  std::erase_if(connections_, [&nonce](const auto& connection) {
    return connection->RevokeIfNonceMatches(nonce);
  });
}

}  // namespace network