File: network_change_notifier_apple.mm

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (578 lines) | stat: -rw-r--r-- 22,822 bytes parent folder | download | duplicates (5)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/network_change_notifier_apple.h"

#include <netinet/in.h>
#include <resolv.h>

#include "base/apple/bridging.h"
#include "base/apple/foundation_util.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/memory/scoped_policy.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "net/base/features.h"
#include "net/base/network_interfaces_getifaddrs.h"
#include "net/dns/dns_config_service.h"
#include "net/log/net_log.h"

#if BUILDFLAG(IS_IOS) && !BUILDFLAG(IS_IOS_TVOS)
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#endif

namespace net {
namespace {
// The maximum number of seconds to wait for the connection type to be
// determined.
const double kMaxWaitForConnectionTypeInSeconds = 2.0;

#if BUILDFLAG(IS_MAC)
std::string GetPrimaryInterfaceName(SCDynamicStoreRef store,
                                    CFStringRef entity) {
  base::apple::ScopedCFTypeRef<CFStringRef> netkey(
      SCDynamicStoreKeyCreateNetworkGlobalEntity(
          nullptr, kSCDynamicStoreDomainState, entity));
  base::apple::ScopedCFTypeRef<CFPropertyListRef> netdict_value(
      SCDynamicStoreCopyValue(store, netkey.get()));
  CFDictionaryRef netdict =
      base::apple::CFCast<CFDictionaryRef>(netdict_value.get());
  if (!netdict) {
    return "";
  }
  CFStringRef primary_if_name_ref =
      base::apple::GetValueFromDictionary<CFStringRef>(
          netdict, kSCDynamicStorePropNetPrimaryInterface);
  if (!primary_if_name_ref) {
    return "";
  }
  return base::SysCFStringRefToUTF8(primary_if_name_ref);
}

std::string GetIPv4PrimaryInterfaceName(SCDynamicStoreRef store) {
  return GetPrimaryInterfaceName(store, kSCEntNetIPv4);
}

std::string GetIPv6PrimaryInterfaceName(SCDynamicStoreRef store) {
  return GetPrimaryInterfaceName(store, kSCEntNetIPv6);
}

std::optional<net::NetworkInterfaceList>
GetNetworkInterfaceListForNetworkChangeCheck(
    base::RepeatingCallback<bool(net::NetworkInterfaceList*, int)>
        get_network_list_callback,
    const std::string& ipv6_primary_interface_name) {
  net::NetworkInterfaceList interfaces;
  if (!get_network_list_callback.Run(
          &interfaces, net::EXCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES)) {
    return std::nullopt;
  }
  std::erase_if(interfaces, [&ipv6_primary_interface_name](
                                const net::NetworkInterface& interface) {
    return interface.address.IsIPv6() &&
           !interface.address.IsPubliclyRoutable() &&
           (interface.name != ipv6_primary_interface_name);
  });
  return interfaces;
}

base::Value::Dict GetNetworkInterfaceValueDict(
    const NetworkInterface& interface) {
  base::Value::Dict dict;
  dict.Set("name", interface.name);
  dict.Set("friendly_name", interface.friendly_name);
  dict.Set("interface_index", static_cast<int>(interface.interface_index));
  dict.Set("type", static_cast<int>(interface.type));
  dict.Set("address", interface.address.ToString());
  dict.Set("prefix_length", static_cast<int>(interface.prefix_length));
  dict.Set("ip_address_attributes", interface.ip_address_attributes);
  if (interface.mac_address) {
    dict.Set("mac_address", base::HexEncode(*interface.mac_address));
  }
  return dict;
}

base::Value::List GetNetworkInterfacesValueList(
    const NetworkInterfaceList& interfaces) {
  base::Value::List list;
  for (const NetworkInterface& interface : interfaces) {
    list.Append(GetNetworkInterfaceValueDict(interface));
  }
  return list;
}

base::Value::Dict NetLogOsConfigChangedParams(
    const std::string& result,
    bool net_ipv4_key_found,
    bool net_ipv6_key_found,
    bool net_interface_key_found,
    bool reduce_ip_address_change_notification,
    const std::string& old_ipv4_primary_interface_name,
    const std::string& old_ipv6_primary_interface_name,
    const std::string& new_ipv4_primary_interface_name,
    const std::string& new_ipv6_primary_interface_name,
    const std::optional<NetworkInterfaceList>& old_interfaces,
    const std::optional<NetworkInterfaceList>& new_interfaces) {
  base::Value::Dict dict;
  dict.Set("result", result);
  dict.Set("net_ipv4_key", net_ipv4_key_found);
  dict.Set("net_ipv6_key", net_ipv6_key_found);
  dict.Set("net_interface_key", net_interface_key_found);
  dict.Set("reduce_notification", reduce_ip_address_change_notification);
  dict.Set("old_ipv4_interface", old_ipv4_primary_interface_name);
  dict.Set("old_ipv6_interface", old_ipv6_primary_interface_name);
  dict.Set("new_ipv4_interface", new_ipv4_primary_interface_name);
  dict.Set("new_ipv6_interface", new_ipv6_primary_interface_name);
  if (old_interfaces) {
    dict.Set("old_interfaces", GetNetworkInterfacesValueList(*old_interfaces));
  }
  if (new_interfaces) {
    dict.Set("new_interfaces", GetNetworkInterfacesValueList(*new_interfaces));
  }
  return dict;
}

#endif  // BUILDFLAG(IS_MAC)

}  // namespace

static bool CalculateReachability(SCNetworkConnectionFlags flags) {
  bool reachable = flags & kSCNetworkFlagsReachable;
  bool connection_required = flags & kSCNetworkFlagsConnectionRequired;
  return reachable && !connection_required;
}

NetworkChangeNotifierApple::NetworkChangeNotifierApple()
    : NetworkChangeNotifier(NetworkChangeCalculatorParamsMac()),
      initial_connection_type_cv_(&connection_type_lock_),
      forwarder_(this),
#if BUILDFLAG(IS_MAC)
      reduce_ip_address_change_notification_(base::FeatureList::IsEnabled(
          features::kReduceIPAddressChangeNotification)),
      get_network_list_callback_(base::BindRepeating(&GetNetworkList)),
      get_ipv4_primary_interface_name_callback_(
          base::BindRepeating(&GetIPv4PrimaryInterfaceName)),
      get_ipv6_primary_interface_name_callback_(
          base::BindRepeating(&GetIPv6PrimaryInterfaceName)),
#endif  // BUILDFLAG(IS_MAC)
      net_log_(net::NetLogWithSource::Make(
          net::NetLog::Get(),
          net::NetLogSourceType::NETWORK_CHANGE_NOTIFIER)) {
  // Must be initialized after the rest of this object, as it may call back into
  // SetInitialConnectionType().
  config_watcher_ = std::make_unique<NetworkConfigWatcherApple>(&forwarder_);
}

NetworkChangeNotifierApple::~NetworkChangeNotifierApple() {
  ClearGlobalPointer();
  // Delete the ConfigWatcher to join the notifier thread, ensuring that
  // StartReachabilityNotifications() has an opportunity to run to completion.
  config_watcher_.reset();

  // Now that StartReachabilityNotifications() has either run to completion or
  // never run at all, unschedule reachability_ if it was previously scheduled.
  if (reachability_.get() && run_loop_.get()) {
    SCNetworkReachabilityUnscheduleFromRunLoop(
        reachability_.get(), run_loop_.get(), kCFRunLoopCommonModes);
  }
}

// static
NetworkChangeNotifier::NetworkChangeCalculatorParams
NetworkChangeNotifierApple::NetworkChangeCalculatorParamsMac() {
  NetworkChangeCalculatorParams params;
  // Delay values arrived at by simple experimentation and adjusted so as to
  // produce a single signal when switching between network connections.
  params.ip_address_offline_delay_ = base::Milliseconds(500);
  params.ip_address_online_delay_ = base::Milliseconds(500);
  params.connection_type_offline_delay_ = base::Milliseconds(1000);
  params.connection_type_online_delay_ = base::Milliseconds(500);
  return params;
}

NetworkChangeNotifier::ConnectionType
NetworkChangeNotifierApple::GetCurrentConnectionType() const {
  // https://crbug.com/125097
  base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait;
  base::AutoLock lock(connection_type_lock_);

  if (connection_type_initialized_)
    return connection_type_;

  // Wait up to a limited amount of time for the connection type to be
  // determined, to avoid blocking the main thread indefinitely. Since
  // ConditionVariables are susceptible to spurious wake-ups, each call to
  // TimedWait can spuriously return even though the connection type hasn't been
  // initialized and the timeout hasn't been reached; so TimedWait must be
  // called repeatedly until either the timeout is reached or the connection
  // type has been determined.
  base::TimeDelta remaining_time =
      base::Seconds(kMaxWaitForConnectionTypeInSeconds);
  base::TimeTicks end_time = base::TimeTicks::Now() + remaining_time;
  while (remaining_time.is_positive()) {
    initial_connection_type_cv_.TimedWait(remaining_time);
    if (connection_type_initialized_)
      return connection_type_;

    remaining_time = end_time - base::TimeTicks::Now();
  }

  return CONNECTION_UNKNOWN;
}

void NetworkChangeNotifierApple::Forwarder::Init() {
  net_config_watcher_->SetInitialConnectionType();
}

// static
NetworkChangeNotifier::ConnectionType
NetworkChangeNotifierApple::CalculateConnectionType(
    SCNetworkConnectionFlags flags) {
  bool reachable = CalculateReachability(flags);
  if (!reachable)
    return CONNECTION_NONE;

#if BUILDFLAG(IS_IOS) && !BUILDFLAG(IS_IOS_TVOS)
  if (!(flags & kSCNetworkReachabilityFlagsIsWWAN)) {
    return CONNECTION_WIFI;
  }
  if (@available(iOS 12, *)) {
    CTTelephonyNetworkInfo* info = [[CTTelephonyNetworkInfo alloc] init];
    NSDictionary<NSString*, NSString*>*
        service_current_radio_access_technology =
            info.serviceCurrentRadioAccessTechnology;
    NSSet<NSString*>* technologies_2g = [NSSet
        setWithObjects:CTRadioAccessTechnologyGPRS, CTRadioAccessTechnologyEdge,
                       CTRadioAccessTechnologyCDMA1x, nil];
    NSSet<NSString*>* technologies_3g =
        [NSSet setWithObjects:CTRadioAccessTechnologyWCDMA,
                              CTRadioAccessTechnologyHSDPA,
                              CTRadioAccessTechnologyHSUPA,
                              CTRadioAccessTechnologyCDMAEVDORev0,
                              CTRadioAccessTechnologyCDMAEVDORevA,
                              CTRadioAccessTechnologyCDMAEVDORevB,
                              CTRadioAccessTechnologyeHRPD, nil];
    NSSet<NSString*>* technologies_4g =
        [NSSet setWithObjects:CTRadioAccessTechnologyLTE, nil];
    // TODO: Use constants from CoreTelephony once Cronet builds with XCode 12.1
    NSSet<NSString*>* technologies_5g =
        [NSSet setWithObjects:@"CTRadioAccessTechnologyNRNSA",
                              @"CTRadioAccessTechnologyNR", nil];
    int best_network = 0;
    for (NSString* service in service_current_radio_access_technology) {
      if (!service_current_radio_access_technology[service]) {
        continue;
      }
      int current_network = 0;

      NSString* network_type = service_current_radio_access_technology[service];

      if ([technologies_2g containsObject:network_type]) {
        current_network = 2;
      } else if ([technologies_3g containsObject:network_type]) {
        current_network = 3;
      } else if ([technologies_4g containsObject:network_type]) {
        current_network = 4;
      } else if ([technologies_5g containsObject:network_type]) {
        current_network = 5;
      } else {
        // New technology?
        NOTREACHED() << "Unknown network technology: " << network_type;
      }
      if (current_network > best_network) {
        // iOS is supposed to use the best network available.
        best_network = current_network;
      }
    }
    switch (best_network) {
      case 2:
        return CONNECTION_2G;
      case 3:
        return CONNECTION_3G;
      case 4:
        return CONNECTION_4G;
      case 5:
        return CONNECTION_5G;
      default:
        // Default to CONNECTION_3G to not change existing behavior.
        return CONNECTION_3G;
    }
  } else {
    return CONNECTION_3G;
  }

#else
  return ConnectionTypeFromInterfaces();
#endif
}

void NetworkChangeNotifierApple::Forwarder::StartReachabilityNotifications() {
  net_config_watcher_->StartReachabilityNotifications();
}

void NetworkChangeNotifierApple::Forwarder::SetDynamicStoreNotificationKeys(
    base::apple::ScopedCFTypeRef<SCDynamicStoreRef> store) {
  net_config_watcher_->SetDynamicStoreNotificationKeys(std::move(store));
}

void NetworkChangeNotifierApple::Forwarder::OnNetworkConfigChange(
    CFArrayRef changed_keys) {
  net_config_watcher_->OnNetworkConfigChange(changed_keys);
}

void NetworkChangeNotifierApple::Forwarder::CleanUpOnNotifierThread() {
  net_config_watcher_->CleanUpOnNotifierThread();
}

void NetworkChangeNotifierApple::SetInitialConnectionType() {
  // Called on notifier thread.

  // Try to reach 0.0.0.0. This is the approach taken by Firefox:
  //
  // http://mxr.mozilla.org/mozilla2.0/source/netwerk/system/mac/nsNetworkLinkService.mm
  //
  // From my (adamk) testing on Snow Leopard, 0.0.0.0
  // seems to be reachable if any network connection is available.
  struct sockaddr_in addr = {0};
  addr.sin_len = sizeof(addr);
  addr.sin_family = AF_INET;
  reachability_.reset(SCNetworkReachabilityCreateWithAddress(
      kCFAllocatorDefault, reinterpret_cast<struct sockaddr*>(&addr)));

  SCNetworkConnectionFlags flags;
  ConnectionType connection_type = CONNECTION_UNKNOWN;
  if (SCNetworkReachabilityGetFlags(reachability_.get(), &flags)) {
    connection_type = CalculateConnectionType(flags);
  } else {
    LOG(ERROR) << "Could not get initial network connection type,"
               << "assuming online.";
  }
  {
    base::AutoLock lock(connection_type_lock_);
    connection_type_ = connection_type;
    connection_type_initialized_ = true;
    initial_connection_type_cv_.Broadcast();
  }
}

void NetworkChangeNotifierApple::StartReachabilityNotifications() {
  // Called on notifier thread.
  run_loop_.reset(CFRunLoopGetCurrent(), base::scoped_policy::RETAIN);

  DCHECK(reachability_);
  SCNetworkReachabilityContext reachability_context = {
      0,        // version
      this,     // user data
      nullptr,  // retain
      nullptr,  // release
      nullptr   // description
  };
  if (!SCNetworkReachabilitySetCallback(
          reachability_.get(), &NetworkChangeNotifierApple::ReachabilityCallback,
          &reachability_context)) {
    LOG(DFATAL) << "Could not set network reachability callback";
    reachability_.reset();
  } else if (!SCNetworkReachabilityScheduleWithRunLoop(
                 reachability_.get(), run_loop_.get(), kCFRunLoopCommonModes)) {
    LOG(DFATAL) << "Could not schedule network reachability on run loop";
    reachability_.reset();
  }
}

void NetworkChangeNotifierApple::SetDynamicStoreNotificationKeys(
    base::apple::ScopedCFTypeRef<SCDynamicStoreRef> store) {
#if BUILDFLAG(IS_IOS)
  // SCDynamicStore API does not exist on iOS.
  NOTREACHED();
#elif BUILDFLAG(IS_MAC)
  NSArray* notification_keys = @[
    base::apple::CFToNSOwnershipCast(SCDynamicStoreKeyCreateNetworkGlobalEntity(
        nullptr, kSCDynamicStoreDomainState, kSCEntNetInterface)),
    base::apple::CFToNSOwnershipCast(SCDynamicStoreKeyCreateNetworkGlobalEntity(
        nullptr, kSCDynamicStoreDomainState, kSCEntNetIPv4)),
    base::apple::CFToNSOwnershipCast(SCDynamicStoreKeyCreateNetworkGlobalEntity(
        nullptr, kSCDynamicStoreDomainState, kSCEntNetIPv6)),
  ];

  // Set the notification keys.  This starts us receiving notifications.
  bool ret = SCDynamicStoreSetNotificationKeys(
      store.get(), base::apple::NSToCFPtrCast(notification_keys),
      /*patterns=*/nullptr);
  // TODO(willchan): Figure out a proper way to handle this rather than crash.
  CHECK(ret);

  if (reduce_ip_address_change_notification_) {
    store_ = std::move(store);
    ipv4_primary_interface_name_ =
        get_ipv4_primary_interface_name_callback_.Run(store_.get());
    ipv6_primary_interface_name_ =
        get_ipv6_primary_interface_name_callback_.Run(store_.get());
    interfaces_for_network_change_check_ =
        GetNetworkInterfaceListForNetworkChangeCheck(
            get_network_list_callback_, ipv6_primary_interface_name_);
  }
  if (initialized_callback_for_test_) {
    std::move(initialized_callback_for_test_).Run();
  }
#endif  // BUILDFLAG(IS_IOS) /  BUILDFLAG(IS_MAC)
}

void NetworkChangeNotifierApple::OnNetworkConfigChange(CFArrayRef changed_keys) {
#if BUILDFLAG(IS_IOS)
  // SCDynamicStore API does not exist on iOS.
  NOTREACHED();
#elif BUILDFLAG(IS_MAC)
  DCHECK_EQ(run_loop_.get(), CFRunLoopGetCurrent());

  bool net_ipv4_key_found = false;
  bool net_ipv6_key_found = false;
  bool net_interface_key_found = false;
  for (CFIndex i = 0; i < CFArrayGetCount(changed_keys); ++i) {
    CFStringRef key =
        static_cast<CFStringRef>(CFArrayGetValueAtIndex(changed_keys, i));
    if (CFStringHasSuffix(key, kSCEntNetIPv4)) {
      net_ipv4_key_found = true;
    }
    if (CFStringHasSuffix(key, kSCEntNetIPv6)) {
      net_ipv6_key_found = true;
    }
    if (net_ipv4_key_found || net_ipv6_key_found) {
      break;
    }
    if (CFStringHasSuffix(key, kSCEntNetInterface)) {
      net_interface_key_found = true;
      // TODO(willchan): Does not appear to be working.  Look into this.
      // Perhaps this isn't needed anyway.
    } else {
      NOTREACHED();
    }
  }
  if (!(net_ipv4_key_found || net_ipv6_key_found)) {
    net_log_.AddEvent(net::NetLogEventType::NETWORK_MAC_OS_CONFIG_CHANGED, [&] {
      return NetLogOsConfigChangedParams(
          "DoNotNotify_NoIPAddressChange", net_ipv4_key_found,
          net_ipv6_key_found, net_interface_key_found,
          reduce_ip_address_change_notification_, ipv4_primary_interface_name_,
          ipv6_primary_interface_name_, "", "",
          interfaces_for_network_change_check_, std::nullopt);
    });
    return;
  }
  if (!reduce_ip_address_change_notification_) {
    net_log_.AddEvent(net::NetLogEventType::NETWORK_MAC_OS_CONFIG_CHANGED, [&] {
      return NetLogOsConfigChangedParams(
          "Notify_NoReduce", net_ipv4_key_found, net_ipv6_key_found,
          net_interface_key_found, reduce_ip_address_change_notification_,
          ipv4_primary_interface_name_, ipv6_primary_interface_name_, "", "",
          interfaces_for_network_change_check_, std::nullopt);
    });
    NotifyObserversOfIPAddressChange();
    return;
  }
  // When the ReduceIPAddressChangeNotification feature is enabled, we notifies
  // the IP address change only when:
  //  - The list of network interfaces has changed, excluding local IPv6
  //    addresses of non-primary interfaces.
  //  - or the primary interface name (for IPv4 and IPv6) has changed.
  std::string ipv4_primary_interface_name =
      get_ipv4_primary_interface_name_callback_.Run(store_.get());
  std::string ipv6_primary_interface_name =
      get_ipv6_primary_interface_name_callback_.Run(store_.get());
  std::optional<NetworkInterfaceList> interfaces =
      GetNetworkInterfaceListForNetworkChangeCheck(get_network_list_callback_,
                                                   ipv6_primary_interface_name);
  if (interfaces_for_network_change_check_ && interfaces &&
      interfaces_for_network_change_check_.value() == interfaces.value() &&
      ipv4_primary_interface_name_ == ipv4_primary_interface_name &&
      ipv6_primary_interface_name_ == ipv6_primary_interface_name) {
    net_log_.AddEvent(net::NetLogEventType::NETWORK_MAC_OS_CONFIG_CHANGED, [&] {
      return NetLogOsConfigChangedParams(
          "DoNotNotify_NoChange", net_ipv4_key_found, net_ipv6_key_found,
          net_interface_key_found, reduce_ip_address_change_notification_,
          ipv4_primary_interface_name_, ipv6_primary_interface_name_,
          ipv4_primary_interface_name, ipv6_primary_interface_name,
          interfaces_for_network_change_check_, interfaces);
    });
    return;
  }
  net_log_.AddEvent(net::NetLogEventType::NETWORK_MAC_OS_CONFIG_CHANGED, [&] {
    return NetLogOsConfigChangedParams(
        "Notify_Changed", net_ipv4_key_found, net_ipv6_key_found,
        net_interface_key_found, reduce_ip_address_change_notification_,
        ipv4_primary_interface_name_, ipv6_primary_interface_name_,
        ipv4_primary_interface_name, ipv6_primary_interface_name,
        interfaces_for_network_change_check_, interfaces);
  });
  ipv4_primary_interface_name_ = std::move(ipv4_primary_interface_name);
  ipv6_primary_interface_name_ = std::move(ipv6_primary_interface_name);
  interfaces_for_network_change_check_ = std::move(interfaces);
  NotifyObserversOfIPAddressChange();
#endif  // BUILDFLAG(IS_IOS)
}

void NetworkChangeNotifierApple::CleanUpOnNotifierThread() {
#if BUILDFLAG(IS_MAC)
  store_.reset();
#endif  // BUILDFLAG(IS_MAC)
}

// static
void NetworkChangeNotifierApple::ReachabilityCallback(
    SCNetworkReachabilityRef target,
    SCNetworkConnectionFlags flags,
    void* notifier) {
  NetworkChangeNotifierApple* notifier_apple =
      static_cast<NetworkChangeNotifierApple*>(notifier);

  DCHECK_EQ(notifier_apple->run_loop_.get(), CFRunLoopGetCurrent());

  ConnectionType new_type = CalculateConnectionType(flags);
  ConnectionType old_type;
  {
    base::AutoLock lock(notifier_apple->connection_type_lock_);
    old_type = notifier_apple->connection_type_;
    notifier_apple->connection_type_ = new_type;
  }
  if (old_type != new_type) {
    NotifyObserversOfConnectionTypeChange();
    double max_bandwidth_mbps =
        NetworkChangeNotifier::GetMaxBandwidthMbpsForConnectionSubtype(
            new_type == CONNECTION_NONE ? SUBTYPE_NONE : SUBTYPE_UNKNOWN);
    NotifyObserversOfMaxBandwidthChange(max_bandwidth_mbps, new_type);
  }

#if BUILDFLAG(IS_IOS)
  // On iOS, the SCDynamicStore API does not exist, and we use the reachability
  // API to detect IP address changes instead.
  NotifyObserversOfIPAddressChange();
#endif  // BUILDFLAG(IS_IOS)
}

#if BUILDFLAG(IS_MAC)
void NetworkChangeNotifierApple::SetCallbacksForTest(
    base::OnceClosure initialized_callback,
    base::RepeatingCallback<bool(NetworkInterfaceList*, int)>
        get_network_list_callback,
    base::RepeatingCallback<std::string(SCDynamicStoreRef)>
        get_ipv4_primary_interface_name_callback,
    base::RepeatingCallback<std::string(SCDynamicStoreRef)>
        get_ipv6_primary_interface_name_callback) {
  initialized_callback_for_test_ = std::move(initialized_callback);
  get_network_list_callback_ = std::move(get_network_list_callback);
  get_ipv4_primary_interface_name_callback_ =
      std::move(get_ipv4_primary_interface_name_callback);
  get_ipv6_primary_interface_name_callback_ =
      std::move(get_ipv6_primary_interface_name_callback);
}
#endif  // BUILDFLAG(IS_MAC)

}  // namespace net