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