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