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