File: tcp_socket_event_dispatcher.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 (224 lines) | stat: -rw-r--r-- 7,650 bytes parent folder | download | duplicates (5)
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
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/browser/api/sockets_tcp/tcp_socket_event_dispatcher.h"

#include <utility>

#include "base/containers/to_vector.h"
#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/api/socket/tcp_socket.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/common/extension_id.h"
#include "net/base/net_errors.h"

namespace {
int kDefaultBufferSize = 4096;
}

namespace extensions {
namespace api {

using content::BrowserThread;

static base::LazyInstance<
    BrowserContextKeyedAPIFactory<TCPSocketEventDispatcher>>::DestructorAtExit
    g_factory = LAZY_INSTANCE_INITIALIZER;

// static
BrowserContextKeyedAPIFactory<TCPSocketEventDispatcher>*
TCPSocketEventDispatcher::GetFactoryInstance() {
  return g_factory.Pointer();
}

// static
TCPSocketEventDispatcher* TCPSocketEventDispatcher::Get(
    content::BrowserContext* context) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  return BrowserContextKeyedAPIFactory<TCPSocketEventDispatcher>::Get(context);
}

TCPSocketEventDispatcher::TCPSocketEventDispatcher(
    content::BrowserContext* context)
    : thread_id_(Socket::kThreadId), browser_context_(context) {
  ApiResourceManager<ResumableTCPSocket>* manager =
      ApiResourceManager<ResumableTCPSocket>::Get(browser_context_);
  DCHECK(manager)
      << "There is no socket manager. "
         "If this assertion is failing during a test, then it is likely that "
         "TestExtensionSystem is failing to provide an instance of "
         "ApiResourceManager<ResumableTCPSocket>.";
  sockets_ = manager->data_;
}

TCPSocketEventDispatcher::~TCPSocketEventDispatcher() = default;

TCPSocketEventDispatcher::ReadParams::ReadParams() = default;

TCPSocketEventDispatcher::ReadParams::ReadParams(const ReadParams& other) =
    default;

TCPSocketEventDispatcher::ReadParams::~ReadParams() = default;

void TCPSocketEventDispatcher::OnSocketConnect(const ExtensionId& extension_id,
                                               int socket_id) {
  DCHECK_CURRENTLY_ON(thread_id_);

  StartSocketRead(extension_id, socket_id);
}

void TCPSocketEventDispatcher::OnSocketResume(const ExtensionId& extension_id,
                                              int socket_id) {
  DCHECK_CURRENTLY_ON(thread_id_);

  StartSocketRead(extension_id, socket_id);
}

void TCPSocketEventDispatcher::StartSocketRead(const ExtensionId& extension_id,
                                               int socket_id) {
  DCHECK_CURRENTLY_ON(thread_id_);

  ReadParams params;
  params.thread_id = thread_id_;
  params.browser_context_id = browser_context_;
  params.extension_id = extension_id;
  params.sockets = sockets_;
  params.socket_id = socket_id;

  StartRead(params);
}

// static
void TCPSocketEventDispatcher::StartRead(const ReadParams& params) {
  DCHECK_CURRENTLY_ON(params.thread_id);

  ResumableTCPSocket* socket =
      params.sockets->Get(params.extension_id, params.socket_id);
  if (!socket) {
    // This can happen if the socket is closed while our callback is active.
    return;
  }
  DCHECK(params.extension_id == socket->owner_extension_id())
      << "Socket has wrong owner.";

  // Don't start another read if the socket has been paused.
  if (socket->paused()) {
    return;
  }

  int buffer_size = socket->buffer_size();
  if (buffer_size <= 0) {
    buffer_size = kDefaultBufferSize;
  }
  socket->Read(buffer_size,
               base::BindOnce(&TCPSocketEventDispatcher::ReadCallback, params));
}

// static
void TCPSocketEventDispatcher::ReadCallback(
    const ReadParams& params,
    int bytes_read,
    scoped_refptr<net::IOBuffer> io_buffer,
    bool socket_destroying) {
  DCHECK_CURRENTLY_ON(params.thread_id);

  // If |bytes_read| == 0, the connection has been closed by the peer.
  // If |bytes_read| < 0, there was a network error, and |bytes_read| is a value
  // from "net::ERR_".

  if (bytes_read == 0) {
    bytes_read = net::ERR_CONNECTION_CLOSED;
  }

  if (bytes_read > 0) {
    // Dispatch "onReceive" event.
    sockets_tcp::ReceiveInfo receive_info;
    receive_info.socket_id = params.socket_id;
    receive_info.data =
        base::ToVector(io_buffer->first(static_cast<size_t>(bytes_read)));
    auto args = sockets_tcp::OnReceive::Create(receive_info);
    std::unique_ptr<Event> event(new Event(events::SOCKETS_TCP_ON_RECEIVE,
                                           sockets_tcp::OnReceive::kEventName,
                                           std::move(args)));
    PostEvent(params, std::move(event));

    // Post a task to delay the read until the socket is available, as
    // calling StartReceive at this point would error with ERR_IO_PENDING.
    content::BrowserThread::GetTaskRunnerForThread(params.thread_id)
        ->PostTask(
            FROM_HERE,
            base::BindOnce(&TCPSocketEventDispatcher::StartRead, params));
  } else if (bytes_read == net::ERR_IO_PENDING) {
    // This happens when resuming a socket which already had an
    // active "read" callback.
  } else {
    // Dispatch "onReceiveError" event but don't start another read to avoid
    // potential infinite reads if we have a persistent network error.
    sockets_tcp::ReceiveErrorInfo receive_error_info;
    receive_error_info.socket_id = params.socket_id;
    receive_error_info.result_code = bytes_read;
    auto args = sockets_tcp::OnReceiveError::Create(receive_error_info);
    std::unique_ptr<Event> event(
        new Event(events::SOCKETS_TCP_ON_RECEIVE_ERROR,
                  sockets_tcp::OnReceiveError::kEventName, std::move(args)));
    PostEvent(params, std::move(event));

    // Do not try to access |socket| when we are destroying it.
    if (!socket_destroying) {
      // Since we got an error, the socket is now "paused" until the application
      // "resumes" it.
      ResumableTCPSocket* socket =
          params.sockets->Get(params.extension_id, params.socket_id);
      if (socket) {
        socket->set_paused(true);
      }
    }
  }
}

// static
void TCPSocketEventDispatcher::PostEvent(const ReadParams& params,
                                         std::unique_ptr<Event> event) {
  DCHECK_CURRENTLY_ON(params.thread_id);

  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(&DispatchEvent,
                     base::UnsafeDanglingUntriaged(params.browser_context_id),
                     params.extension_id, std::move(event)));
}

// static
void TCPSocketEventDispatcher::DispatchEvent(void* browser_context_id,
                                             const ExtensionId& extension_id,
                                             std::unique_ptr<Event> event) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!ExtensionsBrowserClient::Get()->IsValidContext(browser_context_id)) {
    return;
  }

  content::BrowserContext* context =
      reinterpret_cast<content::BrowserContext*>(browser_context_id);
  EventRouter* router = EventRouter::Get(context);
  if (router) {
#if BUILDFLAG(IS_CHROMEOS)
    // Terminal app is the only non-extension to use sockets
    // (crbug.com/1350479).
    if (extension_id == kCrOSTerminal) {
      router->DispatchEventToURL(GURL(extension_id), std::move(event));
      return;
    }
#endif
    router->DispatchEventToExtension(extension_id, std::move(event));
  }
}

}  // namespace api
}  // namespace extensions