summaryrefslogtreecommitdiff
path: root/framework/src/android/net/ConnectivityDiagnosticsManager.java
blob: dcc8a5eacd1386e03688035e54f68465ef25fe0b (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
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.net;

import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StringDef;
import android.content.Context;
import android.os.Binder;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.os.RemoteException;

import com.android.internal.annotations.VisibleForTesting;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;

/**
 * Class that provides utilities for collecting network connectivity diagnostics information.
 * Connectivity information is made available through triggerable diagnostics tools and by listening
 * to System validations. Some diagnostics information may be permissions-restricted.
 *
 * <p>ConnectivityDiagnosticsManager is intended for use by applications offering network
 * connectivity on a user device. These tools will provide several mechanisms for these applications
 * to be alerted to network conditions as well as diagnose potential network issues themselves.
 *
 * <p>The primary responsibilities of this class are to:
 *
 * <ul>
 *   <li>Allow permissioned applications to register and unregister callbacks for network event
 *       notifications
 *   <li>Invoke callbacks for network event notifications, including:
 *       <ul>
 *         <li>Network validations
 *         <li>Data stalls
 *         <li>Connectivity reports from applications
 *       </ul>
 * </ul>
 */
public class ConnectivityDiagnosticsManager {
    /** @hide */
    @VisibleForTesting
    public static final Map<ConnectivityDiagnosticsCallback, ConnectivityDiagnosticsBinder>
            sCallbacks = new ConcurrentHashMap<>();

    private final Context mContext;
    private final IConnectivityManager mService;

    /** @hide */
    public ConnectivityDiagnosticsManager(Context context, IConnectivityManager service) {
        mContext = Objects.requireNonNull(context, "missing context");
        mService = Objects.requireNonNull(service, "missing IConnectivityManager");
    }

    /** @hide */
    @VisibleForTesting
    public static boolean persistableBundleEquals(
            @Nullable PersistableBundle a, @Nullable PersistableBundle b) {
        if (a == b) return true;
        if (a == null || b == null) return false;
        if (!Objects.equals(a.keySet(), b.keySet())) return false;
        for (String key : a.keySet()) {
            if (!Objects.equals(a.get(key), b.get(key))) return false;
        }
        return true;
    }

    /** Class that includes connectivity information for a specific Network at a specific time. */
    public static final class ConnectivityReport implements Parcelable {
        /**
         * The overall status of the network is that it is invalid; it neither provides
         * connectivity nor has been exempted from validation.
         */
        public static final int NETWORK_VALIDATION_RESULT_INVALID = 0;

        /**
         * The overall status of the network is that it is valid, this may be because it provides
         * full Internet access (all probes succeeded), or because other properties of the network
         * caused probes not to be run.
         */
        // TODO: link to INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID
        public static final int NETWORK_VALIDATION_RESULT_VALID = 1;

        /**
         * The overall status of the network is that it provides partial connectivity; some
         * probed services succeeded but others failed.
         */
        // TODO: link to INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
        public static final int NETWORK_VALIDATION_RESULT_PARTIALLY_VALID = 2;

        /**
         * Due to the properties of the network, validation was not performed.
         */
        public static final int NETWORK_VALIDATION_RESULT_SKIPPED = 3;

        /** @hide */
        @IntDef(
                prefix = {"NETWORK_VALIDATION_RESULT_"},
                value = {
                        NETWORK_VALIDATION_RESULT_INVALID,
                        NETWORK_VALIDATION_RESULT_VALID,
                        NETWORK_VALIDATION_RESULT_PARTIALLY_VALID,
                        NETWORK_VALIDATION_RESULT_SKIPPED
                })
        @Retention(RetentionPolicy.SOURCE)
        public @interface NetworkValidationResult {}

        /**
         * The overall validation result for the Network being reported on.
         *
         * <p>The possible values for this key are:
         * {@link #NETWORK_VALIDATION_RESULT_INVALID},
         * {@link #NETWORK_VALIDATION_RESULT_VALID},
         * {@link #NETWORK_VALIDATION_RESULT_PARTIALLY_VALID},
         * {@link #NETWORK_VALIDATION_RESULT_SKIPPED}.
         *
         * @see android.net.NetworkCapabilities#NET_CAPABILITY_VALIDATED
         */
        @NetworkValidationResult
        public static final String KEY_NETWORK_VALIDATION_RESULT = "networkValidationResult";

        /** DNS probe. */
        // TODO: link to INetworkMonitor.NETWORK_VALIDATION_PROBE_DNS
        public static final int NETWORK_PROBE_DNS = 0x04;

        /** HTTP probe. */
        // TODO: link to INetworkMonitor.NETWORK_VALIDATION_PROBE_HTTP
        public static final int NETWORK_PROBE_HTTP = 0x08;

        /** HTTPS probe. */
        // TODO: link to INetworkMonitor.NETWORK_VALIDATION_PROBE_HTTPS;
        public static final int NETWORK_PROBE_HTTPS = 0x10;

        /** Captive portal fallback probe. */
        // TODO: link to INetworkMonitor.NETWORK_VALIDATION_FALLBACK
        public static final int NETWORK_PROBE_FALLBACK = 0x20;

        /** Private DNS (DNS over TLS) probd. */
        // TODO: link to INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS
        public static final int NETWORK_PROBE_PRIVATE_DNS = 0x40;

        /** @hide */
        @IntDef(
                prefix = {"NETWORK_PROBE_"},
                value = {
                        NETWORK_PROBE_DNS,
                        NETWORK_PROBE_HTTP,
                        NETWORK_PROBE_HTTPS,
                        NETWORK_PROBE_FALLBACK,
                        NETWORK_PROBE_PRIVATE_DNS
                })
        @Retention(RetentionPolicy.SOURCE)
        public @interface NetworkProbe {}

        /**
         * A bitmask of network validation probes that succeeded.
         *
         * <p>The possible bits values reported by this key are:
         * {@link #NETWORK_PROBE_DNS},
         * {@link #NETWORK_PROBE_HTTP},
         * {@link #NETWORK_PROBE_HTTPS},
         * {@link #NETWORK_PROBE_FALLBACK},
         * {@link #NETWORK_PROBE_PRIVATE_DNS}.
         */
        @NetworkProbe
        public static final String KEY_NETWORK_PROBES_SUCCEEDED_BITMASK =
                "networkProbesSucceeded";

        /**
         * A bitmask of network validation probes that were attempted.
         *
         * <p>These probes may have failed or may be incomplete at the time of this report.
         *
         * <p>The possible bits values reported by this key are:
         * {@link #NETWORK_PROBE_DNS},
         * {@link #NETWORK_PROBE_HTTP},
         * {@link #NETWORK_PROBE_HTTPS},
         * {@link #NETWORK_PROBE_FALLBACK},
         * {@link #NETWORK_PROBE_PRIVATE_DNS}.
         */
        @NetworkProbe
        public static final String KEY_NETWORK_PROBES_ATTEMPTED_BITMASK =
                "networkProbesAttempted";

        /** @hide */
        @StringDef(prefix = {"KEY_"}, value = {
                KEY_NETWORK_VALIDATION_RESULT, KEY_NETWORK_PROBES_SUCCEEDED_BITMASK,
                KEY_NETWORK_PROBES_ATTEMPTED_BITMASK})
        @Retention(RetentionPolicy.SOURCE)
        public @interface ConnectivityReportBundleKeys {}

        /** The Network for which this ConnectivityReport applied */
        @NonNull private final Network mNetwork;

        /**
         * The timestamp for the report. The timestamp is taken from {@link
         * System#currentTimeMillis}.
         */
        private final long mReportTimestamp;

        /** LinkProperties available on the Network at the reported timestamp */
        @NonNull private final LinkProperties mLinkProperties;

        /** NetworkCapabilities available on the Network at the reported timestamp */
        @NonNull private final NetworkCapabilities mNetworkCapabilities;

        /** PersistableBundle that may contain additional info about the report */
        @NonNull private final PersistableBundle mAdditionalInfo;

        /**
         * Constructor for ConnectivityReport.
         *
         * <p>Apps should obtain instances through {@link
         * ConnectivityDiagnosticsCallback#onConnectivityReportAvailable} instead of instantiating
         * their own instances (unless for testing purposes).
         *
         * @param network The Network for which this ConnectivityReport applies
         * @param reportTimestamp The timestamp for the report
         * @param linkProperties The LinkProperties available on network at reportTimestamp
         * @param networkCapabilities The NetworkCapabilities available on network at
         *     reportTimestamp
         * @param additionalInfo A PersistableBundle that may contain additional info about the
         *     report
         */
        public ConnectivityReport(
                @NonNull Network network,
                long reportTimestamp,
                @NonNull LinkProperties linkProperties,
                @NonNull NetworkCapabilities networkCapabilities,
                @NonNull PersistableBundle additionalInfo) {
            mNetwork = network;
            mReportTimestamp = reportTimestamp;
            mLinkProperties = new LinkProperties(linkProperties);
            mNetworkCapabilities = new NetworkCapabilities(networkCapabilities);
            mAdditionalInfo = additionalInfo;
        }

        /**
         * Returns the Network for this ConnectivityReport.
         *
         * @return The Network for which this ConnectivityReport applied
         */
        @NonNull
        public Network getNetwork() {
            return mNetwork;
        }

        /**
         * Returns the epoch timestamp (milliseconds) for when this report was taken.
         *
         * @return The timestamp for the report. Taken from {@link System#currentTimeMillis}.
         */
        public long getReportTimestamp() {
            return mReportTimestamp;
        }

        /**
         * Returns the LinkProperties available when this report was taken.
         *
         * @return LinkProperties available on the Network at the reported timestamp
         */
        @NonNull
        public LinkProperties getLinkProperties() {
            return new LinkProperties(mLinkProperties);
        }

        /**
         * Returns the NetworkCapabilities when this report was taken.
         *
         * @return NetworkCapabilities available on the Network at the reported timestamp
         */
        @NonNull
        public NetworkCapabilities getNetworkCapabilities() {
            return new NetworkCapabilities(mNetworkCapabilities);
        }

        /**
         * Returns a PersistableBundle with additional info for this report.
         *
         * @return PersistableBundle that may contain additional info about the report
         */
        @NonNull
        public PersistableBundle getAdditionalInfo() {
            return new PersistableBundle(mAdditionalInfo);
        }

        @Override
        public boolean equals(@Nullable Object o) {
            if (this == o) return true;
            if (!(o instanceof ConnectivityReport)) return false;
            final ConnectivityReport that = (ConnectivityReport) o;

            // PersistableBundle is optimized to avoid unparcelling data unless fields are
            // referenced. Because of this, use {@link ConnectivityDiagnosticsManager#equals} over
            // {@link PersistableBundle#kindofEquals}.
            return mReportTimestamp == that.mReportTimestamp
                    && mNetwork.equals(that.mNetwork)
                    && mLinkProperties.equals(that.mLinkProperties)
                    && mNetworkCapabilities.equals(that.mNetworkCapabilities)
                    && persistableBundleEquals(mAdditionalInfo, that.mAdditionalInfo);
        }

        @Override
        public int hashCode() {
            return Objects.hash(
                    mNetwork,
                    mReportTimestamp,
                    mLinkProperties,
                    mNetworkCapabilities,
                    mAdditionalInfo);
        }

        /** {@inheritDoc} */
        @Override
        public int describeContents() {
            return 0;
        }

        /** {@inheritDoc} */
        @Override
        public void writeToParcel(@NonNull Parcel dest, int flags) {
            dest.writeParcelable(mNetwork, flags);
            dest.writeLong(mReportTimestamp);
            dest.writeParcelable(mLinkProperties, flags);
            dest.writeParcelable(mNetworkCapabilities, flags);
            dest.writeParcelable(mAdditionalInfo, flags);
        }

        /** Implement the Parcelable interface */
        public static final @NonNull Creator<ConnectivityReport> CREATOR =
                new Creator<ConnectivityReport>() {
                    public ConnectivityReport createFromParcel(Parcel in) {
                        return new ConnectivityReport(
                                in.readParcelable(null),
                                in.readLong(),
                                in.readParcelable(null),
                                in.readParcelable(null),
                                in.readParcelable(null));
                    }

                    public ConnectivityReport[] newArray(int size) {
                        return new ConnectivityReport[size];
                    }
                };
    }

    /** Class that includes information for a suspected data stall on a specific Network */
    public static final class DataStallReport implements Parcelable {
        /**
         * Indicates that the Data Stall was detected using DNS events.
         */
        public static final int DETECTION_METHOD_DNS_EVENTS = 1;

        /**
         * Indicates that the Data Stall was detected using TCP metrics.
         */
        public static final int DETECTION_METHOD_TCP_METRICS = 2;

        /** @hide */
        @Retention(RetentionPolicy.SOURCE)
        @IntDef(
                prefix = {"DETECTION_METHOD_"},
                value = {DETECTION_METHOD_DNS_EVENTS, DETECTION_METHOD_TCP_METRICS})
        public @interface DetectionMethod {}

        /**
         * This key represents the period in milliseconds over which other included TCP metrics
         * were measured.
         *
         * <p>This key will be included if the data stall detection method is
         * {@link #DETECTION_METHOD_TCP_METRICS}.
         *
         * <p>This value is an int.
         */
        public static final String KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS =
                "tcpMetricsCollectionPeriodMillis";

        /**
         * This key represents the fail rate of TCP packets when the suspected data stall was
         * detected.
         *
         * <p>This key will be included if the data stall detection method is
         * {@link #DETECTION_METHOD_TCP_METRICS}.
         *
         * <p>This value is an int percentage between 0 and 100.
         */
        public static final String KEY_TCP_PACKET_FAIL_RATE = "tcpPacketFailRate";

        /**
         * This key represents the consecutive number of DNS timeouts that have occurred.
         *
         * <p>The consecutive count will be reset any time a DNS response is received.
         *
         * <p>This key will be included if the data stall detection method is
         * {@link #DETECTION_METHOD_DNS_EVENTS}.
         *
         * <p>This value is an int.
         */
        public static final String KEY_DNS_CONSECUTIVE_TIMEOUTS = "dnsConsecutiveTimeouts";

        /** @hide */
        @Retention(RetentionPolicy.SOURCE)
        @StringDef(prefix = {"KEY_"}, value = {
                KEY_TCP_PACKET_FAIL_RATE,
                KEY_DNS_CONSECUTIVE_TIMEOUTS
        })
        public @interface DataStallReportBundleKeys {}

        /** The Network for which this DataStallReport applied */
        @NonNull private final Network mNetwork;

        /**
         * The timestamp for the report. The timestamp is taken from {@link
         * System#currentTimeMillis}.
         */
        private long mReportTimestamp;

        /** A bitmask of the detection methods used to identify the suspected data stall */
        @DetectionMethod private final int mDetectionMethod;

        /** LinkProperties available on the Network at the reported timestamp */
        @NonNull private final LinkProperties mLinkProperties;

        /** NetworkCapabilities available on the Network at the reported timestamp */
        @NonNull private final NetworkCapabilities mNetworkCapabilities;

        /** PersistableBundle that may contain additional information on the suspected data stall */
        @NonNull private final PersistableBundle mStallDetails;

        /**
         * Constructor for DataStallReport.
         *
         * <p>Apps should obtain instances through {@link
         * ConnectivityDiagnosticsCallback#onDataStallSuspected} instead of instantiating their own
         * instances (unless for testing purposes).
         *
         * @param network The Network for which this DataStallReport applies
         * @param reportTimestamp The timestamp for the report
         * @param detectionMethod The detection method used to identify this data stall
         * @param linkProperties The LinkProperties available on network at reportTimestamp
         * @param networkCapabilities The NetworkCapabilities available on network at
         *     reportTimestamp
         * @param stallDetails A PersistableBundle that may contain additional info about the report
         */
        public DataStallReport(
                @NonNull Network network,
                long reportTimestamp,
                @DetectionMethod int detectionMethod,
                @NonNull LinkProperties linkProperties,
                @NonNull NetworkCapabilities networkCapabilities,
                @NonNull PersistableBundle stallDetails) {
            mNetwork = network;
            mReportTimestamp = reportTimestamp;
            mDetectionMethod = detectionMethod;
            mLinkProperties = new LinkProperties(linkProperties);
            mNetworkCapabilities = new NetworkCapabilities(networkCapabilities);
            mStallDetails = stallDetails;
        }

        /**
         * Returns the Network for this DataStallReport.
         *
         * @return The Network for which this DataStallReport applied
         */
        @NonNull
        public Network getNetwork() {
            return mNetwork;
        }

        /**
         * Returns the epoch timestamp (milliseconds) for when this report was taken.
         *
         * @return The timestamp for the report. Taken from {@link System#currentTimeMillis}.
         */
        public long getReportTimestamp() {
            return mReportTimestamp;
        }

        /**
         * Returns the bitmask of detection methods used to identify this suspected data stall.
         *
         * @return The bitmask of detection methods used to identify the suspected data stall
         */
        public int getDetectionMethod() {
            return mDetectionMethod;
        }

        /**
         * Returns the LinkProperties available when this report was taken.
         *
         * @return LinkProperties available on the Network at the reported timestamp
         */
        @NonNull
        public LinkProperties getLinkProperties() {
            return new LinkProperties(mLinkProperties);
        }

        /**
         * Returns the NetworkCapabilities when this report was taken.
         *
         * @return NetworkCapabilities available on the Network at the reported timestamp
         */
        @NonNull
        public NetworkCapabilities getNetworkCapabilities() {
            return new NetworkCapabilities(mNetworkCapabilities);
        }

        /**
         * Returns a PersistableBundle with additional info for this report.
         *
         * <p>Gets a bundle with details about the suspected data stall including information
         * specific to the monitoring method that detected the data stall.
         *
         * @return PersistableBundle that may contain additional information on the suspected data
         *     stall
         */
        @NonNull
        public PersistableBundle getStallDetails() {
            return new PersistableBundle(mStallDetails);
        }

        @Override
        public boolean equals(@Nullable Object o) {
            if (this == o) return true;
            if (!(o instanceof DataStallReport)) return false;
            final DataStallReport that = (DataStallReport) o;

            // PersistableBundle is optimized to avoid unparcelling data unless fields are
            // referenced. Because of this, use {@link ConnectivityDiagnosticsManager#equals} over
            // {@link PersistableBundle#kindofEquals}.
            return mReportTimestamp == that.mReportTimestamp
                    && mDetectionMethod == that.mDetectionMethod
                    && mNetwork.equals(that.mNetwork)
                    && mLinkProperties.equals(that.mLinkProperties)
                    && mNetworkCapabilities.equals(that.mNetworkCapabilities)
                    && persistableBundleEquals(mStallDetails, that.mStallDetails);
        }

        @Override
        public int hashCode() {
            return Objects.hash(
                    mNetwork,
                    mReportTimestamp,
                    mDetectionMethod,
                    mLinkProperties,
                    mNetworkCapabilities,
                    mStallDetails);
        }

        /** {@inheritDoc} */
        @Override
        public int describeContents() {
            return 0;
        }

        /** {@inheritDoc} */
        @Override
        public void writeToParcel(@NonNull Parcel dest, int flags) {
            dest.writeParcelable(mNetwork, flags);
            dest.writeLong(mReportTimestamp);
            dest.writeInt(mDetectionMethod);
            dest.writeParcelable(mLinkProperties, flags);
            dest.writeParcelable(mNetworkCapabilities, flags);
            dest.writeParcelable(mStallDetails, flags);
        }

        /** Implement the Parcelable interface */
        public static final @NonNull Creator<DataStallReport> CREATOR =
                new Creator<DataStallReport>() {
                    public DataStallReport createFromParcel(Parcel in) {
                        return new DataStallReport(
                                in.readParcelable(null),
                                in.readLong(),
                                in.readInt(),
                                in.readParcelable(null),
                                in.readParcelable(null),
                                in.readParcelable(null));
                    }

                    public DataStallReport[] newArray(int size) {
                        return new DataStallReport[size];
                    }
                };
    }

    /** @hide */
    @VisibleForTesting
    public static class ConnectivityDiagnosticsBinder
            extends IConnectivityDiagnosticsCallback.Stub {
        @NonNull private final ConnectivityDiagnosticsCallback mCb;
        @NonNull private final Executor mExecutor;

        /** @hide */
        @VisibleForTesting
        public ConnectivityDiagnosticsBinder(
                @NonNull ConnectivityDiagnosticsCallback cb, @NonNull Executor executor) {
            this.mCb = cb;
            this.mExecutor = executor;
        }

        /** @hide */
        @VisibleForTesting
        public void onConnectivityReportAvailable(@NonNull ConnectivityReport report) {
            final long token = Binder.clearCallingIdentity();
            try {
                mExecutor.execute(() -> {
                    mCb.onConnectivityReportAvailable(report);
                });
            } finally {
                Binder.restoreCallingIdentity(token);
            }
        }

        /** @hide */
        @VisibleForTesting
        public void onDataStallSuspected(@NonNull DataStallReport report) {
            final long token = Binder.clearCallingIdentity();
            try {
                mExecutor.execute(() -> {
                    mCb.onDataStallSuspected(report);
                });
            } finally {
                Binder.restoreCallingIdentity(token);
            }
        }

        /** @hide */
        @VisibleForTesting
        public void onNetworkConnectivityReported(
                @NonNull Network network, boolean hasConnectivity) {
            final long token = Binder.clearCallingIdentity();
            try {
                mExecutor.execute(() -> {
                    mCb.onNetworkConnectivityReported(network, hasConnectivity);
                });
            } finally {
                Binder.restoreCallingIdentity(token);
            }
        }
    }

    /**
     * Abstract base class for Connectivity Diagnostics callbacks. Used for notifications about
     * network connectivity events. Must be extended by applications wanting notifications.
     */
    public abstract static class ConnectivityDiagnosticsCallback {
        /**
         * Called when the platform completes a data connectivity check. This will also be invoked
         * immediately upon registration for each network matching the request with the latest
         * report, if a report has already been generated for that network.
         *
         * <p>The Network specified in the ConnectivityReport may not be active any more when this
         * method is invoked.
         *
         * @param report The ConnectivityReport containing information about a connectivity check
         */
        public void onConnectivityReportAvailable(@NonNull ConnectivityReport report) {}

        /**
         * Called when the platform suspects a data stall on some Network.
         *
         * <p>The Network specified in the DataStallReport may not be active any more when this
         * method is invoked.
         *
         * @param report The DataStallReport containing information about the suspected data stall
         */
        public void onDataStallSuspected(@NonNull DataStallReport report) {}

        /**
         * Called when any app reports connectivity to the System.
         *
         * @param network The Network for which connectivity has been reported
         * @param hasConnectivity The connectivity reported to the System
         */
        public void onNetworkConnectivityReported(
                @NonNull Network network, boolean hasConnectivity) {}
    }

    /**
     * Registers a ConnectivityDiagnosticsCallback with the System.
     *
     * <p>Only apps that offer network connectivity to the user should be registering callbacks.
     * These are the only apps whose callbacks will be invoked by the system. Apps considered to
     * meet these conditions include:
     *
     * <ul>
     *   <li>Carrier apps with active subscriptions
     *   <li>Active VPNs
     *   <li>WiFi Suggesters
     * </ul>
     *
     * <p>Callbacks registered by apps not meeting the above criteria will not be invoked.
     *
     * <p>If a registering app loses its relevant permissions, any callbacks it registered will
     * silently stop receiving callbacks. Note that registering apps must also have location
     * permissions to receive callbacks as some Networks may be location-bound (such as WiFi
     * networks).
     *
     * <p>Each register() call <b>MUST</b> use a ConnectivityDiagnosticsCallback instance that is
     * not currently registered. If a ConnectivityDiagnosticsCallback instance is registered with
     * multiple NetworkRequests, an IllegalArgumentException will be thrown.
     *
     * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
     * number of outstanding requests to 100 per app (identified by their UID), shared with
     * callbacks in {@link ConnectivityManager}. Registering a callback with this method will count
     * toward this limit. If this limit is exceeded, an exception will be thrown. To avoid hitting
     * this issue and to conserve resources, make sure to unregister the callbacks with
     * {@link #unregisterConnectivityDiagnosticsCallback}.
     *
     * @param request The NetworkRequest that will be used to match with Networks for which
     *     callbacks will be fired
     * @param e The Executor to be used for running the callback method invocations
     * @param callback The ConnectivityDiagnosticsCallback that the caller wants registered with the
     *     System
     * @throws IllegalArgumentException if the same callback instance is registered with multiple
     *     NetworkRequests
     * @throws RuntimeException if the app already has too many callbacks registered.
     */
    public void registerConnectivityDiagnosticsCallback(
            @NonNull NetworkRequest request,
            @NonNull Executor e,
            @NonNull ConnectivityDiagnosticsCallback callback) {
        final ConnectivityDiagnosticsBinder binder = new ConnectivityDiagnosticsBinder(callback, e);
        if (sCallbacks.putIfAbsent(callback, binder) != null) {
            throw new IllegalArgumentException("Callback is currently registered");
        }

        try {
            mService.registerConnectivityDiagnosticsCallback(
                    binder, request, mContext.getOpPackageName());
        } catch (RemoteException exception) {
            exception.rethrowFromSystemServer();
        }
    }

    /**
     * Unregisters a ConnectivityDiagnosticsCallback with the System.
     *
     * <p>If the given callback is not currently registered with the System, this operation will be
     * a no-op.
     *
     * @param callback The ConnectivityDiagnosticsCallback to be unregistered from the System.
     */
    public void unregisterConnectivityDiagnosticsCallback(
            @NonNull ConnectivityDiagnosticsCallback callback) {
        // unconditionally removing from sCallbacks prevents race conditions here, since remove() is
        // atomic.
        final ConnectivityDiagnosticsBinder binder = sCallbacks.remove(callback);
        if (binder == null) return;

        try {
            mService.unregisterConnectivityDiagnosticsCallback(binder);
        } catch (RemoteException exception) {
            exception.rethrowFromSystemServer();
        }
    }
}