1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "UDPSocketParent.h"
9 #include "nsComponentManagerUtils.h"
10 #include "nsIUDPSocket.h"
11 #include "nsINetAddr.h"
13 #include "mozilla/Unused.h"
14 #include "mozilla/dom/ContentParent.h"
15 #include "mozilla/ipc/InputStreamUtils.h"
16 #include "mozilla/net/DNS.h"
17 #include "mozilla/net/NeckoCommon.h"
18 #include "mozilla/net/PNeckoParent.h"
19 #include "nsIPermissionManager.h"
20 #include "mozilla/ipc/PBackgroundParent.h"
21 #include "transport/runnable_utils.h"
29 NS_IMPL_ISUPPORTS(UDPSocketParent
, nsIUDPSocketListener
)
31 UDPSocketParent::UDPSocketParent(PBackgroundParent
* aManager
)
32 : mBackgroundManager(aManager
), mIPCOpen(true) {}
34 UDPSocketParent::UDPSocketParent(PNeckoParent
* aManager
)
35 : mBackgroundManager(nullptr), mIPCOpen(true) {}
37 UDPSocketParent::~UDPSocketParent() = default;
39 bool UDPSocketParent::Init(nsIPrincipal
* aPrincipal
,
40 const nsACString
& aFilter
) {
41 MOZ_ASSERT_IF(mBackgroundManager
, !aPrincipal
);
42 // will be used once we move all UDPSocket to PBackground, or
43 // if we add in Principal checking for dom/media/webrtc/transport
44 Unused
<< mBackgroundManager
;
46 mPrincipal
= aPrincipal
;
48 if (!aFilter
.IsEmpty()) {
49 nsAutoCString
contractId(NS_NETWORK_UDP_SOCKET_FILTER_HANDLER_PREFIX
);
50 contractId
.Append(aFilter
);
51 nsCOMPtr
<nsISocketFilterHandler
> filterHandler
=
52 do_GetService(contractId
.get());
54 nsresult rv
= filterHandler
->NewFilter(getter_AddRefs(mFilter
));
57 "Cannot create filter that content specified. "
58 "filter name: %s, error code: %u.",
59 aFilter
.BeginReading(), static_cast<uint32_t>(rv
));
64 "Content doesn't have a valid filter. "
66 aFilter
.BeginReading());
74 // PUDPSocketParent methods
76 mozilla::ipc::IPCResult
UDPSocketParent::RecvBind(
77 const UDPAddressInfo
& aAddressInfo
, const bool& aAddressReuse
,
78 const bool& aLoopback
, const uint32_t& recvBufferSize
,
79 const uint32_t& sendBufferSize
) {
80 UDPSOCKET_LOG(("%s: %s:%u", __FUNCTION__
, aAddressInfo
.addr().get(),
81 aAddressInfo
.port()));
83 if (NS_FAILED(BindInternal(aAddressInfo
.addr(), aAddressInfo
.port(),
84 aAddressReuse
, aLoopback
, recvBufferSize
,
86 FireInternalError(__LINE__
);
90 nsCOMPtr
<nsINetAddr
> localAddr
;
91 mSocket
->GetLocalAddr(getter_AddRefs(localAddr
));
94 if (NS_FAILED(localAddr
->GetAddress(addr
))) {
95 FireInternalError(__LINE__
);
100 if (NS_FAILED(localAddr
->GetPort(&port
))) {
101 FireInternalError(__LINE__
);
106 ("%s: SendCallbackOpened: %s:%u", __FUNCTION__
, addr
.get(), port
));
107 mAddress
= {addr
, port
};
108 mozilla::Unused
<< SendCallbackOpened(UDPAddressInfo(addr
, port
));
113 nsresult
UDPSocketParent::BindInternal(const nsCString
& aHost
,
114 const uint16_t& aPort
,
115 const bool& aAddressReuse
,
116 const bool& aLoopback
,
117 const uint32_t& recvBufferSize
,
118 const uint32_t& sendBufferSize
) {
122 ("%s: [this=%p] %s:%u addressReuse: %d loopback: %d recvBufferSize: "
123 "%" PRIu32
", sendBufferSize: %" PRIu32
,
124 __FUNCTION__
, this, nsCString(aHost
).get(), aPort
, aAddressReuse
,
125 aLoopback
, recvBufferSize
, sendBufferSize
));
127 nsCOMPtr
<nsIUDPSocket
> sock
=
128 do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv
);
130 if (NS_WARN_IF(NS_FAILED(rv
))) {
134 if (aHost
.IsEmpty()) {
135 rv
= sock
->Init(aPort
, false, mPrincipal
, aAddressReuse
,
136 /* optional_argc = */ 1);
139 PR_InitializeNetAddr(PR_IpAddrAny
, aPort
, &prAddr
);
140 PRStatus status
= PR_StringToNetAddr(aHost
.BeginReading(), &prAddr
);
141 if (status
!= PR_SUCCESS
) {
142 return NS_ERROR_FAILURE
;
145 mozilla::net::NetAddr
addr(&prAddr
);
146 rv
= sock
->InitWithAddress(&addr
, mPrincipal
, aAddressReuse
,
147 /* optional_argc = */ 1);
150 if (NS_WARN_IF(NS_FAILED(rv
))) {
154 nsCOMPtr
<nsINetAddr
> laddr
;
155 rv
= sock
->GetLocalAddr(getter_AddRefs(laddr
));
156 if (NS_WARN_IF(NS_FAILED(rv
))) {
160 rv
= laddr
->GetFamily(&family
);
161 if (NS_WARN_IF(NS_FAILED(rv
))) {
164 if (family
== nsINetAddr::FAMILY_INET
) {
165 rv
= sock
->SetMulticastLoopback(aLoopback
);
166 if (NS_WARN_IF(NS_FAILED(rv
))) {
170 // TODO: once bug 1252759 is fixed query buffer first and only increase
171 if (recvBufferSize
!= 0) {
172 rv
= sock
->SetRecvBufferSize(recvBufferSize
);
173 if (NS_WARN_IF(NS_FAILED(rv
))) {
175 ("%s: [this=%p] %s:%u failed to set recv buffer size to: %" PRIu32
,
176 __FUNCTION__
, this, nsCString(aHost
).get(), aPort
, recvBufferSize
));
179 if (sendBufferSize
!= 0) {
180 rv
= sock
->SetSendBufferSize(sendBufferSize
);
181 if (NS_WARN_IF(NS_FAILED(rv
))) {
183 ("%s: [this=%p] %s:%u failed to set send buffer size to: %" PRIu32
,
184 __FUNCTION__
, this, nsCString(aHost
).get(), aPort
, sendBufferSize
));
189 rv
= sock
->AsyncListen(this);
190 if (NS_WARN_IF(NS_FAILED(rv
))) {
199 static nsCOMPtr
<nsIEventTarget
> GetSTSThread() {
202 nsCOMPtr
<nsIEventTarget
> sts_thread
;
204 sts_thread
= do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID
, &rv
);
205 MOZ_ASSERT(NS_SUCCEEDED(rv
));
210 static void CheckSTSThread() {
211 DebugOnly
<nsCOMPtr
<nsIEventTarget
>> sts_thread
= GetSTSThread();
213 ASSERT_ON_THREAD(sts_thread
.value
);
216 // Proxy the Connect() request to the STS thread, since it may block and
217 // should be done there.
218 mozilla::ipc::IPCResult
UDPSocketParent::RecvConnect(
219 const UDPAddressInfo
& aAddressInfo
) {
220 nsCOMPtr
<nsIEventTarget
> target
= GetCurrentSerialEventTarget();
221 Unused
<< NS_WARN_IF(NS_FAILED(GetSTSThread()->Dispatch(
222 WrapRunnable(RefPtr
<UDPSocketParent
>(this), &UDPSocketParent::DoConnect
,
223 mSocket
, target
, aAddressInfo
),
224 NS_DISPATCH_NORMAL
)));
228 void UDPSocketParent::DoSendConnectResponse(
229 const UDPAddressInfo
& aAddressInfo
) {
230 // can't use directly with WrapRunnable due to warnings
231 mozilla::Unused
<< SendCallbackConnected(aAddressInfo
);
234 void UDPSocketParent::SendConnectResponse(
235 const nsCOMPtr
<nsIEventTarget
>& aThread
,
236 const UDPAddressInfo
& aAddressInfo
) {
237 Unused
<< NS_WARN_IF(NS_FAILED(aThread
->Dispatch(
238 WrapRunnable(RefPtr
<UDPSocketParent
>(this),
239 &UDPSocketParent::DoSendConnectResponse
, aAddressInfo
),
240 NS_DISPATCH_NORMAL
)));
243 // Runs on STS thread
244 void UDPSocketParent::DoConnect(const nsCOMPtr
<nsIUDPSocket
>& aSocket
,
245 const nsCOMPtr
<nsIEventTarget
>& aReturnThread
,
246 const UDPAddressInfo
& aAddressInfo
) {
247 UDPSOCKET_LOG(("%s: %s:%u", __FUNCTION__
, aAddressInfo
.addr().get(),
248 aAddressInfo
.port()));
249 if (NS_FAILED(ConnectInternal(aAddressInfo
.addr(), aAddressInfo
.port()))) {
250 SendInternalError(aReturnThread
, __LINE__
);
255 nsCOMPtr
<nsINetAddr
> localAddr
;
256 aSocket
->GetLocalAddr(getter_AddRefs(localAddr
));
259 if (NS_FAILED(localAddr
->GetAddress(addr
))) {
260 SendInternalError(aReturnThread
, __LINE__
);
265 if (NS_FAILED(localAddr
->GetPort(&port
))) {
266 SendInternalError(aReturnThread
, __LINE__
);
271 ("%s: SendConnectResponse: %s:%u", __FUNCTION__
, addr
.get(), port
));
272 SendConnectResponse(aReturnThread
, UDPAddressInfo(addr
, port
));
275 nsresult
UDPSocketParent::ConnectInternal(const nsCString
& aHost
,
276 const uint16_t& aPort
) {
279 UDPSOCKET_LOG(("%s: %s:%u", __FUNCTION__
, nsCString(aHost
).get(), aPort
));
282 return NS_ERROR_NOT_AVAILABLE
;
286 memset(&prAddr
, 0, sizeof(prAddr
));
287 PR_InitializeNetAddr(PR_IpAddrAny
, aPort
, &prAddr
);
288 PRStatus status
= PR_StringToNetAddr(aHost
.BeginReading(), &prAddr
);
289 if (status
!= PR_SUCCESS
) {
290 return NS_ERROR_FAILURE
;
293 mozilla::net::NetAddr
addr(&prAddr
);
294 rv
= mSocket
->Connect(&addr
);
295 if (NS_WARN_IF(NS_FAILED(rv
))) {
302 mozilla::ipc::IPCResult
UDPSocketParent::RecvOutgoingData(
303 const UDPData
& aData
, const UDPSocketAddr
& aAddr
) {
305 NS_WARNING("sending socket is closed");
306 FireInternalError(__LINE__
);
312 if (aAddr
.type() != UDPSocketAddr::TNetAddr
) {
316 // TODO, Packet filter doesn't support input stream yet.
317 if (aData
.type() != UDPData::TArrayOfuint8_t
) {
322 const nsTArray
<uint8_t>& data(aData
.get_ArrayOfuint8_t());
323 UDPSOCKET_LOG(("%s(%s:%d): Filtering outgoing packet", __FUNCTION__
,
324 mAddress
.addr().get(), mAddress
.port()));
326 rv
= mFilter
->FilterPacket(&aAddr
.get_NetAddr(), data
.Elements(),
327 data
.Length(), nsISocketFilter::SF_OUTGOING
,
330 // Sending unallowed data, kill content.
331 if (NS_WARN_IF(NS_FAILED(rv
)) || !allowed
) {
332 return IPC_FAIL(this, "Content tried to send non STUN packet");
336 switch (aData
.type()) {
337 case UDPData::TArrayOfuint8_t
:
338 Send(aData
.get_ArrayOfuint8_t(), aAddr
);
340 case UDPData::TIPCStream
:
341 Send(aData
.get_IPCStream(), aAddr
);
344 MOZ_ASSERT(false, "Invalid data type!");
351 void UDPSocketParent::Send(const nsTArray
<uint8_t>& aData
,
352 const UDPSocketAddr
& aAddr
) {
355 switch (aAddr
.type()) {
356 case UDPSocketAddr::TUDPAddressInfo
: {
357 const UDPAddressInfo
& addrInfo(aAddr
.get_UDPAddressInfo());
358 rv
= mSocket
->Send(addrInfo
.addr(), addrInfo
.port(), aData
, &count
);
361 case UDPSocketAddr::TNetAddr
: {
362 const NetAddr
& addr(aAddr
.get_NetAddr());
363 rv
= mSocket
->SendWithAddress(&addr
, aData
.Elements(), aData
.Length(),
368 MOZ_ASSERT(false, "Invalid address type!");
372 if (NS_WARN_IF(NS_FAILED(rv
)) || count
== 0) {
373 FireInternalError(__LINE__
);
377 void UDPSocketParent::Send(const IPCStream
& aStream
,
378 const UDPSocketAddr
& aAddr
) {
379 nsCOMPtr
<nsIInputStream
> stream
= DeserializeIPCStream(aStream
);
381 if (NS_WARN_IF(!stream
)) {
386 switch (aAddr
.type()) {
387 case UDPSocketAddr::TUDPAddressInfo
: {
388 const UDPAddressInfo
& addrInfo(aAddr
.get_UDPAddressInfo());
389 rv
= mSocket
->SendBinaryStream(addrInfo
.addr(), addrInfo
.port(), stream
);
392 case UDPSocketAddr::TNetAddr
: {
393 const NetAddr
& addr(aAddr
.get_NetAddr());
394 rv
= mSocket
->SendBinaryStreamWithAddress(&addr
, stream
);
398 MOZ_ASSERT(false, "Invalid address type!");
403 FireInternalError(__LINE__
);
407 mozilla::ipc::IPCResult
UDPSocketParent::RecvJoinMulticast(
408 const nsCString
& aMulticastAddress
, const nsCString
& aInterface
) {
410 NS_WARNING("multicast socket is closed");
411 FireInternalError(__LINE__
);
415 nsresult rv
= mSocket
->JoinMulticast(aMulticastAddress
, aInterface
);
417 if (NS_WARN_IF(NS_FAILED(rv
))) {
418 FireInternalError(__LINE__
);
424 mozilla::ipc::IPCResult
UDPSocketParent::RecvLeaveMulticast(
425 const nsCString
& aMulticastAddress
, const nsCString
& aInterface
) {
427 NS_WARNING("multicast socket is closed");
428 FireInternalError(__LINE__
);
432 nsresult rv
= mSocket
->LeaveMulticast(aMulticastAddress
, aInterface
);
434 if (NS_WARN_IF(NS_FAILED(rv
))) {
435 FireInternalError(__LINE__
);
441 mozilla::ipc::IPCResult
UDPSocketParent::RecvClose() {
446 nsresult rv
= mSocket
->Close();
449 mozilla::Unused
<< NS_WARN_IF(NS_FAILED(rv
));
454 mozilla::ipc::IPCResult
UDPSocketParent::RecvRequestDelete() {
455 mozilla::Unused
<< Send__delete__(this);
459 void UDPSocketParent::ActorDestroy(ActorDestroyReason why
) {
460 MOZ_ASSERT(mIPCOpen
);
468 // nsIUDPSocketListener
471 UDPSocketParent::OnPacketReceived(nsIUDPSocket
* aSocket
,
472 nsIUDPMessage
* aMessage
) {
473 // receiving packet from remote host, forward the message content to child
481 nsCOMPtr
<nsINetAddr
> fromAddr
;
482 aMessage
->GetFromAddr(getter_AddRefs(fromAddr
));
483 fromAddr
->GetPort(&port
);
484 fromAddr
->GetAddress(ip
);
487 aMessage
->GetData(data
);
489 const char* buffer
= data
.get();
490 uint32_t len
= data
.Length();
491 UDPSOCKET_LOG(("%s: %s:%u, length %u", __FUNCTION__
, ip
.get(), port
, len
));
495 mozilla::net::NetAddr addr
;
496 fromAddr
->GetNetAddr(&addr
);
497 UDPSOCKET_LOG(("%s(%s:%d): Filtering incoming packet", __FUNCTION__
,
498 mAddress
.addr().get(), mAddress
.port()));
499 nsresult rv
= mFilter
->FilterPacket(&addr
, (const uint8_t*)buffer
, len
,
500 nsISocketFilter::SF_INCOMING
, &allowed
);
501 // Receiving unallowed data, drop.
502 if (NS_WARN_IF(NS_FAILED(rv
)) || !allowed
) {
504 UDPSOCKET_LOG(("%s: not allowed", __FUNCTION__
));
510 FallibleTArray
<uint8_t> fallibleArray
;
511 if (!fallibleArray
.InsertElementsAt(0, buffer
, len
, fallible
)) {
512 FireInternalError(__LINE__
);
513 return NS_ERROR_OUT_OF_MEMORY
;
515 nsTArray
<uint8_t> infallibleArray
{std::move(fallibleArray
)};
518 mozilla::Unused
<< SendCallbackReceivedData(UDPAddressInfo(ip
, port
),
525 UDPSocketParent::OnStopListening(nsIUDPSocket
* aSocket
, nsresult aStatus
) {
526 // underlying socket is dead, send state update to child process
528 mozilla::Unused
<< SendCallbackClosed();
533 void UDPSocketParent::FireInternalError(uint32_t aLineNo
) {
538 mozilla::Unused
<< SendCallbackError("Internal error"_ns
,
539 nsLiteralCString(__FILE__
), aLineNo
);
542 void UDPSocketParent::SendInternalError(const nsCOMPtr
<nsIEventTarget
>& aThread
,
544 UDPSOCKET_LOG(("SendInternalError: %u", aLineNo
));
545 Unused
<< NS_WARN_IF(NS_FAILED(aThread
->Dispatch(
546 WrapRunnable(RefPtr
<UDPSocketParent
>(this),
547 &UDPSocketParent::FireInternalError
, aLineNo
),
548 NS_DISPATCH_NORMAL
)));
552 } // namespace mozilla