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