File: socket_data_pump.cc

package info (click to toggle)
chromium 145.0.7632.159-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, 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 (260 lines) | stat: -rw-r--r-- 8,341 bytes parent folder | download | duplicates (8)
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
// 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/socket_data_pump.h"

#include <optional>
#include <utility>

#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/numerics/safe_conversions.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/log/net_log.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/client_socket_handle.h"
#include "services/network/tls_client_socket.h"

namespace network {

SocketDataPump::SocketDataPump(
    net::StreamSocket* socket,
    Delegate* delegate,
    mojo::ScopedDataPipeProducerHandle receive_pipe_handle,
    mojo::ScopedDataPipeConsumerHandle send_pipe_handle,
    const net::NetworkTrafficAnnotationTag& traffic_annotation)
    : socket_(socket),
      delegate_(delegate),
      receive_stream_(std::move(receive_pipe_handle)),
      receive_stream_watcher_(FROM_HERE,
                              mojo::SimpleWatcher::ArmingPolicy::MANUAL),
      receive_stream_close_watcher_(FROM_HERE,
                                    mojo::SimpleWatcher::ArmingPolicy::MANUAL),
      send_stream_(std::move(send_pipe_handle)),
      send_stream_watcher_(FROM_HERE,
                           mojo::SimpleWatcher::ArmingPolicy::MANUAL),
      traffic_annotation_(traffic_annotation) {
  send_stream_watcher_.Watch(
      send_stream_.get(),
      MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
      base::BindRepeating(&SocketDataPump::OnSendStreamReadable,
                          base::Unretained(this)));
  receive_stream_watcher_.Watch(
      receive_stream_.get(),
      MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
      base::BindRepeating(&SocketDataPump::OnReceiveStreamWritable,
                          base::Unretained(this)));
  receive_stream_close_watcher_.Watch(
      receive_stream_.get(), MOJO_HANDLE_SIGNAL_PEER_CLOSED,
      base::BindRepeating(&SocketDataPump::OnReceiveStreamClosed,
                          base::Unretained(this)));
  ReceiveMore();
  SendMore();
}

SocketDataPump::~SocketDataPump() {}

void SocketDataPump::ReceiveMore() {
  CHECK(!receive_is_shutdown_);
  CHECK(receive_stream_.is_valid());
  CHECK(!read_if_ready_pending_);

  scoped_refptr<NetToMojoPendingBuffer> pending_receive_buffer;
  MojoResult result = NetToMojoPendingBuffer::BeginWrite(
      &receive_stream_, &pending_receive_buffer);
  switch (result) {
    case MOJO_RESULT_OK:
      break;
    case MOJO_RESULT_SHOULD_WAIT:
      receive_stream_watcher_.ArmOrNotify();
      return;
    default:
      ShutdownReceive();
      return;
  }
  uint32_t num_bytes = pending_receive_buffer->size();
  auto buf = base::MakeRefCounted<NetToMojoIOBuffer>(pending_receive_buffer);
  int read_result = socket_->ReadIfReady(
      buf.get(), base::saturated_cast<int>(num_bytes),
      base::BindOnce(&SocketDataPump::OnNetworkReadCompleted,
                     // WeakPtr because `socket_` may outlive `this`.
                     weak_factory_.GetWeakPtr(),
                     /* pending_receive_buffer=*/nullptr));

  if (read_result == net::ERR_READ_IF_READY_NOT_IMPLEMENTED) {
    read_result = socket_->Read(
        buf.get(), base::saturated_cast<int>(num_bytes),
        base::BindOnce(&SocketDataPump::OnNetworkReadCompleted,
                       // WeakPtr because `socket_` may outlive `this`.
                       weak_factory_.GetWeakPtr(), pending_receive_buffer));
    if (read_result == net::ERR_IO_PENDING) {
      receive_stream_close_watcher_.ArmOrNotify();
      return;
    }
  } else if (read_result == net::ERR_IO_PENDING) {
    // The callback passed to `ReadIfReady()` will be invoked asynchronously
    // when data is available on when an error occurs. Invoke `Complete()` now
    // since the buffer won't be used.
    receive_stream_ = pending_receive_buffer->Complete(/* num_bytes=*/0);
    read_if_ready_pending_ = true;
    receive_stream_close_watcher_.ArmOrNotify();
    return;
  }

  CHECK_NE(read_result, net::ERR_IO_PENDING);
  OnNetworkReadCompleted(std::move(pending_receive_buffer), read_result);
}

void SocketDataPump::OnReceiveStreamClosed(MojoResult result) {
  ShutdownReceive();
  return;
}

void SocketDataPump::OnReceiveStreamWritable(MojoResult result) {
  CHECK(!receive_is_shutdown_);
  CHECK(receive_stream_.is_valid());

  if (result != MOJO_RESULT_OK) {
    ShutdownReceive();
    return;
  }
  ReceiveMore();
}

void SocketDataPump::OnNetworkReadCompleted(
    scoped_refptr<NetToMojoPendingBuffer> pending_receive_buffer,
    int result) {
  // `ShutdownReceive()` cancels a pending `ReadIfReady()` but not a pending
  // `Read()`, so this can be invoked after `ShutdownReceive()`. No-op in that
  // case.
  if (receive_is_shutdown_) {
    return;
  }

  // When a `ReadIfReady` is pending:
  // - Result = net::OK (0) means that data is available on the socket.
  // - Result < net::OK (0) means that an error occurred.
  // - Result > net::OK (0) should not happen.
  //
  // Otherwise:
  // - Result = net::OK (0) means that the end of file is reached.
  // - Result < net::OK (0) means that an error occurred.
  // - Result > net::OK (0) means that  `result` bytes were read in
  //   `pending_receive_buffer`.
  bool is_error_or_end_of_file;

  if (read_if_ready_pending_) {
    CHECK_GE(net::OK, result);
    CHECK(!pending_receive_buffer);
    read_if_ready_pending_ = false;
    is_error_or_end_of_file = result < net::OK;
  } else {
    CHECK(pending_receive_buffer);
    receive_stream_ = pending_receive_buffer->Complete(
        /* num_bytes=*/result >= 0 ? result : 0);
    is_error_or_end_of_file = result <= net::OK;
  }

  if (is_error_or_end_of_file) {
    if (delegate_)
      delegate_->OnNetworkReadError(result);
    ShutdownReceive();
    return;
  }

  ReceiveMore();
}

void SocketDataPump::ShutdownReceive() {
  CHECK(!receive_is_shutdown_);

  receive_is_shutdown_ = true;
  receive_stream_watcher_.Cancel();
  receive_stream_close_watcher_.Cancel();
  receive_stream_.reset();
  if (read_if_ready_pending_) {
    int result = socket_->CancelReadIfReady();
    DCHECK_EQ(net::OK, result);
    read_if_ready_pending_ = false;
  }
  MaybeNotifyDelegate();
}

void SocketDataPump::SendMore() {
  DCHECK(send_stream_.is_valid());
  DCHECK(!pending_send_buffer_);

  MojoResult result =
      MojoToNetPendingBuffer::BeginRead(&send_stream_, &pending_send_buffer_);
  if (result == MOJO_RESULT_SHOULD_WAIT) {
    send_stream_watcher_.ArmOrNotify();
    return;
  }
  if (result != MOJO_RESULT_OK) {
    ShutdownSend();
    return;
  }
  auto buf = base::MakeRefCounted<net::WrappedIOBuffer>(*pending_send_buffer_);

  // Use WeakPtr here because |this| doesn't outlive |socket_|.
  int write_result =
      socket_->Write(buf.get(), buf->size(),
                     base::BindOnce(&SocketDataPump::OnNetworkWriteCompleted,
                                    weak_factory_.GetWeakPtr()),
                     traffic_annotation_);
  if (write_result == net::ERR_IO_PENDING)
    return;
  OnNetworkWriteCompleted(write_result);
}

void SocketDataPump::OnSendStreamReadable(MojoResult result) {
  DCHECK(!pending_send_buffer_);
  DCHECK(send_stream_.is_valid());

  if (result != MOJO_RESULT_OK) {
    ShutdownSend();
    return;
  }
  SendMore();
}

void SocketDataPump::OnNetworkWriteCompleted(int result) {
  DCHECK(pending_send_buffer_);
  DCHECK(!send_stream_.is_valid());

  // Partial write is possible.
  pending_send_buffer_->CompleteRead(result >= 0 ? result : 0);
  send_stream_ = pending_send_buffer_->ReleaseHandle();
  pending_send_buffer_ = nullptr;

  if (result <= 0) {
    if (delegate_)
      delegate_->OnNetworkWriteError(result);
    ShutdownSend();
    return;
  }
  SendMore();
}

void SocketDataPump::ShutdownSend() {
  DCHECK(send_stream_.is_valid());
  DCHECK(!pending_send_buffer_);

  send_stream_watcher_.Cancel();
  pending_send_buffer_ = nullptr;
  send_stream_.reset();
  MaybeNotifyDelegate();
}

void SocketDataPump::MaybeNotifyDelegate() {
  if (!delegate_ || send_stream_.is_valid() || !receive_is_shutdown_) {
    return;
  }
  delegate_->OnShutdown();
}

}  // namespace network