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