blob: 2ad12a69b0db2f10e37106aa87e853ff2e344164 [file] [log] [blame]
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
20import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
24import static android.content.pm.PackageManager.PERMISSION_GRANTED;
25import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
33import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
35import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
36import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
37import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
38import static android.net.ConnectivityManager.TYPE_ETHERNET;
39import static android.net.ConnectivityManager.TYPE_MOBILE;
40import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
41import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
42import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
43import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
44import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
46import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
49import static android.net.ConnectivityManager.TYPE_NONE;
50import static android.net.ConnectivityManager.TYPE_PROXY;
51import static android.net.ConnectivityManager.TYPE_VPN;
52import static android.net.ConnectivityManager.TYPE_WIFI;
53import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
54import static android.net.ConnectivityManager.getNetworkTypeName;
55import static android.net.ConnectivityManager.isNetworkTypeValid;
56import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
57import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
58import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
59import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
60import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
61import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
62import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
63import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
64import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
65import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
66import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
67import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
68import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
69import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
70import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
71import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
72import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
73import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
75import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
76import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
77import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
78import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
79import static android.net.NetworkCapabilities.TRANSPORT_TEST;
80import static android.net.NetworkCapabilities.TRANSPORT_VPN;
81import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
82import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
83import static android.os.Process.INVALID_UID;
84import static android.os.Process.VPN_UID;
85import static android.system.OsConstants.IPPROTO_TCP;
86import static android.system.OsConstants.IPPROTO_UDP;
87
88import static java.util.Map.Entry;
89
90import android.Manifest;
91import android.annotation.NonNull;
92import android.annotation.Nullable;
93import android.app.AppOpsManager;
94import android.app.BroadcastOptions;
95import android.app.PendingIntent;
96import android.app.usage.NetworkStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.ContentResolver;
100import android.content.Context;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.pm.PackageManager;
104import android.database.ContentObserver;
105import android.net.CaptivePortal;
106import android.net.CaptivePortalData;
107import android.net.ConnectionInfo;
108import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
109import android.net.ConnectivityDiagnosticsManager.DataStallReport;
110import android.net.ConnectivityManager;
111import android.net.ConnectivityManager.BlockedReason;
112import android.net.ConnectivityManager.NetworkCallback;
Aaron Huangcff22942021-05-27 16:31:26 +0800113import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000114import android.net.ConnectivityResources;
115import android.net.ConnectivitySettingsManager;
116import android.net.DataStallReportParcelable;
117import android.net.DnsResolverServiceManager;
118import android.net.ICaptivePortal;
119import android.net.IConnectivityDiagnosticsCallback;
120import android.net.IConnectivityManager;
121import android.net.IDnsResolver;
122import android.net.INetd;
123import android.net.INetworkActivityListener;
124import android.net.INetworkAgent;
125import android.net.INetworkMonitor;
126import android.net.INetworkMonitorCallbacks;
127import android.net.INetworkOfferCallback;
128import android.net.IOnCompleteListener;
129import android.net.IQosCallback;
130import android.net.ISocketKeepaliveCallback;
131import android.net.InetAddresses;
132import android.net.IpMemoryStore;
133import android.net.IpPrefix;
134import android.net.LinkProperties;
135import android.net.MatchAllNetworkSpecifier;
136import android.net.NativeNetworkConfig;
137import android.net.NativeNetworkType;
138import android.net.NattSocketKeepalive;
139import android.net.Network;
140import android.net.NetworkAgent;
141import android.net.NetworkAgentConfig;
142import android.net.NetworkCapabilities;
143import android.net.NetworkInfo;
144import android.net.NetworkInfo.DetailedState;
145import android.net.NetworkMonitorManager;
146import android.net.NetworkPolicyManager;
147import android.net.NetworkPolicyManager.NetworkPolicyCallback;
148import android.net.NetworkProvider;
149import android.net.NetworkRequest;
150import android.net.NetworkScore;
151import android.net.NetworkSpecifier;
152import android.net.NetworkStack;
153import android.net.NetworkState;
154import android.net.NetworkStateSnapshot;
155import android.net.NetworkTestResultParcelable;
156import android.net.NetworkUtils;
157import android.net.NetworkWatchlistManager;
158import android.net.OemNetworkPreferences;
159import android.net.PrivateDnsConfigParcel;
160import android.net.ProxyInfo;
161import android.net.QosCallbackException;
162import android.net.QosFilter;
163import android.net.QosSocketFilter;
164import android.net.QosSocketInfo;
165import android.net.RouteInfo;
166import android.net.RouteInfoParcel;
167import android.net.SocketKeepalive;
168import android.net.TetheringManager;
169import android.net.TransportInfo;
170import android.net.UidRange;
171import android.net.UidRangeParcel;
172import android.net.UnderlyingNetworkInfo;
173import android.net.Uri;
174import android.net.VpnManager;
175import android.net.VpnTransportInfo;
176import android.net.metrics.IpConnectivityLog;
177import android.net.metrics.NetworkEvent;
178import android.net.netlink.InetDiagMessage;
179import android.net.networkstack.ModuleNetworkStackClient;
180import android.net.networkstack.NetworkStackClientBase;
181import android.net.resolv.aidl.DnsHealthEventParcel;
182import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
183import android.net.resolv.aidl.Nat64PrefixEventParcel;
184import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
185import android.net.shared.PrivateDnsConfig;
186import android.net.util.MultinetworkPolicyTracker;
187import android.os.BatteryStatsManager;
188import android.os.Binder;
189import android.os.Build;
190import android.os.Bundle;
191import android.os.Handler;
192import android.os.HandlerThread;
193import android.os.IBinder;
194import android.os.Looper;
195import android.os.Message;
196import android.os.Messenger;
197import android.os.ParcelFileDescriptor;
198import android.os.Parcelable;
199import android.os.PersistableBundle;
200import android.os.PowerManager;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ServiceSpecificException;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.UserHandle;
208import android.os.UserManager;
209import android.provider.Settings;
210import android.sysprop.NetworkProperties;
211import android.telephony.TelephonyManager;
212import android.text.TextUtils;
213import android.util.ArrayMap;
214import android.util.ArraySet;
215import android.util.LocalLog;
216import android.util.Log;
217import android.util.Pair;
218import android.util.SparseArray;
219import android.util.SparseIntArray;
220
221import com.android.connectivity.resources.R;
222import com.android.internal.annotations.GuardedBy;
223import com.android.internal.annotations.VisibleForTesting;
224import com.android.internal.util.IndentingPrintWriter;
225import com.android.internal.util.MessageUtils;
226import com.android.modules.utils.BasicShellCommandHandler;
227import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
228import com.android.net.module.util.CollectionUtils;
229import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
230import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
231import com.android.net.module.util.LocationPermissionChecker;
232import com.android.net.module.util.NetworkCapabilitiesUtils;
233import com.android.net.module.util.PermissionUtils;
234import com.android.server.connectivity.AutodestructReference;
235import com.android.server.connectivity.DnsManager;
236import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
237import com.android.server.connectivity.FullScore;
238import com.android.server.connectivity.KeepaliveTracker;
239import com.android.server.connectivity.LingerMonitor;
240import com.android.server.connectivity.MockableSystemProperties;
241import com.android.server.connectivity.NetworkAgentInfo;
242import com.android.server.connectivity.NetworkDiagnostics;
243import com.android.server.connectivity.NetworkNotificationManager;
244import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
245import com.android.server.connectivity.NetworkOffer;
246import com.android.server.connectivity.NetworkRanker;
247import com.android.server.connectivity.PermissionMonitor;
248import com.android.server.connectivity.ProfileNetworkPreferences;
249import com.android.server.connectivity.ProxyTracker;
250import com.android.server.connectivity.QosCallbackTracker;
251
252import libcore.io.IoUtils;
253
254import java.io.FileDescriptor;
255import java.io.PrintWriter;
256import java.net.Inet4Address;
257import java.net.InetAddress;
258import java.net.InetSocketAddress;
259import java.net.UnknownHostException;
260import java.util.ArrayList;
261import java.util.Arrays;
262import java.util.Collection;
263import java.util.Collections;
264import java.util.Comparator;
265import java.util.ConcurrentModificationException;
266import java.util.HashMap;
267import java.util.HashSet;
268import java.util.List;
269import java.util.Map;
270import java.util.Objects;
271import java.util.Set;
272import java.util.SortedSet;
273import java.util.StringJoiner;
274import java.util.TreeSet;
275import java.util.concurrent.atomic.AtomicInteger;
276
277/**
278 * @hide
279 */
280public class ConnectivityService extends IConnectivityManager.Stub
281 implements PendingIntent.OnFinished {
282 private static final String TAG = ConnectivityService.class.getSimpleName();
283
284 private static final String DIAG_ARG = "--diag";
285 public static final String SHORT_ARG = "--short";
286 private static final String NETWORK_ARG = "networks";
287 private static final String REQUEST_ARG = "requests";
288
289 private static final boolean DBG = true;
290 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
291 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
292
293 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
294
295 /**
296 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
297 * by OEMs for configuration purposes, as this value is overridden by
298 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
299 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
300 * (preferably via runtime resource overlays).
301 */
302 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
303 "http://connectivitycheck.gstatic.com/generate_204";
304
305 // TODO: create better separation between radio types and network types
306
307 // how long to wait before switching back to a radio's default network
308 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
309 // system property that can override the above value
310 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
311 "android.telephony.apn-restore";
312
313 // How long to wait before putting up a "This network doesn't have an Internet connection,
314 // connect anyway?" dialog after the user selects a network that doesn't validate.
315 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
316
317 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
318 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
319 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
320 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
321
322 // The maximum number of network request allowed per uid before an exception is thrown.
323 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
324
325 // The maximum number of network request allowed for system UIDs before an exception is thrown.
326 @VisibleForTesting
327 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
328
329 @VisibleForTesting
330 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
331 @VisibleForTesting
332 protected int mNascentDelayMs;
333
334 // How long to delay to removal of a pending intent based request.
335 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
336 private final int mReleasePendingIntentDelayMs;
337
338 private MockableSystemProperties mSystemProperties;
339
340 @VisibleForTesting
341 protected final PermissionMonitor mPermissionMonitor;
342
343 private final PerUidCounter mNetworkRequestCounter;
344 @VisibleForTesting
345 final PerUidCounter mSystemNetworkRequestCounter;
346
347 private volatile boolean mLockdownEnabled;
348
349 /**
350 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
351 * internal handler thread, they don't need a lock.
352 */
353 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
354
355 private final Context mContext;
356 private final ConnectivityResources mResources;
357 // The Context is created for UserHandle.ALL.
358 private final Context mUserAllContext;
359 private final Dependencies mDeps;
360 // 0 is full bad, 100 is full good
361 private int mDefaultInetConditionPublished = 0;
362
363 @VisibleForTesting
364 protected IDnsResolver mDnsResolver;
365 @VisibleForTesting
366 protected INetd mNetd;
367 private NetworkStatsManager mStatsManager;
368 private NetworkPolicyManager mPolicyManager;
369 private final NetdCallback mNetdCallback;
370
371 /**
372 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
373 * instances.
374 */
375 @GuardedBy("mTNSLock")
376 private TestNetworkService mTNS;
377
378 private final Object mTNSLock = new Object();
379
380 private String mCurrentTcpBufferSizes;
381
382 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
383 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
384
385 private enum ReapUnvalidatedNetworks {
386 // Tear down networks that have no chance (e.g. even if validated) of becoming
387 // the highest scoring network satisfying a NetworkRequest. This should be passed when
388 // all networks have been rematched against all NetworkRequests.
389 REAP,
390 // Don't reap networks. This should be passed when some networks have not yet been
391 // rematched against all NetworkRequests.
392 DONT_REAP
393 }
394
395 private enum UnneededFor {
396 LINGER, // Determine whether this network is unneeded and should be lingered.
397 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
398 }
399
400 /**
401 * used internally to clear a wakelock when transitioning
402 * from one net to another. Clear happens when we get a new
403 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
404 * after a timeout if no network is found (typically 1 min).
405 */
406 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
407
408 /**
409 * used internally to reload global proxy settings
410 */
411 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
412
413 /**
414 * PAC manager has received new port.
415 */
416 private static final int EVENT_PROXY_HAS_CHANGED = 16;
417
418 /**
419 * used internally when registering NetworkProviders
420 * obj = NetworkProviderInfo
421 */
422 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
423
424 /**
425 * used internally when registering NetworkAgents
426 * obj = Messenger
427 */
428 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
429
430 /**
431 * used to add a network request
432 * includes a NetworkRequestInfo
433 */
434 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
435
436 /**
437 * indicates a timeout period is over - check if we had a network yet or not
438 * and if not, call the timeout callback (but leave the request live until they
439 * cancel it.
440 * includes a NetworkRequestInfo
441 */
442 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
443
444 /**
445 * used to add a network listener - no request
446 * includes a NetworkRequestInfo
447 */
448 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
449
450 /**
451 * used to remove a network request, either a listener or a real request
452 * arg1 = UID of caller
453 * obj = NetworkRequest
454 */
455 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
456
457 /**
458 * used internally when registering NetworkProviders
459 * obj = Messenger
460 */
461 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
462
463 /**
464 * used internally to expire a wakelock when transitioning
465 * from one net to another. Expire happens when we fail to find
466 * a new network (typically after 1 minute) -
467 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
468 * a replacement network.
469 */
470 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
471
472 /**
473 * used to add a network request with a pending intent
474 * obj = NetworkRequestInfo
475 */
476 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
477
478 /**
479 * used to remove a pending intent and its associated network request.
480 * arg1 = UID of caller
481 * obj = PendingIntent
482 */
483 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
484
485 /**
486 * used to specify whether a network should be used even if unvalidated.
487 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
488 * arg2 = whether to remember this choice in the future (1 or 0)
489 * obj = network
490 */
491 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
492
493 /**
494 * used to ask the user to confirm a connection to an unvalidated network.
495 * obj = network
496 */
497 private static final int EVENT_PROMPT_UNVALIDATED = 29;
498
499 /**
500 * used internally to (re)configure always-on networks.
501 */
502 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
503
504 /**
505 * used to add a network listener with a pending intent
506 * obj = NetworkRequestInfo
507 */
508 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
509
510 /**
511 * used to specify whether a network should not be penalized when it becomes unvalidated.
512 */
513 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
514
515 /**
516 * used to trigger revalidation of a network.
517 */
518 private static final int EVENT_REVALIDATE_NETWORK = 36;
519
520 // Handle changes in Private DNS settings.
521 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
522
523 // Handle private DNS validation status updates.
524 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
525
526 /**
527 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
528 * been tested.
529 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
530 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
531 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
532 */
533 private static final int EVENT_NETWORK_TESTED = 41;
534
535 /**
536 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
537 * config was resolved.
538 * obj = PrivateDnsConfig
539 * arg2 = netid
540 */
541 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
542
543 /**
544 * Request ConnectivityService display provisioning notification.
545 * arg1 = Whether to make the notification visible.
546 * arg2 = NetID.
547 * obj = Intent to be launched when notification selected by user, null if !arg1.
548 */
549 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
550
551 /**
552 * Used to specify whether a network should be used even if connectivity is partial.
553 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
554 * false)
555 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
556 * obj = network
557 */
558 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
559
560 /**
561 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
562 * Both of the arguments are bitmasks, and the value of bits come from
563 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
564 * arg1 = A bitmask to describe which probes are completed.
565 * arg2 = A bitmask to describe which probes are successful.
566 */
567 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
568
569 /**
570 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
571 * arg1 = unused
572 * arg2 = netId
573 * obj = captive portal data
574 */
575 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
576
577 /**
578 * Used by setRequireVpnForUids.
579 * arg1 = whether the specified UID ranges are required to use a VPN.
580 * obj = Array of UidRange objects.
581 */
582 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
583
584 /**
585 * Used internally when setting the default networks for OemNetworkPreferences.
586 * obj = Pair<OemNetworkPreferences, listener>
587 */
588 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
589
590 /**
591 * Used to indicate the system default network becomes active.
592 */
593 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
594
595 /**
596 * Used internally when setting a network preference for a user profile.
597 * obj = Pair<ProfileNetworkPreference, Listener>
598 */
599 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
600
601 /**
602 * Event to specify that reasons for why an uid is blocked changed.
603 * arg1 = uid
604 * arg2 = blockedReasons
605 */
606 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
607
608 /**
609 * Event to register a new network offer
610 * obj = NetworkOffer
611 */
612 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
613
614 /**
615 * Event to unregister an existing network offer
616 * obj = INetworkOfferCallback
617 */
618 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
619
620 /**
paulhu71ad4f12021-05-25 14:56:27 +0800621 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
622 */
623 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
624
625 /**
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000626 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
627 * should be shown.
628 */
629 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
630
631 /**
632 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
633 * should be hidden.
634 */
635 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
636
637 private static String eventName(int what) {
638 return sMagicDecoderRing.get(what, Integer.toString(what));
639 }
640
641 private static IDnsResolver getDnsResolver(Context context) {
642 final DnsResolverServiceManager dsm = context.getSystemService(
643 DnsResolverServiceManager.class);
644 return IDnsResolver.Stub.asInterface(dsm.getService());
645 }
646
647 /** Handler thread used for all of the handlers below. */
648 @VisibleForTesting
649 protected final HandlerThread mHandlerThread;
650 /** Handler used for internal events. */
651 final private InternalHandler mHandler;
652 /** Handler used for incoming {@link NetworkStateTracker} events. */
653 final private NetworkStateTrackerHandler mTrackerHandler;
654 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
655 @VisibleForTesting
656 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
657
658 private final DnsManager mDnsManager;
659 private final NetworkRanker mNetworkRanker;
660
661 private boolean mSystemReady;
662 private Intent mInitialBroadcast;
663
664 private PowerManager.WakeLock mNetTransitionWakeLock;
665 private final PowerManager.WakeLock mPendingIntentWakeLock;
666
667 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
668 // the world when it changes.
669 @VisibleForTesting
670 protected final ProxyTracker mProxyTracker;
671
672 final private SettingsObserver mSettingsObserver;
673
674 private UserManager mUserManager;
675
676 // the set of network types that can only be enabled by system/sig apps
677 private List<Integer> mProtectedNetworks;
678
679 private Set<String> mWolSupportedInterfaces;
680
681 private final TelephonyManager mTelephonyManager;
682 private final AppOpsManager mAppOpsManager;
683
684 private final LocationPermissionChecker mLocationPermissionChecker;
685
686 private KeepaliveTracker mKeepaliveTracker;
687 private QosCallbackTracker mQosCallbackTracker;
688 private NetworkNotificationManager mNotifier;
689 private LingerMonitor mLingerMonitor;
690
691 // sequence number of NetworkRequests
692 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
693
694 // Sequence number for NetworkProvider IDs.
695 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
696 NetworkProvider.FIRST_PROVIDER_ID);
697
698 // NetworkRequest activity String log entries.
699 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
700 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
701
702 // NetworkInfo blocked and unblocked String log entries
703 private static final int MAX_NETWORK_INFO_LOGS = 40;
704 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
705
706 private static final int MAX_WAKELOCK_LOGS = 20;
707 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
708 private int mTotalWakelockAcquisitions = 0;
709 private int mTotalWakelockReleases = 0;
710 private long mTotalWakelockDurationMs = 0;
711 private long mMaxWakelockDurationMs = 0;
712 private long mLastWakeLockAcquireTimestamp = 0;
713
714 private final IpConnectivityLog mMetricsLog;
715
716 @GuardedBy("mBandwidthRequests")
717 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
718
719 @VisibleForTesting
720 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
721
722 @VisibleForTesting
723 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
724 new HashMap<>();
725
726 /**
727 * Implements support for the legacy "one network per network type" model.
728 *
729 * We used to have a static array of NetworkStateTrackers, one for each
730 * network type, but that doesn't work any more now that we can have,
731 * for example, more that one wifi network. This class stores all the
732 * NetworkAgentInfo objects that support a given type, but the legacy
733 * API will only see the first one.
734 *
735 * It serves two main purposes:
736 *
737 * 1. Provide information about "the network for a given type" (since this
738 * API only supports one).
739 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
740 * the first network for a given type changes, or if the default network
741 * changes.
742 */
743 @VisibleForTesting
744 static class LegacyTypeTracker {
745
746 private static final boolean DBG = true;
747 private static final boolean VDBG = false;
748
749 /**
750 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
751 * Each list holds references to all NetworkAgentInfos that are used to
752 * satisfy requests for that network type.
753 *
754 * This array is built out at startup such that an unsupported network
755 * doesn't get an ArrayList instance, making this a tristate:
756 * unsupported, supported but not active and active.
757 *
758 * The actual lists are populated when we scan the network types that
759 * are supported on this device.
760 *
761 * Threading model:
762 * - addSupportedType() is only called in the constructor
763 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
764 * They are therefore not thread-safe with respect to each other.
765 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
766 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
767 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
768 * - dump is thread-safe with respect to concurrent add and remove calls.
769 */
770 private final ArrayList<NetworkAgentInfo> mTypeLists[];
771 @NonNull
772 private final ConnectivityService mService;
773
774 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
775 // an entry have no timer (equivalent to -1). Lazily loaded.
776 @NonNull
777 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
778
779 LegacyTypeTracker(@NonNull ConnectivityService service) {
780 mService = service;
781 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
782 }
783
784 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
785 final PackageManager pm = ctx.getPackageManager();
786 if (pm.hasSystemFeature(FEATURE_WIFI)) {
787 addSupportedType(TYPE_WIFI);
788 }
789 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
790 addSupportedType(TYPE_WIFI_P2P);
791 }
792 if (tm.isDataCapable()) {
793 // Telephony does not have granular support for these types: they are either all
794 // supported, or none is supported
795 addSupportedType(TYPE_MOBILE);
796 addSupportedType(TYPE_MOBILE_MMS);
797 addSupportedType(TYPE_MOBILE_SUPL);
798 addSupportedType(TYPE_MOBILE_DUN);
799 addSupportedType(TYPE_MOBILE_HIPRI);
800 addSupportedType(TYPE_MOBILE_FOTA);
801 addSupportedType(TYPE_MOBILE_IMS);
802 addSupportedType(TYPE_MOBILE_CBS);
803 addSupportedType(TYPE_MOBILE_IA);
804 addSupportedType(TYPE_MOBILE_EMERGENCY);
805 }
806 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
807 addSupportedType(TYPE_BLUETOOTH);
808 }
809 if (pm.hasSystemFeature(FEATURE_WATCH)) {
810 // TYPE_PROXY is only used on Wear
811 addSupportedType(TYPE_PROXY);
812 }
813 // Ethernet is often not specified in the configs, although many devices can use it via
814 // USB host adapters. Add it as long as the ethernet service is here.
815 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
816 addSupportedType(TYPE_ETHERNET);
817 }
818
819 // Always add TYPE_VPN as a supported type
820 addSupportedType(TYPE_VPN);
821 }
822
823 private void addSupportedType(int type) {
824 if (mTypeLists[type] != null) {
825 throw new IllegalStateException(
826 "legacy list for type " + type + "already initialized");
827 }
828 mTypeLists[type] = new ArrayList<>();
829 }
830
831 public boolean isTypeSupported(int type) {
832 return isNetworkTypeValid(type) && mTypeLists[type] != null;
833 }
834
835 public NetworkAgentInfo getNetworkForType(int type) {
836 synchronized (mTypeLists) {
837 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
838 return mTypeLists[type].get(0);
839 }
840 }
841 return null;
842 }
843
844 public int getRestoreTimerForType(int type) {
845 synchronized (mTypeLists) {
846 if (mRestoreTimers == null) {
847 mRestoreTimers = loadRestoreTimers();
848 }
849 return mRestoreTimers.getOrDefault(type, -1);
850 }
851 }
852
853 private ArrayMap<Integer, Integer> loadRestoreTimers() {
854 final String[] configs = mService.mResources.get().getStringArray(
855 R.array.config_legacy_networktype_restore_timers);
856 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
857 for (final String config : configs) {
858 final String[] splits = TextUtils.split(config, ",");
859 if (splits.length != 2) {
860 logwtf("Invalid restore timer token count: " + config);
861 continue;
862 }
863 try {
864 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
865 } catch (NumberFormatException e) {
866 logwtf("Invalid restore timer number format: " + config, e);
867 }
868 }
869 return ret;
870 }
871
872 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
873 boolean isDefaultNetwork) {
874 if (DBG) {
875 log("Sending " + state
876 + " broadcast for type " + type + " " + nai.toShortString()
877 + " isDefaultNetwork=" + isDefaultNetwork);
878 }
879 }
880
881 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
882 // network type, to preserve previous behaviour.
883 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
884 if (vpnNai != mService.getLegacyLockdownNai()) return;
885
886 if (vpnNai.declaredUnderlyingNetworks == null
887 || vpnNai.declaredUnderlyingNetworks.length != 1) {
888 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
889 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
890 return;
891 }
892 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
893 vpnNai.declaredUnderlyingNetworks[0]);
894 if (underlyingNai == null) return;
895
896 final int type = underlyingNai.networkInfo.getType();
897 final DetailedState state = DetailedState.CONNECTED;
898 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
899 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
900 }
901
902 /** Adds the given network to the specified legacy type list. */
903 public void add(int type, NetworkAgentInfo nai) {
904 if (!isTypeSupported(type)) {
905 return; // Invalid network type.
906 }
907 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
908
909 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
910 if (list.contains(nai)) {
911 return;
912 }
913 synchronized (mTypeLists) {
914 list.add(nai);
915 }
916
917 // Send a broadcast if this is the first network of its type or if it's the default.
918 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
919
920 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
921 // to preserve previous behaviour.
922 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
923 if ((list.size() == 1) || isDefaultNetwork) {
924 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
925 mService.sendLegacyNetworkBroadcast(nai, state, type);
926 }
927
928 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
929 maybeSendLegacyLockdownBroadcast(nai);
930 }
931 }
932
933 /** Removes the given network from the specified legacy type list. */
934 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
935 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
936 if (list == null || list.isEmpty()) {
937 return;
938 }
939 final boolean wasFirstNetwork = list.get(0).equals(nai);
940
941 synchronized (mTypeLists) {
942 if (!list.remove(nai)) {
943 return;
944 }
945 }
946
947 if (wasFirstNetwork || wasDefault) {
948 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
949 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
950 }
951
952 if (!list.isEmpty() && wasFirstNetwork) {
953 if (DBG) log("Other network available for type " + type +
954 ", sending connected broadcast");
955 final NetworkAgentInfo replacement = list.get(0);
956 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
957 mService.isDefaultNetwork(replacement));
958 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
959 }
960 }
961
962 /** Removes the given network from all legacy type lists. */
963 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
964 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
965 for (int type = 0; type < mTypeLists.length; type++) {
966 remove(type, nai, wasDefault);
967 }
968 }
969
970 // send out another legacy broadcast - currently only used for suspend/unsuspend
971 // toggle
972 public void update(NetworkAgentInfo nai) {
973 final boolean isDefault = mService.isDefaultNetwork(nai);
974 final DetailedState state = nai.networkInfo.getDetailedState();
975 for (int type = 0; type < mTypeLists.length; type++) {
976 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
977 final boolean contains = (list != null && list.contains(nai));
978 final boolean isFirst = contains && (nai == list.get(0));
979 if (isFirst || contains && isDefault) {
980 maybeLogBroadcast(nai, state, type, isDefault);
981 mService.sendLegacyNetworkBroadcast(nai, state, type);
982 }
983 }
984 }
985
986 public void dump(IndentingPrintWriter pw) {
987 pw.println("mLegacyTypeTracker:");
988 pw.increaseIndent();
989 pw.print("Supported types:");
990 for (int type = 0; type < mTypeLists.length; type++) {
991 if (mTypeLists[type] != null) pw.print(" " + type);
992 }
993 pw.println();
994 pw.println("Current state:");
995 pw.increaseIndent();
996 synchronized (mTypeLists) {
997 for (int type = 0; type < mTypeLists.length; type++) {
998 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
999 for (NetworkAgentInfo nai : mTypeLists[type]) {
1000 pw.println(type + " " + nai.toShortString());
1001 }
1002 }
1003 }
1004 pw.decreaseIndent();
1005 pw.decreaseIndent();
1006 pw.println();
1007 }
1008 }
1009 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
1010
1011 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
1012 /**
1013 * Helper class which parses out priority arguments and dumps sections according to their
1014 * priority. If priority arguments are omitted, function calls the legacy dump command.
1015 */
1016 private class LocalPriorityDump {
1017 private static final String PRIORITY_ARG = "--dump-priority";
1018 private static final String PRIORITY_ARG_HIGH = "HIGH";
1019 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1020
1021 LocalPriorityDump() {}
1022
1023 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1024 doDump(fd, pw, new String[] {DIAG_ARG});
1025 doDump(fd, pw, new String[] {SHORT_ARG});
1026 }
1027
1028 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1029 doDump(fd, pw, args);
1030 }
1031
1032 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1033 if (args == null) {
1034 dumpNormal(fd, pw, args);
1035 return;
1036 }
1037
1038 String priority = null;
1039 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1040 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1041 argIndex++;
1042 priority = args[argIndex];
1043 }
1044 }
1045
1046 if (PRIORITY_ARG_HIGH.equals(priority)) {
1047 dumpHigh(fd, pw);
1048 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1049 dumpNormal(fd, pw, args);
1050 } else {
1051 // ConnectivityService publishes binder service using publishBinderService() with
1052 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang12d32a62021-05-17 16:57:15 +08001053 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1054 // legacy output for dumpsys connectivity.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001055 // TODO: Integrate into signal dump.
1056 dumpNormal(fd, pw, args);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001057 }
1058 }
1059 }
1060
1061 /**
1062 * Keeps track of the number of requests made under different uids.
1063 */
1064 public static class PerUidCounter {
1065 private final int mMaxCountPerUid;
1066
1067 // Map from UID to number of NetworkRequests that UID has filed.
1068 @VisibleForTesting
1069 @GuardedBy("mUidToNetworkRequestCount")
1070 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
1071
1072 /**
1073 * Constructor
1074 *
1075 * @param maxCountPerUid the maximum count per uid allowed
1076 */
1077 public PerUidCounter(final int maxCountPerUid) {
1078 mMaxCountPerUid = maxCountPerUid;
1079 }
1080
1081 /**
1082 * Increments the request count of the given uid. Throws an exception if the number
1083 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1084 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1085 *
1086 * @throws ServiceSpecificException with
1087 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1088 * the uid exceed the allowed number.
1089 *
1090 * @param uid the uid that the request was made under
1091 */
1092 public void incrementCountOrThrow(final int uid) {
1093 synchronized (mUidToNetworkRequestCount) {
1094 incrementCountOrThrow(uid, 1 /* numToIncrement */);
1095 }
1096 }
1097
1098 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1099 final int newRequestCount =
1100 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1101 if (newRequestCount >= mMaxCountPerUid) {
1102 throw new ServiceSpecificException(
1103 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1104 }
1105 mUidToNetworkRequestCount.put(uid, newRequestCount);
1106 }
1107
1108 /**
1109 * Decrements the request count of the given uid.
1110 *
1111 * @param uid the uid that the request was made under
1112 */
1113 public void decrementCount(final int uid) {
1114 synchronized (mUidToNetworkRequestCount) {
1115 decrementCount(uid, 1 /* numToDecrement */);
1116 }
1117 }
1118
1119 private void decrementCount(final int uid, final int numToDecrement) {
1120 final int newRequestCount =
1121 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1122 if (newRequestCount < 0) {
1123 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1124 } else if (newRequestCount == 0) {
1125 mUidToNetworkRequestCount.delete(uid);
1126 } else {
1127 mUidToNetworkRequestCount.put(uid, newRequestCount);
1128 }
1129 }
1130
1131 /**
1132 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1133 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1134 * are used to create the new nris upon set. Therefore the request count limit can be
1135 * artificially hit. This method is used as a workaround for this particular case so that
1136 * the request counts are accounted for correctly.
1137 * @param uid the uid to adjust counts for
1138 * @param numOfNewRequests the new request count to account for
1139 * @param r the runnable to execute
1140 */
1141 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1142 // This should only be used on the handler thread as per all current and foreseen
1143 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1144 // no ref to the outer ConnectivityService.
1145 synchronized (mUidToNetworkRequestCount) {
1146 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1147 decrementCount(uid, reqCountOverage);
1148 r.run();
1149 incrementCountOrThrow(uid, reqCountOverage);
1150 }
1151 }
1152
1153 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1154 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1155 + numOfNewRequests;
1156 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1157 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1158 }
1159 }
1160
1161 /**
1162 * Dependencies of ConnectivityService, for injection in tests.
1163 */
1164 @VisibleForTesting
1165 public static class Dependencies {
1166 public int getCallingUid() {
1167 return Binder.getCallingUid();
1168 }
1169
1170 /**
1171 * Get system properties to use in ConnectivityService.
1172 */
1173 public MockableSystemProperties getSystemProperties() {
1174 return new MockableSystemProperties();
1175 }
1176
1177 /**
1178 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1179 */
1180 public ConnectivityResources getResources(@NonNull Context ctx) {
1181 return new ConnectivityResources(ctx);
1182 }
1183
1184 /**
1185 * Create a HandlerThread to use in ConnectivityService.
1186 */
1187 public HandlerThread makeHandlerThread() {
1188 return new HandlerThread("ConnectivityServiceThread");
1189 }
1190
1191 /**
1192 * Get a reference to the ModuleNetworkStackClient.
1193 */
1194 public NetworkStackClientBase getNetworkStack() {
1195 return ModuleNetworkStackClient.getInstance(null);
1196 }
1197
1198 /**
1199 * @see ProxyTracker
1200 */
1201 public ProxyTracker makeProxyTracker(@NonNull Context context,
1202 @NonNull Handler connServiceHandler) {
1203 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1204 }
1205
1206 /**
1207 * @see NetIdManager
1208 */
1209 public NetIdManager makeNetIdManager() {
1210 return new NetIdManager();
1211 }
1212
1213 /**
1214 * @see NetworkUtils#queryUserAccess(int, int)
1215 */
1216 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1217 return cs.queryUserAccess(uid, network);
1218 }
1219
1220 /**
1221 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1222 * requires CAP_NET_ADMIN, which the unit tests do not have.
1223 */
1224 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1225 InetSocketAddress remote) {
1226 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1227 }
1228
1229 /**
1230 * @see MultinetworkPolicyTracker
1231 */
1232 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1233 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1234 return new MultinetworkPolicyTracker(c, h, r);
1235 }
1236
1237 /**
1238 * @see BatteryStatsManager
1239 */
1240 public void reportNetworkInterfaceForTransports(Context context, String iface,
1241 int[] transportTypes) {
1242 final BatteryStatsManager batteryStats =
1243 context.getSystemService(BatteryStatsManager.class);
1244 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1245 }
1246
1247 public boolean getCellular464XlatEnabled() {
1248 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1249 }
1250 }
1251
1252 public ConnectivityService(Context context) {
1253 this(context, getDnsResolver(context), new IpConnectivityLog(),
1254 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1255 new Dependencies());
1256 }
1257
1258 @VisibleForTesting
1259 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1260 IpConnectivityLog logger, INetd netd, Dependencies deps) {
1261 if (DBG) log("ConnectivityService starting up");
1262
1263 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
1264 mSystemProperties = mDeps.getSystemProperties();
1265 mNetIdManager = mDeps.makeNetIdManager();
1266 mContext = Objects.requireNonNull(context, "missing Context");
1267 mResources = deps.getResources(mContext);
1268 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
1269 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
1270
1271 mMetricsLog = logger;
1272 mNetworkRanker = new NetworkRanker();
1273 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1274 mDefaultRequest = new NetworkRequestInfo(
1275 Process.myUid(), defaultInternetRequest, null,
1276 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
1277 null /* attributionTags */);
1278 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1279 mDefaultNetworkRequests.add(mDefaultRequest);
1280 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
1281
1282 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
1283 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
1284
1285 // The default WiFi request is a background request so that apps using WiFi are
1286 // migrated to a better network (typically ethernet) when one comes up, instead
1287 // of staying on WiFi forever.
1288 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1289 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1290
1291 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1292 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1293 NetworkRequest.Type.BACKGROUND_REQUEST);
1294
1295 mHandlerThread = mDeps.makeHandlerThread();
1296 mHandlerThread.start();
1297 mHandler = new InternalHandler(mHandlerThread.getLooper());
1298 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
1299 mConnectivityDiagnosticsHandler =
1300 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
1301
1302 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
1303 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
1304
1305 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1306 // TODO: Consider making the timer customizable.
1307 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1308
1309 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
1310 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
1311 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
1312 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
1313
1314 mNetd = netd;
1315 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
1316 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1317 mLocationPermissionChecker = new LocationPermissionChecker(mContext);
1318
1319 // To ensure uid state is synchronized with Network Policy, register for
1320 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1321 // reading existing policy from disk.
1322 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
1323
1324 final PowerManager powerManager = (PowerManager) context.getSystemService(
1325 Context.POWER_SERVICE);
1326 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1327 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1328
1329 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1330 mProtectedNetworks = new ArrayList<>();
1331 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
1332 for (int p : protectedNetworks) {
1333 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
1334 mProtectedNetworks.add(p);
1335 } else {
1336 if (DBG) loge("Ignoring protectedNetwork " + p);
1337 }
1338 }
1339
1340 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1341
1342 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
1343
1344 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
1345 // Listen for user add/removes to inform PermissionMonitor.
1346 // Should run on mHandler to avoid any races.
1347 final IntentFilter userIntentFilter = new IntentFilter();
1348 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1349 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1350 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1351 null /* broadcastPermission */, mHandler);
1352
1353 // Listen to package add/removes for netd
1354 final IntentFilter packageIntentFilter = new IntentFilter();
1355 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1356 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1357 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1358 packageIntentFilter.addDataScheme("package");
1359 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
1360 null /* broadcastPermission */, mHandler);
1361
1362 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
1363
1364 mNetdCallback = new NetdCallback();
1365 try {
1366 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1367 } catch (RemoteException | ServiceSpecificException e) {
1368 loge("Error registering event listener :" + e);
1369 }
1370
1371 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1372 registerSettingsCallbacks();
1373
1374 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
1375 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
1376 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
1377
1378 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1379 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1380 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1381 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1382 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1383 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1384 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
1385
1386 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
1387 mContext, mHandler, () -> updateAvoidBadWifi());
1388 mMultinetworkPolicyTracker.start();
1389
1390 mDnsManager = new DnsManager(mContext, mDnsResolver);
1391 registerPrivateDnsSettingsCallbacks();
1392
1393 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1394 // request that doesn't allow fallback to the default network. It should never be visible
1395 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1396 // arguments like the handler or the DnsResolver.
1397 // TODO : remove this ; it is probably better handled with a sentinel request.
1398 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen4f612fa2021-05-14 14:30:43 +08001399 new Network(INetd.UNREACHABLE_NET_ID),
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001400 new NetworkInfo(TYPE_NONE, 0, "", ""),
1401 new LinkProperties(), new NetworkCapabilities(),
1402 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
1403 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1404 mLingerDelayMs, mQosCallbackTracker, mDeps);
1405 }
1406
1407 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1408 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1409 }
1410
1411 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1412 @NonNull final UidRange uids) {
1413 final NetworkCapabilities netCap = new NetworkCapabilities();
1414 netCap.addCapability(NET_CAPABILITY_INTERNET);
1415 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
1416 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1417 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
1418 return netCap;
1419 }
1420
1421 private NetworkRequest createDefaultRequest() {
1422 return createDefaultInternetRequestForTransport(
1423 TYPE_NONE, NetworkRequest.Type.REQUEST);
1424 }
1425
1426 private NetworkRequest createDefaultInternetRequestForTransport(
1427 int transportType, NetworkRequest.Type type) {
1428 final NetworkCapabilities netCap = new NetworkCapabilities();
1429 netCap.addCapability(NET_CAPABILITY_INTERNET);
1430 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
1431 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1432 if (transportType > TYPE_NONE) {
1433 netCap.addTransportType(transportType);
1434 }
1435 return createNetworkRequest(type, netCap);
1436 }
1437
1438 private NetworkRequest createNetworkRequest(
1439 NetworkRequest.Type type, NetworkCapabilities netCap) {
1440 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1441 }
1442
1443 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1444 NetworkRequest.Type type) {
1445 final NetworkCapabilities netCap = new NetworkCapabilities();
1446 netCap.clearAll();
1447 netCap.addCapability(capability);
1448 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1449 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1450 }
1451
1452 // Used only for testing.
1453 // TODO: Delete this and either:
1454 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
1455 // changing ContentResolver to make registerContentObserver non-final).
1456 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1457 // by subclassing SettingsObserver.
1458 @VisibleForTesting
1459 void updateAlwaysOnNetworks() {
1460 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1461 }
1462
1463 // See FakeSettingsProvider comment above.
1464 @VisibleForTesting
1465 void updatePrivateDnsSettings() {
1466 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1467 }
1468
paulhu71ad4f12021-05-25 14:56:27 +08001469 @VisibleForTesting
1470 void updateMobileDataPreferredUids() {
1471 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1472 }
1473
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001474 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
1475 final boolean enable = mContext.getResources().getBoolean(id);
1476 handleAlwaysOnNetworkRequest(networkRequest, enable);
1477 }
1478
1479 private void handleAlwaysOnNetworkRequest(
1480 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
1481 final boolean enable = toBool(Settings.Global.getInt(
1482 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1483 handleAlwaysOnNetworkRequest(networkRequest, enable);
1484 }
1485
1486 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
1487 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
1488 if (enable == isEnabled) {
1489 return; // Nothing to do.
1490 }
1491
1492 if (enable) {
1493 handleRegisterNetworkRequest(new NetworkRequestInfo(
1494 Process.myUid(), networkRequest, null, new Binder(),
1495 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
1496 null /* attributionTags */));
1497 } else {
1498 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1499 /* callOnUnavailable */ false);
1500 }
1501 }
1502
1503 private void handleConfigureAlwaysOnNetworks() {
1504 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1505 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1506 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1507 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
1508 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1509 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001510 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001511 }
1512
paulhu71ad4f12021-05-25 14:56:27 +08001513 // Note that registering observer for setting do not get initial callback when registering,
1514 // callers might have self-initialization to update status if need.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001515 private void registerSettingsCallbacks() {
1516 // Watch for global HTTP proxy changes.
1517 mSettingsObserver.observe(
1518 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1519 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1520
1521 // Watch for whether or not to keep mobile data always on.
1522 mSettingsObserver.observe(
1523 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
1524 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1525
1526 // Watch for whether or not to keep wifi always on.
1527 mSettingsObserver.observe(
1528 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
1529 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu71ad4f12021-05-25 14:56:27 +08001530
1531 // Watch for mobile data preferred uids changes.
1532 mSettingsObserver.observe(
1533 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1534 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001535 }
1536
1537 private void registerPrivateDnsSettingsCallbacks() {
1538 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1539 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1540 }
1541 }
1542
1543 private synchronized int nextNetworkRequestId() {
1544 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1545 // doing that.
1546 return mNextNetworkRequestId++;
1547 }
1548
1549 @VisibleForTesting
1550 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1551 if (network == null) {
1552 return null;
1553 }
1554 return getNetworkAgentInfoForNetId(network.getNetId());
1555 }
1556
1557 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
1558 synchronized (mNetworkForNetId) {
1559 return mNetworkForNetId.get(netId);
1560 }
1561 }
1562
1563 // TODO: determine what to do when more than one VPN applies to |uid|.
1564 private NetworkAgentInfo getVpnForUid(int uid) {
1565 synchronized (mNetworkForNetId) {
1566 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1567 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1568 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1569 return nai;
1570 }
1571 }
1572 }
1573 return null;
1574 }
1575
1576 private Network[] getVpnUnderlyingNetworks(int uid) {
1577 if (mLockdownEnabled) return null;
1578 final NetworkAgentInfo nai = getVpnForUid(uid);
1579 if (nai != null) return nai.declaredUnderlyingNetworks;
1580 return null;
1581 }
1582
1583 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
1584 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
1585
1586 final Network[] networks = getVpnUnderlyingNetworks(uid);
1587 if (networks != null) {
1588 // getUnderlyingNetworks() returns:
1589 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1590 // empty array => the VPN explicitly said "no default network".
1591 // non-empty array => the VPN specified one or more default networks; we use the
1592 // first one.
1593 if (networks.length > 0) {
1594 nai = getNetworkAgentInfoForNetwork(networks[0]);
1595 } else {
1596 nai = null;
1597 }
1598 }
1599 return nai;
1600 }
1601
1602 /**
1603 * Check if UID should be blocked from using the specified network.
1604 */
1605 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1606 final int uid, final boolean ignoreBlocked) {
1607 // Networks aren't blocked when ignoring blocked status
1608 if (ignoreBlocked) {
1609 return false;
1610 }
1611 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
1612 final long ident = Binder.clearCallingIdentity();
1613 try {
1614 final boolean metered = nc == null ? true : nc.isMetered();
1615 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1616 } finally {
1617 Binder.restoreCallingIdentity(ident);
1618 }
1619 }
1620
1621 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
1622 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1623 return;
1624 }
1625 final boolean blocked;
1626 synchronized (mBlockedAppUids) {
1627 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1628 blocked = true;
1629 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1630 blocked = false;
1631 } else {
1632 return;
1633 }
1634 }
1635 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1636 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1637 mNetworkInfoBlockingLogs.log(action + " " + uid);
1638 }
1639
1640 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
1641 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1642 return;
1643 }
1644 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
1645 final int requestId = nri.getActiveRequest() != null
1646 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
1647 mNetworkInfoBlockingLogs.log(String.format(
1648 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
1649 Integer.toHexString(blocked)));
1650 }
1651
1652 /**
1653 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
1654 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1655 * on {@link #isNetworkWithCapabilitiesBlocked}.
1656 */
1657 @NonNull
1658 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1659 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
1660 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1661 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1662 // but only exists if an app asks about them or requests them. Ensure the requesting app
1663 // gets the type it asks for.
1664 filtered.setType(type);
1665 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1666 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1667 null /* extraInfo */);
1668 }
1669 filterForLegacyLockdown(filtered);
1670 return filtered;
1671 }
1672
1673 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1674 boolean ignoreBlocked) {
1675 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1676 nai.networkCapabilities, uid, ignoreBlocked);
1677 }
1678
1679 /**
1680 * Return NetworkInfo for the active (i.e., connected) network interface.
1681 * It is assumed that at most one network is active at a time. If more
1682 * than one is active, it is indeterminate which will be returned.
1683 * @return the info for the active network, or {@code null} if none is
1684 * active
1685 */
1686 @Override
1687 public NetworkInfo getActiveNetworkInfo() {
1688 enforceAccessPermission();
1689 final int uid = mDeps.getCallingUid();
1690 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1691 if (nai == null) return null;
1692 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1693 maybeLogBlockedNetworkInfo(networkInfo, uid);
1694 return networkInfo;
1695 }
1696
1697 @Override
1698 public Network getActiveNetwork() {
1699 enforceAccessPermission();
1700 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
1701 }
1702
1703 @Override
1704 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1705 PermissionUtils.enforceNetworkStackPermission(mContext);
1706 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
1707 }
1708
1709 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
1710 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1711 if (vpnNai != null) {
1712 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1713 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1714 return vpnNai.network;
1715 }
1716 }
1717
1718 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
1719 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1720 ignoreBlocked)) {
1721 return null;
1722 }
1723 return nai.network;
1724 }
1725
1726 @Override
1727 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1728 PermissionUtils.enforceNetworkStackPermission(mContext);
1729 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1730 if (nai == null) return null;
1731 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
1732 }
1733
1734 /** Returns a NetworkInfo object for a network that doesn't exist. */
1735 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1736 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1737 getNetworkTypeName(networkType), "" /* subtypeName */);
1738 info.setIsAvailable(true);
1739 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1740 // background data is restricted.
1741 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1742 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1743 ? DetailedState.BLOCKED
1744 : DetailedState.DISCONNECTED;
1745 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1746 filterForLegacyLockdown(info);
1747 return info;
1748 }
1749
1750 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
1751 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1752 return null;
1753 }
1754 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1755 if (nai == null) {
1756 return makeFakeNetworkInfo(networkType, uid);
1757 }
1758 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1759 false);
1760 }
1761
1762 @Override
1763 public NetworkInfo getNetworkInfo(int networkType) {
1764 enforceAccessPermission();
1765 final int uid = mDeps.getCallingUid();
1766 if (getVpnUnderlyingNetworks(uid) != null) {
1767 // A VPN is active, so we may need to return one of its underlying networks. This
1768 // information is not available in LegacyTypeTracker, so we have to get it from
1769 // getNetworkAgentInfoForUid.
1770 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1771 if (nai == null) return null;
1772 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1773 if (networkInfo.getType() == networkType) {
1774 return networkInfo;
1775 }
1776 }
1777 return getFilteredNetworkInfoForType(networkType, uid);
1778 }
1779
1780 @Override
1781 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1782 enforceAccessPermission();
1783 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1784 if (nai == null) return null;
1785 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
1786 }
1787
1788 @Override
1789 public NetworkInfo[] getAllNetworkInfo() {
1790 enforceAccessPermission();
1791 final ArrayList<NetworkInfo> result = new ArrayList<>();
1792 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1793 networkType++) {
1794 NetworkInfo info = getNetworkInfo(networkType);
1795 if (info != null) {
1796 result.add(info);
1797 }
1798 }
1799 return result.toArray(new NetworkInfo[result.size()]);
1800 }
1801
1802 @Override
1803 public Network getNetworkForType(int networkType) {
1804 enforceAccessPermission();
1805 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1806 return null;
1807 }
1808 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1809 if (nai == null) {
1810 return null;
1811 }
1812 final int uid = mDeps.getCallingUid();
1813 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1814 return null;
1815 }
1816 return nai.network;
1817 }
1818
1819 @Override
1820 public Network[] getAllNetworks() {
1821 enforceAccessPermission();
1822 synchronized (mNetworkForNetId) {
1823 final Network[] result = new Network[mNetworkForNetId.size()];
1824 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1825 result[i] = mNetworkForNetId.valueAt(i).network;
1826 }
1827 return result;
1828 }
1829 }
1830
1831 @Override
1832 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
1833 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
1834 // The basic principle is: if an app's traffic could possibly go over a
1835 // network, without the app doing anything multinetwork-specific,
1836 // (hence, by "default"), then include that network's capabilities in
1837 // the array.
1838 //
1839 // In the normal case, app traffic only goes over the system's default
1840 // network connection, so that's the only network returned.
1841 //
1842 // With a VPN in force, some app traffic may go into the VPN, and thus
1843 // over whatever underlying networks the VPN specifies, while other app
1844 // traffic may go over the system default network (e.g.: a split-tunnel
1845 // VPN, or an app disallowed by the VPN), so the set of networks
1846 // returned includes the VPN's underlying networks and the system
1847 // default.
1848 enforceAccessPermission();
1849
1850 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
1851
1852 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1853 if (!nri.isBeingSatisfied()) {
1854 continue;
1855 }
1856 final NetworkAgentInfo nai = nri.getSatisfier();
1857 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1858 if (null != nc
1859 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1860 && !result.containsKey(nai.network)) {
1861 result.put(
1862 nai.network,
1863 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1864 nc, false /* includeLocationSensitiveInfo */,
1865 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1866 callingAttributionTag));
1867 }
1868 }
1869
1870 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
1871 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
1872 if (null != networks) {
1873 for (final Network network : networks) {
1874 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1875 if (null != nc) {
1876 result.put(
1877 network,
1878 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1879 nc,
1880 false /* includeLocationSensitiveInfo */,
1881 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1882 callingAttributionTag));
1883 }
1884 }
1885 }
1886
1887 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1888 out = result.values().toArray(out);
1889 return out;
1890 }
1891
1892 @Override
1893 public boolean isNetworkSupported(int networkType) {
1894 enforceAccessPermission();
1895 return mLegacyTypeTracker.isTypeSupported(networkType);
1896 }
1897
1898 /**
1899 * Return LinkProperties for the active (i.e., connected) default
1900 * network interface for the calling uid.
1901 * @return the ip properties for the active network, or {@code null} if
1902 * none is active
1903 */
1904 @Override
1905 public LinkProperties getActiveLinkProperties() {
1906 enforceAccessPermission();
1907 final int uid = mDeps.getCallingUid();
1908 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1909 if (nai == null) return null;
1910 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
1911 Binder.getCallingPid(), uid);
1912 }
1913
1914 @Override
1915 public LinkProperties getLinkPropertiesForType(int networkType) {
1916 enforceAccessPermission();
1917 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1918 final LinkProperties lp = getLinkProperties(nai);
1919 if (lp == null) return null;
1920 return linkPropertiesRestrictedForCallerPermissions(
1921 lp, Binder.getCallingPid(), mDeps.getCallingUid());
1922 }
1923
1924 // TODO - this should be ALL networks
1925 @Override
1926 public LinkProperties getLinkProperties(Network network) {
1927 enforceAccessPermission();
1928 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1929 if (lp == null) return null;
1930 return linkPropertiesRestrictedForCallerPermissions(
1931 lp, Binder.getCallingPid(), mDeps.getCallingUid());
1932 }
1933
1934 @Nullable
1935 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
1936 if (nai == null) {
1937 return null;
1938 }
1939 synchronized (nai) {
1940 return nai.linkProperties;
1941 }
1942 }
1943
1944 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
1945 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1946 }
1947
1948 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
1949 if (nai == null) return null;
1950 synchronized (nai) {
1951 return networkCapabilitiesRestrictedForCallerPermissions(
1952 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
1953 }
1954 }
1955
1956 @Override
1957 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
1958 @Nullable String callingAttributionTag) {
1959 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
1960 enforceAccessPermission();
1961 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1962 getNetworkCapabilitiesInternal(network),
1963 false /* includeLocationSensitiveInfo */,
1964 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
1965 }
1966
1967 @VisibleForTesting
1968 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
1969 NetworkCapabilities nc, int callerPid, int callerUid) {
1970 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
1971 if (!checkSettingsPermission(callerPid, callerUid)) {
1972 newNc.setUids(null);
1973 newNc.setSSID(null);
1974 }
1975 if (newNc.getNetworkSpecifier() != null) {
1976 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1977 }
1978 newNc.setAdministratorUids(new int[0]);
1979 if (!checkAnyPermissionOf(
1980 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
1981 newNc.setSubscriptionIds(Collections.emptySet());
1982 }
1983
1984 return newNc;
1985 }
1986
1987 /**
1988 * Wrapper used to cache the permission check results performed for the corresponding
1989 * app. This avoid performing multiple permission checks for different fields in
1990 * NetworkCapabilities.
1991 * Note: This wrapper does not support any sort of invalidation and thus must not be
1992 * persistent or long-lived. It may only be used for the time necessary to
1993 * compute the redactions required by one particular NetworkCallback or
1994 * synchronous call.
1995 */
1996 private class RedactionPermissionChecker {
1997 private final int mCallingPid;
1998 private final int mCallingUid;
1999 @NonNull private final String mCallingPackageName;
2000 @Nullable private final String mCallingAttributionTag;
2001
2002 private Boolean mHasLocationPermission = null;
2003 private Boolean mHasLocalMacAddressPermission = null;
2004 private Boolean mHasSettingsPermission = null;
2005
2006 RedactionPermissionChecker(int callingPid, int callingUid,
2007 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2008 mCallingPid = callingPid;
2009 mCallingUid = callingUid;
2010 mCallingPackageName = callingPackageName;
2011 mCallingAttributionTag = callingAttributionTag;
2012 }
2013
2014 private boolean hasLocationPermissionInternal() {
2015 final long token = Binder.clearCallingIdentity();
2016 try {
2017 return mLocationPermissionChecker.checkLocationPermission(
2018 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2019 null /* message */);
2020 } finally {
2021 Binder.restoreCallingIdentity(token);
2022 }
2023 }
2024
2025 /**
2026 * Returns whether the app holds location permission or not (might return cached result
2027 * if the permission was already checked before).
2028 */
2029 public boolean hasLocationPermission() {
2030 if (mHasLocationPermission == null) {
2031 // If there is no cached result, perform the check now.
2032 mHasLocationPermission = hasLocationPermissionInternal();
2033 }
2034 return mHasLocationPermission;
2035 }
2036
2037 /**
2038 * Returns whether the app holds local mac address permission or not (might return cached
2039 * result if the permission was already checked before).
2040 */
2041 public boolean hasLocalMacAddressPermission() {
2042 if (mHasLocalMacAddressPermission == null) {
2043 // If there is no cached result, perform the check now.
2044 mHasLocalMacAddressPermission =
2045 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2046 }
2047 return mHasLocalMacAddressPermission;
2048 }
2049
2050 /**
2051 * Returns whether the app holds settings permission or not (might return cached
2052 * result if the permission was already checked before).
2053 */
2054 public boolean hasSettingsPermission() {
2055 if (mHasSettingsPermission == null) {
2056 // If there is no cached result, perform the check now.
2057 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2058 }
2059 return mHasSettingsPermission;
2060 }
2061 }
2062
2063 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2064 @NetworkCapabilities.NetCapability long redaction) {
2065 return (redactions & redaction) != 0;
2066 }
2067
2068 /**
2069 * Use the provided |applicableRedactions| to check the receiving app's
2070 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2071 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2072 * before being sent to the corresponding app.
2073 */
2074 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2075 @NetworkCapabilities.RedactionType long applicableRedactions,
2076 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2077 boolean includeLocationSensitiveInfo) {
2078 long redactions = applicableRedactions;
2079 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2080 if (includeLocationSensitiveInfo
2081 && redactionPermissionChecker.hasLocationPermission()) {
2082 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2083 }
2084 }
2085 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2086 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2087 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2088 }
2089 }
2090 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2091 if (redactionPermissionChecker.hasSettingsPermission()) {
2092 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2093 }
2094 }
2095 return redactions;
2096 }
2097
2098 @VisibleForTesting
2099 @Nullable
2100 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2101 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
2102 int callingPid, int callingUid, @NonNull String callingPkgName,
2103 @Nullable String callingAttributionTag) {
2104 if (nc == null) {
2105 return null;
2106 }
2107 // Avoid doing location permission check if the transport info has no location sensitive
2108 // data.
2109 final RedactionPermissionChecker redactionPermissionChecker =
2110 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2111 callingAttributionTag);
2112 final long redactions = retrieveRequiredRedactions(
2113 nc.getApplicableRedactions(), redactionPermissionChecker,
2114 includeLocationSensitiveInfo);
2115 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
2116 // Reset owner uid if not destined for the owner app.
2117 if (callingUid != nc.getOwnerUid()) {
2118 newNc.setOwnerUid(INVALID_UID);
2119 return newNc;
2120 }
2121 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2122 if (nc.hasTransport(TRANSPORT_VPN)) {
2123 // Owner UIDs already checked above. No need to re-check.
2124 return newNc;
2125 }
2126 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2127 // Else include the owner UID iff the calling has location permission to provide backwards
2128 // compatibility for older apps.
2129 if (!includeLocationSensitiveInfo
2130 && isTargetSdkAtleast(
2131 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
2132 newNc.setOwnerUid(INVALID_UID);
2133 return newNc;
2134 }
2135 // Reset owner uid if the app has no location permission.
2136 if (!redactionPermissionChecker.hasLocationPermission()) {
2137 newNc.setOwnerUid(INVALID_UID);
2138 }
2139 return newNc;
2140 }
2141
2142 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2143 LinkProperties lp, int callerPid, int callerUid) {
2144 if (lp == null) return new LinkProperties();
2145
2146 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2147 final boolean needsSanitization =
2148 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2149 if (!needsSanitization) {
2150 return new LinkProperties(lp);
2151 }
2152
2153 if (checkSettingsPermission(callerPid, callerUid)) {
2154 return new LinkProperties(lp, true /* parcelSensitiveFields */);
2155 }
2156
2157 final LinkProperties newLp = new LinkProperties(lp);
2158 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2159 // object gets parceled.
2160 newLp.setCaptivePortalApiUrl(null);
2161 newLp.setCaptivePortalData(null);
2162 return newLp;
2163 }
2164
2165 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2166 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002167 // There is no need to track the effective UID of the request here. If the caller
2168 // lacks the settings permission, the effective UID is the same as the calling ID.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002169 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002170 // Unprivileged apps can only pass in null or their own UID.
2171 if (nc.getUids() == null) {
2172 // If the caller passes in null, the callback will also match networks that do not
2173 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2174 // In this case, redact everything in the request immediately. This ensures that the
2175 // app is not able to get any redacted information by filing an unredacted request
2176 // and observing whether the request matches something.
2177 if (nc.getNetworkSpecifier() != null) {
2178 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2179 }
2180 } else {
2181 nc.setSingleUid(callerUid);
2182 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002183 }
2184 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
2185 nc.setAdministratorUids(new int[0]);
2186
2187 // Clear owner UID; this can never come from an app.
2188 nc.setOwnerUid(INVALID_UID);
2189 }
2190
2191 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
2192 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
2193 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2194 }
2195 }
2196
2197 @Override
2198 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2199 enforceAccessPermission();
2200 final int callerUid = Binder.getCallingUid();
2201 final long token = Binder.clearCallingIdentity();
2202 try {
2203 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2204 } finally {
2205 Binder.restoreCallingIdentity(token);
2206 }
2207 }
2208
2209 // TODO: Consider delete this function or turn it into a no-op method.
2210 @Override
2211 public NetworkState[] getAllNetworkState() {
2212 // This contains IMSI details, so make sure the caller is privileged.
2213 PermissionUtils.enforceNetworkStackPermission(mContext);
2214
2215 final ArrayList<NetworkState> result = new ArrayList<>();
2216 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
2217 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2218 // NetworkAgentInfo.
2219 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
2220 if (nai != null && nai.networkInfo.isConnected()) {
2221 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
2222 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2223 snapshot.getNetwork(), snapshot.getSubscriberId()));
2224 }
2225 }
2226 return result.toArray(new NetworkState[result.size()]);
2227 }
2228
2229 @Override
2230 @NonNull
2231 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
2232 // This contains IMSI details, so make sure the caller is privileged.
junyulai7968fba2021-05-14 18:04:29 +08002233 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002234
2235 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2236 for (Network network : getAllNetworks()) {
2237 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2238 // TODO: Consider include SUSPENDED networks, which should be considered as
2239 // temporary shortage of connectivity of a connected network.
2240 if (nai != null && nai.networkInfo.isConnected()) {
2241 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2242 // NetworkCapabilities, which may contain UIDs of apps to which the
2243 // network applies. Should the UIDs be cleared so as not to leak or
2244 // interfere ?
2245 result.add(nai.getNetworkStateSnapshot());
2246 }
2247 }
2248 return result;
2249 }
2250
2251 @Override
2252 public boolean isActiveNetworkMetered() {
2253 enforceAccessPermission();
2254
2255 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
2256 if (caps != null) {
2257 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2258 } else {
2259 // Always return the most conservative value
2260 return true;
2261 }
2262 }
2263
2264 /**
2265 * Ensures that the system cannot call a particular method.
2266 */
2267 private boolean disallowedBecauseSystemCaller() {
2268 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
2269 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2270 // for devices launched with Q and above. However, existing devices upgrading to Q and
2271 // above must continued to be supported for few more releases.
2272 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
2273 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
2274 log("This method exists only for app backwards compatibility"
2275 + " and must not be called by system services.");
2276 return true;
2277 }
2278 return false;
2279 }
2280
2281 /**
2282 * Ensure that a network route exists to deliver traffic to the specified
2283 * host via the specified network interface.
2284 * @param networkType the type of the network over which traffic to the
2285 * specified host is to be routed
2286 * @param hostAddress the IP address of the host to which the route is
2287 * desired
2288 * @return {@code true} on success, {@code false} on failure
2289 */
2290 @Override
2291 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2292 String callingPackageName, String callingAttributionTag) {
2293 if (disallowedBecauseSystemCaller()) {
2294 return false;
2295 }
2296 enforceChangePermission(callingPackageName, callingAttributionTag);
2297 if (mProtectedNetworks.contains(networkType)) {
2298 enforceConnectivityRestrictedNetworksPermission();
2299 }
2300
2301 InetAddress addr;
2302 try {
2303 addr = InetAddress.getByAddress(hostAddress);
2304 } catch (UnknownHostException e) {
2305 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2306 return false;
2307 }
2308
2309 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
2310 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
2311 return false;
2312 }
2313
2314 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2315 if (nai == null) {
2316 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2317 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2318 } else {
2319 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2320 }
2321 return false;
2322 }
2323
2324 DetailedState netState;
2325 synchronized (nai) {
2326 netState = nai.networkInfo.getDetailedState();
2327 }
2328
2329 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
2330 if (VDBG) {
2331 log("requestRouteToHostAddress on down network "
2332 + "(" + networkType + ") - dropped"
2333 + " netState=" + netState);
2334 }
2335 return false;
2336 }
2337
2338 final int uid = mDeps.getCallingUid();
2339 final long token = Binder.clearCallingIdentity();
2340 try {
2341 LinkProperties lp;
2342 int netId;
2343 synchronized (nai) {
2344 lp = nai.linkProperties;
2345 netId = nai.network.getNetId();
2346 }
2347 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
2348 if (DBG) {
2349 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2350 }
2351 return ok;
2352 } finally {
2353 Binder.restoreCallingIdentity(token);
2354 }
2355 }
2356
2357 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
2358 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
2359 if (bestRoute == null) {
2360 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
2361 } else {
2362 String iface = bestRoute.getInterface();
2363 if (bestRoute.getGateway().equals(addr)) {
2364 // if there is no better route, add the implied hostroute for our gateway
2365 bestRoute = RouteInfo.makeHostRoute(addr, iface);
2366 } else {
2367 // if we will connect to this through another route, add a direct route
2368 // to it's gateway
2369 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
2370 }
2371 }
2372 if (DBG) log("Adding legacy route " + bestRoute +
2373 " for UID/PID " + uid + "/" + Binder.getCallingPid());
2374
2375 final String dst = bestRoute.getDestinationLinkAddress().toString();
2376 final String nextHop = bestRoute.hasGateway()
2377 ? bestRoute.getGateway().getHostAddress() : "";
2378 try {
2379 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2380 } catch (RemoteException | ServiceSpecificException e) {
2381 if (DBG) loge("Exception trying to add a route: " + e);
2382 return false;
2383 }
2384 return true;
2385 }
2386
2387 class DnsResolverUnsolicitedEventCallback extends
2388 IDnsResolverUnsolicitedEventListener.Stub {
2389 @Override
2390 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
2391 try {
2392 mHandler.sendMessage(mHandler.obtainMessage(
2393 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
2394 new PrivateDnsValidationUpdate(event.netId,
2395 InetAddresses.parseNumericAddress(event.ipAddress),
2396 event.hostname, event.validation)));
2397 } catch (IllegalArgumentException e) {
2398 loge("Error parsing ip address in validation event");
2399 }
2400 }
2401
2402 @Override
2403 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2404 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
2405 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2406 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2407 // event callback for certain nai. e.g. cellular. Register here to pass to
2408 // NetworkMonitor instead.
2409 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2410 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2411 // multiple NetworkMonitor registrants.
2412 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
2413 nai.networkMonitor().notifyDnsResponse(event.healthResult);
2414 }
2415 }
2416
2417 @Override
2418 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2419 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2420 event.prefixAddress, event.prefixLength));
2421 }
2422
2423 @Override
2424 public int getInterfaceVersion() {
2425 return this.VERSION;
2426 }
2427
2428 @Override
2429 public String getInterfaceHash() {
2430 return this.HASH;
2431 }
2432 }
2433
2434 @VisibleForTesting
2435 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2436 new DnsResolverUnsolicitedEventCallback();
2437
2438 private void registerDnsResolverUnsolicitedEventListener() {
2439 try {
2440 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
2441 } catch (Exception e) {
2442 loge("Error registering DnsResolver unsolicited event callback: " + e);
2443 }
2444 }
2445
2446 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
2447 @Override
2448 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
2449 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2450 uid, blockedReasons));
2451 }
2452 };
2453
2454 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
2455 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
2456 setUidBlockedReasons(uid, blockedReasons);
2457 }
2458
2459 private boolean checkAnyPermissionOf(String... permissions) {
2460 for (String permission : permissions) {
2461 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
2462 return true;
2463 }
2464 }
2465 return false;
2466 }
2467
2468 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2469 for (String permission : permissions) {
2470 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2471 return true;
2472 }
2473 }
2474 return false;
2475 }
2476
2477 private void enforceAnyPermissionOf(String... permissions) {
2478 if (!checkAnyPermissionOf(permissions)) {
2479 throw new SecurityException("Requires one of the following permissions: "
2480 + String.join(", ", permissions) + ".");
2481 }
2482 }
2483
2484 private void enforceInternetPermission() {
2485 mContext.enforceCallingOrSelfPermission(
2486 android.Manifest.permission.INTERNET,
2487 "ConnectivityService");
2488 }
2489
2490 private void enforceAccessPermission() {
2491 mContext.enforceCallingOrSelfPermission(
2492 android.Manifest.permission.ACCESS_NETWORK_STATE,
2493 "ConnectivityService");
2494 }
2495
2496 /**
2497 * Performs a strict and comprehensive check of whether a calling package is allowed to
2498 * change the state of network, as the condition differs for pre-M, M+, and
2499 * privileged/preinstalled apps. The caller is expected to have either the
2500 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2501 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2502 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2503 * permission and cannot be revoked. See http://b/23597341
2504 *
2505 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2506 * of this app will be updated to the current time.
2507 */
2508 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
2509 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2510 == PackageManager.PERMISSION_GRANTED) {
2511 return;
2512 }
2513
2514 if (callingPkg == null) {
2515 throw new SecurityException("Calling package name is null.");
2516 }
2517
2518 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2519 final int uid = mDeps.getCallingUid();
2520 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2521 callingPkg, callingAttributionTag, null /* message */);
2522
2523 if (mode == AppOpsManager.MODE_ALLOWED) {
2524 return;
2525 }
2526
2527 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2528 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2529 return;
2530 }
2531
2532 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2533 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2534 + android.Manifest.permission.WRITE_SETTINGS + ".");
2535 }
2536
2537 private void enforceSettingsPermission() {
2538 enforceAnyPermissionOf(
2539 android.Manifest.permission.NETWORK_SETTINGS,
2540 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2541 }
2542
2543 private void enforceNetworkFactoryPermission() {
2544 enforceAnyPermissionOf(
2545 android.Manifest.permission.NETWORK_FACTORY,
2546 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2547 }
2548
2549 private void enforceNetworkFactoryOrSettingsPermission() {
2550 enforceAnyPermissionOf(
2551 android.Manifest.permission.NETWORK_SETTINGS,
2552 android.Manifest.permission.NETWORK_FACTORY,
2553 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2554 }
2555
2556 private void enforceNetworkFactoryOrTestNetworksPermission() {
2557 enforceAnyPermissionOf(
2558 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2559 android.Manifest.permission.NETWORK_FACTORY,
2560 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2561 }
2562
2563 private boolean checkSettingsPermission() {
2564 return checkAnyPermissionOf(
2565 android.Manifest.permission.NETWORK_SETTINGS,
2566 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2567 }
2568
2569 private boolean checkSettingsPermission(int pid, int uid) {
2570 return PERMISSION_GRANTED == mContext.checkPermission(
2571 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2572 || PERMISSION_GRANTED == mContext.checkPermission(
2573 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
2574 }
2575
2576 private void enforceNetworkStackOrSettingsPermission() {
2577 enforceAnyPermissionOf(
2578 android.Manifest.permission.NETWORK_SETTINGS,
2579 android.Manifest.permission.NETWORK_STACK,
2580 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2581 }
2582
2583 private void enforceNetworkStackSettingsOrSetup() {
2584 enforceAnyPermissionOf(
2585 android.Manifest.permission.NETWORK_SETTINGS,
2586 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2587 android.Manifest.permission.NETWORK_STACK,
2588 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2589 }
2590
2591 private void enforceAirplaneModePermission() {
2592 enforceAnyPermissionOf(
2593 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2594 android.Manifest.permission.NETWORK_SETTINGS,
2595 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2596 android.Manifest.permission.NETWORK_STACK,
2597 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2598 }
2599
2600 private void enforceOemNetworkPreferencesPermission() {
2601 mContext.enforceCallingOrSelfPermission(
2602 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2603 "ConnectivityService");
2604 }
2605
2606 private boolean checkNetworkStackPermission() {
2607 return checkAnyPermissionOf(
2608 android.Manifest.permission.NETWORK_STACK,
2609 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2610 }
2611
2612 private boolean checkNetworkStackPermission(int pid, int uid) {
2613 return checkAnyPermissionOf(pid, uid,
2614 android.Manifest.permission.NETWORK_STACK,
2615 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2616 }
2617
2618 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2619 return checkAnyPermissionOf(pid, uid,
2620 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
2621 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2622 android.Manifest.permission.NETWORK_SETTINGS);
2623 }
2624
2625 private void enforceConnectivityRestrictedNetworksPermission() {
2626 try {
2627 mContext.enforceCallingOrSelfPermission(
2628 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2629 "ConnectivityService");
2630 return;
2631 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
2632 // TODO: Remove this fallback check after all apps have declared
2633 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2634 mContext.enforceCallingOrSelfPermission(
2635 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2636 "ConnectivityService");
2637 }
2638
2639 private void enforceKeepalivePermission() {
2640 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
2641 }
2642
2643 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2644 return PERMISSION_GRANTED == mContext.checkPermission(
2645 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2646 }
2647
2648 private void sendConnectedBroadcast(NetworkInfo info) {
2649 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2650 }
2651
2652 private void sendInetConditionBroadcast(NetworkInfo info) {
2653 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2654 }
2655
2656 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2657 Intent intent = new Intent(bcastType);
2658 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2659 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2660 if (info.isFailover()) {
2661 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2662 info.setFailover(false);
2663 }
2664 if (info.getReason() != null) {
2665 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2666 }
2667 if (info.getExtraInfo() != null) {
2668 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2669 info.getExtraInfo());
2670 }
2671 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2672 return intent;
2673 }
2674
2675 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2676 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2677 }
2678
2679 private void sendStickyBroadcast(Intent intent) {
2680 synchronized (this) {
2681 if (!mSystemReady
2682 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
2683 mInitialBroadcast = new Intent(intent);
2684 }
2685 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2686 if (VDBG) {
2687 log("sendStickyBroadcast: action=" + intent.getAction());
2688 }
2689
2690 Bundle options = null;
2691 final long ident = Binder.clearCallingIdentity();
2692 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
2693 final NetworkInfo ni = intent.getParcelableExtra(
2694 ConnectivityManager.EXTRA_NETWORK_INFO);
2695 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2696 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2697 options = opts.toBundle();
2698 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
2699 }
2700 try {
2701 mUserAllContext.sendStickyBroadcast(intent, options);
2702 } finally {
2703 Binder.restoreCallingIdentity(ident);
2704 }
2705 }
2706 }
2707
2708 /**
2709 * Called by SystemServer through ConnectivityManager when the system is ready.
2710 */
2711 @Override
2712 public void systemReady() {
2713 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
2714 throw new SecurityException("Calling Uid is not system uid.");
2715 }
2716 systemReadyInternal();
2717 }
2718
2719 /**
2720 * Called when ConnectivityService can initialize remaining components.
2721 */
2722 @VisibleForTesting
2723 public void systemReadyInternal() {
2724 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2725 // listening network request which is sent by MultipathPolicyTracker won't be added
2726 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2727 // be called after PermissionMonitor#startMonitoring().
2728 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2729 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2730 // to ensure the tracking will be initialized correctly.
2731 mPermissionMonitor.startMonitoring();
2732 mProxyTracker.loadGlobalProxy();
2733 registerDnsResolverUnsolicitedEventListener();
2734
2735 synchronized (this) {
2736 mSystemReady = true;
2737 if (mInitialBroadcast != null) {
2738 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2739 mInitialBroadcast = null;
2740 }
2741 }
2742
2743 // Create network requests for always-on networks.
2744 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu71ad4f12021-05-25 14:56:27 +08002745
2746 // Update mobile data preference if necessary.
2747 // Note that empty uid list can be skip here only because no uid rules applied before system
2748 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2749 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2750 updateMobileDataPreferredUids();
2751 }
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00002752 }
2753
2754 /**
2755 * Start listening for default data network activity state changes.
2756 */
2757 @Override
2758 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
2759 mNetworkActivityTracker.registerNetworkActivityListener(l);
2760 }
2761
2762 /**
2763 * Stop listening for default data network activity state changes.
2764 */
2765 @Override
2766 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
2767 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
2768 }
2769
2770 /**
2771 * Check whether the default network radio is currently active.
2772 */
2773 @Override
2774 public boolean isDefaultNetworkActive() {
2775 return mNetworkActivityTracker.isDefaultNetworkActive();
2776 }
2777
2778 /**
2779 * Reads the network specific MTU size from resources.
2780 * and set it on it's iface.
2781 */
2782 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2783 final String iface = newLp.getInterfaceName();
2784 final int mtu = newLp.getMtu();
2785 if (oldLp == null && mtu == 0) {
2786 // Silently ignore unset MTU value.
2787 return;
2788 }
2789 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2790 if (VDBG) log("identical MTU - not setting");
2791 return;
2792 }
2793 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
2794 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
2795 return;
2796 }
2797
2798 // Cannot set MTU without interface name
2799 if (TextUtils.isEmpty(iface)) {
2800 loge("Setting MTU size with null iface.");
2801 return;
2802 }
2803
2804 try {
2805 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
2806 mNetd.interfaceSetMtu(iface, mtu);
2807 } catch (RemoteException | ServiceSpecificException e) {
2808 loge("exception in interfaceSetMtu()" + e);
2809 }
2810 }
2811
2812 @VisibleForTesting
2813 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
2814
2815 private void updateTcpBufferSizes(String tcpBufferSizes) {
2816 String[] values = null;
2817 if (tcpBufferSizes != null) {
2818 values = tcpBufferSizes.split(",");
2819 }
2820
2821 if (values == null || values.length != 6) {
2822 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
2823 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2824 values = tcpBufferSizes.split(",");
2825 }
2826
2827 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2828
2829 try {
2830 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
2831
2832 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2833 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2834 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
2835 mCurrentTcpBufferSizes = tcpBufferSizes;
2836 } catch (RemoteException | ServiceSpecificException e) {
2837 loge("Can't set TCP buffer sizes:" + e);
2838 }
2839 }
2840
2841 @Override
2842 public int getRestoreDefaultNetworkDelay(int networkType) {
2843 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
2844 NETWORK_RESTORE_DELAY_PROP_NAME);
2845 if(restoreDefaultNetworkDelayStr != null &&
2846 restoreDefaultNetworkDelayStr.length() != 0) {
2847 try {
2848 return Integer.parseInt(restoreDefaultNetworkDelayStr);
2849 } catch (NumberFormatException e) {
2850 }
2851 }
2852 // if the system property isn't set, use the value for the apn type
2853 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2854
2855 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2856 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
2857 }
2858 return ret;
2859 }
2860
2861 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2862 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2863 final long DIAG_TIME_MS = 5000;
2864 for (NetworkAgentInfo nai : networksSortedById()) {
2865 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
2866 // Start gathering diagnostic information.
2867 netDiags.add(new NetworkDiagnostics(
2868 nai.network,
2869 new LinkProperties(nai.linkProperties), // Must be a copy.
2870 privateDnsCfg,
2871 DIAG_TIME_MS));
2872 }
2873
2874 for (NetworkDiagnostics netDiag : netDiags) {
2875 pw.println();
2876 netDiag.waitForMeasurements();
2877 netDiag.dump(pw);
2878 }
2879 }
2880
2881 @Override
2882 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2883 @Nullable String[] args) {
2884 if (!checkDumpPermission(mContext, TAG, writer)) return;
2885
2886 mPriorityDumper.dump(fd, writer, args);
2887 }
2888
2889 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2890 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2891 != PackageManager.PERMISSION_GRANTED) {
2892 pw.println("Permission Denial: can't dump " + tag + " from from pid="
2893 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
2894 + " due to missing android.permission.DUMP permission");
2895 return false;
2896 } else {
2897 return true;
2898 }
2899 }
2900
2901 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
2902 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2903
2904 if (CollectionUtils.contains(args, DIAG_ARG)) {
2905 dumpNetworkDiagnostics(pw);
2906 return;
2907 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
2908 dumpNetworks(pw);
2909 return;
2910 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
2911 dumpNetworkRequests(pw);
2912 return;
2913 }
2914
2915 pw.print("NetworkProviders for:");
2916 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2917 pw.print(" " + npi.name);
2918 }
2919 pw.println();
2920 pw.println();
2921
2922 final NetworkAgentInfo defaultNai = getDefaultNetwork();
2923 pw.print("Active default network: ");
2924 if (defaultNai == null) {
2925 pw.println("none");
2926 } else {
2927 pw.println(defaultNai.network.getNetId());
2928 }
2929 pw.println();
2930
2931 pw.print("Current per-app default networks: ");
2932 pw.increaseIndent();
2933 dumpPerAppNetworkPreferences(pw);
2934 pw.decreaseIndent();
2935 pw.println();
2936
2937 pw.println("Current Networks:");
2938 pw.increaseIndent();
2939 dumpNetworks(pw);
2940 pw.decreaseIndent();
2941 pw.println();
2942
2943 pw.println("Status for known UIDs:");
2944 pw.increaseIndent();
2945 final int size = mUidBlockedReasons.size();
2946 for (int i = 0; i < size; i++) {
2947 // Don't crash if the array is modified while dumping in bugreports.
2948 try {
2949 final int uid = mUidBlockedReasons.keyAt(i);
2950 final int blockedReasons = mUidBlockedReasons.valueAt(i);
2951 pw.println("UID=" + uid + " blockedReasons="
2952 + Integer.toHexString(blockedReasons));
2953 } catch (ArrayIndexOutOfBoundsException e) {
2954 pw.println(" ArrayIndexOutOfBoundsException");
2955 } catch (ConcurrentModificationException e) {
2956 pw.println(" ConcurrentModificationException");
2957 }
2958 }
2959 pw.println();
2960 pw.decreaseIndent();
2961
2962 pw.println("Network Requests:");
2963 pw.increaseIndent();
2964 dumpNetworkRequests(pw);
2965 pw.decreaseIndent();
2966 pw.println();
2967
2968 mLegacyTypeTracker.dump(pw);
2969
2970 pw.println();
2971 mKeepaliveTracker.dump(pw);
2972
2973 pw.println();
2974 dumpAvoidBadWifiSettings(pw);
2975
2976 pw.println();
2977
2978 if (!CollectionUtils.contains(args, SHORT_ARG)) {
2979 pw.println();
2980 pw.println("mNetworkRequestInfoLogs (most recent first):");
2981 pw.increaseIndent();
2982 mNetworkRequestInfoLogs.reverseDump(pw);
2983 pw.decreaseIndent();
2984
2985 pw.println();
2986 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2987 pw.increaseIndent();
2988 mNetworkInfoBlockingLogs.reverseDump(pw);
2989 pw.decreaseIndent();
2990
2991 pw.println();
2992 pw.println("NetTransition WakeLock activity (most recent first):");
2993 pw.increaseIndent();
2994 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2995 pw.println("total releases: " + mTotalWakelockReleases);
2996 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2997 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2998 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2999 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3000 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3001 }
3002 mWakelockLogs.reverseDump(pw);
3003
3004 pw.println();
3005 pw.println("bandwidth update requests (by uid):");
3006 pw.increaseIndent();
3007 synchronized (mBandwidthRequests) {
3008 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3009 pw.println("[" + mBandwidthRequests.keyAt(i)
3010 + "]: " + mBandwidthRequests.valueAt(i));
3011 }
3012 }
3013 pw.decreaseIndent();
3014 pw.decreaseIndent();
3015
3016 pw.println();
3017 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3018 pw.increaseIndent();
3019 mOemNetworkPreferencesLogs.reverseDump(pw);
3020 pw.decreaseIndent();
3021 }
3022
3023 pw.println();
3024
3025 pw.println();
3026 pw.println("Permission Monitor:");
3027 pw.increaseIndent();
3028 mPermissionMonitor.dump(pw);
3029 pw.decreaseIndent();
3030
3031 pw.println();
3032 pw.println("Legacy network activity:");
3033 pw.increaseIndent();
3034 mNetworkActivityTracker.dump(pw);
3035 pw.decreaseIndent();
3036 }
3037
3038 private void dumpNetworks(IndentingPrintWriter pw) {
3039 for (NetworkAgentInfo nai : networksSortedById()) {
3040 pw.println(nai.toString());
3041 pw.increaseIndent();
3042 pw.println(String.format(
3043 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3044 nai.numForegroundNetworkRequests(),
3045 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3046 nai.numBackgroundNetworkRequests(),
3047 nai.numNetworkRequests()));
3048 pw.increaseIndent();
3049 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3050 pw.println(nai.requestAt(i).toString());
3051 }
3052 pw.decreaseIndent();
3053 pw.println("Inactivity Timers:");
3054 pw.increaseIndent();
3055 nai.dumpInactivityTimers(pw);
3056 pw.decreaseIndent();
3057 pw.decreaseIndent();
3058 }
3059 }
3060
3061 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3062 pw.println("Per-App Network Preference:");
3063 pw.increaseIndent();
3064 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3065 pw.println("none");
3066 } else {
3067 pw.println(mOemNetworkPreferences.toString());
3068 }
3069 pw.decreaseIndent();
3070
3071 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3072 if (mDefaultRequest == defaultRequest) {
3073 continue;
3074 }
3075
3076 final boolean isActive = null != defaultRequest.getSatisfier();
3077 pw.println("Is per-app network active:");
3078 pw.increaseIndent();
3079 pw.println(isActive);
3080 if (isActive) {
3081 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3082 }
3083 pw.println("Tracked UIDs:");
3084 pw.increaseIndent();
3085 if (0 == defaultRequest.mRequests.size()) {
3086 pw.println("none, this should never occur.");
3087 } else {
3088 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
3089 }
3090 pw.decreaseIndent();
3091 pw.decreaseIndent();
3092 }
3093 }
3094
3095 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3096 for (NetworkRequestInfo nri : requestsSortedById()) {
3097 pw.println(nri.toString());
3098 }
3099 }
3100
3101 /**
3102 * Return an array of all current NetworkAgentInfos sorted by network id.
3103 */
3104 private NetworkAgentInfo[] networksSortedById() {
3105 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
3106 networks = mNetworkAgentInfos.toArray(networks);
3107 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
3108 return networks;
3109 }
3110
3111 /**
3112 * Return an array of all current NetworkRequest sorted by request id.
3113 */
3114 @VisibleForTesting
3115 NetworkRequestInfo[] requestsSortedById() {
3116 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
3117 requests = getNrisFromGlobalRequests().toArray(requests);
3118 // Sort the array based off the NRI containing the min requestId in its requests.
3119 Arrays.sort(requests,
3120 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3121 Comparator.comparingInt(req -> req.requestId)).requestId
3122 )
3123 );
3124 return requests;
3125 }
3126
3127 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
3128 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
3129 if (officialNai != null && officialNai.equals(nai)) return true;
3130 if (officialNai != null || VDBG) {
3131 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
3132 " - " + nai);
3133 }
3134 return false;
3135 }
3136
3137 // must be stateless - things change under us.
3138 private class NetworkStateTrackerHandler extends Handler {
3139 public NetworkStateTrackerHandler(Looper looper) {
3140 super(looper);
3141 }
3142
3143 private void maybeHandleNetworkAgentMessage(Message msg) {
3144 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3145 final NetworkAgentInfo nai = arg.first;
3146 if (!mNetworkAgentInfos.contains(nai)) {
3147 if (VDBG) {
3148 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
3149 }
3150 return;
3151 }
3152
3153 switch (msg.what) {
3154 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
3155 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
3156 if (networkCapabilities.hasConnectivityManagedCapability()) {
3157 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
3158 }
3159 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3160 // Make sure the original object is not mutated. NetworkAgent normally
3161 // makes a copy of the capabilities when sending the message through
3162 // the Messenger, but if this ever changes, not making a defensive copy
3163 // here will give attack vectors to clients using this code path.
3164 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3165 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
3166 }
3167 processCapabilitiesFromAgent(nai, networkCapabilities);
3168 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
3169 break;
3170 }
3171 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
3172 LinkProperties newLp = (LinkProperties) arg.second;
3173 processLinkPropertiesFromAgent(nai, newLp);
3174 handleUpdateLinkProperties(nai, newLp);
3175 break;
3176 }
3177 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
3178 NetworkInfo info = (NetworkInfo) arg.second;
3179 updateNetworkInfo(nai, info);
3180 break;
3181 }
3182 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
3183 updateNetworkScore(nai, (NetworkScore) arg.second);
3184 break;
3185 }
3186 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
3187 if (nai.everConnected) {
3188 loge("ERROR: cannot call explicitlySelected on already-connected network");
3189 // Note that if the NAI had been connected, this would affect the
3190 // score, and therefore would require re-mixing the score and performing
3191 // a rematch.
3192 }
3193 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3194 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
3195 // Mark the network as temporarily accepting partial connectivity so that it
3196 // will be validated (and possibly become default) even if it only provides
3197 // partial internet access. Note that if user connects to partial connectivity
3198 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3199 // out of wifi coverage) and if the same wifi is available again, the device
3200 // will auto connect to this wifi even though the wifi has "no internet".
3201 // TODO: Evaluate using a separate setting in IpMemoryStore.
3202 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
3203 break;
3204 }
3205 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
3206 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
3207 break;
3208 }
3209 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
3210 // TODO: prevent loops, e.g., if a network declares itself as underlying.
3211 if (!nai.supportsUnderlyingNetworks()) {
3212 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3213 break;
3214 }
3215
3216 final List<Network> underlying = (List<Network>) arg.second;
3217
3218 if (isLegacyLockdownNai(nai)
3219 && (underlying == null || underlying.size() != 1)) {
3220 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3221 + " must have exactly one underlying network: " + underlying);
3222 }
3223
3224 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3225 nai.declaredUnderlyingNetworks = (underlying != null)
3226 ? underlying.toArray(new Network[0]) : null;
3227
3228 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3229 if (DBG) {
3230 log(nai.toShortString() + " changed underlying networks to "
3231 + Arrays.toString(nai.declaredUnderlyingNetworks));
3232 }
3233 updateCapabilitiesForNetwork(nai);
3234 notifyIfacesChangedForNetworkStats();
3235 }
3236 break;
3237 }
3238 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3239 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3240 nai.teardownDelayMs = msg.arg1;
3241 } else {
3242 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3243 }
3244 break;
3245 }
3246 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3247 nai.setLingerDuration((int) arg.second);
3248 break;
3249 }
3250 }
3251 }
3252
3253 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3254 switch (msg.what) {
3255 default:
3256 return false;
3257 case EVENT_PROBE_STATUS_CHANGED: {
3258 final Integer netId = (Integer) msg.obj;
3259 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3260 if (nai == null) {
3261 break;
3262 }
3263 final boolean probePrivateDnsCompleted =
3264 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3265 final boolean privateDnsBroken =
3266 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3267 if (probePrivateDnsCompleted) {
3268 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3269 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
3270 updateCapabilitiesForNetwork(nai);
3271 }
3272 // Only show the notification when the private DNS is broken and the
3273 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
3274 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
3275 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3276 }
3277 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
3278 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3279 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3280 // private DNS is broken, it means this network is being reevaluated.
3281 // Either probing private DNS is not necessary any more or it hasn't been
3282 // done yet. In either case, the networkCapabilities should be updated to
3283 // reflect the new status.
3284 nai.networkCapabilities.setPrivateDnsBroken(false);
3285 updateCapabilitiesForNetwork(nai);
3286 nai.networkAgentConfig.hasShownBroken = false;
3287 }
3288 break;
3289 }
3290 case EVENT_NETWORK_TESTED: {
3291 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3292
3293 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
3294 if (nai == null) break;
3295
3296 handleNetworkTested(nai, results.mTestResult,
3297 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
3298 break;
3299 }
3300 case EVENT_PROVISIONING_NOTIFICATION: {
3301 final int netId = msg.arg2;
3302 final boolean visible = toBool(msg.arg1);
3303 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3304 // If captive portal status has changed, update capabilities or disconnect.
3305 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3306 nai.lastCaptivePortalDetected = visible;
3307 nai.everCaptivePortalDetected |= visible;
3308 if (nai.lastCaptivePortalDetected &&
3309 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3310 == getCaptivePortalMode()) {
3311 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3312 nai.onPreventAutomaticReconnect();
3313 teardownUnneededNetwork(nai);
3314 break;
3315 }
3316 updateCapabilitiesForNetwork(nai);
3317 }
3318 if (!visible) {
3319 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
3320 // notifications belong to the same network may be cleared unexpectedly.
3321 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3322 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
3323 } else {
3324 if (nai == null) {
3325 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3326 break;
3327 }
3328 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
3329 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
3330 (PendingIntent) msg.obj,
3331 nai.networkAgentConfig.explicitlySelected);
3332 }
3333 }
3334 break;
3335 }
3336 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
3337 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3338 if (nai == null) break;
3339
3340 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
3341 break;
3342 }
3343 case EVENT_CAPPORT_DATA_CHANGED: {
3344 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3345 if (nai == null) break;
3346 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
3347 break;
3348 }
3349 }
3350 return true;
3351 }
3352
3353 private void handleNetworkTested(
3354 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3355 final boolean wasPartial = nai.partialConnectivity;
3356 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3357 final boolean partialConnectivityChanged =
3358 (wasPartial != nai.partialConnectivity);
3359
3360 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3361 final boolean wasValidated = nai.lastValidated;
3362 final boolean wasDefault = isDefaultNetwork(nai);
3363
3364 if (DBG) {
3365 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3366 ? " with redirect to " + redirectUrl
3367 : "";
3368 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
3369 }
3370 if (valid != nai.lastValidated) {
3371 final int oldScore = nai.getCurrentScore();
3372 nai.lastValidated = valid;
3373 nai.everValidated |= valid;
3374 updateCapabilities(oldScore, nai, nai.networkCapabilities);
3375 if (valid) {
3376 handleFreshlyValidatedNetwork(nai);
3377 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3378 // LOST_INTERNET notifications if network becomes valid.
3379 mNotifier.clearNotification(nai.network.getNetId(),
3380 NotificationType.NO_INTERNET);
3381 mNotifier.clearNotification(nai.network.getNetId(),
3382 NotificationType.LOST_INTERNET);
3383 mNotifier.clearNotification(nai.network.getNetId(),
3384 NotificationType.PARTIAL_CONNECTIVITY);
3385 mNotifier.clearNotification(nai.network.getNetId(),
3386 NotificationType.PRIVATE_DNS_BROKEN);
3387 // If network becomes valid, the hasShownBroken should be reset for
3388 // that network so that the notification will be fired when the private
3389 // DNS is broken again.
3390 nai.networkAgentConfig.hasShownBroken = false;
3391 }
3392 } else if (partialConnectivityChanged) {
3393 updateCapabilitiesForNetwork(nai);
3394 }
3395 updateInetCondition(nai);
3396 // Let the NetworkAgent know the state of its network
3397 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
3398 nai.onValidationStatusChanged(
3399 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3400 redirectUrl);
3401
3402 // If NetworkMonitor detects partial connectivity before
3403 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3404 // immediately. Re-notify partial connectivity silently if no internet
3405 // notification already there.
3406 if (!wasPartial && nai.partialConnectivity) {
3407 // Remove delayed message if there is a pending message.
3408 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3409 handlePromptUnvalidated(nai.network);
3410 }
3411
3412 if (wasValidated && !nai.lastValidated) {
3413 handleNetworkUnvalidated(nai);
3414 }
3415 }
3416
3417 private int getCaptivePortalMode() {
3418 return Settings.Global.getInt(mContext.getContentResolver(),
3419 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3420 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
3421 }
3422
3423 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3424 switch (msg.what) {
3425 default:
3426 return false;
3427 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3428 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3429 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3430 handleLingerComplete(nai);
3431 }
3432 break;
3433 }
3434 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3435 handleNetworkAgentRegistered(msg);
3436 break;
3437 }
3438 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3439 handleNetworkAgentDisconnected(msg);
3440 break;
3441 }
3442 }
3443 return true;
3444 }
3445
3446 @Override
3447 public void handleMessage(Message msg) {
3448 if (!maybeHandleNetworkMonitorMessage(msg)
3449 && !maybeHandleNetworkAgentInfoMessage(msg)) {
3450 maybeHandleNetworkAgentMessage(msg);
3451 }
3452 }
3453 }
3454
3455 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
3456 private final int mNetId;
3457 private final AutodestructReference<NetworkAgentInfo> mNai;
3458
3459 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
3460 mNetId = nai.network.getNetId();
3461 mNai = new AutodestructReference<>(nai);
3462 }
3463
3464 @Override
3465 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3466 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
3467 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
3468 }
3469
3470 @Override
3471 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
3472 // Legacy version of notifyNetworkTestedWithExtras.
3473 // Would only be called if the system has a NetworkStack module older than the
3474 // framework, which does not happen in practice.
3475 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
3476 }
3477
3478 @Override
3479 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
3480 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3481 // the same looper so messages will be processed in sequence.
3482 final Message msg = mTrackerHandler.obtainMessage(
3483 EVENT_NETWORK_TESTED,
3484 new NetworkTestedResults(
3485 mNetId, p.result, p.timestampMillis, p.redirectUrl));
3486 mTrackerHandler.sendMessage(msg);
3487
3488 // Invoke ConnectivityReport generation for this Network test event.
3489 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3490 if (nai == null) return;
3491
3492 final PersistableBundle extras = new PersistableBundle();
3493 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3494 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3495 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3496
3497 ConnectivityReportEvent reportEvent =
3498 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3499 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3500 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
3501 mConnectivityDiagnosticsHandler.sendMessage(m);
3502 }
3503
3504 @Override
3505 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3506 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3507 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
3508 0, mNetId, PrivateDnsConfig.fromParcel(config)));
3509 }
3510
3511 @Override
3512 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3513 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3514 EVENT_PROBE_STATUS_CHANGED,
3515 probesCompleted, probesSucceeded, new Integer(mNetId)));
3516 }
3517
3518 @Override
3519 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3520 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3521 EVENT_CAPPORT_DATA_CHANGED,
3522 0, mNetId, data));
3523 }
3524
3525 @Override
3526 public void showProvisioningNotification(String action, String packageName) {
3527 final Intent intent = new Intent(action);
3528 intent.setPackage(packageName);
3529
3530 final PendingIntent pendingIntent;
3531 // Only the system server can register notifications with package "android"
3532 final long token = Binder.clearCallingIdentity();
3533 try {
3534 pendingIntent = PendingIntent.getBroadcast(
3535 mContext,
3536 0 /* requestCode */,
3537 intent,
3538 PendingIntent.FLAG_IMMUTABLE);
3539 } finally {
3540 Binder.restoreCallingIdentity(token);
3541 }
3542 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3543 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
3544 mNetId, pendingIntent));
3545 }
3546
3547 @Override
3548 public void hideProvisioningNotification() {
3549 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3550 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
3551 }
3552
3553 @Override
3554 public void notifyDataStallSuspected(DataStallReportParcelable p) {
3555 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
3556 }
3557
3558 @Override
3559 public int getInterfaceVersion() {
3560 return this.VERSION;
3561 }
3562
3563 @Override
3564 public String getInterfaceHash() {
3565 return this.HASH;
3566 }
3567 }
3568
3569 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
3570 log("Data stall detected with methods: " + p.detectionMethod);
3571
3572 final PersistableBundle extras = new PersistableBundle();
3573 int detectionMethod = 0;
3574 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3575 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3576 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3577 }
3578 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3579 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3580 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3581 p.tcpMetricsCollectionPeriodMillis);
3582 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
3583 }
3584
3585 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
3586 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
3587 new Pair<>(p.timestampMillis, extras));
3588
3589 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3590 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3591 // the cost of going through two handlers.
3592 mConnectivityDiagnosticsHandler.sendMessage(msg);
3593 }
3594
3595 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3596 return (p.detectionMethod & detectionMethod) != 0;
3597 }
3598
3599 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3600 return isPrivateDnsValidationRequired(nai.networkCapabilities);
3601 }
3602
3603 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3604 if (nai == null) return;
3605 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3606 // in order to restart a validation pass from within netd.
3607 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3608 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
3609 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3610 }
3611 }
3612
3613 private void handlePrivateDnsSettingsChanged() {
3614 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3615
3616 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
3617 handlePerNetworkPrivateDnsConfig(nai, cfg);
3618 if (networkRequiresPrivateDnsValidation(nai)) {
3619 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3620 }
3621 }
3622 }
3623
3624 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3625 // Private DNS only ever applies to networks that might provide
3626 // Internet access and therefore also require validation.
3627 if (!networkRequiresPrivateDnsValidation(nai)) return;
3628
3629 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
3630 // schedule DNS resolutions. If a DNS resolution is required the
3631 // result will be sent back to us.
3632 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
3633
3634 // With Private DNS bypass support, we can proceed to update the
3635 // Private DNS config immediately, even if we're in strict mode
3636 // and have not yet resolved the provider name into a set of IPs.
3637 updatePrivateDns(nai, cfg);
3638 }
3639
3640 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3641 mDnsManager.updatePrivateDns(nai.network, newCfg);
3642 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3643 }
3644
3645 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3646 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3647 if (nai == null) {
3648 return;
3649 }
3650 mDnsManager.updatePrivateDnsValidation(update);
3651 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3652 }
3653
3654 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
3655 int prefixLength) {
3656 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3657 if (nai == null) return;
3658
3659 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3660 netId, operation, prefixAddress, prefixLength));
3661
3662 IpPrefix prefix = null;
3663 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
3664 try {
3665 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
3666 prefixLength);
3667 } catch (IllegalArgumentException e) {
3668 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
3669 return;
3670 }
3671 }
3672
3673 nai.clatd.setNat64PrefixFromDns(prefix);
3674 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3675 }
3676
3677 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
3678 @Nullable final CaptivePortalData data) {
3679 nai.capportApiData = data;
3680 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3681 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3682 }
3683
3684 /**
3685 * Updates the inactivity state from the network requests inside the NAI.
3686 * @param nai the agent info to update
3687 * @param now the timestamp of the event causing this update
3688 * @return whether the network was inactive as a result of this update
3689 */
3690 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3691 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3692 // 2. If the network was inactive and there are now requests, unset inactive.
3693 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
3694 // one lingered request, set inactive.
3695 nai.updateInactivityTimer();
3696 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
3697 if (DBG) log("Unsetting inactive " + nai.toShortString());
3698 nai.unsetInactive();
3699 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
3700 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
3701 if (DBG) {
3702 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3703 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
3704 }
3705 nai.setInactive();
3706 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
3707 return true;
3708 }
3709 return false;
3710 }
3711
3712 private void handleNetworkAgentRegistered(Message msg) {
3713 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3714 if (!mNetworkAgentInfos.contains(nai)) {
3715 return;
3716 }
3717
3718 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3719 if (VDBG) log("NetworkAgent registered");
3720 } else {
3721 loge("Error connecting NetworkAgent");
3722 mNetworkAgentInfos.remove(nai);
3723 if (nai != null) {
3724 final boolean wasDefault = isDefaultNetwork(nai);
3725 synchronized (mNetworkForNetId) {
3726 mNetworkForNetId.remove(nai.network.getNetId());
3727 }
3728 mNetIdManager.releaseNetId(nai.network.getNetId());
3729 // Just in case.
3730 mLegacyTypeTracker.remove(nai, wasDefault);
3731 }
3732 }
3733 }
3734
3735 private void handleNetworkAgentDisconnected(Message msg) {
3736 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3737 if (mNetworkAgentInfos.contains(nai)) {
3738 disconnectAndDestroyNetwork(nai);
3739 }
3740 }
3741
3742 // Destroys a network, remove references to it from the internal state managed by
3743 // ConnectivityService, free its interfaces and clean up.
3744 // Must be called on the Handler thread.
3745 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
3746 ensureRunningOnConnectivityServiceThread();
3747 if (DBG) {
3748 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
3749 }
3750 // Clear all notifications of this network.
3751 mNotifier.clearNotification(nai.network.getNetId());
3752 // A network agent has disconnected.
3753 // TODO - if we move the logic to the network agent (have them disconnect
3754 // because they lost all their requests or because their score isn't good)
3755 // then they would disconnect organically, report their new state and then
3756 // disconnect the channel.
3757 if (nai.networkInfo.isConnected()) {
3758 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3759 null, null);
3760 }
3761 final boolean wasDefault = isDefaultNetwork(nai);
3762 if (wasDefault) {
3763 mDefaultInetConditionPublished = 0;
3764 }
3765 notifyIfacesChangedForNetworkStats();
3766 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3767 // by other networks that are already connected. Perhaps that can be done by
3768 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3769 // of rematchAllNetworksAndRequests
3770 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3771 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
3772
3773 mQosCallbackTracker.handleNetworkReleased(nai.network);
3774 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3775 // Disable wakeup packet monitoring for each interface.
3776 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3777 }
3778 nai.networkMonitor().notifyNetworkDisconnected();
3779 mNetworkAgentInfos.remove(nai);
3780 nai.clatd.update();
3781 synchronized (mNetworkForNetId) {
3782 // Remove the NetworkAgent, but don't mark the netId as
3783 // available until we've told netd to delete it below.
3784 mNetworkForNetId.remove(nai.network.getNetId());
3785 }
3786 propagateUnderlyingNetworkCapabilities(nai.network);
3787 // Remove all previously satisfied requests.
3788 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3789 final NetworkRequest request = nai.requestAt(i);
3790 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3791 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
3792 if (currentNetwork != null
3793 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
3794 // uid rules for this network will be removed in destroyNativeNetwork(nai).
3795 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3796 // rematch not to keep disconnected agents instead of setting it here ; this
3797 // will also allow removing updating the offers below.
3798 nri.setSatisfier(null, null);
3799 for (final NetworkOfferInfo noi : mNetworkOffers) {
3800 informOffer(nri, noi.offer, mNetworkRanker);
3801 }
3802
3803 if (mDefaultRequest == nri) {
3804 // TODO : make battery stats aware that since 2013 multiple interfaces may be
3805 // active at the same time. For now keep calling this with the default
3806 // network, because while incorrect this is the closest to the old (also
3807 // incorrect) behavior.
3808 mNetworkActivityTracker.updateDataActivityTracking(
3809 null /* newNetwork */, nai);
3810 ensureNetworkTransitionWakelock(nai.toShortString());
3811 }
3812 }
3813 }
3814 nai.clearInactivityState();
3815 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
3816 // Currently, deleting it breaks tests that check for the default network disconnecting.
3817 // Find out why, fix the rematch code, and delete this.
3818 mLegacyTypeTracker.remove(nai, wasDefault);
3819 rematchAllNetworksAndRequests();
3820 mLingerMonitor.noteDisconnect(nai);
3821
3822 // Immediate teardown.
3823 if (nai.teardownDelayMs == 0) {
3824 destroyNetwork(nai);
3825 return;
3826 }
3827
3828 // Delayed teardown.
3829 try {
3830 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3831 } catch (RemoteException e) {
3832 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3833 }
3834 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3835 }
3836
3837 private void destroyNetwork(NetworkAgentInfo nai) {
3838 if (nai.created) {
3839 // Tell netd to clean up the configuration for this network
3840 // (routing rules, DNS, etc).
3841 // This may be slow as it requires a lot of netd shelling out to ip and
3842 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3843 // after we've rematched networks with requests (which might change the default
3844 // network or service a new request from an app), so network traffic isn't interrupted
3845 // for an unnecessarily long time.
3846 destroyNativeNetwork(nai);
3847 mDnsManager.removeNetwork(nai.network);
3848 }
3849 mNetIdManager.releaseNetId(nai.network.getNetId());
3850 nai.onNetworkDestroyed();
3851 }
3852
3853 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
3854 try {
3855 // This should never fail. Specifying an already in use NetID will cause failure.
3856 final NativeNetworkConfig config;
3857 if (nai.isVPN()) {
3858 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
3859 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
3860 return false;
3861 }
3862 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3863 INetd.PERMISSION_NONE,
3864 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3865 getVpnType(nai));
3866 } else {
3867 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3868 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3869 VpnManager.TYPE_VPN_NONE);
3870 }
3871 mNetd.networkCreate(config);
3872 mDnsResolver.createNetworkCache(nai.network.getNetId());
3873 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3874 nai.networkCapabilities.getTransportTypes());
3875 return true;
3876 } catch (RemoteException | ServiceSpecificException e) {
3877 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
3878 return false;
3879 }
3880 }
3881
3882 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
3883 try {
3884 mNetd.networkDestroy(nai.network.getNetId());
3885 } catch (RemoteException | ServiceSpecificException e) {
3886 loge("Exception destroying network(networkDestroy): " + e);
3887 }
3888 try {
3889 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
3890 } catch (RemoteException | ServiceSpecificException e) {
3891 loge("Exception destroying network: " + e);
3892 }
3893 }
3894
3895 // If this method proves to be too slow then we can maintain a separate
3896 // pendingIntent => NetworkRequestInfo map.
3897 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3898 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3899 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3900 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3901 if (existingPendingIntent != null &&
3902 existingPendingIntent.intentFilterEquals(pendingIntent)) {
3903 return entry.getValue();
3904 }
3905 }
3906 return null;
3907 }
3908
3909 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
3910 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3911 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3912 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3913 final NetworkRequestInfo existingRequest =
3914 findExistingNetworkRequestInfo(nri.mPendingIntent);
3915 if (existingRequest != null) { // remove the existing request.
3916 if (DBG) {
3917 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3918 + nri.mRequests.get(0) + " because their intents matched.");
3919 }
3920 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
3921 /* callOnUnavailable */ false);
3922 }
3923 handleRegisterNetworkRequest(nri);
3924 }
3925
3926 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
3927 handleRegisterNetworkRequests(Collections.singleton(nri));
3928 }
3929
3930 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
3931 ensureRunningOnConnectivityServiceThread();
3932 for (final NetworkRequestInfo nri : nris) {
3933 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3934 for (final NetworkRequest req : nri.mRequests) {
3935 mNetworkRequests.put(req, nri);
3936 // TODO: Consider update signal strength for other types.
3937 if (req.isListen()) {
3938 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3939 if (req.networkCapabilities.hasSignalStrength()
3940 && network.satisfiesImmutableCapabilitiesOf(req)) {
3941 updateSignalStrengthThresholds(network, "REGISTER", req);
3942 }
3943 }
3944 }
3945 }
3946 // If this NRI has a satisfier already, it is replacing an older request that
3947 // has been removed. Track it.
3948 final NetworkRequest activeRequest = nri.getActiveRequest();
3949 if (null != activeRequest) {
3950 // If there is an active request, then for sure there is a satisfier.
3951 nri.getSatisfier().addRequest(activeRequest);
3952 }
3953 }
3954
3955 rematchAllNetworksAndRequests();
3956
3957 // Requests that have not been matched to a network will not have been sent to the
3958 // providers, because the old satisfier and the new satisfier are the same (null in this
3959 // case). Send these requests to the providers.
3960 for (final NetworkRequestInfo nri : nris) {
3961 for (final NetworkOfferInfo noi : mNetworkOffers) {
3962 informOffer(nri, noi.offer, mNetworkRanker);
3963 }
3964 }
3965 }
3966
3967 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
3968 final int callingUid) {
3969 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3970 if (nri != null) {
3971 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
3972 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
3973 handleReleaseNetworkRequest(
3974 nri.mRequests.get(0),
3975 callingUid,
3976 /* callOnUnavailable */ false);
3977 }
3978 }
3979
3980 // Determines whether the network is the best (or could become the best, if it validated), for
3981 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3982 // on the value of reason:
3983 //
3984 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3985 // then it should be torn down.
3986 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3987 // then it should be lingered.
3988 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3989 ensureRunningOnConnectivityServiceThread();
3990
3991 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
3992 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
3993 return false;
3994 }
3995
3996 final int numRequests;
3997 switch (reason) {
3998 case TEARDOWN:
3999 numRequests = nai.numRequestNetworkRequests();
4000 break;
4001 case LINGER:
4002 numRequests = nai.numForegroundNetworkRequests();
4003 break;
4004 default:
4005 Log.wtf(TAG, "Invalid reason. Cannot happen.");
4006 return true;
4007 }
4008
4009 if (numRequests > 0) return false;
4010
4011 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4012 if (reason == UnneededFor.LINGER
4013 && !nri.isMultilayerRequest()
4014 && nri.mRequests.get(0).isBackgroundRequest()) {
4015 // Background requests don't affect lingering.
4016 continue;
4017 }
4018
4019 if (isNetworkPotentialSatisfier(nai, nri)) {
4020 return false;
4021 }
4022 }
4023 return true;
4024 }
4025
4026 private boolean isNetworkPotentialSatisfier(
4027 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4028 // listen requests won't keep up a network satisfying it. If this is not a multilayer
4029 // request, return immediately. For multilayer requests, check to see if any of the
4030 // multilayer requests may have a potential satisfier.
4031 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4032 || nri.mRequests.get(0).isListenForBest())) {
4033 return false;
4034 }
4035 for (final NetworkRequest req : nri.mRequests) {
4036 // This multilayer listen request is satisfied therefore no further requests need to be
4037 // evaluated deeming this network not a potential satisfier.
4038 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
4039 return false;
4040 }
4041 // As non-multilayer listen requests have already returned, the below would only happen
4042 // for a multilayer request therefore continue to the next request if available.
4043 if (req.isListen() || req.isListenForBest()) {
4044 continue;
4045 }
4046 // If this Network is already the highest scoring Network for a request, or if
4047 // there is hope for it to become one if it validated, then it is needed.
4048 if (candidate.satisfies(req)) {
4049 // As soon as a network is found that satisfies a request, return. Specifically for
4050 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4051 // is important so as to not evaluate lower priority requests further in
4052 // nri.mRequests.
4053 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4054 ? nri.getSatisfier() : null;
4055 // Note that this catches two important cases:
4056 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4057 // is currently satisfying the request. This is desirable when
4058 // cellular ends up validating but WiFi does not.
4059 // 2. Unvalidated WiFi will not be reaped when validated cellular
4060 // is currently satisfying the request. This is desirable when
4061 // WiFi ends up validating and out scoring cellular.
4062 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
4063 }
4064 }
4065
4066 return false;
4067 }
4068
4069 private NetworkRequestInfo getNriForAppRequest(
4070 NetworkRequest request, int callingUid, String requestedOperation) {
4071 // Looking up the app passed param request in mRequests isn't possible since it may return
4072 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4073 // do the lookup since that will also find per-app default managed requests.
4074 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4075 // to avoid potential race conditions when validating a package->uid mapping when sending
4076 // the callback on the very low-chance that an application shuts down prior to the callback
4077 // being sent.
4078 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4079 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
4080
4081 if (nri != null) {
4082 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
4083 log(String.format("UID %d attempted to %s for unowned request %s",
4084 callingUid, requestedOperation, nri));
4085 return null;
4086 }
4087 }
4088
4089 return nri;
4090 }
4091
4092 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4093 final String callingMethod) {
4094 if (nri.isMultilayerRequest()) {
4095 throw new IllegalStateException(
4096 callingMethod + " does not support multilayer requests.");
4097 }
4098 }
4099
4100 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4101 ensureRunningOnConnectivityServiceThread();
4102 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4103 // single NetworkRequest and thus does not apply to multilayer requests.
4104 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4105 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
4106 return;
4107 }
4108 if (nri.isBeingSatisfied()) {
4109 return;
4110 }
4111 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4112 log("releasing " + nri.mRequests.get(0) + " (timeout)");
4113 }
4114 handleRemoveNetworkRequest(nri);
4115 callCallbackForRequest(
4116 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4117 }
4118
4119 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4120 final int callingUid,
4121 final boolean callOnUnavailable) {
4122 final NetworkRequestInfo nri =
4123 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4124 if (nri == null) {
4125 return;
4126 }
4127 if (VDBG || (DBG && request.isRequest())) {
4128 log("releasing " + request + " (release request)");
4129 }
4130 handleRemoveNetworkRequest(nri);
4131 if (callOnUnavailable) {
4132 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4133 }
4134 }
4135
4136 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4137 ensureRunningOnConnectivityServiceThread();
4138 nri.unlinkDeathRecipient();
4139 for (final NetworkRequest req : nri.mRequests) {
4140 mNetworkRequests.remove(req);
4141 if (req.isListen()) {
4142 removeListenRequestFromNetworks(req);
4143 }
4144 }
4145 if (mDefaultNetworkRequests.remove(nri)) {
4146 // If this request was one of the defaults, then the UID rules need to be updated
4147 // WARNING : if the app(s) for which this network request is the default are doing
4148 // traffic, this will kill their connected sockets, even if an equivalent request
4149 // is going to be reinstated right away ; unconnected traffic will go on the default
4150 // until the new default is set, which will happen very soon.
4151 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4152 // remove ranges for those requests that won't have a replacement
4153 final NetworkAgentInfo satisfier = nri.getSatisfier();
4154 if (null != satisfier) {
4155 try {
4156 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
4157 toUidRangeStableParcels(nri.getUids()));
4158 } catch (RemoteException e) {
4159 loge("Exception setting network preference default network", e);
4160 }
4161 }
4162 }
4163 nri.decrementRequestCount();
4164 mNetworkRequestInfoLogs.log("RELEASE " + nri);
4165
4166 if (null != nri.getActiveRequest()) {
4167 if (!nri.getActiveRequest().isListen()) {
4168 removeSatisfiedNetworkRequestFromNetwork(nri);
4169 } else {
4170 nri.setSatisfier(null, null);
4171 }
4172 }
4173
4174 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4175 // needed for this offer.
4176 for (final NetworkOfferInfo noi : mNetworkOffers) {
4177 for (final NetworkRequest req : nri.mRequests) {
4178 if (req.isRequest() && noi.offer.neededFor(req)) {
4179 noi.offer.onNetworkUnneeded(req);
4180 }
4181 }
4182 }
4183 }
4184
4185 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4186 for (final NetworkRequestInfo nri : nris) {
4187 if (mDefaultRequest == nri) {
4188 // Make sure we never remove the default request.
4189 continue;
4190 }
4191 handleRemoveNetworkRequest(nri);
4192 }
4193 }
4194
4195 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4196 // listens don't have a singular affected Network. Check all networks to see
4197 // if this listen request applies and remove it.
4198 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4199 nai.removeRequest(req.requestId);
4200 if (req.networkCapabilities.hasSignalStrength()
4201 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4202 updateSignalStrengthThresholds(nai, "RELEASE", req);
4203 }
4204 }
4205 }
4206
4207 /**
4208 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4209 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4210 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4211 */
4212 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4213 boolean wasKept = false;
4214 final NetworkAgentInfo nai = nri.getSatisfier();
4215 if (nai != null) {
4216 final int requestLegacyType = nri.getActiveRequest().legacyType;
4217 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4218 nai.removeRequest(nri.getActiveRequest().requestId);
4219 if (VDBG || DDBG) {
4220 log(" Removing from current network " + nai.toShortString()
4221 + ", leaving " + nai.numNetworkRequests() + " requests.");
4222 }
4223 // If there are still lingered requests on this network, don't tear it down,
4224 // but resume lingering instead.
4225 final long now = SystemClock.elapsedRealtime();
4226 if (updateInactivityState(nai, now)) {
4227 notifyNetworkLosing(nai, now);
4228 }
4229 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4230 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4231 teardownUnneededNetwork(nai);
4232 } else {
4233 wasKept = true;
4234 }
4235 nri.setSatisfier(null, null);
4236 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4237 // Went from foreground to background.
4238 updateCapabilitiesForNetwork(nai);
4239 }
4240
4241 // Maintain the illusion. When this request arrived, we might have pretended
4242 // that a network connected to serve it, even though the network was already
4243 // connected. Now that this request has gone away, we might have to pretend
4244 // that the network disconnected. LegacyTypeTracker will generate that
4245 // phantom disconnect for this type.
4246 if (requestLegacyType != TYPE_NONE) {
4247 boolean doRemove = true;
4248 if (wasKept) {
4249 // check if any of the remaining requests for this network are for the
4250 // same legacy type - if so, don't remove the nai
4251 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4252 NetworkRequest otherRequest = nai.requestAt(i);
4253 if (otherRequest.legacyType == requestLegacyType
4254 && otherRequest.isRequest()) {
4255 if (DBG) log(" still have other legacy request - leaving");
4256 doRemove = false;
4257 }
4258 }
4259 }
4260
4261 if (doRemove) {
4262 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
4263 }
4264 }
4265 }
4266 }
4267
4268 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4269 return checkAnyPermissionOf(
4270 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4271 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4272 }
4273
4274 @Override
4275 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4276 enforceNetworkStackSettingsOrSetup();
4277 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
4278 encodeBool(accept), encodeBool(always), network));
4279 }
4280
4281 @Override
4282 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4283 enforceNetworkStackSettingsOrSetup();
4284 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4285 encodeBool(accept), encodeBool(always), network));
4286 }
4287
4288 @Override
4289 public void setAvoidUnvalidated(Network network) {
4290 enforceNetworkStackSettingsOrSetup();
4291 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4292 }
4293
4294 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4295 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4296 " accept=" + accept + " always=" + always);
4297
4298 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4299 if (nai == null) {
4300 // Nothing to do.
4301 return;
4302 }
4303
4304 if (nai.everValidated) {
4305 // The network validated while the dialog box was up. Take no action.
4306 return;
4307 }
4308
4309 if (!nai.networkAgentConfig.explicitlySelected) {
4310 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
4311 }
4312
4313 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4314 nai.networkAgentConfig.acceptUnvalidated = accept;
4315 // If network becomes partial connectivity and user already accepted to use this
4316 // network, we should respect the user's option and don't need to popup the
4317 // PARTIAL_CONNECTIVITY notification to user again.
4318 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4319 nai.updateScoreForNetworkAgentUpdate();
4320 rematchAllNetworksAndRequests();
4321 }
4322
4323 if (always) {
4324 nai.onSaveAcceptUnvalidated(accept);
4325 }
4326
4327 if (!accept) {
4328 // Tell the NetworkAgent to not automatically reconnect to the network.
4329 nai.onPreventAutomaticReconnect();
4330 // Teardown the network.
4331 teardownUnneededNetwork(nai);
4332 }
4333
4334 }
4335
4336 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4337 boolean always) {
4338 if (DBG) {
4339 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4340 + " always=" + always);
4341 }
4342
4343 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4344 if (nai == null) {
4345 // Nothing to do.
4346 return;
4347 }
4348
4349 if (nai.lastValidated) {
4350 // The network validated while the dialog box was up. Take no action.
4351 return;
4352 }
4353
4354 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4355 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4356 }
4357
4358 // TODO: Use the current design or save the user choice into IpMemoryStore.
4359 if (always) {
4360 nai.onSaveAcceptUnvalidated(accept);
4361 }
4362
4363 if (!accept) {
4364 // Tell the NetworkAgent to not automatically reconnect to the network.
4365 nai.onPreventAutomaticReconnect();
4366 // Tear down the network.
4367 teardownUnneededNetwork(nai);
4368 } else {
4369 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4370 // result in a partial connectivity result which will be processed by
4371 // maybeHandleNetworkMonitorMessage.
4372 //
4373 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4374 // per network. Therefore, NetworkMonitor may still do https probe.
4375 nai.networkMonitor().setAcceptPartialConnectivity();
4376 }
4377 }
4378
4379 private void handleSetAvoidUnvalidated(Network network) {
4380 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4381 if (nai == null || nai.lastValidated) {
4382 // Nothing to do. The network either disconnected or revalidated.
4383 return;
4384 }
4385 if (!nai.avoidUnvalidated) {
4386 nai.avoidUnvalidated = true;
4387 nai.updateScoreForNetworkAgentUpdate();
4388 rematchAllNetworksAndRequests();
4389 }
4390 }
4391
4392 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
4393 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
4394 mHandler.sendMessageDelayed(
4395 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4396 PROMPT_UNVALIDATED_DELAY_MS);
4397 }
4398
4399 @Override
4400 public void startCaptivePortalApp(Network network) {
4401 enforceNetworkStackOrSettingsPermission();
4402 mHandler.post(() -> {
4403 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4404 if (nai == null) return;
4405 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
4406 nai.networkMonitor().launchCaptivePortalApp();
4407 });
4408 }
4409
4410 /**
4411 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4412 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
4413 * @param network Network on which the captive portal was detected.
4414 * @param appExtras Bundle to use as intent extras for the captive portal application.
4415 * Must be treated as opaque to avoid preventing the captive portal app to
4416 * update its arguments.
4417 */
4418 @Override
4419 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
4420 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4421 "ConnectivityService");
4422
4423 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4424 appIntent.putExtras(appExtras);
4425 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4426 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
4427 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4428
4429 final long token = Binder.clearCallingIdentity();
4430 try {
4431 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4432 } finally {
4433 Binder.restoreCallingIdentity(token);
4434 }
4435 }
4436
4437 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4438 private final Network mNetwork;
4439
4440 private CaptivePortalImpl(Network network) {
4441 mNetwork = network;
4442 }
4443
4444 @Override
4445 public void appResponse(final int response) {
4446 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4447 enforceSettingsPermission();
4448 }
4449
4450 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4451 if (nm == null) return;
4452 nm.notifyCaptivePortalAppFinished(response);
4453 }
4454
4455 @Override
4456 public void appRequest(final int request) {
4457 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4458 if (nm == null) return;
4459
4460 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
4461 checkNetworkStackPermission();
4462 nm.forceReevaluation(mDeps.getCallingUid());
4463 }
4464 }
4465
4466 @Nullable
4467 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4468 // getNetworkAgentInfoForNetwork is thread-safe
4469 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4470 if (nai == null) return null;
4471
4472 // nai.networkMonitor() is thread-safe
4473 return nai.networkMonitor();
4474 }
4475 }
4476
4477 public boolean avoidBadWifi() {
4478 return mMultinetworkPolicyTracker.getAvoidBadWifi();
4479 }
4480
4481 /**
4482 * Return whether the device should maintain continuous, working connectivity by switching away
4483 * from WiFi networks having no connectivity.
4484 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4485 */
4486 public boolean shouldAvoidBadWifi() {
4487 if (!checkNetworkStackPermission()) {
4488 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4489 }
4490 return avoidBadWifi();
4491 }
4492
4493 private void updateAvoidBadWifi() {
4494 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4495 nai.updateScoreForNetworkAgentUpdate();
4496 }
4497 rematchAllNetworksAndRequests();
4498 }
4499
4500 // TODO: Evaluate whether this is of interest to other consumers of
4501 // MultinetworkPolicyTracker and worth moving out of here.
4502 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
4503 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
4504 if (!configRestrict) {
4505 pw.println("Bad Wi-Fi avoidance: unrestricted");
4506 return;
4507 }
4508
4509 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4510 pw.increaseIndent();
4511 pw.println("Config restrict: " + configRestrict);
4512
4513 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
4514 String description;
4515 // Can't use a switch statement because strings are legal case labels, but null is not.
4516 if ("0".equals(value)) {
4517 description = "get stuck";
4518 } else if (value == null) {
4519 description = "prompt";
4520 } else if ("1".equals(value)) {
4521 description = "avoid";
4522 } else {
4523 description = value + " (?)";
4524 }
4525 pw.println("User setting: " + description);
4526 pw.println("Network overrides:");
4527 pw.increaseIndent();
4528 for (NetworkAgentInfo nai : networksSortedById()) {
4529 if (nai.avoidUnvalidated) {
4530 pw.println(nai.toShortString());
4531 }
4532 }
4533 pw.decreaseIndent();
4534 pw.decreaseIndent();
4535 }
4536
4537 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4538 // unify the method.
4539 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4540 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4541 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4542 return settingsComponent != null
4543 ? settingsComponent.getPackageName() : "com.android.settings";
4544 }
4545
4546 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
4547 final String action;
4548 final boolean highPriority;
4549 switch (type) {
4550 case NO_INTERNET:
4551 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
4552 // High priority because it is only displayed for explicitly selected networks.
4553 highPriority = true;
4554 break;
4555 case PRIVATE_DNS_BROKEN:
4556 action = Settings.ACTION_WIRELESS_SETTINGS;
4557 // High priority because we should let user know why there is no internet.
4558 highPriority = true;
4559 break;
4560 case LOST_INTERNET:
4561 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
4562 // High priority because it could help the user avoid unexpected data usage.
4563 highPriority = true;
4564 break;
4565 case PARTIAL_CONNECTIVITY:
4566 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
4567 // Don't bother the user with a high-priority notification if the network was not
4568 // explicitly selected by the user.
4569 highPriority = nai.networkAgentConfig.explicitlySelected;
4570 break;
4571 default:
4572 Log.wtf(TAG, "Unknown notification type " + type);
4573 return;
4574 }
4575
4576 Intent intent = new Intent(action);
4577 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
4578 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
4579 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4580 // Some OEMs have their own Settings package. Thus, need to get the current using
4581 // Settings package name instead of just use default name "com.android.settings".
4582 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4583 intent.setClassName(settingsPkgName,
4584 settingsPkgName + ".wifi.WifiNoInternetDialog");
4585 }
4586
4587 PendingIntent pendingIntent = PendingIntent.getActivity(
4588 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
4589 0 /* requestCode */,
4590 intent,
4591 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
4592
4593 mNotifier.showNotification(
4594 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
4595 }
4596
4597 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4598 // Don't prompt if the network is validated, and don't prompt on captive portals
4599 // because we're already prompting the user to sign in.
4600 if (nai.everValidated || nai.everCaptivePortalDetected) {
4601 return false;
4602 }
4603
4604 // If a network has partial connectivity, always prompt unless the user has already accepted
4605 // partial connectivity and selected don't ask again. This ensures that if the device
4606 // automatically connects to a network that has partial Internet access, the user will
4607 // always be able to use it, either because they've already chosen "don't ask again" or
4608 // because we have prompt them.
4609 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
4610 return true;
4611 }
4612
4613 // If a network has no Internet access, only prompt if the network was explicitly selected
4614 // and if the user has not already told us to use the network regardless of whether it
4615 // validated or not.
4616 if (nai.networkAgentConfig.explicitlySelected
4617 && !nai.networkAgentConfig.acceptUnvalidated) {
4618 return true;
4619 }
4620
4621 return false;
4622 }
4623
4624 private void handlePromptUnvalidated(Network network) {
4625 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
4626 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4627
4628 if (nai == null || !shouldPromptUnvalidated(nai)) {
4629 return;
4630 }
4631
4632 // Stop automatically reconnecting to this network in the future. Automatically connecting
4633 // to a network that provides no or limited connectivity is not useful, because the user
4634 // cannot use that network except through the notification shown by this method, and the
4635 // notification is only shown if the network is explicitly selected by the user.
4636 nai.onPreventAutomaticReconnect();
4637
4638 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4639 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4640 // popup the notification immediately when the network is partial connectivity.
4641 if (nai.partialConnectivity) {
4642 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
4643 } else {
4644 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4645 }
4646 }
4647
4648 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4649 NetworkCapabilities nc = nai.networkCapabilities;
4650 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
4651
4652 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4653 return;
4654 }
4655
4656 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
4657 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
4658 }
4659 }
4660
4661 @Override
4662 public int getMultipathPreference(Network network) {
4663 enforceAccessPermission();
4664
4665 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4666 if (nai != null && nai.networkCapabilities
4667 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
4668 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4669 }
4670
4671 final NetworkPolicyManager netPolicyManager =
4672 mContext.getSystemService(NetworkPolicyManager.class);
4673
4674 final long token = Binder.clearCallingIdentity();
4675 final int networkPreference;
4676 try {
4677 networkPreference = netPolicyManager.getMultipathPreference(network);
4678 } finally {
4679 Binder.restoreCallingIdentity(token);
4680 }
4681 if (networkPreference != 0) {
4682 return networkPreference;
4683 }
4684 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4685 }
4686
4687 @Override
4688 public NetworkRequest getDefaultRequest() {
4689 return mDefaultRequest.mRequests.get(0);
4690 }
4691
4692 private class InternalHandler extends Handler {
4693 public InternalHandler(Looper looper) {
4694 super(looper);
4695 }
4696
4697 @Override
4698 public void handleMessage(Message msg) {
4699 switch (msg.what) {
4700 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
4701 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
4702 handleReleaseNetworkTransitionWakelock(msg.what);
4703 break;
4704 }
4705 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
4706 mProxyTracker.loadDeprecatedGlobalHttpProxy();
4707 break;
4708 }
4709 case EVENT_PROXY_HAS_CHANGED: {
4710 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4711 handleApplyDefaultProxy(arg.second);
4712 break;
4713 }
4714 case EVENT_REGISTER_NETWORK_PROVIDER: {
4715 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
4716 break;
4717 }
4718 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4719 handleUnregisterNetworkProvider((Messenger) msg.obj);
4720 break;
4721 }
4722 case EVENT_REGISTER_NETWORK_OFFER: {
4723 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4724 break;
4725 }
4726 case EVENT_UNREGISTER_NETWORK_OFFER: {
4727 final NetworkOfferInfo offer =
4728 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4729 if (null != offer) {
4730 handleUnregisterNetworkOffer(offer);
4731 }
4732 break;
4733 }
4734 case EVENT_REGISTER_NETWORK_AGENT: {
4735 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4736 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4737 handleRegisterNetworkAgent(arg.first, arg.second);
4738 break;
4739 }
4740 case EVENT_REGISTER_NETWORK_REQUEST:
4741 case EVENT_REGISTER_NETWORK_LISTENER: {
4742 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
4743 break;
4744 }
4745 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4746 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
4747 handleRegisterNetworkRequestWithIntent(msg);
4748 break;
4749 }
4750 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4751 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4752 handleTimedOutNetworkRequest(nri);
4753 break;
4754 }
4755 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4756 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4757 break;
4758 }
4759 case EVENT_RELEASE_NETWORK_REQUEST: {
4760 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4761 /* callOnUnavailable */ false);
4762 break;
4763 }
4764 case EVENT_SET_ACCEPT_UNVALIDATED: {
4765 Network network = (Network) msg.obj;
4766 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
4767 break;
4768 }
4769 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4770 Network network = (Network) msg.obj;
4771 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4772 toBool(msg.arg2));
4773 break;
4774 }
4775 case EVENT_SET_AVOID_UNVALIDATED: {
4776 handleSetAvoidUnvalidated((Network) msg.obj);
4777 break;
4778 }
4779 case EVENT_PROMPT_UNVALIDATED: {
4780 handlePromptUnvalidated((Network) msg.obj);
4781 break;
4782 }
4783 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4784 handleConfigureAlwaysOnNetworks();
4785 break;
4786 }
4787 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4788 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
4789 mKeepaliveTracker.handleStartKeepalive(msg);
4790 break;
4791 }
4792 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4793 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
4794 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4795 int slot = msg.arg1;
4796 int reason = msg.arg2;
4797 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4798 break;
4799 }
4800 case EVENT_REVALIDATE_NETWORK: {
4801 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
4802 break;
4803 }
4804 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4805 handlePrivateDnsSettingsChanged();
4806 break;
4807 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4808 handlePrivateDnsValidationUpdate(
4809 (PrivateDnsValidationUpdate) msg.obj);
4810 break;
4811 case EVENT_UID_BLOCKED_REASON_CHANGED:
4812 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
4813 break;
4814 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4815 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4816 break;
4817 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
4818 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4819 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
4820 handleSetOemNetworkPreference(arg.first, arg.second);
4821 break;
4822 }
4823 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4824 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4825 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4826 msg.obj;
4827 handleSetProfileNetworkPreference(arg.first, arg.second);
4828 break;
4829 }
4830 case EVENT_REPORT_NETWORK_ACTIVITY:
4831 mNetworkActivityTracker.handleReportNetworkActivity();
4832 break;
paulhu71ad4f12021-05-25 14:56:27 +08004833 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
4834 handleMobileDataPreferredUidsChanged();
4835 break;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00004836 }
4837 }
4838 }
4839
4840 @Override
4841 @Deprecated
4842 public int getLastTetherError(String iface) {
4843 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4844 Context.TETHERING_SERVICE);
4845 return tm.getLastTetherError(iface);
4846 }
4847
4848 @Override
4849 @Deprecated
4850 public String[] getTetherableIfaces() {
4851 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4852 Context.TETHERING_SERVICE);
4853 return tm.getTetherableIfaces();
4854 }
4855
4856 @Override
4857 @Deprecated
4858 public String[] getTetheredIfaces() {
4859 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4860 Context.TETHERING_SERVICE);
4861 return tm.getTetheredIfaces();
4862 }
4863
4864
4865 @Override
4866 @Deprecated
4867 public String[] getTetheringErroredIfaces() {
4868 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4869 Context.TETHERING_SERVICE);
4870
4871 return tm.getTetheringErroredIfaces();
4872 }
4873
4874 @Override
4875 @Deprecated
4876 public String[] getTetherableUsbRegexs() {
4877 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4878 Context.TETHERING_SERVICE);
4879
4880 return tm.getTetherableUsbRegexs();
4881 }
4882
4883 @Override
4884 @Deprecated
4885 public String[] getTetherableWifiRegexs() {
4886 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4887 Context.TETHERING_SERVICE);
4888 return tm.getTetherableWifiRegexs();
4889 }
4890
4891 // Called when we lose the default network and have no replacement yet.
4892 // This will automatically be cleared after X seconds or a new default network
4893 // becomes CONNECTED, whichever happens first. The timer is started by the
4894 // first caller and not restarted by subsequent callers.
4895 private void ensureNetworkTransitionWakelock(String forWhom) {
4896 synchronized (this) {
4897 if (mNetTransitionWakeLock.isHeld()) {
4898 return;
4899 }
4900 mNetTransitionWakeLock.acquire();
4901 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4902 mTotalWakelockAcquisitions++;
4903 }
4904 mWakelockLogs.log("ACQUIRE for " + forWhom);
4905 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4906 final int lockTimeout = mResources.get().getInteger(
4907 R.integer.config_networkTransitionTimeout);
4908 mHandler.sendMessageDelayed(msg, lockTimeout);
4909 }
4910
4911 // Called when we gain a new default network to release the network transition wakelock in a
4912 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4913 // message is cancelled.
4914 private void scheduleReleaseNetworkTransitionWakelock() {
4915 synchronized (this) {
4916 if (!mNetTransitionWakeLock.isHeld()) {
4917 return; // expiry message released the lock first.
4918 }
4919 }
4920 // Cancel self timeout on wakelock hold.
4921 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4922 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4923 mHandler.sendMessageDelayed(msg, 1000);
4924 }
4925
4926 // Called when either message of ensureNetworkTransitionWakelock or
4927 // scheduleReleaseNetworkTransitionWakelock is processed.
4928 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4929 String event = eventName(eventId);
4930 synchronized (this) {
4931 if (!mNetTransitionWakeLock.isHeld()) {
4932 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
4933 Log.w(TAG, "expected Net Transition WakeLock to be held");
4934 return;
4935 }
4936 mNetTransitionWakeLock.release();
4937 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4938 mTotalWakelockDurationMs += lockDuration;
4939 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4940 mTotalWakelockReleases++;
4941 }
4942 mWakelockLogs.log(String.format("RELEASE (%s)", event));
4943 }
4944
4945 // 100 percent is full good, 0 is full bad.
4946 @Override
4947 public void reportInetCondition(int networkType, int percentage) {
4948 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4949 if (nai == null) return;
4950 reportNetworkConnectivity(nai.network, percentage > 50);
4951 }
4952
4953 @Override
4954 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
4955 enforceAccessPermission();
4956 enforceInternetPermission();
4957 final int uid = mDeps.getCallingUid();
4958 final int connectivityInfo = encodeBool(hasConnectivity);
4959
4960 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
4961 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
4962 // does not match the known connectivity of the network - this causes NetworkMonitor to
4963 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
4964 final NetworkAgentInfo nai;
4965 if (network == null) {
4966 nai = getDefaultNetwork();
4967 } else {
4968 nai = getNetworkAgentInfoForNetwork(network);
4969 }
4970 if (nai != null) {
4971 mConnectivityDiagnosticsHandler.sendMessage(
4972 mConnectivityDiagnosticsHandler.obtainMessage(
4973 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
4974 connectivityInfo, 0, nai));
4975 }
4976
4977 mHandler.sendMessage(
4978 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4979 }
4980
4981 private void handleReportNetworkConnectivity(
4982 Network network, int uid, boolean hasConnectivity) {
4983 final NetworkAgentInfo nai;
4984 if (network == null) {
4985 nai = getDefaultNetwork();
4986 } else {
4987 nai = getNetworkAgentInfoForNetwork(network);
4988 }
4989 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4990 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4991 return;
4992 }
4993 // Revalidate if the app report does not match our current validated state.
4994 if (hasConnectivity == nai.lastValidated) {
4995 return;
4996 }
4997 if (DBG) {
4998 int netid = nai.network.getNetId();
4999 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
5000 }
5001 // Validating a network that has not yet connected could result in a call to
5002 // rematchNetworkAndRequests() which is not meant to work on such networks.
5003 if (!nai.everConnected) {
5004 return;
5005 }
5006 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5007 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
5008 return;
5009 }
5010 nai.networkMonitor().forceReevaluation(uid);
5011 }
5012
5013 // TODO: call into netd.
5014 private boolean queryUserAccess(int uid, Network network) {
5015 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5016 if (nai == null) return false;
5017
5018 // Any UID can use its default network.
5019 if (nai == getDefaultNetworkForUid(uid)) return true;
5020
5021 // Privileged apps can use any network.
5022 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5023 return true;
5024 }
5025
5026 // An unprivileged UID can use a VPN iff the VPN applies to it.
5027 if (nai.isVPN()) {
5028 return nai.networkCapabilities.appliesToUid(uid);
5029 }
5030
5031 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5032 // sockets, i.e., if it is the owner.
5033 final NetworkAgentInfo vpn = getVpnForUid(uid);
5034 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5035 && uid != vpn.networkCapabilities.getOwnerUid()) {
5036 return false;
5037 }
5038
5039 // The UID's permission must be at least sufficient for the network. Since the restricted
5040 // permission was already checked above, that just leaves background networks.
5041 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5042 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5043 }
5044
5045 // Unrestricted network. Anyone gets to use it.
5046 return true;
5047 }
5048
5049 /**
5050 * Returns information about the proxy a certain network is using. If given a null network, it
5051 * it will return the proxy for the bound network for the caller app or the default proxy if
5052 * none.
5053 *
5054 * @param network the network we want to get the proxy information for.
5055 * @return Proxy information if a network has a proxy configured, or otherwise null.
5056 */
5057 @Override
5058 public ProxyInfo getProxyForNetwork(Network network) {
5059 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
5060 if (globalProxy != null) return globalProxy;
5061 if (network == null) {
5062 // Get the network associated with the calling UID.
5063 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
5064 true);
5065 if (activeNetwork == null) {
5066 return null;
5067 }
5068 return getLinkPropertiesProxyInfo(activeNetwork);
5069 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
5070 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5071 // caller may not have.
5072 return getLinkPropertiesProxyInfo(network);
5073 }
5074 // No proxy info available if the calling UID does not have network access.
5075 return null;
5076 }
5077
5078
5079 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
5080 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5081 if (nai == null) return null;
5082 synchronized (nai) {
5083 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5084 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
5085 }
5086 }
5087
5088 @Override
5089 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
5090 PermissionUtils.enforceNetworkStackPermission(mContext);
5091 mProxyTracker.setGlobalProxy(proxyProperties);
5092 }
5093
5094 @Override
5095 @Nullable
5096 public ProxyInfo getGlobalProxy() {
5097 return mProxyTracker.getGlobalProxy();
5098 }
5099
5100 private void handleApplyDefaultProxy(ProxyInfo proxy) {
5101 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
5102 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
5103 proxy = null;
5104 }
5105 mProxyTracker.setDefaultProxy(proxy);
5106 }
5107
5108 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5109 // when any network changes proxy.
5110 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5111 // multi-network world where an app might be bound to a non-default network.
5112 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
5113 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5114 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5115
5116 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
5117 mProxyTracker.sendProxyBroadcast();
5118 }
5119 }
5120
5121 private static class SettingsObserver extends ContentObserver {
5122 final private HashMap<Uri, Integer> mUriEventMap;
5123 final private Context mContext;
5124 final private Handler mHandler;
5125
5126 SettingsObserver(Context context, Handler handler) {
5127 super(null);
5128 mUriEventMap = new HashMap<>();
5129 mContext = context;
5130 mHandler = handler;
5131 }
5132
5133 void observe(Uri uri, int what) {
5134 mUriEventMap.put(uri, what);
5135 final ContentResolver resolver = mContext.getContentResolver();
5136 resolver.registerContentObserver(uri, false, this);
5137 }
5138
5139 @Override
5140 public void onChange(boolean selfChange) {
5141 Log.wtf(TAG, "Should never be reached.");
5142 }
5143
5144 @Override
5145 public void onChange(boolean selfChange, Uri uri) {
5146 final Integer what = mUriEventMap.get(uri);
5147 if (what != null) {
5148 mHandler.obtainMessage(what).sendToTarget();
5149 } else {
5150 loge("No matching event to send for URI=" + uri);
5151 }
5152 }
5153 }
5154
5155 private static void log(String s) {
5156 Log.d(TAG, s);
5157 }
5158
5159 private static void logw(String s) {
5160 Log.w(TAG, s);
5161 }
5162
5163 private static void logwtf(String s) {
5164 Log.wtf(TAG, s);
5165 }
5166
5167 private static void logwtf(String s, Throwable t) {
5168 Log.wtf(TAG, s, t);
5169 }
5170
5171 private static void loge(String s) {
5172 Log.e(TAG, s);
5173 }
5174
5175 private static void loge(String s, Throwable t) {
5176 Log.e(TAG, s, t);
5177 }
5178
5179 /**
5180 * Return the information of all ongoing VPNs.
5181 *
5182 * <p>This method is used to update NetworkStatsService.
5183 *
5184 * <p>Must be called on the handler thread.
5185 */
5186 private UnderlyingNetworkInfo[] getAllVpnInfo() {
5187 ensureRunningOnConnectivityServiceThread();
5188 if (mLockdownEnabled) {
5189 return new UnderlyingNetworkInfo[0];
5190 }
5191 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
5192 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5193 UnderlyingNetworkInfo info = createVpnInfo(nai);
5194 if (info != null) {
5195 infoList.add(info);
5196 }
5197 }
5198 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
5199 }
5200
5201 /**
5202 * @return VPN information for accounting, or null if we can't retrieve all required
5203 * information, e.g underlying ifaces.
5204 */
5205 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
5206 if (!nai.isVPN()) return null;
5207
5208 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
5209 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5210 // the underlyingNetworks list.
5211 if (underlyingNetworks == null) {
5212 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5213 nai.networkCapabilities.getOwnerUid());
5214 if (defaultNai != null) {
5215 underlyingNetworks = new Network[] { defaultNai.network };
5216 }
5217 }
5218
5219 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
5220
5221 List<String> interfaces = new ArrayList<>();
5222 for (Network network : underlyingNetworks) {
5223 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5224 if (underlyingNai == null) continue;
5225 LinkProperties lp = underlyingNai.linkProperties;
5226 for (String iface : lp.getAllInterfaceNames()) {
5227 if (!TextUtils.isEmpty(iface)) {
5228 interfaces.add(iface);
5229 }
5230 }
5231 }
5232
5233 if (interfaces.isEmpty()) return null;
5234
5235 // Must be non-null or NetworkStatsService will crash.
5236 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5237 // tun or ipsec interface is created.
5238 // TODO: Remove this check.
5239 if (nai.linkProperties.getInterfaceName() == null) return null;
5240
5241 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5242 nai.linkProperties.getInterfaceName(), interfaces);
5243 }
5244
5245 // TODO This needs to be the default network that applies to the NAI.
5246 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5247 Network[] underlyingNetworks) {
5248 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
5249 if (underlyingNetworks == null && defaultNetwork != null) {
5250 // null underlying networks means to track the default.
5251 underlyingNetworks = new Network[] { defaultNetwork };
5252 }
5253 return underlyingNetworks;
5254 }
5255
5256 // Returns true iff |network| is an underlying network of |nai|.
5257 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5258 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5259 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5260 if (!nai.supportsUnderlyingNetworks()) return false;
5261 final Network[] underlying = underlyingNetworksOrDefault(
5262 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
5263 return CollectionUtils.contains(underlying, network);
5264 }
5265
5266 /**
5267 * Recompute the capabilities for any networks that had a specific network as underlying.
5268 *
5269 * When underlying networks change, such networks may have to update capabilities to reflect
5270 * things like the metered bit, their transports, and so on. The capabilities are calculated
5271 * immediately. This method runs on the ConnectivityService thread.
5272 */
5273 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
5274 ensureRunningOnConnectivityServiceThread();
5275 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5276 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
5277 updateCapabilitiesForNetwork(nai);
5278 }
5279 }
5280 }
5281
5282 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5283 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5284 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5285 // a VPN is not up.
5286 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5287 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5288 for (UidRange range : blockedUidRanges) {
5289 if (range.contains(uid)) return true;
5290 }
5291 return false;
5292 }
5293
5294 @Override
5295 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5296 enforceNetworkStackOrSettingsPermission();
5297 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5298 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5299 }
5300
5301 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5302 if (DBG) {
5303 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5304 + Arrays.toString(ranges));
5305 }
5306 // Cannot use a Set since the list of UID ranges might contain duplicates.
5307 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5308 for (int i = 0; i < ranges.length; i++) {
5309 if (requireVpn) {
5310 newVpnBlockedUidRanges.add(ranges[i]);
5311 } else {
5312 newVpnBlockedUidRanges.remove(ranges[i]);
5313 }
5314 }
5315
5316 try {
5317 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5318 } catch (RemoteException | ServiceSpecificException e) {
5319 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5320 + Arrays.toString(ranges) + "): netd command failed: " + e);
5321 }
5322
5323 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5324 final boolean curMetered = nai.networkCapabilities.isMetered();
5325 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5326 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
5327 }
5328
5329 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5330 }
5331
5332 @Override
5333 public void setLegacyLockdownVpnEnabled(boolean enabled) {
5334 enforceNetworkStackOrSettingsPermission();
5335 mHandler.post(() -> mLockdownEnabled = enabled);
5336 }
5337
5338 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5339 return mLockdownEnabled
5340 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5341 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
5342 }
5343
5344 private NetworkAgentInfo getLegacyLockdownNai() {
5345 if (!mLockdownEnabled) {
5346 return null;
5347 }
5348 // The legacy lockdown VPN always only applies to userId 0.
5349 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5350 if (nai == null || !isLegacyLockdownNai(nai)) return null;
5351
5352 // The legacy lockdown VPN must always have exactly one underlying network.
5353 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5354 // a local variable. There is no need to make a copy because its contents cannot change.
5355 final Network[] underlying = nai.declaredUnderlyingNetworks;
5356 if (underlying == null || underlying.length != 1) {
5357 return null;
5358 }
5359
5360 // The legacy lockdown VPN always uses the default network.
5361 // If the VPN's underlying network is no longer the current default network, it means that
5362 // the default network has just switched, and the VPN is about to disconnect.
5363 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5364 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
5365 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5366 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
5367 return null;
5368 }
5369
5370 return nai;
5371 };
5372
5373 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5374 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5375 // just a DetailedState object.
5376 private DetailedState getLegacyLockdownState(DetailedState origState) {
5377 if (origState != DetailedState.CONNECTED) {
5378 return origState;
5379 }
5380 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5381 ? DetailedState.CONNECTING
5382 : DetailedState.CONNECTED;
5383 }
5384
5385 private void filterForLegacyLockdown(NetworkInfo ni) {
5386 if (!mLockdownEnabled || !ni.isConnected()) return;
5387 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5388 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5389 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5390 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5391 // network, this time with a state of CONNECTED.
5392 //
5393 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5394 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5395 // is not too far off the truth, since an always-on VPN, when not connected, is always
5396 // trying to reconnect.
5397 if (getLegacyLockdownNai() == null) {
5398 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5399 }
5400 }
5401
5402 @Override
5403 public void setProvisioningNotificationVisible(boolean visible, int networkType,
5404 String action) {
5405 enforceSettingsPermission();
5406 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5407 return;
5408 }
5409 final long ident = Binder.clearCallingIdentity();
5410 try {
5411 // Concatenate the range of types onto the range of NetIDs.
5412 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
5413 mNotifier.setProvNotificationVisible(visible, id, action);
5414 } finally {
5415 Binder.restoreCallingIdentity(ident);
5416 }
5417 }
5418
5419 @Override
5420 public void setAirplaneMode(boolean enable) {
5421 enforceAirplaneModePermission();
5422 final long ident = Binder.clearCallingIdentity();
5423 try {
5424 final ContentResolver cr = mContext.getContentResolver();
5425 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
5426 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5427 intent.putExtra("state", enable);
5428 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
5429 } finally {
5430 Binder.restoreCallingIdentity(ident);
5431 }
5432 }
5433
5434 private void onUserAdded(@NonNull final UserHandle user) {
5435 mPermissionMonitor.onUserAdded(user);
5436 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5437 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5438 }
5439 }
5440
5441 private void onUserRemoved(@NonNull final UserHandle user) {
5442 mPermissionMonitor.onUserRemoved(user);
5443 // If there was a network preference for this user, remove it.
5444 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5445 null /* listener */);
5446 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5447 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5448 }
5449 }
5450
5451 private void onPackageChanged(@NonNull final String packageName) {
5452 // This is necessary in case a package is added or removed, but also when it's replaced to
5453 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5454 // as one in the preferences, then it should follow the same routing as that other package,
5455 // which means updating the rules is never to be needed in this case (whether it joins or
5456 // leaves a UID with a preference).
5457 if (isMappedInOemNetworkPreference(packageName)) {
5458 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5459 }
5460 }
5461
5462 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5463 @Override
5464 public void onReceive(Context context, Intent intent) {
5465 ensureRunningOnConnectivityServiceThread();
5466 final String action = intent.getAction();
5467 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
5468
5469 // User should be filled for below intents, check the existence.
5470 if (user == null) {
5471 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5472 return;
5473 }
5474
5475 if (Intent.ACTION_USER_ADDED.equals(action)) {
5476 onUserAdded(user);
5477 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
5478 onUserRemoved(user);
5479 } else {
5480 Log.wtf(TAG, "received unexpected intent: " + action);
5481 }
5482 }
5483 };
5484
5485 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5486 @Override
5487 public void onReceive(Context context, Intent intent) {
5488 ensureRunningOnConnectivityServiceThread();
5489 switch (intent.getAction()) {
5490 case Intent.ACTION_PACKAGE_ADDED:
5491 case Intent.ACTION_PACKAGE_REMOVED:
5492 case Intent.ACTION_PACKAGE_REPLACED:
5493 onPackageChanged(intent.getData().getSchemeSpecificPart());
5494 break;
5495 default:
5496 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5497 }
5498 }
5499 };
5500
5501 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
5502 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
5503
5504 private static class NetworkProviderInfo {
5505 public final String name;
5506 public final Messenger messenger;
5507 private final IBinder.DeathRecipient mDeathRecipient;
5508 public final int providerId;
5509
5510 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5511 @NonNull IBinder.DeathRecipient deathRecipient) {
5512 this.name = name;
5513 this.messenger = messenger;
5514 this.providerId = providerId;
5515 mDeathRecipient = deathRecipient;
5516
5517 if (mDeathRecipient == null) {
5518 throw new AssertionError("Must pass a deathRecipient");
5519 }
5520 }
5521
5522 void connect(Context context, Handler handler) {
5523 try {
5524 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5525 } catch (RemoteException e) {
5526 mDeathRecipient.binderDied();
5527 }
5528 }
5529 }
5530
5531 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5532 for (int i = 0; i < requests.size(); i++) {
5533 ensureNetworkRequestHasType(requests.get(i));
5534 }
5535 }
5536
5537 private void ensureNetworkRequestHasType(NetworkRequest request) {
5538 if (request.type == NetworkRequest.Type.NONE) {
5539 throw new IllegalArgumentException(
5540 "All NetworkRequests in ConnectivityService must have a type");
5541 }
5542 }
5543
5544 /**
5545 * Tracks info about the requester.
5546 * Also used to notice when the calling process dies so as to self-expire
5547 */
5548 @VisibleForTesting
5549 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
5550 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5551 // single NetworkRequest in mRequests.
5552 final List<NetworkRequest> mRequests;
5553
5554 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5555 void setSatisfier(
5556 @Nullable final NetworkAgentInfo satisfier,
5557 @Nullable final NetworkRequest activeRequest) {
5558 mSatisfier = satisfier;
5559 mActiveRequest = activeRequest;
5560 }
5561
5562 // The network currently satisfying this NRI. Only one request in an NRI can have a
5563 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
5564 @Nullable
5565 private NetworkAgentInfo mSatisfier;
5566 NetworkAgentInfo getSatisfier() {
5567 return mSatisfier;
5568 }
5569
5570 // The request in mRequests assigned to a network agent. This is null if none of the
5571 // requests in mRequests can be satisfied. This member has the constraint of only being
5572 // accessible on the handler thread.
5573 @Nullable
5574 private NetworkRequest mActiveRequest;
5575 NetworkRequest getActiveRequest() {
5576 return mActiveRequest;
5577 }
5578
5579 final PendingIntent mPendingIntent;
5580 boolean mPendingIntentSent;
5581 @Nullable
5582 final Messenger mMessenger;
5583
5584 // Information about the caller that caused this object to be created.
5585 @Nullable
5586 private final IBinder mBinder;
5587 final int mPid;
5588 final int mUid;
5589 final @NetworkCallback.Flag int mCallbackFlags;
5590 @Nullable
5591 final String mCallingAttributionTag;
5592
5593 // Counter keeping track of this NRI.
5594 final PerUidCounter mPerUidCounter;
5595
5596 // Effective UID of this request. This is different from mUid when a privileged process
5597 // files a request on behalf of another UID. This UID is used to determine blocked status,
5598 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5599 // maximum limit of registered callbacks per UID.
5600 final int mAsUid;
5601
5602 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5603 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5604 // maintained for keying off of. This is only a concern when the original nri
5605 // mNetworkRequests changes which happens currently for apps that register callbacks to
5606 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5607 // that match the per-app default nri that currently tracks the calling app's uid so that
5608 // callbacks are fired at the appropriate time. When the callbacks fire,
5609 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5610 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5611 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5612 @NonNull
5613 private final NetworkRequest mNetworkRequestForCallback;
5614 NetworkRequest getNetworkRequestForCallback() {
5615 return mNetworkRequestForCallback;
5616 }
5617
5618 /**
5619 * Get the list of UIDs this nri applies to.
5620 */
5621 @NonNull
paulhu71ad4f12021-05-25 14:56:27 +08005622 Set<UidRange> getUids() {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00005623 // networkCapabilities.getUids() returns a defensive copy.
5624 // multilayer requests will all have the same uids so return the first one.
5625 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5626 return (null == uids) ? new ArraySet<>() : uids;
5627 }
5628
5629 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5630 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
5631 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag);
5632 }
5633
5634 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5635 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
5636 @Nullable String callingAttributionTag) {
5637 ensureAllNetworkRequestsHaveType(r);
5638 mRequests = initializeRequests(r);
5639 mNetworkRequestForCallback = requestForCallback;
5640 mPendingIntent = pi;
5641 mMessenger = null;
5642 mBinder = null;
5643 mPid = getCallingPid();
5644 mUid = mDeps.getCallingUid();
5645 mAsUid = asUid;
5646 mPerUidCounter = getRequestCounter(this);
5647 mPerUidCounter.incrementCountOrThrow(mUid);
5648 /**
5649 * Location sensitive data not included in pending intent. Only included in
5650 * {@link NetworkCallback}.
5651 */
5652 mCallbackFlags = NetworkCallback.FLAG_NONE;
5653 mCallingAttributionTag = callingAttributionTag;
5654 }
5655
5656 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
5657 @Nullable final IBinder binder,
5658 @NetworkCallback.Flag int callbackFlags,
5659 @Nullable String callingAttributionTag) {
5660 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5661 callingAttributionTag);
5662 }
5663
5664 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5665 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
5666 @Nullable final IBinder binder,
5667 @NetworkCallback.Flag int callbackFlags,
5668 @Nullable String callingAttributionTag) {
5669 super();
5670 ensureAllNetworkRequestsHaveType(r);
5671 mRequests = initializeRequests(r);
5672 mNetworkRequestForCallback = requestForCallback;
5673 mMessenger = m;
5674 mBinder = binder;
5675 mPid = getCallingPid();
5676 mUid = mDeps.getCallingUid();
5677 mAsUid = asUid;
5678 mPendingIntent = null;
5679 mPerUidCounter = getRequestCounter(this);
5680 mPerUidCounter.incrementCountOrThrow(mUid);
5681 mCallbackFlags = callbackFlags;
5682 mCallingAttributionTag = callingAttributionTag;
5683 linkDeathRecipient();
5684 }
5685
5686 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5687 @NonNull final List<NetworkRequest> r) {
5688 super();
5689 ensureAllNetworkRequestsHaveType(r);
5690 mRequests = initializeRequests(r);
5691 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
5692 final NetworkAgentInfo satisfier = nri.getSatisfier();
5693 if (null != satisfier) {
5694 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5695 // The active request is necessary to figure out what callbacks to send, in
5696 // particular then a network updates its capabilities.
5697 // As this code creates a new NRI with a new set of requests, figure out which of
5698 // the list of requests should be the active request. It is always the first
5699 // request of the list that can be satisfied by the satisfier since the order of
5700 // requests is a priority order.
5701 // Note even in the presence of a satisfier there may not be an active request,
5702 // when the satisfier is the no-service network.
5703 NetworkRequest activeRequest = null;
5704 for (final NetworkRequest candidate : r) {
5705 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5706 activeRequest = candidate;
5707 break;
5708 }
5709 }
5710 setSatisfier(satisfier, activeRequest);
5711 }
5712 mMessenger = nri.mMessenger;
5713 mBinder = nri.mBinder;
5714 mPid = nri.mPid;
5715 mUid = nri.mUid;
5716 mAsUid = nri.mAsUid;
5717 mPendingIntent = nri.mPendingIntent;
5718 mPerUidCounter = getRequestCounter(this);
5719 mPerUidCounter.incrementCountOrThrow(mUid);
5720 mCallbackFlags = nri.mCallbackFlags;
5721 mCallingAttributionTag = nri.mCallingAttributionTag;
5722 linkDeathRecipient();
5723 }
5724
5725 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
5726 this(asUid, Collections.singletonList(r));
5727 }
5728
5729 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r) {
5730 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */);
5731 }
5732
5733 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5734 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5735 // false.
5736 boolean isBeingSatisfied() {
5737 return (null != mSatisfier && null != mActiveRequest);
5738 }
5739
5740 boolean isMultilayerRequest() {
5741 return mRequests.size() > 1;
5742 }
5743
5744 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5745 // Creating a defensive copy to prevent the sender from modifying the list being
5746 // reflected in the return value of this method.
5747 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
5748 return Collections.unmodifiableList(tempRequests);
5749 }
5750
5751 void decrementRequestCount() {
5752 mPerUidCounter.decrementCount(mUid);
5753 }
5754
5755 void linkDeathRecipient() {
5756 if (null != mBinder) {
5757 try {
5758 mBinder.linkToDeath(this, 0);
5759 } catch (RemoteException e) {
5760 binderDied();
5761 }
5762 }
5763 }
5764
5765 void unlinkDeathRecipient() {
5766 if (null != mBinder) {
5767 mBinder.unlinkToDeath(this, 0);
5768 }
5769 }
5770
5771 @Override
5772 public void binderDied() {
5773 log("ConnectivityService NetworkRequestInfo binderDied(" +
5774 mRequests + ", " + mBinder + ")");
5775 releaseNetworkRequests(mRequests);
5776 }
5777
5778 @Override
5779 public String toString() {
5780 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5781 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
5782 + (mActiveRequest == null ? null : mActiveRequest.requestId)
5783 + " callbackRequest: "
5784 + mNetworkRequestForCallback.requestId
5785 + " " + mRequests
5786 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
5787 + " callback flags: " + mCallbackFlags;
5788 }
5789 }
5790
5791 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5792 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5793 if (badCapability != null) {
5794 throw new IllegalArgumentException("Cannot request network with " + badCapability);
5795 }
5796 }
5797
5798 // This checks that the passed capabilities either do not request a
5799 // specific SSID/SignalStrength, or the calling app has permission to do so.
5800 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5801 int callerPid, int callerUid, String callerPackageName) {
5802 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
5803 throw new SecurityException("Insufficient permissions to request a specific SSID");
5804 }
5805
5806 if (nc.hasSignalStrength()
5807 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5808 throw new SecurityException(
5809 "Insufficient permissions to request a specific signal strength");
5810 }
5811 mAppOpsManager.checkPackage(callerUid, callerPackageName);
5812
5813 if (!nc.getSubscriptionIds().isEmpty()) {
5814 enforceNetworkFactoryPermission();
5815 }
5816 }
5817
5818 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
5819 final SortedSet<Integer> thresholds = new TreeSet<>();
5820 synchronized (nai) {
5821 // mNetworkRequests may contain the same value multiple times in case of
5822 // multilayer requests. It won't matter in this case because the thresholds
5823 // will then be the same and be deduplicated as they enter the `thresholds` set.
5824 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
5825 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5826 for (final NetworkRequest req : nri.mRequests) {
5827 if (req.networkCapabilities.hasSignalStrength()
5828 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5829 thresholds.add(req.networkCapabilities.getSignalStrength());
5830 }
5831 }
5832 }
5833 }
5834 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
5835 }
5836
5837 private void updateSignalStrengthThresholds(
5838 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5839 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
5840
5841 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
5842 String detail;
5843 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5844 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5845 } else {
5846 detail = reason;
5847 }
5848 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5849 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
5850 }
5851
5852 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
5853 }
5854
5855 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5856 if (nc == null) {
5857 return;
5858 }
5859 NetworkSpecifier ns = nc.getNetworkSpecifier();
5860 if (ns == null) {
5861 return;
5862 }
5863 if (ns instanceof MatchAllNetworkSpecifier) {
5864 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5865 }
5866 }
5867
5868 private void ensureValid(NetworkCapabilities nc) {
5869 ensureValidNetworkSpecifier(nc);
5870 if (nc.isPrivateDnsBroken()) {
5871 throw new IllegalArgumentException("Can't request broken private DNS");
5872 }
5873 }
5874
5875 private boolean isTargetSdkAtleast(int version, int callingUid,
5876 @NonNull String callingPackageName) {
5877 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
5878 final PackageManager pm =
5879 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
5880 try {
5881 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
5882 if (callingVersion < version) return false;
5883 } catch (PackageManager.NameNotFoundException e) { }
5884 return true;
5885 }
5886
5887 @Override
5888 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
5889 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
5890 int legacyType, int callbackFlags, @NonNull String callingPackageName,
5891 @Nullable String callingAttributionTag) {
5892 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
5893 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5894 callingPackageName)) {
5895 throw new SecurityException("Insufficient permissions to specify legacy type");
5896 }
5897 }
5898 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
5899 final int callingUid = mDeps.getCallingUid();
5900 // Privileged callers can track the default network of another UID by passing in a UID.
5901 if (asUid != Process.INVALID_UID) {
5902 enforceSettingsPermission();
5903 } else {
5904 asUid = callingUid;
5905 }
5906 final NetworkRequest.Type reqType;
5907 try {
5908 reqType = NetworkRequest.Type.values()[reqTypeInt];
5909 } catch (ArrayIndexOutOfBoundsException e) {
5910 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5911 }
5912 switch (reqType) {
5913 case TRACK_DEFAULT:
5914 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
5915 // is unused and will be replaced by ones appropriate for the UID (usually, the
5916 // calling app). This allows callers to keep track of the default network.
5917 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
5918 defaultNc, asUid, callingUid, callingPackageName);
5919 enforceAccessPermission();
5920 break;
5921 case TRACK_SYSTEM_DEFAULT:
5922 enforceSettingsPermission();
5923 networkCapabilities = new NetworkCapabilities(defaultNc);
5924 break;
5925 case BACKGROUND_REQUEST:
5926 enforceNetworkStackOrSettingsPermission();
5927 // Fall-through since other checks are the same with normal requests.
5928 case REQUEST:
5929 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5930 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
5931 callingAttributionTag);
5932 // TODO: this is incorrect. We mark the request as metered or not depending on
5933 // the state of the app when the request is filed, but we never change the
5934 // request if the app changes network state. http://b/29964605
5935 enforceMeteredApnPolicy(networkCapabilities);
5936 break;
5937 case LISTEN_FOR_BEST:
5938 enforceAccessPermission();
5939 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5940 break;
5941 default:
5942 throw new IllegalArgumentException("Unsupported request type " + reqType);
5943 }
5944 ensureRequestableCapabilities(networkCapabilities);
5945 ensureSufficientPermissionsForRequest(networkCapabilities,
5946 Binder.getCallingPid(), callingUid, callingPackageName);
5947
5948 // Enforce FOREGROUND if the caller does not have permission to use background network.
5949 if (reqType == LISTEN_FOR_BEST) {
5950 restrictBackgroundRequestForCaller(networkCapabilities);
5951 }
5952
5953 // Set the UID range for this request to the single UID of the requester, unless the
5954 // requester has the permission to specify other UIDs.
5955 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5956 // are no visible methods to set the UIDs, an app could use reflection to try and get
5957 // networks for other apps so it's essential that the UIDs are overwritten.
5958 // Also set the requester UID and package name in the request.
5959 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
5960 callingUid, callingPackageName);
5961
5962 if (timeoutMs < 0) {
5963 throw new IllegalArgumentException("Bad timeout specified");
5964 }
5965 ensureValid(networkCapabilities);
5966
5967 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
5968 nextNetworkRequestId(), reqType);
5969 final NetworkRequestInfo nri = getNriToRegister(
5970 asUid, networkRequest, messenger, binder, callbackFlags,
5971 callingAttributionTag);
5972 if (DBG) log("requestNetwork for " + nri);
5973
5974 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
5975 // copied from the default request above. (This is necessary to ensure, for example, that
5976 // the callback does not leak sensitive information to unprivileged apps.) Check that the
5977 // changes don't alter request matching.
5978 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
5979 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
5980 throw new IllegalStateException(
5981 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
5982 + networkCapabilities + " vs. " + defaultNc);
5983 }
5984
5985 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
5986 if (timeoutMs > 0) {
5987 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
5988 nri), timeoutMs);
5989 }
5990 return networkRequest;
5991 }
5992
5993 /**
5994 * Return the nri to be used when registering a network request. Specifically, this is used with
5995 * requests registered to track the default request. If there is currently a per-app default
5996 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
5997 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
5998 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
5999 * when a privileged caller is tracking the default network for another uid.
6000 * @param nr the network request for the nri.
6001 * @param msgr the messenger for the nri.
6002 * @param binder the binder for the nri.
6003 * @param callingAttributionTag the calling attribution tag for the nri.
6004 * @return the nri to register.
6005 */
6006 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
6007 @Nullable final Messenger msgr, @Nullable final IBinder binder,
6008 @NetworkCallback.Flag int callbackFlags,
6009 @Nullable String callingAttributionTag) {
6010 final List<NetworkRequest> requests;
6011 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6012 requests = copyDefaultNetworkRequestsForUid(
6013 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
6014 } else {
6015 requests = Collections.singletonList(nr);
6016 }
6017 return new NetworkRequestInfo(
6018 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
6019 }
6020
6021 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6022 String callingPackageName, String callingAttributionTag) {
6023 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
6024 enforceConnectivityRestrictedNetworksPermission();
6025 } else {
6026 enforceChangePermission(callingPackageName, callingAttributionTag);
6027 }
6028 }
6029
6030 @Override
6031 public boolean requestBandwidthUpdate(Network network) {
6032 enforceAccessPermission();
6033 NetworkAgentInfo nai = null;
6034 if (network == null) {
6035 return false;
6036 }
6037 synchronized (mNetworkForNetId) {
6038 nai = mNetworkForNetId.get(network.getNetId());
6039 }
6040 if (nai != null) {
6041 nai.onBandwidthUpdateRequested();
6042 synchronized (mBandwidthRequests) {
6043 final int uid = mDeps.getCallingUid();
6044 Integer uidReqs = mBandwidthRequests.get(uid);
6045 if (uidReqs == null) {
6046 uidReqs = 0;
6047 }
6048 mBandwidthRequests.put(uid, ++uidReqs);
6049 }
6050 return true;
6051 }
6052 return false;
6053 }
6054
6055 private boolean isSystem(int uid) {
6056 return uid < Process.FIRST_APPLICATION_UID;
6057 }
6058
6059 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
6060 final int uid = mDeps.getCallingUid();
6061 if (isSystem(uid)) {
6062 // Exemption for system uid.
6063 return;
6064 }
6065 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6066 // Policy already enforced.
6067 return;
6068 }
6069 final long ident = Binder.clearCallingIdentity();
6070 try {
6071 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6072 // If UID is restricted, don't allow them to bring up metered APNs.
6073 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6074 }
6075 } finally {
6076 Binder.restoreCallingIdentity(ident);
6077 }
6078 }
6079
6080 @Override
6081 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
6082 PendingIntent operation, @NonNull String callingPackageName,
6083 @Nullable String callingAttributionTag) {
6084 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6085 final int callingUid = mDeps.getCallingUid();
6086 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6087 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6088 callingAttributionTag);
6089 enforceMeteredApnPolicy(networkCapabilities);
6090 ensureRequestableCapabilities(networkCapabilities);
6091 ensureSufficientPermissionsForRequest(networkCapabilities,
6092 Binder.getCallingPid(), callingUid, callingPackageName);
6093 ensureValidNetworkSpecifier(networkCapabilities);
6094 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6095 callingUid, callingPackageName);
6096
6097 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
6098 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
6099 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6100 callingAttributionTag);
6101 if (DBG) log("pendingRequest for " + nri);
6102 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6103 nri));
6104 return networkRequest;
6105 }
6106
6107 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6108 mHandler.sendMessageDelayed(
6109 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6110 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
6111 }
6112
6113 @Override
6114 public void releasePendingNetworkRequest(PendingIntent operation) {
6115 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6116 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6117 mDeps.getCallingUid(), 0, operation));
6118 }
6119
6120 // In order to implement the compatibility measure for pre-M apps that call
6121 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6122 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6123 // This ensures it has permission to do so.
6124 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6125 if (nc == null) {
6126 return false;
6127 }
6128 int[] transportTypes = nc.getTransportTypes();
6129 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6130 return false;
6131 }
6132 try {
6133 mContext.enforceCallingOrSelfPermission(
6134 android.Manifest.permission.ACCESS_WIFI_STATE,
6135 "ConnectivityService");
6136 } catch (SecurityException e) {
6137 return false;
6138 }
6139 return true;
6140 }
6141
6142 @Override
6143 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
6144 Messenger messenger, IBinder binder,
6145 @NetworkCallback.Flag int callbackFlags,
6146 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
6147 final int callingUid = mDeps.getCallingUid();
6148 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6149 enforceAccessPermission();
6150 }
6151
6152 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6153 ensureSufficientPermissionsForRequest(networkCapabilities,
6154 Binder.getCallingPid(), callingUid, callingPackageName);
6155 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6156 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6157 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6158 // onLost and onAvailable callbacks when networks move in and out of the background.
6159 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6160 // can't request networks.
6161 restrictBackgroundRequestForCaller(nc);
6162 ensureValid(nc);
6163
6164 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6165 NetworkRequest.Type.LISTEN);
6166 NetworkRequestInfo nri =
6167 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
6168 callingAttributionTag);
6169 if (VDBG) log("listenForNetwork for " + nri);
6170
6171 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6172 return networkRequest;
6173 }
6174
6175 @Override
6176 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
6177 PendingIntent operation, @NonNull String callingPackageName,
6178 @Nullable String callingAttributionTag) {
6179 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6180 final int callingUid = mDeps.getCallingUid();
6181 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6182 enforceAccessPermission();
6183 }
6184 ensureValid(networkCapabilities);
6185 ensureSufficientPermissionsForRequest(networkCapabilities,
6186 Binder.getCallingPid(), callingUid, callingPackageName);
6187 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6188 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6189
6190 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6191 NetworkRequest.Type.LISTEN);
6192 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6193 callingAttributionTag);
6194 if (VDBG) log("pendingListenForNetwork for " + nri);
6195
6196 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6197 }
6198
6199 /** Returns the next Network provider ID. */
6200 public final int nextNetworkProviderId() {
6201 return mNextNetworkProviderId.getAndIncrement();
6202 }
6203
6204 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
6205 for (int i = 0; i < networkRequests.size(); i++) {
6206 releaseNetworkRequest(networkRequests.get(i));
6207 }
6208 }
6209
6210 @Override
6211 public void releaseNetworkRequest(NetworkRequest networkRequest) {
6212 ensureNetworkRequestHasType(networkRequest);
6213 mHandler.sendMessage(mHandler.obtainMessage(
6214 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
6215 }
6216
6217 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6218 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
6219 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6220 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6221 // as that will throw if a duplicate provider is registered.
6222 loge("Attempt to register existing NetworkProviderInfo "
6223 + mNetworkProviderInfos.get(npi.messenger).name);
6224 return;
6225 }
6226
6227 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6228 mNetworkProviderInfos.put(npi.messenger, npi);
6229 npi.connect(mContext, mTrackerHandler);
6230 }
6231
6232 @Override
6233 public int registerNetworkProvider(Messenger messenger, String name) {
6234 enforceNetworkFactoryOrSettingsPermission();
6235 Objects.requireNonNull(messenger, "messenger must be non-null");
6236 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
6237 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
6238 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6239 return npi.providerId;
6240 }
6241
6242 @Override
6243 public void unregisterNetworkProvider(Messenger messenger) {
6244 enforceNetworkFactoryOrSettingsPermission();
6245 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
6246 }
6247
6248 @Override
6249 public void offerNetwork(final int providerId,
6250 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6251 @NonNull final INetworkOfferCallback callback) {
6252 Objects.requireNonNull(score);
6253 Objects.requireNonNull(caps);
6254 Objects.requireNonNull(callback);
6255 final NetworkOffer offer = new NetworkOffer(
6256 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
6257 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6258 }
6259
6260 @Override
6261 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6262 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6263 }
6264
6265 private void handleUnregisterNetworkProvider(Messenger messenger) {
6266 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6267 if (npi == null) {
6268 loge("Failed to find Messenger in unregisterNetworkProvider");
6269 return;
6270 }
6271 // Unregister all the offers from this provider
6272 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6273 for (final NetworkOfferInfo noi : mNetworkOffers) {
6274 if (noi.offer.providerId == npi.providerId) {
6275 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6276 toRemove.add(noi);
6277 }
6278 }
6279 for (final NetworkOfferInfo noi : toRemove) {
6280 handleUnregisterNetworkOffer(noi);
6281 }
6282 if (DBG) log("unregisterNetworkProvider for " + npi.name);
6283 }
6284
6285 @Override
6286 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
6287 if (request.hasTransport(TRANSPORT_TEST)) {
6288 enforceNetworkFactoryOrTestNetworksPermission();
6289 } else {
6290 enforceNetworkFactoryPermission();
6291 }
6292 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6293 if (nri != null) {
6294 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6295 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6296 mHandler.post(() -> handleReleaseNetworkRequest(
6297 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6298 }
6299 }
6300
6301 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6302 @GuardedBy("mNetworkForNetId")
6303 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
6304 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
6305 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
6306 // there may not be a strict 1:1 correlation between the two.
6307 private final NetIdManager mNetIdManager;
6308
6309 // NetworkAgentInfo keyed off its connecting messenger
6310 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
6311 // 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
7453 if (getNetworkAgentInfoForNetId(nai.network.getNetId()) != nai) {
7454 // 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
Cody Kesting0b4be022021-05-20 22:57:07 +00009197 private boolean hasLocationPermission(String packageName, int uid) {
9198 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9199 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9200 // call in a try-catch.
9201 try {
9202 if (!mLocationPermissionChecker.checkLocationPermission(
9203 packageName, null /* featureId */, uid, null /* message */)) {
9204 return false;
9205 }
9206 } catch (SecurityException e) {
9207 return false;
9208 }
9209
9210 return true;
9211 }
9212
9213 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9214 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
9215 if (virtual.supportsUnderlyingNetworks()
9216 && virtual.networkCapabilities.getOwnerUid() == uid
9217 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9218 return true;
9219 }
9220 }
9221
9222 return false;
9223 }
9224
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009225 @VisibleForTesting
9226 boolean checkConnectivityDiagnosticsPermissions(
9227 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9228 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9229 return true;
9230 }
9231
Cody Kesting0b4be022021-05-20 22:57:07 +00009232 // Administrator UIDs also contains the Owner UID
9233 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9234 if (!CollectionUtils.contains(administratorUids, callbackUid)
9235 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009236 return false;
9237 }
9238
Cody Kesting0b4be022021-05-20 22:57:07 +00009239 return hasLocationPermission(callbackPackageName, callbackUid);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009240 }
9241
9242 @Override
9243 public void registerConnectivityDiagnosticsCallback(
9244 @NonNull IConnectivityDiagnosticsCallback callback,
9245 @NonNull NetworkRequest request,
9246 @NonNull String callingPackageName) {
9247 if (request.legacyType != TYPE_NONE) {
9248 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9249 + " Please use NetworkCapabilities instead.");
9250 }
9251 final int callingUid = mDeps.getCallingUid();
9252 mAppOpsManager.checkPackage(callingUid, callingPackageName);
9253
9254 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9255 // and administrator uids to be safe.
9256 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
9257 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
9258
9259 final NetworkRequest requestWithId =
9260 new NetworkRequest(
9261 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9262
9263 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9264 //
9265 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9266 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9267 // callback's binder death.
9268 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
9269 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9270 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
9271
9272 mConnectivityDiagnosticsHandler.sendMessage(
9273 mConnectivityDiagnosticsHandler.obtainMessage(
9274 ConnectivityDiagnosticsHandler
9275 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9276 cbInfo));
9277 }
9278
9279 @Override
9280 public void unregisterConnectivityDiagnosticsCallback(
9281 @NonNull IConnectivityDiagnosticsCallback callback) {
9282 Objects.requireNonNull(callback, "callback must be non-null");
9283 mConnectivityDiagnosticsHandler.sendMessage(
9284 mConnectivityDiagnosticsHandler.obtainMessage(
9285 ConnectivityDiagnosticsHandler
9286 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9287 mDeps.getCallingUid(),
9288 0,
9289 callback));
9290 }
9291
9292 @Override
9293 public void simulateDataStall(int detectionMethod, long timestampMillis,
9294 @NonNull Network network, @NonNull PersistableBundle extras) {
9295 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9296 android.Manifest.permission.NETWORK_STACK);
9297 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9298 if (!nc.hasTransport(TRANSPORT_TEST)) {
9299 throw new SecurityException("Data Stall simluation is only possible for test networks");
9300 }
9301
9302 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
9303 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
9304 throw new SecurityException("Data Stall simulation is only possible for network "
9305 + "creators");
9306 }
9307
9308 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9309 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9310 // Data Stall information as a DataStallReportParcelable and passing to
9311 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9312 // still passed to ConnectivityDiagnostics (with new detection methods masked).
9313 final DataStallReportParcelable p = new DataStallReportParcelable();
9314 p.timestampMillis = timestampMillis;
9315 p.detectionMethod = detectionMethod;
9316
9317 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9318 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9319 }
9320 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9321 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9322 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9323 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9324 }
9325
9326 notifyDataStallSuspected(p, network.getNetId());
9327 }
9328
9329 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9330 @Override
9331 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
9332 long timestampNs, int uid) {
9333 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
9334 }
9335
9336 @Override
9337 public void onInterfaceLinkStateChanged(String iface, boolean up) {
9338 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9339 nai.clatd.interfaceLinkStateChanged(iface, up);
9340 }
9341 }
9342
9343 @Override
9344 public void onInterfaceRemoved(String iface) {
9345 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9346 nai.clatd.interfaceRemoved(iface);
9347 }
9348 }
9349 }
9350
9351 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9352
9353 /**
9354 * Class used for updating network activity tracking with netd and notify network activity
9355 * changes.
9356 */
9357 private static final class LegacyNetworkActivityTracker {
9358 private static final int NO_UID = -1;
9359 private final Context mContext;
9360 private final INetd mNetd;
9361 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9362 new RemoteCallbackList<>();
9363 // Indicate the current system default network activity is active or not.
9364 @GuardedBy("mActiveIdleTimers")
9365 private boolean mNetworkActive;
9366 @GuardedBy("mActiveIdleTimers")
9367 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9368 private final Handler mHandler;
9369
9370 private class IdleTimerParams {
9371 public final int timeout;
9372 public final int transportType;
9373
9374 IdleTimerParams(int timeout, int transport) {
9375 this.timeout = timeout;
9376 this.transportType = transport;
9377 }
9378 }
9379
9380 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
9381 @NonNull INetd netd) {
9382 mContext = context;
9383 mNetd = netd;
9384 mHandler = handler;
9385 }
9386
9387 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9388 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9389 synchronized (mActiveIdleTimers) {
9390 mNetworkActive = active;
9391 // If there are no idle timers, it means that system is not monitoring
9392 // activity, so the system default network for those default network
9393 // unspecified apps is always considered active.
9394 //
9395 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9396 // any network activity change event. Whenever this event is received,
9397 // the mActiveIdleTimers should be always not empty. The legacy behavior
9398 // is no-op. Remove to refer to mNetworkActive only.
9399 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9400 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9401 }
9402 }
9403 }
9404
9405 // The network activity should only be updated from ConnectivityService handler thread
9406 // when mActiveIdleTimers lock is held.
9407 @GuardedBy("mActiveIdleTimers")
9408 private void reportNetworkActive() {
9409 final int length = mNetworkActivityListeners.beginBroadcast();
9410 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9411 try {
9412 for (int i = 0; i < length; i++) {
9413 try {
9414 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9415 } catch (RemoteException | RuntimeException e) {
9416 loge("Fail to send network activie to listener " + e);
9417 }
9418 }
9419 } finally {
9420 mNetworkActivityListeners.finishBroadcast();
9421 }
9422 }
9423
9424 @GuardedBy("mActiveIdleTimers")
9425 public void handleReportNetworkActivity() {
9426 synchronized (mActiveIdleTimers) {
9427 reportNetworkActive();
9428 }
9429 }
9430
9431 // This is deprecated and only to support legacy use cases.
9432 private int transportTypeToLegacyType(int type) {
9433 switch (type) {
9434 case NetworkCapabilities.TRANSPORT_CELLULAR:
9435 return TYPE_MOBILE;
9436 case NetworkCapabilities.TRANSPORT_WIFI:
9437 return TYPE_WIFI;
9438 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
9439 return TYPE_BLUETOOTH;
9440 case NetworkCapabilities.TRANSPORT_ETHERNET:
9441 return TYPE_ETHERNET;
9442 default:
9443 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9444 }
9445 return ConnectivityManager.TYPE_NONE;
9446 }
9447
9448 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9449 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9450 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9451 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9452 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9453 final long ident = Binder.clearCallingIdentity();
9454 try {
9455 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9456 RECEIVE_DATA_ACTIVITY_CHANGE,
9457 null /* resultReceiver */,
9458 null /* scheduler */,
9459 0 /* initialCode */,
9460 null /* initialData */,
9461 null /* initialExtra */);
9462 } finally {
9463 Binder.restoreCallingIdentity(ident);
9464 }
9465 }
9466
9467 /**
9468 * Setup data activity tracking for the given network.
9469 *
9470 * Every {@code setupDataActivityTracking} should be paired with a
9471 * {@link #removeDataActivityTracking} for cleanup.
9472 */
9473 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9474 final String iface = networkAgent.linkProperties.getInterfaceName();
9475
9476 final int timeout;
9477 final int type;
9478
9479 if (networkAgent.networkCapabilities.hasTransport(
9480 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9481 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9482 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
9483 10);
9484 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9485 } else if (networkAgent.networkCapabilities.hasTransport(
9486 NetworkCapabilities.TRANSPORT_WIFI)) {
9487 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9488 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
9489 15);
9490 type = NetworkCapabilities.TRANSPORT_WIFI;
9491 } else {
9492 return; // do not track any other networks
9493 }
9494
9495 updateRadioPowerState(true /* isActive */, type);
9496
9497 if (timeout > 0 && iface != null) {
9498 try {
9499 synchronized (mActiveIdleTimers) {
9500 // Networks start up.
9501 mNetworkActive = true;
9502 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9503 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9504 reportNetworkActive();
9505 }
9506 } catch (Exception e) {
9507 // You shall not crash!
9508 loge("Exception in setupDataActivityTracking " + e);
9509 }
9510 }
9511 }
9512
9513 /**
9514 * Remove data activity tracking when network disconnects.
9515 */
9516 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9517 final String iface = networkAgent.linkProperties.getInterfaceName();
9518 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9519
9520 if (iface == null) return;
9521
9522 final int type;
9523 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9524 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9525 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9526 type = NetworkCapabilities.TRANSPORT_WIFI;
9527 } else {
9528 return; // do not track any other networks
9529 }
9530
9531 try {
9532 updateRadioPowerState(false /* isActive */, type);
9533 synchronized (mActiveIdleTimers) {
9534 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9535 // The call fails silently if no idle timer setup for this interface
9536 mNetd.idletimerRemoveInterface(iface, params.timeout,
9537 Integer.toString(params.transportType));
9538 }
9539 } catch (Exception e) {
9540 // You shall not crash!
9541 loge("Exception in removeDataActivityTracking " + e);
9542 }
9543 }
9544
9545 /**
9546 * Update data activity tracking when network state is updated.
9547 */
9548 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9549 NetworkAgentInfo oldNetwork) {
9550 if (newNetwork != null) {
9551 setupDataActivityTracking(newNetwork);
9552 }
9553 if (oldNetwork != null) {
9554 removeDataActivityTracking(oldNetwork);
9555 }
9556 }
9557
9558 private void updateRadioPowerState(boolean isActive, int transportType) {
9559 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9560 switch (transportType) {
9561 case NetworkCapabilities.TRANSPORT_CELLULAR:
9562 bs.reportMobileRadioPowerState(isActive, NO_UID);
9563 break;
9564 case NetworkCapabilities.TRANSPORT_WIFI:
9565 bs.reportWifiRadioPowerState(isActive, NO_UID);
9566 break;
9567 default:
9568 logw("Untracked transport type:" + transportType);
9569 }
9570 }
9571
9572 public boolean isDefaultNetworkActive() {
9573 synchronized (mActiveIdleTimers) {
9574 // If there are no idle timers, it means that system is not monitoring activity,
9575 // so the default network is always considered active.
9576 //
9577 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9578 // tracking is disabled (negative idle timer value configured), or no active default
9579 // network. In the latter case, this reports active but it should report inactive.
9580 return mNetworkActive || mActiveIdleTimers.isEmpty();
9581 }
9582 }
9583
9584 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9585 mNetworkActivityListeners.register(l);
9586 }
9587
9588 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9589 mNetworkActivityListeners.unregister(l);
9590 }
9591
9592 public void dump(IndentingPrintWriter pw) {
9593 synchronized (mActiveIdleTimers) {
9594 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9595 pw.println("Idle timers:");
9596 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9597 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9598 final IdleTimerParams params = ent.getValue();
9599 pw.print(" timeout="); pw.print(params.timeout);
9600 pw.print(" type="); pw.println(params.transportType);
9601 }
9602 }
9603 }
9604 }
9605
9606 /**
9607 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9608 *
9609 * @param socketInfo the socket information
9610 * @param callback the callback to register
9611 */
9612 @Override
9613 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9614 @NonNull final IQosCallback callback) {
9615 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9616 if (nai == null || nai.networkCapabilities == null) {
9617 try {
9618 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9619 } catch (final RemoteException ex) {
9620 loge("registerQosCallbackInternal: RemoteException", ex);
9621 }
9622 return;
9623 }
9624 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9625 }
9626
9627 /**
9628 * Register a {@link IQosCallback} with base {@link QosFilter}.
9629 *
9630 * @param filter the filter to register
9631 * @param callback the callback to register
9632 * @param nai the agent information related to the filter's network
9633 */
9634 @VisibleForTesting
9635 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9636 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9637 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9638 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9639
9640 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9641 enforceConnectivityRestrictedNetworksPermission();
9642 }
9643 mQosCallbackTracker.registerCallback(callback, filter, nai);
9644 }
9645
9646 /**
9647 * Unregisters the given callback.
9648 *
9649 * @param callback the callback to unregister
9650 */
9651 @Override
9652 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
9653 Objects.requireNonNull(callback, "callback must be non-null");
9654 mQosCallbackTracker.unregisterCallback(callback);
9655 }
9656
9657 // Network preference per-profile and OEM network preferences can't be set at the same
9658 // time, because it is unclear what should happen if both preferences are active for
9659 // one given UID. To make it possible, the stack would have to clarify what would happen
9660 // in case both are active at the same time. The implementation may have to be adjusted
9661 // to implement the resulting rules. For example, a priority could be defined between them,
9662 // where the OEM preference would be considered less or more important than the enterprise
9663 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9664 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9665 // are set at the right level. Other solutions are possible, e.g. merging of the
9666 // preferences for the relevant UIDs.
9667 private static void throwConcurrentPreferenceException() {
9668 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9669 + "set OemNetworkPreference at the same time");
9670 }
9671
9672 /**
9673 * Request that a user profile is put by default on a network matching a given preference.
9674 *
9675 * See the documentation for the individual preferences for a description of the supported
9676 * behaviors.
9677 *
9678 * @param profile the profile concerned.
9679 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9680 * constants.
9681 * @param listener an optional listener to listen for completion of the operation.
9682 */
9683 @Override
9684 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9685 @ConnectivityManager.ProfileNetworkPreference final int preference,
9686 @Nullable final IOnCompleteListener listener) {
9687 Objects.requireNonNull(profile);
9688 PermissionUtils.enforceNetworkStackPermission(mContext);
9689 if (DBG) {
9690 log("setProfileNetworkPreference " + profile + " to " + preference);
9691 }
9692 if (profile.getIdentifier() < 0) {
9693 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9694 + "UserHandle.CURRENT not supported)");
9695 }
9696 final UserManager um = mContext.getSystemService(UserManager.class);
9697 if (!um.isManagedProfile(profile.getIdentifier())) {
9698 throw new IllegalArgumentException("Profile must be a managed profile");
9699 }
9700 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9701 // handler thread. However it is an immutable object, so reading the reference is
9702 // safe - it's just possible the value is slightly outdated. For the final check,
9703 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9704 // lot easier to understand, so opportunistically check it.
paulhu71ad4f12021-05-25 14:56:27 +08009705 // TODO: Have a priority for each preference.
9706 if (!mOemNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009707 throwConcurrentPreferenceException();
9708 }
9709 final NetworkCapabilities nc;
9710 switch (preference) {
9711 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9712 nc = null;
9713 break;
9714 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9715 final UidRange uids = UidRange.createForUser(profile);
9716 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9717 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9718 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9719 break;
9720 default:
9721 throw new IllegalArgumentException(
9722 "Invalid preference in setProfileNetworkPreference");
9723 }
9724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9725 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9726 }
9727
9728 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9729 @Nullable final NetworkCapabilities nc) {
9730 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9731 ensureRequestableCapabilities(nc);
9732 }
9733
9734 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9735 @NonNull final ProfileNetworkPreferences prefs) {
9736 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9737 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9738 // The NRI for a user should be comprised of two layers:
9739 // - The request for the capabilities
9740 // - The request for the default network, for fallback. Create an image of it to
9741 // have the correct UIDs in it (also a request can only be part of one NRI, because
9742 // of lookups in 1:1 associations like mNetworkRequests).
9743 // Note that denying a fallback can be implemented simply by not adding the second
9744 // request.
9745 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9746 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
9747 nrs.add(createDefaultInternetRequestForTransport(
9748 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9749 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
9750 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs);
9751 result.add(nri);
9752 }
9753 return result;
9754 }
9755
9756 private void handleSetProfileNetworkPreference(
9757 @NonNull final ProfileNetworkPreferences.Preference preference,
9758 @Nullable final IOnCompleteListener listener) {
9759 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9760 // particular because it's not clear what preference should win in case both apply
9761 // to the same app.
9762 // The binder call has already checked this, but as mOemNetworkPreferences is only
9763 // touched on the handler thread, it's theoretically not impossible that it has changed
9764 // since.
paulhu71ad4f12021-05-25 14:56:27 +08009765 // TODO: Have a priority for each preference.
9766 if (!mOemNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009767 // This may happen on a device with an OEM preference set when a user is removed.
9768 // In this case, it's safe to ignore. In particular this happens in the tests.
9769 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
9770 return;
9771 }
9772
9773 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9774
9775 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
9776 mSystemNetworkRequestCounter.transact(
9777 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9778 () -> {
9779 final ArraySet<NetworkRequestInfo> nris =
9780 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9781 replaceDefaultNetworkRequestsForPreference(nris);
9782 });
9783 // Finally, rematch.
9784 rematchAllNetworksAndRequests();
9785
9786 if (null != listener) {
9787 try {
9788 listener.onComplete();
9789 } catch (RemoteException e) {
9790 loge("Listener for setProfileNetworkPreference has died");
9791 }
9792 }
9793 }
9794
paulhu71ad4f12021-05-25 14:56:27 +08009795 @VisibleForTesting
9796 @NonNull
9797 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
9798 @NonNull final Set<Integer> uids) {
9799 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
9800 if (uids.size() == 0) {
9801 // Should not create NetworkRequestInfo if no preferences. Without uid range in
9802 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
9803 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
9804 return nris;
9805 }
9806
9807 final List<NetworkRequest> requests = new ArrayList<>();
9808 // The NRI should be comprised of two layers:
9809 // - The request for the mobile network preferred.
9810 // - The request for the default network, for fallback.
9811 requests.add(createDefaultInternetRequestForTransport(
9812 TRANSPORT_CELLULAR, NetworkRequest.Type.LISTEN));
9813 requests.add(createDefaultInternetRequestForTransport(
9814 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9815 final Set<UidRange> ranges = new ArraySet<>();
9816 for (final int uid : uids) {
9817 ranges.add(new UidRange(uid, uid));
9818 }
9819 setNetworkRequestUids(requests, ranges);
9820 nris.add(new NetworkRequestInfo(Process.myUid(), requests));
9821 return nris;
9822 }
9823
9824 private void handleMobileDataPreferredUidsChanged() {
9825 // Ignore update preference because it's not clear what preference should win in case both
9826 // apply to the same app.
9827 // TODO: Have a priority for each preference.
9828 if (!mOemNetworkPreferences.isEmpty() || !mProfileNetworkPreferences.isEmpty()) {
9829 loge("Ignore mobile data preference change because other preferences are not empty");
9830 return;
9831 }
9832
9833 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
9834 mSystemNetworkRequestCounter.transact(
9835 mDeps.getCallingUid(), 1 /* numOfNewRequests */,
9836 () -> {
9837 final ArraySet<NetworkRequestInfo> nris =
9838 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids);
9839 replaceDefaultNetworkRequestsForPreference(nris);
9840 });
9841 // Finally, rematch.
9842 rematchAllNetworksAndRequests();
9843 }
9844
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009845 private void enforceAutomotiveDevice() {
9846 final boolean isAutomotiveDevice =
9847 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9848 if (!isAutomotiveDevice) {
9849 throw new UnsupportedOperationException(
9850 "setOemNetworkPreference() is only available on automotive devices.");
9851 }
9852 }
9853
9854 /**
9855 * Used by automotive devices to set the network preferences used to direct traffic at an
9856 * application level as per the given OemNetworkPreferences. An example use-case would be an
9857 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9858 * vehicle via a particular network.
9859 *
9860 * Calling this will overwrite the existing preference.
9861 *
9862 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
9863 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
9864 * to communicate completion of setOemNetworkPreference();
9865 */
9866 @Override
9867 public void setOemNetworkPreference(
9868 @NonNull final OemNetworkPreferences preference,
9869 @Nullable final IOnCompleteListener listener) {
9870
9871 enforceAutomotiveDevice();
9872 enforceOemNetworkPreferencesPermission();
9873
paulhu71ad4f12021-05-25 14:56:27 +08009874 // TODO: Have a priority for each preference.
9875 if (!mProfileNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009876 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
9877 // handler thread. However it is an immutable object, so reading the reference is
9878 // safe - it's just possible the value is slightly outdated. For the final check,
9879 // see #handleSetOemPreference. But if this can be caught here it is a
9880 // lot easier to understand, so opportunistically check it.
9881 throwConcurrentPreferenceException();
9882 }
9883
9884 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9885 validateOemNetworkPreferences(preference);
9886 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
9887 new Pair<>(preference, listener)));
9888 }
9889
9890 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
9891 for (@OemNetworkPreferences.OemNetworkPreference final int pref
9892 : preference.getNetworkPreferences().values()) {
9893 if (OemNetworkPreferences.OEM_NETWORK_PREFERENCE_UNINITIALIZED == pref) {
9894 final String msg = "OEM_NETWORK_PREFERENCE_UNINITIALIZED is an invalid value.";
9895 throw new IllegalArgumentException(msg);
9896 }
9897 }
9898 }
9899
9900 private void handleSetOemNetworkPreference(
9901 @NonNull final OemNetworkPreferences preference,
9902 @Nullable final IOnCompleteListener listener) {
9903 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9904 if (DBG) {
9905 log("set OEM network preferences :" + preference.toString());
9906 }
9907 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9908 // particular because it's not clear what preference should win in case both apply
9909 // to the same app.
9910 // The binder call has already checked this, but as mOemNetworkPreferences is only
9911 // touched on the handler thread, it's theoretically not impossible that it has changed
9912 // since.
paulhu71ad4f12021-05-25 14:56:27 +08009913 // TODO: Have a priority for each preference.
9914 if (!mProfileNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) {
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00009915 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
9916 return;
9917 }
9918
9919 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
9920 final int uniquePreferenceCount = new ArraySet<>(
9921 preference.getNetworkPreferences().values()).size();
9922 mSystemNetworkRequestCounter.transact(
9923 mDeps.getCallingUid(), uniquePreferenceCount,
9924 () -> {
9925 final ArraySet<NetworkRequestInfo> nris =
9926 new OemNetworkRequestFactory()
9927 .createNrisFromOemNetworkPreferences(preference);
9928 replaceDefaultNetworkRequestsForPreference(nris);
9929 });
9930 mOemNetworkPreferences = preference;
9931
9932 if (null != listener) {
9933 try {
9934 listener.onComplete();
9935 } catch (RemoteException e) {
9936 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
9937 }
9938 }
9939 }
9940
9941 private void replaceDefaultNetworkRequestsForPreference(
9942 @NonNull final Set<NetworkRequestInfo> nris) {
9943 // Pass in a defensive copy as this collection will be updated on remove.
9944 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
9945 addPerAppDefaultNetworkRequests(nris);
9946 }
9947
9948 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
9949 ensureRunningOnConnectivityServiceThread();
9950 mDefaultNetworkRequests.addAll(nris);
9951 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
9952 getPerAppCallbackRequestsToUpdate();
9953 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
9954 mSystemNetworkRequestCounter.transact(
9955 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
9956 () -> {
9957 nrisToRegister.addAll(
9958 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
9959 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
9960 handleRegisterNetworkRequests(nrisToRegister);
9961 });
9962 }
9963
9964 /**
9965 * All current requests that are tracking the default network need to be assessed as to whether
9966 * or not the current set of per-application default requests will be changing their default
9967 * network. If so, those requests will need to be updated so that they will send callbacks for
9968 * default network changes at the appropriate time. Additionally, those requests tracking the
9969 * default that were previously updated by this flow will need to be reassessed.
9970 * @return the nris which will need to be updated.
9971 */
9972 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
9973 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
9974 // Get the distinct nris to check since for multilayer requests, it is possible to have the
9975 // same nri in the map's values for each of its NetworkRequest objects.
9976 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
9977 for (final NetworkRequestInfo nri : nris) {
9978 // Include this nri if it is currently being tracked.
9979 if (isPerAppTrackedNri(nri)) {
9980 defaultCallbackRequests.add(nri);
9981 continue;
9982 }
9983 // We only track callbacks for requests tracking the default.
9984 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
9985 continue;
9986 }
9987 // Include this nri if it will be tracked by the new per-app default requests.
9988 final boolean isNriGoingToBeTracked =
9989 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
9990 if (isNriGoingToBeTracked) {
9991 defaultCallbackRequests.add(nri);
9992 }
9993 }
9994 return defaultCallbackRequests;
9995 }
9996
9997 /**
9998 * Create nris for those network requests that are currently tracking the default network that
9999 * are being controlled by a per-application default.
10000 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10001 * foundation when creating the nri. Important items include the calling uid's original
10002 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10003 * requests are assumed to have already been validated as needing to be updated.
10004 * @return the Set of nris to use when registering network requests.
10005 */
10006 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10007 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10008 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10009 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10010 final NetworkRequestInfo trackingNri =
10011 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
10012
10013 // If this nri is not being tracked, the change it back to an untracked nri.
10014 if (trackingNri == mDefaultRequest) {
10015 callbackRequestsToRegister.add(new NetworkRequestInfo(
10016 callbackRequest,
10017 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10018 continue;
10019 }
10020
10021 final NetworkRequest request = callbackRequest.mRequests.get(0);
10022 callbackRequestsToRegister.add(new NetworkRequestInfo(
10023 callbackRequest,
10024 copyNetworkRequestsForUid(
10025 trackingNri.mRequests, callbackRequest.mAsUid,
10026 callbackRequest.mUid, request.getRequestorPackageName())));
10027 }
10028 return callbackRequestsToRegister;
10029 }
10030
10031 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10032 @NonNull final Set<UidRange> uids) {
10033 for (final NetworkRequest req : requests) {
10034 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
10035 }
10036 }
10037
10038 /**
10039 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10040 */
10041 @VisibleForTesting
10042 final class OemNetworkRequestFactory {
10043 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
10044 @NonNull final OemNetworkPreferences preference) {
10045 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10046 final SparseArray<Set<Integer>> uids =
10047 createUidsFromOemNetworkPreferences(preference);
10048 for (int i = 0; i < uids.size(); i++) {
10049 final int key = uids.keyAt(i);
10050 final Set<Integer> value = uids.valueAt(i);
10051 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10052 // No need to add an nri without any requests.
10053 if (0 == nri.mRequests.size()) {
10054 continue;
10055 }
10056 nris.add(nri);
10057 }
10058
10059 return nris;
10060 }
10061
10062 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10063 @NonNull final OemNetworkPreferences preference) {
10064 final SparseArray<Set<Integer>> uids = new SparseArray<>();
10065 final PackageManager pm = mContext.getPackageManager();
10066 final List<UserHandle> users =
10067 mContext.getSystemService(UserManager.class).getUserHandles(true);
10068 if (null == users || users.size() == 0) {
10069 if (VDBG || DDBG) {
10070 log("No users currently available for setting the OEM network preference.");
10071 }
10072 return uids;
10073 }
10074 for (final Map.Entry<String, Integer> entry :
10075 preference.getNetworkPreferences().entrySet()) {
10076 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
10077 try {
10078 final int uid = pm.getApplicationInfo(entry.getKey(), 0).uid;
10079 if (!uids.contains(pref)) {
10080 uids.put(pref, new ArraySet<>());
10081 }
10082 for (final UserHandle ui : users) {
10083 // Add the rules for all users as this policy is device wide.
10084 uids.get(pref).add(ui.getUid(uid));
10085 }
10086 } catch (PackageManager.NameNotFoundException e) {
10087 // Although this may seem like an error scenario, it is ok that uninstalled
10088 // packages are sent on a network preference as the system will watch for
10089 // package installations associated with this network preference and update
10090 // accordingly. This is done so as to minimize race conditions on app install.
10091 continue;
10092 }
10093 }
10094 return uids;
10095 }
10096
10097 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10098 @OemNetworkPreferences.OemNetworkPreference final int preference,
10099 @NonNull final Set<Integer> uids) {
10100 final List<NetworkRequest> requests = new ArrayList<>();
10101 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10102 switch (preference) {
10103 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10104 requests.add(createUnmeteredNetworkRequest());
10105 requests.add(createOemPaidNetworkRequest());
10106 requests.add(createDefaultInternetRequestForTransport(
10107 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10108 break;
10109 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10110 requests.add(createUnmeteredNetworkRequest());
10111 requests.add(createOemPaidNetworkRequest());
10112 break;
10113 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10114 requests.add(createOemPaidNetworkRequest());
10115 break;
10116 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10117 requests.add(createOemPrivateNetworkRequest());
10118 break;
10119 default:
10120 // This should never happen.
10121 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10122 + " called with invalid preference of " + preference);
10123 }
10124
10125 final ArraySet ranges = new ArraySet<Integer>();
10126 for (final int uid : uids) {
10127 ranges.add(new UidRange(uid, uid));
10128 }
10129 setNetworkRequestUids(requests, ranges);
10130 return new NetworkRequestInfo(Process.myUid(), requests);
10131 }
10132
10133 private NetworkRequest createUnmeteredNetworkRequest() {
10134 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10135 .addCapability(NET_CAPABILITY_NOT_METERED)
10136 .addCapability(NET_CAPABILITY_VALIDATED);
10137 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10138 }
10139
10140 private NetworkRequest createOemPaidNetworkRequest() {
10141 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10142 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10143 .addCapability(NET_CAPABILITY_OEM_PAID)
10144 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10145 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10146 }
10147
10148 private NetworkRequest createOemPrivateNetworkRequest() {
10149 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10150 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10151 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10152 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10153 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10154 }
10155
10156 private NetworkCapabilities createDefaultPerAppNetCap() {
10157 final NetworkCapabilities netCap = new NetworkCapabilities();
10158 netCap.addCapability(NET_CAPABILITY_INTERNET);
10159 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10160 return netCap;
10161 }
10162 }
10163}