blob: 6f1466ce91f1bd0737ab242889b6053e44b9e65c [file] [log] [blame]
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
20import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
24import static android.content.pm.PackageManager.PERMISSION_GRANTED;
25import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
33import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
35import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
36import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
37import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
38import static android.net.ConnectivityManager.TYPE_ETHERNET;
39import static android.net.ConnectivityManager.TYPE_MOBILE;
40import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
41import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
42import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
43import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
44import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
46import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
49import static android.net.ConnectivityManager.TYPE_NONE;
50import static android.net.ConnectivityManager.TYPE_PROXY;
51import static android.net.ConnectivityManager.TYPE_VPN;
52import static android.net.ConnectivityManager.TYPE_WIFI;
53import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
54import static android.net.ConnectivityManager.getNetworkTypeName;
55import static android.net.ConnectivityManager.isNetworkTypeValid;
56import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
57import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
58import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
59import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
60import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
61import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
62import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
63import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
64import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
65import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
66import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
67import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
68import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
69import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
70import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
71import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
72import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
73import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
75import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
76import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
77import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
78import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
79import static android.net.NetworkCapabilities.TRANSPORT_TEST;
80import static android.net.NetworkCapabilities.TRANSPORT_VPN;
81import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
82import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
83import static android.os.Process.INVALID_UID;
84import static android.os.Process.VPN_UID;
85import static android.system.OsConstants.IPPROTO_TCP;
86import static android.system.OsConstants.IPPROTO_UDP;
87
88import static java.util.Map.Entry;
89
90import android.Manifest;
91import android.annotation.NonNull;
92import android.annotation.Nullable;
93import android.app.AppOpsManager;
94import android.app.BroadcastOptions;
95import android.app.PendingIntent;
96import android.app.usage.NetworkStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.ContentResolver;
100import android.content.Context;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.pm.PackageManager;
104import android.database.ContentObserver;
105import android.net.CaptivePortal;
106import android.net.CaptivePortalData;
107import android.net.ConnectionInfo;
Aaron Huang6a7e6ad2021-04-14 01:25:55 +0800108import android.net.ConnectivityAnnotations.RestrictBackgroundStatus;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000109import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
110import android.net.ConnectivityDiagnosticsManager.DataStallReport;
111import android.net.ConnectivityManager;
112import android.net.ConnectivityManager.BlockedReason;
113import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000114import android.net.ConnectivityResources;
115import android.net.ConnectivitySettingsManager;
116import android.net.DataStallReportParcelable;
117import android.net.DnsResolverServiceManager;
118import android.net.ICaptivePortal;
119import android.net.IConnectivityDiagnosticsCallback;
120import android.net.IConnectivityManager;
121import android.net.IDnsResolver;
122import android.net.INetd;
123import android.net.INetworkActivityListener;
124import android.net.INetworkAgent;
125import android.net.INetworkMonitor;
126import android.net.INetworkMonitorCallbacks;
127import android.net.INetworkOfferCallback;
128import android.net.IOnCompleteListener;
129import android.net.IQosCallback;
130import android.net.ISocketKeepaliveCallback;
131import android.net.InetAddresses;
132import android.net.IpMemoryStore;
133import android.net.IpPrefix;
134import android.net.LinkProperties;
135import android.net.MatchAllNetworkSpecifier;
136import android.net.NativeNetworkConfig;
137import android.net.NativeNetworkType;
138import android.net.NattSocketKeepalive;
139import android.net.Network;
140import android.net.NetworkAgent;
141import android.net.NetworkAgentConfig;
142import android.net.NetworkCapabilities;
143import android.net.NetworkInfo;
144import android.net.NetworkInfo.DetailedState;
145import android.net.NetworkMonitorManager;
146import android.net.NetworkPolicyManager;
147import android.net.NetworkPolicyManager.NetworkPolicyCallback;
148import android.net.NetworkProvider;
149import android.net.NetworkRequest;
150import android.net.NetworkScore;
151import android.net.NetworkSpecifier;
152import android.net.NetworkStack;
153import android.net.NetworkState;
154import android.net.NetworkStateSnapshot;
155import android.net.NetworkTestResultParcelable;
156import android.net.NetworkUtils;
157import android.net.NetworkWatchlistManager;
158import android.net.OemNetworkPreferences;
159import android.net.PrivateDnsConfigParcel;
160import android.net.ProxyInfo;
161import android.net.QosCallbackException;
162import android.net.QosFilter;
163import android.net.QosSocketFilter;
164import android.net.QosSocketInfo;
165import android.net.RouteInfo;
166import android.net.RouteInfoParcel;
167import android.net.SocketKeepalive;
168import android.net.TetheringManager;
169import android.net.TransportInfo;
170import android.net.UidRange;
171import android.net.UidRangeParcel;
172import android.net.UnderlyingNetworkInfo;
173import android.net.Uri;
174import android.net.VpnManager;
175import android.net.VpnTransportInfo;
176import android.net.metrics.IpConnectivityLog;
177import android.net.metrics.NetworkEvent;
178import android.net.netlink.InetDiagMessage;
179import android.net.networkstack.ModuleNetworkStackClient;
180import android.net.networkstack.NetworkStackClientBase;
181import android.net.resolv.aidl.DnsHealthEventParcel;
182import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
183import android.net.resolv.aidl.Nat64PrefixEventParcel;
184import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
185import android.net.shared.PrivateDnsConfig;
186import android.net.util.MultinetworkPolicyTracker;
187import android.os.BatteryStatsManager;
188import android.os.Binder;
189import android.os.Build;
190import android.os.Bundle;
191import android.os.Handler;
192import android.os.HandlerThread;
193import android.os.IBinder;
194import android.os.Looper;
195import android.os.Message;
196import android.os.Messenger;
197import android.os.ParcelFileDescriptor;
198import android.os.Parcelable;
199import android.os.PersistableBundle;
200import android.os.PowerManager;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ServiceSpecificException;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.UserHandle;
208import android.os.UserManager;
209import android.provider.Settings;
210import android.sysprop.NetworkProperties;
211import android.telephony.TelephonyManager;
212import android.text.TextUtils;
213import android.util.ArrayMap;
214import android.util.ArraySet;
215import android.util.LocalLog;
216import android.util.Log;
217import android.util.Pair;
218import android.util.SparseArray;
219import android.util.SparseIntArray;
220
221import com.android.connectivity.resources.R;
222import com.android.internal.annotations.GuardedBy;
223import com.android.internal.annotations.VisibleForTesting;
224import com.android.internal.util.IndentingPrintWriter;
225import com.android.internal.util.MessageUtils;
226import com.android.modules.utils.BasicShellCommandHandler;
227import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
228import com.android.net.module.util.CollectionUtils;
229import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
230import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
231import com.android.net.module.util.LocationPermissionChecker;
232import com.android.net.module.util.NetworkCapabilitiesUtils;
233import com.android.net.module.util.PermissionUtils;
234import com.android.server.connectivity.AutodestructReference;
235import com.android.server.connectivity.DnsManager;
236import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
237import com.android.server.connectivity.FullScore;
238import com.android.server.connectivity.KeepaliveTracker;
239import com.android.server.connectivity.LingerMonitor;
240import com.android.server.connectivity.MockableSystemProperties;
241import com.android.server.connectivity.NetworkAgentInfo;
242import com.android.server.connectivity.NetworkDiagnostics;
243import com.android.server.connectivity.NetworkNotificationManager;
244import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
245import com.android.server.connectivity.NetworkOffer;
246import com.android.server.connectivity.NetworkRanker;
247import com.android.server.connectivity.PermissionMonitor;
248import com.android.server.connectivity.ProfileNetworkPreferences;
249import com.android.server.connectivity.ProxyTracker;
250import com.android.server.connectivity.QosCallbackTracker;
251
252import libcore.io.IoUtils;
253
254import java.io.FileDescriptor;
255import java.io.PrintWriter;
256import java.net.Inet4Address;
257import java.net.InetAddress;
258import java.net.InetSocketAddress;
259import java.net.UnknownHostException;
260import java.util.ArrayList;
261import java.util.Arrays;
262import java.util.Collection;
263import java.util.Collections;
264import java.util.Comparator;
265import java.util.ConcurrentModificationException;
266import java.util.HashMap;
267import java.util.HashSet;
268import java.util.List;
269import java.util.Map;
270import java.util.Objects;
271import java.util.Set;
272import java.util.SortedSet;
273import java.util.StringJoiner;
274import java.util.TreeSet;
275import java.util.concurrent.atomic.AtomicInteger;
276
277/**
278 * @hide
279 */
280public class ConnectivityService extends IConnectivityManager.Stub
281 implements PendingIntent.OnFinished {
282 private static final String TAG = ConnectivityService.class.getSimpleName();
283
284 private static final String DIAG_ARG = "--diag";
285 public static final String SHORT_ARG = "--short";
286 private static final String NETWORK_ARG = "networks";
287 private static final String REQUEST_ARG = "requests";
288
289 private static final boolean DBG = true;
290 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
291 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
292
293 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
294
295 /**
296 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
297 * by OEMs for configuration purposes, as this value is overridden by
298 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
299 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
300 * (preferably via runtime resource overlays).
301 */
302 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
303 "http://connectivitycheck.gstatic.com/generate_204";
304
305 // TODO: create better separation between radio types and network types
306
307 // how long to wait before switching back to a radio's default network
308 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
309 // system property that can override the above value
310 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
311 "android.telephony.apn-restore";
312
313 // How long to wait before putting up a "This network doesn't have an Internet connection,
314 // connect anyway?" dialog after the user selects a network that doesn't validate.
315 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
316
317 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
318 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
319 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
320 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
321
322 // The maximum number of network request allowed per uid before an exception is thrown.
323 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
324
325 // The maximum number of network request allowed for system UIDs before an exception is thrown.
326 @VisibleForTesting
327 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
328
329 @VisibleForTesting
330 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
331 @VisibleForTesting
332 protected int mNascentDelayMs;
333
334 // How long to delay to removal of a pending intent based request.
335 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
336 private final int mReleasePendingIntentDelayMs;
337
338 private MockableSystemProperties mSystemProperties;
339
340 @VisibleForTesting
341 protected final PermissionMonitor mPermissionMonitor;
342
343 private final PerUidCounter mNetworkRequestCounter;
344 @VisibleForTesting
345 final PerUidCounter mSystemNetworkRequestCounter;
346
347 private volatile boolean mLockdownEnabled;
348
349 /**
350 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
351 * internal handler thread, they don't need a lock.
352 */
353 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
354
355 private final Context mContext;
356 private final ConnectivityResources mResources;
357 // The Context is created for UserHandle.ALL.
358 private final Context mUserAllContext;
359 private final Dependencies mDeps;
360 // 0 is full bad, 100 is full good
361 private int mDefaultInetConditionPublished = 0;
362
363 @VisibleForTesting
364 protected IDnsResolver mDnsResolver;
365 @VisibleForTesting
366 protected INetd mNetd;
367 private NetworkStatsManager mStatsManager;
368 private NetworkPolicyManager mPolicyManager;
369 private final NetdCallback mNetdCallback;
370
371 /**
372 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
373 * instances.
374 */
375 @GuardedBy("mTNSLock")
376 private TestNetworkService mTNS;
377
378 private final Object mTNSLock = new Object();
379
380 private String mCurrentTcpBufferSizes;
381
382 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
383 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
384
385 private enum ReapUnvalidatedNetworks {
386 // Tear down networks that have no chance (e.g. even if validated) of becoming
387 // the highest scoring network satisfying a NetworkRequest. This should be passed when
388 // all networks have been rematched against all NetworkRequests.
389 REAP,
390 // Don't reap networks. This should be passed when some networks have not yet been
391 // rematched against all NetworkRequests.
392 DONT_REAP
393 }
394
395 private enum UnneededFor {
396 LINGER, // Determine whether this network is unneeded and should be lingered.
397 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
398 }
399
400 /**
401 * used internally to clear a wakelock when transitioning
402 * from one net to another. Clear happens when we get a new
403 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
404 * after a timeout if no network is found (typically 1 min).
405 */
406 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
407
408 /**
409 * used internally to reload global proxy settings
410 */
411 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
412
413 /**
414 * PAC manager has received new port.
415 */
416 private static final int EVENT_PROXY_HAS_CHANGED = 16;
417
418 /**
419 * used internally when registering NetworkProviders
420 * obj = NetworkProviderInfo
421 */
422 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
423
424 /**
425 * used internally when registering NetworkAgents
426 * obj = Messenger
427 */
428 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
429
430 /**
431 * used to add a network request
432 * includes a NetworkRequestInfo
433 */
434 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
435
436 /**
437 * indicates a timeout period is over - check if we had a network yet or not
438 * and if not, call the timeout callback (but leave the request live until they
439 * cancel it.
440 * includes a NetworkRequestInfo
441 */
442 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
443
444 /**
445 * used to add a network listener - no request
446 * includes a NetworkRequestInfo
447 */
448 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
449
450 /**
451 * used to remove a network request, either a listener or a real request
452 * arg1 = UID of caller
453 * obj = NetworkRequest
454 */
455 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
456
457 /**
458 * used internally when registering NetworkProviders
459 * obj = Messenger
460 */
461 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
462
463 /**
464 * used internally to expire a wakelock when transitioning
465 * from one net to another. Expire happens when we fail to find
466 * a new network (typically after 1 minute) -
467 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
468 * a replacement network.
469 */
470 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
471
472 /**
473 * used to add a network request with a pending intent
474 * obj = NetworkRequestInfo
475 */
476 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
477
478 /**
479 * used to remove a pending intent and its associated network request.
480 * arg1 = UID of caller
481 * obj = PendingIntent
482 */
483 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
484
485 /**
486 * used to specify whether a network should be used even if unvalidated.
487 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
488 * arg2 = whether to remember this choice in the future (1 or 0)
489 * obj = network
490 */
491 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
492
493 /**
494 * used to ask the user to confirm a connection to an unvalidated network.
495 * obj = network
496 */
497 private static final int EVENT_PROMPT_UNVALIDATED = 29;
498
499 /**
500 * used internally to (re)configure always-on networks.
501 */
502 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
503
504 /**
505 * used to add a network listener with a pending intent
506 * obj = NetworkRequestInfo
507 */
508 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
509
510 /**
511 * used to specify whether a network should not be penalized when it becomes unvalidated.
512 */
513 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
514
515 /**
516 * used to trigger revalidation of a network.
517 */
518 private static final int EVENT_REVALIDATE_NETWORK = 36;
519
520 // Handle changes in Private DNS settings.
521 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
522
523 // Handle private DNS validation status updates.
524 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
525
526 /**
527 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
528 * been tested.
529 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
530 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
531 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
532 */
533 private static final int EVENT_NETWORK_TESTED = 41;
534
535 /**
536 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
537 * config was resolved.
538 * obj = PrivateDnsConfig
539 * arg2 = netid
540 */
541 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
542
543 /**
544 * Request ConnectivityService display provisioning notification.
545 * arg1 = Whether to make the notification visible.
546 * arg2 = NetID.
547 * obj = Intent to be launched when notification selected by user, null if !arg1.
548 */
549 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
550
551 /**
552 * Used to specify whether a network should be used even if connectivity is partial.
553 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
554 * false)
555 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
556 * obj = network
557 */
558 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
559
560 /**
561 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
562 * Both of the arguments are bitmasks, and the value of bits come from
563 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
564 * arg1 = A bitmask to describe which probes are completed.
565 * arg2 = A bitmask to describe which probes are successful.
566 */
567 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
568
569 /**
570 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
571 * arg1 = unused
572 * arg2 = netId
573 * obj = captive portal data
574 */
575 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
576
577 /**
578 * Used by setRequireVpnForUids.
579 * arg1 = whether the specified UID ranges are required to use a VPN.
580 * obj = Array of UidRange objects.
581 */
582 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
583
584 /**
585 * Used internally when setting the default networks for OemNetworkPreferences.
586 * obj = Pair<OemNetworkPreferences, listener>
587 */
588 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
589
590 /**
591 * Used to indicate the system default network becomes active.
592 */
593 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
594
595 /**
596 * Used internally when setting a network preference for a user profile.
597 * obj = Pair<ProfileNetworkPreference, Listener>
598 */
599 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
600
601 /**
602 * Event to specify that reasons for why an uid is blocked changed.
603 * arg1 = uid
604 * arg2 = blockedReasons
605 */
606 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
607
608 /**
609 * Event to register a new network offer
610 * obj = NetworkOffer
611 */
612 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
613
614 /**
615 * Event to unregister an existing network offer
616 * obj = INetworkOfferCallback
617 */
618 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
619
620 /**
621 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
622 * should be shown.
623 */
624 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
625
626 /**
627 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
628 * should be hidden.
629 */
630 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
631
632 private static String eventName(int what) {
633 return sMagicDecoderRing.get(what, Integer.toString(what));
634 }
635
636 private static IDnsResolver getDnsResolver(Context context) {
637 final DnsResolverServiceManager dsm = context.getSystemService(
638 DnsResolverServiceManager.class);
639 return IDnsResolver.Stub.asInterface(dsm.getService());
640 }
641
642 /** Handler thread used for all of the handlers below. */
643 @VisibleForTesting
644 protected final HandlerThread mHandlerThread;
645 /** Handler used for internal events. */
646 final private InternalHandler mHandler;
647 /** Handler used for incoming {@link NetworkStateTracker} events. */
648 final private NetworkStateTrackerHandler mTrackerHandler;
649 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
650 @VisibleForTesting
651 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
652
653 private final DnsManager mDnsManager;
654 private final NetworkRanker mNetworkRanker;
655
656 private boolean mSystemReady;
657 private Intent mInitialBroadcast;
658
659 private PowerManager.WakeLock mNetTransitionWakeLock;
660 private final PowerManager.WakeLock mPendingIntentWakeLock;
661
662 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
663 // the world when it changes.
664 @VisibleForTesting
665 protected final ProxyTracker mProxyTracker;
666
667 final private SettingsObserver mSettingsObserver;
668
669 private UserManager mUserManager;
670
671 // the set of network types that can only be enabled by system/sig apps
672 private List<Integer> mProtectedNetworks;
673
674 private Set<String> mWolSupportedInterfaces;
675
676 private final TelephonyManager mTelephonyManager;
677 private final AppOpsManager mAppOpsManager;
678
679 private final LocationPermissionChecker mLocationPermissionChecker;
680
681 private KeepaliveTracker mKeepaliveTracker;
682 private QosCallbackTracker mQosCallbackTracker;
683 private NetworkNotificationManager mNotifier;
684 private LingerMonitor mLingerMonitor;
685
686 // sequence number of NetworkRequests
687 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
688
689 // Sequence number for NetworkProvider IDs.
690 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
691 NetworkProvider.FIRST_PROVIDER_ID);
692
693 // NetworkRequest activity String log entries.
694 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
695 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
696
697 // NetworkInfo blocked and unblocked String log entries
698 private static final int MAX_NETWORK_INFO_LOGS = 40;
699 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
700
701 private static final int MAX_WAKELOCK_LOGS = 20;
702 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
703 private int mTotalWakelockAcquisitions = 0;
704 private int mTotalWakelockReleases = 0;
705 private long mTotalWakelockDurationMs = 0;
706 private long mMaxWakelockDurationMs = 0;
707 private long mLastWakeLockAcquireTimestamp = 0;
708
709 private final IpConnectivityLog mMetricsLog;
710
711 @GuardedBy("mBandwidthRequests")
712 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
713
714 @VisibleForTesting
715 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
716
717 @VisibleForTesting
718 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
719 new HashMap<>();
720
721 /**
722 * Implements support for the legacy "one network per network type" model.
723 *
724 * We used to have a static array of NetworkStateTrackers, one for each
725 * network type, but that doesn't work any more now that we can have,
726 * for example, more that one wifi network. This class stores all the
727 * NetworkAgentInfo objects that support a given type, but the legacy
728 * API will only see the first one.
729 *
730 * It serves two main purposes:
731 *
732 * 1. Provide information about "the network for a given type" (since this
733 * API only supports one).
734 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
735 * the first network for a given type changes, or if the default network
736 * changes.
737 */
738 @VisibleForTesting
739 static class LegacyTypeTracker {
740
741 private static final boolean DBG = true;
742 private static final boolean VDBG = false;
743
744 /**
745 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
746 * Each list holds references to all NetworkAgentInfos that are used to
747 * satisfy requests for that network type.
748 *
749 * This array is built out at startup such that an unsupported network
750 * doesn't get an ArrayList instance, making this a tristate:
751 * unsupported, supported but not active and active.
752 *
753 * The actual lists are populated when we scan the network types that
754 * are supported on this device.
755 *
756 * Threading model:
757 * - addSupportedType() is only called in the constructor
758 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
759 * They are therefore not thread-safe with respect to each other.
760 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
761 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
762 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
763 * - dump is thread-safe with respect to concurrent add and remove calls.
764 */
765 private final ArrayList<NetworkAgentInfo> mTypeLists[];
766 @NonNull
767 private final ConnectivityService mService;
768
769 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
770 // an entry have no timer (equivalent to -1). Lazily loaded.
771 @NonNull
772 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
773
774 LegacyTypeTracker(@NonNull ConnectivityService service) {
775 mService = service;
776 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
777 }
778
779 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
780 final PackageManager pm = ctx.getPackageManager();
781 if (pm.hasSystemFeature(FEATURE_WIFI)) {
782 addSupportedType(TYPE_WIFI);
783 }
784 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
785 addSupportedType(TYPE_WIFI_P2P);
786 }
787 if (tm.isDataCapable()) {
788 // Telephony does not have granular support for these types: they are either all
789 // supported, or none is supported
790 addSupportedType(TYPE_MOBILE);
791 addSupportedType(TYPE_MOBILE_MMS);
792 addSupportedType(TYPE_MOBILE_SUPL);
793 addSupportedType(TYPE_MOBILE_DUN);
794 addSupportedType(TYPE_MOBILE_HIPRI);
795 addSupportedType(TYPE_MOBILE_FOTA);
796 addSupportedType(TYPE_MOBILE_IMS);
797 addSupportedType(TYPE_MOBILE_CBS);
798 addSupportedType(TYPE_MOBILE_IA);
799 addSupportedType(TYPE_MOBILE_EMERGENCY);
800 }
801 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
802 addSupportedType(TYPE_BLUETOOTH);
803 }
804 if (pm.hasSystemFeature(FEATURE_WATCH)) {
805 // TYPE_PROXY is only used on Wear
806 addSupportedType(TYPE_PROXY);
807 }
808 // Ethernet is often not specified in the configs, although many devices can use it via
809 // USB host adapters. Add it as long as the ethernet service is here.
810 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
811 addSupportedType(TYPE_ETHERNET);
812 }
813
814 // Always add TYPE_VPN as a supported type
815 addSupportedType(TYPE_VPN);
816 }
817
818 private void addSupportedType(int type) {
819 if (mTypeLists[type] != null) {
820 throw new IllegalStateException(
821 "legacy list for type " + type + "already initialized");
822 }
823 mTypeLists[type] = new ArrayList<>();
824 }
825
826 public boolean isTypeSupported(int type) {
827 return isNetworkTypeValid(type) && mTypeLists[type] != null;
828 }
829
830 public NetworkAgentInfo getNetworkForType(int type) {
831 synchronized (mTypeLists) {
832 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
833 return mTypeLists[type].get(0);
834 }
835 }
836 return null;
837 }
838
839 public int getRestoreTimerForType(int type) {
840 synchronized (mTypeLists) {
841 if (mRestoreTimers == null) {
842 mRestoreTimers = loadRestoreTimers();
843 }
844 return mRestoreTimers.getOrDefault(type, -1);
845 }
846 }
847
848 private ArrayMap<Integer, Integer> loadRestoreTimers() {
849 final String[] configs = mService.mResources.get().getStringArray(
850 R.array.config_legacy_networktype_restore_timers);
851 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
852 for (final String config : configs) {
853 final String[] splits = TextUtils.split(config, ",");
854 if (splits.length != 2) {
855 logwtf("Invalid restore timer token count: " + config);
856 continue;
857 }
858 try {
859 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
860 } catch (NumberFormatException e) {
861 logwtf("Invalid restore timer number format: " + config, e);
862 }
863 }
864 return ret;
865 }
866
867 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
868 boolean isDefaultNetwork) {
869 if (DBG) {
870 log("Sending " + state
871 + " broadcast for type " + type + " " + nai.toShortString()
872 + " isDefaultNetwork=" + isDefaultNetwork);
873 }
874 }
875
876 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
877 // network type, to preserve previous behaviour.
878 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
879 if (vpnNai != mService.getLegacyLockdownNai()) return;
880
881 if (vpnNai.declaredUnderlyingNetworks == null
882 || vpnNai.declaredUnderlyingNetworks.length != 1) {
883 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
884 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
885 return;
886 }
887 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
888 vpnNai.declaredUnderlyingNetworks[0]);
889 if (underlyingNai == null) return;
890
891 final int type = underlyingNai.networkInfo.getType();
892 final DetailedState state = DetailedState.CONNECTED;
893 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
894 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
895 }
896
897 /** Adds the given network to the specified legacy type list. */
898 public void add(int type, NetworkAgentInfo nai) {
899 if (!isTypeSupported(type)) {
900 return; // Invalid network type.
901 }
902 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
903
904 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
905 if (list.contains(nai)) {
906 return;
907 }
908 synchronized (mTypeLists) {
909 list.add(nai);
910 }
911
912 // Send a broadcast if this is the first network of its type or if it's the default.
913 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
914
915 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
916 // to preserve previous behaviour.
917 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
918 if ((list.size() == 1) || isDefaultNetwork) {
919 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
920 mService.sendLegacyNetworkBroadcast(nai, state, type);
921 }
922
923 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
924 maybeSendLegacyLockdownBroadcast(nai);
925 }
926 }
927
928 /** Removes the given network from the specified legacy type list. */
929 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
930 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
931 if (list == null || list.isEmpty()) {
932 return;
933 }
934 final boolean wasFirstNetwork = list.get(0).equals(nai);
935
936 synchronized (mTypeLists) {
937 if (!list.remove(nai)) {
938 return;
939 }
940 }
941
942 if (wasFirstNetwork || wasDefault) {
943 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
944 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
945 }
946
947 if (!list.isEmpty() && wasFirstNetwork) {
948 if (DBG) log("Other network available for type " + type +
949 ", sending connected broadcast");
950 final NetworkAgentInfo replacement = list.get(0);
951 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
952 mService.isDefaultNetwork(replacement));
953 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
954 }
955 }
956
957 /** Removes the given network from all legacy type lists. */
958 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
959 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
960 for (int type = 0; type < mTypeLists.length; type++) {
961 remove(type, nai, wasDefault);
962 }
963 }
964
965 // send out another legacy broadcast - currently only used for suspend/unsuspend
966 // toggle
967 public void update(NetworkAgentInfo nai) {
968 final boolean isDefault = mService.isDefaultNetwork(nai);
969 final DetailedState state = nai.networkInfo.getDetailedState();
970 for (int type = 0; type < mTypeLists.length; type++) {
971 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
972 final boolean contains = (list != null && list.contains(nai));
973 final boolean isFirst = contains && (nai == list.get(0));
974 if (isFirst || contains && isDefault) {
975 maybeLogBroadcast(nai, state, type, isDefault);
976 mService.sendLegacyNetworkBroadcast(nai, state, type);
977 }
978 }
979 }
980
981 public void dump(IndentingPrintWriter pw) {
982 pw.println("mLegacyTypeTracker:");
983 pw.increaseIndent();
984 pw.print("Supported types:");
985 for (int type = 0; type < mTypeLists.length; type++) {
986 if (mTypeLists[type] != null) pw.print(" " + type);
987 }
988 pw.println();
989 pw.println("Current state:");
990 pw.increaseIndent();
991 synchronized (mTypeLists) {
992 for (int type = 0; type < mTypeLists.length; type++) {
993 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
994 for (NetworkAgentInfo nai : mTypeLists[type]) {
995 pw.println(type + " " + nai.toShortString());
996 }
997 }
998 }
999 pw.decreaseIndent();
1000 pw.decreaseIndent();
1001 pw.println();
1002 }
1003 }
1004 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
1005
1006 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
1007 /**
1008 * Helper class which parses out priority arguments and dumps sections according to their
1009 * priority. If priority arguments are omitted, function calls the legacy dump command.
1010 */
1011 private class LocalPriorityDump {
1012 private static final String PRIORITY_ARG = "--dump-priority";
1013 private static final String PRIORITY_ARG_HIGH = "HIGH";
1014 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1015
1016 LocalPriorityDump() {}
1017
1018 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1019 doDump(fd, pw, new String[] {DIAG_ARG});
1020 doDump(fd, pw, new String[] {SHORT_ARG});
1021 }
1022
1023 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1024 doDump(fd, pw, args);
1025 }
1026
1027 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1028 if (args == null) {
1029 dumpNormal(fd, pw, args);
1030 return;
1031 }
1032
1033 String priority = null;
1034 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1035 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1036 argIndex++;
1037 priority = args[argIndex];
1038 }
1039 }
1040
1041 if (PRIORITY_ARG_HIGH.equals(priority)) {
1042 dumpHigh(fd, pw);
1043 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1044 dumpNormal(fd, pw, args);
1045 } else {
1046 // ConnectivityService publishes binder service using publishBinderService() with
1047 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
1048 // "--dump-priority" arguments to the service. Thus, dump both NORMAL and HIGH to
1049 // align the legacy design.
1050 // TODO: Integrate into signal dump.
1051 dumpNormal(fd, pw, args);
1052 pw.println();
1053 pw.println("DUMP OF SERVICE HIGH connectivity");
1054 pw.println();
1055 dumpHigh(fd, pw);
1056 }
1057 }
1058 }
1059
1060 /**
1061 * Keeps track of the number of requests made under different uids.
1062 */
1063 public static class PerUidCounter {
1064 private final int mMaxCountPerUid;
1065
1066 // Map from UID to number of NetworkRequests that UID has filed.
1067 @VisibleForTesting
1068 @GuardedBy("mUidToNetworkRequestCount")
1069 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
1070
1071 /**
1072 * Constructor
1073 *
1074 * @param maxCountPerUid the maximum count per uid allowed
1075 */
1076 public PerUidCounter(final int maxCountPerUid) {
1077 mMaxCountPerUid = maxCountPerUid;
1078 }
1079
1080 /**
1081 * Increments the request count of the given uid. Throws an exception if the number
1082 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1083 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1084 *
1085 * @throws ServiceSpecificException with
1086 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1087 * the uid exceed the allowed number.
1088 *
1089 * @param uid the uid that the request was made under
1090 */
1091 public void incrementCountOrThrow(final int uid) {
1092 synchronized (mUidToNetworkRequestCount) {
1093 incrementCountOrThrow(uid, 1 /* numToIncrement */);
1094 }
1095 }
1096
1097 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1098 final int newRequestCount =
1099 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1100 if (newRequestCount >= mMaxCountPerUid) {
1101 throw new ServiceSpecificException(
1102 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1103 }
1104 mUidToNetworkRequestCount.put(uid, newRequestCount);
1105 }
1106
1107 /**
1108 * Decrements the request count of the given uid.
1109 *
1110 * @param uid the uid that the request was made under
1111 */
1112 public void decrementCount(final int uid) {
1113 synchronized (mUidToNetworkRequestCount) {
1114 decrementCount(uid, 1 /* numToDecrement */);
1115 }
1116 }
1117
1118 private void decrementCount(final int uid, final int numToDecrement) {
1119 final int newRequestCount =
1120 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1121 if (newRequestCount < 0) {
1122 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1123 } else if (newRequestCount == 0) {
1124 mUidToNetworkRequestCount.delete(uid);
1125 } else {
1126 mUidToNetworkRequestCount.put(uid, newRequestCount);
1127 }
1128 }
1129
1130 /**
1131 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1132 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1133 * are used to create the new nris upon set. Therefore the request count limit can be
1134 * artificially hit. This method is used as a workaround for this particular case so that
1135 * the request counts are accounted for correctly.
1136 * @param uid the uid to adjust counts for
1137 * @param numOfNewRequests the new request count to account for
1138 * @param r the runnable to execute
1139 */
1140 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1141 // This should only be used on the handler thread as per all current and foreseen
1142 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1143 // no ref to the outer ConnectivityService.
1144 synchronized (mUidToNetworkRequestCount) {
1145 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1146 decrementCount(uid, reqCountOverage);
1147 r.run();
1148 incrementCountOrThrow(uid, reqCountOverage);
1149 }
1150 }
1151
1152 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1153 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1154 + numOfNewRequests;
1155 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1156 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1157 }
1158 }
1159
1160 /**
1161 * Dependencies of ConnectivityService, for injection in tests.
1162 */
1163 @VisibleForTesting
1164 public static class Dependencies {
1165 public int getCallingUid() {
1166 return Binder.getCallingUid();
1167 }
1168
1169 /**
1170 * Get system properties to use in ConnectivityService.
1171 */
1172 public MockableSystemProperties getSystemProperties() {
1173 return new MockableSystemProperties();
1174 }
1175
1176 /**
1177 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1178 */
1179 public ConnectivityResources getResources(@NonNull Context ctx) {
1180 return new ConnectivityResources(ctx);
1181 }
1182
1183 /**
1184 * Create a HandlerThread to use in ConnectivityService.
1185 */
1186 public HandlerThread makeHandlerThread() {
1187 return new HandlerThread("ConnectivityServiceThread");
1188 }
1189
1190 /**
1191 * Get a reference to the ModuleNetworkStackClient.
1192 */
1193 public NetworkStackClientBase getNetworkStack() {
1194 return ModuleNetworkStackClient.getInstance(null);
1195 }
1196
1197 /**
1198 * @see ProxyTracker
1199 */
1200 public ProxyTracker makeProxyTracker(@NonNull Context context,
1201 @NonNull Handler connServiceHandler) {
1202 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1203 }
1204
1205 /**
1206 * @see NetIdManager
1207 */
1208 public NetIdManager makeNetIdManager() {
1209 return new NetIdManager();
1210 }
1211
1212 /**
1213 * @see NetworkUtils#queryUserAccess(int, int)
1214 */
1215 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1216 return cs.queryUserAccess(uid, network);
1217 }
1218
1219 /**
1220 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1221 * requires CAP_NET_ADMIN, which the unit tests do not have.
1222 */
1223 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1224 InetSocketAddress remote) {
1225 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1226 }
1227
1228 /**
1229 * @see MultinetworkPolicyTracker
1230 */
1231 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1232 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1233 return new MultinetworkPolicyTracker(c, h, r);
1234 }
1235
1236 /**
1237 * @see BatteryStatsManager
1238 */
1239 public void reportNetworkInterfaceForTransports(Context context, String iface,
1240 int[] transportTypes) {
1241 final BatteryStatsManager batteryStats =
1242 context.getSystemService(BatteryStatsManager.class);
1243 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1244 }
1245
1246 public boolean getCellular464XlatEnabled() {
1247 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1248 }
1249 }
1250
1251 public ConnectivityService(Context context) {
1252 this(context, getDnsResolver(context), new IpConnectivityLog(),
1253 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1254 new Dependencies());
1255 }
1256
1257 @VisibleForTesting
1258 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1259 IpConnectivityLog logger, INetd netd, Dependencies deps) {
1260 if (DBG) log("ConnectivityService starting up");
1261
1262 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
1263 mSystemProperties = mDeps.getSystemProperties();
1264 mNetIdManager = mDeps.makeNetIdManager();
1265 mContext = Objects.requireNonNull(context, "missing Context");
1266 mResources = deps.getResources(mContext);
1267 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
1268 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
1269
1270 mMetricsLog = logger;
1271 mNetworkRanker = new NetworkRanker();
1272 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1273 mDefaultRequest = new NetworkRequestInfo(
1274 Process.myUid(), defaultInternetRequest, null,
1275 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
1276 null /* attributionTags */);
1277 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1278 mDefaultNetworkRequests.add(mDefaultRequest);
1279 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
1280
1281 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
1282 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
1283
1284 // The default WiFi request is a background request so that apps using WiFi are
1285 // migrated to a better network (typically ethernet) when one comes up, instead
1286 // of staying on WiFi forever.
1287 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1288 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1289
1290 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1291 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1292 NetworkRequest.Type.BACKGROUND_REQUEST);
1293
1294 mHandlerThread = mDeps.makeHandlerThread();
1295 mHandlerThread.start();
1296 mHandler = new InternalHandler(mHandlerThread.getLooper());
1297 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
1298 mConnectivityDiagnosticsHandler =
1299 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
1300
1301 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
1302 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
1303
1304 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1305 // TODO: Consider making the timer customizable.
1306 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1307
1308 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
1309 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
1310 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
1311 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
1312
1313 mNetd = netd;
1314 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
1315 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1316 mLocationPermissionChecker = new LocationPermissionChecker(mContext);
1317
1318 // To ensure uid state is synchronized with Network Policy, register for
1319 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1320 // reading existing policy from disk.
1321 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
1322
1323 final PowerManager powerManager = (PowerManager) context.getSystemService(
1324 Context.POWER_SERVICE);
1325 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1326 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1327
1328 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1329 mProtectedNetworks = new ArrayList<>();
1330 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
1331 for (int p : protectedNetworks) {
1332 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
1333 mProtectedNetworks.add(p);
1334 } else {
1335 if (DBG) loge("Ignoring protectedNetwork " + p);
1336 }
1337 }
1338
1339 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1340
1341 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
1342
1343 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
1344 // Listen for user add/removes to inform PermissionMonitor.
1345 // Should run on mHandler to avoid any races.
1346 final IntentFilter userIntentFilter = new IntentFilter();
1347 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1348 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1349 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1350 null /* broadcastPermission */, mHandler);
1351
1352 // Listen to package add/removes for netd
1353 final IntentFilter packageIntentFilter = new IntentFilter();
1354 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1355 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1356 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1357 packageIntentFilter.addDataScheme("package");
1358 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
1359 null /* broadcastPermission */, mHandler);
1360
1361 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
1362
1363 mNetdCallback = new NetdCallback();
1364 try {
1365 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1366 } catch (RemoteException | ServiceSpecificException e) {
1367 loge("Error registering event listener :" + e);
1368 }
1369
1370 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1371 registerSettingsCallbacks();
1372
1373 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
1374 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
1375 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
1376
1377 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1378 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1379 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1380 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1381 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1382 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1383 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
1384
1385 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
1386 mContext, mHandler, () -> updateAvoidBadWifi());
1387 mMultinetworkPolicyTracker.start();
1388
1389 mDnsManager = new DnsManager(mContext, mDnsResolver);
1390 registerPrivateDnsSettingsCallbacks();
1391
1392 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1393 // request that doesn't allow fallback to the default network. It should never be visible
1394 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1395 // arguments like the handler or the DnsResolver.
1396 // TODO : remove this ; it is probably better handled with a sentinel request.
1397 mNoServiceNetwork = new NetworkAgentInfo(null,
1398 new Network(NO_SERVICE_NET_ID),
1399 new NetworkInfo(TYPE_NONE, 0, "", ""),
1400 new LinkProperties(), new NetworkCapabilities(),
1401 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
1402 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1403 mLingerDelayMs, mQosCallbackTracker, mDeps);
1404 }
1405
1406 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1407 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1408 }
1409
1410 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1411 @NonNull final UidRange uids) {
1412 final NetworkCapabilities netCap = new NetworkCapabilities();
1413 netCap.addCapability(NET_CAPABILITY_INTERNET);
1414 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
1415 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1416 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
1417 return netCap;
1418 }
1419
1420 private NetworkRequest createDefaultRequest() {
1421 return createDefaultInternetRequestForTransport(
1422 TYPE_NONE, NetworkRequest.Type.REQUEST);
1423 }
1424
1425 private NetworkRequest createDefaultInternetRequestForTransport(
1426 int transportType, NetworkRequest.Type type) {
1427 final NetworkCapabilities netCap = new NetworkCapabilities();
1428 netCap.addCapability(NET_CAPABILITY_INTERNET);
1429 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
1430 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1431 if (transportType > TYPE_NONE) {
1432 netCap.addTransportType(transportType);
1433 }
1434 return createNetworkRequest(type, netCap);
1435 }
1436
1437 private NetworkRequest createNetworkRequest(
1438 NetworkRequest.Type type, NetworkCapabilities netCap) {
1439 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1440 }
1441
1442 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1443 NetworkRequest.Type type) {
1444 final NetworkCapabilities netCap = new NetworkCapabilities();
1445 netCap.clearAll();
1446 netCap.addCapability(capability);
1447 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1448 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1449 }
1450
1451 // Used only for testing.
1452 // TODO: Delete this and either:
1453 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
1454 // changing ContentResolver to make registerContentObserver non-final).
1455 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1456 // by subclassing SettingsObserver.
1457 @VisibleForTesting
1458 void updateAlwaysOnNetworks() {
1459 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1460 }
1461
1462 // See FakeSettingsProvider comment above.
1463 @VisibleForTesting
1464 void updatePrivateDnsSettings() {
1465 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1466 }
1467
1468 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
1469 final boolean enable = mContext.getResources().getBoolean(id);
1470 handleAlwaysOnNetworkRequest(networkRequest, enable);
1471 }
1472
1473 private void handleAlwaysOnNetworkRequest(
1474 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
1475 final boolean enable = toBool(Settings.Global.getInt(
1476 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1477 handleAlwaysOnNetworkRequest(networkRequest, enable);
1478 }
1479
1480 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
1481 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
1482 if (enable == isEnabled) {
1483 return; // Nothing to do.
1484 }
1485
1486 if (enable) {
1487 handleRegisterNetworkRequest(new NetworkRequestInfo(
1488 Process.myUid(), networkRequest, null, new Binder(),
1489 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
1490 null /* attributionTags */));
1491 } else {
1492 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1493 /* callOnUnavailable */ false);
1494 }
1495 }
1496
1497 private void handleConfigureAlwaysOnNetworks() {
1498 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1499 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1500 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1501 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
1502 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1503 R.bool.config_vehicleInternalNetworkAlwaysRequested);
1504 // TODO (b/183076074): remove legacy fallback after migrating overlays
1505 final boolean legacyAlwaysRequested = mContext.getResources().getBoolean(
1506 mContext.getResources().getIdentifier(
1507 "config_vehicleInternalNetworkAlwaysRequested", "bool", "android"));
1508 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest,
1509 vehicleAlwaysRequested || legacyAlwaysRequested);
1510 }
1511
1512 private void registerSettingsCallbacks() {
1513 // Watch for global HTTP proxy changes.
1514 mSettingsObserver.observe(
1515 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1516 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1517
1518 // Watch for whether or not to keep mobile data always on.
1519 mSettingsObserver.observe(
1520 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
1521 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1522
1523 // Watch for whether or not to keep wifi always on.
1524 mSettingsObserver.observe(
1525 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
1526 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1527 }
1528
1529 private void registerPrivateDnsSettingsCallbacks() {
1530 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1531 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1532 }
1533 }
1534
1535 private synchronized int nextNetworkRequestId() {
1536 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1537 // doing that.
1538 return mNextNetworkRequestId++;
1539 }
1540
1541 @VisibleForTesting
1542 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1543 if (network == null) {
1544 return null;
1545 }
1546 return getNetworkAgentInfoForNetId(network.getNetId());
1547 }
1548
1549 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
1550 synchronized (mNetworkForNetId) {
1551 return mNetworkForNetId.get(netId);
1552 }
1553 }
1554
1555 // TODO: determine what to do when more than one VPN applies to |uid|.
1556 private NetworkAgentInfo getVpnForUid(int uid) {
1557 synchronized (mNetworkForNetId) {
1558 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1559 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1560 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1561 return nai;
1562 }
1563 }
1564 }
1565 return null;
1566 }
1567
1568 private Network[] getVpnUnderlyingNetworks(int uid) {
1569 if (mLockdownEnabled) return null;
1570 final NetworkAgentInfo nai = getVpnForUid(uid);
1571 if (nai != null) return nai.declaredUnderlyingNetworks;
1572 return null;
1573 }
1574
1575 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
1576 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
1577
1578 final Network[] networks = getVpnUnderlyingNetworks(uid);
1579 if (networks != null) {
1580 // getUnderlyingNetworks() returns:
1581 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1582 // empty array => the VPN explicitly said "no default network".
1583 // non-empty array => the VPN specified one or more default networks; we use the
1584 // first one.
1585 if (networks.length > 0) {
1586 nai = getNetworkAgentInfoForNetwork(networks[0]);
1587 } else {
1588 nai = null;
1589 }
1590 }
1591 return nai;
1592 }
1593
1594 /**
1595 * Check if UID should be blocked from using the specified network.
1596 */
1597 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1598 final int uid, final boolean ignoreBlocked) {
1599 // Networks aren't blocked when ignoring blocked status
1600 if (ignoreBlocked) {
1601 return false;
1602 }
1603 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
1604 final long ident = Binder.clearCallingIdentity();
1605 try {
1606 final boolean metered = nc == null ? true : nc.isMetered();
1607 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1608 } finally {
1609 Binder.restoreCallingIdentity(ident);
1610 }
1611 }
1612
1613 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
1614 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1615 return;
1616 }
1617 final boolean blocked;
1618 synchronized (mBlockedAppUids) {
1619 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1620 blocked = true;
1621 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1622 blocked = false;
1623 } else {
1624 return;
1625 }
1626 }
1627 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1628 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1629 mNetworkInfoBlockingLogs.log(action + " " + uid);
1630 }
1631
1632 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
1633 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1634 return;
1635 }
1636 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
1637 final int requestId = nri.getActiveRequest() != null
1638 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
1639 mNetworkInfoBlockingLogs.log(String.format(
1640 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
1641 Integer.toHexString(blocked)));
1642 }
1643
1644 /**
1645 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
1646 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1647 * on {@link #isNetworkWithCapabilitiesBlocked}.
1648 */
1649 @NonNull
1650 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1651 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
1652 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1653 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1654 // but only exists if an app asks about them or requests them. Ensure the requesting app
1655 // gets the type it asks for.
1656 filtered.setType(type);
1657 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1658 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1659 null /* extraInfo */);
1660 }
1661 filterForLegacyLockdown(filtered);
1662 return filtered;
1663 }
1664
1665 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1666 boolean ignoreBlocked) {
1667 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1668 nai.networkCapabilities, uid, ignoreBlocked);
1669 }
1670
1671 /**
1672 * Return NetworkInfo for the active (i.e., connected) network interface.
1673 * It is assumed that at most one network is active at a time. If more
1674 * than one is active, it is indeterminate which will be returned.
1675 * @return the info for the active network, or {@code null} if none is
1676 * active
1677 */
1678 @Override
1679 public NetworkInfo getActiveNetworkInfo() {
1680 enforceAccessPermission();
1681 final int uid = mDeps.getCallingUid();
1682 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1683 if (nai == null) return null;
1684 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1685 maybeLogBlockedNetworkInfo(networkInfo, uid);
1686 return networkInfo;
1687 }
1688
1689 @Override
1690 public Network getActiveNetwork() {
1691 enforceAccessPermission();
1692 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
1693 }
1694
1695 @Override
1696 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1697 PermissionUtils.enforceNetworkStackPermission(mContext);
1698 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
1699 }
1700
1701 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
1702 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1703 if (vpnNai != null) {
1704 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1705 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1706 return vpnNai.network;
1707 }
1708 }
1709
1710 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
1711 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1712 ignoreBlocked)) {
1713 return null;
1714 }
1715 return nai.network;
1716 }
1717
1718 @Override
1719 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1720 PermissionUtils.enforceNetworkStackPermission(mContext);
1721 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1722 if (nai == null) return null;
1723 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
1724 }
1725
1726 /** Returns a NetworkInfo object for a network that doesn't exist. */
1727 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1728 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1729 getNetworkTypeName(networkType), "" /* subtypeName */);
1730 info.setIsAvailable(true);
1731 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1732 // background data is restricted.
1733 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1734 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1735 ? DetailedState.BLOCKED
1736 : DetailedState.DISCONNECTED;
1737 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1738 filterForLegacyLockdown(info);
1739 return info;
1740 }
1741
1742 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
1743 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1744 return null;
1745 }
1746 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1747 if (nai == null) {
1748 return makeFakeNetworkInfo(networkType, uid);
1749 }
1750 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1751 false);
1752 }
1753
1754 @Override
1755 public NetworkInfo getNetworkInfo(int networkType) {
1756 enforceAccessPermission();
1757 final int uid = mDeps.getCallingUid();
1758 if (getVpnUnderlyingNetworks(uid) != null) {
1759 // A VPN is active, so we may need to return one of its underlying networks. This
1760 // information is not available in LegacyTypeTracker, so we have to get it from
1761 // getNetworkAgentInfoForUid.
1762 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1763 if (nai == null) return null;
1764 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1765 if (networkInfo.getType() == networkType) {
1766 return networkInfo;
1767 }
1768 }
1769 return getFilteredNetworkInfoForType(networkType, uid);
1770 }
1771
1772 @Override
1773 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1774 enforceAccessPermission();
1775 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1776 if (nai == null) return null;
1777 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
1778 }
1779
1780 @Override
1781 public NetworkInfo[] getAllNetworkInfo() {
1782 enforceAccessPermission();
1783 final ArrayList<NetworkInfo> result = new ArrayList<>();
1784 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1785 networkType++) {
1786 NetworkInfo info = getNetworkInfo(networkType);
1787 if (info != null) {
1788 result.add(info);
1789 }
1790 }
1791 return result.toArray(new NetworkInfo[result.size()]);
1792 }
1793
1794 @Override
1795 public Network getNetworkForType(int networkType) {
1796 enforceAccessPermission();
1797 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1798 return null;
1799 }
1800 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1801 if (nai == null) {
1802 return null;
1803 }
1804 final int uid = mDeps.getCallingUid();
1805 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1806 return null;
1807 }
1808 return nai.network;
1809 }
1810
1811 @Override
1812 public Network[] getAllNetworks() {
1813 enforceAccessPermission();
1814 synchronized (mNetworkForNetId) {
1815 final Network[] result = new Network[mNetworkForNetId.size()];
1816 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1817 result[i] = mNetworkForNetId.valueAt(i).network;
1818 }
1819 return result;
1820 }
1821 }
1822
1823 @Override
1824 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
1825 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
1826 // The basic principle is: if an app's traffic could possibly go over a
1827 // network, without the app doing anything multinetwork-specific,
1828 // (hence, by "default"), then include that network's capabilities in
1829 // the array.
1830 //
1831 // In the normal case, app traffic only goes over the system's default
1832 // network connection, so that's the only network returned.
1833 //
1834 // With a VPN in force, some app traffic may go into the VPN, and thus
1835 // over whatever underlying networks the VPN specifies, while other app
1836 // traffic may go over the system default network (e.g.: a split-tunnel
1837 // VPN, or an app disallowed by the VPN), so the set of networks
1838 // returned includes the VPN's underlying networks and the system
1839 // default.
1840 enforceAccessPermission();
1841
1842 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
1843
1844 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1845 if (!nri.isBeingSatisfied()) {
1846 continue;
1847 }
1848 final NetworkAgentInfo nai = nri.getSatisfier();
1849 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1850 if (null != nc
1851 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1852 && !result.containsKey(nai.network)) {
1853 result.put(
1854 nai.network,
1855 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1856 nc, false /* includeLocationSensitiveInfo */,
1857 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1858 callingAttributionTag));
1859 }
1860 }
1861
1862 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
1863 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
1864 if (null != networks) {
1865 for (final Network network : networks) {
1866 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1867 if (null != nc) {
1868 result.put(
1869 network,
1870 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1871 nc,
1872 false /* includeLocationSensitiveInfo */,
1873 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1874 callingAttributionTag));
1875 }
1876 }
1877 }
1878
1879 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1880 out = result.values().toArray(out);
1881 return out;
1882 }
1883
1884 @Override
1885 public boolean isNetworkSupported(int networkType) {
1886 enforceAccessPermission();
1887 return mLegacyTypeTracker.isTypeSupported(networkType);
1888 }
1889
1890 /**
1891 * Return LinkProperties for the active (i.e., connected) default
1892 * network interface for the calling uid.
1893 * @return the ip properties for the active network, or {@code null} if
1894 * none is active
1895 */
1896 @Override
1897 public LinkProperties getActiveLinkProperties() {
1898 enforceAccessPermission();
1899 final int uid = mDeps.getCallingUid();
1900 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1901 if (nai == null) return null;
1902 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
1903 Binder.getCallingPid(), uid);
1904 }
1905
1906 @Override
1907 public LinkProperties getLinkPropertiesForType(int networkType) {
1908 enforceAccessPermission();
1909 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1910 final LinkProperties lp = getLinkProperties(nai);
1911 if (lp == null) return null;
1912 return linkPropertiesRestrictedForCallerPermissions(
1913 lp, Binder.getCallingPid(), mDeps.getCallingUid());
1914 }
1915
1916 // TODO - this should be ALL networks
1917 @Override
1918 public LinkProperties getLinkProperties(Network network) {
1919 enforceAccessPermission();
1920 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1921 if (lp == null) return null;
1922 return linkPropertiesRestrictedForCallerPermissions(
1923 lp, Binder.getCallingPid(), mDeps.getCallingUid());
1924 }
1925
1926 @Nullable
1927 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
1928 if (nai == null) {
1929 return null;
1930 }
1931 synchronized (nai) {
1932 return nai.linkProperties;
1933 }
1934 }
1935
1936 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
1937 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1938 }
1939
1940 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
1941 if (nai == null) return null;
1942 synchronized (nai) {
1943 return networkCapabilitiesRestrictedForCallerPermissions(
1944 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
1945 }
1946 }
1947
1948 @Override
1949 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
1950 @Nullable String callingAttributionTag) {
1951 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
1952 enforceAccessPermission();
1953 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1954 getNetworkCapabilitiesInternal(network),
1955 false /* includeLocationSensitiveInfo */,
1956 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
1957 }
1958
1959 @VisibleForTesting
1960 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
1961 NetworkCapabilities nc, int callerPid, int callerUid) {
1962 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
1963 if (!checkSettingsPermission(callerPid, callerUid)) {
1964 newNc.setUids(null);
1965 newNc.setSSID(null);
1966 }
1967 if (newNc.getNetworkSpecifier() != null) {
1968 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1969 }
1970 newNc.setAdministratorUids(new int[0]);
1971 if (!checkAnyPermissionOf(
1972 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
1973 newNc.setSubscriptionIds(Collections.emptySet());
1974 }
1975
1976 return newNc;
1977 }
1978
1979 /**
1980 * Wrapper used to cache the permission check results performed for the corresponding
1981 * app. This avoid performing multiple permission checks for different fields in
1982 * NetworkCapabilities.
1983 * Note: This wrapper does not support any sort of invalidation and thus must not be
1984 * persistent or long-lived. It may only be used for the time necessary to
1985 * compute the redactions required by one particular NetworkCallback or
1986 * synchronous call.
1987 */
1988 private class RedactionPermissionChecker {
1989 private final int mCallingPid;
1990 private final int mCallingUid;
1991 @NonNull private final String mCallingPackageName;
1992 @Nullable private final String mCallingAttributionTag;
1993
1994 private Boolean mHasLocationPermission = null;
1995 private Boolean mHasLocalMacAddressPermission = null;
1996 private Boolean mHasSettingsPermission = null;
1997
1998 RedactionPermissionChecker(int callingPid, int callingUid,
1999 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2000 mCallingPid = callingPid;
2001 mCallingUid = callingUid;
2002 mCallingPackageName = callingPackageName;
2003 mCallingAttributionTag = callingAttributionTag;
2004 }
2005
2006 private boolean hasLocationPermissionInternal() {
2007 final long token = Binder.clearCallingIdentity();
2008 try {
2009 return mLocationPermissionChecker.checkLocationPermission(
2010 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2011 null /* message */);
2012 } finally {
2013 Binder.restoreCallingIdentity(token);
2014 }
2015 }
2016
2017 /**
2018 * Returns whether the app holds location permission or not (might return cached result
2019 * if the permission was already checked before).
2020 */
2021 public boolean hasLocationPermission() {
2022 if (mHasLocationPermission == null) {
2023 // If there is no cached result, perform the check now.
2024 mHasLocationPermission = hasLocationPermissionInternal();
2025 }
2026 return mHasLocationPermission;
2027 }
2028
2029 /**
2030 * Returns whether the app holds local mac address permission or not (might return cached
2031 * result if the permission was already checked before).
2032 */
2033 public boolean hasLocalMacAddressPermission() {
2034 if (mHasLocalMacAddressPermission == null) {
2035 // If there is no cached result, perform the check now.
2036 mHasLocalMacAddressPermission =
2037 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2038 }
2039 return mHasLocalMacAddressPermission;
2040 }
2041
2042 /**
2043 * Returns whether the app holds settings permission or not (might return cached
2044 * result if the permission was already checked before).
2045 */
2046 public boolean hasSettingsPermission() {
2047 if (mHasSettingsPermission == null) {
2048 // If there is no cached result, perform the check now.
2049 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2050 }
2051 return mHasSettingsPermission;
2052 }
2053 }
2054
2055 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2056 @NetworkCapabilities.NetCapability long redaction) {
2057 return (redactions & redaction) != 0;
2058 }
2059
2060 /**
2061 * Use the provided |applicableRedactions| to check the receiving app's
2062 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2063 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2064 * before being sent to the corresponding app.
2065 */
2066 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2067 @NetworkCapabilities.RedactionType long applicableRedactions,
2068 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2069 boolean includeLocationSensitiveInfo) {
2070 long redactions = applicableRedactions;
2071 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2072 if (includeLocationSensitiveInfo
2073 && redactionPermissionChecker.hasLocationPermission()) {
2074 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2075 }
2076 }
2077 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2078 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2079 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2080 }
2081 }
2082 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2083 if (redactionPermissionChecker.hasSettingsPermission()) {
2084 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2085 }
2086 }
2087 return redactions;
2088 }
2089
2090 @VisibleForTesting
2091 @Nullable
2092 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2093 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
2094 int callingPid, int callingUid, @NonNull String callingPkgName,
2095 @Nullable String callingAttributionTag) {
2096 if (nc == null) {
2097 return null;
2098 }
2099 // Avoid doing location permission check if the transport info has no location sensitive
2100 // data.
2101 final RedactionPermissionChecker redactionPermissionChecker =
2102 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2103 callingAttributionTag);
2104 final long redactions = retrieveRequiredRedactions(
2105 nc.getApplicableRedactions(), redactionPermissionChecker,
2106 includeLocationSensitiveInfo);
2107 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
2108 // Reset owner uid if not destined for the owner app.
2109 if (callingUid != nc.getOwnerUid()) {
2110 newNc.setOwnerUid(INVALID_UID);
2111 return newNc;
2112 }
2113 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2114 if (nc.hasTransport(TRANSPORT_VPN)) {
2115 // Owner UIDs already checked above. No need to re-check.
2116 return newNc;
2117 }
2118 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2119 // Else include the owner UID iff the calling has location permission to provide backwards
2120 // compatibility for older apps.
2121 if (!includeLocationSensitiveInfo
2122 && isTargetSdkAtleast(
2123 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
2124 newNc.setOwnerUid(INVALID_UID);
2125 return newNc;
2126 }
2127 // Reset owner uid if the app has no location permission.
2128 if (!redactionPermissionChecker.hasLocationPermission()) {
2129 newNc.setOwnerUid(INVALID_UID);
2130 }
2131 return newNc;
2132 }
2133
2134 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2135 LinkProperties lp, int callerPid, int callerUid) {
2136 if (lp == null) return new LinkProperties();
2137
2138 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2139 final boolean needsSanitization =
2140 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2141 if (!needsSanitization) {
2142 return new LinkProperties(lp);
2143 }
2144
2145 if (checkSettingsPermission(callerPid, callerUid)) {
2146 return new LinkProperties(lp, true /* parcelSensitiveFields */);
2147 }
2148
2149 final LinkProperties newLp = new LinkProperties(lp);
2150 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2151 // object gets parceled.
2152 newLp.setCaptivePortalApiUrl(null);
2153 newLp.setCaptivePortalData(null);
2154 return newLp;
2155 }
2156
2157 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2158 int callerUid, String callerPackageName) {
2159 if (!checkSettingsPermission()) {
2160 // There is no need to track the effective UID of the request here. If the caller lacks
2161 // the settings permission, the effective UID is the same as the calling ID.
2162 nc.setSingleUid(callerUid);
2163 }
2164 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
2165 nc.setAdministratorUids(new int[0]);
2166
2167 // Clear owner UID; this can never come from an app.
2168 nc.setOwnerUid(INVALID_UID);
2169 }
2170
2171 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
2172 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
2173 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2174 }
2175 }
2176
2177 @Override
2178 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2179 enforceAccessPermission();
2180 final int callerUid = Binder.getCallingUid();
2181 final long token = Binder.clearCallingIdentity();
2182 try {
2183 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2184 } finally {
2185 Binder.restoreCallingIdentity(token);
2186 }
2187 }
2188
2189 // TODO: Consider delete this function or turn it into a no-op method.
2190 @Override
2191 public NetworkState[] getAllNetworkState() {
2192 // This contains IMSI details, so make sure the caller is privileged.
2193 PermissionUtils.enforceNetworkStackPermission(mContext);
2194
2195 final ArrayList<NetworkState> result = new ArrayList<>();
2196 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
2197 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2198 // NetworkAgentInfo.
2199 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
2200 if (nai != null && nai.networkInfo.isConnected()) {
2201 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
2202 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2203 snapshot.getNetwork(), snapshot.getSubscriberId()));
2204 }
2205 }
2206 return result.toArray(new NetworkState[result.size()]);
2207 }
2208
2209 @Override
2210 @NonNull
2211 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
2212 // This contains IMSI details, so make sure the caller is privileged.
2213 PermissionUtils.enforceNetworkStackPermission(mContext);
2214
2215 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2216 for (Network network : getAllNetworks()) {
2217 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2218 // TODO: Consider include SUSPENDED networks, which should be considered as
2219 // temporary shortage of connectivity of a connected network.
2220 if (nai != null && nai.networkInfo.isConnected()) {
2221 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2222 // NetworkCapabilities, which may contain UIDs of apps to which the
2223 // network applies. Should the UIDs be cleared so as not to leak or
2224 // interfere ?
2225 result.add(nai.getNetworkStateSnapshot());
2226 }
2227 }
2228 return result;
2229 }
2230
2231 @Override
2232 public boolean isActiveNetworkMetered() {
2233 enforceAccessPermission();
2234
2235 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
2236 if (caps != null) {
2237 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2238 } else {
2239 // Always return the most conservative value
2240 return true;
2241 }
2242 }
2243
2244 /**
2245 * Ensures that the system cannot call a particular method.
2246 */
2247 private boolean disallowedBecauseSystemCaller() {
2248 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
2249 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2250 // for devices launched with Q and above. However, existing devices upgrading to Q and
2251 // above must continued to be supported for few more releases.
2252 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
2253 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
2254 log("This method exists only for app backwards compatibility"
2255 + " and must not be called by system services.");
2256 return true;
2257 }
2258 return false;
2259 }
2260
2261 /**
2262 * Ensure that a network route exists to deliver traffic to the specified
2263 * host via the specified network interface.
2264 * @param networkType the type of the network over which traffic to the
2265 * specified host is to be routed
2266 * @param hostAddress the IP address of the host to which the route is
2267 * desired
2268 * @return {@code true} on success, {@code false} on failure
2269 */
2270 @Override
2271 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2272 String callingPackageName, String callingAttributionTag) {
2273 if (disallowedBecauseSystemCaller()) {
2274 return false;
2275 }
2276 enforceChangePermission(callingPackageName, callingAttributionTag);
2277 if (mProtectedNetworks.contains(networkType)) {
2278 enforceConnectivityRestrictedNetworksPermission();
2279 }
2280
2281 InetAddress addr;
2282 try {
2283 addr = InetAddress.getByAddress(hostAddress);
2284 } catch (UnknownHostException e) {
2285 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2286 return false;
2287 }
2288
2289 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
2290 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
2291 return false;
2292 }
2293
2294 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2295 if (nai == null) {
2296 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2297 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2298 } else {
2299 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2300 }
2301 return false;
2302 }
2303
2304 DetailedState netState;
2305 synchronized (nai) {
2306 netState = nai.networkInfo.getDetailedState();
2307 }
2308
2309 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
2310 if (VDBG) {
2311 log("requestRouteToHostAddress on down network "
2312 + "(" + networkType + ") - dropped"
2313 + " netState=" + netState);
2314 }
2315 return false;
2316 }
2317
2318 final int uid = mDeps.getCallingUid();
2319 final long token = Binder.clearCallingIdentity();
2320 try {
2321 LinkProperties lp;
2322 int netId;
2323 synchronized (nai) {
2324 lp = nai.linkProperties;
2325 netId = nai.network.getNetId();
2326 }
2327 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
2328 if (DBG) {
2329 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2330 }
2331 return ok;
2332 } finally {
2333 Binder.restoreCallingIdentity(token);
2334 }
2335 }
2336
2337 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
2338 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
2339 if (bestRoute == null) {
2340 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
2341 } else {
2342 String iface = bestRoute.getInterface();
2343 if (bestRoute.getGateway().equals(addr)) {
2344 // if there is no better route, add the implied hostroute for our gateway
2345 bestRoute = RouteInfo.makeHostRoute(addr, iface);
2346 } else {
2347 // if we will connect to this through another route, add a direct route
2348 // to it's gateway
2349 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
2350 }
2351 }
2352 if (DBG) log("Adding legacy route " + bestRoute +
2353 " for UID/PID " + uid + "/" + Binder.getCallingPid());
2354
2355 final String dst = bestRoute.getDestinationLinkAddress().toString();
2356 final String nextHop = bestRoute.hasGateway()
2357 ? bestRoute.getGateway().getHostAddress() : "";
2358 try {
2359 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2360 } catch (RemoteException | ServiceSpecificException e) {
2361 if (DBG) loge("Exception trying to add a route: " + e);
2362 return false;
2363 }
2364 return true;
2365 }
2366
2367 class DnsResolverUnsolicitedEventCallback extends
2368 IDnsResolverUnsolicitedEventListener.Stub {
2369 @Override
2370 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
2371 try {
2372 mHandler.sendMessage(mHandler.obtainMessage(
2373 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
2374 new PrivateDnsValidationUpdate(event.netId,
2375 InetAddresses.parseNumericAddress(event.ipAddress),
2376 event.hostname, event.validation)));
2377 } catch (IllegalArgumentException e) {
2378 loge("Error parsing ip address in validation event");
2379 }
2380 }
2381
2382 @Override
2383 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2384 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
2385 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2386 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2387 // event callback for certain nai. e.g. cellular. Register here to pass to
2388 // NetworkMonitor instead.
2389 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2390 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2391 // multiple NetworkMonitor registrants.
2392 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
2393 nai.networkMonitor().notifyDnsResponse(event.healthResult);
2394 }
2395 }
2396
2397 @Override
2398 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2399 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2400 event.prefixAddress, event.prefixLength));
2401 }
2402
2403 @Override
2404 public int getInterfaceVersion() {
2405 return this.VERSION;
2406 }
2407
2408 @Override
2409 public String getInterfaceHash() {
2410 return this.HASH;
2411 }
2412 }
2413
2414 @VisibleForTesting
2415 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2416 new DnsResolverUnsolicitedEventCallback();
2417
2418 private void registerDnsResolverUnsolicitedEventListener() {
2419 try {
2420 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
2421 } catch (Exception e) {
2422 loge("Error registering DnsResolver unsolicited event callback: " + e);
2423 }
2424 }
2425
2426 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
2427 @Override
2428 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
2429 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2430 uid, blockedReasons));
2431 }
2432 };
2433
2434 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
2435 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
2436 setUidBlockedReasons(uid, blockedReasons);
2437 }
2438
2439 private boolean checkAnyPermissionOf(String... permissions) {
2440 for (String permission : permissions) {
2441 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
2442 return true;
2443 }
2444 }
2445 return false;
2446 }
2447
2448 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2449 for (String permission : permissions) {
2450 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2451 return true;
2452 }
2453 }
2454 return false;
2455 }
2456
2457 private void enforceAnyPermissionOf(String... permissions) {
2458 if (!checkAnyPermissionOf(permissions)) {
2459 throw new SecurityException("Requires one of the following permissions: "
2460 + String.join(", ", permissions) + ".");
2461 }
2462 }
2463
2464 private void enforceInternetPermission() {
2465 mContext.enforceCallingOrSelfPermission(
2466 android.Manifest.permission.INTERNET,
2467 "ConnectivityService");
2468 }
2469
2470 private void enforceAccessPermission() {
2471 mContext.enforceCallingOrSelfPermission(
2472 android.Manifest.permission.ACCESS_NETWORK_STATE,
2473 "ConnectivityService");
2474 }
2475
2476 /**
2477 * Performs a strict and comprehensive check of whether a calling package is allowed to
2478 * change the state of network, as the condition differs for pre-M, M+, and
2479 * privileged/preinstalled apps. The caller is expected to have either the
2480 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2481 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2482 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2483 * permission and cannot be revoked. See http://b/23597341
2484 *
2485 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2486 * of this app will be updated to the current time.
2487 */
2488 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
2489 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2490 == PackageManager.PERMISSION_GRANTED) {
2491 return;
2492 }
2493
2494 if (callingPkg == null) {
2495 throw new SecurityException("Calling package name is null.");
2496 }
2497
2498 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2499 final int uid = mDeps.getCallingUid();
2500 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2501 callingPkg, callingAttributionTag, null /* message */);
2502
2503 if (mode == AppOpsManager.MODE_ALLOWED) {
2504 return;
2505 }
2506
2507 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2508 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2509 return;
2510 }
2511
2512 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2513 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2514 + android.Manifest.permission.WRITE_SETTINGS + ".");
2515 }
2516
2517 private void enforceSettingsPermission() {
2518 enforceAnyPermissionOf(
2519 android.Manifest.permission.NETWORK_SETTINGS,
2520 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2521 }
2522
2523 private void enforceNetworkFactoryPermission() {
2524 enforceAnyPermissionOf(
2525 android.Manifest.permission.NETWORK_FACTORY,
2526 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2527 }
2528
2529 private void enforceNetworkFactoryOrSettingsPermission() {
2530 enforceAnyPermissionOf(
2531 android.Manifest.permission.NETWORK_SETTINGS,
2532 android.Manifest.permission.NETWORK_FACTORY,
2533 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2534 }
2535
2536 private void enforceNetworkFactoryOrTestNetworksPermission() {
2537 enforceAnyPermissionOf(
2538 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2539 android.Manifest.permission.NETWORK_FACTORY,
2540 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2541 }
2542
2543 private boolean checkSettingsPermission() {
2544 return checkAnyPermissionOf(
2545 android.Manifest.permission.NETWORK_SETTINGS,
2546 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2547 }
2548
2549 private boolean checkSettingsPermission(int pid, int uid) {
2550 return PERMISSION_GRANTED == mContext.checkPermission(
2551 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2552 || PERMISSION_GRANTED == mContext.checkPermission(
2553 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
2554 }
2555
2556 private void enforceNetworkStackOrSettingsPermission() {
2557 enforceAnyPermissionOf(
2558 android.Manifest.permission.NETWORK_SETTINGS,
2559 android.Manifest.permission.NETWORK_STACK,
2560 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2561 }
2562
2563 private void enforceNetworkStackSettingsOrSetup() {
2564 enforceAnyPermissionOf(
2565 android.Manifest.permission.NETWORK_SETTINGS,
2566 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2567 android.Manifest.permission.NETWORK_STACK,
2568 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2569 }
2570
2571 private void enforceAirplaneModePermission() {
2572 enforceAnyPermissionOf(
2573 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2574 android.Manifest.permission.NETWORK_SETTINGS,
2575 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2576 android.Manifest.permission.NETWORK_STACK,
2577 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2578 }
2579
2580 private void enforceOemNetworkPreferencesPermission() {
2581 mContext.enforceCallingOrSelfPermission(
2582 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2583 "ConnectivityService");
2584 }
2585
2586 private boolean checkNetworkStackPermission() {
2587 return checkAnyPermissionOf(
2588 android.Manifest.permission.NETWORK_STACK,
2589 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2590 }
2591
2592 private boolean checkNetworkStackPermission(int pid, int uid) {
2593 return checkAnyPermissionOf(pid, uid,
2594 android.Manifest.permission.NETWORK_STACK,
2595 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2596 }
2597
2598 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2599 return checkAnyPermissionOf(pid, uid,
2600 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
2601 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2602 android.Manifest.permission.NETWORK_SETTINGS);
2603 }
2604
2605 private void enforceConnectivityRestrictedNetworksPermission() {
2606 try {
2607 mContext.enforceCallingOrSelfPermission(
2608 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2609 "ConnectivityService");
2610 return;
2611 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
2612 // TODO: Remove this fallback check after all apps have declared
2613 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2614 mContext.enforceCallingOrSelfPermission(
2615 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2616 "ConnectivityService");
2617 }
2618
2619 private void enforceKeepalivePermission() {
2620 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
2621 }
2622
2623 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2624 return PERMISSION_GRANTED == mContext.checkPermission(
2625 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2626 }
2627
2628 private void sendConnectedBroadcast(NetworkInfo info) {
2629 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2630 }
2631
2632 private void sendInetConditionBroadcast(NetworkInfo info) {
2633 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2634 }
2635
2636 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2637 Intent intent = new Intent(bcastType);
2638 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2639 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2640 if (info.isFailover()) {
2641 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2642 info.setFailover(false);
2643 }
2644 if (info.getReason() != null) {
2645 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2646 }
2647 if (info.getExtraInfo() != null) {
2648 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2649 info.getExtraInfo());
2650 }
2651 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2652 return intent;
2653 }
2654
2655 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2656 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2657 }
2658
2659 private void sendStickyBroadcast(Intent intent) {
2660 synchronized (this) {
2661 if (!mSystemReady
2662 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
2663 mInitialBroadcast = new Intent(intent);
2664 }
2665 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2666 if (VDBG) {
2667 log("sendStickyBroadcast: action=" + intent.getAction());
2668 }
2669
2670 Bundle options = null;
2671 final long ident = Binder.clearCallingIdentity();
2672 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
2673 final NetworkInfo ni = intent.getParcelableExtra(
2674 ConnectivityManager.EXTRA_NETWORK_INFO);
2675 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2676 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2677 options = opts.toBundle();
2678 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
2679 }
2680 try {
2681 mUserAllContext.sendStickyBroadcast(intent, options);
2682 } finally {
2683 Binder.restoreCallingIdentity(ident);
2684 }
2685 }
2686 }
2687
2688 /**
2689 * Called by SystemServer through ConnectivityManager when the system is ready.
2690 */
2691 @Override
2692 public void systemReady() {
2693 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
2694 throw new SecurityException("Calling Uid is not system uid.");
2695 }
2696 systemReadyInternal();
2697 }
2698
2699 /**
2700 * Called when ConnectivityService can initialize remaining components.
2701 */
2702 @VisibleForTesting
2703 public void systemReadyInternal() {
2704 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2705 // listening network request which is sent by MultipathPolicyTracker won't be added
2706 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2707 // be called after PermissionMonitor#startMonitoring().
2708 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2709 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2710 // to ensure the tracking will be initialized correctly.
2711 mPermissionMonitor.startMonitoring();
2712 mProxyTracker.loadGlobalProxy();
2713 registerDnsResolverUnsolicitedEventListener();
2714
2715 synchronized (this) {
2716 mSystemReady = true;
2717 if (mInitialBroadcast != null) {
2718 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2719 mInitialBroadcast = null;
2720 }
2721 }
2722
2723 // Create network requests for always-on networks.
2724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
2725 }
2726
2727 /**
2728 * Start listening for default data network activity state changes.
2729 */
2730 @Override
2731 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
2732 mNetworkActivityTracker.registerNetworkActivityListener(l);
2733 }
2734
2735 /**
2736 * Stop listening for default data network activity state changes.
2737 */
2738 @Override
2739 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
2740 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
2741 }
2742
2743 /**
2744 * Check whether the default network radio is currently active.
2745 */
2746 @Override
2747 public boolean isDefaultNetworkActive() {
2748 return mNetworkActivityTracker.isDefaultNetworkActive();
2749 }
2750
2751 /**
2752 * Reads the network specific MTU size from resources.
2753 * and set it on it's iface.
2754 */
2755 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2756 final String iface = newLp.getInterfaceName();
2757 final int mtu = newLp.getMtu();
2758 if (oldLp == null && mtu == 0) {
2759 // Silently ignore unset MTU value.
2760 return;
2761 }
2762 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2763 if (VDBG) log("identical MTU - not setting");
2764 return;
2765 }
2766 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
2767 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
2768 return;
2769 }
2770
2771 // Cannot set MTU without interface name
2772 if (TextUtils.isEmpty(iface)) {
2773 loge("Setting MTU size with null iface.");
2774 return;
2775 }
2776
2777 try {
2778 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
2779 mNetd.interfaceSetMtu(iface, mtu);
2780 } catch (RemoteException | ServiceSpecificException e) {
2781 loge("exception in interfaceSetMtu()" + e);
2782 }
2783 }
2784
2785 @VisibleForTesting
2786 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
2787
2788 private void updateTcpBufferSizes(String tcpBufferSizes) {
2789 String[] values = null;
2790 if (tcpBufferSizes != null) {
2791 values = tcpBufferSizes.split(",");
2792 }
2793
2794 if (values == null || values.length != 6) {
2795 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
2796 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2797 values = tcpBufferSizes.split(",");
2798 }
2799
2800 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2801
2802 try {
2803 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
2804
2805 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2806 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2807 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
2808 mCurrentTcpBufferSizes = tcpBufferSizes;
2809 } catch (RemoteException | ServiceSpecificException e) {
2810 loge("Can't set TCP buffer sizes:" + e);
2811 }
2812 }
2813
2814 @Override
2815 public int getRestoreDefaultNetworkDelay(int networkType) {
2816 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
2817 NETWORK_RESTORE_DELAY_PROP_NAME);
2818 if(restoreDefaultNetworkDelayStr != null &&
2819 restoreDefaultNetworkDelayStr.length() != 0) {
2820 try {
2821 return Integer.parseInt(restoreDefaultNetworkDelayStr);
2822 } catch (NumberFormatException e) {
2823 }
2824 }
2825 // if the system property isn't set, use the value for the apn type
2826 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2827
2828 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2829 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
2830 }
2831 return ret;
2832 }
2833
2834 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2835 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2836 final long DIAG_TIME_MS = 5000;
2837 for (NetworkAgentInfo nai : networksSortedById()) {
2838 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
2839 // Start gathering diagnostic information.
2840 netDiags.add(new NetworkDiagnostics(
2841 nai.network,
2842 new LinkProperties(nai.linkProperties), // Must be a copy.
2843 privateDnsCfg,
2844 DIAG_TIME_MS));
2845 }
2846
2847 for (NetworkDiagnostics netDiag : netDiags) {
2848 pw.println();
2849 netDiag.waitForMeasurements();
2850 netDiag.dump(pw);
2851 }
2852 }
2853
2854 @Override
2855 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2856 @Nullable String[] args) {
2857 if (!checkDumpPermission(mContext, TAG, writer)) return;
2858
2859 mPriorityDumper.dump(fd, writer, args);
2860 }
2861
2862 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2863 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2864 != PackageManager.PERMISSION_GRANTED) {
2865 pw.println("Permission Denial: can't dump " + tag + " from from pid="
2866 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
2867 + " due to missing android.permission.DUMP permission");
2868 return false;
2869 } else {
2870 return true;
2871 }
2872 }
2873
2874 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
2875 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2876
2877 if (CollectionUtils.contains(args, DIAG_ARG)) {
2878 dumpNetworkDiagnostics(pw);
2879 return;
2880 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
2881 dumpNetworks(pw);
2882 return;
2883 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
2884 dumpNetworkRequests(pw);
2885 return;
2886 }
2887
2888 pw.print("NetworkProviders for:");
2889 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2890 pw.print(" " + npi.name);
2891 }
2892 pw.println();
2893 pw.println();
2894
2895 final NetworkAgentInfo defaultNai = getDefaultNetwork();
2896 pw.print("Active default network: ");
2897 if (defaultNai == null) {
2898 pw.println("none");
2899 } else {
2900 pw.println(defaultNai.network.getNetId());
2901 }
2902 pw.println();
2903
2904 pw.print("Current per-app default networks: ");
2905 pw.increaseIndent();
2906 dumpPerAppNetworkPreferences(pw);
2907 pw.decreaseIndent();
2908 pw.println();
2909
2910 pw.println("Current Networks:");
2911 pw.increaseIndent();
2912 dumpNetworks(pw);
2913 pw.decreaseIndent();
2914 pw.println();
2915
2916 pw.println("Status for known UIDs:");
2917 pw.increaseIndent();
2918 final int size = mUidBlockedReasons.size();
2919 for (int i = 0; i < size; i++) {
2920 // Don't crash if the array is modified while dumping in bugreports.
2921 try {
2922 final int uid = mUidBlockedReasons.keyAt(i);
2923 final int blockedReasons = mUidBlockedReasons.valueAt(i);
2924 pw.println("UID=" + uid + " blockedReasons="
2925 + Integer.toHexString(blockedReasons));
2926 } catch (ArrayIndexOutOfBoundsException e) {
2927 pw.println(" ArrayIndexOutOfBoundsException");
2928 } catch (ConcurrentModificationException e) {
2929 pw.println(" ConcurrentModificationException");
2930 }
2931 }
2932 pw.println();
2933 pw.decreaseIndent();
2934
2935 pw.println("Network Requests:");
2936 pw.increaseIndent();
2937 dumpNetworkRequests(pw);
2938 pw.decreaseIndent();
2939 pw.println();
2940
2941 mLegacyTypeTracker.dump(pw);
2942
2943 pw.println();
2944 mKeepaliveTracker.dump(pw);
2945
2946 pw.println();
2947 dumpAvoidBadWifiSettings(pw);
2948
2949 pw.println();
2950
2951 if (!CollectionUtils.contains(args, SHORT_ARG)) {
2952 pw.println();
2953 pw.println("mNetworkRequestInfoLogs (most recent first):");
2954 pw.increaseIndent();
2955 mNetworkRequestInfoLogs.reverseDump(pw);
2956 pw.decreaseIndent();
2957
2958 pw.println();
2959 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2960 pw.increaseIndent();
2961 mNetworkInfoBlockingLogs.reverseDump(pw);
2962 pw.decreaseIndent();
2963
2964 pw.println();
2965 pw.println("NetTransition WakeLock activity (most recent first):");
2966 pw.increaseIndent();
2967 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2968 pw.println("total releases: " + mTotalWakelockReleases);
2969 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2970 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2971 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2972 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2973 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2974 }
2975 mWakelockLogs.reverseDump(pw);
2976
2977 pw.println();
2978 pw.println("bandwidth update requests (by uid):");
2979 pw.increaseIndent();
2980 synchronized (mBandwidthRequests) {
2981 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2982 pw.println("[" + mBandwidthRequests.keyAt(i)
2983 + "]: " + mBandwidthRequests.valueAt(i));
2984 }
2985 }
2986 pw.decreaseIndent();
2987 pw.decreaseIndent();
2988
2989 pw.println();
2990 pw.println("mOemNetworkPreferencesLogs (most recent first):");
2991 pw.increaseIndent();
2992 mOemNetworkPreferencesLogs.reverseDump(pw);
2993 pw.decreaseIndent();
2994 }
2995
2996 pw.println();
2997
2998 pw.println();
2999 pw.println("Permission Monitor:");
3000 pw.increaseIndent();
3001 mPermissionMonitor.dump(pw);
3002 pw.decreaseIndent();
3003
3004 pw.println();
3005 pw.println("Legacy network activity:");
3006 pw.increaseIndent();
3007 mNetworkActivityTracker.dump(pw);
3008 pw.decreaseIndent();
3009 }
3010
3011 private void dumpNetworks(IndentingPrintWriter pw) {
3012 for (NetworkAgentInfo nai : networksSortedById()) {
3013 pw.println(nai.toString());
3014 pw.increaseIndent();
3015 pw.println(String.format(
3016 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3017 nai.numForegroundNetworkRequests(),
3018 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3019 nai.numBackgroundNetworkRequests(),
3020 nai.numNetworkRequests()));
3021 pw.increaseIndent();
3022 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3023 pw.println(nai.requestAt(i).toString());
3024 }
3025 pw.decreaseIndent();
3026 pw.println("Inactivity Timers:");
3027 pw.increaseIndent();
3028 nai.dumpInactivityTimers(pw);
3029 pw.decreaseIndent();
3030 pw.decreaseIndent();
3031 }
3032 }
3033
3034 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3035 pw.println("Per-App Network Preference:");
3036 pw.increaseIndent();
3037 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3038 pw.println("none");
3039 } else {
3040 pw.println(mOemNetworkPreferences.toString());
3041 }
3042 pw.decreaseIndent();
3043
3044 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3045 if (mDefaultRequest == defaultRequest) {
3046 continue;
3047 }
3048
3049 final boolean isActive = null != defaultRequest.getSatisfier();
3050 pw.println("Is per-app network active:");
3051 pw.increaseIndent();
3052 pw.println(isActive);
3053 if (isActive) {
3054 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3055 }
3056 pw.println("Tracked UIDs:");
3057 pw.increaseIndent();
3058 if (0 == defaultRequest.mRequests.size()) {
3059 pw.println("none, this should never occur.");
3060 } else {
3061 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
3062 }
3063 pw.decreaseIndent();
3064 pw.decreaseIndent();
3065 }
3066 }
3067
3068 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3069 for (NetworkRequestInfo nri : requestsSortedById()) {
3070 pw.println(nri.toString());
3071 }
3072 }
3073
3074 /**
3075 * Return an array of all current NetworkAgentInfos sorted by network id.
3076 */
3077 private NetworkAgentInfo[] networksSortedById() {
3078 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
3079 networks = mNetworkAgentInfos.toArray(networks);
3080 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
3081 return networks;
3082 }
3083
3084 /**
3085 * Return an array of all current NetworkRequest sorted by request id.
3086 */
3087 @VisibleForTesting
3088 NetworkRequestInfo[] requestsSortedById() {
3089 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
3090 requests = getNrisFromGlobalRequests().toArray(requests);
3091 // Sort the array based off the NRI containing the min requestId in its requests.
3092 Arrays.sort(requests,
3093 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3094 Comparator.comparingInt(req -> req.requestId)).requestId
3095 )
3096 );
3097 return requests;
3098 }
3099
3100 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
3101 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
3102 if (officialNai != null && officialNai.equals(nai)) return true;
3103 if (officialNai != null || VDBG) {
3104 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
3105 " - " + nai);
3106 }
3107 return false;
3108 }
3109
3110 // must be stateless - things change under us.
3111 private class NetworkStateTrackerHandler extends Handler {
3112 public NetworkStateTrackerHandler(Looper looper) {
3113 super(looper);
3114 }
3115
3116 private void maybeHandleNetworkAgentMessage(Message msg) {
3117 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3118 final NetworkAgentInfo nai = arg.first;
3119 if (!mNetworkAgentInfos.contains(nai)) {
3120 if (VDBG) {
3121 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
3122 }
3123 return;
3124 }
3125
3126 switch (msg.what) {
3127 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
3128 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
3129 if (networkCapabilities.hasConnectivityManagedCapability()) {
3130 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
3131 }
3132 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3133 // Make sure the original object is not mutated. NetworkAgent normally
3134 // makes a copy of the capabilities when sending the message through
3135 // the Messenger, but if this ever changes, not making a defensive copy
3136 // here will give attack vectors to clients using this code path.
3137 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3138 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
3139 }
3140 processCapabilitiesFromAgent(nai, networkCapabilities);
3141 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
3142 break;
3143 }
3144 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
3145 LinkProperties newLp = (LinkProperties) arg.second;
3146 processLinkPropertiesFromAgent(nai, newLp);
3147 handleUpdateLinkProperties(nai, newLp);
3148 break;
3149 }
3150 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
3151 NetworkInfo info = (NetworkInfo) arg.second;
3152 updateNetworkInfo(nai, info);
3153 break;
3154 }
3155 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
3156 updateNetworkScore(nai, (NetworkScore) arg.second);
3157 break;
3158 }
3159 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
3160 if (nai.everConnected) {
3161 loge("ERROR: cannot call explicitlySelected on already-connected network");
3162 // Note that if the NAI had been connected, this would affect the
3163 // score, and therefore would require re-mixing the score and performing
3164 // a rematch.
3165 }
3166 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3167 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
3168 // Mark the network as temporarily accepting partial connectivity so that it
3169 // will be validated (and possibly become default) even if it only provides
3170 // partial internet access. Note that if user connects to partial connectivity
3171 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3172 // out of wifi coverage) and if the same wifi is available again, the device
3173 // will auto connect to this wifi even though the wifi has "no internet".
3174 // TODO: Evaluate using a separate setting in IpMemoryStore.
3175 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
3176 break;
3177 }
3178 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
3179 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
3180 break;
3181 }
3182 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
3183 // TODO: prevent loops, e.g., if a network declares itself as underlying.
3184 if (!nai.supportsUnderlyingNetworks()) {
3185 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3186 break;
3187 }
3188
3189 final List<Network> underlying = (List<Network>) arg.second;
3190
3191 if (isLegacyLockdownNai(nai)
3192 && (underlying == null || underlying.size() != 1)) {
3193 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3194 + " must have exactly one underlying network: " + underlying);
3195 }
3196
3197 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3198 nai.declaredUnderlyingNetworks = (underlying != null)
3199 ? underlying.toArray(new Network[0]) : null;
3200
3201 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3202 if (DBG) {
3203 log(nai.toShortString() + " changed underlying networks to "
3204 + Arrays.toString(nai.declaredUnderlyingNetworks));
3205 }
3206 updateCapabilitiesForNetwork(nai);
3207 notifyIfacesChangedForNetworkStats();
3208 }
3209 break;
3210 }
3211 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3212 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3213 nai.teardownDelayMs = msg.arg1;
3214 } else {
3215 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3216 }
3217 break;
3218 }
3219 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3220 nai.setLingerDuration((int) arg.second);
3221 break;
3222 }
3223 }
3224 }
3225
3226 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3227 switch (msg.what) {
3228 default:
3229 return false;
3230 case EVENT_PROBE_STATUS_CHANGED: {
3231 final Integer netId = (Integer) msg.obj;
3232 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3233 if (nai == null) {
3234 break;
3235 }
3236 final boolean probePrivateDnsCompleted =
3237 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3238 final boolean privateDnsBroken =
3239 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3240 if (probePrivateDnsCompleted) {
3241 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3242 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
3243 updateCapabilitiesForNetwork(nai);
3244 }
3245 // Only show the notification when the private DNS is broken and the
3246 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
3247 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
3248 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3249 }
3250 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
3251 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3252 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3253 // private DNS is broken, it means this network is being reevaluated.
3254 // Either probing private DNS is not necessary any more or it hasn't been
3255 // done yet. In either case, the networkCapabilities should be updated to
3256 // reflect the new status.
3257 nai.networkCapabilities.setPrivateDnsBroken(false);
3258 updateCapabilitiesForNetwork(nai);
3259 nai.networkAgentConfig.hasShownBroken = false;
3260 }
3261 break;
3262 }
3263 case EVENT_NETWORK_TESTED: {
3264 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3265
3266 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
3267 if (nai == null) break;
3268
3269 handleNetworkTested(nai, results.mTestResult,
3270 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
3271 break;
3272 }
3273 case EVENT_PROVISIONING_NOTIFICATION: {
3274 final int netId = msg.arg2;
3275 final boolean visible = toBool(msg.arg1);
3276 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3277 // If captive portal status has changed, update capabilities or disconnect.
3278 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3279 nai.lastCaptivePortalDetected = visible;
3280 nai.everCaptivePortalDetected |= visible;
3281 if (nai.lastCaptivePortalDetected &&
3282 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3283 == getCaptivePortalMode()) {
3284 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3285 nai.onPreventAutomaticReconnect();
3286 teardownUnneededNetwork(nai);
3287 break;
3288 }
3289 updateCapabilitiesForNetwork(nai);
3290 }
3291 if (!visible) {
3292 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
3293 // notifications belong to the same network may be cleared unexpectedly.
3294 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3295 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
3296 } else {
3297 if (nai == null) {
3298 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3299 break;
3300 }
3301 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
3302 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
3303 (PendingIntent) msg.obj,
3304 nai.networkAgentConfig.explicitlySelected);
3305 }
3306 }
3307 break;
3308 }
3309 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
3310 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3311 if (nai == null) break;
3312
3313 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
3314 break;
3315 }
3316 case EVENT_CAPPORT_DATA_CHANGED: {
3317 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3318 if (nai == null) break;
3319 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
3320 break;
3321 }
3322 }
3323 return true;
3324 }
3325
3326 private void handleNetworkTested(
3327 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3328 final boolean wasPartial = nai.partialConnectivity;
3329 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3330 final boolean partialConnectivityChanged =
3331 (wasPartial != nai.partialConnectivity);
3332
3333 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3334 final boolean wasValidated = nai.lastValidated;
3335 final boolean wasDefault = isDefaultNetwork(nai);
3336
3337 if (DBG) {
3338 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3339 ? " with redirect to " + redirectUrl
3340 : "";
3341 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
3342 }
3343 if (valid != nai.lastValidated) {
3344 final int oldScore = nai.getCurrentScore();
3345 nai.lastValidated = valid;
3346 nai.everValidated |= valid;
3347 updateCapabilities(oldScore, nai, nai.networkCapabilities);
3348 if (valid) {
3349 handleFreshlyValidatedNetwork(nai);
3350 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3351 // LOST_INTERNET notifications if network becomes valid.
3352 mNotifier.clearNotification(nai.network.getNetId(),
3353 NotificationType.NO_INTERNET);
3354 mNotifier.clearNotification(nai.network.getNetId(),
3355 NotificationType.LOST_INTERNET);
3356 mNotifier.clearNotification(nai.network.getNetId(),
3357 NotificationType.PARTIAL_CONNECTIVITY);
3358 mNotifier.clearNotification(nai.network.getNetId(),
3359 NotificationType.PRIVATE_DNS_BROKEN);
3360 // If network becomes valid, the hasShownBroken should be reset for
3361 // that network so that the notification will be fired when the private
3362 // DNS is broken again.
3363 nai.networkAgentConfig.hasShownBroken = false;
3364 }
3365 } else if (partialConnectivityChanged) {
3366 updateCapabilitiesForNetwork(nai);
3367 }
3368 updateInetCondition(nai);
3369 // Let the NetworkAgent know the state of its network
3370 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
3371 nai.onValidationStatusChanged(
3372 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3373 redirectUrl);
3374
3375 // If NetworkMonitor detects partial connectivity before
3376 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3377 // immediately. Re-notify partial connectivity silently if no internet
3378 // notification already there.
3379 if (!wasPartial && nai.partialConnectivity) {
3380 // Remove delayed message if there is a pending message.
3381 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3382 handlePromptUnvalidated(nai.network);
3383 }
3384
3385 if (wasValidated && !nai.lastValidated) {
3386 handleNetworkUnvalidated(nai);
3387 }
3388 }
3389
3390 private int getCaptivePortalMode() {
3391 return Settings.Global.getInt(mContext.getContentResolver(),
3392 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3393 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
3394 }
3395
3396 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3397 switch (msg.what) {
3398 default:
3399 return false;
3400 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3401 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3402 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3403 handleLingerComplete(nai);
3404 }
3405 break;
3406 }
3407 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3408 handleNetworkAgentRegistered(msg);
3409 break;
3410 }
3411 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3412 handleNetworkAgentDisconnected(msg);
3413 break;
3414 }
3415 }
3416 return true;
3417 }
3418
3419 @Override
3420 public void handleMessage(Message msg) {
3421 if (!maybeHandleNetworkMonitorMessage(msg)
3422 && !maybeHandleNetworkAgentInfoMessage(msg)) {
3423 maybeHandleNetworkAgentMessage(msg);
3424 }
3425 }
3426 }
3427
3428 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
3429 private final int mNetId;
3430 private final AutodestructReference<NetworkAgentInfo> mNai;
3431
3432 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
3433 mNetId = nai.network.getNetId();
3434 mNai = new AutodestructReference<>(nai);
3435 }
3436
3437 @Override
3438 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3439 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
3440 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
3441 }
3442
3443 @Override
3444 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
3445 // Legacy version of notifyNetworkTestedWithExtras.
3446 // Would only be called if the system has a NetworkStack module older than the
3447 // framework, which does not happen in practice.
3448 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
3449 }
3450
3451 @Override
3452 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
3453 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3454 // the same looper so messages will be processed in sequence.
3455 final Message msg = mTrackerHandler.obtainMessage(
3456 EVENT_NETWORK_TESTED,
3457 new NetworkTestedResults(
3458 mNetId, p.result, p.timestampMillis, p.redirectUrl));
3459 mTrackerHandler.sendMessage(msg);
3460
3461 // Invoke ConnectivityReport generation for this Network test event.
3462 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3463 if (nai == null) return;
3464
3465 final PersistableBundle extras = new PersistableBundle();
3466 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3467 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3468 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3469
3470 ConnectivityReportEvent reportEvent =
3471 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3472 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3473 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
3474 mConnectivityDiagnosticsHandler.sendMessage(m);
3475 }
3476
3477 @Override
3478 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3479 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3480 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
3481 0, mNetId, PrivateDnsConfig.fromParcel(config)));
3482 }
3483
3484 @Override
3485 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3486 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3487 EVENT_PROBE_STATUS_CHANGED,
3488 probesCompleted, probesSucceeded, new Integer(mNetId)));
3489 }
3490
3491 @Override
3492 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3493 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3494 EVENT_CAPPORT_DATA_CHANGED,
3495 0, mNetId, data));
3496 }
3497
3498 @Override
3499 public void showProvisioningNotification(String action, String packageName) {
3500 final Intent intent = new Intent(action);
3501 intent.setPackage(packageName);
3502
3503 final PendingIntent pendingIntent;
3504 // Only the system server can register notifications with package "android"
3505 final long token = Binder.clearCallingIdentity();
3506 try {
3507 pendingIntent = PendingIntent.getBroadcast(
3508 mContext,
3509 0 /* requestCode */,
3510 intent,
3511 PendingIntent.FLAG_IMMUTABLE);
3512 } finally {
3513 Binder.restoreCallingIdentity(token);
3514 }
3515 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3516 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
3517 mNetId, pendingIntent));
3518 }
3519
3520 @Override
3521 public void hideProvisioningNotification() {
3522 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3523 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
3524 }
3525
3526 @Override
3527 public void notifyDataStallSuspected(DataStallReportParcelable p) {
3528 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
3529 }
3530
3531 @Override
3532 public int getInterfaceVersion() {
3533 return this.VERSION;
3534 }
3535
3536 @Override
3537 public String getInterfaceHash() {
3538 return this.HASH;
3539 }
3540 }
3541
3542 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
3543 log("Data stall detected with methods: " + p.detectionMethod);
3544
3545 final PersistableBundle extras = new PersistableBundle();
3546 int detectionMethod = 0;
3547 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3548 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3549 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3550 }
3551 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3552 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3553 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3554 p.tcpMetricsCollectionPeriodMillis);
3555 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
3556 }
3557
3558 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
3559 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
3560 new Pair<>(p.timestampMillis, extras));
3561
3562 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3563 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3564 // the cost of going through two handlers.
3565 mConnectivityDiagnosticsHandler.sendMessage(msg);
3566 }
3567
3568 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3569 return (p.detectionMethod & detectionMethod) != 0;
3570 }
3571
3572 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3573 return isPrivateDnsValidationRequired(nai.networkCapabilities);
3574 }
3575
3576 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3577 if (nai == null) return;
3578 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3579 // in order to restart a validation pass from within netd.
3580 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3581 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
3582 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3583 }
3584 }
3585
3586 private void handlePrivateDnsSettingsChanged() {
3587 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3588
3589 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
3590 handlePerNetworkPrivateDnsConfig(nai, cfg);
3591 if (networkRequiresPrivateDnsValidation(nai)) {
3592 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3593 }
3594 }
3595 }
3596
3597 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3598 // Private DNS only ever applies to networks that might provide
3599 // Internet access and therefore also require validation.
3600 if (!networkRequiresPrivateDnsValidation(nai)) return;
3601
3602 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
3603 // schedule DNS resolutions. If a DNS resolution is required the
3604 // result will be sent back to us.
3605 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
3606
3607 // With Private DNS bypass support, we can proceed to update the
3608 // Private DNS config immediately, even if we're in strict mode
3609 // and have not yet resolved the provider name into a set of IPs.
3610 updatePrivateDns(nai, cfg);
3611 }
3612
3613 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3614 mDnsManager.updatePrivateDns(nai.network, newCfg);
3615 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3616 }
3617
3618 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3619 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3620 if (nai == null) {
3621 return;
3622 }
3623 mDnsManager.updatePrivateDnsValidation(update);
3624 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3625 }
3626
3627 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
3628 int prefixLength) {
3629 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3630 if (nai == null) return;
3631
3632 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3633 netId, operation, prefixAddress, prefixLength));
3634
3635 IpPrefix prefix = null;
3636 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
3637 try {
3638 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
3639 prefixLength);
3640 } catch (IllegalArgumentException e) {
3641 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
3642 return;
3643 }
3644 }
3645
3646 nai.clatd.setNat64PrefixFromDns(prefix);
3647 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3648 }
3649
3650 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
3651 @Nullable final CaptivePortalData data) {
3652 nai.capportApiData = data;
3653 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3654 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3655 }
3656
3657 /**
3658 * Updates the inactivity state from the network requests inside the NAI.
3659 * @param nai the agent info to update
3660 * @param now the timestamp of the event causing this update
3661 * @return whether the network was inactive as a result of this update
3662 */
3663 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3664 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3665 // 2. If the network was inactive and there are now requests, unset inactive.
3666 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
3667 // one lingered request, set inactive.
3668 nai.updateInactivityTimer();
3669 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
3670 if (DBG) log("Unsetting inactive " + nai.toShortString());
3671 nai.unsetInactive();
3672 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
3673 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
3674 if (DBG) {
3675 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3676 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
3677 }
3678 nai.setInactive();
3679 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
3680 return true;
3681 }
3682 return false;
3683 }
3684
3685 private void handleNetworkAgentRegistered(Message msg) {
3686 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3687 if (!mNetworkAgentInfos.contains(nai)) {
3688 return;
3689 }
3690
3691 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3692 if (VDBG) log("NetworkAgent registered");
3693 } else {
3694 loge("Error connecting NetworkAgent");
3695 mNetworkAgentInfos.remove(nai);
3696 if (nai != null) {
3697 final boolean wasDefault = isDefaultNetwork(nai);
3698 synchronized (mNetworkForNetId) {
3699 mNetworkForNetId.remove(nai.network.getNetId());
3700 }
3701 mNetIdManager.releaseNetId(nai.network.getNetId());
3702 // Just in case.
3703 mLegacyTypeTracker.remove(nai, wasDefault);
3704 }
3705 }
3706 }
3707
3708 private void handleNetworkAgentDisconnected(Message msg) {
3709 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3710 if (mNetworkAgentInfos.contains(nai)) {
3711 disconnectAndDestroyNetwork(nai);
3712 }
3713 }
3714
3715 // Destroys a network, remove references to it from the internal state managed by
3716 // ConnectivityService, free its interfaces and clean up.
3717 // Must be called on the Handler thread.
3718 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
3719 ensureRunningOnConnectivityServiceThread();
3720 if (DBG) {
3721 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
3722 }
3723 // Clear all notifications of this network.
3724 mNotifier.clearNotification(nai.network.getNetId());
3725 // A network agent has disconnected.
3726 // TODO - if we move the logic to the network agent (have them disconnect
3727 // because they lost all their requests or because their score isn't good)
3728 // then they would disconnect organically, report their new state and then
3729 // disconnect the channel.
3730 if (nai.networkInfo.isConnected()) {
3731 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3732 null, null);
3733 }
3734 final boolean wasDefault = isDefaultNetwork(nai);
3735 if (wasDefault) {
3736 mDefaultInetConditionPublished = 0;
3737 }
3738 notifyIfacesChangedForNetworkStats();
3739 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3740 // by other networks that are already connected. Perhaps that can be done by
3741 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3742 // of rematchAllNetworksAndRequests
3743 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3744 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
3745
3746 mQosCallbackTracker.handleNetworkReleased(nai.network);
3747 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3748 // Disable wakeup packet monitoring for each interface.
3749 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3750 }
3751 nai.networkMonitor().notifyNetworkDisconnected();
3752 mNetworkAgentInfos.remove(nai);
3753 nai.clatd.update();
3754 synchronized (mNetworkForNetId) {
3755 // Remove the NetworkAgent, but don't mark the netId as
3756 // available until we've told netd to delete it below.
3757 mNetworkForNetId.remove(nai.network.getNetId());
3758 }
3759 propagateUnderlyingNetworkCapabilities(nai.network);
3760 // Remove all previously satisfied requests.
3761 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3762 final NetworkRequest request = nai.requestAt(i);
3763 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3764 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
3765 if (currentNetwork != null
3766 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
3767 // uid rules for this network will be removed in destroyNativeNetwork(nai).
3768 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3769 // rematch not to keep disconnected agents instead of setting it here ; this
3770 // will also allow removing updating the offers below.
3771 nri.setSatisfier(null, null);
3772 for (final NetworkOfferInfo noi : mNetworkOffers) {
3773 informOffer(nri, noi.offer, mNetworkRanker);
3774 }
3775
3776 if (mDefaultRequest == nri) {
3777 // TODO : make battery stats aware that since 2013 multiple interfaces may be
3778 // active at the same time. For now keep calling this with the default
3779 // network, because while incorrect this is the closest to the old (also
3780 // incorrect) behavior.
3781 mNetworkActivityTracker.updateDataActivityTracking(
3782 null /* newNetwork */, nai);
3783 ensureNetworkTransitionWakelock(nai.toShortString());
3784 }
3785 }
3786 }
3787 nai.clearInactivityState();
3788 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
3789 // Currently, deleting it breaks tests that check for the default network disconnecting.
3790 // Find out why, fix the rematch code, and delete this.
3791 mLegacyTypeTracker.remove(nai, wasDefault);
3792 rematchAllNetworksAndRequests();
3793 mLingerMonitor.noteDisconnect(nai);
3794
3795 // Immediate teardown.
3796 if (nai.teardownDelayMs == 0) {
3797 destroyNetwork(nai);
3798 return;
3799 }
3800
3801 // Delayed teardown.
3802 try {
3803 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3804 } catch (RemoteException e) {
3805 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3806 }
3807 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3808 }
3809
3810 private void destroyNetwork(NetworkAgentInfo nai) {
3811 if (nai.created) {
3812 // Tell netd to clean up the configuration for this network
3813 // (routing rules, DNS, etc).
3814 // This may be slow as it requires a lot of netd shelling out to ip and
3815 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3816 // after we've rematched networks with requests (which might change the default
3817 // network or service a new request from an app), so network traffic isn't interrupted
3818 // for an unnecessarily long time.
3819 destroyNativeNetwork(nai);
3820 mDnsManager.removeNetwork(nai.network);
3821 }
3822 mNetIdManager.releaseNetId(nai.network.getNetId());
3823 nai.onNetworkDestroyed();
3824 }
3825
3826 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
3827 try {
3828 // This should never fail. Specifying an already in use NetID will cause failure.
3829 final NativeNetworkConfig config;
3830 if (nai.isVPN()) {
3831 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
3832 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
3833 return false;
3834 }
3835 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3836 INetd.PERMISSION_NONE,
3837 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3838 getVpnType(nai));
3839 } else {
3840 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3841 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3842 VpnManager.TYPE_VPN_NONE);
3843 }
3844 mNetd.networkCreate(config);
3845 mDnsResolver.createNetworkCache(nai.network.getNetId());
3846 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3847 nai.networkCapabilities.getTransportTypes());
3848 return true;
3849 } catch (RemoteException | ServiceSpecificException e) {
3850 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
3851 return false;
3852 }
3853 }
3854
3855 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
3856 try {
3857 mNetd.networkDestroy(nai.network.getNetId());
3858 } catch (RemoteException | ServiceSpecificException e) {
3859 loge("Exception destroying network(networkDestroy): " + e);
3860 }
3861 try {
3862 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
3863 } catch (RemoteException | ServiceSpecificException e) {
3864 loge("Exception destroying network: " + e);
3865 }
3866 }
3867
3868 // If this method proves to be too slow then we can maintain a separate
3869 // pendingIntent => NetworkRequestInfo map.
3870 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3871 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3872 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3873 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3874 if (existingPendingIntent != null &&
3875 existingPendingIntent.intentFilterEquals(pendingIntent)) {
3876 return entry.getValue();
3877 }
3878 }
3879 return null;
3880 }
3881
3882 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
3883 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3884 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3885 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3886 final NetworkRequestInfo existingRequest =
3887 findExistingNetworkRequestInfo(nri.mPendingIntent);
3888 if (existingRequest != null) { // remove the existing request.
3889 if (DBG) {
3890 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3891 + nri.mRequests.get(0) + " because their intents matched.");
3892 }
3893 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
3894 /* callOnUnavailable */ false);
3895 }
3896 handleRegisterNetworkRequest(nri);
3897 }
3898
3899 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
3900 handleRegisterNetworkRequests(Collections.singleton(nri));
3901 }
3902
3903 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
3904 ensureRunningOnConnectivityServiceThread();
3905 for (final NetworkRequestInfo nri : nris) {
3906 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3907 for (final NetworkRequest req : nri.mRequests) {
3908 mNetworkRequests.put(req, nri);
3909 // TODO: Consider update signal strength for other types.
3910 if (req.isListen()) {
3911 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3912 if (req.networkCapabilities.hasSignalStrength()
3913 && network.satisfiesImmutableCapabilitiesOf(req)) {
3914 updateSignalStrengthThresholds(network, "REGISTER", req);
3915 }
3916 }
3917 }
3918 }
3919 // If this NRI has a satisfier already, it is replacing an older request that
3920 // has been removed. Track it.
3921 final NetworkRequest activeRequest = nri.getActiveRequest();
3922 if (null != activeRequest) {
3923 // If there is an active request, then for sure there is a satisfier.
3924 nri.getSatisfier().addRequest(activeRequest);
3925 }
3926 }
3927
3928 rematchAllNetworksAndRequests();
3929
3930 // Requests that have not been matched to a network will not have been sent to the
3931 // providers, because the old satisfier and the new satisfier are the same (null in this
3932 // case). Send these requests to the providers.
3933 for (final NetworkRequestInfo nri : nris) {
3934 for (final NetworkOfferInfo noi : mNetworkOffers) {
3935 informOffer(nri, noi.offer, mNetworkRanker);
3936 }
3937 }
3938 }
3939
3940 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
3941 final int callingUid) {
3942 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3943 if (nri != null) {
3944 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
3945 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
3946 handleReleaseNetworkRequest(
3947 nri.mRequests.get(0),
3948 callingUid,
3949 /* callOnUnavailable */ false);
3950 }
3951 }
3952
3953 // Determines whether the network is the best (or could become the best, if it validated), for
3954 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3955 // on the value of reason:
3956 //
3957 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3958 // then it should be torn down.
3959 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3960 // then it should be lingered.
3961 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3962 ensureRunningOnConnectivityServiceThread();
3963
3964 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
3965 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
3966 return false;
3967 }
3968
3969 final int numRequests;
3970 switch (reason) {
3971 case TEARDOWN:
3972 numRequests = nai.numRequestNetworkRequests();
3973 break;
3974 case LINGER:
3975 numRequests = nai.numForegroundNetworkRequests();
3976 break;
3977 default:
3978 Log.wtf(TAG, "Invalid reason. Cannot happen.");
3979 return true;
3980 }
3981
3982 if (numRequests > 0) return false;
3983
3984 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3985 if (reason == UnneededFor.LINGER
3986 && !nri.isMultilayerRequest()
3987 && nri.mRequests.get(0).isBackgroundRequest()) {
3988 // Background requests don't affect lingering.
3989 continue;
3990 }
3991
3992 if (isNetworkPotentialSatisfier(nai, nri)) {
3993 return false;
3994 }
3995 }
3996 return true;
3997 }
3998
3999 private boolean isNetworkPotentialSatisfier(
4000 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4001 // listen requests won't keep up a network satisfying it. If this is not a multilayer
4002 // request, return immediately. For multilayer requests, check to see if any of the
4003 // multilayer requests may have a potential satisfier.
4004 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4005 || nri.mRequests.get(0).isListenForBest())) {
4006 return false;
4007 }
4008 for (final NetworkRequest req : nri.mRequests) {
4009 // This multilayer listen request is satisfied therefore no further requests need to be
4010 // evaluated deeming this network not a potential satisfier.
4011 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
4012 return false;
4013 }
4014 // As non-multilayer listen requests have already returned, the below would only happen
4015 // for a multilayer request therefore continue to the next request if available.
4016 if (req.isListen() || req.isListenForBest()) {
4017 continue;
4018 }
4019 // If this Network is already the highest scoring Network for a request, or if
4020 // there is hope for it to become one if it validated, then it is needed.
4021 if (candidate.satisfies(req)) {
4022 // As soon as a network is found that satisfies a request, return. Specifically for
4023 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4024 // is important so as to not evaluate lower priority requests further in
4025 // nri.mRequests.
4026 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4027 ? nri.getSatisfier() : null;
4028 // Note that this catches two important cases:
4029 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4030 // is currently satisfying the request. This is desirable when
4031 // cellular ends up validating but WiFi does not.
4032 // 2. Unvalidated WiFi will not be reaped when validated cellular
4033 // is currently satisfying the request. This is desirable when
4034 // WiFi ends up validating and out scoring cellular.
4035 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
4036 }
4037 }
4038
4039 return false;
4040 }
4041
4042 private NetworkRequestInfo getNriForAppRequest(
4043 NetworkRequest request, int callingUid, String requestedOperation) {
4044 // Looking up the app passed param request in mRequests isn't possible since it may return
4045 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4046 // do the lookup since that will also find per-app default managed requests.
4047 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4048 // to avoid potential race conditions when validating a package->uid mapping when sending
4049 // the callback on the very low-chance that an application shuts down prior to the callback
4050 // being sent.
4051 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4052 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
4053
4054 if (nri != null) {
4055 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
4056 log(String.format("UID %d attempted to %s for unowned request %s",
4057 callingUid, requestedOperation, nri));
4058 return null;
4059 }
4060 }
4061
4062 return nri;
4063 }
4064
4065 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4066 final String callingMethod) {
4067 if (nri.isMultilayerRequest()) {
4068 throw new IllegalStateException(
4069 callingMethod + " does not support multilayer requests.");
4070 }
4071 }
4072
4073 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4074 ensureRunningOnConnectivityServiceThread();
4075 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4076 // single NetworkRequest and thus does not apply to multilayer requests.
4077 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4078 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
4079 return;
4080 }
4081 if (nri.isBeingSatisfied()) {
4082 return;
4083 }
4084 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4085 log("releasing " + nri.mRequests.get(0) + " (timeout)");
4086 }
4087 handleRemoveNetworkRequest(nri);
4088 callCallbackForRequest(
4089 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4090 }
4091
4092 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4093 final int callingUid,
4094 final boolean callOnUnavailable) {
4095 final NetworkRequestInfo nri =
4096 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4097 if (nri == null) {
4098 return;
4099 }
4100 if (VDBG || (DBG && request.isRequest())) {
4101 log("releasing " + request + " (release request)");
4102 }
4103 handleRemoveNetworkRequest(nri);
4104 if (callOnUnavailable) {
4105 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4106 }
4107 }
4108
4109 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4110 ensureRunningOnConnectivityServiceThread();
4111 nri.unlinkDeathRecipient();
4112 for (final NetworkRequest req : nri.mRequests) {
4113 mNetworkRequests.remove(req);
4114 if (req.isListen()) {
4115 removeListenRequestFromNetworks(req);
4116 }
4117 }
4118 if (mDefaultNetworkRequests.remove(nri)) {
4119 // If this request was one of the defaults, then the UID rules need to be updated
4120 // WARNING : if the app(s) for which this network request is the default are doing
4121 // traffic, this will kill their connected sockets, even if an equivalent request
4122 // is going to be reinstated right away ; unconnected traffic will go on the default
4123 // until the new default is set, which will happen very soon.
4124 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4125 // remove ranges for those requests that won't have a replacement
4126 final NetworkAgentInfo satisfier = nri.getSatisfier();
4127 if (null != satisfier) {
4128 try {
4129 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
4130 toUidRangeStableParcels(nri.getUids()));
4131 } catch (RemoteException e) {
4132 loge("Exception setting network preference default network", e);
4133 }
4134 }
4135 }
4136 nri.decrementRequestCount();
4137 mNetworkRequestInfoLogs.log("RELEASE " + nri);
4138
4139 if (null != nri.getActiveRequest()) {
4140 if (!nri.getActiveRequest().isListen()) {
4141 removeSatisfiedNetworkRequestFromNetwork(nri);
4142 } else {
4143 nri.setSatisfier(null, null);
4144 }
4145 }
4146
4147 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4148 // needed for this offer.
4149 for (final NetworkOfferInfo noi : mNetworkOffers) {
4150 for (final NetworkRequest req : nri.mRequests) {
4151 if (req.isRequest() && noi.offer.neededFor(req)) {
4152 noi.offer.onNetworkUnneeded(req);
4153 }
4154 }
4155 }
4156 }
4157
4158 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4159 for (final NetworkRequestInfo nri : nris) {
4160 if (mDefaultRequest == nri) {
4161 // Make sure we never remove the default request.
4162 continue;
4163 }
4164 handleRemoveNetworkRequest(nri);
4165 }
4166 }
4167
4168 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4169 // listens don't have a singular affected Network. Check all networks to see
4170 // if this listen request applies and remove it.
4171 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4172 nai.removeRequest(req.requestId);
4173 if (req.networkCapabilities.hasSignalStrength()
4174 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4175 updateSignalStrengthThresholds(nai, "RELEASE", req);
4176 }
4177 }
4178 }
4179
4180 /**
4181 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4182 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4183 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4184 */
4185 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4186 boolean wasKept = false;
4187 final NetworkAgentInfo nai = nri.getSatisfier();
4188 if (nai != null) {
4189 final int requestLegacyType = nri.getActiveRequest().legacyType;
4190 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4191 nai.removeRequest(nri.getActiveRequest().requestId);
4192 if (VDBG || DDBG) {
4193 log(" Removing from current network " + nai.toShortString()
4194 + ", leaving " + nai.numNetworkRequests() + " requests.");
4195 }
4196 // If there are still lingered requests on this network, don't tear it down,
4197 // but resume lingering instead.
4198 final long now = SystemClock.elapsedRealtime();
4199 if (updateInactivityState(nai, now)) {
4200 notifyNetworkLosing(nai, now);
4201 }
4202 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4203 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4204 teardownUnneededNetwork(nai);
4205 } else {
4206 wasKept = true;
4207 }
4208 nri.setSatisfier(null, null);
4209 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4210 // Went from foreground to background.
4211 updateCapabilitiesForNetwork(nai);
4212 }
4213
4214 // Maintain the illusion. When this request arrived, we might have pretended
4215 // that a network connected to serve it, even though the network was already
4216 // connected. Now that this request has gone away, we might have to pretend
4217 // that the network disconnected. LegacyTypeTracker will generate that
4218 // phantom disconnect for this type.
4219 if (requestLegacyType != TYPE_NONE) {
4220 boolean doRemove = true;
4221 if (wasKept) {
4222 // check if any of the remaining requests for this network are for the
4223 // same legacy type - if so, don't remove the nai
4224 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4225 NetworkRequest otherRequest = nai.requestAt(i);
4226 if (otherRequest.legacyType == requestLegacyType
4227 && otherRequest.isRequest()) {
4228 if (DBG) log(" still have other legacy request - leaving");
4229 doRemove = false;
4230 }
4231 }
4232 }
4233
4234 if (doRemove) {
4235 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
4236 }
4237 }
4238 }
4239 }
4240
4241 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4242 return checkAnyPermissionOf(
4243 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4244 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4245 }
4246
4247 @Override
4248 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4249 enforceNetworkStackSettingsOrSetup();
4250 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
4251 encodeBool(accept), encodeBool(always), network));
4252 }
4253
4254 @Override
4255 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4256 enforceNetworkStackSettingsOrSetup();
4257 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4258 encodeBool(accept), encodeBool(always), network));
4259 }
4260
4261 @Override
4262 public void setAvoidUnvalidated(Network network) {
4263 enforceNetworkStackSettingsOrSetup();
4264 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4265 }
4266
4267 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4268 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4269 " accept=" + accept + " always=" + always);
4270
4271 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4272 if (nai == null) {
4273 // Nothing to do.
4274 return;
4275 }
4276
4277 if (nai.everValidated) {
4278 // The network validated while the dialog box was up. Take no action.
4279 return;
4280 }
4281
4282 if (!nai.networkAgentConfig.explicitlySelected) {
4283 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
4284 }
4285
4286 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4287 nai.networkAgentConfig.acceptUnvalidated = accept;
4288 // If network becomes partial connectivity and user already accepted to use this
4289 // network, we should respect the user's option and don't need to popup the
4290 // PARTIAL_CONNECTIVITY notification to user again.
4291 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4292 nai.updateScoreForNetworkAgentUpdate();
4293 rematchAllNetworksAndRequests();
4294 }
4295
4296 if (always) {
4297 nai.onSaveAcceptUnvalidated(accept);
4298 }
4299
4300 if (!accept) {
4301 // Tell the NetworkAgent to not automatically reconnect to the network.
4302 nai.onPreventAutomaticReconnect();
4303 // Teardown the network.
4304 teardownUnneededNetwork(nai);
4305 }
4306
4307 }
4308
4309 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4310 boolean always) {
4311 if (DBG) {
4312 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4313 + " always=" + always);
4314 }
4315
4316 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4317 if (nai == null) {
4318 // Nothing to do.
4319 return;
4320 }
4321
4322 if (nai.lastValidated) {
4323 // The network validated while the dialog box was up. Take no action.
4324 return;
4325 }
4326
4327 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4328 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4329 }
4330
4331 // TODO: Use the current design or save the user choice into IpMemoryStore.
4332 if (always) {
4333 nai.onSaveAcceptUnvalidated(accept);
4334 }
4335
4336 if (!accept) {
4337 // Tell the NetworkAgent to not automatically reconnect to the network.
4338 nai.onPreventAutomaticReconnect();
4339 // Tear down the network.
4340 teardownUnneededNetwork(nai);
4341 } else {
4342 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4343 // result in a partial connectivity result which will be processed by
4344 // maybeHandleNetworkMonitorMessage.
4345 //
4346 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4347 // per network. Therefore, NetworkMonitor may still do https probe.
4348 nai.networkMonitor().setAcceptPartialConnectivity();
4349 }
4350 }
4351
4352 private void handleSetAvoidUnvalidated(Network network) {
4353 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4354 if (nai == null || nai.lastValidated) {
4355 // Nothing to do. The network either disconnected or revalidated.
4356 return;
4357 }
4358 if (!nai.avoidUnvalidated) {
4359 nai.avoidUnvalidated = true;
4360 nai.updateScoreForNetworkAgentUpdate();
4361 rematchAllNetworksAndRequests();
4362 }
4363 }
4364
4365 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
4366 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
4367 mHandler.sendMessageDelayed(
4368 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4369 PROMPT_UNVALIDATED_DELAY_MS);
4370 }
4371
4372 @Override
4373 public void startCaptivePortalApp(Network network) {
4374 enforceNetworkStackOrSettingsPermission();
4375 mHandler.post(() -> {
4376 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4377 if (nai == null) return;
4378 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
4379 nai.networkMonitor().launchCaptivePortalApp();
4380 });
4381 }
4382
4383 /**
4384 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4385 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
4386 * @param network Network on which the captive portal was detected.
4387 * @param appExtras Bundle to use as intent extras for the captive portal application.
4388 * Must be treated as opaque to avoid preventing the captive portal app to
4389 * update its arguments.
4390 */
4391 @Override
4392 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
4393 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4394 "ConnectivityService");
4395
4396 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4397 appIntent.putExtras(appExtras);
4398 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4399 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
4400 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4401
4402 final long token = Binder.clearCallingIdentity();
4403 try {
4404 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4405 } finally {
4406 Binder.restoreCallingIdentity(token);
4407 }
4408 }
4409
4410 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4411 private final Network mNetwork;
4412
4413 private CaptivePortalImpl(Network network) {
4414 mNetwork = network;
4415 }
4416
4417 @Override
4418 public void appResponse(final int response) {
4419 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4420 enforceSettingsPermission();
4421 }
4422
4423 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4424 if (nm == null) return;
4425 nm.notifyCaptivePortalAppFinished(response);
4426 }
4427
4428 @Override
4429 public void appRequest(final int request) {
4430 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4431 if (nm == null) return;
4432
4433 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
4434 checkNetworkStackPermission();
4435 nm.forceReevaluation(mDeps.getCallingUid());
4436 }
4437 }
4438
4439 @Nullable
4440 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4441 // getNetworkAgentInfoForNetwork is thread-safe
4442 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4443 if (nai == null) return null;
4444
4445 // nai.networkMonitor() is thread-safe
4446 return nai.networkMonitor();
4447 }
4448 }
4449
4450 public boolean avoidBadWifi() {
4451 return mMultinetworkPolicyTracker.getAvoidBadWifi();
4452 }
4453
4454 /**
4455 * Return whether the device should maintain continuous, working connectivity by switching away
4456 * from WiFi networks having no connectivity.
4457 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4458 */
4459 public boolean shouldAvoidBadWifi() {
4460 if (!checkNetworkStackPermission()) {
4461 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4462 }
4463 return avoidBadWifi();
4464 }
4465
4466 private void updateAvoidBadWifi() {
4467 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4468 nai.updateScoreForNetworkAgentUpdate();
4469 }
4470 rematchAllNetworksAndRequests();
4471 }
4472
4473 // TODO: Evaluate whether this is of interest to other consumers of
4474 // MultinetworkPolicyTracker and worth moving out of here.
4475 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
4476 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
4477 if (!configRestrict) {
4478 pw.println("Bad Wi-Fi avoidance: unrestricted");
4479 return;
4480 }
4481
4482 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4483 pw.increaseIndent();
4484 pw.println("Config restrict: " + configRestrict);
4485
4486 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
4487 String description;
4488 // Can't use a switch statement because strings are legal case labels, but null is not.
4489 if ("0".equals(value)) {
4490 description = "get stuck";
4491 } else if (value == null) {
4492 description = "prompt";
4493 } else if ("1".equals(value)) {
4494 description = "avoid";
4495 } else {
4496 description = value + " (?)";
4497 }
4498 pw.println("User setting: " + description);
4499 pw.println("Network overrides:");
4500 pw.increaseIndent();
4501 for (NetworkAgentInfo nai : networksSortedById()) {
4502 if (nai.avoidUnvalidated) {
4503 pw.println(nai.toShortString());
4504 }
4505 }
4506 pw.decreaseIndent();
4507 pw.decreaseIndent();
4508 }
4509
4510 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4511 // unify the method.
4512 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4513 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4514 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4515 return settingsComponent != null
4516 ? settingsComponent.getPackageName() : "com.android.settings";
4517 }
4518
4519 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
4520 final String action;
4521 final boolean highPriority;
4522 switch (type) {
4523 case NO_INTERNET:
4524 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
4525 // High priority because it is only displayed for explicitly selected networks.
4526 highPriority = true;
4527 break;
4528 case PRIVATE_DNS_BROKEN:
4529 action = Settings.ACTION_WIRELESS_SETTINGS;
4530 // High priority because we should let user know why there is no internet.
4531 highPriority = true;
4532 break;
4533 case LOST_INTERNET:
4534 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
4535 // High priority because it could help the user avoid unexpected data usage.
4536 highPriority = true;
4537 break;
4538 case PARTIAL_CONNECTIVITY:
4539 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
4540 // Don't bother the user with a high-priority notification if the network was not
4541 // explicitly selected by the user.
4542 highPriority = nai.networkAgentConfig.explicitlySelected;
4543 break;
4544 default:
4545 Log.wtf(TAG, "Unknown notification type " + type);
4546 return;
4547 }
4548
4549 Intent intent = new Intent(action);
4550 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
4551 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
4552 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4553 // Some OEMs have their own Settings package. Thus, need to get the current using
4554 // Settings package name instead of just use default name "com.android.settings".
4555 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4556 intent.setClassName(settingsPkgName,
4557 settingsPkgName + ".wifi.WifiNoInternetDialog");
4558 }
4559
4560 PendingIntent pendingIntent = PendingIntent.getActivity(
4561 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
4562 0 /* requestCode */,
4563 intent,
4564 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
4565
4566 mNotifier.showNotification(
4567 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
4568 }
4569
4570 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4571 // Don't prompt if the network is validated, and don't prompt on captive portals
4572 // because we're already prompting the user to sign in.
4573 if (nai.everValidated || nai.everCaptivePortalDetected) {
4574 return false;
4575 }
4576
4577 // If a network has partial connectivity, always prompt unless the user has already accepted
4578 // partial connectivity and selected don't ask again. This ensures that if the device
4579 // automatically connects to a network that has partial Internet access, the user will
4580 // always be able to use it, either because they've already chosen "don't ask again" or
4581 // because we have prompt them.
4582 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
4583 return true;
4584 }
4585
4586 // If a network has no Internet access, only prompt if the network was explicitly selected
4587 // and if the user has not already told us to use the network regardless of whether it
4588 // validated or not.
4589 if (nai.networkAgentConfig.explicitlySelected
4590 && !nai.networkAgentConfig.acceptUnvalidated) {
4591 return true;
4592 }
4593
4594 return false;
4595 }
4596
4597 private void handlePromptUnvalidated(Network network) {
4598 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
4599 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4600
4601 if (nai == null || !shouldPromptUnvalidated(nai)) {
4602 return;
4603 }
4604
4605 // Stop automatically reconnecting to this network in the future. Automatically connecting
4606 // to a network that provides no or limited connectivity is not useful, because the user
4607 // cannot use that network except through the notification shown by this method, and the
4608 // notification is only shown if the network is explicitly selected by the user.
4609 nai.onPreventAutomaticReconnect();
4610
4611 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4612 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4613 // popup the notification immediately when the network is partial connectivity.
4614 if (nai.partialConnectivity) {
4615 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
4616 } else {
4617 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4618 }
4619 }
4620
4621 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4622 NetworkCapabilities nc = nai.networkCapabilities;
4623 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
4624
4625 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4626 return;
4627 }
4628
4629 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
4630 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
4631 }
4632 }
4633
4634 @Override
4635 public int getMultipathPreference(Network network) {
4636 enforceAccessPermission();
4637
4638 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4639 if (nai != null && nai.networkCapabilities
4640 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
4641 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4642 }
4643
4644 final NetworkPolicyManager netPolicyManager =
4645 mContext.getSystemService(NetworkPolicyManager.class);
4646
4647 final long token = Binder.clearCallingIdentity();
4648 final int networkPreference;
4649 try {
4650 networkPreference = netPolicyManager.getMultipathPreference(network);
4651 } finally {
4652 Binder.restoreCallingIdentity(token);
4653 }
4654 if (networkPreference != 0) {
4655 return networkPreference;
4656 }
4657 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4658 }
4659
4660 @Override
4661 public NetworkRequest getDefaultRequest() {
4662 return mDefaultRequest.mRequests.get(0);
4663 }
4664
4665 private class InternalHandler extends Handler {
4666 public InternalHandler(Looper looper) {
4667 super(looper);
4668 }
4669
4670 @Override
4671 public void handleMessage(Message msg) {
4672 switch (msg.what) {
4673 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
4674 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
4675 handleReleaseNetworkTransitionWakelock(msg.what);
4676 break;
4677 }
4678 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
4679 mProxyTracker.loadDeprecatedGlobalHttpProxy();
4680 break;
4681 }
4682 case EVENT_PROXY_HAS_CHANGED: {
4683 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4684 handleApplyDefaultProxy(arg.second);
4685 break;
4686 }
4687 case EVENT_REGISTER_NETWORK_PROVIDER: {
4688 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
4689 break;
4690 }
4691 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4692 handleUnregisterNetworkProvider((Messenger) msg.obj);
4693 break;
4694 }
4695 case EVENT_REGISTER_NETWORK_OFFER: {
4696 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4697 break;
4698 }
4699 case EVENT_UNREGISTER_NETWORK_OFFER: {
4700 final NetworkOfferInfo offer =
4701 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4702 if (null != offer) {
4703 handleUnregisterNetworkOffer(offer);
4704 }
4705 break;
4706 }
4707 case EVENT_REGISTER_NETWORK_AGENT: {
4708 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4709 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4710 handleRegisterNetworkAgent(arg.first, arg.second);
4711 break;
4712 }
4713 case EVENT_REGISTER_NETWORK_REQUEST:
4714 case EVENT_REGISTER_NETWORK_LISTENER: {
4715 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
4716 break;
4717 }
4718 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4719 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
4720 handleRegisterNetworkRequestWithIntent(msg);
4721 break;
4722 }
4723 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4724 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4725 handleTimedOutNetworkRequest(nri);
4726 break;
4727 }
4728 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4729 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4730 break;
4731 }
4732 case EVENT_RELEASE_NETWORK_REQUEST: {
4733 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4734 /* callOnUnavailable */ false);
4735 break;
4736 }
4737 case EVENT_SET_ACCEPT_UNVALIDATED: {
4738 Network network = (Network) msg.obj;
4739 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
4740 break;
4741 }
4742 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4743 Network network = (Network) msg.obj;
4744 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4745 toBool(msg.arg2));
4746 break;
4747 }
4748 case EVENT_SET_AVOID_UNVALIDATED: {
4749 handleSetAvoidUnvalidated((Network) msg.obj);
4750 break;
4751 }
4752 case EVENT_PROMPT_UNVALIDATED: {
4753 handlePromptUnvalidated((Network) msg.obj);
4754 break;
4755 }
4756 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4757 handleConfigureAlwaysOnNetworks();
4758 break;
4759 }
4760 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4761 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
4762 mKeepaliveTracker.handleStartKeepalive(msg);
4763 break;
4764 }
4765 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4766 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
4767 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4768 int slot = msg.arg1;
4769 int reason = msg.arg2;
4770 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4771 break;
4772 }
4773 case EVENT_REVALIDATE_NETWORK: {
4774 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
4775 break;
4776 }
4777 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4778 handlePrivateDnsSettingsChanged();
4779 break;
4780 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4781 handlePrivateDnsValidationUpdate(
4782 (PrivateDnsValidationUpdate) msg.obj);
4783 break;
4784 case EVENT_UID_BLOCKED_REASON_CHANGED:
4785 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
4786 break;
4787 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4788 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4789 break;
4790 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
4791 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4792 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
4793 handleSetOemNetworkPreference(arg.first, arg.second);
4794 break;
4795 }
4796 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4797 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4798 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4799 msg.obj;
4800 handleSetProfileNetworkPreference(arg.first, arg.second);
4801 break;
4802 }
4803 case EVENT_REPORT_NETWORK_ACTIVITY:
4804 mNetworkActivityTracker.handleReportNetworkActivity();
4805 break;
4806 }
4807 }
4808 }
4809
4810 @Override
4811 @Deprecated
4812 public int getLastTetherError(String iface) {
4813 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4814 Context.TETHERING_SERVICE);
4815 return tm.getLastTetherError(iface);
4816 }
4817
4818 @Override
4819 @Deprecated
4820 public String[] getTetherableIfaces() {
4821 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4822 Context.TETHERING_SERVICE);
4823 return tm.getTetherableIfaces();
4824 }
4825
4826 @Override
4827 @Deprecated
4828 public String[] getTetheredIfaces() {
4829 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4830 Context.TETHERING_SERVICE);
4831 return tm.getTetheredIfaces();
4832 }
4833
4834
4835 @Override
4836 @Deprecated
4837 public String[] getTetheringErroredIfaces() {
4838 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4839 Context.TETHERING_SERVICE);
4840
4841 return tm.getTetheringErroredIfaces();
4842 }
4843
4844 @Override
4845 @Deprecated
4846 public String[] getTetherableUsbRegexs() {
4847 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4848 Context.TETHERING_SERVICE);
4849
4850 return tm.getTetherableUsbRegexs();
4851 }
4852
4853 @Override
4854 @Deprecated
4855 public String[] getTetherableWifiRegexs() {
4856 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4857 Context.TETHERING_SERVICE);
4858 return tm.getTetherableWifiRegexs();
4859 }
4860
4861 // Called when we lose the default network and have no replacement yet.
4862 // This will automatically be cleared after X seconds or a new default network
4863 // becomes CONNECTED, whichever happens first. The timer is started by the
4864 // first caller and not restarted by subsequent callers.
4865 private void ensureNetworkTransitionWakelock(String forWhom) {
4866 synchronized (this) {
4867 if (mNetTransitionWakeLock.isHeld()) {
4868 return;
4869 }
4870 mNetTransitionWakeLock.acquire();
4871 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4872 mTotalWakelockAcquisitions++;
4873 }
4874 mWakelockLogs.log("ACQUIRE for " + forWhom);
4875 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4876 final int lockTimeout = mResources.get().getInteger(
4877 R.integer.config_networkTransitionTimeout);
4878 mHandler.sendMessageDelayed(msg, lockTimeout);
4879 }
4880
4881 // Called when we gain a new default network to release the network transition wakelock in a
4882 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4883 // message is cancelled.
4884 private void scheduleReleaseNetworkTransitionWakelock() {
4885 synchronized (this) {
4886 if (!mNetTransitionWakeLock.isHeld()) {
4887 return; // expiry message released the lock first.
4888 }
4889 }
4890 // Cancel self timeout on wakelock hold.
4891 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4892 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4893 mHandler.sendMessageDelayed(msg, 1000);
4894 }
4895
4896 // Called when either message of ensureNetworkTransitionWakelock or
4897 // scheduleReleaseNetworkTransitionWakelock is processed.
4898 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4899 String event = eventName(eventId);
4900 synchronized (this) {
4901 if (!mNetTransitionWakeLock.isHeld()) {
4902 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
4903 Log.w(TAG, "expected Net Transition WakeLock to be held");
4904 return;
4905 }
4906 mNetTransitionWakeLock.release();
4907 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4908 mTotalWakelockDurationMs += lockDuration;
4909 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4910 mTotalWakelockReleases++;
4911 }
4912 mWakelockLogs.log(String.format("RELEASE (%s)", event));
4913 }
4914
4915 // 100 percent is full good, 0 is full bad.
4916 @Override
4917 public void reportInetCondition(int networkType, int percentage) {
4918 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4919 if (nai == null) return;
4920 reportNetworkConnectivity(nai.network, percentage > 50);
4921 }
4922
4923 @Override
4924 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
4925 enforceAccessPermission();
4926 enforceInternetPermission();
4927 final int uid = mDeps.getCallingUid();
4928 final int connectivityInfo = encodeBool(hasConnectivity);
4929
4930 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
4931 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
4932 // does not match the known connectivity of the network - this causes NetworkMonitor to
4933 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
4934 final NetworkAgentInfo nai;
4935 if (network == null) {
4936 nai = getDefaultNetwork();
4937 } else {
4938 nai = getNetworkAgentInfoForNetwork(network);
4939 }
4940 if (nai != null) {
4941 mConnectivityDiagnosticsHandler.sendMessage(
4942 mConnectivityDiagnosticsHandler.obtainMessage(
4943 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
4944 connectivityInfo, 0, nai));
4945 }
4946
4947 mHandler.sendMessage(
4948 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4949 }
4950
4951 private void handleReportNetworkConnectivity(
4952 Network network, int uid, boolean hasConnectivity) {
4953 final NetworkAgentInfo nai;
4954 if (network == null) {
4955 nai = getDefaultNetwork();
4956 } else {
4957 nai = getNetworkAgentInfoForNetwork(network);
4958 }
4959 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4960 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4961 return;
4962 }
4963 // Revalidate if the app report does not match our current validated state.
4964 if (hasConnectivity == nai.lastValidated) {
4965 return;
4966 }
4967 if (DBG) {
4968 int netid = nai.network.getNetId();
4969 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
4970 }
4971 // Validating a network that has not yet connected could result in a call to
4972 // rematchNetworkAndRequests() which is not meant to work on such networks.
4973 if (!nai.everConnected) {
4974 return;
4975 }
4976 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
4977 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
4978 return;
4979 }
4980 nai.networkMonitor().forceReevaluation(uid);
4981 }
4982
4983 // TODO: call into netd.
4984 private boolean queryUserAccess(int uid, Network network) {
4985 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4986 if (nai == null) return false;
4987
4988 // Any UID can use its default network.
4989 if (nai == getDefaultNetworkForUid(uid)) return true;
4990
4991 // Privileged apps can use any network.
4992 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
4993 return true;
4994 }
4995
4996 // An unprivileged UID can use a VPN iff the VPN applies to it.
4997 if (nai.isVPN()) {
4998 return nai.networkCapabilities.appliesToUid(uid);
4999 }
5000
5001 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5002 // sockets, i.e., if it is the owner.
5003 final NetworkAgentInfo vpn = getVpnForUid(uid);
5004 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5005 && uid != vpn.networkCapabilities.getOwnerUid()) {
5006 return false;
5007 }
5008
5009 // The UID's permission must be at least sufficient for the network. Since the restricted
5010 // permission was already checked above, that just leaves background networks.
5011 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5012 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5013 }
5014
5015 // Unrestricted network. Anyone gets to use it.
5016 return true;
5017 }
5018
5019 /**
5020 * Returns information about the proxy a certain network is using. If given a null network, it
5021 * it will return the proxy for the bound network for the caller app or the default proxy if
5022 * none.
5023 *
5024 * @param network the network we want to get the proxy information for.
5025 * @return Proxy information if a network has a proxy configured, or otherwise null.
5026 */
5027 @Override
5028 public ProxyInfo getProxyForNetwork(Network network) {
5029 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
5030 if (globalProxy != null) return globalProxy;
5031 if (network == null) {
5032 // Get the network associated with the calling UID.
5033 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
5034 true);
5035 if (activeNetwork == null) {
5036 return null;
5037 }
5038 return getLinkPropertiesProxyInfo(activeNetwork);
5039 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
5040 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5041 // caller may not have.
5042 return getLinkPropertiesProxyInfo(network);
5043 }
5044 // No proxy info available if the calling UID does not have network access.
5045 return null;
5046 }
5047
5048
5049 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
5050 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5051 if (nai == null) return null;
5052 synchronized (nai) {
5053 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5054 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
5055 }
5056 }
5057
5058 @Override
5059 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
5060 PermissionUtils.enforceNetworkStackPermission(mContext);
5061 mProxyTracker.setGlobalProxy(proxyProperties);
5062 }
5063
5064 @Override
5065 @Nullable
5066 public ProxyInfo getGlobalProxy() {
5067 return mProxyTracker.getGlobalProxy();
5068 }
5069
5070 private void handleApplyDefaultProxy(ProxyInfo proxy) {
5071 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
5072 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
5073 proxy = null;
5074 }
5075 mProxyTracker.setDefaultProxy(proxy);
5076 }
5077
5078 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5079 // when any network changes proxy.
5080 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5081 // multi-network world where an app might be bound to a non-default network.
5082 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
5083 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5084 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5085
5086 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
5087 mProxyTracker.sendProxyBroadcast();
5088 }
5089 }
5090
5091 private static class SettingsObserver extends ContentObserver {
5092 final private HashMap<Uri, Integer> mUriEventMap;
5093 final private Context mContext;
5094 final private Handler mHandler;
5095
5096 SettingsObserver(Context context, Handler handler) {
5097 super(null);
5098 mUriEventMap = new HashMap<>();
5099 mContext = context;
5100 mHandler = handler;
5101 }
5102
5103 void observe(Uri uri, int what) {
5104 mUriEventMap.put(uri, what);
5105 final ContentResolver resolver = mContext.getContentResolver();
5106 resolver.registerContentObserver(uri, false, this);
5107 }
5108
5109 @Override
5110 public void onChange(boolean selfChange) {
5111 Log.wtf(TAG, "Should never be reached.");
5112 }
5113
5114 @Override
5115 public void onChange(boolean selfChange, Uri uri) {
5116 final Integer what = mUriEventMap.get(uri);
5117 if (what != null) {
5118 mHandler.obtainMessage(what).sendToTarget();
5119 } else {
5120 loge("No matching event to send for URI=" + uri);
5121 }
5122 }
5123 }
5124
5125 private static void log(String s) {
5126 Log.d(TAG, s);
5127 }
5128
5129 private static void logw(String s) {
5130 Log.w(TAG, s);
5131 }
5132
5133 private static void logwtf(String s) {
5134 Log.wtf(TAG, s);
5135 }
5136
5137 private static void logwtf(String s, Throwable t) {
5138 Log.wtf(TAG, s, t);
5139 }
5140
5141 private static void loge(String s) {
5142 Log.e(TAG, s);
5143 }
5144
5145 private static void loge(String s, Throwable t) {
5146 Log.e(TAG, s, t);
5147 }
5148
5149 /**
5150 * Return the information of all ongoing VPNs.
5151 *
5152 * <p>This method is used to update NetworkStatsService.
5153 *
5154 * <p>Must be called on the handler thread.
5155 */
5156 private UnderlyingNetworkInfo[] getAllVpnInfo() {
5157 ensureRunningOnConnectivityServiceThread();
5158 if (mLockdownEnabled) {
5159 return new UnderlyingNetworkInfo[0];
5160 }
5161 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
5162 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5163 UnderlyingNetworkInfo info = createVpnInfo(nai);
5164 if (info != null) {
5165 infoList.add(info);
5166 }
5167 }
5168 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
5169 }
5170
5171 /**
5172 * @return VPN information for accounting, or null if we can't retrieve all required
5173 * information, e.g underlying ifaces.
5174 */
5175 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
5176 if (!nai.isVPN()) return null;
5177
5178 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
5179 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5180 // the underlyingNetworks list.
5181 if (underlyingNetworks == null) {
5182 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5183 nai.networkCapabilities.getOwnerUid());
5184 if (defaultNai != null) {
5185 underlyingNetworks = new Network[] { defaultNai.network };
5186 }
5187 }
5188
5189 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
5190
5191 List<String> interfaces = new ArrayList<>();
5192 for (Network network : underlyingNetworks) {
5193 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5194 if (underlyingNai == null) continue;
5195 LinkProperties lp = underlyingNai.linkProperties;
5196 for (String iface : lp.getAllInterfaceNames()) {
5197 if (!TextUtils.isEmpty(iface)) {
5198 interfaces.add(iface);
5199 }
5200 }
5201 }
5202
5203 if (interfaces.isEmpty()) return null;
5204
5205 // Must be non-null or NetworkStatsService will crash.
5206 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5207 // tun or ipsec interface is created.
5208 // TODO: Remove this check.
5209 if (nai.linkProperties.getInterfaceName() == null) return null;
5210
5211 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5212 nai.linkProperties.getInterfaceName(), interfaces);
5213 }
5214
5215 // TODO This needs to be the default network that applies to the NAI.
5216 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5217 Network[] underlyingNetworks) {
5218 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
5219 if (underlyingNetworks == null && defaultNetwork != null) {
5220 // null underlying networks means to track the default.
5221 underlyingNetworks = new Network[] { defaultNetwork };
5222 }
5223 return underlyingNetworks;
5224 }
5225
5226 // Returns true iff |network| is an underlying network of |nai|.
5227 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5228 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5229 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5230 if (!nai.supportsUnderlyingNetworks()) return false;
5231 final Network[] underlying = underlyingNetworksOrDefault(
5232 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
5233 return CollectionUtils.contains(underlying, network);
5234 }
5235
5236 /**
5237 * Recompute the capabilities for any networks that had a specific network as underlying.
5238 *
5239 * When underlying networks change, such networks may have to update capabilities to reflect
5240 * things like the metered bit, their transports, and so on. The capabilities are calculated
5241 * immediately. This method runs on the ConnectivityService thread.
5242 */
5243 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
5244 ensureRunningOnConnectivityServiceThread();
5245 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5246 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
5247 updateCapabilitiesForNetwork(nai);
5248 }
5249 }
5250 }
5251
5252 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5253 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5254 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5255 // a VPN is not up.
5256 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5257 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5258 for (UidRange range : blockedUidRanges) {
5259 if (range.contains(uid)) return true;
5260 }
5261 return false;
5262 }
5263
5264 @Override
5265 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5266 enforceNetworkStackOrSettingsPermission();
5267 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5268 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5269 }
5270
5271 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5272 if (DBG) {
5273 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5274 + Arrays.toString(ranges));
5275 }
5276 // Cannot use a Set since the list of UID ranges might contain duplicates.
5277 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5278 for (int i = 0; i < ranges.length; i++) {
5279 if (requireVpn) {
5280 newVpnBlockedUidRanges.add(ranges[i]);
5281 } else {
5282 newVpnBlockedUidRanges.remove(ranges[i]);
5283 }
5284 }
5285
5286 try {
5287 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5288 } catch (RemoteException | ServiceSpecificException e) {
5289 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5290 + Arrays.toString(ranges) + "): netd command failed: " + e);
5291 }
5292
5293 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5294 final boolean curMetered = nai.networkCapabilities.isMetered();
5295 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5296 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
5297 }
5298
5299 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5300 }
5301
5302 @Override
5303 public void setLegacyLockdownVpnEnabled(boolean enabled) {
5304 enforceNetworkStackOrSettingsPermission();
5305 mHandler.post(() -> mLockdownEnabled = enabled);
5306 }
5307
5308 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5309 return mLockdownEnabled
5310 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5311 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
5312 }
5313
5314 private NetworkAgentInfo getLegacyLockdownNai() {
5315 if (!mLockdownEnabled) {
5316 return null;
5317 }
5318 // The legacy lockdown VPN always only applies to userId 0.
5319 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5320 if (nai == null || !isLegacyLockdownNai(nai)) return null;
5321
5322 // The legacy lockdown VPN must always have exactly one underlying network.
5323 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5324 // a local variable. There is no need to make a copy because its contents cannot change.
5325 final Network[] underlying = nai.declaredUnderlyingNetworks;
5326 if (underlying == null || underlying.length != 1) {
5327 return null;
5328 }
5329
5330 // The legacy lockdown VPN always uses the default network.
5331 // If the VPN's underlying network is no longer the current default network, it means that
5332 // the default network has just switched, and the VPN is about to disconnect.
5333 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5334 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
5335 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5336 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
5337 return null;
5338 }
5339
5340 return nai;
5341 };
5342
5343 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5344 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5345 // just a DetailedState object.
5346 private DetailedState getLegacyLockdownState(DetailedState origState) {
5347 if (origState != DetailedState.CONNECTED) {
5348 return origState;
5349 }
5350 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5351 ? DetailedState.CONNECTING
5352 : DetailedState.CONNECTED;
5353 }
5354
5355 private void filterForLegacyLockdown(NetworkInfo ni) {
5356 if (!mLockdownEnabled || !ni.isConnected()) return;
5357 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5358 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5359 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5360 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5361 // network, this time with a state of CONNECTED.
5362 //
5363 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5364 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5365 // is not too far off the truth, since an always-on VPN, when not connected, is always
5366 // trying to reconnect.
5367 if (getLegacyLockdownNai() == null) {
5368 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5369 }
5370 }
5371
5372 @Override
5373 public void setProvisioningNotificationVisible(boolean visible, int networkType,
5374 String action) {
5375 enforceSettingsPermission();
5376 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5377 return;
5378 }
5379 final long ident = Binder.clearCallingIdentity();
5380 try {
5381 // Concatenate the range of types onto the range of NetIDs.
5382 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
5383 mNotifier.setProvNotificationVisible(visible, id, action);
5384 } finally {
5385 Binder.restoreCallingIdentity(ident);
5386 }
5387 }
5388
5389 @Override
5390 public void setAirplaneMode(boolean enable) {
5391 enforceAirplaneModePermission();
5392 final long ident = Binder.clearCallingIdentity();
5393 try {
5394 final ContentResolver cr = mContext.getContentResolver();
5395 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
5396 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5397 intent.putExtra("state", enable);
5398 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
5399 } finally {
5400 Binder.restoreCallingIdentity(ident);
5401 }
5402 }
5403
5404 private void onUserAdded(@NonNull final UserHandle user) {
5405 mPermissionMonitor.onUserAdded(user);
5406 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5407 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5408 }
5409 }
5410
5411 private void onUserRemoved(@NonNull final UserHandle user) {
5412 mPermissionMonitor.onUserRemoved(user);
5413 // If there was a network preference for this user, remove it.
5414 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5415 null /* listener */);
5416 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5417 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5418 }
5419 }
5420
5421 private void onPackageChanged(@NonNull final String packageName) {
5422 // This is necessary in case a package is added or removed, but also when it's replaced to
5423 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5424 // as one in the preferences, then it should follow the same routing as that other package,
5425 // which means updating the rules is never to be needed in this case (whether it joins or
5426 // leaves a UID with a preference).
5427 if (isMappedInOemNetworkPreference(packageName)) {
5428 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5429 }
5430 }
5431
5432 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5433 @Override
5434 public void onReceive(Context context, Intent intent) {
5435 ensureRunningOnConnectivityServiceThread();
5436 final String action = intent.getAction();
5437 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
5438
5439 // User should be filled for below intents, check the existence.
5440 if (user == null) {
5441 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5442 return;
5443 }
5444
5445 if (Intent.ACTION_USER_ADDED.equals(action)) {
5446 onUserAdded(user);
5447 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
5448 onUserRemoved(user);
5449 } else {
5450 Log.wtf(TAG, "received unexpected intent: " + action);
5451 }
5452 }
5453 };
5454
5455 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5456 @Override
5457 public void onReceive(Context context, Intent intent) {
5458 ensureRunningOnConnectivityServiceThread();
5459 switch (intent.getAction()) {
5460 case Intent.ACTION_PACKAGE_ADDED:
5461 case Intent.ACTION_PACKAGE_REMOVED:
5462 case Intent.ACTION_PACKAGE_REPLACED:
5463 onPackageChanged(intent.getData().getSchemeSpecificPart());
5464 break;
5465 default:
5466 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5467 }
5468 }
5469 };
5470
5471 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
5472 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
5473
5474 private static class NetworkProviderInfo {
5475 public final String name;
5476 public final Messenger messenger;
5477 private final IBinder.DeathRecipient mDeathRecipient;
5478 public final int providerId;
5479
5480 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5481 @NonNull IBinder.DeathRecipient deathRecipient) {
5482 this.name = name;
5483 this.messenger = messenger;
5484 this.providerId = providerId;
5485 mDeathRecipient = deathRecipient;
5486
5487 if (mDeathRecipient == null) {
5488 throw new AssertionError("Must pass a deathRecipient");
5489 }
5490 }
5491
5492 void connect(Context context, Handler handler) {
5493 try {
5494 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5495 } catch (RemoteException e) {
5496 mDeathRecipient.binderDied();
5497 }
5498 }
5499 }
5500
5501 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5502 for (int i = 0; i < requests.size(); i++) {
5503 ensureNetworkRequestHasType(requests.get(i));
5504 }
5505 }
5506
5507 private void ensureNetworkRequestHasType(NetworkRequest request) {
5508 if (request.type == NetworkRequest.Type.NONE) {
5509 throw new IllegalArgumentException(
5510 "All NetworkRequests in ConnectivityService must have a type");
5511 }
5512 }
5513
5514 /**
5515 * Tracks info about the requester.
5516 * Also used to notice when the calling process dies so as to self-expire
5517 */
5518 @VisibleForTesting
5519 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
5520 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5521 // single NetworkRequest in mRequests.
5522 final List<NetworkRequest> mRequests;
5523
5524 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5525 void setSatisfier(
5526 @Nullable final NetworkAgentInfo satisfier,
5527 @Nullable final NetworkRequest activeRequest) {
5528 mSatisfier = satisfier;
5529 mActiveRequest = activeRequest;
5530 }
5531
5532 // The network currently satisfying this NRI. Only one request in an NRI can have a
5533 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
5534 @Nullable
5535 private NetworkAgentInfo mSatisfier;
5536 NetworkAgentInfo getSatisfier() {
5537 return mSatisfier;
5538 }
5539
5540 // The request in mRequests assigned to a network agent. This is null if none of the
5541 // requests in mRequests can be satisfied. This member has the constraint of only being
5542 // accessible on the handler thread.
5543 @Nullable
5544 private NetworkRequest mActiveRequest;
5545 NetworkRequest getActiveRequest() {
5546 return mActiveRequest;
5547 }
5548
5549 final PendingIntent mPendingIntent;
5550 boolean mPendingIntentSent;
5551 @Nullable
5552 final Messenger mMessenger;
5553
5554 // Information about the caller that caused this object to be created.
5555 @Nullable
5556 private final IBinder mBinder;
5557 final int mPid;
5558 final int mUid;
5559 final @NetworkCallback.Flag int mCallbackFlags;
5560 @Nullable
5561 final String mCallingAttributionTag;
5562
5563 // Counter keeping track of this NRI.
5564 final PerUidCounter mPerUidCounter;
5565
5566 // Effective UID of this request. This is different from mUid when a privileged process
5567 // files a request on behalf of another UID. This UID is used to determine blocked status,
5568 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5569 // maximum limit of registered callbacks per UID.
5570 final int mAsUid;
5571
5572 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5573 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5574 // maintained for keying off of. This is only a concern when the original nri
5575 // mNetworkRequests changes which happens currently for apps that register callbacks to
5576 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5577 // that match the per-app default nri that currently tracks the calling app's uid so that
5578 // callbacks are fired at the appropriate time. When the callbacks fire,
5579 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5580 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5581 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5582 @NonNull
5583 private final NetworkRequest mNetworkRequestForCallback;
5584 NetworkRequest getNetworkRequestForCallback() {
5585 return mNetworkRequestForCallback;
5586 }
5587
5588 /**
5589 * Get the list of UIDs this nri applies to.
5590 */
5591 @NonNull
5592 private Set<UidRange> getUids() {
5593 // networkCapabilities.getUids() returns a defensive copy.
5594 // multilayer requests will all have the same uids so return the first one.
5595 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5596 return (null == uids) ? new ArraySet<>() : uids;
5597 }
5598
5599 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5600 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
5601 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag);
5602 }
5603
5604 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5605 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
5606 @Nullable String callingAttributionTag) {
5607 ensureAllNetworkRequestsHaveType(r);
5608 mRequests = initializeRequests(r);
5609 mNetworkRequestForCallback = requestForCallback;
5610 mPendingIntent = pi;
5611 mMessenger = null;
5612 mBinder = null;
5613 mPid = getCallingPid();
5614 mUid = mDeps.getCallingUid();
5615 mAsUid = asUid;
5616 mPerUidCounter = getRequestCounter(this);
5617 mPerUidCounter.incrementCountOrThrow(mUid);
5618 /**
5619 * Location sensitive data not included in pending intent. Only included in
5620 * {@link NetworkCallback}.
5621 */
5622 mCallbackFlags = NetworkCallback.FLAG_NONE;
5623 mCallingAttributionTag = callingAttributionTag;
5624 }
5625
5626 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
5627 @Nullable final IBinder binder,
5628 @NetworkCallback.Flag int callbackFlags,
5629 @Nullable String callingAttributionTag) {
5630 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5631 callingAttributionTag);
5632 }
5633
5634 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5635 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
5636 @Nullable final IBinder binder,
5637 @NetworkCallback.Flag int callbackFlags,
5638 @Nullable String callingAttributionTag) {
5639 super();
5640 ensureAllNetworkRequestsHaveType(r);
5641 mRequests = initializeRequests(r);
5642 mNetworkRequestForCallback = requestForCallback;
5643 mMessenger = m;
5644 mBinder = binder;
5645 mPid = getCallingPid();
5646 mUid = mDeps.getCallingUid();
5647 mAsUid = asUid;
5648 mPendingIntent = null;
5649 mPerUidCounter = getRequestCounter(this);
5650 mPerUidCounter.incrementCountOrThrow(mUid);
5651 mCallbackFlags = callbackFlags;
5652 mCallingAttributionTag = callingAttributionTag;
5653 linkDeathRecipient();
5654 }
5655
5656 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5657 @NonNull final List<NetworkRequest> r) {
5658 super();
5659 ensureAllNetworkRequestsHaveType(r);
5660 mRequests = initializeRequests(r);
5661 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
5662 final NetworkAgentInfo satisfier = nri.getSatisfier();
5663 if (null != satisfier) {
5664 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5665 // The active request is necessary to figure out what callbacks to send, in
5666 // particular then a network updates its capabilities.
5667 // As this code creates a new NRI with a new set of requests, figure out which of
5668 // the list of requests should be the active request. It is always the first
5669 // request of the list that can be satisfied by the satisfier since the order of
5670 // requests is a priority order.
5671 // Note even in the presence of a satisfier there may not be an active request,
5672 // when the satisfier is the no-service network.
5673 NetworkRequest activeRequest = null;
5674 for (final NetworkRequest candidate : r) {
5675 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5676 activeRequest = candidate;
5677 break;
5678 }
5679 }
5680 setSatisfier(satisfier, activeRequest);
5681 }
5682 mMessenger = nri.mMessenger;
5683 mBinder = nri.mBinder;
5684 mPid = nri.mPid;
5685 mUid = nri.mUid;
5686 mAsUid = nri.mAsUid;
5687 mPendingIntent = nri.mPendingIntent;
5688 mPerUidCounter = getRequestCounter(this);
5689 mPerUidCounter.incrementCountOrThrow(mUid);
5690 mCallbackFlags = nri.mCallbackFlags;
5691 mCallingAttributionTag = nri.mCallingAttributionTag;
5692 linkDeathRecipient();
5693 }
5694
5695 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
5696 this(asUid, Collections.singletonList(r));
5697 }
5698
5699 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r) {
5700 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */);
5701 }
5702
5703 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5704 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5705 // false.
5706 boolean isBeingSatisfied() {
5707 return (null != mSatisfier && null != mActiveRequest);
5708 }
5709
5710 boolean isMultilayerRequest() {
5711 return mRequests.size() > 1;
5712 }
5713
5714 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5715 // Creating a defensive copy to prevent the sender from modifying the list being
5716 // reflected in the return value of this method.
5717 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
5718 return Collections.unmodifiableList(tempRequests);
5719 }
5720
5721 void decrementRequestCount() {
5722 mPerUidCounter.decrementCount(mUid);
5723 }
5724
5725 void linkDeathRecipient() {
5726 if (null != mBinder) {
5727 try {
5728 mBinder.linkToDeath(this, 0);
5729 } catch (RemoteException e) {
5730 binderDied();
5731 }
5732 }
5733 }
5734
5735 void unlinkDeathRecipient() {
5736 if (null != mBinder) {
5737 mBinder.unlinkToDeath(this, 0);
5738 }
5739 }
5740
5741 @Override
5742 public void binderDied() {
5743 log("ConnectivityService NetworkRequestInfo binderDied(" +
5744 mRequests + ", " + mBinder + ")");
5745 releaseNetworkRequests(mRequests);
5746 }
5747
5748 @Override
5749 public String toString() {
5750 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5751 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
5752 + (mActiveRequest == null ? null : mActiveRequest.requestId)
5753 + " callbackRequest: "
5754 + mNetworkRequestForCallback.requestId
5755 + " " + mRequests
5756 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
5757 + " callback flags: " + mCallbackFlags;
5758 }
5759 }
5760
5761 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5762 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5763 if (badCapability != null) {
5764 throw new IllegalArgumentException("Cannot request network with " + badCapability);
5765 }
5766 }
5767
5768 // This checks that the passed capabilities either do not request a
5769 // specific SSID/SignalStrength, or the calling app has permission to do so.
5770 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5771 int callerPid, int callerUid, String callerPackageName) {
5772 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
5773 throw new SecurityException("Insufficient permissions to request a specific SSID");
5774 }
5775
5776 if (nc.hasSignalStrength()
5777 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5778 throw new SecurityException(
5779 "Insufficient permissions to request a specific signal strength");
5780 }
5781 mAppOpsManager.checkPackage(callerUid, callerPackageName);
5782
5783 if (!nc.getSubscriptionIds().isEmpty()) {
5784 enforceNetworkFactoryPermission();
5785 }
5786 }
5787
5788 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
5789 final SortedSet<Integer> thresholds = new TreeSet<>();
5790 synchronized (nai) {
5791 // mNetworkRequests may contain the same value multiple times in case of
5792 // multilayer requests. It won't matter in this case because the thresholds
5793 // will then be the same and be deduplicated as they enter the `thresholds` set.
5794 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
5795 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5796 for (final NetworkRequest req : nri.mRequests) {
5797 if (req.networkCapabilities.hasSignalStrength()
5798 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5799 thresholds.add(req.networkCapabilities.getSignalStrength());
5800 }
5801 }
5802 }
5803 }
5804 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
5805 }
5806
5807 private void updateSignalStrengthThresholds(
5808 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5809 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
5810
5811 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
5812 String detail;
5813 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5814 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5815 } else {
5816 detail = reason;
5817 }
5818 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5819 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
5820 }
5821
5822 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
5823 }
5824
5825 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5826 if (nc == null) {
5827 return;
5828 }
5829 NetworkSpecifier ns = nc.getNetworkSpecifier();
5830 if (ns == null) {
5831 return;
5832 }
5833 if (ns instanceof MatchAllNetworkSpecifier) {
5834 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5835 }
5836 }
5837
5838 private void ensureValid(NetworkCapabilities nc) {
5839 ensureValidNetworkSpecifier(nc);
5840 if (nc.isPrivateDnsBroken()) {
5841 throw new IllegalArgumentException("Can't request broken private DNS");
5842 }
5843 }
5844
5845 private boolean isTargetSdkAtleast(int version, int callingUid,
5846 @NonNull String callingPackageName) {
5847 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
5848 final PackageManager pm =
5849 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
5850 try {
5851 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
5852 if (callingVersion < version) return false;
5853 } catch (PackageManager.NameNotFoundException e) { }
5854 return true;
5855 }
5856
5857 @Override
5858 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
5859 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
5860 int legacyType, int callbackFlags, @NonNull String callingPackageName,
5861 @Nullable String callingAttributionTag) {
5862 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
5863 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5864 callingPackageName)) {
5865 throw new SecurityException("Insufficient permissions to specify legacy type");
5866 }
5867 }
5868 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
5869 final int callingUid = mDeps.getCallingUid();
5870 // Privileged callers can track the default network of another UID by passing in a UID.
5871 if (asUid != Process.INVALID_UID) {
5872 enforceSettingsPermission();
5873 } else {
5874 asUid = callingUid;
5875 }
5876 final NetworkRequest.Type reqType;
5877 try {
5878 reqType = NetworkRequest.Type.values()[reqTypeInt];
5879 } catch (ArrayIndexOutOfBoundsException e) {
5880 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5881 }
5882 switch (reqType) {
5883 case TRACK_DEFAULT:
5884 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
5885 // is unused and will be replaced by ones appropriate for the UID (usually, the
5886 // calling app). This allows callers to keep track of the default network.
5887 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
5888 defaultNc, asUid, callingUid, callingPackageName);
5889 enforceAccessPermission();
5890 break;
5891 case TRACK_SYSTEM_DEFAULT:
5892 enforceSettingsPermission();
5893 networkCapabilities = new NetworkCapabilities(defaultNc);
5894 break;
5895 case BACKGROUND_REQUEST:
5896 enforceNetworkStackOrSettingsPermission();
5897 // Fall-through since other checks are the same with normal requests.
5898 case REQUEST:
5899 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5900 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
5901 callingAttributionTag);
5902 // TODO: this is incorrect. We mark the request as metered or not depending on
5903 // the state of the app when the request is filed, but we never change the
5904 // request if the app changes network state. http://b/29964605
5905 enforceMeteredApnPolicy(networkCapabilities);
5906 break;
5907 case LISTEN_FOR_BEST:
5908 enforceAccessPermission();
5909 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5910 break;
5911 default:
5912 throw new IllegalArgumentException("Unsupported request type " + reqType);
5913 }
5914 ensureRequestableCapabilities(networkCapabilities);
5915 ensureSufficientPermissionsForRequest(networkCapabilities,
5916 Binder.getCallingPid(), callingUid, callingPackageName);
5917
5918 // Enforce FOREGROUND if the caller does not have permission to use background network.
5919 if (reqType == LISTEN_FOR_BEST) {
5920 restrictBackgroundRequestForCaller(networkCapabilities);
5921 }
5922
5923 // Set the UID range for this request to the single UID of the requester, unless the
5924 // requester has the permission to specify other UIDs.
5925 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5926 // are no visible methods to set the UIDs, an app could use reflection to try and get
5927 // networks for other apps so it's essential that the UIDs are overwritten.
5928 // Also set the requester UID and package name in the request.
5929 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
5930 callingUid, callingPackageName);
5931
5932 if (timeoutMs < 0) {
5933 throw new IllegalArgumentException("Bad timeout specified");
5934 }
5935 ensureValid(networkCapabilities);
5936
5937 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
5938 nextNetworkRequestId(), reqType);
5939 final NetworkRequestInfo nri = getNriToRegister(
5940 asUid, networkRequest, messenger, binder, callbackFlags,
5941 callingAttributionTag);
5942 if (DBG) log("requestNetwork for " + nri);
5943
5944 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
5945 // copied from the default request above. (This is necessary to ensure, for example, that
5946 // the callback does not leak sensitive information to unprivileged apps.) Check that the
5947 // changes don't alter request matching.
5948 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
5949 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
5950 throw new IllegalStateException(
5951 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
5952 + networkCapabilities + " vs. " + defaultNc);
5953 }
5954
5955 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
5956 if (timeoutMs > 0) {
5957 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
5958 nri), timeoutMs);
5959 }
5960 return networkRequest;
5961 }
5962
5963 /**
5964 * Return the nri to be used when registering a network request. Specifically, this is used with
5965 * requests registered to track the default request. If there is currently a per-app default
5966 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
5967 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
5968 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
5969 * when a privileged caller is tracking the default network for another uid.
5970 * @param nr the network request for the nri.
5971 * @param msgr the messenger for the nri.
5972 * @param binder the binder for the nri.
5973 * @param callingAttributionTag the calling attribution tag for the nri.
5974 * @return the nri to register.
5975 */
5976 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
5977 @Nullable final Messenger msgr, @Nullable final IBinder binder,
5978 @NetworkCallback.Flag int callbackFlags,
5979 @Nullable String callingAttributionTag) {
5980 final List<NetworkRequest> requests;
5981 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
5982 requests = copyDefaultNetworkRequestsForUid(
5983 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
5984 } else {
5985 requests = Collections.singletonList(nr);
5986 }
5987 return new NetworkRequestInfo(
5988 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
5989 }
5990
5991 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
5992 String callingPackageName, String callingAttributionTag) {
5993 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
5994 enforceConnectivityRestrictedNetworksPermission();
5995 } else {
5996 enforceChangePermission(callingPackageName, callingAttributionTag);
5997 }
5998 }
5999
6000 @Override
6001 public boolean requestBandwidthUpdate(Network network) {
6002 enforceAccessPermission();
6003 NetworkAgentInfo nai = null;
6004 if (network == null) {
6005 return false;
6006 }
6007 synchronized (mNetworkForNetId) {
6008 nai = mNetworkForNetId.get(network.getNetId());
6009 }
6010 if (nai != null) {
6011 nai.onBandwidthUpdateRequested();
6012 synchronized (mBandwidthRequests) {
6013 final int uid = mDeps.getCallingUid();
6014 Integer uidReqs = mBandwidthRequests.get(uid);
6015 if (uidReqs == null) {
6016 uidReqs = 0;
6017 }
6018 mBandwidthRequests.put(uid, ++uidReqs);
6019 }
6020 return true;
6021 }
6022 return false;
6023 }
6024
6025 private boolean isSystem(int uid) {
6026 return uid < Process.FIRST_APPLICATION_UID;
6027 }
6028
6029 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
6030 final int uid = mDeps.getCallingUid();
6031 if (isSystem(uid)) {
6032 // Exemption for system uid.
6033 return;
6034 }
6035 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6036 // Policy already enforced.
6037 return;
6038 }
6039 final long ident = Binder.clearCallingIdentity();
6040 try {
6041 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6042 // If UID is restricted, don't allow them to bring up metered APNs.
6043 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6044 }
6045 } finally {
6046 Binder.restoreCallingIdentity(ident);
6047 }
6048 }
6049
6050 @Override
6051 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
6052 PendingIntent operation, @NonNull String callingPackageName,
6053 @Nullable String callingAttributionTag) {
6054 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6055 final int callingUid = mDeps.getCallingUid();
6056 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6057 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6058 callingAttributionTag);
6059 enforceMeteredApnPolicy(networkCapabilities);
6060 ensureRequestableCapabilities(networkCapabilities);
6061 ensureSufficientPermissionsForRequest(networkCapabilities,
6062 Binder.getCallingPid(), callingUid, callingPackageName);
6063 ensureValidNetworkSpecifier(networkCapabilities);
6064 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6065 callingUid, callingPackageName);
6066
6067 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
6068 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
6069 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6070 callingAttributionTag);
6071 if (DBG) log("pendingRequest for " + nri);
6072 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6073 nri));
6074 return networkRequest;
6075 }
6076
6077 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6078 mHandler.sendMessageDelayed(
6079 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6080 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
6081 }
6082
6083 @Override
6084 public void releasePendingNetworkRequest(PendingIntent operation) {
6085 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6086 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6087 mDeps.getCallingUid(), 0, operation));
6088 }
6089
6090 // In order to implement the compatibility measure for pre-M apps that call
6091 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6092 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6093 // This ensures it has permission to do so.
6094 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6095 if (nc == null) {
6096 return false;
6097 }
6098 int[] transportTypes = nc.getTransportTypes();
6099 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6100 return false;
6101 }
6102 try {
6103 mContext.enforceCallingOrSelfPermission(
6104 android.Manifest.permission.ACCESS_WIFI_STATE,
6105 "ConnectivityService");
6106 } catch (SecurityException e) {
6107 return false;
6108 }
6109 return true;
6110 }
6111
6112 @Override
6113 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
6114 Messenger messenger, IBinder binder,
6115 @NetworkCallback.Flag int callbackFlags,
6116 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
6117 final int callingUid = mDeps.getCallingUid();
6118 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6119 enforceAccessPermission();
6120 }
6121
6122 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6123 ensureSufficientPermissionsForRequest(networkCapabilities,
6124 Binder.getCallingPid(), callingUid, callingPackageName);
6125 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6126 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6127 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6128 // onLost and onAvailable callbacks when networks move in and out of the background.
6129 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6130 // can't request networks.
6131 restrictBackgroundRequestForCaller(nc);
6132 ensureValid(nc);
6133
6134 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6135 NetworkRequest.Type.LISTEN);
6136 NetworkRequestInfo nri =
6137 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
6138 callingAttributionTag);
6139 if (VDBG) log("listenForNetwork for " + nri);
6140
6141 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6142 return networkRequest;
6143 }
6144
6145 @Override
6146 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
6147 PendingIntent operation, @NonNull String callingPackageName,
6148 @Nullable String callingAttributionTag) {
6149 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6150 final int callingUid = mDeps.getCallingUid();
6151 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6152 enforceAccessPermission();
6153 }
6154 ensureValid(networkCapabilities);
6155 ensureSufficientPermissionsForRequest(networkCapabilities,
6156 Binder.getCallingPid(), callingUid, callingPackageName);
6157 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6158 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6159
6160 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6161 NetworkRequest.Type.LISTEN);
6162 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6163 callingAttributionTag);
6164 if (VDBG) log("pendingListenForNetwork for " + nri);
6165
6166 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6167 }
6168
6169 /** Returns the next Network provider ID. */
6170 public final int nextNetworkProviderId() {
6171 return mNextNetworkProviderId.getAndIncrement();
6172 }
6173
6174 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
6175 for (int i = 0; i < networkRequests.size(); i++) {
6176 releaseNetworkRequest(networkRequests.get(i));
6177 }
6178 }
6179
6180 @Override
6181 public void releaseNetworkRequest(NetworkRequest networkRequest) {
6182 ensureNetworkRequestHasType(networkRequest);
6183 mHandler.sendMessage(mHandler.obtainMessage(
6184 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
6185 }
6186
6187 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6188 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
6189 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6190 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6191 // as that will throw if a duplicate provider is registered.
6192 loge("Attempt to register existing NetworkProviderInfo "
6193 + mNetworkProviderInfos.get(npi.messenger).name);
6194 return;
6195 }
6196
6197 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6198 mNetworkProviderInfos.put(npi.messenger, npi);
6199 npi.connect(mContext, mTrackerHandler);
6200 }
6201
6202 @Override
6203 public int registerNetworkProvider(Messenger messenger, String name) {
6204 enforceNetworkFactoryOrSettingsPermission();
6205 Objects.requireNonNull(messenger, "messenger must be non-null");
6206 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
6207 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
6208 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6209 return npi.providerId;
6210 }
6211
6212 @Override
6213 public void unregisterNetworkProvider(Messenger messenger) {
6214 enforceNetworkFactoryOrSettingsPermission();
6215 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
6216 }
6217
6218 @Override
6219 public void offerNetwork(final int providerId,
6220 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6221 @NonNull final INetworkOfferCallback callback) {
6222 Objects.requireNonNull(score);
6223 Objects.requireNonNull(caps);
6224 Objects.requireNonNull(callback);
6225 final NetworkOffer offer = new NetworkOffer(
6226 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
6227 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6228 }
6229
6230 @Override
6231 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6233 }
6234
6235 private void handleUnregisterNetworkProvider(Messenger messenger) {
6236 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6237 if (npi == null) {
6238 loge("Failed to find Messenger in unregisterNetworkProvider");
6239 return;
6240 }
6241 // Unregister all the offers from this provider
6242 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6243 for (final NetworkOfferInfo noi : mNetworkOffers) {
6244 if (noi.offer.providerId == npi.providerId) {
6245 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6246 toRemove.add(noi);
6247 }
6248 }
6249 for (final NetworkOfferInfo noi : toRemove) {
6250 handleUnregisterNetworkOffer(noi);
6251 }
6252 if (DBG) log("unregisterNetworkProvider for " + npi.name);
6253 }
6254
6255 @Override
6256 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
6257 if (request.hasTransport(TRANSPORT_TEST)) {
6258 enforceNetworkFactoryOrTestNetworksPermission();
6259 } else {
6260 enforceNetworkFactoryPermission();
6261 }
6262 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6263 if (nri != null) {
6264 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6265 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6266 mHandler.post(() -> handleReleaseNetworkRequest(
6267 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6268 }
6269 }
6270
6271 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6272 @GuardedBy("mNetworkForNetId")
6273 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
6274 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
6275 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
6276 // there may not be a strict 1:1 correlation between the two.
6277 private final NetIdManager mNetIdManager;
6278
6279 // NetworkAgentInfo keyed off its connecting messenger
6280 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
6281 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
6282 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
6283
6284 // UID ranges for users that are currently blocked by VPNs.
6285 // This array is accessed and iterated on multiple threads without holding locks, so its
6286 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6287 // (on the handler thread).
6288 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6289
6290 // Must only be accessed on the handler thread
6291 @NonNull
6292 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6293
6294 @GuardedBy("mBlockedAppUids")
6295 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
6296
6297 // Current OEM network preferences. This object must only be written to on the handler thread.
6298 // Since it is immutable and always non-null, other threads may read it if they only care
6299 // about seeing a consistent object but not that it is current.
6300 @NonNull
6301 private OemNetworkPreferences mOemNetworkPreferences =
6302 new OemNetworkPreferences.Builder().build();
6303 // Current per-profile network preferences. This object follows the same threading rules as
6304 // the OEM network preferences above.
6305 @NonNull
6306 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
6307
6308 // OemNetworkPreferences activity String log entries.
6309 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6310 @NonNull
6311 private final LocalLog mOemNetworkPreferencesLogs =
6312 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6313
6314 /**
6315 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6316 * @param packageName the package name to check existence of a mapping for.
6317 * @return true if a mapping exists, false otherwise
6318 */
6319 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6320 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6321 }
6322
6323 // The always-on request for an Internet-capable network that apps without a specific default
6324 // fall back to.
6325 @VisibleForTesting
6326 @NonNull
6327 final NetworkRequestInfo mDefaultRequest;
6328 // Collection of NetworkRequestInfo's used for default networks.
6329 @VisibleForTesting
6330 @NonNull
6331 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
6332
6333 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6334 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6335 }
6336
6337 /**
6338 * Return the default network request currently tracking the given uid.
6339 * @param uid the uid to check.
6340 * @return the NetworkRequestInfo tracking the given uid.
6341 */
6342 @NonNull
6343 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
6344 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6345 if (nri == mDefaultRequest) {
6346 continue;
6347 }
6348 // Checking the first request is sufficient as only multilayer requests will have more
6349 // than one request and for multilayer, all requests will track the same uids.
6350 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6351 return nri;
6352 }
6353 }
6354 return mDefaultRequest;
6355 }
6356
6357 /**
6358 * Get a copy of the network requests of the default request that is currently tracking the
6359 * given uid.
6360 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6361 * when a privileged caller is tracking the default network for another uid.
6362 * @param requestorUid the uid to check the default for.
6363 * @param requestorPackageName the requestor's package name.
6364 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6365 */
6366 @NonNull
6367 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
6368 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
6369 return copyNetworkRequestsForUid(
6370 getDefaultRequestTrackingUid(asUid).mRequests,
6371 asUid, requestorUid, requestorPackageName);
6372 }
6373
6374 /**
6375 * Copy the given nri's NetworkRequest collection.
6376 * @param requestsToCopy the NetworkRequest collection to be copied.
6377 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6378 * when a privileged caller is tracking the default network for another uid.
6379 * @param requestorUid the uid to set on the copied collection.
6380 * @param requestorPackageName the package name to set on the copied collection.
6381 * @return the copied NetworkRequest collection.
6382 */
6383 @NonNull
6384 private List<NetworkRequest> copyNetworkRequestsForUid(
6385 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6386 final int requestorUid, @NonNull final String requestorPackageName) {
6387 final List<NetworkRequest> requests = new ArrayList<>();
6388 for (final NetworkRequest nr : requestsToCopy) {
6389 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
6390 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
6391 nr.legacyType, nextNetworkRequestId(), nr.type));
6392 }
6393 return requests;
6394 }
6395
6396 @NonNull
6397 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
6398 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6399 final int requestorUid, @NonNull final String requestorPackageName) {
6400 // These capabilities are for a TRACK_DEFAULT callback, so:
6401 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6402 // mDefaultRequest and a per-UID default request.
6403 // TODO: stop depending on the fact that these two unrelated things happen to be the same
6404 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
6405 // not do this in the case of a privileged application.
6406 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6407 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
6408 netCap.setSingleUid(asUid);
6409 restrictRequestUidsForCallerAndSetRequestorInfo(
6410 netCap, requestorUid, requestorPackageName);
6411 return netCap;
6412 }
6413
6414 /**
6415 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6416 * @param nr the network request to check for equality against.
6417 * @return the nri if one exists, null otherwise.
6418 */
6419 @Nullable
6420 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6421 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6422 if (nri.getNetworkRequestForCallback().equals(nr)) {
6423 return nri;
6424 }
6425 }
6426 return null;
6427 }
6428
6429 /**
6430 * Check if an nri is currently being managed by per-app default networking.
6431 * @param nri the nri to check.
6432 * @return true if this nri is currently being managed by per-app default networking.
6433 */
6434 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6435 // nri.mRequests.get(0) is only different from the original request filed in
6436 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6437 // functionality therefore if these two don't match, it means this particular nri is
6438 // currently being managed by a per-app default.
6439 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6440 }
6441
6442 /**
6443 * Determine if an nri is a managed default request that disallows default networking.
6444 * @param nri the request to evaluate
6445 * @return true if device-default networking is disallowed
6446 */
6447 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6448 // Check if this nri is a managed default that supports the default network at its
6449 // lowest priority request.
6450 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6451 final NetworkCapabilities lowestPriorityNetCap =
6452 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6453 return isPerAppDefaultRequest(nri)
6454 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6455 lowestPriorityNetCap));
6456 }
6457
6458 // Request used to optionally keep mobile data active even when higher
6459 // priority networks like Wi-Fi are active.
6460 private final NetworkRequest mDefaultMobileDataRequest;
6461
6462 // Request used to optionally keep wifi data active even when higher
6463 // priority networks like ethernet are active.
6464 private final NetworkRequest mDefaultWifiRequest;
6465
6466 // Request used to optionally keep vehicle internal network always active
6467 private final NetworkRequest mDefaultVehicleRequest;
6468
6469 // TODO replace with INetd.UNREACHABLE_NET_ID when available.
6470 private static final int NO_SERVICE_NET_ID = 52;
6471 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6472 // network with no service. This NAI should never be matched against, nor should any public API
6473 // ever return the associated network. For this reason, this NAI is not in the list of available
6474 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6475 // default requests that don't support using the device default network which will ultimately
6476 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6477 @VisibleForTesting
6478 final NetworkAgentInfo mNoServiceNetwork;
6479
6480 // The NetworkAgentInfo currently satisfying the default request, if any.
6481 private NetworkAgentInfo getDefaultNetwork() {
6482 return mDefaultRequest.mSatisfier;
6483 }
6484
6485 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6486 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6487 // Currently, all network requests will have the same uids therefore checking the first
6488 // one is sufficient. If/when uids are tracked at the nri level, this can change.
6489 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
6490 if (null == uids) {
6491 continue;
6492 }
6493 for (final UidRange range : uids) {
6494 if (range.contains(uid)) {
6495 return nri.getSatisfier();
6496 }
6497 }
6498 }
6499 return getDefaultNetwork();
6500 }
6501
6502 @Nullable
6503 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6504 return nai != null ? nai.network : null;
6505 }
6506
6507 private void ensureRunningOnConnectivityServiceThread() {
6508 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6509 throw new IllegalStateException(
6510 "Not running on ConnectivityService thread: "
6511 + Thread.currentThread().getName());
6512 }
6513 }
6514
6515 @VisibleForTesting
6516 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6517 return nai == getDefaultNetwork();
6518 }
6519
6520 /**
6521 * Register a new agent with ConnectivityService to handle a network.
6522 *
6523 * @param na a reference for ConnectivityService to contact the agent asynchronously.
6524 * @param networkInfo the initial info associated with this network. It can be updated later :
6525 * see {@link #updateNetworkInfo}.
6526 * @param linkProperties the initial link properties of this network. They can be updated
6527 * later : see {@link #updateLinkProperties}.
6528 * @param networkCapabilities the initial capabilites of this network. They can be updated
6529 * later : see {@link #updateCapabilities}.
6530 * @param initialScore the initial score of the network. See
6531 * {@link NetworkAgentInfo#getCurrentScore}.
6532 * @param networkAgentConfig metadata about the network. This is never updated.
6533 * @param providerId the ID of the provider owning this NetworkAgent.
6534 * @return the network created for this agent.
6535 */
6536 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
6537 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6538 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6539 int providerId) {
6540 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6541 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6542 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
6543 Objects.requireNonNull(initialScore, "initialScore must not be null");
6544 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
6545 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6546 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
6547 } else {
6548 enforceNetworkFactoryPermission();
6549 }
6550
6551 final int uid = mDeps.getCallingUid();
6552 final long token = Binder.clearCallingIdentity();
6553 try {
6554 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
6555 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
6556 } finally {
6557 Binder.restoreCallingIdentity(token);
6558 }
6559 }
6560
6561 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
6562 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6563 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6564 int uid) {
6565 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6566 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6567 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6568 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6569 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6570 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
6571 }
6572
6573 LinkProperties lp = new LinkProperties(linkProperties);
6574
6575 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6576 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
6577 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
6578 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
6579 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6580 mQosCallbackTracker, mDeps);
6581
6582 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
6583 processCapabilitiesFromAgent(nai, nc);
6584 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
6585 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6586
6587 final String extraInfo = networkInfo.getExtraInfo();
6588 final String name = TextUtils.isEmpty(extraInfo)
6589 ? nai.networkCapabilities.getSsid() : extraInfo;
6590 if (DBG) log("registerNetworkAgent " + nai);
6591 mDeps.getNetworkStack().makeNetworkMonitor(
6592 nai.network, name, new NetworkMonitorCallbacks(nai));
6593 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6594 // If the network disconnects or sends any other event before that, messages are deferred by
6595 // NetworkAgent until nai.connect(), which will be called when finalizing the
6596 // registration.
6597 return nai.network;
6598 }
6599
6600 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6601 nai.onNetworkMonitorCreated(networkMonitor);
6602 if (VDBG) log("Got NetworkAgent Messenger");
6603 mNetworkAgentInfos.add(nai);
6604 synchronized (mNetworkForNetId) {
6605 mNetworkForNetId.put(nai.network.getNetId(), nai);
6606 }
6607
6608 try {
6609 networkMonitor.start();
6610 } catch (RemoteException e) {
6611 e.rethrowAsRuntimeException();
6612 }
6613 nai.notifyRegistered();
6614 NetworkInfo networkInfo = nai.networkInfo;
6615 updateNetworkInfo(nai, networkInfo);
6616 updateUids(nai, null, nai.networkCapabilities);
6617 }
6618
6619 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6620 @NonNull public final NetworkOffer offer;
6621
6622 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6623 this.offer = offer;
6624 }
6625
6626 @Override
6627 public void binderDied() {
6628 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6629 }
6630 }
6631
6632 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6633 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6634 if (npi.providerId == providerId) return true;
6635 }
6636 return false;
6637 }
6638
6639 /**
6640 * Register or update a network offer.
6641 * @param newOffer The new offer. If the callback member is the same as an existing
6642 * offer, it is an update of that offer.
6643 */
6644 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6645 ensureRunningOnConnectivityServiceThread();
6646 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6647 // This may actually happen if a provider updates its score or registers and then
6648 // immediately unregisters. The offer would still be in the handler queue, but the
6649 // provider would have been removed.
6650 if (DBG) log("Received offer from an unregistered provider");
6651 return;
6652 }
6653 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6654 if (null != existingOffer) {
6655 handleUnregisterNetworkOffer(existingOffer);
6656 newOffer.migrateFrom(existingOffer.offer);
6657 }
6658 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6659 try {
6660 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
6661 } catch (RemoteException e) {
6662 noi.binderDied();
6663 return;
6664 }
6665 mNetworkOffers.add(noi);
6666 issueNetworkNeeds(noi);
6667 }
6668
6669 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6670 ensureRunningOnConnectivityServiceThread();
6671 mNetworkOffers.remove(noi);
6672 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
6673 }
6674
6675 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6676 @NonNull final INetworkOfferCallback callback) {
6677 ensureRunningOnConnectivityServiceThread();
6678 for (final NetworkOfferInfo noi : mNetworkOffers) {
6679 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
6680 }
6681 return null;
6682 }
6683
6684 /**
6685 * Called when receiving LinkProperties directly from a NetworkAgent.
6686 * Stores into |nai| any data coming from the agent that might also be written to the network's
6687 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6688 * agent is not lost when updateLinkProperties is called.
6689 * This method should never alter the agent's LinkProperties, only store data in |nai|.
6690 */
6691 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6692 lp.ensureDirectlyConnectedRoutes();
6693 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
6694 nai.networkAgentPortalData = lp.getCaptivePortalData();
6695 }
6696
6697 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
6698 @NonNull LinkProperties oldLp) {
6699 int netId = networkAgent.network.getNetId();
6700
6701 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6702 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6703 // the LinkProperties for the network are accurate.
6704 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
6705
6706 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
6707
6708 // update filtering rules, need to happen after the interface update so netd knows about the
6709 // new interface (the interface name -> index map becomes initialized)
6710 updateVpnFiltering(newLp, oldLp, networkAgent);
6711
6712 updateMtu(newLp, oldLp);
6713 // TODO - figure out what to do for clat
6714// for (LinkProperties lp : newLp.getStackedLinks()) {
6715// updateMtu(lp, null);
6716// }
6717 if (isDefaultNetwork(networkAgent)) {
6718 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6719 }
6720
6721 updateRoutes(newLp, oldLp, netId);
6722 updateDnses(newLp, oldLp, netId);
6723 // Make sure LinkProperties represents the latest private DNS status.
6724 // This does not need to be done before updateDnses because the
6725 // LinkProperties are not the source of the private DNS configuration.
6726 // updateDnses will fetch the private DNS configuration from DnsManager.
6727 mDnsManager.updatePrivateDnsStatus(netId, newLp);
6728
6729 if (isDefaultNetwork(networkAgent)) {
6730 handleApplyDefaultProxy(newLp.getHttpProxy());
6731 } else {
6732 updateProxy(newLp, oldLp);
6733 }
6734
6735 updateWakeOnLan(newLp);
6736
6737 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6738 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6739 // does, it needs to be merged here.
6740 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6741 networkAgent.capportApiData));
6742
6743 // TODO - move this check to cover the whole function
6744 if (!Objects.equals(newLp, oldLp)) {
6745 synchronized (networkAgent) {
6746 networkAgent.linkProperties = newLp;
6747 }
6748 // Start or stop DNS64 detection and 464xlat according to network state.
6749 networkAgent.clatd.update();
6750 notifyIfacesChangedForNetworkStats();
6751 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6752 new LinkProperties(newLp, true /* parcelSensitiveFields */));
6753 if (networkAgent.everConnected) {
6754 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6755 }
6756 }
6757
6758 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
6759 }
6760
6761 /**
6762 * @param naData captive portal data from NetworkAgent
6763 * @param apiData captive portal data from capport API
6764 */
6765 @Nullable
6766 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6767 CaptivePortalData apiData) {
6768 if (naData == null || apiData == null) {
6769 return naData == null ? apiData : naData;
6770 }
6771 final CaptivePortalData.Builder captivePortalBuilder =
6772 new CaptivePortalData.Builder(naData);
6773
6774 if (apiData.isCaptive()) {
6775 captivePortalBuilder.setCaptive(true);
6776 }
6777 if (apiData.isSessionExtendable()) {
6778 captivePortalBuilder.setSessionExtendable(true);
6779 }
6780 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6781 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6782 // otherwise data would be inconsistent. Prefer the capport API info if present,
6783 // as it can generally be refreshed more often.
6784 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6785 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6786 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6787 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6788 // No source has time / bytes remaining information: surface the newest refresh time
6789 // for other fields
6790 captivePortalBuilder.setRefreshTime(
6791 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6792 }
6793
6794 // Prioritize the user portal URL from the network agent if the source is authenticated.
6795 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6796 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6797 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6798 apiData.getUserPortalUrlSource());
6799 }
6800 // Prioritize the venue information URL from the network agent if the source is
6801 // authenticated.
6802 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6803 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6804 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6805 apiData.getVenueInfoUrlSource());
6806 }
6807 return captivePortalBuilder.build();
6808 }
6809
6810 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
6811 // Marks are only available on WiFi interfaces. Checking for
6812 // marks on unsupported interfaces is harmless.
6813 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6814 return;
6815 }
6816
6817 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6818 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6819
6820 // TODO (b/183076074): remove legacy fallback after migrating overlays
6821 final int legacyMark = mContext.getResources().getInteger(mContext.getResources()
6822 .getIdentifier("config_networkWakeupPacketMark", "integer", "android"));
6823 final int legacyMask = mContext.getResources().getInteger(mContext.getResources()
6824 .getIdentifier("config_networkWakeupPacketMask", "integer", "android"));
6825 mark = mark == 0 ? legacyMark : mark;
6826 mask = mask == 0 ? legacyMask : mask;
6827
6828 // Mask/mark of zero will not detect anything interesting.
6829 // Don't install rules unless both values are nonzero.
6830 if (mark == 0 || mask == 0) {
6831 return;
6832 }
6833
6834 final String prefix = "iface:" + iface;
6835 try {
6836 if (add) {
6837 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
6838 } else {
6839 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
6840 }
6841 } catch (Exception e) {
6842 loge("Exception modifying wakeup packet monitoring: " + e);
6843 }
6844
6845 }
6846
6847 private void updateInterfaces(final @Nullable LinkProperties newLp,
6848 final @Nullable LinkProperties oldLp, final int netId,
6849 final @NonNull NetworkCapabilities caps) {
6850 final CompareResult<String> interfaceDiff = new CompareResult<>(
6851 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6852 newLp != null ? newLp.getAllInterfaceNames() : null);
6853 if (!interfaceDiff.added.isEmpty()) {
6854 for (final String iface : interfaceDiff.added) {
6855 try {
6856 if (DBG) log("Adding iface " + iface + " to network " + netId);
6857 mNetd.networkAddInterface(netId, iface);
6858 wakeupModifyInterface(iface, caps, true);
6859 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6860 caps.getTransportTypes());
6861 } catch (Exception e) {
6862 logw("Exception adding interface: " + e);
6863 }
6864 }
6865 }
6866 for (final String iface : interfaceDiff.removed) {
6867 try {
6868 if (DBG) log("Removing iface " + iface + " from network " + netId);
6869 wakeupModifyInterface(iface, caps, false);
6870 mNetd.networkRemoveInterface(netId, iface);
6871 } catch (Exception e) {
6872 loge("Exception removing interface: " + e);
6873 }
6874 }
6875 }
6876
6877 // TODO: move to frameworks/libs/net.
6878 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6879 final String nextHop;
6880
6881 switch (route.getType()) {
6882 case RouteInfo.RTN_UNICAST:
6883 if (route.hasGateway()) {
6884 nextHop = route.getGateway().getHostAddress();
6885 } else {
6886 nextHop = INetd.NEXTHOP_NONE;
6887 }
6888 break;
6889 case RouteInfo.RTN_UNREACHABLE:
6890 nextHop = INetd.NEXTHOP_UNREACHABLE;
6891 break;
6892 case RouteInfo.RTN_THROW:
6893 nextHop = INetd.NEXTHOP_THROW;
6894 break;
6895 default:
6896 nextHop = INetd.NEXTHOP_NONE;
6897 break;
6898 }
6899
6900 final RouteInfoParcel rip = new RouteInfoParcel();
6901 rip.ifName = route.getInterface();
6902 rip.destination = route.getDestination().toString();
6903 rip.nextHop = nextHop;
6904 rip.mtu = route.getMtu();
6905
6906 return rip;
6907 }
6908
6909 /**
6910 * Have netd update routes from oldLp to newLp.
6911 * @return true if routes changed between oldLp and newLp
6912 */
6913 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
6914 // compare the route diff to determine which routes have been updated
6915 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
6916 new CompareOrUpdateResult<>(
6917 oldLp != null ? oldLp.getAllRoutes() : null,
6918 newLp != null ? newLp.getAllRoutes() : null,
6919 (r) -> r.getRouteKey());
6920
6921 // add routes before removing old in case it helps with continuous connectivity
6922
6923 // do this twice, adding non-next-hop routes first, then routes they are dependent on
6924 for (RouteInfo route : routeDiff.added) {
6925 if (route.hasGateway()) continue;
6926 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
6927 try {
6928 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
6929 } catch (Exception e) {
6930 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
6931 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
6932 }
6933 }
6934 }
6935 for (RouteInfo route : routeDiff.added) {
6936 if (!route.hasGateway()) continue;
6937 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
6938 try {
6939 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
6940 } catch (Exception e) {
6941 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
6942 loge("Exception in networkAddRouteParcel for gateway: " + e);
6943 }
6944 }
6945 }
6946
6947 for (RouteInfo route : routeDiff.removed) {
6948 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
6949 try {
6950 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
6951 } catch (Exception e) {
6952 loge("Exception in networkRemoveRouteParcel: " + e);
6953 }
6954 }
6955
6956 for (RouteInfo route : routeDiff.updated) {
6957 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
6958 try {
6959 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
6960 } catch (Exception e) {
6961 loge("Exception in networkUpdateRouteParcel: " + e);
6962 }
6963 }
6964 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
6965 || !routeDiff.updated.isEmpty();
6966 }
6967
6968 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
6969 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
6970 return; // no updating necessary
6971 }
6972
6973 if (DBG) {
6974 final Collection<InetAddress> dnses = newLp.getDnsServers();
6975 log("Setting DNS servers for network " + netId + " to " + dnses);
6976 }
6977 try {
6978 mDnsManager.noteDnsServersForNetwork(netId, newLp);
6979 mDnsManager.flushVmDnsCache();
6980 } catch (Exception e) {
6981 loge("Exception in setDnsConfigurationForNetwork: " + e);
6982 }
6983 }
6984
6985 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
6986 NetworkAgentInfo nai) {
6987 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
6988 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
6989 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
6990 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
6991
6992 if (!wasFiltering && !needsFiltering) {
6993 // Nothing to do.
6994 return;
6995 }
6996
6997 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
6998 // Nothing changed.
6999 return;
7000 }
7001
7002 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
7003 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
7004 // TODO: this create a window of opportunity for apps to receive traffic between the time
7005 // when the old rules are removed and the time when new rules are added. To fix this,
7006 // make eBPF support two allowlisted interfaces so here new rules can be added before the
7007 // old rules are being removed.
7008 if (wasFiltering) {
7009 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7010 }
7011 if (needsFiltering) {
7012 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7013 }
7014 }
7015
7016 private void updateWakeOnLan(@NonNull LinkProperties lp) {
7017 if (mWolSupportedInterfaces == null) {
7018 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
7019 R.array.config_wakeonlan_supported_interfaces));
7020 }
7021 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7022 }
7023
7024 private int getNetworkPermission(NetworkCapabilities nc) {
7025 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7026 return INetd.PERMISSION_SYSTEM;
7027 }
7028 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
7029 return INetd.PERMISSION_NETWORK;
7030 }
7031 return INetd.PERMISSION_NONE;
7032 }
7033
7034 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7035 @NonNull final NetworkCapabilities newNc) {
7036 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7037 final int newPermission = getNetworkPermission(newNc);
7038 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7039 try {
7040 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
7041 } catch (RemoteException | ServiceSpecificException e) {
7042 loge("Exception in networkSetPermissionForNetwork: " + e);
7043 }
7044 }
7045 }
7046
7047 /**
7048 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7049 * Stores into |nai| any data coming from the agent that might also be written to the network's
7050 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7051 * agent is not lost when updateCapabilities is called.
7052 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
7053 */
7054 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
7055 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7056 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7057 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7058 // the owner UID here and behave as if the agent had never tried to change it.
7059 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7060 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7061 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7062 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7063 }
7064 nai.declaredCapabilities = new NetworkCapabilities(nc);
7065 }
7066
7067 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
7068 @VisibleForTesting
7069 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
7070 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
7071 underlyingNetworks = underlyingNetworksOrDefault(
7072 agentCaps.getOwnerUid(), underlyingNetworks);
7073 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
7074 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7075 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7076 // metered if any underlying is metered, or originally declared metered by the agent.
7077 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7078 boolean roaming = false; // roaming if any underlying is roaming
7079 boolean congested = false; // congested if any underlying is congested
7080 boolean suspended = true; // suspended if all underlying are suspended
7081
7082 boolean hadUnderlyingNetworks = false;
7083 if (null != underlyingNetworks) {
7084 for (Network underlyingNetwork : underlyingNetworks) {
7085 final NetworkAgentInfo underlying =
7086 getNetworkAgentInfoForNetwork(underlyingNetwork);
7087 if (underlying == null) continue;
7088
7089 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7090 hadUnderlyingNetworks = true;
7091 for (int underlyingType : underlyingCaps.getTransportTypes()) {
7092 transportTypes |= 1L << underlyingType;
7093 }
7094
7095 // Merge capabilities of this underlying network. For bandwidth, assume the
7096 // worst case.
7097 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7098 underlyingCaps.getLinkDownstreamBandwidthKbps());
7099 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7100 underlyingCaps.getLinkUpstreamBandwidthKbps());
7101 // If this underlying network is metered, the VPN is metered (it may cost money
7102 // to send packets on this network).
7103 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7104 // If this underlying network is roaming, the VPN is roaming (the billing structure
7105 // is different than the usual, local one).
7106 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7107 // If this underlying network is congested, the VPN is congested (the current
7108 // condition of the network affects the performance of this network).
7109 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7110 // If this network is not suspended, the VPN is not suspended (the VPN
7111 // is able to transfer some data).
7112 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7113 }
7114 }
7115 if (!hadUnderlyingNetworks) {
7116 // No idea what the underlying networks are; assume reasonable defaults
7117 metered = true;
7118 roaming = false;
7119 congested = false;
7120 suspended = false;
7121 }
7122
7123 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
7124 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7125 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7126 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7127 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7128 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7129 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
7130 }
7131
7132 /**
7133 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7134 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7135 * and foreground status).
7136 */
7137 @NonNull
7138 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
7139 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
7140 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7141 // causing a connect/teardown loop.
7142 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
7143 // avoid connect/teardown loops.
7144 if (nai.everConnected &&
7145 !nai.isVPN() &&
7146 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7147 // TODO: consider not complaining when a network agent degrades its capabilities if this
7148 // does not cause any request (that is not a listen) currently matching that agent to
7149 // stop being matched by the updated agent.
7150 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
7151 if (!TextUtils.isEmpty(diff)) {
7152 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
7153 }
7154 }
7155
7156 // Don't modify caller's NetworkCapabilities.
7157 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
7158 if (nai.lastValidated) {
7159 newNc.addCapability(NET_CAPABILITY_VALIDATED);
7160 } else {
7161 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
7162 }
7163 if (nai.lastCaptivePortalDetected) {
7164 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7165 } else {
7166 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7167 }
7168 if (nai.isBackgroundNetwork()) {
7169 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
7170 } else {
7171 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
7172 }
7173 if (nai.partialConnectivity) {
7174 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7175 } else {
7176 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7177 }
7178 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
7179
7180 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
7181 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7182 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
7183 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
7184 }
7185
7186 if (nai.supportsUnderlyingNetworks()) {
7187 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7188 newNc);
7189 }
7190
7191 return newNc;
7192 }
7193
7194 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7195 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7196 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7197 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7198 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7199 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7200 if (prevSuspended != suspended) {
7201 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7202 // onResumed have been removed.
7203 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7204 : ConnectivityManager.CALLBACK_RESUMED);
7205 }
7206 if (prevSuspended != suspended || prevRoaming != roaming) {
7207 // updateNetworkInfo will mix in the suspended info from the capabilities and
7208 // take appropriate action for the network having possibly changed state.
7209 updateNetworkInfo(nai, nai.networkInfo);
7210 }
7211 }
7212
7213 /**
7214 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7215 *
7216 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7217 * capabilities we manage and store in {@code nai}, such as validated status and captive
7218 * portal status)
7219 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7220 * potentially triggers rematches.
7221 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7222 * change.)
7223 *
7224 * @param oldScore score of the network before any of the changes that prompted us
7225 * to call this function.
7226 * @param nai the network having its capabilities updated.
7227 * @param nc the new network capabilities.
7228 */
7229 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7230 @NonNull final NetworkCapabilities nc) {
7231 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
7232 if (Objects.equals(nai.networkCapabilities, newNc)) return;
7233 updateNetworkPermissions(nai, newNc);
7234 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
7235
7236 updateUids(nai, prevNc, newNc);
7237 nai.updateScoreForNetworkAgentUpdate();
7238
7239 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
7240 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7241 // the change we're processing can't affect any requests, it can only affect the listens
7242 // on this network. We might have been called by rematchNetworkAndRequests when a
7243 // network changed foreground state.
7244 processListenRequests(nai);
7245 } else {
7246 // If the requestable capabilities have changed or the score changed, we can't have been
7247 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
7248 rematchAllNetworksAndRequests();
7249 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7250 }
7251 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
7252
7253 final boolean oldMetered = prevNc.isMetered();
7254 final boolean newMetered = newNc.isMetered();
7255 final boolean meteredChanged = oldMetered != newMetered;
7256
7257 if (meteredChanged) {
7258 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7259 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
7260 }
7261
7262 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7263 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7264
7265 // Report changes that are interesting for network statistics tracking.
7266 if (meteredChanged || roamingChanged) {
7267 notifyIfacesChangedForNetworkStats();
7268 }
7269
7270 // This network might have been underlying another network. Propagate its capabilities.
7271 propagateUnderlyingNetworkCapabilities(nai.network);
7272
7273 if (!newNc.equalsTransportTypes(prevNc)) {
7274 mDnsManager.updateTransportsForNetwork(
7275 nai.network.getNetId(), newNc.getTransportTypes());
7276 }
7277 }
7278
7279 /** Convenience method to update the capabilities for a given network. */
7280 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7281 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7282 }
7283
7284 /**
7285 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7286 * network.
7287 *
7288 * Ingress interface filtering enforces that all apps under the given network can only receive
7289 * packets from the network's interface (and loopback). This is important for VPNs because
7290 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7291 * non-VPN interfaces.
7292 *
7293 * As a result, this method should return true iff
7294 * 1. the network is an app VPN (not legacy VPN)
7295 * 2. the VPN does not allow bypass
7296 * 3. the VPN is fully-routed
7297 * 4. the VPN interface is non-null
7298 *
7299 * @see INetd#firewallAddUidInterfaceRules
7300 * @see INetd#firewallRemoveUidInterfaceRules
7301 */
7302 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7303 LinkProperties lp) {
7304 if (nc == null || lp == null) return false;
7305 return nai.isVPN()
7306 && !nai.networkAgentConfig.allowBypass
7307 && nc.getOwnerUid() != Process.SYSTEM_UID
7308 && lp.getInterfaceName() != null
7309 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7310 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
7311 }
7312
7313 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7314 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7315 int index = 0;
7316 for (UidRange range : ranges) {
7317 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7318 index++;
7319 }
7320 return stableRanges;
7321 }
7322
7323 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7324 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7325 for (int i = 0; i < ranges.length; i++) {
7326 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7327 }
7328 return stableRanges;
7329 }
7330
7331 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7332 int[] exemptUids) {
7333 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7334 try {
7335 mNetd.socketDestroy(ranges, exemptUids);
7336 } catch (Exception e) {
7337 loge("Exception in socket destroy: ", e);
7338 }
7339 }
7340 }
7341
7342 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7343 int[] exemptUids = new int[2];
7344 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7345 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7346 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7347 exemptUids[0] = VPN_UID;
7348 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7349 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7350
7351 maybeCloseSockets(nai, ranges, exemptUids);
7352 try {
7353 if (add) {
7354 mNetd.networkAddUidRanges(nai.network.netId, ranges);
7355 } else {
7356 mNetd.networkRemoveUidRanges(nai.network.netId, ranges);
7357 }
7358 } catch (Exception e) {
7359 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7360 " on netId " + nai.network.netId + ". " + e);
7361 }
7362 maybeCloseSockets(nai, ranges, exemptUids);
7363 }
7364
7365 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7366 NetworkCapabilities newNc) {
7367 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7368 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
7369 if (null == prevRanges) prevRanges = new ArraySet<>();
7370 if (null == newRanges) newRanges = new ArraySet<>();
7371 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7372
7373 prevRanges.removeAll(newRanges);
7374 newRanges.removeAll(prevRangesCopy);
7375
7376 try {
7377 // When updating the VPN uid routing rules, add the new range first then remove the old
7378 // range. If old range were removed first, there would be a window between the old
7379 // range being removed and the new range being added, during which UIDs contained
7380 // in both ranges are not subject to any VPN routing rules. Adding new range before
7381 // removing old range works because, unlike the filtering rules below, it's possible to
7382 // add duplicate UID routing rules.
7383 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7384 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7385 // [1-5] & [1-2],[4-5] == [3]
7386 // Then we can do:
7387 // maybeCloseSockets([3])
7388 // mNetd.networkAddUidRanges([1-2],[4-5])
7389 // mNetd.networkRemoveUidRanges([1-5])
7390 // maybeCloseSockets([3])
7391 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7392 // number of binder calls from 6 to 4.
7393 if (!newRanges.isEmpty()) {
7394 updateUidRanges(true, nai, newRanges);
7395 }
7396 if (!prevRanges.isEmpty()) {
7397 updateUidRanges(false, nai, prevRanges);
7398 }
7399 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7400 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7401 final String iface = nai.linkProperties.getInterfaceName();
7402 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
7403 // be added, due to the range being expanded and stored as individual UIDs. For example
7404 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7405 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7406 // were added first and then newRanges got removed later, there would be only one uid
7407 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7408 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7409 // Note that this is in contrast with the (more robust) update of VPN routing rules
7410 // above, where the addition of new ranges happens before the removal of old ranges.
7411 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7412 // to be removed will never overlap with the new range to be added.
7413 if (wasFiltering && !prevRanges.isEmpty()) {
7414 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
7415 }
7416 if (shouldFilter && !newRanges.isEmpty()) {
7417 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
7418 }
7419 } catch (Exception e) {
7420 // Never crash!
7421 loge("Exception in updateUids: ", e);
7422 }
7423 }
7424
7425 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
7426 ensureRunningOnConnectivityServiceThread();
7427
7428 if (getNetworkAgentInfoForNetId(nai.network.getNetId()) != nai) {
7429 // Ignore updates for disconnected networks
7430 return;
7431 }
7432 if (VDBG || DDBG) {
7433 log("Update of LinkProperties for " + nai.toShortString()
7434 + "; created=" + nai.created
7435 + "; everConnected=" + nai.everConnected);
7436 }
7437 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7438 // modify its oldLp parameter.
7439 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
7440 }
7441
7442 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7443 int notificationType) {
7444 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
7445 Intent intent = new Intent();
7446 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
7447 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7448 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7449 // such an API is ever implemented, there is no doubt the right request to send in
7450 // EXTRA_NETWORK_REQUEST is mActiveRequest, and whatever ID would be added would need to
7451 // be sent as a separate extra.
7452 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.getActiveRequest());
7453 nri.mPendingIntentSent = true;
7454 sendIntent(nri.mPendingIntent, intent);
7455 }
7456 // else not handled
7457 }
7458
7459 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7460 mPendingIntentWakeLock.acquire();
7461 try {
7462 if (DBG) log("Sending " + pendingIntent);
7463 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7464 } catch (PendingIntent.CanceledException e) {
7465 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7466 mPendingIntentWakeLock.release();
7467 releasePendingNetworkRequest(pendingIntent);
7468 }
7469 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7470 }
7471
7472 @Override
7473 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7474 String resultData, Bundle resultExtras) {
7475 if (DBG) log("Finished sending " + pendingIntent);
7476 mPendingIntentWakeLock.release();
7477 // Release with a delay so the receiving client has an opportunity to put in its
7478 // own request.
7479 releasePendingNetworkRequestWithDelay(pendingIntent);
7480 }
7481
7482 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7483 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7484 final int arg1) {
7485 if (nri.mMessenger == null) {
7486 // Default request has no msgr. Also prevents callbacks from being invoked for
7487 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7488 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7489 return;
7490 }
7491 Bundle bundle = new Bundle();
7492 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7493 // TODO: check if defensive copies of data is needed.
7494 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
7495 putParcelable(bundle, nrForCallback);
7496 Message msg = Message.obtain();
7497 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7498 putParcelable(bundle, networkAgent.network);
7499 }
7500 final boolean includeLocationSensitiveInfo =
7501 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
7502 switch (notificationType) {
7503 case ConnectivityManager.CALLBACK_AVAILABLE: {
7504 final NetworkCapabilities nc =
7505 networkCapabilitiesRestrictedForCallerPermissions(
7506 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7507 putParcelable(
7508 bundle,
7509 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7510 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7511 nrForCallback.getRequestorPackageName(),
7512 nri.mCallingAttributionTag));
7513 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7514 networkAgent.linkProperties, nri.mPid, nri.mUid));
7515 // For this notification, arg1 contains the blocked status.
7516 msg.arg1 = arg1;
7517 break;
7518 }
7519 case ConnectivityManager.CALLBACK_LOSING: {
7520 msg.arg1 = arg1;
7521 break;
7522 }
7523 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
7524 // networkAgent can't be null as it has been accessed a few lines above.
7525 final NetworkCapabilities netCap =
7526 networkCapabilitiesRestrictedForCallerPermissions(
7527 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7528 putParcelable(
7529 bundle,
7530 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7531 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7532 nrForCallback.getRequestorPackageName(),
7533 nri.mCallingAttributionTag));
7534 break;
7535 }
7536 case ConnectivityManager.CALLBACK_IP_CHANGED: {
7537 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7538 networkAgent.linkProperties, nri.mPid, nri.mUid));
7539 break;
7540 }
7541 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
7542 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
7543 msg.arg1 = arg1;
7544 break;
7545 }
7546 }
7547 msg.what = notificationType;
7548 msg.setData(bundle);
7549 try {
7550 if (VDBG) {
7551 String notification = ConnectivityManager.getCallbackName(notificationType);
7552 log("sending notification " + notification + " for " + nrForCallback);
7553 }
7554 nri.mMessenger.send(msg);
7555 } catch (RemoteException e) {
7556 // may occur naturally in the race of binder death.
7557 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
7558 }
7559 }
7560
7561 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7562 bundle.putParcelable(t.getClass().getSimpleName(), t);
7563 }
7564
7565 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
7566 if (nai.numRequestNetworkRequests() != 0) {
7567 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7568 NetworkRequest nr = nai.requestAt(i);
7569 // Ignore listening and track default requests.
7570 if (!nr.isRequest()) continue;
7571 loge("Dead network still had at least " + nr);
7572 break;
7573 }
7574 }
7575 nai.disconnect();
7576 }
7577
7578 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7579 if (oldNetwork == null) {
7580 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7581 return;
7582 }
7583 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
7584
7585 // If we get here it means that the last linger timeout for this network expired. So there
7586 // must be no other active linger timers, and we must stop lingering.
7587 oldNetwork.clearInactivityState();
7588
7589 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
7590 // Tear the network down.
7591 teardownUnneededNetwork(oldNetwork);
7592 } else {
7593 // Put the network in the background if it doesn't satisfy any foreground request.
7594 updateCapabilitiesForNetwork(oldNetwork);
7595 }
7596 }
7597
7598 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7599 boolean isDefaultChanged = false;
7600 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7601 final NetworkReassignment.RequestReassignment reassignment =
7602 changes.getReassignment(defaultRequestInfo);
7603 if (null == reassignment) {
7604 continue;
7605 }
7606 // reassignment only contains those instances where the satisfying network changed.
7607 isDefaultChanged = true;
7608 // Notify system services of the new default.
7609 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7610 }
7611
7612 if (isDefaultChanged) {
7613 // Hold a wakelock for a short time to help apps in migrating to a new default.
7614 scheduleReleaseNetworkTransitionWakelock();
7615 }
7616 }
7617
7618 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7619 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7620 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7621 if (DBG) {
7622 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7623 }
7624
7625 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7626 if (newDefaultNetwork != null) {
7627 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
7628 }
7629
7630 // Set an app level managed default and return since further processing only applies to the
7631 // default network.
7632 if (mDefaultRequest != nri) {
7633 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7634 return;
7635 }
7636
7637 makeDefaultNetwork(newDefaultNetwork);
7638
7639 if (oldDefaultNetwork != null) {
7640 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7641 }
7642 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
7643 handleApplyDefaultProxy(null != newDefaultNetwork
7644 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7645 updateTcpBufferSizes(null != newDefaultNetwork
7646 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
7647 notifyIfacesChangedForNetworkStats();
7648 }
7649
7650 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7651 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7652 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7653 try {
7654 if (VDBG) {
7655 log("Setting default network for " + nri
7656 + " using UIDs " + nri.getUids()
7657 + " with old network " + (oldDefaultNetwork != null
7658 ? oldDefaultNetwork.network().getNetId() : "null")
7659 + " and new network " + (newDefaultNetwork != null
7660 ? newDefaultNetwork.network().getNetId() : "null"));
7661 }
7662 if (nri.getUids().isEmpty()) {
7663 throw new IllegalStateException("makeDefaultForApps called without specifying"
7664 + " any applications to set as the default." + nri);
7665 }
7666 if (null != newDefaultNetwork) {
7667 mNetd.networkAddUidRanges(
7668 newDefaultNetwork.network.getNetId(),
7669 toUidRangeStableParcels(nri.getUids()));
7670 }
7671 if (null != oldDefaultNetwork) {
7672 mNetd.networkRemoveUidRanges(
7673 oldDefaultNetwork.network.getNetId(),
7674 toUidRangeStableParcels(nri.getUids()));
7675 }
7676 } catch (RemoteException | ServiceSpecificException e) {
7677 loge("Exception setting app default network", e);
7678 }
7679 }
7680
7681 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7682 try {
7683 if (null != newDefaultNetwork) {
7684 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7685 } else {
7686 mNetd.networkClearDefault();
7687 }
7688 } catch (RemoteException | ServiceSpecificException e) {
7689 loge("Exception setting default network :" + e);
7690 }
7691 }
7692
7693 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
7694 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
7695 processNewlyLostListenRequests(nai);
7696 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7697 processNewlySatisfiedListenRequests(nai);
7698 }
7699
7700 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
7701 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7702 if (nri.isMultilayerRequest()) {
7703 continue;
7704 }
7705 final NetworkRequest nr = nri.mRequests.get(0);
7706 if (!nr.isListen()) continue;
7707 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
7708 nai.removeRequest(nr.requestId);
7709 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7710 }
7711 }
7712 }
7713
7714 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
7715 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7716 if (nri.isMultilayerRequest()) {
7717 continue;
7718 }
7719 final NetworkRequest nr = nri.mRequests.get(0);
7720 if (!nr.isListen()) continue;
7721 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7722 nai.addRequest(nr);
7723 notifyNetworkAvailable(nai, nri);
7724 }
7725 }
7726 }
7727
7728 // An accumulator class to gather the list of changes that result from a rematch.
7729 private static class NetworkReassignment {
7730 static class RequestReassignment {
7731 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
7732 @Nullable public final NetworkRequest mOldNetworkRequest;
7733 @Nullable public final NetworkRequest mNewNetworkRequest;
7734 @Nullable public final NetworkAgentInfo mOldNetwork;
7735 @Nullable public final NetworkAgentInfo mNewNetwork;
7736 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
7737 @Nullable final NetworkRequest oldNetworkRequest,
7738 @Nullable final NetworkRequest newNetworkRequest,
7739 @Nullable final NetworkAgentInfo oldNetwork,
7740 @Nullable final NetworkAgentInfo newNetwork) {
7741 mNetworkRequestInfo = networkRequestInfo;
7742 mOldNetworkRequest = oldNetworkRequest;
7743 mNewNetworkRequest = newNetworkRequest;
7744 mOldNetwork = oldNetwork;
7745 mNewNetwork = newNetwork;
7746 }
7747
7748 public String toString() {
7749 final NetworkRequest requestToShow = null != mNewNetworkRequest
7750 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7751 return requestToShow.requestId + " : "
7752 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7753 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
7754 }
7755 }
7756
7757 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
7758
7759 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
7760 return mReassignments;
7761 }
7762
7763 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
7764 if (Build.isDebuggable()) {
7765 // The code is never supposed to add two reassignments of the same request. Make
7766 // sure this stays true, but without imposing this expensive check on all
7767 // reassignments on all user devices.
7768 for (final RequestReassignment existing : mReassignments) {
7769 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
7770 throw new IllegalStateException("Trying to reassign ["
7771 + reassignment + "] but already have ["
7772 + existing + "]");
7773 }
7774 }
7775 }
7776 mReassignments.add(reassignment);
7777 }
7778
7779 // Will return null if this reassignment does not change the network assigned to
7780 // the passed request.
7781 @Nullable
7782 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
7783 for (final RequestReassignment event : getRequestReassignments()) {
7784 if (nri == event.mNetworkRequestInfo) return event;
7785 }
7786 return null;
7787 }
7788
7789 public String toString() {
7790 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7791 "NetReassign [" /* prefix */, "]" /* suffix */);
7792 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
7793 for (final RequestReassignment rr : getRequestReassignments()) {
7794 sj.add(rr.toString());
7795 }
7796 return sj.toString();
7797 }
7798
7799 public String debugString() {
7800 final StringBuilder sb = new StringBuilder();
7801 sb.append("NetworkReassignment :");
7802 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
7803 for (final RequestReassignment rr : getRequestReassignments()) {
7804 sb.append("\n ").append(rr);
7805 }
7806 return sb.append("\n").toString();
7807 }
7808 }
7809
7810 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
7811 @Nullable final NetworkRequest previousRequest,
7812 @Nullable final NetworkRequest newRequest,
7813 @Nullable final NetworkAgentInfo previousSatisfier,
7814 @Nullable final NetworkAgentInfo newSatisfier,
7815 final long now) {
7816 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
7817 if (VDBG) log("rematch for " + newSatisfier.toShortString());
7818 if (null != previousRequest && null != previousSatisfier) {
7819 if (VDBG || DDBG) {
7820 log(" accepting network in place of " + previousSatisfier.toShortString());
7821 }
7822 previousSatisfier.removeRequest(previousRequest.requestId);
7823 previousSatisfier.lingerRequest(previousRequest.requestId, now);
7824 } else {
7825 if (VDBG || DDBG) log(" accepting network in place of null");
7826 }
7827
7828 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7829 // and immediately satisfies a request then remove the timer. This will happen for
7830 // all networks except in the case of an underlying network for a VCN.
7831 if (newSatisfier.isNascent()) {
7832 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
7833 newSatisfier.unsetInactive();
7834 }
7835
7836 // if newSatisfier is not null, then newRequest may not be null.
7837 newSatisfier.unlingerRequest(newRequest.requestId);
7838 if (!newSatisfier.addRequest(newRequest)) {
7839 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
7840 + newRequest);
7841 }
7842 } else if (null != previousRequest && null != previousSatisfier) {
7843 if (DBG) {
7844 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
7845 + " request " + previousRequest.requestId);
7846 }
7847 previousSatisfier.removeRequest(previousRequest.requestId);
7848 }
7849 nri.setSatisfier(newSatisfier, newRequest);
7850 }
7851
7852 /**
7853 * This function is triggered when something can affect what network should satisfy what
7854 * request, and it computes the network reassignment from the passed collection of requests to
7855 * network match to the one that the system should now have. That data is encoded in an
7856 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
7857 * satisfier.
7858 *
7859 * After the reassignment is computed, it is applied to the state objects.
7860 *
7861 * @param networkRequests the nri objects to evaluate for possible network reassignment
7862 * @return NetworkReassignment listing of proposed network assignment changes
7863 */
7864 @NonNull
7865 private NetworkReassignment computeNetworkReassignment(
7866 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
7867 final NetworkReassignment changes = new NetworkReassignment();
7868
7869 // Gather the list of all relevant agents.
7870 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
7871 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
7872 if (!nai.everConnected) {
7873 continue;
7874 }
7875 nais.add(nai);
7876 }
7877
7878 for (final NetworkRequestInfo nri : networkRequests) {
7879 // Non-multilayer listen requests can be ignored.
7880 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
7881 continue;
7882 }
7883 NetworkAgentInfo bestNetwork = null;
7884 NetworkRequest bestRequest = null;
7885 for (final NetworkRequest req : nri.mRequests) {
7886 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
7887 // Stop evaluating as the highest possible priority request is satisfied.
7888 if (null != bestNetwork) {
7889 bestRequest = req;
7890 break;
7891 }
7892 }
7893 if (null == bestNetwork && isDefaultBlocked(nri)) {
7894 // Remove default networking if disallowed for managed default requests.
7895 bestNetwork = mNoServiceNetwork;
7896 }
7897 if (nri.getSatisfier() != bestNetwork) {
7898 // bestNetwork may be null if no network can satisfy this request.
7899 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
7900 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
7901 }
7902 }
7903 return changes;
7904 }
7905
7906 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
7907 return new HashSet<>(mNetworkRequests.values());
7908 }
7909
7910 /**
7911 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
7912 * being disconnected.
7913 */
7914 private void rematchAllNetworksAndRequests() {
7915 rematchNetworksAndRequests(getNrisFromGlobalRequests());
7916 }
7917
7918 /**
7919 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
7920 * being disconnected.
7921 */
7922 private void rematchNetworksAndRequests(
7923 @NonNull final Set<NetworkRequestInfo> networkRequests) {
7924 ensureRunningOnConnectivityServiceThread();
7925 // TODO: This may be slow, and should be optimized.
7926 final long now = SystemClock.elapsedRealtime();
7927 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
7928 if (VDBG || DDBG) {
7929 log(changes.debugString());
7930 } else if (DBG) {
7931 log(changes.toString()); // Shorter form, only one line of log
7932 }
7933 applyNetworkReassignment(changes, now);
7934 issueNetworkNeeds();
7935 }
7936
7937 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
7938 final long now) {
7939 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
7940
7941 // Since most of the time there are only 0 or 1 background networks, it would probably
7942 // be more efficient to just use an ArrayList here. TODO : measure performance
7943 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
7944 for (final NetworkAgentInfo nai : nais) {
7945 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
7946 }
7947
7948 // First, update the lists of satisfied requests in the network agents. This is necessary
7949 // because some code later depends on this state to be correct, most prominently computing
7950 // the linger status.
7951 for (final NetworkReassignment.RequestReassignment event :
7952 changes.getRequestReassignments()) {
7953 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
7954 event.mOldNetworkRequest, event.mNewNetworkRequest,
7955 event.mOldNetwork, event.mNewNetwork,
7956 now);
7957 }
7958
7959 // Process default network changes if applicable.
7960 processDefaultNetworkChanges(changes);
7961
7962 // Notify requested networks are available after the default net is switched, but
7963 // before LegacyTypeTracker sends legacy broadcasts
7964 for (final NetworkReassignment.RequestReassignment event :
7965 changes.getRequestReassignments()) {
7966 if (null != event.mNewNetwork) {
7967 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
7968 } else {
7969 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
7970 ConnectivityManager.CALLBACK_LOST, 0);
7971 }
7972 }
7973
7974 // Update the inactivity state before processing listen callbacks, because the background
7975 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
7976 // just yet though, because they have to be sent after the listens are processed to keep
7977 // backward compatibility.
7978 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
7979 for (final NetworkAgentInfo nai : nais) {
7980 // Rematching may have altered the inactivity state of some networks, so update all
7981 // inactivity timers. updateInactivityState reads the state from the network agent
7982 // and does nothing if the state has not changed : the source of truth is controlled
7983 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
7984 // have been called while rematching the individual networks above.
7985 if (updateInactivityState(nai, now)) {
7986 inactiveNetworks.add(nai);
7987 }
7988 }
7989
7990 for (final NetworkAgentInfo nai : nais) {
7991 if (!nai.everConnected) continue;
7992 final boolean oldBackground = oldBgNetworks.contains(nai);
7993 // Process listen requests and update capabilities if the background state has
7994 // changed for this network. For consistency with previous behavior, send onLost
7995 // callbacks before onAvailable.
7996 processNewlyLostListenRequests(nai);
7997 if (oldBackground != nai.isBackgroundNetwork()) {
7998 applyBackgroundChangeForRematch(nai);
7999 }
8000 processNewlySatisfiedListenRequests(nai);
8001 }
8002
8003 for (final NetworkAgentInfo nai : inactiveNetworks) {
8004 // For nascent networks, if connecting with no foreground request, skip broadcasting
8005 // LOSING for backward compatibility. This is typical when mobile data connected while
8006 // wifi connected with mobile data always-on enabled.
8007 if (nai.isNascent()) continue;
8008 notifyNetworkLosing(nai, now);
8009 }
8010
8011 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
8012
8013 // Tear down all unneeded networks.
8014 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8015 if (unneeded(nai, UnneededFor.TEARDOWN)) {
8016 if (nai.getInactivityExpiry() > 0) {
8017 // This network has active linger timers and no requests, but is not
8018 // lingering. Linger it.
8019 //
8020 // One way (the only way?) this can happen if this network is unvalidated
8021 // and became unneeded due to another network improving its score to the
8022 // point where this network will no longer be able to satisfy any requests
8023 // even if it validates.
8024 if (updateInactivityState(nai, now)) {
8025 notifyNetworkLosing(nai, now);
8026 }
8027 } else {
8028 if (DBG) log("Reaping " + nai.toShortString());
8029 teardownUnneededNetwork(nai);
8030 }
8031 }
8032 }
8033 }
8034
8035 /**
8036 * Apply a change in background state resulting from rematching networks with requests.
8037 *
8038 * During rematch, a network may change background states by starting to satisfy or stopping
8039 * to satisfy a foreground request. Listens don't count for this. When a network changes
8040 * background states, its capabilities need to be updated and callbacks fired for the
8041 * capability change.
8042 *
8043 * @param nai The network that changed background states
8044 */
8045 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8046 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8047 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8048 updateNetworkPermissions(nai, newNc);
8049 nai.getAndSetNetworkCapabilities(newNc);
8050 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8051 }
8052
8053 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
8054 @NonNull final NetworkReassignment changes,
8055 @NonNull final Collection<NetworkAgentInfo> nais) {
8056 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8057 changes.getReassignment(mDefaultRequest);
8058 final NetworkAgentInfo oldDefaultNetwork =
8059 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8060 final NetworkAgentInfo newDefaultNetwork =
8061 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
8062
8063 if (oldDefaultNetwork != newDefaultNetwork) {
8064 // Maintain the illusion : since the legacy API only understands one network at a time,
8065 // if the default network changed, apps should see a disconnected broadcast for the
8066 // old default network before they see a connected broadcast for the new one.
8067 if (oldDefaultNetwork != null) {
8068 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8069 oldDefaultNetwork, true);
8070 }
8071 if (newDefaultNetwork != null) {
8072 // The new default network can be newly null if and only if the old default
8073 // network doesn't satisfy the default request any more because it lost a
8074 // capability.
8075 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
8076 mLegacyTypeTracker.add(
8077 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
8078 }
8079 }
8080
8081 // Now that all the callbacks have been sent, send the legacy network broadcasts
8082 // as needed. This is necessary so that legacy requests correctly bind dns
8083 // requests to this network. The legacy users are listening for this broadcast
8084 // and will generally do a dns request so they can ensureRouteToHost and if
8085 // they do that before the callbacks happen they'll use the default network.
8086 //
8087 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8088 // callbacks, but if apps can receive the broadcast before the callback, they still might
8089 // have an inconsistent view of networking.
8090 //
8091 // This *does* introduce a race where if the user uses the new api
8092 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8093 // they may get old info. Reverse this after the old startUsing api is removed.
8094 // This is on top of the multiple intent sequencing referenced in the todo above.
8095 for (NetworkAgentInfo nai : nais) {
8096 if (nai.everConnected) {
8097 addNetworkToLegacyTypeTracker(nai);
8098 }
8099 }
8100 }
8101
8102 private void issueNetworkNeeds() {
8103 ensureRunningOnConnectivityServiceThread();
8104 for (final NetworkOfferInfo noi : mNetworkOffers) {
8105 issueNetworkNeeds(noi);
8106 }
8107 }
8108
8109 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8110 ensureRunningOnConnectivityServiceThread();
8111 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8112 informOffer(nri, noi.offer, mNetworkRanker);
8113 }
8114 }
8115
8116 /**
8117 * Inform a NetworkOffer about any new situation of a request.
8118 *
8119 * This function handles updates to offers. A number of events may happen that require
8120 * updating the registrant for this offer about the situation :
8121 * • The offer itself was updated. This may lead the offer to no longer being able
8122 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8123 * or conversely being strengthened enough to beat the satisfier (and therefore
8124 * start being needed)
8125 * • The network satisfying a request changed (including cases where the request
8126 * starts or stops being satisfied). The new network may be a stronger or weaker
8127 * match than the old one, possibly affecting whether the offer is needed.
8128 * • The network satisfying a request updated their score. This may lead the offer
8129 * to no longer be able to beat it if the current satisfier got better, or
8130 * conversely start being a good choice if the current satisfier got weaker.
8131 *
8132 * @param nri The request
8133 * @param offer The offer. This may be an updated offer.
8134 */
8135 private static void informOffer(@NonNull NetworkRequestInfo nri,
8136 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8137 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8138 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
8139
8140 // Multi-layer requests have a currently active request, the one being satisfied.
8141 // Since the system will try to bring up a better network than is currently satisfying
8142 // the request, NetworkProviders need to be told the offers matching the requests *above*
8143 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8144 // not needed, and the offer is needed for the active request iff the offer can beat
8145 // the satisfier.
8146 // For non-multilayer requests, the logic above gracefully degenerates to only the
8147 // last case.
8148 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8149 // providers that the offer is needed for this request, until the active request is found.
8150 // In a second phase, deal with the currently active request. In a third phase, inform
8151 // the providers that offer is unneeded for the remaining requests.
8152
8153 // First phase : inform providers of all requests above the active request.
8154 int i;
8155 for (i = 0; nri.mRequests.size() > i; ++i) {
8156 final NetworkRequest request = nri.mRequests.get(i);
8157 if (activeRequest == request) break; // Found the active request : go to phase 2
8158 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8159 // Since this request is higher-priority than the one currently satisfied, if the
8160 // offer can satisfy it, the provider should try and bring up the network for sure ;
8161 // no need to even ask the ranker – an offer that can satisfy is always better than
8162 // no network. Hence tell the provider so unless it already knew.
8163 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8164 offer.onNetworkNeeded(request);
8165 }
8166 }
8167
8168 // Second phase : deal with the active request (if any)
8169 if (null != activeRequest && activeRequest.isRequest()) {
8170 final boolean oldNeeded = offer.neededFor(activeRequest);
8171 // An offer is needed if it is currently served by this provider or if this offer
8172 // can beat the current satisfier.
8173 final boolean currentlyServing = satisfier != null
8174 && satisfier.factorySerialNumber == offer.providerId;
8175 final boolean newNeeded = (currentlyServing
8176 || (activeRequest.canBeSatisfiedBy(offer.caps)
8177 && networkRanker.mightBeat(activeRequest, satisfier, offer)));
8178 if (newNeeded != oldNeeded) {
8179 if (newNeeded) {
8180 offer.onNetworkNeeded(activeRequest);
8181 } else {
8182 // The offer used to be able to beat the satisfier. Now it can't.
8183 offer.onNetworkUnneeded(activeRequest);
8184 }
8185 }
8186 }
8187
8188 // Third phase : inform the providers that the offer isn't needed for any request
8189 // below the active one.
8190 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8191 final NetworkRequest request = nri.mRequests.get(i);
8192 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8193 // Since this request is lower-priority than the one currently satisfied, if the
8194 // offer can satisfy it, the provider should not try and bring up the network.
8195 // Hence tell the provider so unless it already knew.
8196 if (offer.neededFor(request)) {
8197 offer.onNetworkUnneeded(request);
8198 }
8199 }
8200 }
8201
8202 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8203 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8204 NetworkRequest nr = nai.requestAt(i);
8205 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8206 // legacy type tracker filters out repeat adds
8207 mLegacyTypeTracker.add(nr.legacyType, nai);
8208 }
8209 }
8210
8211 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
8212 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
8213 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8214 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8215 if (nai.isVPN()) {
8216 mLegacyTypeTracker.add(TYPE_VPN, nai);
8217 }
8218 }
8219
8220 private void updateInetCondition(NetworkAgentInfo nai) {
8221 // Don't bother updating until we've graduated to validated at least once.
8222 if (!nai.everValidated) return;
8223 // For now only update icons for the default connection.
8224 // TODO: Update WiFi and cellular icons separately. b/17237507
8225 if (!isDefaultNetwork(nai)) return;
8226
8227 int newInetCondition = nai.lastValidated ? 100 : 0;
8228 // Don't repeat publish.
8229 if (newInetCondition == mDefaultInetConditionPublished) return;
8230
8231 mDefaultInetConditionPublished = newInetCondition;
8232 sendInetConditionBroadcast(nai.networkInfo);
8233 }
8234
8235 @NonNull
8236 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8237 final NetworkInfo newInfo = new NetworkInfo(info);
8238 // The suspended and roaming bits are managed in NetworkCapabilities.
8239 final boolean suspended =
8240 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8241 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8242 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8243 // state. This is because the network could have been suspended before connecting,
8244 // or it could be disconnecting while being suspended, and in both these cases
8245 // the state should not be overridden. Note that the only detailed state that
8246 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8247 // worry about multiple different substates of CONNECTED.
8248 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8249 info.getExtraInfo());
8250 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8251 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8252 // network agent is created, then goes to suspended, then goes out of suspended without
8253 // ever setting connected. Check if network agent is ever connected to update the state.
8254 newInfo.setDetailedState(nai.everConnected
8255 ? NetworkInfo.DetailedState.CONNECTED
8256 : NetworkInfo.DetailedState.CONNECTING,
8257 info.getReason(),
8258 info.getExtraInfo());
8259 }
8260 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
8261 return newInfo;
8262 }
8263
8264 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8265 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8266
8267 final NetworkInfo.State state = newInfo.getState();
8268 NetworkInfo oldInfo = null;
8269 synchronized (networkAgent) {
8270 oldInfo = networkAgent.networkInfo;
8271 networkAgent.networkInfo = newInfo;
8272 }
8273
8274 if (DBG) {
8275 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8276 + oldInfo.getState() + " to " + state);
8277 }
8278
8279 if (!networkAgent.created
8280 && (state == NetworkInfo.State.CONNECTED
8281 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
8282
8283 // A network that has just connected has zero requests and is thus a foreground network.
8284 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8285
8286 if (!createNativeNetwork(networkAgent)) return;
8287 if (networkAgent.supportsUnderlyingNetworks()) {
8288 // Initialize the network's capabilities to their starting values according to the
8289 // underlying networks. This ensures that the capabilities are correct before
8290 // anything happens to the network.
8291 updateCapabilitiesForNetwork(networkAgent);
8292 }
8293 networkAgent.created = true;
8294 networkAgent.onNetworkCreated();
8295 }
8296
8297 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8298 networkAgent.everConnected = true;
8299
8300 // NetworkCapabilities need to be set before sending the private DNS config to
8301 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
8302 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8303
8304 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
8305 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8306 null);
8307
8308 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8309 // command must be sent after updating LinkProperties to maximize chances of
8310 // NetworkMonitor seeing the correct LinkProperties when starting.
8311 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
8312 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
8313 networkAgent.networkMonitor().setAcceptPartialConnectivity();
8314 }
8315 networkAgent.networkMonitor().notifyNetworkConnected(
8316 new LinkProperties(networkAgent.linkProperties,
8317 true /* parcelSensitiveFields */),
8318 networkAgent.networkCapabilities);
8319 scheduleUnvalidatedPrompt(networkAgent);
8320
8321 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8322 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8323 // capabilities, so it only needs to be done once on initial connect, not every time the
8324 // network's capabilities change. Note that we do this before rematching the network,
8325 // so we could decide to tear it down immediately afterwards. That's fine though - on
8326 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8327 // doing.
8328 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
8329
8330 // Before first rematching networks, put an inactivity timer without any request, this
8331 // allows {@code updateInactivityState} to update the state accordingly and prevent
8332 // tearing down for any {@code unneeded} evaluation in this period.
8333 // Note that the timer will not be rescheduled since the expiry time is
8334 // fixed after connection regardless of the network satisfying other requests or not.
8335 // But it will be removed as soon as the network satisfies a request for the first time.
8336 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8337 SystemClock.elapsedRealtime(), mNascentDelayMs);
8338 networkAgent.setInactive();
8339
8340 // Consider network even though it is not yet validated.
8341 rematchAllNetworksAndRequests();
8342
8343 // This has to happen after matching the requests, because callbacks are just requests.
8344 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
8345 } else if (state == NetworkInfo.State.DISCONNECTED) {
8346 networkAgent.disconnect();
8347 if (networkAgent.isVPN()) {
8348 updateUids(networkAgent, networkAgent.networkCapabilities, null);
8349 }
8350 disconnectAndDestroyNetwork(networkAgent);
8351 if (networkAgent.isVPN()) {
8352 // As the active or bound network changes for apps, broadcast the default proxy, as
8353 // apps may need to update their proxy data. This is called after disconnecting from
8354 // VPN to make sure we do not broadcast the old proxy data.
8355 // TODO(b/122649188): send the broadcast only to VPN users.
8356 mProxyTracker.sendProxyBroadcast();
8357 }
8358 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8359 state == NetworkInfo.State.SUSPENDED)) {
8360 mLegacyTypeTracker.update(networkAgent);
8361 }
8362 }
8363
8364 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
8365 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8366 nai.setScore(score);
8367 rematchAllNetworksAndRequests();
8368 }
8369
8370 // Notify only this one new request of the current state. Transfer all the
8371 // current state by calling NetworkCapabilities and LinkProperties callbacks
8372 // so that callers can be guaranteed to have as close to atomicity in state
8373 // transfer as can be supported by this current API.
8374 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
8375 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
8376 if (nri.mPendingIntent != null) {
8377 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8378 // Attempt no subsequent state pushes where intents are involved.
8379 return;
8380 }
8381
8382 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8383 final boolean metered = nai.networkCapabilities.isMetered();
8384 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8385 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8386 getBlockedState(blockedReasons, metered, vpnBlocked));
8387 }
8388
8389 // Notify the requests on this NAI that the network is now lingered.
8390 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
8391 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
8392 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8393 }
8394
8395 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8396 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8397 return vpnBlocked
8398 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8399 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8400 }
8401
8402 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8403 if (blockedReasons == BLOCKED_REASON_NONE) {
8404 mUidBlockedReasons.delete(uid);
8405 } else {
8406 mUidBlockedReasons.put(uid, blockedReasons);
8407 }
8408 }
8409
8410 /**
8411 * Notify of the blocked state apps with a registered callback matching a given NAI.
8412 *
8413 * Unlike other callbacks, blocked status is different between each individual uid. So for
8414 * any given nai, all requests need to be considered according to the uid who filed it.
8415 *
8416 * @param nai The target NetworkAgentInfo.
8417 * @param oldMetered True if the previous network capabilities were metered.
8418 * @param newMetered True if the current network capabilities are metered.
8419 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8420 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
8421 */
8422 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
8423 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8424 List<UidRange> newBlockedUidRanges) {
8425
8426 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8427 NetworkRequest nr = nai.requestAt(i);
8428 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8429
8430 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8431 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8432 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
8433 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
8434 : oldVpnBlocked;
8435
8436 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8437 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8438 if (oldBlockedState != newBlockedState) {
8439 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8440 newBlockedState);
8441 }
8442 }
8443 }
8444
8445 /**
8446 * Notify apps with a given UID of the new blocked state according to new uid state.
8447 * @param uid The uid for which the rules changed.
8448 * @param blockedReasons The reasons for why an uid is blocked.
8449 */
8450 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
8451 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8452 final boolean metered = nai.networkCapabilities.isMetered();
8453 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
8454
8455 final int oldBlockedState = getBlockedState(
8456 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8457 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8458 if (oldBlockedState == newBlockedState) {
8459 continue;
8460 }
8461 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8462 NetworkRequest nr = nai.requestAt(i);
8463 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8464 if (nri != null && nri.mAsUid == uid) {
8465 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8466 newBlockedState);
8467 }
8468 }
8469 }
8470 }
8471
8472 @VisibleForTesting
8473 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
8474 // The NetworkInfo we actually send out has no bearing on the real
8475 // state of affairs. For example, if the default connection is mobile,
8476 // and a request for HIPRI has just gone away, we need to pretend that
8477 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8478 // the state to DISCONNECTED, even though the network is of type MOBILE
8479 // and is still connected.
8480 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8481 info.setType(type);
8482 filterForLegacyLockdown(info);
8483 if (state != DetailedState.DISCONNECTED) {
8484 info.setDetailedState(state, null, info.getExtraInfo());
8485 sendConnectedBroadcast(info);
8486 } else {
8487 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
8488 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8489 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8490 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8491 if (info.isFailover()) {
8492 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8493 nai.networkInfo.setFailover(false);
8494 }
8495 if (info.getReason() != null) {
8496 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8497 }
8498 if (info.getExtraInfo() != null) {
8499 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8500 }
8501 NetworkAgentInfo newDefaultAgent = null;
8502 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
8503 newDefaultAgent = mDefaultRequest.getSatisfier();
8504 if (newDefaultAgent != null) {
8505 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8506 newDefaultAgent.networkInfo);
8507 } else {
8508 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8509 }
8510 }
8511 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8512 mDefaultInetConditionPublished);
8513 sendStickyBroadcast(intent);
8514 if (newDefaultAgent != null) {
8515 sendConnectedBroadcast(newDefaultAgent.networkInfo);
8516 }
8517 }
8518 }
8519
8520 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
8521 if (VDBG || DDBG) {
8522 String notification = ConnectivityManager.getCallbackName(notifyType);
8523 log("notifyType " + notification + " for " + networkAgent.toShortString());
8524 }
8525 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8526 NetworkRequest nr = networkAgent.requestAt(i);
8527 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8528 if (VDBG) log(" sending notification for " + nr);
8529 if (nri.mPendingIntent == null) {
8530 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
8531 } else {
8532 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8533 }
8534 }
8535 }
8536
8537 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8538 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8539 }
8540
8541 /**
8542 * Returns the list of all interfaces that could be used by network traffic that does not
8543 * explicitly specify a network. This includes the default network, but also all VPNs that are
8544 * currently connected.
8545 *
8546 * Must be called on the handler thread.
8547 */
8548 @NonNull
8549 private ArrayList<Network> getDefaultNetworks() {
8550 ensureRunningOnConnectivityServiceThread();
8551 final ArrayList<Network> defaultNetworks = new ArrayList<>();
8552 final Set<Integer> activeNetIds = new ArraySet<>();
8553 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8554 if (nri.isBeingSatisfied()) {
8555 activeNetIds.add(nri.getSatisfier().network().netId);
8556 }
8557 }
8558 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8559 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
8560 defaultNetworks.add(nai.network);
8561 }
8562 }
8563 return defaultNetworks;
8564 }
8565
8566 /**
8567 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8568 * active iface's tracked properties has changed.
8569 */
8570 private void notifyIfacesChangedForNetworkStats() {
8571 ensureRunningOnConnectivityServiceThread();
8572 String activeIface = null;
8573 LinkProperties activeLinkProperties = getActiveLinkProperties();
8574 if (activeLinkProperties != null) {
8575 activeIface = activeLinkProperties.getInterfaceName();
8576 }
8577
8578 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
8579 try {
8580 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
8581 // TODO: Directly use NetworkStateSnapshot when feasible.
8582 for (final NetworkState state : getAllNetworkState()) {
8583 final NetworkStateSnapshot snapshot = new NetworkStateSnapshot(state.network,
8584 state.networkCapabilities, state.linkProperties, state.subscriberId,
8585 state.legacyNetworkType);
8586 snapshots.add(snapshot);
8587 }
8588 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8589 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
8590 } catch (Exception ignored) {
8591 }
8592 }
8593
8594 @Override
8595 public String getCaptivePortalServerUrl() {
8596 enforceNetworkStackOrSettingsPermission();
8597 String settingUrl = mResources.get().getString(
8598 R.string.config_networkCaptivePortalServerUrl);
8599
8600 if (!TextUtils.isEmpty(settingUrl)) {
8601 return settingUrl;
8602 }
8603
8604 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
8605 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
8606 if (!TextUtils.isEmpty(settingUrl)) {
8607 return settingUrl;
8608 }
8609
8610 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
8611 }
8612
8613 @Override
8614 public void startNattKeepalive(Network network, int intervalSeconds,
8615 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
8616 enforceKeepalivePermission();
8617 mKeepaliveTracker.startNattKeepalive(
8618 getNetworkAgentInfoForNetwork(network), null /* fd */,
8619 intervalSeconds, cb,
8620 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
8621 }
8622
8623 @Override
8624 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
8625 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
8626 String dstAddr) {
8627 try {
8628 final FileDescriptor fd = pfd.getFileDescriptor();
8629 mKeepaliveTracker.startNattKeepalive(
8630 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8631 intervalSeconds, cb,
8632 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8633 } finally {
8634 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8635 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8636 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8637 IoUtils.closeQuietly(pfd);
8638 }
8639 }
8640 }
8641
8642 @Override
8643 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
8644 ISocketKeepaliveCallback cb) {
8645 try {
8646 enforceKeepalivePermission();
8647 final FileDescriptor fd = pfd.getFileDescriptor();
8648 mKeepaliveTracker.startTcpKeepalive(
8649 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8650 } finally {
8651 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8652 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8653 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8654 IoUtils.closeQuietly(pfd);
8655 }
8656 }
8657 }
8658
8659 @Override
8660 public void stopKeepalive(Network network, int slot) {
8661 mHandler.sendMessage(mHandler.obtainMessage(
8662 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
8663 }
8664
8665 @Override
8666 public void factoryReset() {
8667 enforceSettingsPermission();
8668
8669 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
8670 return;
8671 }
8672
8673 final long token = Binder.clearCallingIdentity();
8674 try {
8675 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8676 ipMemoryStore.factoryReset();
8677 } finally {
8678 Binder.restoreCallingIdentity(token);
8679 }
8680
8681 // Turn airplane mode off
8682 setAirplaneMode(false);
8683
8684 // restore private DNS settings to default mode (opportunistic)
8685 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_PRIVATE_DNS)) {
8686 ConnectivitySettingsManager.setPrivateDnsMode(mContext, PRIVATE_DNS_MODE_OPPORTUNISTIC);
8687 }
8688
8689 Settings.Global.putString(mContext.getContentResolver(),
8690 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
8691 }
8692
8693 @Override
8694 public byte[] getNetworkWatchlistConfigHash() {
8695 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8696 if (nwm == null) {
8697 loge("Unable to get NetworkWatchlistManager");
8698 return null;
8699 }
8700 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8701 return nwm.getWatchlistConfigHash();
8702 }
8703
8704 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
8705 int[] transports = nai.networkCapabilities.getTransportTypes();
8706 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
8707 }
8708
8709 private static boolean toBool(int encodedBoolean) {
8710 return encodedBoolean != 0; // Only 0 means false.
8711 }
8712
8713 private static int encodeBool(boolean b) {
8714 return b ? 1 : 0;
8715 }
8716
8717 @Override
8718 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8719 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8720 @NonNull String[] args) {
8721 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8722 err.getFileDescriptor(), args);
8723 }
8724
8725 private class ShellCmd extends BasicShellCommandHandler {
8726 @Override
8727 public int onCommand(String cmd) {
8728 if (cmd == null) {
8729 return handleDefaultCommands(cmd);
8730 }
8731 final PrintWriter pw = getOutPrintWriter();
8732 try {
8733 switch (cmd) {
8734 case "airplane-mode":
8735 final String action = getNextArg();
8736 if ("enable".equals(action)) {
8737 setAirplaneMode(true);
8738 return 0;
8739 } else if ("disable".equals(action)) {
8740 setAirplaneMode(false);
8741 return 0;
8742 } else if (action == null) {
8743 final ContentResolver cr = mContext.getContentResolver();
8744 final int enabled = Settings.Global.getInt(cr,
8745 Settings.Global.AIRPLANE_MODE_ON);
8746 pw.println(enabled == 0 ? "disabled" : "enabled");
8747 return 0;
8748 } else {
8749 onHelp();
8750 return -1;
8751 }
8752 default:
8753 return handleDefaultCommands(cmd);
8754 }
8755 } catch (Exception e) {
8756 pw.println(e);
8757 }
8758 return -1;
8759 }
8760
8761 @Override
8762 public void onHelp() {
8763 PrintWriter pw = getOutPrintWriter();
8764 pw.println("Connectivity service commands:");
8765 pw.println(" help");
8766 pw.println(" Print this help text.");
8767 pw.println(" airplane-mode [enable|disable]");
8768 pw.println(" Turn airplane mode on or off.");
8769 pw.println(" airplane-mode");
8770 pw.println(" Get airplane mode.");
8771 }
8772 }
8773
8774 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
8775 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8776 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8777 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
8778 return ((VpnTransportInfo) ti).getType();
8779 }
8780
8781 /**
8782 * @param connectionInfo the connection to resolve.
8783 * @return {@code uid} if the connection is found and the app has permission to observe it
8784 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8785 * connection is not found.
8786 */
8787 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
8788 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8789 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8790 }
8791
8792 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
8793 connectionInfo.local, connectionInfo.remote);
8794
8795 if (uid == INVALID_UID) return uid; // Not found.
8796
8797 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8798 // VPN, if any, that applies to the UID that owns the connection.
8799 if (checkNetworkStackPermission()) return uid;
8800
8801 final NetworkAgentInfo vpn = getVpnForUid(uid);
8802 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
8803 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
8804 return INVALID_UID;
8805 }
8806
8807 return uid;
8808 }
8809
8810 /**
8811 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8812 *
8813 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8814 */
8815 @Override
8816 public IBinder startOrGetTestNetworkService() {
8817 synchronized (mTNSLock) {
8818 TestNetworkService.enforceTestNetworkPermissions(mContext);
8819
8820 if (mTNS == null) {
8821 mTNS = new TestNetworkService(mContext);
8822 }
8823
8824 return mTNS;
8825 }
8826 }
8827
8828 /**
8829 * Handler used for managing all Connectivity Diagnostics related functions.
8830 *
8831 * @see android.net.ConnectivityDiagnosticsManager
8832 *
8833 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8834 */
8835 @VisibleForTesting
8836 class ConnectivityDiagnosticsHandler extends Handler {
8837 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8838
8839 /**
8840 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8841 * android.net.ConnectivityDiagnosticsManager}.
8842 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8843 * NetworkRequestInfo to be registered
8844 */
8845 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
8846
8847 /**
8848 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
8849 * android.net.ConnectivityDiagnosticsManager}.
8850 * obj = the IConnectivityDiagnosticsCallback to be unregistered
8851 * arg1 = the uid of the caller
8852 */
8853 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
8854
8855 /**
8856 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
8857 * after processing {@link #EVENT_NETWORK_TESTED} events.
8858 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
8859 * NetworkMonitor.
8860 * data = PersistableBundle of extras passed from NetworkMonitor.
8861 *
8862 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
8863 */
8864 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
8865
8866 /**
8867 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
8868 * been detected on the network.
8869 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
8870 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
8871 * arg2 = NetID.
8872 * data = PersistableBundle of extras passed from NetworkMonitor.
8873 */
8874 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
8875
8876 /**
8877 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
8878 * the platform. This event will invoke {@link
8879 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
8880 * callbacks.
8881 * obj = Network that was reported on
8882 * arg1 = boolint for the quality reported
8883 */
8884 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
8885
8886 private ConnectivityDiagnosticsHandler(Looper looper) {
8887 super(looper);
8888 }
8889
8890 @Override
8891 public void handleMessage(Message msg) {
8892 switch (msg.what) {
8893 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8894 handleRegisterConnectivityDiagnosticsCallback(
8895 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
8896 break;
8897 }
8898 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8899 handleUnregisterConnectivityDiagnosticsCallback(
8900 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
8901 break;
8902 }
8903 case EVENT_NETWORK_TESTED: {
8904 final ConnectivityReportEvent reportEvent =
8905 (ConnectivityReportEvent) msg.obj;
8906
8907 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
8908 break;
8909 }
8910 case EVENT_DATA_STALL_SUSPECTED: {
8911 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
8912 final Pair<Long, PersistableBundle> arg =
8913 (Pair<Long, PersistableBundle>) msg.obj;
8914 if (nai == null) break;
8915
8916 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
8917 break;
8918 }
8919 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
8920 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
8921 break;
8922 }
8923 default: {
8924 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
8925 }
8926 }
8927 }
8928 }
8929
8930 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
8931 @VisibleForTesting
8932 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
8933 @NonNull private final IConnectivityDiagnosticsCallback mCb;
8934 @NonNull private final NetworkRequestInfo mRequestInfo;
8935 @NonNull private final String mCallingPackageName;
8936
8937 @VisibleForTesting
8938 ConnectivityDiagnosticsCallbackInfo(
8939 @NonNull IConnectivityDiagnosticsCallback cb,
8940 @NonNull NetworkRequestInfo nri,
8941 @NonNull String callingPackageName) {
8942 mCb = cb;
8943 mRequestInfo = nri;
8944 mCallingPackageName = callingPackageName;
8945 }
8946
8947 @Override
8948 public void binderDied() {
8949 log("ConnectivityDiagnosticsCallback IBinder died.");
8950 unregisterConnectivityDiagnosticsCallback(mCb);
8951 }
8952 }
8953
8954 /**
8955 * Class used for sending information from {@link
8956 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
8957 */
8958 private static class NetworkTestedResults {
8959 private final int mNetId;
8960 private final int mTestResult;
8961 private final long mTimestampMillis;
8962 @Nullable private final String mRedirectUrl;
8963
8964 private NetworkTestedResults(
8965 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
8966 mNetId = netId;
8967 mTestResult = testResult;
8968 mTimestampMillis = timestampMillis;
8969 mRedirectUrl = redirectUrl;
8970 }
8971 }
8972
8973 /**
8974 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
8975 * ConnectivityDiagnosticsHandler}.
8976 */
8977 private static class ConnectivityReportEvent {
8978 private final long mTimestampMillis;
8979 @NonNull private final NetworkAgentInfo mNai;
8980 private final PersistableBundle mExtras;
8981
8982 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
8983 PersistableBundle p) {
8984 mTimestampMillis = timestampMillis;
8985 mNai = nai;
8986 mExtras = p;
8987 }
8988 }
8989
8990 private void handleRegisterConnectivityDiagnosticsCallback(
8991 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
8992 ensureRunningOnConnectivityServiceThread();
8993
8994 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
8995 final IBinder iCb = cb.asBinder();
8996 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
8997
8998 // Connectivity Diagnostics are meant to be used with a single network request. It would be
8999 // confusing for these networks to change when an NRI is satisfied in another layer.
9000 if (nri.isMultilayerRequest()) {
9001 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9002 + "network requests.");
9003 }
9004
9005 // This means that the client registered the same callback multiple times. Do
9006 // not override the previous entry, and exit silently.
9007 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
9008 if (VDBG) log("Diagnostics callback is already registered");
9009
9010 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9011 // incremented when the NetworkRequestInfo is created as part of
9012 // enforceRequestCountLimit().
9013 nri.decrementRequestCount();
9014 return;
9015 }
9016
9017 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
9018
9019 try {
9020 iCb.linkToDeath(cbInfo, 0);
9021 } catch (RemoteException e) {
9022 cbInfo.binderDied();
9023 return;
9024 }
9025
9026 // Once registered, provide ConnectivityReports for matching Networks
9027 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9028 synchronized (mNetworkForNetId) {
9029 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9030 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
9031 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9032 if (nai.satisfies(nri.mRequests.get(0))) {
9033 matchingNetworks.add(nai);
9034 }
9035 }
9036 }
9037 for (final NetworkAgentInfo nai : matchingNetworks) {
9038 final ConnectivityReport report = nai.getConnectivityReport();
9039 if (report == null) {
9040 continue;
9041 }
9042 if (!checkConnectivityDiagnosticsPermissions(
9043 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9044 continue;
9045 }
9046
9047 try {
9048 cb.onConnectivityReportAvailable(report);
9049 } catch (RemoteException e) {
9050 // Exception while sending the ConnectivityReport. Move on to the next network.
9051 }
9052 }
9053 }
9054
9055 private void handleUnregisterConnectivityDiagnosticsCallback(
9056 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9057 ensureRunningOnConnectivityServiceThread();
9058 final IBinder iCb = cb.asBinder();
9059
9060 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9061 mConnectivityDiagnosticsCallbacks.remove(iCb);
9062 if (cbInfo == null) {
9063 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9064 return;
9065 }
9066
9067 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9068
9069 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9070 // (if the Binder died)
9071 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9072 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
9073 return;
9074 }
9075
9076 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9077 // incremented when the NetworkRequestInfo is created as part of
9078 // enforceRequestCountLimit().
9079 nri.decrementRequestCount();
9080
9081 iCb.unlinkToDeath(cbInfo, 0);
9082 }
9083
9084 private void handleNetworkTestedWithExtras(
9085 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9086 final NetworkAgentInfo nai = reportEvent.mNai;
9087 final NetworkCapabilities networkCapabilities =
9088 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9089 final ConnectivityReport report =
9090 new ConnectivityReport(
9091 reportEvent.mNai.network,
9092 reportEvent.mTimestampMillis,
9093 nai.linkProperties,
9094 networkCapabilities,
9095 extras);
9096 nai.setConnectivityReport(report);
9097 final List<IConnectivityDiagnosticsCallback> results =
9098 getMatchingPermissionedCallbacks(nai);
9099 for (final IConnectivityDiagnosticsCallback cb : results) {
9100 try {
9101 cb.onConnectivityReportAvailable(report);
9102 } catch (RemoteException ex) {
9103 loge("Error invoking onConnectivityReport", ex);
9104 }
9105 }
9106 }
9107
9108 private void handleDataStallSuspected(
9109 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9110 @NonNull PersistableBundle extras) {
9111 final NetworkCapabilities networkCapabilities =
9112 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9113 final DataStallReport report =
9114 new DataStallReport(
9115 nai.network,
9116 timestampMillis,
9117 detectionMethod,
9118 nai.linkProperties,
9119 networkCapabilities,
9120 extras);
9121 final List<IConnectivityDiagnosticsCallback> results =
9122 getMatchingPermissionedCallbacks(nai);
9123 for (final IConnectivityDiagnosticsCallback cb : results) {
9124 try {
9125 cb.onDataStallSuspected(report);
9126 } catch (RemoteException ex) {
9127 loge("Error invoking onDataStallSuspected", ex);
9128 }
9129 }
9130 }
9131
9132 private void handleNetworkConnectivityReported(
9133 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9134 final List<IConnectivityDiagnosticsCallback> results =
9135 getMatchingPermissionedCallbacks(nai);
9136 for (final IConnectivityDiagnosticsCallback cb : results) {
9137 try {
9138 cb.onNetworkConnectivityReported(nai.network, connectivity);
9139 } catch (RemoteException ex) {
9140 loge("Error invoking onNetworkConnectivityReported", ex);
9141 }
9142 }
9143 }
9144
9145 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
9146 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9147 NetworkCapabilities.REDACT_ALL);
9148 sanitized.setUids(null);
9149 sanitized.setAdministratorUids(new int[0]);
9150 sanitized.setOwnerUid(Process.INVALID_UID);
9151 return sanitized;
9152 }
9153
9154 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9155 @NonNull NetworkAgentInfo nai) {
9156 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
9157 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
9158 mConnectivityDiagnosticsCallbacks.entrySet()) {
9159 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9160 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9161 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9162 if (nai.satisfies(nri.mRequests.get(0))) {
9163 if (checkConnectivityDiagnosticsPermissions(
9164 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9165 results.add(entry.getValue().mCb);
9166 }
9167 }
9168 }
9169 return results;
9170 }
9171
9172 @VisibleForTesting
9173 boolean checkConnectivityDiagnosticsPermissions(
9174 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9175 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9176 return true;
9177 }
9178
9179 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9180 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9181 // call in a try-catch.
9182 try {
9183 if (!mLocationPermissionChecker.checkLocationPermission(
9184 callbackPackageName, null /* featureId */, callbackUid, null /* message */)) {
9185 return false;
9186 }
9187 } catch (SecurityException e) {
9188 return false;
9189 }
9190
9191 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
9192 if (virtual.supportsUnderlyingNetworks()
9193 && virtual.networkCapabilities.getOwnerUid() == callbackUid
9194 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, nai.network)) {
9195 return true;
9196 }
9197 }
9198
9199 // Administrator UIDs also contains the Owner UID
9200 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9201 return CollectionUtils.contains(administratorUids, callbackUid);
9202 }
9203
9204 @Override
9205 public void registerConnectivityDiagnosticsCallback(
9206 @NonNull IConnectivityDiagnosticsCallback callback,
9207 @NonNull NetworkRequest request,
9208 @NonNull String callingPackageName) {
9209 if (request.legacyType != TYPE_NONE) {
9210 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9211 + " Please use NetworkCapabilities instead.");
9212 }
9213 final int callingUid = mDeps.getCallingUid();
9214 mAppOpsManager.checkPackage(callingUid, callingPackageName);
9215
9216 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9217 // and administrator uids to be safe.
9218 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
9219 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
9220
9221 final NetworkRequest requestWithId =
9222 new NetworkRequest(
9223 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9224
9225 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9226 //
9227 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9228 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9229 // callback's binder death.
9230 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
9231 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9232 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
9233
9234 mConnectivityDiagnosticsHandler.sendMessage(
9235 mConnectivityDiagnosticsHandler.obtainMessage(
9236 ConnectivityDiagnosticsHandler
9237 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9238 cbInfo));
9239 }
9240
9241 @Override
9242 public void unregisterConnectivityDiagnosticsCallback(
9243 @NonNull IConnectivityDiagnosticsCallback callback) {
9244 Objects.requireNonNull(callback, "callback must be non-null");
9245 mConnectivityDiagnosticsHandler.sendMessage(
9246 mConnectivityDiagnosticsHandler.obtainMessage(
9247 ConnectivityDiagnosticsHandler
9248 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9249 mDeps.getCallingUid(),
9250 0,
9251 callback));
9252 }
9253
9254 @Override
9255 public void simulateDataStall(int detectionMethod, long timestampMillis,
9256 @NonNull Network network, @NonNull PersistableBundle extras) {
9257 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9258 android.Manifest.permission.NETWORK_STACK);
9259 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9260 if (!nc.hasTransport(TRANSPORT_TEST)) {
9261 throw new SecurityException("Data Stall simluation is only possible for test networks");
9262 }
9263
9264 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
9265 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
9266 throw new SecurityException("Data Stall simulation is only possible for network "
9267 + "creators");
9268 }
9269
9270 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9271 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9272 // Data Stall information as a DataStallReportParcelable and passing to
9273 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9274 // still passed to ConnectivityDiagnostics (with new detection methods masked).
9275 final DataStallReportParcelable p = new DataStallReportParcelable();
9276 p.timestampMillis = timestampMillis;
9277 p.detectionMethod = detectionMethod;
9278
9279 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9280 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9281 }
9282 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9283 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9284 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9285 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9286 }
9287
9288 notifyDataStallSuspected(p, network.getNetId());
9289 }
9290
9291 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9292 @Override
9293 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
9294 long timestampNs, int uid) {
9295 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
9296 }
9297
9298 @Override
9299 public void onInterfaceLinkStateChanged(String iface, boolean up) {
9300 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9301 nai.clatd.interfaceLinkStateChanged(iface, up);
9302 }
9303 }
9304
9305 @Override
9306 public void onInterfaceRemoved(String iface) {
9307 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9308 nai.clatd.interfaceRemoved(iface);
9309 }
9310 }
9311 }
9312
9313 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9314
9315 /**
9316 * Class used for updating network activity tracking with netd and notify network activity
9317 * changes.
9318 */
9319 private static final class LegacyNetworkActivityTracker {
9320 private static final int NO_UID = -1;
9321 private final Context mContext;
9322 private final INetd mNetd;
9323 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9324 new RemoteCallbackList<>();
9325 // Indicate the current system default network activity is active or not.
9326 @GuardedBy("mActiveIdleTimers")
9327 private boolean mNetworkActive;
9328 @GuardedBy("mActiveIdleTimers")
9329 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9330 private final Handler mHandler;
9331
9332 private class IdleTimerParams {
9333 public final int timeout;
9334 public final int transportType;
9335
9336 IdleTimerParams(int timeout, int transport) {
9337 this.timeout = timeout;
9338 this.transportType = transport;
9339 }
9340 }
9341
9342 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
9343 @NonNull INetd netd) {
9344 mContext = context;
9345 mNetd = netd;
9346 mHandler = handler;
9347 }
9348
9349 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9350 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9351 synchronized (mActiveIdleTimers) {
9352 mNetworkActive = active;
9353 // If there are no idle timers, it means that system is not monitoring
9354 // activity, so the system default network for those default network
9355 // unspecified apps is always considered active.
9356 //
9357 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9358 // any network activity change event. Whenever this event is received,
9359 // the mActiveIdleTimers should be always not empty. The legacy behavior
9360 // is no-op. Remove to refer to mNetworkActive only.
9361 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9362 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9363 }
9364 }
9365 }
9366
9367 // The network activity should only be updated from ConnectivityService handler thread
9368 // when mActiveIdleTimers lock is held.
9369 @GuardedBy("mActiveIdleTimers")
9370 private void reportNetworkActive() {
9371 final int length = mNetworkActivityListeners.beginBroadcast();
9372 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9373 try {
9374 for (int i = 0; i < length; i++) {
9375 try {
9376 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9377 } catch (RemoteException | RuntimeException e) {
9378 loge("Fail to send network activie to listener " + e);
9379 }
9380 }
9381 } finally {
9382 mNetworkActivityListeners.finishBroadcast();
9383 }
9384 }
9385
9386 @GuardedBy("mActiveIdleTimers")
9387 public void handleReportNetworkActivity() {
9388 synchronized (mActiveIdleTimers) {
9389 reportNetworkActive();
9390 }
9391 }
9392
9393 // This is deprecated and only to support legacy use cases.
9394 private int transportTypeToLegacyType(int type) {
9395 switch (type) {
9396 case NetworkCapabilities.TRANSPORT_CELLULAR:
9397 return TYPE_MOBILE;
9398 case NetworkCapabilities.TRANSPORT_WIFI:
9399 return TYPE_WIFI;
9400 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
9401 return TYPE_BLUETOOTH;
9402 case NetworkCapabilities.TRANSPORT_ETHERNET:
9403 return TYPE_ETHERNET;
9404 default:
9405 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9406 }
9407 return ConnectivityManager.TYPE_NONE;
9408 }
9409
9410 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9411 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9412 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9413 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9414 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9415 final long ident = Binder.clearCallingIdentity();
9416 try {
9417 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9418 RECEIVE_DATA_ACTIVITY_CHANGE,
9419 null /* resultReceiver */,
9420 null /* scheduler */,
9421 0 /* initialCode */,
9422 null /* initialData */,
9423 null /* initialExtra */);
9424 } finally {
9425 Binder.restoreCallingIdentity(ident);
9426 }
9427 }
9428
9429 /**
9430 * Setup data activity tracking for the given network.
9431 *
9432 * Every {@code setupDataActivityTracking} should be paired with a
9433 * {@link #removeDataActivityTracking} for cleanup.
9434 */
9435 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9436 final String iface = networkAgent.linkProperties.getInterfaceName();
9437
9438 final int timeout;
9439 final int type;
9440
9441 if (networkAgent.networkCapabilities.hasTransport(
9442 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9443 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9444 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
9445 10);
9446 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9447 } else if (networkAgent.networkCapabilities.hasTransport(
9448 NetworkCapabilities.TRANSPORT_WIFI)) {
9449 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9450 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
9451 15);
9452 type = NetworkCapabilities.TRANSPORT_WIFI;
9453 } else {
9454 return; // do not track any other networks
9455 }
9456
9457 updateRadioPowerState(true /* isActive */, type);
9458
9459 if (timeout > 0 && iface != null) {
9460 try {
9461 synchronized (mActiveIdleTimers) {
9462 // Networks start up.
9463 mNetworkActive = true;
9464 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9465 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9466 reportNetworkActive();
9467 }
9468 } catch (Exception e) {
9469 // You shall not crash!
9470 loge("Exception in setupDataActivityTracking " + e);
9471 }
9472 }
9473 }
9474
9475 /**
9476 * Remove data activity tracking when network disconnects.
9477 */
9478 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9479 final String iface = networkAgent.linkProperties.getInterfaceName();
9480 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9481
9482 if (iface == null) return;
9483
9484 final int type;
9485 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9486 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9487 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9488 type = NetworkCapabilities.TRANSPORT_WIFI;
9489 } else {
9490 return; // do not track any other networks
9491 }
9492
9493 try {
9494 updateRadioPowerState(false /* isActive */, type);
9495 synchronized (mActiveIdleTimers) {
9496 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9497 // The call fails silently if no idle timer setup for this interface
9498 mNetd.idletimerRemoveInterface(iface, params.timeout,
9499 Integer.toString(params.transportType));
9500 }
9501 } catch (Exception e) {
9502 // You shall not crash!
9503 loge("Exception in removeDataActivityTracking " + e);
9504 }
9505 }
9506
9507 /**
9508 * Update data activity tracking when network state is updated.
9509 */
9510 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9511 NetworkAgentInfo oldNetwork) {
9512 if (newNetwork != null) {
9513 setupDataActivityTracking(newNetwork);
9514 }
9515 if (oldNetwork != null) {
9516 removeDataActivityTracking(oldNetwork);
9517 }
9518 }
9519
9520 private void updateRadioPowerState(boolean isActive, int transportType) {
9521 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9522 switch (transportType) {
9523 case NetworkCapabilities.TRANSPORT_CELLULAR:
9524 bs.reportMobileRadioPowerState(isActive, NO_UID);
9525 break;
9526 case NetworkCapabilities.TRANSPORT_WIFI:
9527 bs.reportWifiRadioPowerState(isActive, NO_UID);
9528 break;
9529 default:
9530 logw("Untracked transport type:" + transportType);
9531 }
9532 }
9533
9534 public boolean isDefaultNetworkActive() {
9535 synchronized (mActiveIdleTimers) {
9536 // If there are no idle timers, it means that system is not monitoring activity,
9537 // so the default network is always considered active.
9538 //
9539 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9540 // tracking is disabled (negative idle timer value configured), or no active default
9541 // network. In the latter case, this reports active but it should report inactive.
9542 return mNetworkActive || mActiveIdleTimers.isEmpty();
9543 }
9544 }
9545
9546 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9547 mNetworkActivityListeners.register(l);
9548 }
9549
9550 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9551 mNetworkActivityListeners.unregister(l);
9552 }
9553
9554 public void dump(IndentingPrintWriter pw) {
9555 synchronized (mActiveIdleTimers) {
9556 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9557 pw.println("Idle timers:");
9558 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9559 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9560 final IdleTimerParams params = ent.getValue();
9561 pw.print(" timeout="); pw.print(params.timeout);
9562 pw.print(" type="); pw.println(params.transportType);
9563 }
9564 }
9565 }
9566 }
9567
9568 /**
9569 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9570 *
9571 * @param socketInfo the socket information
9572 * @param callback the callback to register
9573 */
9574 @Override
9575 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9576 @NonNull final IQosCallback callback) {
9577 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9578 if (nai == null || nai.networkCapabilities == null) {
9579 try {
9580 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9581 } catch (final RemoteException ex) {
9582 loge("registerQosCallbackInternal: RemoteException", ex);
9583 }
9584 return;
9585 }
9586 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9587 }
9588
9589 /**
9590 * Register a {@link IQosCallback} with base {@link QosFilter}.
9591 *
9592 * @param filter the filter to register
9593 * @param callback the callback to register
9594 * @param nai the agent information related to the filter's network
9595 */
9596 @VisibleForTesting
9597 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9598 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9599 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9600 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9601
9602 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9603 enforceConnectivityRestrictedNetworksPermission();
9604 }
9605 mQosCallbackTracker.registerCallback(callback, filter, nai);
9606 }
9607
9608 /**
9609 * Unregisters the given callback.
9610 *
9611 * @param callback the callback to unregister
9612 */
9613 @Override
9614 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
9615 Objects.requireNonNull(callback, "callback must be non-null");
9616 mQosCallbackTracker.unregisterCallback(callback);
9617 }
9618
9619 // Network preference per-profile and OEM network preferences can't be set at the same
9620 // time, because it is unclear what should happen if both preferences are active for
9621 // one given UID. To make it possible, the stack would have to clarify what would happen
9622 // in case both are active at the same time. The implementation may have to be adjusted
9623 // to implement the resulting rules. For example, a priority could be defined between them,
9624 // where the OEM preference would be considered less or more important than the enterprise
9625 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9626 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9627 // are set at the right level. Other solutions are possible, e.g. merging of the
9628 // preferences for the relevant UIDs.
9629 private static void throwConcurrentPreferenceException() {
9630 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9631 + "set OemNetworkPreference at the same time");
9632 }
9633
9634 /**
9635 * Request that a user profile is put by default on a network matching a given preference.
9636 *
9637 * See the documentation for the individual preferences for a description of the supported
9638 * behaviors.
9639 *
9640 * @param profile the profile concerned.
9641 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9642 * constants.
9643 * @param listener an optional listener to listen for completion of the operation.
9644 */
9645 @Override
9646 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9647 @ConnectivityManager.ProfileNetworkPreference final int preference,
9648 @Nullable final IOnCompleteListener listener) {
9649 Objects.requireNonNull(profile);
9650 PermissionUtils.enforceNetworkStackPermission(mContext);
9651 if (DBG) {
9652 log("setProfileNetworkPreference " + profile + " to " + preference);
9653 }
9654 if (profile.getIdentifier() < 0) {
9655 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9656 + "UserHandle.CURRENT not supported)");
9657 }
9658 final UserManager um = mContext.getSystemService(UserManager.class);
9659 if (!um.isManagedProfile(profile.getIdentifier())) {
9660 throw new IllegalArgumentException("Profile must be a managed profile");
9661 }
9662 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9663 // handler thread. However it is an immutable object, so reading the reference is
9664 // safe - it's just possible the value is slightly outdated. For the final check,
9665 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9666 // lot easier to understand, so opportunistically check it.
9667 if (!mOemNetworkPreferences.isEmpty()) {
9668 throwConcurrentPreferenceException();
9669 }
9670 final NetworkCapabilities nc;
9671 switch (preference) {
9672 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9673 nc = null;
9674 break;
9675 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9676 final UidRange uids = UidRange.createForUser(profile);
9677 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9678 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9679 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9680 break;
9681 default:
9682 throw new IllegalArgumentException(
9683 "Invalid preference in setProfileNetworkPreference");
9684 }
9685 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9686 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9687 }
9688
9689 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9690 @Nullable final NetworkCapabilities nc) {
9691 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9692 ensureRequestableCapabilities(nc);
9693 }
9694
9695 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9696 @NonNull final ProfileNetworkPreferences prefs) {
9697 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9698 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9699 // The NRI for a user should be comprised of two layers:
9700 // - The request for the capabilities
9701 // - The request for the default network, for fallback. Create an image of it to
9702 // have the correct UIDs in it (also a request can only be part of one NRI, because
9703 // of lookups in 1:1 associations like mNetworkRequests).
9704 // Note that denying a fallback can be implemented simply by not adding the second
9705 // request.
9706 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9707 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
9708 nrs.add(createDefaultInternetRequestForTransport(
9709 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9710 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
9711 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs);
9712 result.add(nri);
9713 }
9714 return result;
9715 }
9716
9717 private void handleSetProfileNetworkPreference(
9718 @NonNull final ProfileNetworkPreferences.Preference preference,
9719 @Nullable final IOnCompleteListener listener) {
9720 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9721 // particular because it's not clear what preference should win in case both apply
9722 // to the same app.
9723 // The binder call has already checked this, but as mOemNetworkPreferences is only
9724 // touched on the handler thread, it's theoretically not impossible that it has changed
9725 // since.
9726 if (!mOemNetworkPreferences.isEmpty()) {
9727 // This may happen on a device with an OEM preference set when a user is removed.
9728 // In this case, it's safe to ignore. In particular this happens in the tests.
9729 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
9730 return;
9731 }
9732
9733 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9734
9735 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
9736 mSystemNetworkRequestCounter.transact(
9737 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9738 () -> {
9739 final ArraySet<NetworkRequestInfo> nris =
9740 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9741 replaceDefaultNetworkRequestsForPreference(nris);
9742 });
9743 // Finally, rematch.
9744 rematchAllNetworksAndRequests();
9745
9746 if (null != listener) {
9747 try {
9748 listener.onComplete();
9749 } catch (RemoteException e) {
9750 loge("Listener for setProfileNetworkPreference has died");
9751 }
9752 }
9753 }
9754
9755 private void enforceAutomotiveDevice() {
9756 final boolean isAutomotiveDevice =
9757 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9758 if (!isAutomotiveDevice) {
9759 throw new UnsupportedOperationException(
9760 "setOemNetworkPreference() is only available on automotive devices.");
9761 }
9762 }
9763
9764 /**
9765 * Used by automotive devices to set the network preferences used to direct traffic at an
9766 * application level as per the given OemNetworkPreferences. An example use-case would be an
9767 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9768 * vehicle via a particular network.
9769 *
9770 * Calling this will overwrite the existing preference.
9771 *
9772 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
9773 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
9774 * to communicate completion of setOemNetworkPreference();
9775 */
9776 @Override
9777 public void setOemNetworkPreference(
9778 @NonNull final OemNetworkPreferences preference,
9779 @Nullable final IOnCompleteListener listener) {
9780
9781 enforceAutomotiveDevice();
9782 enforceOemNetworkPreferencesPermission();
9783
9784 if (!mProfileNetworkPreferences.isEmpty()) {
9785 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
9786 // handler thread. However it is an immutable object, so reading the reference is
9787 // safe - it's just possible the value is slightly outdated. For the final check,
9788 // see #handleSetOemPreference. But if this can be caught here it is a
9789 // lot easier to understand, so opportunistically check it.
9790 throwConcurrentPreferenceException();
9791 }
9792
9793 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9794 validateOemNetworkPreferences(preference);
9795 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
9796 new Pair<>(preference, listener)));
9797 }
9798
9799 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
9800 for (@OemNetworkPreferences.OemNetworkPreference final int pref
9801 : preference.getNetworkPreferences().values()) {
9802 if (OemNetworkPreferences.OEM_NETWORK_PREFERENCE_UNINITIALIZED == pref) {
9803 final String msg = "OEM_NETWORK_PREFERENCE_UNINITIALIZED is an invalid value.";
9804 throw new IllegalArgumentException(msg);
9805 }
9806 }
9807 }
9808
9809 private void handleSetOemNetworkPreference(
9810 @NonNull final OemNetworkPreferences preference,
9811 @Nullable final IOnCompleteListener listener) {
9812 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9813 if (DBG) {
9814 log("set OEM network preferences :" + preference.toString());
9815 }
9816 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9817 // particular because it's not clear what preference should win in case both apply
9818 // to the same app.
9819 // The binder call has already checked this, but as mOemNetworkPreferences is only
9820 // touched on the handler thread, it's theoretically not impossible that it has changed
9821 // since.
9822 if (!mProfileNetworkPreferences.isEmpty()) {
9823 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
9824 return;
9825 }
9826
9827 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
9828 final int uniquePreferenceCount = new ArraySet<>(
9829 preference.getNetworkPreferences().values()).size();
9830 mSystemNetworkRequestCounter.transact(
9831 mDeps.getCallingUid(), uniquePreferenceCount,
9832 () -> {
9833 final ArraySet<NetworkRequestInfo> nris =
9834 new OemNetworkRequestFactory()
9835 .createNrisFromOemNetworkPreferences(preference);
9836 replaceDefaultNetworkRequestsForPreference(nris);
9837 });
9838 mOemNetworkPreferences = preference;
9839
9840 if (null != listener) {
9841 try {
9842 listener.onComplete();
9843 } catch (RemoteException e) {
9844 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
9845 }
9846 }
9847 }
9848
9849 private void replaceDefaultNetworkRequestsForPreference(
9850 @NonNull final Set<NetworkRequestInfo> nris) {
9851 // Pass in a defensive copy as this collection will be updated on remove.
9852 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
9853 addPerAppDefaultNetworkRequests(nris);
9854 }
9855
9856 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
9857 ensureRunningOnConnectivityServiceThread();
9858 mDefaultNetworkRequests.addAll(nris);
9859 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
9860 getPerAppCallbackRequestsToUpdate();
9861 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
9862 mSystemNetworkRequestCounter.transact(
9863 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
9864 () -> {
9865 nrisToRegister.addAll(
9866 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
9867 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
9868 handleRegisterNetworkRequests(nrisToRegister);
9869 });
9870 }
9871
9872 /**
9873 * All current requests that are tracking the default network need to be assessed as to whether
9874 * or not the current set of per-application default requests will be changing their default
9875 * network. If so, those requests will need to be updated so that they will send callbacks for
9876 * default network changes at the appropriate time. Additionally, those requests tracking the
9877 * default that were previously updated by this flow will need to be reassessed.
9878 * @return the nris which will need to be updated.
9879 */
9880 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
9881 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
9882 // Get the distinct nris to check since for multilayer requests, it is possible to have the
9883 // same nri in the map's values for each of its NetworkRequest objects.
9884 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
9885 for (final NetworkRequestInfo nri : nris) {
9886 // Include this nri if it is currently being tracked.
9887 if (isPerAppTrackedNri(nri)) {
9888 defaultCallbackRequests.add(nri);
9889 continue;
9890 }
9891 // We only track callbacks for requests tracking the default.
9892 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
9893 continue;
9894 }
9895 // Include this nri if it will be tracked by the new per-app default requests.
9896 final boolean isNriGoingToBeTracked =
9897 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
9898 if (isNriGoingToBeTracked) {
9899 defaultCallbackRequests.add(nri);
9900 }
9901 }
9902 return defaultCallbackRequests;
9903 }
9904
9905 /**
9906 * Create nris for those network requests that are currently tracking the default network that
9907 * are being controlled by a per-application default.
9908 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
9909 * foundation when creating the nri. Important items include the calling uid's original
9910 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
9911 * requests are assumed to have already been validated as needing to be updated.
9912 * @return the Set of nris to use when registering network requests.
9913 */
9914 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
9915 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
9916 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
9917 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
9918 final NetworkRequestInfo trackingNri =
9919 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
9920
9921 // If this nri is not being tracked, the change it back to an untracked nri.
9922 if (trackingNri == mDefaultRequest) {
9923 callbackRequestsToRegister.add(new NetworkRequestInfo(
9924 callbackRequest,
9925 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
9926 continue;
9927 }
9928
9929 final NetworkRequest request = callbackRequest.mRequests.get(0);
9930 callbackRequestsToRegister.add(new NetworkRequestInfo(
9931 callbackRequest,
9932 copyNetworkRequestsForUid(
9933 trackingNri.mRequests, callbackRequest.mAsUid,
9934 callbackRequest.mUid, request.getRequestorPackageName())));
9935 }
9936 return callbackRequestsToRegister;
9937 }
9938
9939 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
9940 @NonNull final Set<UidRange> uids) {
9941 for (final NetworkRequest req : requests) {
9942 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
9943 }
9944 }
9945
9946 /**
9947 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
9948 */
9949 @VisibleForTesting
9950 final class OemNetworkRequestFactory {
9951 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
9952 @NonNull final OemNetworkPreferences preference) {
9953 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
9954 final SparseArray<Set<Integer>> uids =
9955 createUidsFromOemNetworkPreferences(preference);
9956 for (int i = 0; i < uids.size(); i++) {
9957 final int key = uids.keyAt(i);
9958 final Set<Integer> value = uids.valueAt(i);
9959 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
9960 // No need to add an nri without any requests.
9961 if (0 == nri.mRequests.size()) {
9962 continue;
9963 }
9964 nris.add(nri);
9965 }
9966
9967 return nris;
9968 }
9969
9970 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
9971 @NonNull final OemNetworkPreferences preference) {
9972 final SparseArray<Set<Integer>> uids = new SparseArray<>();
9973 final PackageManager pm = mContext.getPackageManager();
9974 final List<UserHandle> users =
9975 mContext.getSystemService(UserManager.class).getUserHandles(true);
9976 if (null == users || users.size() == 0) {
9977 if (VDBG || DDBG) {
9978 log("No users currently available for setting the OEM network preference.");
9979 }
9980 return uids;
9981 }
9982 for (final Map.Entry<String, Integer> entry :
9983 preference.getNetworkPreferences().entrySet()) {
9984 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
9985 try {
9986 final int uid = pm.getApplicationInfo(entry.getKey(), 0).uid;
9987 if (!uids.contains(pref)) {
9988 uids.put(pref, new ArraySet<>());
9989 }
9990 for (final UserHandle ui : users) {
9991 // Add the rules for all users as this policy is device wide.
9992 uids.get(pref).add(ui.getUid(uid));
9993 }
9994 } catch (PackageManager.NameNotFoundException e) {
9995 // Although this may seem like an error scenario, it is ok that uninstalled
9996 // packages are sent on a network preference as the system will watch for
9997 // package installations associated with this network preference and update
9998 // accordingly. This is done so as to minimize race conditions on app install.
9999 continue;
10000 }
10001 }
10002 return uids;
10003 }
10004
10005 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10006 @OemNetworkPreferences.OemNetworkPreference final int preference,
10007 @NonNull final Set<Integer> uids) {
10008 final List<NetworkRequest> requests = new ArrayList<>();
10009 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10010 switch (preference) {
10011 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10012 requests.add(createUnmeteredNetworkRequest());
10013 requests.add(createOemPaidNetworkRequest());
10014 requests.add(createDefaultInternetRequestForTransport(
10015 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10016 break;
10017 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10018 requests.add(createUnmeteredNetworkRequest());
10019 requests.add(createOemPaidNetworkRequest());
10020 break;
10021 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10022 requests.add(createOemPaidNetworkRequest());
10023 break;
10024 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10025 requests.add(createOemPrivateNetworkRequest());
10026 break;
10027 default:
10028 // This should never happen.
10029 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10030 + " called with invalid preference of " + preference);
10031 }
10032
10033 final ArraySet ranges = new ArraySet<Integer>();
10034 for (final int uid : uids) {
10035 ranges.add(new UidRange(uid, uid));
10036 }
10037 setNetworkRequestUids(requests, ranges);
10038 return new NetworkRequestInfo(Process.myUid(), requests);
10039 }
10040
10041 private NetworkRequest createUnmeteredNetworkRequest() {
10042 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10043 .addCapability(NET_CAPABILITY_NOT_METERED)
10044 .addCapability(NET_CAPABILITY_VALIDATED);
10045 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10046 }
10047
10048 private NetworkRequest createOemPaidNetworkRequest() {
10049 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10050 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10051 .addCapability(NET_CAPABILITY_OEM_PAID)
10052 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10053 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10054 }
10055
10056 private NetworkRequest createOemPrivateNetworkRequest() {
10057 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10058 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10059 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10060 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10061 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10062 }
10063
10064 private NetworkCapabilities createDefaultPerAppNetCap() {
10065 final NetworkCapabilities netCap = new NetworkCapabilities();
10066 netCap.addCapability(NET_CAPABILITY_INTERNET);
10067 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10068 return netCap;
10069 }
10070 }
10071}