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