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
|
// 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.
#include "third_party/blink/renderer/modules/direct_sockets/tcp_writable_stream_wrapper.h"
#include <optional>
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "mojo/public/cpp/system/handle_signals_state.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "net/base/net_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_typedefs.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_arraybuffer_arraybufferview.h"
#include "third_party/blink/renderer/core/core_probes_inl.h"
#include "third_party/blink/renderer/core/dom/abort_signal.h"
#include "third_party/blink/renderer/core/dom/events/event_target_impl.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/streams/underlying_sink_base.h"
#include "third_party/blink/renderer/core/streams/writable_stream.h"
#include "third_party/blink/renderer/core/streams/writable_stream_default_controller.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_piece.h"
#include "third_party/blink/renderer/modules/direct_sockets/stream_wrapper.h"
#include "third_party/blink/renderer/modules/direct_sockets/tcp_readable_stream_wrapper.h"
#include "third_party/blink/renderer/platform/bindings/exception_code.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/heap/visitor.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
TCPWritableStreamWrapper::TCPWritableStreamWrapper(
ScriptState* script_state,
CloseOnceCallback on_close,
mojo::ScopedDataPipeProducerHandle handle,
uint64_t inspector_id)
: WritableStreamWrapper(script_state),
on_close_(std::move(on_close)),
data_pipe_(std::move(handle)),
write_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL),
close_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC),
inspector_id_(inspector_id) {
write_watcher_.Watch(
data_pipe_.get(), MOJO_HANDLE_SIGNAL_WRITABLE,
MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
WTF::BindRepeating(&TCPWritableStreamWrapper::OnHandleReady,
WrapWeakPersistent(this)));
close_watcher_.Watch(
data_pipe_.get(), MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
WTF::BindRepeating(&TCPWritableStreamWrapper::OnHandleReset,
WrapWeakPersistent(this)));
ScriptState::Scope scope(script_state);
auto* sink = WritableStreamWrapper::MakeForwardingUnderlyingSink(this);
SetSink(sink);
// Set the CountQueueingStrategy's high water mark as 1 to make the logic of
// |WriteOrCacheData| much simpler.
auto* writable = WritableStream::CreateWithCountQueueingStrategy(
script_state, sink, /*high_water_mark=*/1);
SetWritable(writable);
}
bool TCPWritableStreamWrapper::HasPendingWrite() const {
return !!write_promise_resolver_;
}
void TCPWritableStreamWrapper::Trace(Visitor* visitor) const {
visitor->Trace(buffer_source_);
visitor->Trace(write_promise_resolver_);
WritableStreamWrapper::Trace(visitor);
}
void TCPWritableStreamWrapper::OnHandleReady(MojoResult result,
const mojo::HandleSignalsState&) {
switch (result) {
case MOJO_RESULT_OK:
WriteDataAsynchronously();
break;
case MOJO_RESULT_FAILED_PRECONDITION:
// Will be handled by |close_watcher_|.
break;
default:
NOTREACHED();
}
}
void TCPWritableStreamWrapper::OnHandleReset(MojoResult result,
const mojo::HandleSignalsState&) {
DCHECK_EQ(result, MOJO_RESULT_OK);
ResetPipe();
}
void TCPWritableStreamWrapper::OnAbortSignal() {
if (write_promise_resolver_) {
write_promise_resolver_->Reject(
Controller()->signal()->reason(GetScriptState()));
write_promise_resolver_ = nullptr;
}
}
ScriptPromise<IDLUndefined> TCPWritableStreamWrapper::Write(
ScriptValue chunk,
ExceptionState& exception_state) {
// There can only be one call to write() in progress at a time.
DCHECK(!write_promise_resolver_);
DCHECK(!buffer_source_);
DCHECK_EQ(0u, offset_);
if (!data_pipe_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNetworkError,
"The underlying data pipe was disconnected.");
return EmptyPromise();
}
buffer_source_ = V8BufferSource::Create(GetScriptState()->GetIsolate(),
chunk.V8Value(), exception_state);
if (exception_state.HadException()) {
return EmptyPromise();
}
DCHECK(buffer_source_);
write_promise_resolver_ =
MakeGarbageCollected<ScriptPromiseResolver<IDLUndefined>>(
GetScriptState(), exception_state.GetContext());
auto promise = write_promise_resolver_->Promise();
WriteDataAsynchronously();
return promise;
}
void TCPWritableStreamWrapper::WriteDataAsynchronously() {
DCHECK(data_pipe_);
DCHECK(buffer_source_);
DOMArrayPiece array_piece(buffer_source_);
// From https://webidl.spec.whatwg.org/#dfn-get-buffer-source-copy, if the
// buffer source is detached then an empty byte sequence is returned, which
// means the write is complete.
if (array_piece.IsDetached()) {
FinalizeWrite();
return;
}
size_t written =
WriteDataSynchronously(array_piece.ByteSpan().subspan(offset_));
DCHECK_LE(offset_ + written, array_piece.ByteLength());
if (offset_ + written == array_piece.ByteLength()) {
FinalizeWrite();
return;
}
offset_ += written;
write_watcher_.ArmOrNotify();
}
// Write as much of |data| as can be written synchronously. Return the number of
// bytes written. May close |data_pipe_| as a side-effect on error.
size_t TCPWritableStreamWrapper::WriteDataSynchronously(
base::span<const uint8_t> data) {
size_t actually_written_bytes = 0;
MojoResult result = data_pipe_->WriteData(data, MOJO_WRITE_DATA_FLAG_NONE,
actually_written_bytes);
switch (result) {
case MOJO_RESULT_OK:
case MOJO_RESULT_SHOULD_WAIT:
return actually_written_bytes;
case MOJO_RESULT_FAILED_PRECONDITION:
// Will be handled by |close_watcher_|.
return 0;
default:
NOTREACHED();
}
}
void TCPWritableStreamWrapper::FinalizeWrite() {
if (buffer_source_) {
// report to CDP
DOMArrayPiece array_piece(buffer_source_);
base::span<const uint8_t> data = array_piece.ByteSpan();
probe::DirectTCPSocketChunkSent(*GetScriptState(), inspector_id_, data);
}
buffer_source_ = nullptr;
offset_ = 0;
write_promise_resolver_->Resolve();
write_promise_resolver_ = nullptr;
}
void TCPWritableStreamWrapper::CloseStream() {
if (GetState() != State::kOpen) {
return;
}
SetState(State::kClosed);
DCHECK(!write_promise_resolver_);
// If close request came from writer.close() or writer.abort(), the internal
// state of the stream is already set to closed. Therefore we don't have to
// do anything with the controller.
if (!data_pipe_) {
// This is a rare case indicating that writer.close/abort() interrupted
// the OnWriteError() call where the pipe already got reset, but the
// corresponding IPC hasn't yet arrived. The simplest way is to abort
// CloseStream by setting state to Open and allow the IPC to finish the
// job.
SetState(State::kOpen);
return;
}
ResetPipe();
std::move(on_close_).Run(/*exception=*/v8::Local<v8::Value>(),
/*net_error=*/net::OK);
}
void TCPWritableStreamWrapper::ErrorStream(int32_t error_code) {
if (GetState() != State::kOpen) {
return;
}
SetState(State::kAborted);
// Error codes are negative.
base::UmaHistogramSparse("DirectSockets.TCPWritableStreamError", -error_code);
auto message =
String{"Stream aborted by the remote: " + net::ErrorToString(error_code)};
auto* script_state = write_promise_resolver_
? write_promise_resolver_->GetScriptState()
: GetScriptState();
// Scope is needed because there's no ScriptState* on the call stack for
// ScriptValue.
ScriptState::Scope scope{script_state};
auto exception = V8ThrowDOMException::CreateOrDie(
script_state->GetIsolate(), DOMExceptionCode::kNetworkError, message);
// Can be already reset due to HandlePipeClosed() called previously.
if (data_pipe_) {
ResetPipe();
}
if (write_promise_resolver_) {
write_promise_resolver_->Reject(exception);
write_promise_resolver_ = nullptr;
} else {
Controller()->error(script_state,
ScriptValue(script_state->GetIsolate(), exception));
}
std::move(on_close_).Run(exception, error_code);
}
void TCPWritableStreamWrapper::ResetPipe() {
write_watcher_.Cancel();
close_watcher_.Cancel();
data_pipe_.reset();
buffer_source_ = nullptr;
offset_ = 0;
}
void TCPWritableStreamWrapper::Dispose() {
ResetPipe();
}
} // namespace blink
|