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