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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
|
/* -*- 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 "TCPSocketParent.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "nsJSUtils.h"
#include "mozilla/Unused.h"
#include "mozilla/AppProcessChecker.h"
#include "mozilla/net/NeckoCommon.h"
#include "mozilla/net/PNeckoParent.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/TabParent.h"
#include "mozilla/HoldDropJSObjects.h"
#include "nsISocketTransportService.h"
#include "nsISocketTransport.h"
#include "nsIScriptSecurityManager.h"
#include "nsNetUtil.h"
namespace IPC {
//Defined in TCPSocketChild.cpp
extern bool
DeserializeArrayBuffer(JSContext* aCx,
const InfallibleTArray<uint8_t>& aBuffer,
JS::MutableHandle<JS::Value> aVal);
} // namespace IPC
namespace mozilla {
namespace net {
//
// set MOZ_LOG=TCPSocket:5
//
extern LazyLogModule gTCPSocketLog;
#define TCPSOCKET_LOG(args) MOZ_LOG(gTCPSocketLog, LogLevel::Debug, args)
#define TCPSOCKET_LOG_ENABLED() MOZ_LOG_TEST(gTCPSocketLog, LogLevel::Debug)
} // namespace net
namespace dom {
static void
FireInteralError(mozilla::net::PTCPSocketParent* aActor, uint32_t aLineNo)
{
mozilla::Unused <<
aActor->SendCallback(NS_LITERAL_STRING("onerror"),
TCPError(NS_LITERAL_STRING("InvalidStateError"), NS_LITERAL_STRING("Internal error")),
static_cast<uint32_t>(TCPReadyState::Connecting));
}
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TCPSocketParentBase)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION(TCPSocketParentBase, mSocket)
NS_IMPL_CYCLE_COLLECTING_ADDREF(TCPSocketParentBase)
NS_IMPL_CYCLE_COLLECTING_RELEASE(TCPSocketParentBase)
TCPSocketParentBase::TCPSocketParentBase()
: mIPCOpen(false)
{
}
TCPSocketParentBase::~TCPSocketParentBase()
{
}
uint32_t
TCPSocketParent::GetAppId()
{
const PContentParent *content = Manager()->Manager();
if (PBrowserParent* browser = SingleManagedOrNull(content->ManagedPBrowserParent())) {
TabParent *tab = TabParent::GetFrom(browser);
return tab->OwnAppId();
} else {
return nsIScriptSecurityManager::UNKNOWN_APP_ID;
}
};
bool
TCPSocketParent::GetInIsolatedMozBrowser()
{
const PContentParent *content = Manager()->Manager();
if (PBrowserParent* browser = SingleManagedOrNull(content->ManagedPBrowserParent())) {
TabParent *tab = TabParent::GetFrom(browser);
return tab->IsIsolatedMozBrowserElement();
} else {
return false;
}
}
void
TCPSocketParentBase::ReleaseIPDLReference()
{
MOZ_ASSERT(mIPCOpen);
mIPCOpen = false;
this->Release();
}
void
TCPSocketParentBase::AddIPDLReference()
{
MOZ_ASSERT(!mIPCOpen);
mIPCOpen = true;
this->AddRef();
}
NS_IMETHODIMP_(MozExternalRefCountType) TCPSocketParent::Release(void)
{
nsrefcnt refcnt = TCPSocketParentBase::Release();
if (refcnt == 1 && mIPCOpen) {
mozilla::Unused << PTCPSocketParent::SendRequestDelete();
return 1;
}
return refcnt;
}
bool
TCPSocketParent::RecvOpen(const nsString& aHost, const uint16_t& aPort, const bool& aUseSSL,
const bool& aUseArrayBuffers)
{
// We don't have browser actors in xpcshell, and hence can't run automated
// tests without this loophole.
if (net::UsingNeckoIPCSecurity() &&
!AssertAppProcessPermission(Manager()->Manager(), "tcp-socket")) {
FireInteralError(this, __LINE__);
return true;
}
// Obtain App ID
uint32_t appId = GetAppId();
bool inIsolatedMozBrowser = GetInIsolatedMozBrowser();
mSocket = new TCPSocket(nullptr, aHost, aPort, aUseSSL, aUseArrayBuffers);
mSocket->SetAppIdAndBrowser(appId, inIsolatedMozBrowser);
mSocket->SetSocketBridgeParent(this);
NS_ENSURE_SUCCESS(mSocket->Init(), true);
return true;
}
bool
TCPSocketParent::RecvOpenBind(const nsCString& aRemoteHost,
const uint16_t& aRemotePort,
const nsCString& aLocalAddr,
const uint16_t& aLocalPort,
const bool& aUseSSL,
const bool& aUseArrayBuffers,
const nsCString& aFilter)
{
if (net::UsingNeckoIPCSecurity() &&
!AssertAppProcessPermission(Manager()->Manager(), "tcp-socket")) {
FireInteralError(this, __LINE__);
return true;
}
nsresult rv;
nsCOMPtr<nsISocketTransportService> sts =
do_GetService("@mozilla.org/network/socket-transport-service;1", &rv);
if (NS_FAILED(rv)) {
FireInteralError(this, __LINE__);
return true;
}
nsCOMPtr<nsISocketTransport> socketTransport;
rv = sts->CreateTransport(nullptr, 0,
aRemoteHost, aRemotePort,
nullptr, getter_AddRefs(socketTransport));
if (NS_FAILED(rv)) {
FireInteralError(this, __LINE__);
return true;
}
PRNetAddr prAddr;
if (PR_SUCCESS != PR_InitializeNetAddr(PR_IpAddrAny, aLocalPort, &prAddr)) {
FireInteralError(this, __LINE__);
return true;
}
if (PR_SUCCESS != PR_StringToNetAddr(aLocalAddr.BeginReading(), &prAddr)) {
FireInteralError(this, __LINE__);
return true;
}
mozilla::net::NetAddr addr;
PRNetAddrToNetAddr(&prAddr, &addr);
rv = socketTransport->Bind(&addr);
if (NS_FAILED(rv)) {
FireInteralError(this, __LINE__);
return true;
}
if (!aFilter.IsEmpty()) {
nsAutoCString contractId(NS_NETWORK_TCP_SOCKET_FILTER_HANDLER_PREFIX);
contractId.Append(aFilter);
nsCOMPtr<nsISocketFilterHandler> filterHandler =
do_GetService(contractId.get());
if (!filterHandler) {
NS_ERROR("Content doesn't have a valid filter");
FireInteralError(this, __LINE__);
return true;
}
rv = filterHandler->NewFilter(getter_AddRefs(mFilter));
if (NS_FAILED(rv)) {
NS_ERROR("Cannot create filter that content specified");
FireInteralError(this, __LINE__);
return true;
}
}
// Obtain App ID
uint32_t appId = nsIScriptSecurityManager::NO_APP_ID;
bool inIsolatedMozBrowser = false;
const PContentParent *content = Manager()->Manager();
if (PBrowserParent* browser = SingleManagedOrNull(content->ManagedPBrowserParent())) {
// appId's are for B2G only currently, where managees.Count() == 1
// This is not guaranteed currently in Desktop, so skip this there.
TabParent *tab = TabParent::GetFrom(browser);
appId = tab->OwnAppId();
inIsolatedMozBrowser = tab->IsIsolatedMozBrowserElement();
}
mSocket = new TCPSocket(nullptr, NS_ConvertUTF8toUTF16(aRemoteHost), aRemotePort, aUseSSL, aUseArrayBuffers);
mSocket->SetAppIdAndBrowser(appId, inIsolatedMozBrowser);
mSocket->SetSocketBridgeParent(this);
rv = mSocket->InitWithUnconnectedTransport(socketTransport);
NS_ENSURE_SUCCESS(rv, true);
return true;
}
bool
TCPSocketParent::RecvStartTLS()
{
NS_ENSURE_TRUE(mSocket, true);
ErrorResult rv;
mSocket->UpgradeToSecure(rv);
if (NS_WARN_IF(rv.Failed())) {
rv.SuppressException();
}
return true;
}
bool
TCPSocketParent::RecvSuspend()
{
NS_ENSURE_TRUE(mSocket, true);
mSocket->Suspend();
return true;
}
bool
TCPSocketParent::RecvResume()
{
NS_ENSURE_TRUE(mSocket, true);
ErrorResult rv;
mSocket->Resume(rv);
if (NS_WARN_IF(rv.Failed())) {
rv.SuppressException();
}
return true;
}
bool
TCPSocketParent::RecvData(const SendableData& aData,
const uint32_t& aTrackingNumber)
{
ErrorResult rv;
if (mFilter) {
mozilla::net::NetAddr addr; // dummy value
bool allowed;
MOZ_ASSERT(aData.type() == SendableData::TArrayOfuint8_t,
"Unsupported data type for filtering");
const InfallibleTArray<uint8_t>& data(aData.get_ArrayOfuint8_t());
nsresult nsrv = mFilter->FilterPacket(&addr, data.Elements(),
data.Length(),
nsISocketFilter::SF_OUTGOING,
&allowed);
// Reject sending of unallowed data
if (NS_WARN_IF(NS_FAILED(nsrv)) || !allowed) {
TCPSOCKET_LOG(("%s: Dropping outgoing TCP packet", __FUNCTION__));
return false;
}
}
switch (aData.type()) {
case SendableData::TArrayOfuint8_t: {
AutoSafeJSContext autoCx;
JS::Rooted<JS::Value> val(autoCx);
const nsTArray<uint8_t>& buffer = aData.get_ArrayOfuint8_t();
bool ok = IPC::DeserializeArrayBuffer(autoCx, buffer, &val);
NS_ENSURE_TRUE(ok, true);
RootedTypedArray<ArrayBuffer> data(autoCx);
data.Init(&val.toObject());
Optional<uint32_t> byteLength(buffer.Length());
mSocket->SendWithTrackingNumber(autoCx, data, 0, byteLength, aTrackingNumber, rv);
break;
}
case SendableData::TnsCString: {
const nsCString& strData = aData.get_nsCString();
mSocket->SendWithTrackingNumber(strData, aTrackingNumber, rv);
break;
}
default:
MOZ_CRASH("unexpected SendableData type");
}
NS_ENSURE_SUCCESS(rv.StealNSResult(), true);
return true;
}
bool
TCPSocketParent::RecvClose()
{
NS_ENSURE_TRUE(mSocket, true);
mSocket->Close();
return true;
}
void
TCPSocketParent::FireErrorEvent(const nsAString& aName, const nsAString& aType, TCPReadyState aReadyState)
{
SendEvent(NS_LITERAL_STRING("error"), TCPError(nsString(aName), nsString(aType)), aReadyState);
}
void
TCPSocketParent::FireEvent(const nsAString& aType, TCPReadyState aReadyState)
{
return SendEvent(aType, mozilla::void_t(), aReadyState);
}
void
TCPSocketParent::FireArrayBufferDataEvent(nsTArray<uint8_t>& aBuffer, TCPReadyState aReadyState)
{
InfallibleTArray<uint8_t> arr;
arr.SwapElements(aBuffer);
if (mFilter) {
bool allowed;
mozilla::net::NetAddr addr;
nsresult nsrv = mFilter->FilterPacket(&addr, arr.Elements(), arr.Length(),
nsISocketFilter::SF_INCOMING,
&allowed);
// receiving unallowed data, drop it.
if (NS_WARN_IF(NS_FAILED(nsrv)) || !allowed) {
TCPSOCKET_LOG(("%s: Dropping incoming TCP packet", __FUNCTION__));
return;
}
}
SendableData data(arr);
SendEvent(NS_LITERAL_STRING("data"), data, aReadyState);
}
void
TCPSocketParent::FireStringDataEvent(const nsACString& aData, TCPReadyState aReadyState)
{
SendableData data((nsCString(aData)));
MOZ_ASSERT(!mFilter, "Socket filtering doesn't support nsCString");
SendEvent(NS_LITERAL_STRING("data"), data, aReadyState);
}
void
TCPSocketParent::SendEvent(const nsAString& aType, CallbackData aData, TCPReadyState aReadyState)
{
if (mIPCOpen) {
mozilla::Unused << PTCPSocketParent::SendCallback(nsString(aType),
aData,
static_cast<uint32_t>(aReadyState));
}
}
void
TCPSocketParent::SetSocket(TCPSocket *socket)
{
mSocket = socket;
}
nsresult
TCPSocketParent::GetHost(nsAString& aHost)
{
if (!mSocket) {
NS_ERROR("No internal socket instance mSocket!");
return NS_ERROR_FAILURE;
}
mSocket->GetHost(aHost);
return NS_OK;
}
nsresult
TCPSocketParent::GetPort(uint16_t* aPort)
{
if (!mSocket) {
NS_ERROR("No internal socket instance mSocket!");
return NS_ERROR_FAILURE;
}
*aPort = mSocket->Port();
return NS_OK;
}
void
TCPSocketParent::ActorDestroy(ActorDestroyReason why)
{
if (mSocket) {
mSocket->Close();
}
mSocket = nullptr;
}
bool
TCPSocketParent::RecvRequestDelete()
{
mozilla::Unused << Send__delete__(this);
return true;
}
} // namespace dom
} // namespace mozilla
|