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