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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* 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 <stdarg.h>
#include <windef.h>
#include <winbase.h>
#include <wingdi.h>
#include <winuser.h>
#include <ole2.h>
#include <netcon.h>
#include <objbase.h>
#include <winsock2.h>
#include <ws2ipdef.h>
#include <tcpmib.h>
#include <iphlpapi.h>
#include <netioapi.h>
#include <iprtrmib.h>
#include "plstr.h"
#include "mozilla/Logging.h"
#include "nsThreadUtils.h"
#include "nsIObserverService.h"
#include "nsServiceManagerUtils.h"
#include "nsNotifyAddrListener.h"
#include "nsString.h"
#include "nsAutoPtr.h"
#include "mozilla/Services.h"
#include "nsCRT.h"
#include "mozilla/Preferences.h"
#include "mozilla/SHA1.h"
#include "mozilla/Base64.h"
#include <iptypes.h>
#include <iphlpapi.h>
using namespace mozilla;
static LazyLogModule gNotifyAddrLog("nsNotifyAddr");
#define LOG(args) MOZ_LOG(gNotifyAddrLog, mozilla::LogLevel::Debug, args)
static HMODULE sNetshell;
static decltype(NcFreeNetconProperties)* sNcFreeNetconProperties;
static HMODULE sIphlpapi;
static decltype(NotifyIpInterfaceChange)* sNotifyIpInterfaceChange;
static decltype(CancelMibChangeNotify2)* sCancelMibChangeNotify2;
#define NETWORK_NOTIFY_CHANGED_PREF "network.notify.changed"
#define NETWORK_NOTIFY_IPV6_PREF "network.notify.IPv6"
// period during which to absorb subsequent network change events, in
// milliseconds
static const unsigned int kNetworkChangeCoalescingPeriod = 1000;
static void InitIphlpapi(void)
{
if (!sIphlpapi) {
sIphlpapi = LoadLibraryW(L"Iphlpapi.dll");
if (sIphlpapi) {
sNotifyIpInterfaceChange = (decltype(NotifyIpInterfaceChange)*)
GetProcAddress(sIphlpapi, "NotifyIpInterfaceChange");
sCancelMibChangeNotify2 = (decltype(CancelMibChangeNotify2)*)
GetProcAddress(sIphlpapi, "CancelMibChangeNotify2");
} else {
NS_WARNING("Failed to load Iphlpapi.dll - cannot detect network"
" changes!");
}
}
}
static void InitNetshellLibrary(void)
{
if (!sNetshell) {
sNetshell = LoadLibraryW(L"Netshell.dll");
if (sNetshell) {
sNcFreeNetconProperties = (decltype(NcFreeNetconProperties)*)
GetProcAddress(sNetshell, "NcFreeNetconProperties");
}
}
}
static void FreeDynamicLibraries(void)
{
if (sNetshell) {
sNcFreeNetconProperties = nullptr;
FreeLibrary(sNetshell);
sNetshell = nullptr;
}
if (sIphlpapi) {
sNotifyIpInterfaceChange = nullptr;
sCancelMibChangeNotify2 = nullptr;
FreeLibrary(sIphlpapi);
sIphlpapi = nullptr;
}
}
NS_IMPL_ISUPPORTS(nsNotifyAddrListener,
nsINetworkLinkService,
nsIRunnable,
nsIObserver)
nsNotifyAddrListener::nsNotifyAddrListener()
: mLinkUp(true) // assume true by default
, mStatusKnown(false)
, mCheckAttempted(false)
, mCheckEvent(nullptr)
, mShutdown(false)
, mIPInterfaceChecksum(0)
, mAllowChangedEvent(true)
, mIPv6Changes(false)
, mCoalescingActive(false)
{
InitIphlpapi();
}
nsNotifyAddrListener::~nsNotifyAddrListener()
{
NS_ASSERTION(!mThread, "nsNotifyAddrListener thread shutdown failed");
FreeDynamicLibraries();
}
NS_IMETHODIMP
nsNotifyAddrListener::GetIsLinkUp(bool *aIsUp)
{
if (!mCheckAttempted && !mStatusKnown) {
mCheckAttempted = true;
CheckLinkStatus();
}
*aIsUp = mLinkUp;
return NS_OK;
}
NS_IMETHODIMP
nsNotifyAddrListener::GetLinkStatusKnown(bool *aIsUp)
{
*aIsUp = mStatusKnown;
return NS_OK;
}
NS_IMETHODIMP
nsNotifyAddrListener::GetLinkType(uint32_t *aLinkType)
{
NS_ENSURE_ARG_POINTER(aLinkType);
// XXX This function has not yet been implemented for this platform
*aLinkType = nsINetworkLinkService::LINK_TYPE_UNKNOWN;
return NS_OK;
}
static bool macAddr(BYTE addr[], DWORD len, char *buf, size_t buflen)
{
buf[0] = '\0';
if (!addr || !len || (len * 3 > buflen)) {
return false;
}
for (DWORD i = 0; i < len; ++i) {
sprintf_s(buf + (i * 3), sizeof(buf + (i * 3)),
"%02x%s", addr[i], (i == len-1) ? "" : ":");
}
return true;
}
bool nsNotifyAddrListener::findMac(char *gateway)
{
// query for buffer size needed
DWORD dwActualSize = 0;
bool found = FALSE;
// GetIpNetTable gets the IPv4 to physical address mapping table
DWORD status = GetIpNetTable(NULL, &dwActualSize, FALSE);
if (status == ERROR_INSUFFICIENT_BUFFER) {
// the expected route, now with a known buffer size
UniquePtr <char[]>buf(new char[dwActualSize]);
PMIB_IPNETTABLE pIpNetTable =
reinterpret_cast<PMIB_IPNETTABLE>(&buf[0]);
status = GetIpNetTable(pIpNetTable, &dwActualSize, FALSE);
if (status == NO_ERROR) {
for (DWORD i = 0; i < pIpNetTable->dwNumEntries; ++i) {
DWORD dwCurrIndex = pIpNetTable->table[i].dwIndex;
char hw[256];
if (!macAddr(pIpNetTable->table[i].bPhysAddr,
pIpNetTable->table[i].dwPhysAddrLen,
hw, sizeof(hw))) {
// failed to get the MAC
continue;
}
struct in_addr addr;
addr.s_addr = pIpNetTable->table[i].dwAddr;
if (!strcmp(gateway, inet_ntoa(addr))) {
LOG(("networkid: MAC %s\n", hw));
nsAutoCString mac(hw);
// This 'addition' could potentially be a
// fixed number from the profile or something.
nsAutoCString addition("local-rubbish");
nsAutoCString output;
SHA1Sum sha1;
nsCString combined(mac + addition);
sha1.update(combined.get(), combined.Length());
uint8_t digest[SHA1Sum::kHashSize];
sha1.finish(digest);
nsCString newString(reinterpret_cast<char*>(digest),
SHA1Sum::kHashSize);
Base64Encode(newString, output);
LOG(("networkid: id %s\n", output.get()));
if (mNetworkId != output) {
// new id
mNetworkId = output;
}
else {
// same id
}
found = true;
break;
}
}
}
}
return found;
}
// returns 'true' when the gw is found and stored
static bool defaultgw(char *aGateway, size_t aGatewayLen)
{
PMIB_IPFORWARDTABLE pIpForwardTable = NULL;
DWORD dwSize = 0;
if (GetIpForwardTable(NULL, &dwSize, 0) != ERROR_INSUFFICIENT_BUFFER) {
return false;
}
UniquePtr <char[]>buf(new char[dwSize]);
pIpForwardTable = reinterpret_cast<PMIB_IPFORWARDTABLE>(&buf[0]);
// Note that the IPv4 addresses returned in GetIpForwardTable entries are
// in network byte order
DWORD retVal = GetIpForwardTable(pIpForwardTable, &dwSize, 0);
if (retVal == NO_ERROR) {
for (unsigned int i = 0; i < pIpForwardTable->dwNumEntries; ++i) {
// Convert IPv4 addresses to strings
struct in_addr IpAddr;
IpAddr.S_un.S_addr = static_cast<u_long>
(pIpForwardTable->table[i].dwForwardDest);
char *ipStr = inet_ntoa(IpAddr);
if (ipStr && !strcmp("0.0.0.0", ipStr)) {
// Default gateway!
IpAddr.S_un.S_addr = static_cast<u_long>
(pIpForwardTable->table[i].dwForwardNextHop);
ipStr = inet_ntoa(IpAddr);
if (ipStr) {
strcpy_s(aGateway, aGatewayLen, ipStr);
return true;
}
}
} // for loop
}
return false;
}
//
// Figure out the current "network identification" string.
//
// It detects the IP of the default gateway in the routing table, then the MAC
// address of that IP in the ARP table before it hashes that string (to avoid
// information leakage).
//
void nsNotifyAddrListener::calculateNetworkId(void)
{
bool found = FALSE;
char gateway[128];
if (defaultgw(gateway, sizeof(gateway) )) {
found = findMac(gateway);
}
if (!found) {
// no id
}
}
// Static Callback function for NotifyIpInterfaceChange API.
static void WINAPI OnInterfaceChange(PVOID callerContext,
PMIB_IPINTERFACE_ROW row,
MIB_NOTIFICATION_TYPE notificationType)
{
nsNotifyAddrListener *notify = static_cast<nsNotifyAddrListener*>(callerContext);
notify->CheckLinkStatus();
}
DWORD
nsNotifyAddrListener::nextCoalesceWaitTime()
{
// check if coalescing period should continue
double period = (TimeStamp::Now() - mChangeTime).ToMilliseconds();
if (period >= kNetworkChangeCoalescingPeriod) {
calculateNetworkId();
SendEvent(NS_NETWORK_LINK_DATA_CHANGED);
mCoalescingActive = false;
return INFINITE; // return default
} else {
// wait no longer than to the end of the period
return static_cast<DWORD>
(kNetworkChangeCoalescingPeriod - period);
}
}
NS_IMETHODIMP
nsNotifyAddrListener::Run()
{
PR_SetCurrentThreadName("Link Monitor");
mStartTime = TimeStamp::Now();
calculateNetworkId();
DWORD waitTime = INFINITE;
if (!sNotifyIpInterfaceChange || !sCancelMibChangeNotify2 || !mIPv6Changes) {
// For Windows versions which are older than Vista which lack
// NotifyIpInterfaceChange. Note this means no IPv6 support.
HANDLE ev = CreateEvent(nullptr, FALSE, FALSE, nullptr);
NS_ENSURE_TRUE(ev, NS_ERROR_OUT_OF_MEMORY);
HANDLE handles[2] = { ev, mCheckEvent };
OVERLAPPED overlapped = { 0 };
bool shuttingDown = false;
overlapped.hEvent = ev;
while (!shuttingDown) {
HANDLE h;
DWORD ret = NotifyAddrChange(&h, &overlapped);
if (ret == ERROR_IO_PENDING) {
ret = WaitForMultipleObjects(2, handles, FALSE, waitTime);
if (ret == WAIT_OBJECT_0) {
CheckLinkStatus();
} else if (!mShutdown) {
waitTime = nextCoalesceWaitTime();
} else {
shuttingDown = true;
}
} else {
shuttingDown = true;
}
}
CloseHandle(ev);
} else {
// Windows Vista and newer versions.
HANDLE interfacechange;
// The callback will simply invoke CheckLinkStatus()
DWORD ret = sNotifyIpInterfaceChange(
AF_UNSPEC, // IPv4 and IPv6
(PIPINTERFACE_CHANGE_CALLBACK)OnInterfaceChange,
this, // pass to callback
false, // no initial notification
&interfacechange);
if (ret == NO_ERROR) {
do {
ret = WaitForSingleObject(mCheckEvent, waitTime);
if (!mShutdown) {
waitTime = nextCoalesceWaitTime();
}
else {
break;
}
} while (ret != WAIT_FAILED);
sCancelMibChangeNotify2(interfacechange);
} else {
LOG(("Link Monitor: sNotifyIpInterfaceChange returned %d\n",
(int)ret));
}
}
return NS_OK;
}
NS_IMETHODIMP
nsNotifyAddrListener::Observe(nsISupports *subject,
const char *topic,
const char16_t *data)
{
if (!strcmp("xpcom-shutdown-threads", topic))
Shutdown();
return NS_OK;
}
nsresult
nsNotifyAddrListener::Init(void)
{
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (!observerService)
return NS_ERROR_FAILURE;
nsresult rv = observerService->AddObserver(this, "xpcom-shutdown-threads",
false);
NS_ENSURE_SUCCESS(rv, rv);
Preferences::AddBoolVarCache(&mAllowChangedEvent,
NETWORK_NOTIFY_CHANGED_PREF, true);
Preferences::AddBoolVarCache(&mIPv6Changes,
NETWORK_NOTIFY_IPV6_PREF, false);
mCheckEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
NS_ENSURE_TRUE(mCheckEvent, NS_ERROR_OUT_OF_MEMORY);
rv = NS_NewThread(getter_AddRefs(mThread), this);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult
nsNotifyAddrListener::Shutdown(void)
{
// remove xpcom shutdown observer
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService)
observerService->RemoveObserver(this, "xpcom-shutdown-threads");
if (!mCheckEvent)
return NS_OK;
mShutdown = true;
SetEvent(mCheckEvent);
nsresult rv = mThread ? mThread->Shutdown() : NS_OK;
// Have to break the cycle here, otherwise nsNotifyAddrListener holds
// onto the thread and the thread holds onto the nsNotifyAddrListener
// via its mRunnable
mThread = nullptr;
CloseHandle(mCheckEvent);
mCheckEvent = nullptr;
return rv;
}
/*
* A network event has been registered. Delay the actual sending of the event
* for a while and absorb subsequent events in the mean time in an effort to
* squash potentially many triggers into a single event.
* Only ever called from the same thread.
*/
nsresult
nsNotifyAddrListener::NetworkChanged()
{
if (mCoalescingActive) {
LOG(("NetworkChanged: absorbed an event (coalescing active)\n"));
} else {
// A fresh trigger!
mChangeTime = TimeStamp::Now();
mCoalescingActive = true;
SetEvent(mCheckEvent);
LOG(("NetworkChanged: coalescing period started\n"));
}
return NS_OK;
}
/* Sends the given event. Assumes aEventID never goes out of scope (static
* strings are ideal).
*/
nsresult
nsNotifyAddrListener::SendEvent(const char *aEventID)
{
if (!aEventID)
return NS_ERROR_NULL_POINTER;
LOG(("SendEvent: network is '%s'\n", aEventID));
nsresult rv;
nsCOMPtr<nsIRunnable> event = new ChangeEvent(this, aEventID);
if (NS_FAILED(rv = NS_DispatchToMainThread(event)))
NS_WARNING("Failed to dispatch ChangeEvent");
return rv;
}
NS_IMETHODIMP
nsNotifyAddrListener::ChangeEvent::Run()
{
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService)
observerService->NotifyObservers(
mService, NS_NETWORK_LINK_TOPIC,
NS_ConvertASCIItoUTF16(mEventID).get());
return NS_OK;
}
// Bug 465158 features an explanation for this check. ICS being "Internet
// Connection Sharing). The description says it is always IP address
// 192.168.0.1 for this case.
bool
nsNotifyAddrListener::CheckICSGateway(PIP_ADAPTER_ADDRESSES aAdapter)
{
if (!aAdapter->FirstUnicastAddress)
return false;
LPSOCKADDR aAddress = aAdapter->FirstUnicastAddress->Address.lpSockaddr;
if (!aAddress)
return false;
PSOCKADDR_IN in_addr = (PSOCKADDR_IN)aAddress;
bool isGateway = (aAddress->sa_family == AF_INET &&
in_addr->sin_addr.S_un.S_un_b.s_b1 == 192 &&
in_addr->sin_addr.S_un.S_un_b.s_b2 == 168 &&
in_addr->sin_addr.S_un.S_un_b.s_b3 == 0 &&
in_addr->sin_addr.S_un.S_un_b.s_b4 == 1);
if (isGateway)
isGateway = CheckICSStatus(aAdapter->FriendlyName);
return isGateway;
}
bool
nsNotifyAddrListener::CheckICSStatus(PWCHAR aAdapterName)
{
InitNetshellLibrary();
// This method enumerates all privately shared connections and checks if some
// of them has the same name as the one provided in aAdapterName. If such
// connection is found in the collection the adapter is used as ICS gateway
bool isICSGatewayAdapter = false;
HRESULT hr;
RefPtr<INetSharingManager> netSharingManager;
hr = CoCreateInstance(
CLSID_NetSharingManager,
nullptr,
CLSCTX_INPROC_SERVER,
IID_INetSharingManager,
getter_AddRefs(netSharingManager));
RefPtr<INetSharingPrivateConnectionCollection> privateCollection;
if (SUCCEEDED(hr)) {
hr = netSharingManager->get_EnumPrivateConnections(
ICSSC_DEFAULT,
getter_AddRefs(privateCollection));
}
RefPtr<IEnumNetSharingPrivateConnection> privateEnum;
if (SUCCEEDED(hr)) {
RefPtr<IUnknown> privateEnumUnknown;
hr = privateCollection->get__NewEnum(getter_AddRefs(privateEnumUnknown));
if (SUCCEEDED(hr)) {
hr = privateEnumUnknown->QueryInterface(
IID_IEnumNetSharingPrivateConnection,
getter_AddRefs(privateEnum));
}
}
if (SUCCEEDED(hr)) {
ULONG fetched;
VARIANT connectionVariant;
while (!isICSGatewayAdapter &&
SUCCEEDED(hr = privateEnum->Next(1, &connectionVariant,
&fetched)) &&
fetched) {
if (connectionVariant.vt != VT_UNKNOWN) {
// We should call VariantClear here but it needs to link
// with oleaut32.lib that produces a Ts incrase about 10ms
// that is undesired. As it is quit unlikely the result would
// be of a different type anyway, let's pass the variant
// unfreed here.
NS_ERROR("Variant of unexpected type, expecting VT_UNKNOWN, we probably leak it!");
continue;
}
RefPtr<INetConnection> connection;
if (SUCCEEDED(connectionVariant.punkVal->QueryInterface(
IID_INetConnection,
getter_AddRefs(connection)))) {
connectionVariant.punkVal->Release();
NETCON_PROPERTIES *properties;
if (SUCCEEDED(connection->GetProperties(&properties))) {
if (!wcscmp(properties->pszwName, aAdapterName))
isICSGatewayAdapter = true;
if (sNcFreeNetconProperties)
sNcFreeNetconProperties(properties);
}
}
}
}
return isICSGatewayAdapter;
}
DWORD
nsNotifyAddrListener::CheckAdaptersAddresses(void)
{
ULONG len = 16384;
PIP_ADAPTER_ADDRESSES adapterList = (PIP_ADAPTER_ADDRESSES) moz_xmalloc(len);
ULONG flags = GAA_FLAG_SKIP_DNS_SERVER|GAA_FLAG_SKIP_MULTICAST|
GAA_FLAG_SKIP_ANYCAST;
DWORD ret = GetAdaptersAddresses(AF_UNSPEC, flags, nullptr, adapterList, &len);
if (ret == ERROR_BUFFER_OVERFLOW) {
free(adapterList);
adapterList = static_cast<PIP_ADAPTER_ADDRESSES> (moz_xmalloc(len));
ret = GetAdaptersAddresses(AF_UNSPEC, flags, nullptr, adapterList, &len);
}
if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) {
free(adapterList);
return ERROR_NOT_SUPPORTED;
}
//
// Since NotifyIpInterfaceChange() signals a change more often than we
// think is a worthy change, we checksum the entire state of all interfaces
// that are UP. If the checksum is the same as previous check, nothing
// of interest changed!
//
ULONG sum = 0;
if (ret == ERROR_SUCCESS) {
bool linkUp = false;
for (PIP_ADAPTER_ADDRESSES adapter = adapterList; adapter;
adapter = adapter->Next) {
if (adapter->OperStatus != IfOperStatusUp ||
!adapter->FirstUnicastAddress ||
adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK ||
CheckICSGateway(adapter) ) {
continue;
}
// Add chars from AdapterName to the checksum.
for (int i = 0; adapter->AdapterName[i]; ++i) {
sum <<= 2;
sum += adapter->AdapterName[i];
}
// Add bytes from each socket address to the checksum.
for (PIP_ADAPTER_UNICAST_ADDRESS pip = adapter->FirstUnicastAddress;
pip; pip = pip->Next) {
SOCKET_ADDRESS *sockAddr = &pip->Address;
for (int i = 0; i < sockAddr->iSockaddrLength; ++i) {
sum += (reinterpret_cast<unsigned char *>
(sockAddr->lpSockaddr))[i];
}
}
linkUp = true;
}
mLinkUp = linkUp;
mStatusKnown = true;
}
free(adapterList);
if (mLinkUp) {
/* Store the checksum only if one or more interfaces are up */
mIPInterfaceChecksum = sum;
}
CoUninitialize();
return ret;
}
/**
* Checks the status of all network adapters. If one is up and has a valid IP
* address, sets mLinkUp to true. Sets mStatusKnown to true if the link status
* is definitive.
*/
void
nsNotifyAddrListener::CheckLinkStatus(void)
{
DWORD ret;
const char *event;
bool prevLinkUp = mLinkUp;
ULONG prevCsum = mIPInterfaceChecksum;
LOG(("check status of all network adapters\n"));
// The CheckAdaptersAddresses call is very expensive (~650 milliseconds),
// so we don't want to call it synchronously. Instead, we just start up
// assuming we have a network link, but we'll report that the status is
// unknown.
if (NS_IsMainThread()) {
NS_WARNING("CheckLinkStatus called on main thread! No check "
"performed. Assuming link is up, status is unknown.");
mLinkUp = true;
if (!mStatusKnown) {
event = NS_NETWORK_LINK_DATA_UNKNOWN;
} else if (!prevLinkUp) {
event = NS_NETWORK_LINK_DATA_UP;
} else {
// Known status and it was already UP
event = nullptr;
}
if (event) {
SendEvent(event);
}
} else {
ret = CheckAdaptersAddresses();
if (ret != ERROR_SUCCESS) {
mLinkUp = true;
}
if (mLinkUp && (prevCsum != mIPInterfaceChecksum)) {
TimeDuration since = TimeStamp::Now() - mStartTime;
// Network is online. Topology has changed. Always send CHANGED
// before UP - if allowed to and having cooled down.
if (mAllowChangedEvent && (since.ToMilliseconds() > 2000)) {
NetworkChanged();
}
}
if (prevLinkUp != mLinkUp) {
// UP/DOWN status changed, send appropriate UP/DOWN event
SendEvent(mLinkUp ?
NS_NETWORK_LINK_DATA_UP : NS_NETWORK_LINK_DATA_DOWN);
}
}
}
|