summaryrefslogtreecommitdiffstats
path: root/netwerk/test/gtest/TestUDPSocket.cpp
blob: 84d26fbedf04c3babcf064cecec4cc42e64ba332 (plain)
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
/* 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 "TestCommon.h"
#include "gtest/gtest.h"
#include "nsIUDPSocket.h"
#include "nsISocketTransport.h"
#include "nsIOutputStream.h"
#include "nsINetAddr.h"
#include "nsITimer.h"
#include "nsContentUtils.h"
#include "mozilla/net/DNS.h"
#include "prerror.h"

#define REQUEST 0x68656c6f
#define RESPONSE 0x6f6c6568
#define MULTICAST_TIMEOUT 2000

enum TestPhase { TEST_OUTPUT_STREAM, TEST_SEND_API, TEST_MULTICAST, TEST_NONE };

static TestPhase phase = TEST_NONE;

static bool CheckMessageContent(nsIUDPMessage* aMessage,
                                uint32_t aExpectedContent) {
  nsCString data;
  aMessage->GetData(data);

  const char* buffer = data.get();
  uint32_t len = data.Length();

  FallibleTArray<uint8_t>& rawData = aMessage->GetDataAsTArray();
  uint32_t rawLen = rawData.Length();

  if (len != rawLen) {
    ADD_FAILURE() << "Raw data length " << rawLen
                  << " does not match String data length " << len;
    return false;
  }

  for (uint32_t i = 0; i < len; i++) {
    if (buffer[i] != rawData[i]) {
      ADD_FAILURE();
      return false;
    }
  }

  uint32_t input = 0;
  for (uint32_t i = 0; i < len; i++) {
    input += buffer[i] << (8 * i);
  }

  if (len != sizeof(uint32_t)) {
    ADD_FAILURE() << "Message length mismatch, expected " << sizeof(uint32_t)
                  << " got " << len;
    return false;
  }
  if (input != aExpectedContent) {
    ADD_FAILURE() << "Message content mismatch, expected 0x" << std::hex
                  << aExpectedContent << " got 0x" << input;
    return false;
  }

  return true;
}

/*
 * UDPClientListener: listens for incomming UDP packets
 */
class UDPClientListener : public nsIUDPSocketListener {
 protected:
  virtual ~UDPClientListener();

 public:
  explicit UDPClientListener(WaitForCondition* waiter) : mWaiter(waiter) {}

  NS_DECL_THREADSAFE_ISUPPORTS
  NS_DECL_NSIUDPSOCKETLISTENER
  nsresult mResult = NS_ERROR_FAILURE;
  RefPtr<WaitForCondition> mWaiter;
};

NS_IMPL_ISUPPORTS(UDPClientListener, nsIUDPSocketListener)

UDPClientListener::~UDPClientListener() = default;

NS_IMETHODIMP
UDPClientListener::OnPacketReceived(nsIUDPSocket* socket,
                                    nsIUDPMessage* message) {
  mResult = NS_OK;

  uint16_t port;
  nsCString ip;
  nsCOMPtr<nsINetAddr> fromAddr;
  message->GetFromAddr(getter_AddRefs(fromAddr));
  fromAddr->GetPort(&port);
  fromAddr->GetAddress(ip);

  if (TEST_SEND_API == phase && CheckMessageContent(message, REQUEST)) {
    uint32_t count;
    nsTArray<uint8_t> data;
    const uint32_t dataBuffer = RESPONSE;
    data.AppendElements((const uint8_t*)&dataBuffer, sizeof(uint32_t));
    mResult = socket->SendWithAddr(fromAddr, data, &count);
    if (mResult == NS_OK && count == sizeof(uint32_t)) {
      SUCCEED();
    } else {
      ADD_FAILURE();
    }
    return NS_OK;
  } else if (TEST_OUTPUT_STREAM != phase ||
             !CheckMessageContent(message, RESPONSE)) {
    mResult = NS_ERROR_FAILURE;
  }

  // Notify thread
  mWaiter->Notify();
  return NS_OK;
}

NS_IMETHODIMP
UDPClientListener::OnStopListening(nsIUDPSocket*, nsresult) {
  mWaiter->Notify();
  return NS_OK;
}

/*
 * UDPServerListener: listens for incomming UDP packets
 */
class UDPServerListener : public nsIUDPSocketListener {
 protected:
  virtual ~UDPServerListener();

 public:
  explicit UDPServerListener(WaitForCondition* waiter) : mWaiter(waiter) {}

  NS_DECL_THREADSAFE_ISUPPORTS
  NS_DECL_NSIUDPSOCKETLISTENER

  nsresult mResult = NS_ERROR_FAILURE;
  RefPtr<WaitForCondition> mWaiter;
};

NS_IMPL_ISUPPORTS(UDPServerListener, nsIUDPSocketListener)

UDPServerListener::~UDPServerListener() = default;

NS_IMETHODIMP
UDPServerListener::OnPacketReceived(nsIUDPSocket* socket,
                                    nsIUDPMessage* message) {
  mResult = NS_OK;

  uint16_t port;
  nsCString ip;
  nsCOMPtr<nsINetAddr> fromAddr;
  message->GetFromAddr(getter_AddRefs(fromAddr));
  fromAddr->GetPort(&port);
  fromAddr->GetAddress(ip);
  SUCCEED();

  if (TEST_OUTPUT_STREAM == phase && CheckMessageContent(message, REQUEST)) {
    nsCOMPtr<nsIOutputStream> outstream;
    message->GetOutputStream(getter_AddRefs(outstream));

    uint32_t count;
    const uint32_t data = RESPONSE;
    mResult = outstream->Write((const char*)&data, sizeof(uint32_t), &count);

    if (mResult == NS_OK && count == sizeof(uint32_t)) {
      SUCCEED();
    } else {
      ADD_FAILURE();
    }
    return NS_OK;
  } else if (TEST_MULTICAST == phase && CheckMessageContent(message, REQUEST)) {
    mResult = NS_OK;
  } else if (TEST_SEND_API != phase ||
             !CheckMessageContent(message, RESPONSE)) {
    mResult = NS_ERROR_FAILURE;
  }

  // Notify thread
  mWaiter->Notify();
  return NS_OK;
}

NS_IMETHODIMP
UDPServerListener::OnStopListening(nsIUDPSocket*, nsresult) {
  mWaiter->Notify();
  return NS_OK;
}

/**
 * Multicast timer callback: detects delivery failure
 */
class MulticastTimerCallback : public nsITimerCallback {
 protected:
  virtual ~MulticastTimerCallback();

 public:
  explicit MulticastTimerCallback(WaitForCondition* waiter)
      : mResult(NS_ERROR_NOT_INITIALIZED), mWaiter(waiter) {}

  NS_DECL_THREADSAFE_ISUPPORTS
  NS_DECL_NSITIMERCALLBACK

  nsresult mResult;
  RefPtr<WaitForCondition> mWaiter;
};

NS_IMPL_ISUPPORTS(MulticastTimerCallback, nsITimerCallback)

MulticastTimerCallback::~MulticastTimerCallback() = default;

NS_IMETHODIMP
MulticastTimerCallback::Notify(nsITimer* timer) {
  if (TEST_MULTICAST != phase) {
    return NS_OK;
  }
  // Multicast ping failed
  printf("Multicast ping timeout expired\n");
  mResult = NS_ERROR_FAILURE;
  mWaiter->Notify();
  return NS_OK;
}

/**** Main ****/

TEST(TestUDPSocket, TestUDPSocketMain)
{
  nsresult rv;

  // Create UDPSocket
  nsCOMPtr<nsIUDPSocket> server, client;
  server = do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv);
  ASSERT_TRUE(NS_SUCCEEDED(rv));

  client = do_CreateInstance("@mozilla.org/network/udp-socket;1", &rv);
  ASSERT_TRUE(NS_SUCCEEDED(rv));

  RefPtr<WaitForCondition> waiter = new WaitForCondition();

  // Create UDPServerListener to process UDP packets
  RefPtr<UDPServerListener> serverListener = new UDPServerListener(waiter);

  nsCOMPtr<nsIPrincipal> systemPrincipal = nsContentUtils::GetSystemPrincipal();

  // Bind server socket to 0.0.0.0
  rv = server->Init(0, false, systemPrincipal, true, 0);
  ASSERT_TRUE(NS_SUCCEEDED(rv));
  int32_t serverPort;
  server->GetPort(&serverPort);
  server->AsyncListen(serverListener);

  // Bind clinet on arbitrary port
  RefPtr<UDPClientListener> clientListener = new UDPClientListener(waiter);
  client->Init(0, false, systemPrincipal, true, 0);
  client->AsyncListen(clientListener);

  // Write data to server
  uint32_t count;
  nsTArray<uint8_t> data;
  const uint32_t dataBuffer = REQUEST;
  data.AppendElements((const uint8_t*)&dataBuffer, sizeof(uint32_t));

  phase = TEST_OUTPUT_STREAM;
  rv = client->Send("127.0.0.1"_ns, serverPort, data, &count);
  ASSERT_TRUE(NS_SUCCEEDED(rv));
  EXPECT_EQ(count, sizeof(uint32_t));

  // Wait for server
  waiter->Wait(1);
  ASSERT_TRUE(NS_SUCCEEDED(serverListener->mResult));

  // Read response from server
  ASSERT_TRUE(NS_SUCCEEDED(clientListener->mResult));

  mozilla::net::NetAddr clientAddr;
  rv = client->GetAddress(&clientAddr);
  ASSERT_TRUE(NS_SUCCEEDED(rv));
  // The client address is 0.0.0.0, but Windows won't receive packets there, so
  // use 127.0.0.1 explicitly
  clientAddr.inet.ip = PR_htonl(127 << 24 | 1);

  phase = TEST_SEND_API;
  rv = server->SendWithAddress(&clientAddr, data, &count);
  ASSERT_TRUE(NS_SUCCEEDED(rv));
  EXPECT_EQ(count, sizeof(uint32_t));

  // Wait for server
  waiter->Wait(1);
  ASSERT_TRUE(NS_SUCCEEDED(serverListener->mResult));

  // Read response from server
  ASSERT_TRUE(NS_SUCCEEDED(clientListener->mResult));

  // Setup timer to detect multicast failure
  nsCOMPtr<nsITimer> timer = NS_NewTimer();
  ASSERT_TRUE(timer);
  RefPtr<MulticastTimerCallback> timerCb = new MulticastTimerCallback(waiter);

  // Join multicast group
  printf("Joining multicast group\n");
  phase = TEST_MULTICAST;
  mozilla::net::NetAddr multicastAddr;
  multicastAddr.inet.family = AF_INET;
  multicastAddr.inet.ip = PR_htonl(224 << 24 | 255);
  multicastAddr.inet.port = PR_htons(serverPort);
  rv = server->JoinMulticastAddr(multicastAddr, nullptr);
  ASSERT_TRUE(NS_SUCCEEDED(rv));

  // Send multicast ping
  timerCb->mResult = NS_OK;
  timer->InitWithCallback(timerCb, MULTICAST_TIMEOUT, nsITimer::TYPE_ONE_SHOT);
  rv = client->SendWithAddress(&multicastAddr, data, &count);
  ASSERT_TRUE(NS_SUCCEEDED(rv));
  EXPECT_EQ(count, sizeof(uint32_t));

  // Wait for server to receive successfully
  waiter->Wait(1);
  ASSERT_TRUE(NS_SUCCEEDED(serverListener->mResult));
  ASSERT_TRUE(NS_SUCCEEDED(timerCb->mResult));
  timer->Cancel();

  // Disable multicast loopback
  printf("Disable multicast loopback\n");
  client->SetMulticastLoopback(false);
  server->SetMulticastLoopback(false);

  // Send multicast ping
  timerCb->mResult = NS_OK;
  timer->InitWithCallback(timerCb, MULTICAST_TIMEOUT, nsITimer::TYPE_ONE_SHOT);
  rv = client->SendWithAddress(&multicastAddr, data, &count);
  ASSERT_TRUE(NS_SUCCEEDED(rv));
  EXPECT_EQ(count, sizeof(uint32_t));

  // Wait for server to fail to receive
  waiter->Wait(1);
  ASSERT_FALSE(NS_SUCCEEDED(timerCb->mResult));
  timer->Cancel();

  // Reset state
  client->SetMulticastLoopback(true);
  server->SetMulticastLoopback(true);

  // Change multicast interface
  mozilla::net::NetAddr loopbackAddr;
  loopbackAddr.inet.family = AF_INET;
  loopbackAddr.inet.ip = PR_htonl(INADDR_LOOPBACK);
  client->SetMulticastInterfaceAddr(loopbackAddr);

  // Send multicast ping
  timerCb->mResult = NS_OK;
  timer->InitWithCallback(timerCb, MULTICAST_TIMEOUT, nsITimer::TYPE_ONE_SHOT);
  rv = client->SendWithAddress(&multicastAddr, data, &count);
  ASSERT_TRUE(NS_SUCCEEDED(rv));
  EXPECT_EQ(count, sizeof(uint32_t));

  // Wait for server to fail to receive
  waiter->Wait(1);
  ASSERT_FALSE(NS_SUCCEEDED(timerCb->mResult));
  timer->Cancel();

  // Reset state
  mozilla::net::NetAddr anyAddr;
  anyAddr.inet.family = AF_INET;
  anyAddr.inet.ip = PR_htonl(INADDR_ANY);
  client->SetMulticastInterfaceAddr(anyAddr);

  // Leave multicast group
  rv = server->LeaveMulticastAddr(multicastAddr, nullptr);
  ASSERT_TRUE(NS_SUCCEEDED(rv));

  // Send multicast ping
  timerCb->mResult = NS_OK;
  timer->InitWithCallback(timerCb, MULTICAST_TIMEOUT, nsITimer::TYPE_ONE_SHOT);
  rv = client->SendWithAddress(&multicastAddr, data, &count);
  ASSERT_TRUE(NS_SUCCEEDED(rv));
  EXPECT_EQ(count, sizeof(uint32_t));

  // Wait for server to fail to receive
  waiter->Wait(1);
  ASSERT_FALSE(NS_SUCCEEDED(timerCb->mResult));
  timer->Cancel();

  goto close;  // suppress warning about unused label

close:
  // Close server
  server->Close();
  client->Close();

  // Wait for client and server to see closing
  waiter->Wait(2);
}