gecko-dev/dom/base/nsDOMDataChannel.cpp

555 строки
14 KiB
C++
Исходник Обычный вид История

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsDOMDataChannel.h"
#include "base/basictypes.h"
#include "mozilla/Logging.h"
#include "nsDOMDataChannelDeclarations.h"
#include "nsDOMDataChannel.h"
#include "nsIDOMDataChannel.h"
#include "mozilla/DOMEventTargetHelper.h"
#include "mozilla/dom/File.h"
#include "mozilla/dom/MessageEvent.h"
#include "mozilla/dom/MessageEventBinding.h"
#include "mozilla/dom/ScriptSettings.h"
#include "nsError.h"
#include "nsContentUtils.h"
#include "nsCycleCollectionParticipant.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsProxyRelease.h"
#include "DataChannel.h"
#include "DataChannelLog.h"
#undef LOG
#define LOG(args) MOZ_LOG(mozilla::gDataChannelLog, mozilla::LogLevel::Debug, args)
// Since we've moved the windows.h include down here, we have to explicitly
// undef GetBinaryType, otherwise we'll get really odd conflicts
#ifdef GetBinaryType
#undef GetBinaryType
#endif
using namespace mozilla;
using namespace mozilla::dom;
nsDOMDataChannel::~nsDOMDataChannel()
{
// Don't call us anymore! Likely isn't an issue (or maybe just less of
// one) once we block GC until all the (appropriate) onXxxx handlers
// are dropped. (See WebRTC spec)
LOG(("%p: Close()ing %p", this, mDataChannel.get()));
mDataChannel->SetListener(nullptr, nullptr);
mDataChannel->Close();
}
/* virtual */ JSObject*
Bug 1117172 part 3. Change the wrappercached WrapObject methods to allow passing in aGivenProto. r=peterv The only manual changes here are to BindingUtils.h, BindingUtils.cpp, Codegen.py, Element.cpp, IDBFileRequest.cpp, IDBObjectStore.cpp, dom/workers/Navigator.cpp, WorkerPrivate.cpp, DeviceStorageRequestChild.cpp, Notification.cpp, nsGlobalWindow.cpp, MessagePort.cpp, nsJSEnvironment.cpp, Sandbox.cpp, XPCConvert.cpp, ExportHelpers.cpp, and DataStoreService.cpp. The rest of this diff was generated by running the following commands: find . -name "*.h" -o -name "*.cpp" | xargs perl -pi -e 'BEGIN { $/ = undef } s/(WrapObjectInternal\(JSContext *\* *(?:aCx|cx|aContext|aCtx|js))\)/\1, JS::Handle<JSObject*> aGivenProto)/g' find . -name "*.h" -o -name "*.cpp" | xargs perl -pi -e 'BEGIN { $/ = undef } s/(WrapObjectInternal\((?:aCx|cx|aContext|aCtx|js))\)/\1, aGivenProto)/g' find . -name "*.h" -o -name "*.cpp" | xargs perl -pi -e 'BEGIN { $/ = undef } s/(WrapNode\(JSContext *\* *(?:aCx|cx|aContext|aCtx|js))\)/\1, JS::Handle<JSObject*> aGivenProto)/g' find . -name "*.h" -o -name "*.cpp" | xargs perl -pi -e 'BEGIN { $/ = undef } s/(WrapNode\((?:aCx|cx|aContext|aCtx|js))\)/\1, aGivenProto)/g' find . -name "*.h" -o -name "*.cpp" | xargs perl -pi -e 'BEGIN { $/ = undef } s/(WrapObject\(JSContext *\* *(?:aCx|cx|aContext|aCtx|js))\)/\1, JS::Handle<JSObject*> aGivenProto)/g' find . -name "*.h" -o -name "*.cpp" | xargs perl -pi -e 'BEGIN { $/ = undef } s/(Binding(?:_workers)?::Wrap\((?:aCx|cx|aContext|aCtx|js), [^,)]+)\)/\1, aGivenProto)/g'
2015-03-19 17:13:33 +03:00
nsDOMDataChannel::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
return RTCDataChannelBinding::Wrap(aCx, this, aGivenProto);
}
NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMDataChannel)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMDataChannel,
DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMDataChannel,
DOMEventTargetHelper)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_ADDREF_INHERITED(nsDOMDataChannel, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(nsDOMDataChannel, DOMEventTargetHelper)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMDataChannel)
NS_INTERFACE_MAP_ENTRY(nsIDOMDataChannel)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
nsDOMDataChannel::nsDOMDataChannel(already_AddRefed<mozilla::DataChannel>& aDataChannel,
nsPIDOMWindowInner* aWindow)
: DOMEventTargetHelper(aWindow)
, mDataChannel(aDataChannel)
, mBinaryType(DC_BINARY_TYPE_BLOB)
, mCheckMustKeepAlive(true)
, mSentClose(false)
{
}
nsresult
nsDOMDataChannel::Init(nsPIDOMWindowInner* aDOMWindow)
{
nsresult rv;
nsAutoString urlParam;
MOZ_ASSERT(mDataChannel);
mDataChannel->SetListener(this, nullptr);
// Now grovel through the objects to get a usable origin for onMessage
nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(aDOMWindow);
NS_ENSURE_STATE(sgo);
nsCOMPtr<nsIScriptContext> scriptContext = sgo->GetContext();
NS_ENSURE_STATE(scriptContext);
nsCOMPtr<nsIScriptObjectPrincipal> scriptPrincipal(do_QueryInterface(aDOMWindow));
NS_ENSURE_STATE(scriptPrincipal);
nsCOMPtr<nsIPrincipal> principal = scriptPrincipal->GetPrincipal();
NS_ENSURE_STATE(principal);
// Attempt to kill "ghost" DataChannel (if one can happen): but usually too early for check to fail
rv = CheckInnerWindowCorrectness();
NS_ENSURE_SUCCESS(rv,rv);
rv = nsContentUtils::GetUTFOrigin(principal,mOrigin);
LOG(("%s: origin = %s\n",__FUNCTION__,NS_LossyConvertUTF16toASCII(mOrigin).get()));
return rv;
}
// Most of the GetFoo()/SetFoo()s don't need to touch shared resources and
// are safe after Close()
void
nsDOMDataChannel::GetLabel(nsAString& aLabel)
{
mDataChannel->GetLabel(aLabel);
}
void
nsDOMDataChannel::GetProtocol(nsAString& aProtocol)
{
mDataChannel->GetProtocol(aProtocol);
}
uint16_t
nsDOMDataChannel::Id() const
{
return mDataChannel->GetStream();
}
// XXX should be GetType()? Open question for the spec
bool
nsDOMDataChannel::Reliable() const
{
return mDataChannel->GetType() == mozilla::DataChannelConnection::RELIABLE;
}
bool
nsDOMDataChannel::Ordered() const
{
return mDataChannel->GetOrdered();
}
RTCDataChannelState
nsDOMDataChannel::ReadyState() const
{
return static_cast<RTCDataChannelState>(mDataChannel->GetReadyState());
}
uint32_t
nsDOMDataChannel::BufferedAmount() const
{
if (!mSentClose) {
return mDataChannel->GetBufferedAmount();
}
return 0;
}
uint32_t
nsDOMDataChannel::BufferedAmountLowThreshold() const
{
return mDataChannel->GetBufferedAmountLowThreshold();
}
void
nsDOMDataChannel::SetBufferedAmountLowThreshold(uint32_t aThreshold)
{
mDataChannel->SetBufferedAmountLowThreshold(aThreshold);
}
void
nsDOMDataChannel::Close()
{
mDataChannel->Close();
UpdateMustKeepAlive();
}
// All of the following is copy/pasted from WebSocket.cpp.
void
nsDOMDataChannel::Send(const nsAString& aData, ErrorResult& aRv)
{
NS_ConvertUTF16toUTF8 msgString(aData);
Bug 979417 - Implement EOR when receiving and explicit EOR when sending on data channels (including DCEP). r=drno,jesup This allows sending and receiving arbitrarily (we limit to 1 GiB atm) sized messages while not relying on the deprecated PPID fragmentation/reassembly mode. The code already supports the ndata extension but it's not activated, yet. Without the SCTP ndata extension, a large data channel message will monopolise the SCTP association. While this is a problem, it is a temporary solution until the extension is being activated. Keep in mind that every application that uses data channels currently does fragmentation/reassembly on application-level and it's unlikely that this will change until the popular implementations (libwebrtc) implement EOR as well. Moreover, until the WebRTC API specifies an API that hands over partial messages, doing application-level fragmentation/reassembly is still useful for very large messages (sadly). We fall back to PPID-based fragmentation/reassembly mode IFF a=max-message-size is not set in the SDP and the negotiated amount of SCTP inbound streams is exactly 256. Other implementations should avoid using this combination (to be precise, other implementations should send a=max-message-size). It also changes behaviour of RTCDataChannel.send which now raises TypeError in case the message is too large for the other peer to receive. This is a necessity to ensure that implementations that do not look at the EOR flag when receiving are always able to receive our messages. Even if these implementations do not set a=max-message-size, we use a safe default value (64 KiB, dictated by the spec) that every implementation should be able to receive, with or without EOR support. * Due to the use of explicit EOR, this required some major refactoring of all send-related and deferred sending functions (which is now a lot less complex). There's now only one place where `usrsctp_sendv` is being used. * All data channel messages and DCEP messages will be sent without copying them first. Only in case this fails (e.g. usrsctp's buffer is full), the message will be copied and added to a buffer queue. * Queued data channel messages will now be re-sent fairly (round-robin). * Maximum message size and the PPID-based fragmentation are configurable using about:config (media.peerconnection.sctp.force_ppid_fragmentation and media.peerconnection.sctp.force_maximum_message_size). * Enable interleaving of incoming messages for different streams (preparation for SCTP ndata, has no effect until it is enabled). * Enable interleaving of outgoing messages (disabled if SCTP ndata has not been negotiated). * Add pending messages flag to reduce performance impact from frequent calls to SendDeferredMessages. * Handle partial delivery events (for cases where a partially delivered message is being aborted). * Close a data channel/the connection in case the message is too large to be handled (this is only applied in cases where the remote peer ignores our announced local maximum message size). * Various size_t to uint32_t conversions (message length) and back should be safe now. * Remove aUsingDtls/mUsingDtls from DataChannelConnection. * Set maximum message size in SDP and in the data channel stack. * Replace implicit NS_ENSURE_*'s with explicit NS_WARN_IF's. * Add SetMaxMessageSize method for late-applying those signalling parameters when a data channel has been created before the remote SDP was available. * Limit remote maximum message size and add a GetMaxMessageSize method for a future implementation of RTCSctpTransport.maxMessageSize. MozReview-Commit-ID: FlmZrpC5zVI --HG-- extra : rebase_source : 54e1b838c788a3abbded4fb32fe7c2788f8a9bc0
2017-07-26 14:18:54 +03:00
Send(nullptr, msgString, false, aRv);
}
void
nsDOMDataChannel::Send(Blob& aData, ErrorResult& aRv)
{
MOZ_ASSERT(NS_IsMainThread(), "Not running on main thread");
nsCOMPtr<nsIInputStream> msgStream;
aData.CreateInputStream(getter_AddRefs(msgStream), aRv);
if (NS_WARN_IF(aRv.Failed())){
return;
}
uint64_t msgLength = aData.GetSize(aRv);
if (NS_WARN_IF(aRv.Failed())){
return;
}
if (msgLength > UINT32_MAX) {
aRv.Throw(NS_ERROR_FILE_TOO_BIG);
return;
}
Bug 979417 - Implement EOR when receiving and explicit EOR when sending on data channels (including DCEP). r=drno,jesup This allows sending and receiving arbitrarily (we limit to 1 GiB atm) sized messages while not relying on the deprecated PPID fragmentation/reassembly mode. The code already supports the ndata extension but it's not activated, yet. Without the SCTP ndata extension, a large data channel message will monopolise the SCTP association. While this is a problem, it is a temporary solution until the extension is being activated. Keep in mind that every application that uses data channels currently does fragmentation/reassembly on application-level and it's unlikely that this will change until the popular implementations (libwebrtc) implement EOR as well. Moreover, until the WebRTC API specifies an API that hands over partial messages, doing application-level fragmentation/reassembly is still useful for very large messages (sadly). We fall back to PPID-based fragmentation/reassembly mode IFF a=max-message-size is not set in the SDP and the negotiated amount of SCTP inbound streams is exactly 256. Other implementations should avoid using this combination (to be precise, other implementations should send a=max-message-size). It also changes behaviour of RTCDataChannel.send which now raises TypeError in case the message is too large for the other peer to receive. This is a necessity to ensure that implementations that do not look at the EOR flag when receiving are always able to receive our messages. Even if these implementations do not set a=max-message-size, we use a safe default value (64 KiB, dictated by the spec) that every implementation should be able to receive, with or without EOR support. * Due to the use of explicit EOR, this required some major refactoring of all send-related and deferred sending functions (which is now a lot less complex). There's now only one place where `usrsctp_sendv` is being used. * All data channel messages and DCEP messages will be sent without copying them first. Only in case this fails (e.g. usrsctp's buffer is full), the message will be copied and added to a buffer queue. * Queued data channel messages will now be re-sent fairly (round-robin). * Maximum message size and the PPID-based fragmentation are configurable using about:config (media.peerconnection.sctp.force_ppid_fragmentation and media.peerconnection.sctp.force_maximum_message_size). * Enable interleaving of incoming messages for different streams (preparation for SCTP ndata, has no effect until it is enabled). * Enable interleaving of outgoing messages (disabled if SCTP ndata has not been negotiated). * Add pending messages flag to reduce performance impact from frequent calls to SendDeferredMessages. * Handle partial delivery events (for cases where a partially delivered message is being aborted). * Close a data channel/the connection in case the message is too large to be handled (this is only applied in cases where the remote peer ignores our announced local maximum message size). * Various size_t to uint32_t conversions (message length) and back should be safe now. * Remove aUsingDtls/mUsingDtls from DataChannelConnection. * Set maximum message size in SDP and in the data channel stack. * Replace implicit NS_ENSURE_*'s with explicit NS_WARN_IF's. * Add SetMaxMessageSize method for late-applying those signalling parameters when a data channel has been created before the remote SDP was available. * Limit remote maximum message size and add a GetMaxMessageSize method for a future implementation of RTCSctpTransport.maxMessageSize. MozReview-Commit-ID: FlmZrpC5zVI --HG-- extra : rebase_source : 54e1b838c788a3abbded4fb32fe7c2788f8a9bc0
2017-07-26 14:18:54 +03:00
Send(msgStream, EmptyCString(), true, aRv);
}
void
nsDOMDataChannel::Send(const ArrayBuffer& aData, ErrorResult& aRv)
{
MOZ_ASSERT(NS_IsMainThread(), "Not running on main thread");
aData.ComputeLengthAndData();
static_assert(sizeof(*aData.Data()) == 1, "byte-sized data required");
uint32_t len = aData.Length();
char* data = reinterpret_cast<char*>(aData.Data());
nsDependentCSubstring msgString(data, len);
Bug 979417 - Implement EOR when receiving and explicit EOR when sending on data channels (including DCEP). r=drno,jesup This allows sending and receiving arbitrarily (we limit to 1 GiB atm) sized messages while not relying on the deprecated PPID fragmentation/reassembly mode. The code already supports the ndata extension but it's not activated, yet. Without the SCTP ndata extension, a large data channel message will monopolise the SCTP association. While this is a problem, it is a temporary solution until the extension is being activated. Keep in mind that every application that uses data channels currently does fragmentation/reassembly on application-level and it's unlikely that this will change until the popular implementations (libwebrtc) implement EOR as well. Moreover, until the WebRTC API specifies an API that hands over partial messages, doing application-level fragmentation/reassembly is still useful for very large messages (sadly). We fall back to PPID-based fragmentation/reassembly mode IFF a=max-message-size is not set in the SDP and the negotiated amount of SCTP inbound streams is exactly 256. Other implementations should avoid using this combination (to be precise, other implementations should send a=max-message-size). It also changes behaviour of RTCDataChannel.send which now raises TypeError in case the message is too large for the other peer to receive. This is a necessity to ensure that implementations that do not look at the EOR flag when receiving are always able to receive our messages. Even if these implementations do not set a=max-message-size, we use a safe default value (64 KiB, dictated by the spec) that every implementation should be able to receive, with or without EOR support. * Due to the use of explicit EOR, this required some major refactoring of all send-related and deferred sending functions (which is now a lot less complex). There's now only one place where `usrsctp_sendv` is being used. * All data channel messages and DCEP messages will be sent without copying them first. Only in case this fails (e.g. usrsctp's buffer is full), the message will be copied and added to a buffer queue. * Queued data channel messages will now be re-sent fairly (round-robin). * Maximum message size and the PPID-based fragmentation are configurable using about:config (media.peerconnection.sctp.force_ppid_fragmentation and media.peerconnection.sctp.force_maximum_message_size). * Enable interleaving of incoming messages for different streams (preparation for SCTP ndata, has no effect until it is enabled). * Enable interleaving of outgoing messages (disabled if SCTP ndata has not been negotiated). * Add pending messages flag to reduce performance impact from frequent calls to SendDeferredMessages. * Handle partial delivery events (for cases where a partially delivered message is being aborted). * Close a data channel/the connection in case the message is too large to be handled (this is only applied in cases where the remote peer ignores our announced local maximum message size). * Various size_t to uint32_t conversions (message length) and back should be safe now. * Remove aUsingDtls/mUsingDtls from DataChannelConnection. * Set maximum message size in SDP and in the data channel stack. * Replace implicit NS_ENSURE_*'s with explicit NS_WARN_IF's. * Add SetMaxMessageSize method for late-applying those signalling parameters when a data channel has been created before the remote SDP was available. * Limit remote maximum message size and add a GetMaxMessageSize method for a future implementation of RTCSctpTransport.maxMessageSize. MozReview-Commit-ID: FlmZrpC5zVI --HG-- extra : rebase_source : 54e1b838c788a3abbded4fb32fe7c2788f8a9bc0
2017-07-26 14:18:54 +03:00
Send(nullptr, msgString, true, aRv);
}
void
nsDOMDataChannel::Send(const ArrayBufferView& aData, ErrorResult& aRv)
{
MOZ_ASSERT(NS_IsMainThread(), "Not running on main thread");
aData.ComputeLengthAndData();
static_assert(sizeof(*aData.Data()) == 1, "byte-sized data required");
uint32_t len = aData.Length();
char* data = reinterpret_cast<char*>(aData.Data());
nsDependentCSubstring msgString(data, len);
Bug 979417 - Implement EOR when receiving and explicit EOR when sending on data channels (including DCEP). r=drno,jesup This allows sending and receiving arbitrarily (we limit to 1 GiB atm) sized messages while not relying on the deprecated PPID fragmentation/reassembly mode. The code already supports the ndata extension but it's not activated, yet. Without the SCTP ndata extension, a large data channel message will monopolise the SCTP association. While this is a problem, it is a temporary solution until the extension is being activated. Keep in mind that every application that uses data channels currently does fragmentation/reassembly on application-level and it's unlikely that this will change until the popular implementations (libwebrtc) implement EOR as well. Moreover, until the WebRTC API specifies an API that hands over partial messages, doing application-level fragmentation/reassembly is still useful for very large messages (sadly). We fall back to PPID-based fragmentation/reassembly mode IFF a=max-message-size is not set in the SDP and the negotiated amount of SCTP inbound streams is exactly 256. Other implementations should avoid using this combination (to be precise, other implementations should send a=max-message-size). It also changes behaviour of RTCDataChannel.send which now raises TypeError in case the message is too large for the other peer to receive. This is a necessity to ensure that implementations that do not look at the EOR flag when receiving are always able to receive our messages. Even if these implementations do not set a=max-message-size, we use a safe default value (64 KiB, dictated by the spec) that every implementation should be able to receive, with or without EOR support. * Due to the use of explicit EOR, this required some major refactoring of all send-related and deferred sending functions (which is now a lot less complex). There's now only one place where `usrsctp_sendv` is being used. * All data channel messages and DCEP messages will be sent without copying them first. Only in case this fails (e.g. usrsctp's buffer is full), the message will be copied and added to a buffer queue. * Queued data channel messages will now be re-sent fairly (round-robin). * Maximum message size and the PPID-based fragmentation are configurable using about:config (media.peerconnection.sctp.force_ppid_fragmentation and media.peerconnection.sctp.force_maximum_message_size). * Enable interleaving of incoming messages for different streams (preparation for SCTP ndata, has no effect until it is enabled). * Enable interleaving of outgoing messages (disabled if SCTP ndata has not been negotiated). * Add pending messages flag to reduce performance impact from frequent calls to SendDeferredMessages. * Handle partial delivery events (for cases where a partially delivered message is being aborted). * Close a data channel/the connection in case the message is too large to be handled (this is only applied in cases where the remote peer ignores our announced local maximum message size). * Various size_t to uint32_t conversions (message length) and back should be safe now. * Remove aUsingDtls/mUsingDtls from DataChannelConnection. * Set maximum message size in SDP and in the data channel stack. * Replace implicit NS_ENSURE_*'s with explicit NS_WARN_IF's. * Add SetMaxMessageSize method for late-applying those signalling parameters when a data channel has been created before the remote SDP was available. * Limit remote maximum message size and add a GetMaxMessageSize method for a future implementation of RTCSctpTransport.maxMessageSize. MozReview-Commit-ID: FlmZrpC5zVI --HG-- extra : rebase_source : 54e1b838c788a3abbded4fb32fe7c2788f8a9bc0
2017-07-26 14:18:54 +03:00
Send(nullptr, msgString, true, aRv);
}
void
nsDOMDataChannel::Send(nsIInputStream* aMsgStream,
const nsACString& aMsgString,
bool aIsBinary,
ErrorResult& aRv)
{
MOZ_ASSERT(NS_IsMainThread());
uint16_t state = mozilla::DataChannel::CLOSED;
if (!mSentClose) {
state = mDataChannel->GetReadyState();
}
// In reality, the DataChannel protocol allows this, but we want it to
// look like WebSockets
if (state == mozilla::DataChannel::CONNECTING) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
if (state == mozilla::DataChannel::CLOSING ||
state == mozilla::DataChannel::CLOSED) {
return;
}
MOZ_ASSERT(state == mozilla::DataChannel::OPEN,
"Unknown state in nsDOMDataChannel::Send");
if (aMsgStream) {
Bug 979417 - Implement EOR when receiving and explicit EOR when sending on data channels (including DCEP). r=drno,jesup This allows sending and receiving arbitrarily (we limit to 1 GiB atm) sized messages while not relying on the deprecated PPID fragmentation/reassembly mode. The code already supports the ndata extension but it's not activated, yet. Without the SCTP ndata extension, a large data channel message will monopolise the SCTP association. While this is a problem, it is a temporary solution until the extension is being activated. Keep in mind that every application that uses data channels currently does fragmentation/reassembly on application-level and it's unlikely that this will change until the popular implementations (libwebrtc) implement EOR as well. Moreover, until the WebRTC API specifies an API that hands over partial messages, doing application-level fragmentation/reassembly is still useful for very large messages (sadly). We fall back to PPID-based fragmentation/reassembly mode IFF a=max-message-size is not set in the SDP and the negotiated amount of SCTP inbound streams is exactly 256. Other implementations should avoid using this combination (to be precise, other implementations should send a=max-message-size). It also changes behaviour of RTCDataChannel.send which now raises TypeError in case the message is too large for the other peer to receive. This is a necessity to ensure that implementations that do not look at the EOR flag when receiving are always able to receive our messages. Even if these implementations do not set a=max-message-size, we use a safe default value (64 KiB, dictated by the spec) that every implementation should be able to receive, with or without EOR support. * Due to the use of explicit EOR, this required some major refactoring of all send-related and deferred sending functions (which is now a lot less complex). There's now only one place where `usrsctp_sendv` is being used. * All data channel messages and DCEP messages will be sent without copying them first. Only in case this fails (e.g. usrsctp's buffer is full), the message will be copied and added to a buffer queue. * Queued data channel messages will now be re-sent fairly (round-robin). * Maximum message size and the PPID-based fragmentation are configurable using about:config (media.peerconnection.sctp.force_ppid_fragmentation and media.peerconnection.sctp.force_maximum_message_size). * Enable interleaving of incoming messages for different streams (preparation for SCTP ndata, has no effect until it is enabled). * Enable interleaving of outgoing messages (disabled if SCTP ndata has not been negotiated). * Add pending messages flag to reduce performance impact from frequent calls to SendDeferredMessages. * Handle partial delivery events (for cases where a partially delivered message is being aborted). * Close a data channel/the connection in case the message is too large to be handled (this is only applied in cases where the remote peer ignores our announced local maximum message size). * Various size_t to uint32_t conversions (message length) and back should be safe now. * Remove aUsingDtls/mUsingDtls from DataChannelConnection. * Set maximum message size in SDP and in the data channel stack. * Replace implicit NS_ENSURE_*'s with explicit NS_WARN_IF's. * Add SetMaxMessageSize method for late-applying those signalling parameters when a data channel has been created before the remote SDP was available. * Limit remote maximum message size and add a GetMaxMessageSize method for a future implementation of RTCSctpTransport.maxMessageSize. MozReview-Commit-ID: FlmZrpC5zVI --HG-- extra : rebase_source : 54e1b838c788a3abbded4fb32fe7c2788f8a9bc0
2017-07-26 14:18:54 +03:00
mDataChannel->SendBinaryStream(aMsgStream, aRv);
} else {
if (aIsBinary) {
Bug 979417 - Implement EOR when receiving and explicit EOR when sending on data channels (including DCEP). r=drno,jesup This allows sending and receiving arbitrarily (we limit to 1 GiB atm) sized messages while not relying on the deprecated PPID fragmentation/reassembly mode. The code already supports the ndata extension but it's not activated, yet. Without the SCTP ndata extension, a large data channel message will monopolise the SCTP association. While this is a problem, it is a temporary solution until the extension is being activated. Keep in mind that every application that uses data channels currently does fragmentation/reassembly on application-level and it's unlikely that this will change until the popular implementations (libwebrtc) implement EOR as well. Moreover, until the WebRTC API specifies an API that hands over partial messages, doing application-level fragmentation/reassembly is still useful for very large messages (sadly). We fall back to PPID-based fragmentation/reassembly mode IFF a=max-message-size is not set in the SDP and the negotiated amount of SCTP inbound streams is exactly 256. Other implementations should avoid using this combination (to be precise, other implementations should send a=max-message-size). It also changes behaviour of RTCDataChannel.send which now raises TypeError in case the message is too large for the other peer to receive. This is a necessity to ensure that implementations that do not look at the EOR flag when receiving are always able to receive our messages. Even if these implementations do not set a=max-message-size, we use a safe default value (64 KiB, dictated by the spec) that every implementation should be able to receive, with or without EOR support. * Due to the use of explicit EOR, this required some major refactoring of all send-related and deferred sending functions (which is now a lot less complex). There's now only one place where `usrsctp_sendv` is being used. * All data channel messages and DCEP messages will be sent without copying them first. Only in case this fails (e.g. usrsctp's buffer is full), the message will be copied and added to a buffer queue. * Queued data channel messages will now be re-sent fairly (round-robin). * Maximum message size and the PPID-based fragmentation are configurable using about:config (media.peerconnection.sctp.force_ppid_fragmentation and media.peerconnection.sctp.force_maximum_message_size). * Enable interleaving of incoming messages for different streams (preparation for SCTP ndata, has no effect until it is enabled). * Enable interleaving of outgoing messages (disabled if SCTP ndata has not been negotiated). * Add pending messages flag to reduce performance impact from frequent calls to SendDeferredMessages. * Handle partial delivery events (for cases where a partially delivered message is being aborted). * Close a data channel/the connection in case the message is too large to be handled (this is only applied in cases where the remote peer ignores our announced local maximum message size). * Various size_t to uint32_t conversions (message length) and back should be safe now. * Remove aUsingDtls/mUsingDtls from DataChannelConnection. * Set maximum message size in SDP and in the data channel stack. * Replace implicit NS_ENSURE_*'s with explicit NS_WARN_IF's. * Add SetMaxMessageSize method for late-applying those signalling parameters when a data channel has been created before the remote SDP was available. * Limit remote maximum message size and add a GetMaxMessageSize method for a future implementation of RTCSctpTransport.maxMessageSize. MozReview-Commit-ID: FlmZrpC5zVI --HG-- extra : rebase_source : 54e1b838c788a3abbded4fb32fe7c2788f8a9bc0
2017-07-26 14:18:54 +03:00
mDataChannel->SendBinaryMsg(aMsgString, aRv);
} else {
Bug 979417 - Implement EOR when receiving and explicit EOR when sending on data channels (including DCEP). r=drno,jesup This allows sending and receiving arbitrarily (we limit to 1 GiB atm) sized messages while not relying on the deprecated PPID fragmentation/reassembly mode. The code already supports the ndata extension but it's not activated, yet. Without the SCTP ndata extension, a large data channel message will monopolise the SCTP association. While this is a problem, it is a temporary solution until the extension is being activated. Keep in mind that every application that uses data channels currently does fragmentation/reassembly on application-level and it's unlikely that this will change until the popular implementations (libwebrtc) implement EOR as well. Moreover, until the WebRTC API specifies an API that hands over partial messages, doing application-level fragmentation/reassembly is still useful for very large messages (sadly). We fall back to PPID-based fragmentation/reassembly mode IFF a=max-message-size is not set in the SDP and the negotiated amount of SCTP inbound streams is exactly 256. Other implementations should avoid using this combination (to be precise, other implementations should send a=max-message-size). It also changes behaviour of RTCDataChannel.send which now raises TypeError in case the message is too large for the other peer to receive. This is a necessity to ensure that implementations that do not look at the EOR flag when receiving are always able to receive our messages. Even if these implementations do not set a=max-message-size, we use a safe default value (64 KiB, dictated by the spec) that every implementation should be able to receive, with or without EOR support. * Due to the use of explicit EOR, this required some major refactoring of all send-related and deferred sending functions (which is now a lot less complex). There's now only one place where `usrsctp_sendv` is being used. * All data channel messages and DCEP messages will be sent without copying them first. Only in case this fails (e.g. usrsctp's buffer is full), the message will be copied and added to a buffer queue. * Queued data channel messages will now be re-sent fairly (round-robin). * Maximum message size and the PPID-based fragmentation are configurable using about:config (media.peerconnection.sctp.force_ppid_fragmentation and media.peerconnection.sctp.force_maximum_message_size). * Enable interleaving of incoming messages for different streams (preparation for SCTP ndata, has no effect until it is enabled). * Enable interleaving of outgoing messages (disabled if SCTP ndata has not been negotiated). * Add pending messages flag to reduce performance impact from frequent calls to SendDeferredMessages. * Handle partial delivery events (for cases where a partially delivered message is being aborted). * Close a data channel/the connection in case the message is too large to be handled (this is only applied in cases where the remote peer ignores our announced local maximum message size). * Various size_t to uint32_t conversions (message length) and back should be safe now. * Remove aUsingDtls/mUsingDtls from DataChannelConnection. * Set maximum message size in SDP and in the data channel stack. * Replace implicit NS_ENSURE_*'s with explicit NS_WARN_IF's. * Add SetMaxMessageSize method for late-applying those signalling parameters when a data channel has been created before the remote SDP was available. * Limit remote maximum message size and add a GetMaxMessageSize method for a future implementation of RTCSctpTransport.maxMessageSize. MozReview-Commit-ID: FlmZrpC5zVI --HG-- extra : rebase_source : 54e1b838c788a3abbded4fb32fe7c2788f8a9bc0
2017-07-26 14:18:54 +03:00
mDataChannel->SendMsg(aMsgString, aRv);
}
}
}
nsresult
nsDOMDataChannel::DoOnMessageAvailable(const nsACString& aData,
bool aBinary)
{
MOZ_ASSERT(NS_IsMainThread());
LOG(("DoOnMessageAvailable%s\n",aBinary ? ((mBinaryType == DC_BINARY_TYPE_BLOB) ? " (blob)" : " (binary)") : ""));
nsresult rv = CheckInnerWindowCorrectness();
if (NS_FAILED(rv)) {
return NS_OK;
}
AutoJSAPI jsapi;
if (NS_WARN_IF(!jsapi.Init(GetOwner()))) {
return NS_ERROR_FAILURE;
}
JSContext* cx = jsapi.cx();
JS::Rooted<JS::Value> jsData(cx);
if (aBinary) {
if (mBinaryType == DC_BINARY_TYPE_BLOB) {
RefPtr<Blob> blob =
Blob::CreateStringBlob(GetOwner(), aData, EmptyString());
MOZ_ASSERT(blob);
if (!ToJSValue(cx, blob, &jsData)) {
return NS_ERROR_FAILURE;
}
} else if (mBinaryType == DC_BINARY_TYPE_ARRAYBUFFER) {
JS::Rooted<JSObject*> arrayBuf(cx);
rv = nsContentUtils::CreateArrayBuffer(cx, aData, arrayBuf.address());
NS_ENSURE_SUCCESS(rv, rv);
jsData.setObject(*arrayBuf);
} else {
MOZ_CRASH("Unknown binary type!");
return NS_ERROR_UNEXPECTED;
}
} else {
NS_ConvertUTF8toUTF16 utf16data(aData);
JSString* jsString = JS_NewUCStringCopyN(cx, utf16data.get(), utf16data.Length());
NS_ENSURE_TRUE(jsString, NS_ERROR_FAILURE);
jsData.setString(jsString);
}
RefPtr<MessageEvent> event = new MessageEvent(this, nullptr, nullptr);
event->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), false, false,
jsData, mOrigin, EmptyString(), nullptr,
Sequence<OwningNonNull<MessagePort>>());
event->SetTrusted(true);
LOG(("%p(%p): %s - Dispatching\n",this,(void*)mDataChannel,__FUNCTION__));
bool dummy;
rv = DispatchEvent(static_cast<Event*>(event), &dummy);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to dispatch the message event!!!");
}
return rv;
}
nsresult
nsDOMDataChannel::OnMessageAvailable(nsISupports* aContext,
const nsACString& aMessage)
{
MOZ_ASSERT(NS_IsMainThread());
return DoOnMessageAvailable(aMessage, false);
}
nsresult
nsDOMDataChannel::OnBinaryMessageAvailable(nsISupports* aContext,
const nsACString& aMessage)
{
MOZ_ASSERT(NS_IsMainThread());
return DoOnMessageAvailable(aMessage, true);
}
nsresult
nsDOMDataChannel::OnSimpleEvent(nsISupports* aContext, const nsAString& aName)
{
MOZ_ASSERT(NS_IsMainThread());
nsresult rv = CheckInnerWindowCorrectness();
if (NS_FAILED(rv)) {
return NS_OK;
}
Bug 1207245 - part 6 - rename nsRefPtr<T> to RefPtr<T>; r=ehsan; a=Tomcat The bulk of this commit was generated with a script, executed at the top level of a typical source code checkout. The only non-machine-generated part was modifying MFBT's moz.build to reflect the new naming. CLOSED TREE makes big refactorings like this a piece of cake. # The main substitution. find . -name '*.cpp' -o -name '*.cc' -o -name '*.h' -o -name '*.mm' -o -name '*.idl'| \ xargs perl -p -i -e ' s/nsRefPtr\.h/RefPtr\.h/g; # handle includes s/nsRefPtr ?</RefPtr</g; # handle declarations and variables ' # Handle a special friend declaration in gfx/layers/AtomicRefCountedWithFinalize.h. perl -p -i -e 's/::nsRefPtr;/::RefPtr;/' gfx/layers/AtomicRefCountedWithFinalize.h # Handle nsRefPtr.h itself, a couple places that define constructors # from nsRefPtr, and code generators specially. We do this here, rather # than indiscriminantly s/nsRefPtr/RefPtr/, because that would rename # things like nsRefPtrHashtable. perl -p -i -e 's/nsRefPtr/RefPtr/g' \ mfbt/nsRefPtr.h \ xpcom/glue/nsCOMPtr.h \ xpcom/base/OwningNonNull.h \ ipc/ipdl/ipdl/lower.py \ ipc/ipdl/ipdl/builtin.py \ dom/bindings/Codegen.py \ python/lldbutils/lldbutils/utils.py # In our indiscriminate substitution above, we renamed # nsRefPtrGetterAddRefs, the class behind getter_AddRefs. Fix that up. find . -name '*.cpp' -o -name '*.h' -o -name '*.idl' | \ xargs perl -p -i -e 's/nsRefPtrGetterAddRefs/RefPtrGetterAddRefs/g' if [ -d .git ]; then git mv mfbt/nsRefPtr.h mfbt/RefPtr.h else hg mv mfbt/nsRefPtr.h mfbt/RefPtr.h fi --HG-- rename : mfbt/nsRefPtr.h => mfbt/RefPtr.h
2015-10-18 08:24:48 +03:00
RefPtr<Event> event = NS_NewDOMEvent(this, nullptr, nullptr);
event->InitEvent(aName, false, false);
event->SetTrusted(true);
bool dummy;
return DispatchEvent(event, &dummy);
}
nsresult
nsDOMDataChannel::OnChannelConnected(nsISupports* aContext)
{
LOG(("%p(%p): %s - Dispatching\n",this,(void*)mDataChannel,__FUNCTION__));
return OnSimpleEvent(aContext, NS_LITERAL_STRING("open"));
}
nsresult
nsDOMDataChannel::OnChannelClosed(nsISupports* aContext)
{
nsresult rv;
// so we don't have to worry if we're notified from different paths in
// the underlying code
if (!mSentClose) {
// Ok, we're done with it.
mDataChannel->ReleaseConnection();
LOG(("%p(%p): %s - Dispatching\n",this,(void*)mDataChannel,__FUNCTION__));
rv = OnSimpleEvent(aContext, NS_LITERAL_STRING("close"));
// no more events can happen
mSentClose = true;
} else {
rv = NS_OK;
}
DontKeepAliveAnyMore();
return rv;
}
nsresult
nsDOMDataChannel::OnBufferLow(nsISupports* aContext)
{
LOG(("%p(%p): %s - Dispatching\n",this,(void*)mDataChannel,__FUNCTION__));
return OnSimpleEvent(aContext, NS_LITERAL_STRING("bufferedamountlow"));
}
nsresult
nsDOMDataChannel::NotBuffered(nsISupports* aContext)
{
// In the rare case that we held off GC to let the buffer drain
UpdateMustKeepAlive();
return NS_OK;
}
void
nsDOMDataChannel::AppReady()
{
if (!mSentClose) { // may not be possible, simpler to just test anyways
mDataChannel->AppReady();
}
}
//-----------------------------------------------------------------------------
// Methods that keep alive the DataChannel object when:
// 1. the object has registered event listeners that can be triggered
// ("strong event listeners");
// 2. there are outgoing not sent messages.
//-----------------------------------------------------------------------------
void
nsDOMDataChannel::UpdateMustKeepAlive()
{
MOZ_ASSERT(NS_IsMainThread());
if (!mCheckMustKeepAlive) {
return;
}
bool shouldKeepAlive = false;
uint16_t readyState = mDataChannel->GetReadyState();
switch (readyState)
{
case DataChannel::CONNECTING:
case DataChannel::WAITING_TO_OPEN:
{
if (mListenerManager &&
(mListenerManager->HasListenersFor(nsGkAtoms::onopen) ||
mListenerManager->HasListenersFor(nsGkAtoms::onmessage) ||
mListenerManager->HasListenersFor(nsGkAtoms::onerror) ||
mListenerManager->HasListenersFor(nsGkAtoms::onbufferedamountlow) ||
mListenerManager->HasListenersFor(nsGkAtoms::onclose))) {
shouldKeepAlive = true;
}
}
break;
case DataChannel::OPEN:
case DataChannel::CLOSING:
{
if (mDataChannel->GetBufferedAmount() != 0 ||
(mListenerManager &&
(mListenerManager->HasListenersFor(nsGkAtoms::onmessage) ||
mListenerManager->HasListenersFor(nsGkAtoms::onerror) ||
mListenerManager->HasListenersFor(nsGkAtoms::onbufferedamountlow) ||
mListenerManager->HasListenersFor(nsGkAtoms::onclose)))) {
shouldKeepAlive = true;
}
}
break;
case DataChannel::CLOSED:
{
shouldKeepAlive = false;
}
}
if (mSelfRef && !shouldKeepAlive) {
ReleaseSelf();
} else if (!mSelfRef && shouldKeepAlive) {
mSelfRef = this;
}
}
void
nsDOMDataChannel::DontKeepAliveAnyMore()
{
MOZ_ASSERT(NS_IsMainThread());
if (mSelfRef) {
// Since we're on MainThread, force an eventloop trip to avoid deleting
// ourselves.
ReleaseSelf();
}
mCheckMustKeepAlive = false;
}
void
nsDOMDataChannel::ReleaseSelf()
{
// release our self-reference (safely) by putting it in an event (always)
NS_ReleaseOnMainThreadSystemGroup("nsDOMDataChannel::mSelfRef",
mSelfRef.forget(), true);
}
void
nsDOMDataChannel::EventListenerAdded(nsAtom* aType)
{
MOZ_ASSERT(NS_IsMainThread());
UpdateMustKeepAlive();
}
void
nsDOMDataChannel::EventListenerRemoved(nsAtom* aType)
{
MOZ_ASSERT(NS_IsMainThread());
UpdateMustKeepAlive();
}
/* static */
nsresult
NS_NewDOMDataChannel(already_AddRefed<mozilla::DataChannel>&& aDataChannel,
nsPIDOMWindowInner* aWindow,
nsIDOMDataChannel** aDomDataChannel)
{
Bug 1207245 - part 6 - rename nsRefPtr<T> to RefPtr<T>; r=ehsan; a=Tomcat The bulk of this commit was generated with a script, executed at the top level of a typical source code checkout. The only non-machine-generated part was modifying MFBT's moz.build to reflect the new naming. CLOSED TREE makes big refactorings like this a piece of cake. # The main substitution. find . -name '*.cpp' -o -name '*.cc' -o -name '*.h' -o -name '*.mm' -o -name '*.idl'| \ xargs perl -p -i -e ' s/nsRefPtr\.h/RefPtr\.h/g; # handle includes s/nsRefPtr ?</RefPtr</g; # handle declarations and variables ' # Handle a special friend declaration in gfx/layers/AtomicRefCountedWithFinalize.h. perl -p -i -e 's/::nsRefPtr;/::RefPtr;/' gfx/layers/AtomicRefCountedWithFinalize.h # Handle nsRefPtr.h itself, a couple places that define constructors # from nsRefPtr, and code generators specially. We do this here, rather # than indiscriminantly s/nsRefPtr/RefPtr/, because that would rename # things like nsRefPtrHashtable. perl -p -i -e 's/nsRefPtr/RefPtr/g' \ mfbt/nsRefPtr.h \ xpcom/glue/nsCOMPtr.h \ xpcom/base/OwningNonNull.h \ ipc/ipdl/ipdl/lower.py \ ipc/ipdl/ipdl/builtin.py \ dom/bindings/Codegen.py \ python/lldbutils/lldbutils/utils.py # In our indiscriminate substitution above, we renamed # nsRefPtrGetterAddRefs, the class behind getter_AddRefs. Fix that up. find . -name '*.cpp' -o -name '*.h' -o -name '*.idl' | \ xargs perl -p -i -e 's/nsRefPtrGetterAddRefs/RefPtrGetterAddRefs/g' if [ -d .git ]; then git mv mfbt/nsRefPtr.h mfbt/RefPtr.h else hg mv mfbt/nsRefPtr.h mfbt/RefPtr.h fi --HG-- rename : mfbt/nsRefPtr.h => mfbt/RefPtr.h
2015-10-18 08:24:48 +03:00
RefPtr<nsDOMDataChannel> domdc =
new nsDOMDataChannel(aDataChannel, aWindow);
nsresult rv = domdc->Init(aWindow);
NS_ENSURE_SUCCESS(rv,rv);
return CallQueryInterface(domdc, aDomDataChannel);
}
/* static */
void
NS_DataChannelAppReady(nsIDOMDataChannel* aDomDataChannel)
{
((nsDOMDataChannel *)aDomDataChannel)->AppReady();
}