blob: 569324a84fd064e77f4f64bb2126cd032fb9d293 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Chalard Jeanb552c462018-02-21 18:43:54 +090020import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090023import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070024import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070025import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070026import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070027import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040028import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090030import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jean804b8fb2018-01-30 22:41:41 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090036import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060037import static android.net.NetworkCapabilities.TRANSPORT_VPN;
38
Hugo Benichia0385682017-03-22 17:07:57 +090039import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060040
Wenchao Tongf5ea3402015-03-04 13:26:38 -080041import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080042import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090043import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070044import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.ContentResolver;
47import android.content.Context;
48import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070049import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070051import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090053import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
dalyk1fcb7392018-03-05 12:42:22 -050055import android.net.IIpConnectivityMetrics;
56import android.net.INetdEventCallback;
Haoyu Baidb3c8672012-06-20 14:29:57 -070057import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070058import android.net.INetworkPolicyListener;
59import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070060import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080061import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070062import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010063import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070064import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070065import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070067import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070069import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070070import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090071import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070072import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070073import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070074import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070075import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070076import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000077import android.net.NetworkWatchlistManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070078import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040079import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070080import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040081import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040082import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060083import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090084import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090085import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090086import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080088import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070089import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040090import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070092import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070093import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070094import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Looper;
96import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070097import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070098import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090099import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700100import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -0700101import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700102import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -0800103import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900104import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900105import android.os.ServiceSpecificException;
mswest46386886f2018-03-12 10:34:34 -0700106import android.os.ShellCallback;
107import android.os.ShellCommand;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900108import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700109import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400110import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700112import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700113import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700114import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700115import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900116import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700117import android.util.LocalLog;
118import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600119import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800120import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700121import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500122import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700123import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700124import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
Wink Savilleab9321d2013-06-29 21:10:57 -0700126import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400127import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400128import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700129import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700130import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700131import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700132import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800133import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700134import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700135import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600136import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700137import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900138import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900139import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700141import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400142import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900143import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900144import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
dalyk1fcb7392018-03-05 12:42:22 -0500145import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Hugo Benichi64901e52017-10-19 14:42:40 +0900146import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900147import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100148import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700149import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900150import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700151import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600152import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400153import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900154import com.android.server.connectivity.NetworkNotificationManager;
155import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400156import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700157import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800158import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700159import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100160import com.android.server.connectivity.tethering.TetheringDependencies;
dalyk1fcb7392018-03-05 12:42:22 -0500161import com.android.server.net.BaseNetdEventCallback;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700162import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700163import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900164import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700165import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600166
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700167import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700168
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700169import org.xmlpull.v1.XmlPullParser;
170import org.xmlpull.v1.XmlPullParserException;
171
172import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700174import java.io.FileNotFoundException;
175import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700176import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700178import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700179import java.net.InetAddress;
180import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700181import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700182import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700183import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700184import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700185import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700186import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700187import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700188import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700189import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900190import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600191import java.util.SortedSet;
192import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194/**
195 * @hide
196 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800197public class ConnectivityService extends IConnectivityManager.Stub
198 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900199 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Erik Kline7747fd42017-05-12 16:52:48 +0900201 public static final String DIAG_ARG = "--diag";
202 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900203 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900204
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900205 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700206 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Jake Hamby786e71a2014-02-06 14:43:50 -0800208 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900209 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210
Jeff Sharkey899223b2012-08-04 15:24:58 -0700211 // TODO: create better separation between radio types and network types
212
Robert Greenwalt42acef32009-08-12 16:08:25 -0700213 // how long to wait before switching back to a radio's default network
214 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
215 // system property that can override the above value
216 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
217 "android.telephony.apn-restore";
218
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900219 // How long to wait before putting up a "This network doesn't have an Internet connection,
220 // connect anyway?" dialog after the user selects a network that doesn't validate.
221 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
222
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900223 // Default to 30s linger time-out. Modifiable only for testing.
224 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
225 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
226 @VisibleForTesting
227 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
228
Jeremy Joslin79294842014-12-03 17:15:28 -0800229 // How long to delay to removal of a pending intent based request.
230 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
231 private final int mReleasePendingIntentDelayMs;
232
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900233 private MockableSystemProperties mSystemProperties;
234
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800235 private Tethering mTethering;
236
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700237 private final PermissionMonitor mPermissionMonitor;
238
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700239 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700240
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900241 @VisibleForTesting
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700242 @GuardedBy("mVpns")
Chalard Jeanfb0c87e2018-04-18 19:18:58 +0900243 protected final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700244
Hugo Benichi69744342017-11-27 10:57:16 +0900245 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
246 // a direct call to LockdownVpnTracker.isEnabled().
247 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700248 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900249 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700250 private LockdownVpnTracker mLockdownTracker;
251
Erik Klineda4bfa82015-04-30 12:58:40 +0900252 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700254 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700255 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700258 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700260 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800261 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700262 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900263 private NetworkPolicyManagerInternal mPolicyManagerInternal;
dalyk1fcb7392018-03-05 12:42:22 -0500264 private IIpConnectivityMetrics mIpConnectivityMetrics;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700265
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700266 private String mCurrentTcpBufferSizes;
267
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700268 private static final int ENABLED = 1;
269 private static final int DISABLED = 0;
270
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900271 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900272 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
273 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900274
Paul Jensenb10e37f2014-11-25 12:33:08 -0500275 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400276 // Tear down networks that have no chance (e.g. even if validated) of becoming
277 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500278 // all networks have been rematched against all NetworkRequests.
279 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400280 // Don't reap networks. This should be passed when some networks have not yet been
281 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500282 DONT_REAP
283 };
284
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900285 private enum UnneededFor {
286 LINGER, // Determine whether this network is unneeded and should be lingered.
287 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
288 }
289
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700290 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700291 * used internally to change our mobile data enabled flag
292 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700293 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700294
295 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700296 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700297 * from one net to another. Clear happens when we get a new
298 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
299 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700300 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700301 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700302
Robert Greenwalt434203a2010-10-11 16:00:27 -0700303 /**
304 * used internally to reload global proxy settings
305 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700306 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700307
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700308 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400309 * PAC manager has received new port.
310 */
311 private static final int EVENT_PROXY_HAS_CHANGED = 16;
312
Robert Greenwalte049c232014-04-11 15:53:27 -0700313 /**
314 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700315 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700316 */
317 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
318
Robert Greenwalt7b816022014-04-18 15:25:25 -0700319 /**
320 * used internally when registering NetworkAgents
321 * obj = Messenger
322 */
323 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
324
Robert Greenwalt9258c642014-03-26 16:47:06 -0700325 /**
326 * used to add a network request
327 * includes a NetworkRequestInfo
328 */
329 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
330
331 /**
332 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900333 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700334 * cancel it.
335 * includes a NetworkRequestInfo
336 */
337 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
338
339 /**
340 * used to add a network listener - no request
341 * includes a NetworkRequestInfo
342 */
343 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
344
345 /**
346 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400347 * arg1 = UID of caller
348 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700349 */
350 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
351
Robert Greenwalta67be032014-05-16 15:49:14 -0700352 /**
353 * used internally when registering NetworkFactories
354 * obj = Messenger
355 */
356 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
357
Robert Greenwalt27711812014-06-25 16:45:57 -0700358 /**
359 * used internally to expire a wakelock when transitioning
360 * from one net to another. Expire happens when we fail to find
361 * a new network (typically after 1 minute) -
362 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
363 * a replacement network.
364 */
365 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
366
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700367 /**
368 * Used internally to indicate the system is ready.
369 */
370 private static final int EVENT_SYSTEM_READY = 25;
371
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800372 /**
373 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400374 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800375 */
376 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
377
378 /**
379 * used to remove a pending intent and its associated network request.
380 * arg1 = UID of caller
381 * obj = PendingIntent
382 */
383 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
384
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900385 /**
386 * used to specify whether a network should be used even if unvalidated.
387 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
388 * arg2 = whether to remember this choice in the future (1 or 0)
389 * obj = network
390 */
391 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
392
393 /**
394 * used to ask the user to confirm a connection to an unvalidated network.
395 * obj = network
396 */
397 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700398
Erik Klineda4bfa82015-04-30 12:58:40 +0900399 /**
400 * used internally to (re)configure mobile data always-on settings.
401 */
402 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
403
Paul Jensen694f2b82015-06-17 14:15:39 -0400404 /**
405 * used to add a network listener with a pending intent
406 * obj = NetworkRequestInfo
407 */
408 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
409
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900410 /**
411 * used to specify whether a network should not be penalized when it becomes unvalidated.
412 */
413 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
414
415 /**
416 * used to trigger revalidation of a network.
417 */
418 private static final int EVENT_REVALIDATE_NETWORK = 36;
419
Erik Klinea24d4592018-01-11 21:07:29 +0900420 // Handle changes in Private DNS settings.
421 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
422
dalyk1fcb7392018-03-05 12:42:22 -0500423 // Handle private DNS validation status updates.
424 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
425
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900426 private static String eventName(int what) {
427 return sMagicDecoderRing.get(what, Integer.toString(what));
428 }
429
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900430 /** Handler thread used for both of the handlers below. */
431 @VisibleForTesting
432 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700433 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700434 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700435 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700436 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900437 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700438
Mike Lockwood0f79b542009-08-14 14:18:49 -0400439 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800440 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400441
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700442 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700443 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800444 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700445
Robert Greenwalt434203a2010-10-11 16:00:27 -0700446 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400447 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700448 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700449 private boolean mDefaultProxyDisabled = false;
450
Robert Greenwalt434203a2010-10-11 16:00:27 -0700451 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400452 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700453
Jason Monk602b2322013-07-03 17:04:33 -0400454 private PacManager mPacManager = null;
455
Erik Klineda4bfa82015-04-30 12:58:40 +0900456 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700457
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400458 private UserManager mUserManager;
459
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700460 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700461 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700462
Robert Greenwalt50393202011-06-21 17:26:14 -0700463 // the set of network types that can only be enabled by system/sig apps
464 List mProtectedNetworks;
465
John Spurlockbf991a82013-06-24 14:20:23 -0400466 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700467
Wink Savilleab9321d2013-06-29 21:10:57 -0700468 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400469
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900470 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900471 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900472 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900473
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700474 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800475 private static final int MIN_NET_ID = 100; // some reserved marks
476 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700477 private int mNextNetId = MIN_NET_ID;
478
Robert Greenwalt34524f02014-05-18 16:22:10 -0700479 // sequence number of NetworkRequests
480 private int mNextNetworkRequestId = 1;
481
Erik Kline7523eb32015-07-09 18:24:03 +0900482 // NetworkRequest activity String log entries.
483 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
484 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
485
Hugo Benichic2ae2872016-07-11 11:05:12 +0900486 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900487 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900488 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
489
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900490 private static final int MAX_WAKELOCK_LOGS = 20;
491 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900492 private int mTotalWakelockAcquisitions = 0;
493 private int mTotalWakelockReleases = 0;
494 private long mTotalWakelockDurationMs = 0;
495 private long mMaxWakelockDurationMs = 0;
496 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900497
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700498 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
499 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400500 private static class ValidationLog {
501 final Network mNetwork;
502 final String mNetworkExtraInfo;
503 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700504
Paul Jensen0808eb82016-06-03 13:51:21 -0400505 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
506 mNetwork = network;
507 mNetworkExtraInfo = networkExtraInfo;
508 mLog = log;
509 }
510 }
511 private final ArrayDeque<ValidationLog> mValidationLogs =
512 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
513
514 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900515 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700516 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
517 mValidationLogs.removeLast();
518 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400519 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700520 }
521 }
522
Hugo Benichif9fdf872016-07-28 17:53:06 +0900523 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900524
Erik Kline065ab6e2016-10-02 18:02:14 +0900525 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900526 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900527
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900528 @VisibleForTesting
529 final MultipathPolicyTracker mMultipathPolicyTracker;
530
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700531 /**
532 * Implements support for the legacy "one network per network type" model.
533 *
534 * We used to have a static array of NetworkStateTrackers, one for each
535 * network type, but that doesn't work any more now that we can have,
536 * for example, more that one wifi network. This class stores all the
537 * NetworkAgentInfo objects that support a given type, but the legacy
538 * API will only see the first one.
539 *
540 * It serves two main purposes:
541 *
542 * 1. Provide information about "the network for a given type" (since this
543 * API only supports one).
544 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
545 * the first network for a given type changes, or if the default network
546 * changes.
547 */
548 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900549
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900550 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900551 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700553 /**
554 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
555 * Each list holds references to all NetworkAgentInfos that are used to
556 * satisfy requests for that network type.
557 *
558 * This array is built out at startup such that an unsupported network
559 * doesn't get an ArrayList instance, making this a tristate:
560 * unsupported, supported but not active and active.
561 *
562 * The actual lists are populated when we scan the network types that
563 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900564 *
565 * Threading model:
566 * - addSupportedType() is only called in the constructor
567 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
568 * They are therefore not thread-safe with respect to each other.
569 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
570 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
571 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900573 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574
575 public LegacyTypeTracker() {
576 mTypeLists = (ArrayList<NetworkAgentInfo>[])
577 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
578 }
579
580 public void addSupportedType(int type) {
581 if (mTypeLists[type] != null) {
582 throw new IllegalStateException(
583 "legacy list for type " + type + "already initialized");
584 }
585 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
586 }
587
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700588 public boolean isTypeSupported(int type) {
589 return isNetworkTypeValid(type) && mTypeLists[type] != null;
590 }
591
592 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900593 synchronized (mTypeLists) {
594 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
595 return mTypeLists[type].get(0);
596 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900598 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700599 }
600
Robert Greenwalt8d482522015-06-24 13:23:42 -0700601 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900602 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900603 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700604 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900605 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900606 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607 }
608 }
609
610 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700611 public void add(int type, NetworkAgentInfo nai) {
612 if (!isTypeSupported(type)) {
613 return; // Invalid network type.
614 }
615 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
616
617 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
618 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700619 return;
620 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900621 synchronized (mTypeLists) {
622 list.add(nai);
623 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900624
625 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900627 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700628 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
629 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700631 }
632
Lorenzo Colittia793a672014-07-31 23:20:17 +0900633 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900634 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900635 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
636 if (list == null || list.isEmpty()) {
637 return;
638 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900639 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900640
Hugo Benichi78caa2582016-06-21 09:48:07 +0900641 synchronized (mTypeLists) {
642 if (!list.remove(nai)) {
643 return;
644 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900645 }
646
Robert Greenwalt8d482522015-06-24 13:23:42 -0700647 final DetailedState state = DetailedState.DISCONNECTED;
648
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900649 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700650 maybeLogBroadcast(nai, state, type, wasDefault);
651 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900652 }
653
654 if (!list.isEmpty() && wasFirstNetwork) {
655 if (DBG) log("Other network available for type " + type +
656 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900657 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700658 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
659 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900660 }
661 }
662
663 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900664 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
665 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700666 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900667 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700668 }
669 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700670
Robert Greenwalt8d482522015-06-24 13:23:42 -0700671 // send out another legacy broadcast - currently only used for suspend/unsuspend
672 // toggle
673 public void update(NetworkAgentInfo nai) {
674 final boolean isDefault = isDefaultNetwork(nai);
675 final DetailedState state = nai.networkInfo.getDetailedState();
676 for (int type = 0; type < mTypeLists.length; type++) {
677 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700678 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900679 final boolean isFirst = contains && (nai == list.get(0));
680 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700681 maybeLogBroadcast(nai, state, type, isDefault);
682 sendLegacyNetworkBroadcast(nai, state, type);
683 }
684 }
685 }
686
Lorenzo Colittia793a672014-07-31 23:20:17 +0900687 private String naiToString(NetworkAgentInfo nai) {
688 String name = (nai != null) ? nai.name() : "null";
689 String state = (nai.networkInfo != null) ?
690 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
691 "???/???";
692 return name + " " + state;
693 }
694
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700695 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900696 pw.println("mLegacyTypeTracker:");
697 pw.increaseIndent();
698 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700699 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900700 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700701 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900702 pw.println();
703 pw.println("Current state:");
704 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900705 synchronized (mTypeLists) {
706 for (int type = 0; type < mTypeLists.length; type++) {
707 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
708 for (NetworkAgentInfo nai : mTypeLists[type]) {
709 pw.println(type + " " + naiToString(nai));
710 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900711 }
712 }
713 pw.decreaseIndent();
714 pw.decreaseIndent();
715 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700716 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700717 }
718 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
719
Vishnu Nair5c010902017-10-26 10:08:50 -0700720 /**
721 * Helper class which parses out priority arguments and dumps sections according to their
722 * priority. If priority arguments are omitted, function calls the legacy dump command.
723 */
724 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
725 @Override
726 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
727 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
728 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
729 }
730
731 @Override
732 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
733 doDump(fd, pw, args, asProto);
734 }
735
736 @Override
737 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
738 doDump(fd, pw, args, asProto);
739 }
740 };
741
Jeff Sharkey899223b2012-08-04 15:24:58 -0700742 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700743 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900744 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
745 }
746
747 @VisibleForTesting
748 protected ConnectivityService(Context context, INetworkManagementService netManager,
749 INetworkStatsService statsService, INetworkPolicyManager policyManager,
750 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800751 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800752
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900753 mSystemProperties = getSystemProperties();
754
Hugo Benichif9fdf872016-07-28 17:53:06 +0900755 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900756 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900757 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900758 mNetworkRequests.put(mDefaultRequest, defaultNRI);
759 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900760
Chalard Jeandda156a2018-01-10 21:19:32 +0900761 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900762 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700763
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900764 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900765 mHandlerThread.start();
766 mHandler = new InternalHandler(mHandlerThread.getLooper());
767 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700768
Jeremy Joslin79294842014-12-03 17:15:28 -0800769 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
770 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
771
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900772 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900773
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700774 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700775 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800776 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700777 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900778 mPolicyManagerInternal = checkNotNull(
779 LocalServices.getService(NetworkPolicyManagerInternal.class),
780 "missing NetworkPolicyManagerInternal");
781
Jeff Sharkey82f85212012-08-24 11:17:25 -0700782 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700783 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700784
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700785 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900786 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700787 } catch (RemoteException e) {
788 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700789 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700790 }
791
792 final PowerManager powerManager = (PowerManager) context.getSystemService(
793 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700794 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
795 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
796 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800797 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700798
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700799 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700800
Wink Saville51f456f2013-04-23 14:26:51 -0700801 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900802 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700803 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700804 String[] naStrings = context.getResources().getStringArray(
805 com.android.internal.R.array.networkAttributes);
806 for (String naString : naStrings) {
807 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700808 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700809 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700810 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800811 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700812 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700813 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700814 }
Wink Saville51f456f2013-04-23 14:26:51 -0700815 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
816 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
817 n.type);
818 continue;
819 }
Wink Saville975c8482011-04-07 14:23:45 -0700820 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800821 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700822 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700823 continue;
824 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700825 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700826
Wink Saville975c8482011-04-07 14:23:45 -0700827 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700828 mNetworksDefined++;
829 } catch(Exception e) {
830 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700831 }
832 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700833
834 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
835 if (mNetConfigs[TYPE_VPN] == null) {
836 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
837 // don't need to add TYPE_VPN to mNetConfigs.
838 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
839 mNetworksDefined++; // used only in the log() statement below.
840 }
841
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900842 // Do the same for Ethernet, since it's often not specified in the configs, although many
843 // devices can use it via USB host adapters.
844 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
845 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
846 mNetworksDefined++;
847 }
848
Wink Saville5e56bc52013-07-29 15:00:57 -0700849 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700850
Robert Greenwalt50393202011-06-21 17:26:14 -0700851 mProtectedNetworks = new ArrayList<Integer>();
852 int[] protectedNetworks = context.getResources().getIntArray(
853 com.android.internal.R.array.config_protectedNetworks);
854 for (int p : protectedNetworks) {
855 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
856 mProtectedNetworks.add(p);
857 } else {
858 if (DBG) loge("Ignoring protectedNetwork " + p);
859 }
860 }
861
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900862 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
863 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700864
Erik Kline47222fc2017-04-30 19:36:15 +0900865 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800866
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700867 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
868
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700869 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700870 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100871 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700872 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700873 intentFilter.addAction(Intent.ACTION_USER_ADDED);
874 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000875 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700876 mContext.registerReceiverAsUser(
877 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000878 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
879 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900880
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700881 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700882 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700883 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700884 } catch (RemoteException e) {
885 loge("Error registering observer :" + e);
886 }
887
Erik Klineda4bfa82015-04-30 12:58:40 +0900888 mSettingsObserver = new SettingsObserver(mContext, mHandler);
889 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800890
John Spurlockbf991a82013-06-24 14:20:23 -0400891 mDataConnectionStats = new DataConnectionStats(mContext);
892 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400893
Jason Monkdecd2952013-10-10 14:02:51 -0400894 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700895
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400896 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900897
898 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900899 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
900 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900901
902 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
903 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
904 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
905 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
906 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
907 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
908 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900909
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900910 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900911 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900912 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900913
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900914 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
915
Erik Kline1742fe12017-12-13 19:40:49 +0900916 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900917 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700919
Erik Kline47222fc2017-04-30 19:36:15 +0900920 private Tethering makeTethering() {
921 // TODO: Move other elements into @Overridden getters.
Erik Kline7a26ba32018-03-09 14:18:02 +0900922 final TetheringDependencies deps = new TetheringDependencies() {
923 @Override
924 public boolean isTetheringSupported() {
925 return ConnectivityService.this.isTetheringSupported();
926 }
927 };
Erik Kline47222fc2017-04-30 19:36:15 +0900928 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
929 IoThread.get().getLooper(), new MockableSystemProperties(),
930 deps);
931 }
932
Chalard Jeandda156a2018-01-10 21:19:32 +0900933 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900934 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900935 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900936 netCap.addCapability(NET_CAPABILITY_INTERNET);
937 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900938 if (transportType > -1) {
939 netCap.addTransportType(transportType);
940 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900941 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900942 }
943
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900944 // Used only for testing.
945 // TODO: Delete this and either:
Erik Kline79c6d052018-03-21 07:18:33 -0700946 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900947 // changing ContentResolver to make registerContentObserver non-final).
948 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
949 // by subclassing SettingsObserver.
950 @VisibleForTesting
951 void updateMobileDataAlwaysOn() {
952 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
953 }
954
Erik Kline79c6d052018-03-21 07:18:33 -0700955 // See FakeSettingsProvider comment above.
956 @VisibleForTesting
957 void updatePrivateDnsSettings() {
958 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
959 }
960
Erik Klineda4bfa82015-04-30 12:58:40 +0900961 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900962 final boolean enable = toBool(Settings.Global.getInt(
963 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900964 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
965 if (enable == isEnabled) {
966 return; // Nothing to do.
967 }
968
969 if (enable) {
970 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900971 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900972 } else {
973 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
974 }
975 }
976
977 private void registerSettingsCallbacks() {
978 // Watch for global HTTP proxy changes.
979 mSettingsObserver.observe(
980 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
981 EVENT_APPLY_GLOBAL_HTTP_PROXY);
982
983 // Watch for whether or not to keep mobile data always on.
984 mSettingsObserver.observe(
985 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
986 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
987 }
988
Erik Klinea24d4592018-01-11 21:07:29 +0900989 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline79c6d052018-03-21 07:18:33 -0700990 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
991 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Klinea24d4592018-01-11 21:07:29 +0900992 }
993 }
994
Robert Greenwalt34524f02014-05-18 16:22:10 -0700995 private synchronized int nextNetworkRequestId() {
996 return mNextNetworkRequestId++;
997 }
998
Paul Jensen67b0b072015-06-10 11:22:17 -0400999 @VisibleForTesting
1000 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -04001001 synchronized (mNetworkForNetId) {
1002 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
1003 int netId = mNextNetId;
1004 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
1005 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -05001006 if (!mNetIdInUse.get(netId)) {
1007 mNetIdInUse.put(netId, true);
1008 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -04001009 }
1010 }
1011 }
1012 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001013 }
1014
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001015 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001016 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001017 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1018 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001019 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001020 state = nai.getNetworkState();
1021 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001022 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001023 final NetworkInfo info = new NetworkInfo(networkType, 0,
1024 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1026 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001027 final NetworkCapabilities capabilities = new NetworkCapabilities();
1028 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1029 !info.isRoaming());
1030 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001031 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001032 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001033 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001034 return state;
1035 } else {
1036 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001037 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001038 }
1039
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001040 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1041 if (network == null) {
1042 return null;
1043 }
Erik Kline79c6d052018-03-21 07:18:33 -07001044 return getNetworkAgentInfoForNetId(network.netId);
1045 }
1046
1047 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001048 synchronized (mNetworkForNetId) {
Erik Kline79c6d052018-03-21 07:18:33 -07001049 return mNetworkForNetId.get(netId);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001051 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001052
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001053 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001054 synchronized (mVpns) {
1055 if (!mLockdownEnabled) {
1056 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001057 Vpn vpn = mVpns.get(user);
1058 if (vpn != null && vpn.appliesToUid(uid)) {
1059 return vpn.getUnderlyingNetworks();
1060 }
1061 }
1062 }
1063 return null;
1064 }
1065
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001066 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001067 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001068
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001069 final Network[] networks = getVpnUnderlyingNetworks(uid);
1070 if (networks != null) {
1071 // getUnderlyingNetworks() returns:
1072 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1073 // empty array => the VPN explicitly said "no default network".
1074 // non-empty array => the VPN specified one or more default networks; we use the
1075 // first one.
1076 if (networks.length > 0) {
1077 nai = getNetworkAgentInfoForNetwork(networks[0]);
1078 } else {
1079 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001080 }
1081 }
1082
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001083 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001084 return nai.getNetworkState();
1085 } else {
1086 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001087 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001088 }
1089
1090 /**
1091 * Check if UID should be blocked from using the network with the given LinkProperties.
1092 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001093 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1094 boolean ignoreBlocked) {
1095 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001096 if (ignoreBlocked) {
1097 return false;
1098 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001099 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001100 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1101 if (isSystem(uid)) {
1102 return false;
1103 }
Robin Lee17e61832016-05-09 13:46:28 +01001104 synchronized (mVpns) {
1105 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1106 if (vpn != null && vpn.isBlockingUid(uid)) {
1107 return true;
1108 }
1109 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001110 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001111 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001112 }
1113
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001114 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001115 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1116 return;
1117 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001118 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001119 synchronized (mBlockedAppUids) {
1120 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001121 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001122 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001123 blocked = false;
1124 } else {
1125 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001126 }
1127 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001128 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1129 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1130 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001131 }
1132
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001133 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001134 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1135 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001136 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001137 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001139 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1140
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001141 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001142 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001143 }
Hugo Benichi69744342017-11-27 10:57:16 +09001144 synchronized (mVpns) {
1145 if (mLockdownTracker != null) {
1146 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1147 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001148 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001149 }
1150
1151 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 * Return NetworkInfo for the active (i.e., connected) network interface.
1153 * It is assumed that at most one network is active at a time. If more
1154 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001155 * @return the info for the active network, or {@code null} if none is
1156 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001158 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001160 enforceAccessPermission();
1161 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001162 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001163 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001164 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1165 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167
Paul Jensen31a94f42015-02-13 14:18:39 -05001168 @Override
1169 public Network getActiveNetwork() {
1170 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001172 }
1173
1174 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001175 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001176 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001178 }
1179
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001180 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001181 final int user = UserHandle.getUserId(uid);
1182 int vpnNetId = NETID_UNSET;
1183 synchronized (mVpns) {
1184 final Vpn vpn = mVpns.get(user);
1185 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1186 }
1187 NetworkAgentInfo nai;
1188 if (vpnNetId != NETID_UNSET) {
Erik Kline79c6d052018-03-21 07:18:33 -07001189 nai = getNetworkAgentInfoForNetId(vpnNetId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001190 if (nai != null) return nai.network;
1191 }
1192 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001193 if (nai != null
1194 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1195 nai = null;
1196 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001197 return nai != null ? nai.network : null;
1198 }
1199
Lorenzo Colitti18660282016-07-04 12:55:44 +09001200 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001201 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1202 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 final int uid = Binder.getCallingUid();
1204 NetworkState state = getUnfilteredActiveNetworkState(uid);
1205 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001206 }
1207
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001208 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001209 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001210 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001211 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001212 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001213 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001214 }
1215
1216 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 public NetworkInfo getNetworkInfo(int networkType) {
1218 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001219 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001220 if (getVpnUnderlyingNetworks(uid) != null) {
1221 // A VPN is active, so we may need to return one of its underlying networks. This
1222 // information is not available in LegacyTypeTracker, so we have to get it from
1223 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001224 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001225 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001226 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001227 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001228 }
1229 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001230 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001231 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001234 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001235 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001237 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001238 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001239 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001240 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001241 return state.networkInfo;
1242 } else {
1243 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001244 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001245 }
1246
1247 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 public NetworkInfo[] getAllNetworkInfo() {
1249 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001250 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001251 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1252 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001253 NetworkInfo info = getNetworkInfo(networkType);
1254 if (info != null) {
1255 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001258 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 }
1260
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001261 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001262 public Network getNetworkForType(int networkType) {
1263 enforceAccessPermission();
1264 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001265 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1266 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001267 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001268 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001269 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001270 }
1271
1272 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001273 public Network[] getAllNetworks() {
1274 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001275 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001276 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001277 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001278 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001279 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001280 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001281 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 }
1283
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001284 @Override
1285 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1286 // The basic principle is: if an app's traffic could possibly go over a
1287 // network, without the app doing anything multinetwork-specific,
1288 // (hence, by "default"), then include that network's capabilities in
1289 // the array.
1290 //
1291 // In the normal case, app traffic only goes over the system's default
1292 // network connection, so that's the only network returned.
1293 //
1294 // With a VPN in force, some app traffic may go into the VPN, and thus
1295 // over whatever underlying networks the VPN specifies, while other app
1296 // traffic may go over the system default network (e.g.: a split-tunnel
1297 // VPN, or an app disallowed by the VPN), so the set of networks
1298 // returned includes the VPN's underlying networks and the system
1299 // default.
1300 enforceAccessPermission();
1301
1302 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1303
1304 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001305 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001306 if (nc != null) {
1307 result.put(nai.network, nc);
1308 }
1309
Hugo Benichi69744342017-11-27 10:57:16 +09001310 synchronized (mVpns) {
1311 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001312 Vpn vpn = mVpns.get(userId);
1313 if (vpn != null) {
1314 Network[] networks = vpn.getUnderlyingNetworks();
1315 if (networks != null) {
1316 for (Network network : networks) {
1317 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001318 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001319 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001320 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001321 }
1322 }
1323 }
1324 }
1325 }
1326 }
1327
1328 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1329 out = result.values().toArray(out);
1330 return out;
1331 }
1332
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001334 public boolean isNetworkSupported(int networkType) {
1335 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001336 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001337 }
1338
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001339 /**
1340 * Return LinkProperties for the active (i.e., connected) default
1341 * network interface. It is assumed that at most one default network
1342 * is active at a time. If more than one is active, it is indeterminate
1343 * which will be returned.
1344 * @return the ip properties for the active network, or {@code null} if
1345 * none is active
1346 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001347 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001348 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001349 enforceAccessPermission();
1350 final int uid = Binder.getCallingUid();
1351 NetworkState state = getUnfilteredActiveNetworkState(uid);
1352 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001353 }
1354
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001356 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001357 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001358 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1359 if (nai != null) {
1360 synchronized (nai) {
1361 return new LinkProperties(nai.linkProperties);
1362 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001363 }
1364 return null;
1365 }
1366
Robert Greenwalt12e67352014-05-13 21:41:06 -07001367 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001368 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001369 public LinkProperties getLinkProperties(Network network) {
1370 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001371 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1372 }
1373
1374 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1375 if (nai == null) {
1376 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001377 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001378 synchronized (nai) {
1379 return new LinkProperties(nai.linkProperties);
1380 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001381 }
1382
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001383 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001384 if (nai != null) {
1385 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001386 if (nai.networkCapabilities != null) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001387 return networkCapabilitiesRestrictedForCallerPermissions(
1388 nai.networkCapabilities,
Chalard Jeanb552c462018-02-21 18:43:54 +09001389 Binder.getCallingPid(), Binder.getCallingUid());
Sanket Padawe7094d222015-05-01 16:55:00 -07001390 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001391 }
1392 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001393 return null;
1394 }
1395
1396 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001397 public NetworkCapabilities getNetworkCapabilities(Network network) {
1398 enforceAccessPermission();
1399 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1400 }
1401
Chalard Jeanb03a6222018-04-11 21:09:10 +09001402 private NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09001403 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09001404 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
1405 if (!checkSettingsPermission(callerPid, callerUid)) newNc.setUids(null);
Chalard Jeanb5120ca2018-04-16 12:25:22 +09001406 if (!checkSettingsPermission(callerPid, callerUid)) newNc.setSSID(null);
Chalard Jeanb03a6222018-04-11 21:09:10 +09001407 return newNc;
Chalard Jeanf19db372018-01-26 19:24:40 +09001408 }
1409
Chalard Jeanb552c462018-02-21 18:43:54 +09001410 private void restrictRequestUidsForCaller(NetworkCapabilities nc) {
1411 if (!checkSettingsPermission()) {
1412 nc.setSingleUid(Binder.getCallingUid());
1413 }
1414 }
1415
Chalard Jean26aa91a2018-03-20 19:13:57 +09001416 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
1417 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
1418 nc.addCapability(NET_CAPABILITY_FOREGROUND);
1419 }
1420 }
1421
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001422 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001423 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001424 // Require internal since we're handing out IMSI details
1425 enforceConnectivityInternalPermission();
1426
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001427 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001428 for (Network network : getAllNetworks()) {
1429 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1430 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001431 // TODO (b/73321673) : NetworkState contains a copy of the
1432 // NetworkCapabilities, which may contain UIDs of apps to which the
1433 // network applies. Should the UIDs be cleared so as not to leak or
1434 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001435 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001436 }
1437 }
1438 return result.toArray(new NetworkState[result.size()]);
1439 }
1440
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001441 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001442 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001443 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001444 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1445 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1446 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001447 }
1448
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001449 @Override
1450 public boolean isActiveNetworkMetered() {
1451 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001452
Eric Enslenc81ef192018-02-07 18:03:53 -08001453 final int uid = Binder.getCallingUid();
1454 final NetworkCapabilities caps = getUnfilteredActiveNetworkState(uid).networkCapabilities;
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001455 if (caps != null) {
1456 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1457 } else {
1458 // Always return the most conservative value
1459 return true;
1460 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001461 }
1462
Jeff Sharkey216c1812012-08-05 14:29:23 -07001463 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1464 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001465 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001466 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001467 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001468 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001469 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001470
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001471 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 * Ensure that a network route exists to deliver traffic to the specified
1473 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001474 * @param networkType the type of the network over which traffic to the
1475 * specified host is to be routed
1476 * @param hostAddress the IP address of the host to which the route is
1477 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 * @return {@code true} on success, {@code false} on failure
1479 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001480 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001481 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001483 if (mProtectedNetworks.contains(networkType)) {
1484 enforceConnectivityInternalPermission();
1485 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001486
Chad Brubakerc0234532014-02-14 13:24:29 -08001487 InetAddress addr;
1488 try {
1489 addr = InetAddress.getByAddress(hostAddress);
1490 } catch (UnknownHostException e) {
1491 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1492 return false;
1493 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001496 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 return false;
1498 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001499
1500 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1501 if (nai == null) {
1502 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1503 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1504 } else {
1505 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1506 }
1507 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001508 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001509
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001510 DetailedState netState;
1511 synchronized (nai) {
1512 netState = nai.networkInfo.getDetailedState();
1513 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001514
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001515 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001516 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001517 log("requestRouteToHostAddress on down network "
1518 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001519 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001520 }
1521 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001523
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001524 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001525 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001526 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001527 LinkProperties lp;
1528 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001529 synchronized (nai) {
1530 lp = nai.linkProperties;
1531 netId = nai.network.netId;
1532 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001533 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001534 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1535 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001536 } finally {
1537 Binder.restoreCallingIdentity(token);
1538 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001539 }
1540
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001541 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001542 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001543 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001544 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001545 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001546 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001547 if (bestRoute.getGateway().equals(addr)) {
1548 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001549 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001550 } else {
1551 // if we will connect to this through another route, add a direct route
1552 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001553 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001554 }
1555 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001556 if (DBG) log("Adding legacy route " + bestRoute +
1557 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001558 try {
1559 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1560 } catch (Exception e) {
1561 // never crash - catch them all
1562 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001563 return false;
1564 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001565 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 }
1567
dalyk1fcb7392018-03-05 12:42:22 -05001568 @VisibleForTesting
1569 protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
1570 @Override
1571 public void onPrivateDnsValidationEvent(int netId, String ipAddress,
1572 String hostname, boolean validated) {
1573 try {
1574 mHandler.sendMessage(mHandler.obtainMessage(
1575 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
1576 new PrivateDnsValidationUpdate(netId,
1577 InetAddress.parseNumericAddress(ipAddress),
1578 hostname, validated)));
1579 } catch (IllegalArgumentException e) {
1580 loge("Error parsing ip address in validation event");
1581 }
1582 }
1583 };
1584
1585 @VisibleForTesting
1586 protected void registerNetdEventCallback() {
1587 mIpConnectivityMetrics =
1588 (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1589 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1590 if (mIpConnectivityMetrics == null) {
1591 Slog.wtf(TAG, "Missing IIpConnectivityMetrics");
1592 }
1593
1594 try {
1595 mIpConnectivityMetrics.addNetdEventCallback(
1596 INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
1597 mNetdEventCallback);
1598 } catch (Exception e) {
1599 loge("Error registering netd callback: " + e);
1600 }
1601 }
1602
Jeff Sharkey75d31892018-01-18 22:01:59 +09001603 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001604 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001605 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001606 // TODO: notify UID when it has requested targeted updates
1607 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001608 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001609 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001610 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001611 if (restrictBackground) {
1612 log("onRestrictBackgroundChanged(true): disabling tethering");
1613 mTethering.untetherAll();
1614 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001615 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001616 };
1617
Robin Lee3b3dd942015-05-12 18:14:58 +01001618 /**
1619 * Require that the caller is either in the same user or has appropriate permission to interact
1620 * across users.
1621 *
1622 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1623 */
1624 private void enforceCrossUserPermission(int userId) {
1625 if (userId == UserHandle.getCallingUserId()) {
1626 // Not a cross-user call.
1627 return;
1628 }
1629 mContext.enforceCallingOrSelfPermission(
1630 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1631 "ConnectivityService");
1632 }
1633
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001634 private void enforceInternetPermission() {
1635 mContext.enforceCallingOrSelfPermission(
1636 android.Manifest.permission.INTERNET,
1637 "ConnectivityService");
1638 }
1639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001641 mContext.enforceCallingOrSelfPermission(
1642 android.Manifest.permission.ACCESS_NETWORK_STATE,
1643 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645
1646 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001647 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649
Charles He36738632017-05-15 17:07:18 +01001650 private void enforceSettingsPermission() {
1651 mContext.enforceCallingOrSelfPermission(
1652 android.Manifest.permission.NETWORK_SETTINGS,
1653 "ConnectivityService");
1654 }
1655
Chalard Jeanb552c462018-02-21 18:43:54 +09001656 private boolean checkSettingsPermission() {
1657 return PERMISSION_GRANTED == mContext.checkCallingOrSelfPermission(
1658 android.Manifest.permission.NETWORK_SETTINGS);
1659 }
1660
1661 private boolean checkSettingsPermission(int pid, int uid) {
1662 return PERMISSION_GRANTED == mContext.checkPermission(
1663 android.Manifest.permission.NETWORK_SETTINGS, pid, uid);
1664 }
1665
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001666 private void enforceTetherAccessPermission() {
1667 mContext.enforceCallingOrSelfPermission(
1668 android.Manifest.permission.ACCESS_NETWORK_STATE,
1669 "ConnectivityService");
1670 }
1671
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001672 private void enforceConnectivityInternalPermission() {
1673 mContext.enforceCallingOrSelfPermission(
1674 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1675 "ConnectivityService");
1676 }
1677
Hugo Benichi514da602016-07-19 15:59:27 +09001678 private void enforceConnectivityRestrictedNetworksPermission() {
1679 try {
1680 mContext.enforceCallingOrSelfPermission(
1681 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1682 "ConnectivityService");
1683 return;
1684 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1685 enforceConnectivityInternalPermission();
1686 }
1687
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001688 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001689 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001690 }
1691
Lorenzo Colitti18660282016-07-04 12:55:44 +09001692 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001693 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001694 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001695 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001696 }
1697
1698 private void sendInetConditionBroadcast(NetworkInfo info) {
1699 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1700 }
1701
Wink Saville628b0852011-08-04 15:01:58 -07001702 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001703 synchronized (mVpns) {
1704 if (mLockdownTracker != null) {
1705 info = new NetworkInfo(info);
1706 mLockdownTracker.augmentNetworkInfo(info);
1707 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001708 }
1709
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001710 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001711 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001712 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 if (info.isFailover()) {
1714 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1715 info.setFailover(false);
1716 }
1717 if (info.getReason() != null) {
1718 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1719 }
1720 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001721 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1722 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001724 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001725 return intent;
1726 }
1727
1728 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1729 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1730 }
1731
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001732 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001733 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1734 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1735 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001736 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001737 final long ident = Binder.clearCallingIdentity();
1738 try {
1739 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1740 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1741 } finally {
1742 Binder.restoreCallingIdentity(ident);
1743 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001744 }
1745
Mike Lockwood0f79b542009-08-14 14:18:49 -04001746 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001747 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001748 if (!mSystemReady) {
1749 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001750 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001751 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001752 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001753 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001754 }
1755
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001756 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001757 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001758 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001759 final NetworkInfo ni = intent.getParcelableExtra(
1760 ConnectivityManager.EXTRA_NETWORK_INFO);
1761 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1762 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1763 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001764 } else {
1765 BroadcastOptions opts = BroadcastOptions.makeBasic();
1766 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1767 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001768 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001769 final IBatteryStats bs = BatteryStatsService.getService();
1770 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001771 bs.noteConnectivityChanged(intent.getIntExtra(
1772 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1773 ni != null ? ni.getState().toString() : "?");
1774 } catch (RemoteException e) {
1775 }
Chad Brubakerac925012018-03-08 10:37:09 -08001776 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001777 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001778 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001779 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001780 } finally {
1781 Binder.restoreCallingIdentity(ident);
1782 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001783 }
1784 }
1785
1786 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001787 loadGlobalProxy();
dalyk1fcb7392018-03-05 12:42:22 -05001788 registerNetdEventCallback();
Wink Saville948282b2013-08-29 08:55:16 -07001789
Hugo Benichi20035e02017-04-26 14:53:28 +09001790 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001791 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001792 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001793 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001794 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001795 }
1796 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001797 // load the global proxy at startup
1798 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001799
Robin Lee244ce8e2016-01-05 18:03:46 +00001800 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1801 // for user to unlock device too.
1802 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001803
Erik Klineda4bfa82015-04-30 12:58:40 +09001804 // Configure whether mobile data is always on.
1805 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1806
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001807 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001808
1809 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
1811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001813 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001814 *
1815 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001816 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001817 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001818 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1819 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001820
1821 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001822 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001823
Robert Greenwalt7b816022014-04-18 15:25:25 -07001824 if (networkAgent.networkCapabilities.hasTransport(
1825 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001826 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1827 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001828 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001829 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001830 } else if (networkAgent.networkCapabilities.hasTransport(
1831 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001832 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1833 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001834 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001835 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001836 } else {
1837 // do not track any other networks
1838 timeout = 0;
1839 }
1840
Robert Greenwalt7b816022014-04-18 15:25:25 -07001841 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001842 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001843 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001844 } catch (Exception e) {
1845 // You shall not crash!
1846 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001847 }
1848 }
1849 }
1850
1851 /**
1852 * Remove data activity tracking when network disconnects.
1853 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001854 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1855 final String iface = networkAgent.linkProperties.getInterfaceName();
1856 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001857
Robert Greenwalt7b816022014-04-18 15:25:25 -07001858 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1859 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001860 try {
1861 // the call fails silently if no idletimer setup for this interface
1862 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001863 } catch (Exception e) {
1864 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001865 }
1866 }
1867 }
1868
1869 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001870 * Reads the network specific MTU size from reources.
1871 * and set it on it's iface.
1872 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001873 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1874 final String iface = newLp.getInterfaceName();
1875 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001876 if (oldLp == null && mtu == 0) {
1877 // Silently ignore unset MTU value.
1878 return;
1879 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001880 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1881 if (VDBG) log("identical MTU - not setting");
1882 return;
1883 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001884 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001885 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001886 return;
1887 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001888
w1997615afd812014-08-05 15:18:11 -07001889 // Cannot set MTU without interface name
1890 if (TextUtils.isEmpty(iface)) {
1891 loge("Setting MTU size with null iface.");
1892 return;
1893 }
1894
Robert Greenwalt7b816022014-04-18 15:25:25 -07001895 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001896 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001897 mNetd.setMtu(iface, mtu);
1898 } catch (Exception e) {
1899 Slog.e(TAG, "exception in setMtu()" + e);
1900 }
1901 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001902
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001903 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001904 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1905
1906 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001907 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001908 protected MockableSystemProperties getSystemProperties() {
1909 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001910 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001911
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001912 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1913 if (isDefaultNetwork(nai) == false) {
1914 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001915 }
1916
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001917 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1918 String[] values = null;
1919 if (tcpBufferSizes != null) {
1920 values = tcpBufferSizes.split(",");
1921 }
1922
1923 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001924 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001925 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1926 values = tcpBufferSizes.split(",");
1927 }
1928
1929 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1930
1931 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001932 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001933
1934 final String prefix = "/sys/kernel/ipv4/tcp_";
1935 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1936 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1937 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1938 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1939 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1940 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1941 mCurrentTcpBufferSizes = tcpBufferSizes;
1942 } catch (IOException e) {
1943 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001944 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001945
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001946 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001947 Settings.Global.TCP_DEFAULT_INIT_RWND,
1948 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001949 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1950 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001951 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001952 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001953 }
1954
Robert Greenwalt562cc542014-05-15 18:07:26 -07001955 @Override
1956 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001957 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001958 NETWORK_RESTORE_DELAY_PROP_NAME);
1959 if(restoreDefaultNetworkDelayStr != null &&
1960 restoreDefaultNetworkDelayStr.length() != 0) {
1961 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001962 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001963 } catch (NumberFormatException e) {
1964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001966 // if the system property isn't set, use the value for the apn type
1967 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1968
1969 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1970 (mNetConfigs[networkType] != null)) {
1971 ret = mNetConfigs[networkType].restoreTime;
1972 }
1973 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
1975
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001976 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001977 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001978 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001979 }
1980 return false;
1981 }
1982
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001983 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1984 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1985 final long DIAG_TIME_MS = 5000;
1986 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1987 // Start gathering diagnostic information.
1988 netDiags.add(new NetworkDiagnostics(
1989 nai.network,
1990 new LinkProperties(nai.linkProperties), // Must be a copy.
1991 DIAG_TIME_MS));
1992 }
1993
1994 for (NetworkDiagnostics netDiag : netDiags) {
1995 pw.println();
1996 netDiag.waitForMeasurements();
1997 netDiag.dump(pw);
1998 }
1999 }
2000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002002 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07002003 PriorityDump.dump(mPriorityDumper, fd, writer, args);
2004 }
2005
2006 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002007 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002008 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07002009 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002010
Erik Kline7747fd42017-05-12 16:52:48 +09002011 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002012 dumpNetworkDiagnostics(pw);
2013 return;
Erik Klineee363c42017-05-29 09:11:03 +09002014 } else if (argsContain(args, TETHERING_ARG)) {
2015 mTethering.dump(fd, pw, args);
2016 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002017 }
Erik Kline379747a2015-06-05 17:47:34 +09002018
Lorenzo Colittie3805462015-06-03 11:18:24 +09002019 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07002020 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002021 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07002022 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09002023 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07002024 pw.println();
2025
Paul Jensen85cf78e2015-06-25 13:25:07 -04002026 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002027 pw.print("Active default network: ");
2028 if (defaultNai == null) {
2029 pw.println("none");
2030 } else {
2031 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002033 pw.println();
2034
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002035 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002036 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002037 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2038 pw.println(nai.toString());
2039 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002040 pw.println(String.format(
2041 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2042 nai.numForegroundNetworkRequests(),
2043 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2044 nai.numBackgroundNetworkRequests(),
2045 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002046 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002047 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2048 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002049 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002050 pw.decreaseIndent();
2051 pw.println("Lingered:");
2052 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002053 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002054 pw.decreaseIndent();
2055 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002056 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002057 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002058 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002059
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002060 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002061 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002062 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2063 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002064 }
2065 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002066 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002067
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002068 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002069
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002070 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002071 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002072
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002073 pw.println();
2074 mKeepaliveTracker.dump(pw);
2075
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002076 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002077 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002078
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002079 pw.println();
2080 mMultipathPolicyTracker.dump(pw);
2081
Erik Kline7747fd42017-05-12 16:52:48 +09002082 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002083 pw.println();
2084 synchronized (mValidationLogs) {
2085 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002086 for (ValidationLog p : mValidationLogs) {
2087 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002088 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002089 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002090 pw.decreaseIndent();
2091 }
2092 }
Erik Kline7523eb32015-07-09 18:24:03 +09002093
2094 pw.println();
2095 pw.println("mNetworkRequestInfoLogs (most recent first):");
2096 pw.increaseIndent();
2097 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2098 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002099
2100 pw.println();
2101 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2102 pw.increaseIndent();
2103 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2104 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002105
2106 pw.println();
2107 pw.println("NetTransition WakeLock activity (most recent first):");
2108 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002109 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2110 pw.println("total releases: " + mTotalWakelockReleases);
2111 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2112 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2113 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2114 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2115 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2116 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002117 mWakelockLogs.reverseDump(fd, pw, args);
2118 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
2121
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002122 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002123 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002124 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002125 if (officialNai != null && officialNai.equals(nai)) return true;
2126 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002127 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002128 " - " + nai);
2129 }
2130 return false;
2131 }
2132
Robert Greenwalt42acef32009-08-12 16:08:25 -07002133 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002134 private class NetworkStateTrackerHandler extends Handler {
2135 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002136 super(looper);
2137 }
2138
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002139 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002141 default:
2142 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002143 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 handleAsyncChannelHalfConnect(msg);
2145 break;
2146 }
2147 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2148 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2149 if (nai != null) nai.asyncChannel.disconnect();
2150 break;
2151 }
2152 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2153 handleAsyncChannelDisconnected(msg);
2154 break;
2155 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002156 }
2157 return true;
2158 }
2159
2160 private void maybeHandleNetworkAgentMessage(Message msg) {
2161 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2162 if (nai == null) {
2163 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002164 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002165 }
2166 return;
2167 }
2168
2169 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002170 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002171 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2172 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002173 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2174 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002175 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002176 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002177 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002178 break;
2179 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002180 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002181 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002182 break;
2183 }
2184 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002185 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002186 updateNetworkInfo(nai, info);
2187 break;
2188 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002189 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002190 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002191 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002192 break;
2193 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002194 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002195 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2196 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002197 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002198 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002199 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002200 break;
2201 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002202 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002203 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2204 break;
2205 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002206 }
2207 }
2208
2209 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2210 switch (msg.what) {
2211 default:
2212 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002213 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002214 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002215 if (nai == null) break;
2216
2217 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2218 final boolean wasValidated = nai.lastValidated;
2219 final boolean wasDefault = isDefaultNetwork(nai);
2220
Erik Klinea24d4592018-01-11 21:07:29 +09002221 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2222
Erik Klinea24d4592018-01-11 21:07:29 +09002223 if (DBG) {
Erik Kline79c6d052018-03-21 07:18:33 -07002224 final String logMsg = !TextUtils.isEmpty(redirectUrl)
2225 ? " with redirect to " + redirectUrl
2226 : "";
Erik Klinea24d4592018-01-11 21:07:29 +09002227 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2228 }
Erik Klinea24d4592018-01-11 21:07:29 +09002229 if (valid != nai.lastValidated) {
2230 if (wasDefault) {
2231 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2232 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002233 }
Erik Klinea24d4592018-01-11 21:07:29 +09002234 final int oldScore = nai.getCurrentScore();
2235 nai.lastValidated = valid;
2236 nai.everValidated |= valid;
2237 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2238 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2239 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2240 }
2241 updateInetCondition(nai);
2242 // Let the NetworkAgent know the state of its network
2243 Bundle redirectUrlBundle = new Bundle();
2244 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2245 nai.asyncChannel.sendMessage(
2246 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2247 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2248 0, redirectUrlBundle);
2249 if (wasValidated && !nai.lastValidated) {
2250 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002251 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002252 break;
2253 }
Paul Jensen869868be2014-05-15 10:33:05 -04002254 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002255 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002256 final boolean visible = toBool(msg.arg1);
Erik Kline79c6d052018-03-21 07:18:33 -07002257 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Onbe96da12016-10-11 15:10:46 -07002258 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002259 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002260 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002261 nai.lastCaptivePortalDetected = visible;
2262 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002263 if (nai.lastCaptivePortalDetected &&
2264 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2265 if (DBG) log("Avoiding captive portal network: " + nai.name());
2266 nai.asyncChannel.sendMessage(
2267 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2268 teardownUnneededNetwork(nai);
2269 break;
2270 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002271 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002272 }
2273 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002274 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002275 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002276 if (nai == null) {
2277 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2278 break;
2279 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002280 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002281 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002282 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002283 }
Paul Jensen869868be2014-05-15 10:33:05 -04002284 }
Paul Jensen869868be2014-05-15 10:33:05 -04002285 break;
2286 }
Erik Klinea24d4592018-01-11 21:07:29 +09002287 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline79c6d052018-03-21 07:18:33 -07002288 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Klinea24d4592018-01-11 21:07:29 +09002289 if (nai == null) break;
2290
Erik Kline79c6d052018-03-21 07:18:33 -07002291 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Klinea24d4592018-01-11 21:07:29 +09002292 break;
2293 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002294 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002295 return true;
2296 }
2297
Calvin Onbe96da12016-10-11 15:10:46 -07002298 private int getCaptivePortalMode() {
2299 return Settings.Global.getInt(mContext.getContentResolver(),
2300 Settings.Global.CAPTIVE_PORTAL_MODE,
2301 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2302 }
2303
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002304 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2305 switch (msg.what) {
2306 default:
2307 return false;
2308 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2309 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2310 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2311 handleLingerComplete(nai);
2312 }
2313 break;
2314 }
2315 }
2316 return true;
2317 }
2318
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002319 @Override
2320 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002321 if (!maybeHandleAsyncChannelMessage(msg) &&
2322 !maybeHandleNetworkMonitorMessage(msg) &&
2323 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002324 maybeHandleNetworkAgentMessage(msg);
2325 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002326 }
2327 }
2328
Erik Kline79c6d052018-03-21 07:18:33 -07002329 private boolean networkRequiresValidation(NetworkAgentInfo nai) {
2330 return NetworkMonitor.isValidationRequired(
2331 mDefaultRequest.networkCapabilities, nai.networkCapabilities);
2332 }
2333
Erik Klinea24d4592018-01-11 21:07:29 +09002334 private void handlePrivateDnsSettingsChanged() {
2335 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2336
2337 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Erik Kline79c6d052018-03-21 07:18:33 -07002338 handlePerNetworkPrivateDnsConfig(nai, cfg);
dalyk1fcb7392018-03-05 12:42:22 -05002339 if (networkRequiresValidation(nai)) {
2340 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2341 }
Erik Klinea24d4592018-01-11 21:07:29 +09002342 }
2343 }
2344
Erik Kline79c6d052018-03-21 07:18:33 -07002345 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
2346 // Private DNS only ever applies to networks that might provide
2347 // Internet access and therefore also require validation.
2348 if (!networkRequiresValidation(nai)) return;
Erik Klinea24d4592018-01-11 21:07:29 +09002349
Erik Kline79c6d052018-03-21 07:18:33 -07002350 // Notify the NetworkMonitor thread in case it needs to cancel or
2351 // schedule DNS resolutions. If a DNS resolution is required the
2352 // result will be sent back to us.
2353 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2354
2355 // With Private DNS bypass support, we can proceed to update the
2356 // Private DNS config immediately, even if we're in strict mode
2357 // and have not yet resolved the provider name into a set of IPs.
2358 updatePrivateDns(nai, cfg);
2359 }
2360
2361 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2362 mDnsManager.updatePrivateDns(nai.network, newCfg);
Erik Klinea24d4592018-01-11 21:07:29 +09002363 updateDnses(nai.linkProperties, null, nai.network.netId);
Erik Klinea24d4592018-01-11 21:07:29 +09002364 }
2365
dalyk1fcb7392018-03-05 12:42:22 -05002366 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
2367 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
2368 if (nai == null) {
2369 return;
2370 }
2371 mDnsManager.updatePrivateDnsValidation(update);
2372 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
2373 }
2374
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002375 private void updateLingerState(NetworkAgentInfo nai, long now) {
2376 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2377 // 2. If the network was lingering and there are now requests, unlinger it.
2378 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2379 // one lingered request, start lingering.
2380 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002381 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002382 if (DBG) log("Unlingering " + nai.name());
2383 nai.unlinger();
2384 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002385 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002386 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002387 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002388 nai.linger();
2389 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2390 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2391 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002392 }
2393
Robert Greenwalt7b816022014-04-18 15:25:25 -07002394 private void handleAsyncChannelHalfConnect(Message msg) {
2395 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002396 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002397 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2398 if (VDBG) log("NetworkFactory connected");
2399 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002400 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002401 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002402 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002403 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002404 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002405 }
2406 } else {
2407 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002408 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002409 }
2410 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2411 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2412 if (VDBG) log("NetworkAgent connected");
2413 // A network agent has requested a connection. Establish the connection.
2414 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2415 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2416 } else {
2417 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002418 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002419 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002420 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002421 synchronized (mNetworkForNetId) {
2422 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002423 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002424 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002425 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002426 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002427 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002428 }
2429 }
2430 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002431
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 private void handleAsyncChannelDisconnected(Message msg) {
2433 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2434 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002435 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002436 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002437 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002438 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002439 // TODO - if we move the logic to the network agent (have them disconnect
2440 // because they lost all their requests or because their score isn't good)
2441 // then they would disconnect organically, report their new state and then
2442 // disconnect the channel.
2443 if (nai.networkInfo.isConnected()) {
2444 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2445 null, null);
2446 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002447 final boolean wasDefault = isDefaultNetwork(nai);
2448 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002449 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002450 // Log default network disconnection before required book-keeping.
2451 // Let rematchAllNetworksAndRequests() below record a new default network event
2452 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2453 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002454 long now = SystemClock.elapsedRealtime();
2455 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002456 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002457 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002458 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2459 // by other networks that are already connected. Perhaps that can be done by
2460 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2461 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002462 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002463 mKeepaliveTracker.handleStopAllKeepalives(nai,
2464 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002465 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2466 // Disable wakeup packet monitoring for each interface.
2467 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2468 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002469 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002470 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002471 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002472 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002473 // Remove the NetworkAgent, but don't mark the netId as
2474 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002475 mNetworkForNetId.remove(nai.network.netId);
2476 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002477 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002478 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2479 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002480 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002481 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002482 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002483 sendUpdatedScoreToFactories(request, 0);
2484 }
2485 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002486 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002487 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002488 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002489 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002490 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002491 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002492 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002493 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002494 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002495 if (nai.created) {
2496 // Tell netd to clean up the configuration for this network
2497 // (routing rules, DNS, etc).
2498 // This may be slow as it requires a lot of netd shelling out to ip and
2499 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2500 // after we've rematched networks with requests which should make a potential
2501 // fallback network the default or requested a new network from the
2502 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2503 // long time.
2504 try {
2505 mNetd.removeNetwork(nai.network.netId);
2506 } catch (Exception e) {
2507 loge("Exception removing network: " + e);
2508 }
Erik Klinea24d4592018-01-11 21:07:29 +09002509 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002510 }
2511 synchronized (mNetworkForNetId) {
2512 mNetIdInUse.delete(nai.network.netId);
2513 }
2514 } else {
2515 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2516 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002517 }
2518 }
2519
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002520 // If this method proves to be too slow then we can maintain a separate
2521 // pendingIntent => NetworkRequestInfo map.
2522 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2523 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2524 Intent intent = pendingIntent.getIntent();
2525 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2526 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2527 if (existingPendingIntent != null &&
2528 existingPendingIntent.getIntent().filterEquals(intent)) {
2529 return entry.getValue();
2530 }
2531 }
2532 return null;
2533 }
2534
2535 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2536 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2537
2538 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2539 if (existingRequest != null) { // remove the existing request.
2540 if (DBG) log("Replacing " + existingRequest.request + " with "
2541 + nri.request + " because their intents matched.");
2542 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2543 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002544 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002545 }
2546
Erik Klineda4bfa82015-04-30 12:58:40 +09002547 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002548 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002549 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002550 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002551 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002552 if (nri.request.networkCapabilities.hasSignalStrength() &&
2553 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2554 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002555 }
2556 }
2557 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002558 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002559 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002560 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002561 }
2562 }
2563
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002564 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2565 int callingUid) {
2566 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2567 if (nri != null) {
2568 handleReleaseNetworkRequest(nri.request, callingUid);
2569 }
2570 }
2571
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002572 // Determines whether the network is the best (or could become the best, if it validated), for
2573 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2574 // on the value of reason:
2575 //
2576 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2577 // then it should be torn down.
2578 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2579 // then it should be lingered.
2580 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2581 final int numRequests;
2582 switch (reason) {
2583 case TEARDOWN:
2584 numRequests = nai.numRequestNetworkRequests();
2585 break;
2586 case LINGER:
2587 numRequests = nai.numForegroundNetworkRequests();
2588 break;
2589 default:
2590 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2591 return true;
2592 }
2593
2594 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002595 return false;
2596 }
Paul Jensene0988542015-06-25 15:30:08 -04002597 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002598 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2599 // Background requests don't affect lingering.
2600 continue;
2601 }
2602
Paul Jensene0988542015-06-25 15:30:08 -04002603 // If this Network is already the highest scoring Network for a request, or if
2604 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002605 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002606 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002607 // Note that this catches two important cases:
2608 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2609 // is currently satisfying the request. This is desirable when
2610 // cellular ends up validating but WiFi does not.
2611 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002612 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002613 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002614 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002615 nai.getCurrentScoreAsValidated())) {
2616 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002617 }
2618 }
Paul Jensene0988542015-06-25 15:30:08 -04002619 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002620 }
2621
Erik Klineacdd6392016-07-07 16:50:58 +09002622 private NetworkRequestInfo getNriForAppRequest(
2623 NetworkRequest request, int callingUid, String requestedOperation) {
2624 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2625
Robert Greenwalt9258c642014-03-26 16:47:06 -07002626 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002627 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002628 log(String.format("UID %d attempted to %s for unowned request %s",
2629 callingUid, requestedOperation, nri));
2630 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002631 }
Erik Klineacdd6392016-07-07 16:50:58 +09002632 }
2633
2634 return nri;
2635 }
2636
Erik Kline57faba92015-11-25 12:49:38 +09002637 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002638 if (mNetworkRequests.get(nri.request) == null) {
2639 return;
Erik Kline57faba92015-11-25 12:49:38 +09002640 }
Hugo Benichicd952782017-09-20 11:20:14 +09002641 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002642 return;
2643 }
2644 if (VDBG || (DBG && nri.request.isRequest())) {
2645 log("releasing " + nri.request + " (timeout)");
2646 }
2647 handleRemoveNetworkRequest(nri);
2648 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002649 }
2650
Erik Klineacdd6392016-07-07 16:50:58 +09002651 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002652 final NetworkRequestInfo nri =
2653 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2654 if (nri == null) {
2655 return;
Erik Kline57faba92015-11-25 12:49:38 +09002656 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002657 if (VDBG || (DBG && nri.request.isRequest())) {
2658 log("releasing " + nri.request + " (release request)");
2659 }
2660 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002661 }
Erik Klineacdd6392016-07-07 16:50:58 +09002662
Hugo Benichidba33db2017-03-23 22:40:44 +09002663 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002664 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002665 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002666
Erik Klineacdd6392016-07-07 16:50:58 +09002667 synchronized (mUidToNetworkRequestCount) {
2668 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2669 if (requests < 1) {
2670 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2671 nri.mUid);
2672 } else if (requests == 1) {
2673 mUidToNetworkRequestCount.removeAt(
2674 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2675 } else {
2676 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2677 }
2678 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002679
Erik Klineacdd6392016-07-07 16:50:58 +09002680 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2681 if (nri.request.isRequest()) {
2682 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002683 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002684 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002685 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002686 nai.removeRequest(nri.request.requestId);
2687 if (VDBG) {
2688 log(" Removing from current network " + nai.name() +
2689 ", leaving " + nai.numNetworkRequests() + " requests.");
2690 }
2691 // If there are still lingered requests on this network, don't tear it down,
2692 // but resume lingering instead.
2693 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002694 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002695 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2696 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002697 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002698 wasKept = true;
2699 }
Hugo Benichicd952782017-09-20 11:20:14 +09002700 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002701 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2702 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002703 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002704 }
Erik Klineacdd6392016-07-07 16:50:58 +09002705 }
2706
2707 // TODO: remove this code once we know that the Slog.wtf is never hit.
2708 //
2709 // Find all networks that are satisfying this request and remove the request
2710 // from their request lists.
2711 // TODO - it's my understanding that for a request there is only a single
2712 // network satisfying it, so this loop is wasteful
2713 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2714 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2715 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2716 otherNai.name() + ", but mNetworkAgentInfos says " +
2717 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002718 }
2719 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002720
Erik Klineacdd6392016-07-07 16:50:58 +09002721 // Maintain the illusion. When this request arrived, we might have pretended
2722 // that a network connected to serve it, even though the network was already
2723 // connected. Now that this request has gone away, we might have to pretend
2724 // that the network disconnected. LegacyTypeTracker will generate that
2725 // phantom disconnect for this type.
2726 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2727 boolean doRemove = true;
2728 if (wasKept) {
2729 // check if any of the remaining requests for this network are for the
2730 // same legacy type - if so, don't remove the nai
2731 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2732 NetworkRequest otherRequest = nai.requestAt(i);
2733 if (otherRequest.legacyType == nri.request.legacyType &&
2734 otherRequest.isRequest()) {
2735 if (DBG) log(" still have other legacy request - leaving");
2736 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002737 }
2738 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002739 }
2740
Erik Klineacdd6392016-07-07 16:50:58 +09002741 if (doRemove) {
2742 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002743 }
2744 }
Erik Klineacdd6392016-07-07 16:50:58 +09002745
2746 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2747 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2748 nri.request);
2749 }
2750 } else {
2751 // listens don't have a singular affectedNetwork. Check all networks to see
2752 // if this listen request applies and remove it.
2753 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2754 nai.removeRequest(nri.request.requestId);
2755 if (nri.request.networkCapabilities.hasSignalStrength() &&
2756 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2757 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2758 }
2759 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002760 }
2761 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002762
Lorenzo Colitti18660282016-07-04 12:55:44 +09002763 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002764 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2765 enforceConnectivityInternalPermission();
2766 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002767 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002768 }
2769
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002770 @Override
2771 public void setAvoidUnvalidated(Network network) {
2772 enforceConnectivityInternalPermission();
2773 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2774 }
2775
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002776 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2777 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2778 " accept=" + accept + " always=" + always);
2779
2780 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2781 if (nai == null) {
2782 // Nothing to do.
2783 return;
2784 }
2785
2786 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002787 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002788 return;
2789 }
2790
2791 if (!nai.networkMisc.explicitlySelected) {
2792 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2793 }
2794
2795 if (accept != nai.networkMisc.acceptUnvalidated) {
2796 int oldScore = nai.getCurrentScore();
2797 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002798 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002799 sendUpdatedScoreToFactories(nai);
2800 }
2801
2802 if (always) {
2803 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002804 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002805 }
2806
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002807 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002808 // Tell the NetworkAgent to not automatically reconnect to the network.
2809 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2810 // Teardown the nework.
2811 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002812 }
2813
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002814 }
2815
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002816 private void handleSetAvoidUnvalidated(Network network) {
2817 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2818 if (nai == null || nai.lastValidated) {
2819 // Nothing to do. The network either disconnected or revalidated.
2820 return;
2821 }
2822 if (!nai.avoidUnvalidated) {
2823 int oldScore = nai.getCurrentScore();
2824 nai.avoidUnvalidated = true;
2825 rematchAllNetworksAndRequests(nai, oldScore);
2826 sendUpdatedScoreToFactories(nai);
2827 }
2828 }
2829
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002830 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002831 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002832 mHandler.sendMessageDelayed(
2833 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2834 PROMPT_UNVALIDATED_DELAY_MS);
2835 }
2836
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002837 @Override
2838 public void startCaptivePortalApp(Network network) {
2839 enforceConnectivityInternalPermission();
2840 mHandler.post(() -> {
2841 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2842 if (nai == null) return;
2843 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2844 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2845 });
2846 }
2847
Hugo Benichic8e9e122016-09-14 23:23:08 +00002848 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002849 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002850 }
2851
Erik Kline065ab6e2016-10-02 18:02:14 +09002852 private void rematchForAvoidBadWifiUpdate() {
2853 rematchAllNetworksAndRequests(null, 0);
2854 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2855 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2856 sendUpdatedScoreToFactories(nai);
2857 }
2858 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002859 }
2860
Erik Kline065ab6e2016-10-02 18:02:14 +09002861 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002862 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002863 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002864 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002865 if (!configRestrict) {
2866 pw.println("Bad Wi-Fi avoidance: unrestricted");
2867 return;
2868 }
2869
2870 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2871 pw.increaseIndent();
2872 pw.println("Config restrict: " + configRestrict);
2873
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002874 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002875 String description;
2876 // Can't use a switch statement because strings are legal case labels, but null is not.
2877 if ("0".equals(value)) {
2878 description = "get stuck";
2879 } else if (value == null) {
2880 description = "prompt";
2881 } else if ("1".equals(value)) {
2882 description = "avoid";
2883 } else {
2884 description = value + " (?)";
2885 }
2886 pw.println("User setting: " + description);
2887 pw.println("Network overrides:");
2888 pw.increaseIndent();
2889 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2890 if (nai.avoidUnvalidated) {
2891 pw.println(nai.name());
2892 }
2893 }
2894 pw.decreaseIndent();
2895 pw.decreaseIndent();
2896 }
2897
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002898 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2899 final String action;
2900 switch (type) {
2901 case NO_INTERNET:
2902 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2903 break;
2904 case LOST_INTERNET:
2905 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2906 break;
2907 default:
2908 Slog.wtf(TAG, "Unknown notification type " + type);
2909 return;
2910 }
2911
2912 Intent intent = new Intent(action);
2913 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2914 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2915 intent.setClassName("com.android.settings",
2916 "com.android.settings.wifi.WifiNoInternetDialog");
2917
2918 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2919 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2920 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2921 }
2922
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002923 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002924 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002925 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2926
2927 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2928 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002929 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002930 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002931 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2932 return;
2933 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002934 showValidationNotification(nai, NotificationType.NO_INTERNET);
2935 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002936
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002937 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2938 NetworkCapabilities nc = nai.networkCapabilities;
2939 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002940
Erik Kline065ab6e2016-10-02 18:02:14 +09002941 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002942 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002943 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2944 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002945 }
2946
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002947 @Override
2948 public int getMultipathPreference(Network network) {
2949 enforceAccessPermission();
2950
2951 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002952 if (nai != null && nai.networkCapabilities
2953 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002954 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2955 }
2956
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002957 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2958 if (networkPreference != null) {
2959 return networkPreference;
2960 }
2961
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002962 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2963 }
2964
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002965 private class InternalHandler extends Handler {
2966 public InternalHandler(Looper looper) {
2967 super(looper);
2968 }
2969
2970 @Override
2971 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002972 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002973 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002974 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002975 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002976 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002977 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002978 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002979 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002980 break;
2981 }
Jason Monkdecd2952013-10-10 14:02:51 -04002982 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002983 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002984 break;
2985 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002986 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002987 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2988 break;
2989 }
2990 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2991 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002992 break;
2993 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002994 case EVENT_REGISTER_NETWORK_AGENT: {
2995 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2996 break;
2997 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002998 case EVENT_REGISTER_NETWORK_REQUEST:
2999 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09003000 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003001 break;
3002 }
Paul Jensen694f2b82015-06-17 14:15:39 -04003003 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
3004 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003005 handleRegisterNetworkRequestWithIntent(msg);
3006 break;
3007 }
Erik Kline57faba92015-11-25 12:49:38 +09003008 case EVENT_TIMEOUT_NETWORK_REQUEST: {
3009 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
3010 handleTimedOutNetworkRequest(nri);
3011 break;
3012 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003013 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
3014 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
3015 break;
3016 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003017 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003018 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003019 break;
3020 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003021 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003022 Network network = (Network) msg.obj;
3023 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003024 break;
3025 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09003026 case EVENT_SET_AVOID_UNVALIDATED: {
3027 handleSetAvoidUnvalidated((Network) msg.obj);
3028 break;
3029 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09003030 case EVENT_PROMPT_UNVALIDATED: {
3031 handlePromptUnvalidated((Network) msg.obj);
3032 break;
3033 }
Erik Klineda4bfa82015-04-30 12:58:40 +09003034 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
3035 handleMobileDataAlwaysOn();
3036 break;
3037 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003038 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3039 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
3040 mKeepaliveTracker.handleStartKeepalive(msg);
3041 break;
3042 }
3043 // Sent by KeepaliveTracker to process an app request on the state machine thread.
3044 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3045 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3046 int slot = msg.arg1;
3047 int reason = msg.arg2;
3048 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3049 break;
3050 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003051 case EVENT_SYSTEM_READY: {
3052 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3053 nai.networkMonitor.systemReady = true;
3054 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003055 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003056 break;
3057 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003058 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003059 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003060 break;
3061 }
Erik Klinea24d4592018-01-11 21:07:29 +09003062 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3063 handlePrivateDnsSettingsChanged();
3064 break;
dalyk1fcb7392018-03-05 12:42:22 -05003065 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
3066 handlePrivateDnsValidationUpdate(
3067 (PrivateDnsValidationUpdate) msg.obj);
3068 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 }
3070 }
3071 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003072
3073 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003074 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003075 public int tether(String iface, String callerPkg) {
3076 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003077 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003078 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003079 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003080 } else {
3081 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3082 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003083 }
3084
3085 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003086 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003087 public int untether(String iface, String callerPkg) {
3088 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003089
3090 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003091 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003092 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003093 } else {
3094 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3095 }
3096 }
3097
3098 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003099 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003100 public int getLastTetherError(String iface) {
3101 enforceTetherAccessPermission();
3102
3103 if (isTetheringSupported()) {
3104 return mTethering.getLastTetherError(iface);
3105 } else {
3106 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3107 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003108 }
3109
3110 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003111 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003112 public String[] getTetherableUsbRegexs() {
3113 enforceTetherAccessPermission();
3114 if (isTetheringSupported()) {
3115 return mTethering.getTetherableUsbRegexs();
3116 } else {
3117 return new String[0];
3118 }
3119 }
3120
Lorenzo Colitti18660282016-07-04 12:55:44 +09003121 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003122 public String[] getTetherableWifiRegexs() {
3123 enforceTetherAccessPermission();
3124 if (isTetheringSupported()) {
3125 return mTethering.getTetherableWifiRegexs();
3126 } else {
3127 return new String[0];
3128 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003129 }
3130
Lorenzo Colitti18660282016-07-04 12:55:44 +09003131 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003132 public String[] getTetherableBluetoothRegexs() {
3133 enforceTetherAccessPermission();
3134 if (isTetheringSupported()) {
3135 return mTethering.getTetherableBluetoothRegexs();
3136 } else {
3137 return new String[0];
3138 }
3139 }
3140
Lorenzo Colitti18660282016-07-04 12:55:44 +09003141 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003142 public int setUsbTethering(boolean enable, String callerPkg) {
3143 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003144 if (isTetheringSupported()) {
3145 return mTethering.setUsbTethering(enable);
3146 } else {
3147 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3148 }
3149 }
3150
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003151 // TODO - move iface listing, queries, etc to new module
3152 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003153 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003154 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003155 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003156 return mTethering.getTetherableIfaces();
3157 }
3158
Lorenzo Colitti18660282016-07-04 12:55:44 +09003159 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003160 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003161 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003162 return mTethering.getTetheredIfaces();
3163 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003164
Lorenzo Colitti18660282016-07-04 12:55:44 +09003165 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003166 public String[] getTetheringErroredIfaces() {
3167 enforceTetherAccessPermission();
3168 return mTethering.getErroredIfaces();
3169 }
3170
Lorenzo Colitti18660282016-07-04 12:55:44 +09003171 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003172 public String[] getTetheredDhcpRanges() {
3173 enforceConnectivityInternalPermission();
3174 return mTethering.getTetheredDhcpRanges();
3175 }
3176
Udam Saini0e94c362017-06-07 12:06:28 -07003177 @Override
3178 public boolean isTetheringSupported(String callerPkg) {
3179 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3180 return isTetheringSupported();
3181 }
3182
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003183 // if ro.tether.denied = true we default to no tethering
3184 // gservices could set the secure setting to 1 though to enable it on a build where it
3185 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003186 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003187 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3188 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3189 Settings.Global.TETHER_SUPPORTED, defaultVal));
3190 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003191 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003192
3193 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3194 boolean adminUser = false;
3195 final long token = Binder.clearCallingIdentity();
3196 try {
3197 adminUser = mUserManager.isAdminUser();
3198 } finally {
3199 Binder.restoreCallingIdentity(token);
3200 }
3201
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003202 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003203 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003204
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003205 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003206 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3207 String callerPkg) {
3208 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003209 if (!isTetheringSupported()) {
3210 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3211 return;
3212 }
3213 mTethering.startTethering(type, receiver, showProvisioningUi);
3214 }
3215
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003216 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003217 public void stopTethering(int type, String callerPkg) {
3218 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003219 mTethering.stopTethering(type);
3220 }
3221
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003222 // Called when we lose the default network and have no replacement yet.
3223 // This will automatically be cleared after X seconds or a new default network
3224 // becomes CONNECTED, whichever happens first. The timer is started by the
3225 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003226 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003227 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003228 if (mNetTransitionWakeLock.isHeld()) {
3229 return;
3230 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003231 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003232 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3233 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003234 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003235 mWakelockLogs.log("ACQUIRE for " + forWhom);
3236 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3237 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003238 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003239
Hugo Benichi4c31b342017-03-30 23:18:10 +09003240 // Called when we gain a new default network to release the network transition wakelock in a
3241 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3242 // message is cancelled.
3243 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003244 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003245 if (!mNetTransitionWakeLock.isHeld()) {
3246 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003247 }
3248 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003249 // Cancel self timeout on wakelock hold.
3250 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3251 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3252 mHandler.sendMessageDelayed(msg, 1000);
3253 }
3254
3255 // Called when either message of ensureNetworkTransitionWakelock or
3256 // scheduleReleaseNetworkTransitionWakelock is processed.
3257 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3258 String event = eventName(eventId);
3259 synchronized (this) {
3260 if (!mNetTransitionWakeLock.isHeld()) {
3261 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3262 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3263 return;
3264 }
3265 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003266 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3267 mTotalWakelockDurationMs += lockDuration;
3268 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3269 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003270 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003271 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003272 }
3273
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003274 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003275 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003276 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003277 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003278 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003279 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003280 }
3281
Lorenzo Colitti18660282016-07-04 12:55:44 +09003282 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003283 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003284 enforceAccessPermission();
3285 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003286 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003287 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003288 mHandler.sendMessage(
3289 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3290 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003291
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003292 private void handleReportNetworkConnectivity(
3293 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003294 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003295 if (network == null) {
3296 nai = getDefaultNetwork();
3297 } else {
3298 nai = getNetworkAgentInfoForNetwork(network);
3299 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003300 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3301 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3302 return;
3303 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003304 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003305 if (hasConnectivity == nai.lastValidated) {
3306 return;
3307 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003308 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003309 int netid = nai.network.netId;
3310 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003311 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003312 // Validating a network that has not yet connected could result in a call to
3313 // rematchNetworkAndRequests() which is not meant to work on such networks.
3314 if (!nai.everConnected) {
3315 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003316 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003317 LinkProperties lp = getLinkProperties(nai);
3318 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3319 return;
3320 }
Erik Kline79c6d052018-03-21 07:18:33 -07003321 nai.networkMonitor.forceReevaluation(uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003322 }
3323
Paul Jensencee9b512015-05-06 07:32:40 -04003324 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003325 // this information is already available as a world read/writable jvm property
3326 // so this API change wouldn't have a benifit. It also breaks the passing
3327 // of proxy info to all the JVMs.
3328 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003329 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003330 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003331 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3332 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003333 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003334 }
3335
Lorenzo Colitti18660282016-07-04 12:55:44 +09003336 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003337 public ProxyInfo getProxyForNetwork(Network network) {
3338 if (network == null) return getDefaultProxy();
3339 final ProxyInfo globalProxy = getGlobalProxy();
3340 if (globalProxy != null) return globalProxy;
3341 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3342 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3343 // caller may not have.
3344 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3345 if (nai == null) return null;
3346 synchronized (nai) {
3347 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3348 if (proxyInfo == null) return null;
3349 return new ProxyInfo(proxyInfo);
3350 }
3351 }
3352
Paul Jensene0bef712014-12-10 15:12:18 -05003353 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3354 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3355 // proxy is null then there is no proxy in place).
3356 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3357 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3358 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3359 proxy = null;
3360 }
3361 return proxy;
3362 }
3363
3364 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3365 // better for determining if a new proxy broadcast is necessary:
3366 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3367 // avoid unnecessary broadcasts.
3368 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3369 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3370 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3371 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3372 // all set.
3373 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3374 a = canonicalizeProxyInfo(a);
3375 b = canonicalizeProxyInfo(b);
3376 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3377 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3378 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3379 }
3380
Jason Monk207900c2014-04-25 15:00:09 -04003381 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003382 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003383
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003384 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003385 if (proxyProperties == mGlobalProxy) return;
3386 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3387 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3388
3389 String host = "";
3390 int port = 0;
3391 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003392 String pacFileUrl = "";
3393 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003394 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003395 if (!proxyProperties.isValid()) {
3396 if (DBG)
3397 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3398 return;
3399 }
Jason Monk207900c2014-04-25 15:00:09 -04003400 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003401 host = mGlobalProxy.getHost();
3402 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003403 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003404 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003405 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003406 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003407 } else {
3408 mGlobalProxy = null;
3409 }
3410 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003411 final long token = Binder.clearCallingIdentity();
3412 try {
3413 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3414 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3415 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3416 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003417 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003418 } finally {
3419 Binder.restoreCallingIdentity(token);
3420 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003421
Jason Monkcf0f97a2014-10-02 15:39:38 -04003422 if (mGlobalProxy == null) {
3423 proxyProperties = mDefaultProxy;
3424 }
3425 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003427 }
3428
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003429 private void loadGlobalProxy() {
3430 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003431 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3432 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3433 String exclList = Settings.Global.getString(res,
3434 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003435 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3436 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003437 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003438 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003439 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003440 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003441 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003442 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003443 if (!proxyProperties.isValid()) {
3444 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3445 return;
3446 }
3447
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003448 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003449 mGlobalProxy = proxyProperties;
3450 }
3451 }
3452 }
3453
Jason Monk207900c2014-04-25 15:00:09 -04003454 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003455 // this information is already available as a world read/writable jvm property
3456 // so this API change wouldn't have a benifit. It also breaks the passing
3457 // of proxy info to all the JVMs.
3458 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003459 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003460 return mGlobalProxy;
3461 }
3462 }
3463
Jason Monk207900c2014-04-25 15:00:09 -04003464 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003465 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003466 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003467 proxy = null;
3468 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003469 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003470 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003471 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003472 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003473 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3474 return;
3475 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003476
3477 // This call could be coming from the PacManager, containing the port of the local
3478 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3479 // global (to get the correct local port), and send a broadcast.
3480 // TODO: Switch PacManager to have its own message to send back rather than
3481 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003482 if ((mGlobalProxy != null) && (proxy != null)
3483 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003484 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3485 mGlobalProxy = proxy;
3486 sendProxyBroadcast(mGlobalProxy);
3487 return;
3488 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003489 mDefaultProxy = proxy;
3490
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003491 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003492 if (!mDefaultProxyDisabled) {
3493 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003494 }
3495 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003496 }
3497
Paul Jensene0bef712014-12-10 15:12:18 -05003498 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3499 // This method gets called when any network changes proxy, but the broadcast only ever contains
3500 // the default proxy (even if it hasn't changed).
3501 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3502 // world where an app might be bound to a non-default network.
3503 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3504 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3505 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3506
3507 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3508 sendProxyBroadcast(getDefaultProxy());
3509 }
3510 }
3511
Robert Greenwalt434203a2010-10-11 16:00:27 -07003512 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003513 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3514 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003515 if (!TextUtils.isEmpty(proxy)) {
3516 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003517 if (data.length == 0) {
3518 return;
3519 }
3520
Robert Greenwalt434203a2010-10-11 16:00:27 -07003521 String proxyHost = data[0];
3522 int proxyPort = 8080;
3523 if (data.length > 1) {
3524 try {
3525 proxyPort = Integer.parseInt(data[1]);
3526 } catch (NumberFormatException e) {
3527 return;
3528 }
3529 }
Jason Monk207900c2014-04-25 15:00:09 -04003530 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003531 setGlobalProxy(p);
3532 }
3533 }
3534
Jason Monk207900c2014-04-25 15:00:09 -04003535 private void sendProxyBroadcast(ProxyInfo proxy) {
3536 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003537 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003538 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003539 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003540 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3541 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003542 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003543 final long ident = Binder.clearCallingIdentity();
3544 try {
3545 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3546 } finally {
3547 Binder.restoreCallingIdentity(ident);
3548 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003549 }
3550
3551 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003552 final private HashMap<Uri, Integer> mUriEventMap;
3553 final private Context mContext;
3554 final private Handler mHandler;
3555
3556 SettingsObserver(Context context, Handler handler) {
3557 super(null);
3558 mUriEventMap = new HashMap<Uri, Integer>();
3559 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003560 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003561 }
3562
Erik Klineda4bfa82015-04-30 12:58:40 +09003563 void observe(Uri uri, int what) {
3564 mUriEventMap.put(uri, what);
3565 final ContentResolver resolver = mContext.getContentResolver();
3566 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003567 }
3568
3569 @Override
3570 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003571 Slog.wtf(TAG, "Should never be reached.");
3572 }
3573
3574 @Override
3575 public void onChange(boolean selfChange, Uri uri) {
3576 final Integer what = mUriEventMap.get(uri);
3577 if (what != null) {
3578 mHandler.obtainMessage(what.intValue()).sendToTarget();
3579 } else {
3580 loge("No matching event to send for URI=" + uri);
3581 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003582 }
3583 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003584
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003585 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003586 Slog.d(TAG, s);
3587 }
3588
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003589 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003590 Slog.e(TAG, s);
3591 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003592
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003593 private static void loge(String s, Throwable t) {
3594 Slog.e(TAG, s, t);
3595 }
3596
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003597 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003598 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003599 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3600 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3601 *
3602 * @param oldPackage Package name of the application which currently controls VPN, which will
3603 * be replaced. If there is no such application, this should should either be
3604 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3605 * @param newPackage Package name of the application which should gain control of VPN, or
3606 * {@code null} to disable.
3607 * @param userId User for whom to prepare the new VPN.
3608 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003609 * @hide
3610 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003611 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003612 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3613 int userId) {
3614 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003615
Hugo Benichi20035e02017-04-26 14:53:28 +09003616 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003617 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003618 Vpn vpn = mVpns.get(userId);
3619 if (vpn != null) {
3620 return vpn.prepare(oldPackage, newPackage);
3621 } else {
3622 return false;
3623 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003624 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003625 }
3626
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003627 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003628 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3629 * This method is used by system-privileged apps.
3630 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3631 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3632 *
3633 * @param packageName The package for which authorization state should change.
3634 * @param userId User for whom {@code packageName} is installed.
3635 * @param authorized {@code true} if this app should be able to start a VPN connection without
3636 * explicit user approval, {@code false} if not.
3637 *
Jeff Davidson05542602014-08-11 14:07:27 -07003638 * @hide
3639 */
3640 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003641 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3642 enforceCrossUserPermission(userId);
3643
Hugo Benichi20035e02017-04-26 14:53:28 +09003644 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003645 Vpn vpn = mVpns.get(userId);
3646 if (vpn != null) {
3647 vpn.setPackageAuthorization(packageName, authorized);
3648 }
Jeff Davidson05542602014-08-11 14:07:27 -07003649 }
3650 }
3651
3652 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003653 * Configure a TUN interface and return its file descriptor. Parameters
3654 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003655 * and not available in ConnectivityManager. Permissions are checked in
3656 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003657 * @hide
3658 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003659 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003660 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003661 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003662 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003663 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003664 return mVpns.get(user).establish(config);
3665 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003666 }
3667
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003668 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003669 * Start legacy VPN, controlling native daemons as needed. Creates a
3670 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003671 */
3672 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003673 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003674 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003675 final LinkProperties egress = getActiveLinkProperties();
3676 if (egress == null) {
3677 throw new IllegalStateException("Missing active network connection");
3678 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003679 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003680 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003681 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3682 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003683 }
3684
3685 /**
3686 * Return the information of the ongoing legacy VPN. This method is used
3687 * by VpnSettings and not available in ConnectivityManager. Permissions
3688 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003689 */
3690 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003691 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3692 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003693
Hugo Benichi20035e02017-04-26 14:53:28 +09003694 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003695 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003696 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003697 }
3698
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003699 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003700 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3701 * and not available in ConnectivityManager.
3702 */
3703 @Override
3704 public VpnInfo[] getAllVpnInfo() {
3705 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003706 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003707 if (mLockdownEnabled) {
3708 return new VpnInfo[0];
3709 }
3710
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003711 List<VpnInfo> infoList = new ArrayList<>();
3712 for (int i = 0; i < mVpns.size(); i++) {
3713 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3714 if (info != null) {
3715 infoList.add(info);
3716 }
3717 }
3718 return infoList.toArray(new VpnInfo[infoList.size()]);
3719 }
3720 }
3721
3722 /**
3723 * @return VPN information for accounting, or null if we can't retrieve all required
3724 * information, e.g primary underlying iface.
3725 */
3726 @Nullable
3727 private VpnInfo createVpnInfo(Vpn vpn) {
3728 VpnInfo info = vpn.getVpnInfo();
3729 if (info == null) {
3730 return null;
3731 }
3732 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3733 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3734 // the underlyingNetworks list.
3735 if (underlyingNetworks == null) {
3736 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3737 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3738 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3739 }
3740 } else if (underlyingNetworks.length > 0) {
3741 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3742 if (linkProperties != null) {
3743 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3744 }
3745 }
3746 return info.primaryUnderlyingIface == null ? null : info;
3747 }
3748
3749 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003750 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3751 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003752 * Permissions are checked in Vpn class.
3753 * @hide
3754 */
3755 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003756 public VpnConfig getVpnConfig(int userId) {
3757 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003758 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003759 Vpn vpn = mVpns.get(userId);
3760 if (vpn != null) {
3761 return vpn.getVpnConfig();
3762 } else {
3763 return null;
3764 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003765 }
3766 }
3767
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003768 @Override
3769 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003770 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3771 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3772 return false;
3773 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003774
Hugo Benichi69744342017-11-27 10:57:16 +09003775 synchronized (mVpns) {
3776 // Tear down existing lockdown if profile was removed
3777 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3778 if (mLockdownEnabled) {
3779 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3780 if (profileTag == null) {
3781 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3782 return false;
3783 }
3784 String profileName = new String(profileTag);
3785 final VpnProfile profile = VpnProfile.decode(
3786 profileName, mKeyStore.get(Credentials.VPN + profileName));
3787 if (profile == null) {
3788 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3789 setLockdownTracker(null);
3790 return true;
3791 }
3792 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003793 Vpn vpn = mVpns.get(user);
3794 if (vpn == null) {
3795 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3796 return false;
3797 }
3798 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003799 } else {
3800 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003801 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003802 }
3803
3804 return true;
3805 }
3806
3807 /**
3808 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3809 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3810 */
Hugo Benichi69744342017-11-27 10:57:16 +09003811 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003812 private void setLockdownTracker(LockdownVpnTracker tracker) {
3813 // Shutdown any existing tracker
3814 final LockdownVpnTracker existing = mLockdownTracker;
3815 mLockdownTracker = null;
3816 if (existing != null) {
3817 existing.shutdown();
3818 }
3819
Robin Leec3736bc2017-03-10 16:19:54 +00003820 if (tracker != null) {
3821 mLockdownTracker = tracker;
3822 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003823 }
3824 }
3825
Hugo Benichi69744342017-11-27 10:57:16 +09003826 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003827 private void throwIfLockdownEnabled() {
3828 if (mLockdownEnabled) {
3829 throw new IllegalStateException("Unavailable in lockdown mode");
3830 }
3831 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003832
Robin Lee244ce8e2016-01-05 18:03:46 +00003833 /**
Robin Lee17e61832016-05-09 13:46:28 +01003834 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3835 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003836 *
Robin Lee17e61832016-05-09 13:46:28 +01003837 * @return {@code true} if the service was started, the service was already connected, or there
3838 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003839 */
Robin Lee17e61832016-05-09 13:46:28 +01003840 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003841 synchronized (mVpns) {
3842 Vpn vpn = mVpns.get(userId);
3843 if (vpn == null) {
3844 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3845 // exists already.
3846 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3847 return false;
3848 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003849
Robin Lee812800c2016-05-13 15:38:08 +01003850 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003851 }
3852 }
3853
3854 @Override
Charles He36738632017-05-15 17:07:18 +01003855 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3856 enforceSettingsPermission();
3857 enforceCrossUserPermission(userId);
3858
3859 synchronized (mVpns) {
3860 Vpn vpn = mVpns.get(userId);
3861 if (vpn == null) {
3862 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3863 return false;
3864 }
3865 return vpn.isAlwaysOnPackageSupported(packageName);
3866 }
3867 }
3868
3869 @Override
Robin Leedc679712016-05-03 13:23:03 +01003870 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003871 enforceConnectivityInternalPermission();
3872 enforceCrossUserPermission(userId);
3873
Robin Lee244ce8e2016-01-05 18:03:46 +00003874 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003875 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3876 if (LockdownVpnTracker.isEnabled()) {
3877 return false;
3878 }
3879
Robin Lee244ce8e2016-01-05 18:03:46 +00003880 Vpn vpn = mVpns.get(userId);
3881 if (vpn == null) {
3882 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3883 return false;
3884 }
Robin Lee17e61832016-05-09 13:46:28 +01003885 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003886 return false;
3887 }
Robin Lee17e61832016-05-09 13:46:28 +01003888 if (!startAlwaysOnVpn(userId)) {
3889 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003890 return false;
3891 }
3892 }
3893 return true;
3894 }
3895
3896 @Override
3897 public String getAlwaysOnVpnPackage(int userId) {
3898 enforceConnectivityInternalPermission();
3899 enforceCrossUserPermission(userId);
3900
3901 synchronized (mVpns) {
3902 Vpn vpn = mVpns.get(userId);
3903 if (vpn == null) {
3904 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3905 return null;
3906 }
3907 return vpn.getAlwaysOnPackage();
3908 }
3909 }
3910
Wink Savilleab9321d2013-06-29 21:10:57 -07003911 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003912 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003913 // TODO: Remove? Any reason to trigger a provisioning check?
3914 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003915 }
3916
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003917 /** Location to an updatable file listing carrier provisioning urls.
3918 * An example:
3919 *
3920 * <?xml version="1.0" encoding="utf-8"?>
3921 * <provisioningUrls>
3922 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003923 * </provisioningUrls>
3924 */
3925 private static final String PROVISIONING_URL_PATH =
3926 "/data/misc/radio/provisioning_urls.xml";
3927 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003928
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003929 /** XML tag for root element. */
3930 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3931 /** XML tag for individual url */
3932 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003933 /** XML attribute for mcc */
3934 private static final String ATTR_MCC = "mcc";
3935 /** XML attribute for mnc */
3936 private static final String ATTR_MNC = "mnc";
3937
Paul Jensen434dde82015-06-11 09:43:30 -04003938 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003939 FileReader fileReader = null;
3940 XmlPullParser parser = null;
3941 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003942
3943 try {
3944 fileReader = new FileReader(mProvisioningUrlFile);
3945 parser = Xml.newPullParser();
3946 parser.setInput(fileReader);
3947 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3948
3949 while (true) {
3950 XmlUtils.nextElement(parser);
3951
3952 String element = parser.getName();
3953 if (element == null) break;
3954
Paul Jensen434dde82015-06-11 09:43:30 -04003955 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003956 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3957 try {
3958 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3959 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3960 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3961 parser.next();
3962 if (parser.getEventType() == XmlPullParser.TEXT) {
3963 return parser.getText();
3964 }
3965 }
3966 }
3967 } catch (NumberFormatException e) {
3968 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3969 }
3970 }
3971 }
3972 return null;
3973 } catch (FileNotFoundException e) {
3974 loge("Carrier Provisioning Urls file not found");
3975 } catch (XmlPullParserException e) {
3976 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3977 } catch (IOException e) {
3978 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3979 } finally {
3980 if (fileReader != null) {
3981 try {
3982 fileReader.close();
3983 } catch (IOException e) {}
3984 }
3985 }
3986 return null;
3987 }
3988
Wink Saville42d4f082013-07-20 20:31:59 -07003989 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003990 public String getMobileProvisioningUrl() {
3991 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003992 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003993 if (TextUtils.isEmpty(url)) {
3994 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003995 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003996 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003997 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003998 }
Wink Saville8cf35602013-07-10 23:00:07 -07003999 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07004000 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07004001 String phoneNumber = mTelephonyManager.getLine1Number();
4002 if (TextUtils.isEmpty(phoneNumber)) {
4003 phoneNumber = "0000000000";
4004 }
Wink Savilleab9321d2013-06-29 21:10:57 -07004005 url = String.format(url,
4006 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4007 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07004008 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07004009 }
4010
Wink Savilleab9321d2013-06-29 21:10:57 -07004011 return url;
4012 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004013
Wink Saville948282b2013-08-29 08:55:16 -07004014 @Override
4015 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04004016 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07004017 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09004018 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
4019 return;
4020 }
Paul Jensen89e0f092014-09-15 15:59:36 -04004021 final long ident = Binder.clearCallingIdentity();
4022 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09004023 // Concatenate the range of types onto the range of NetIDs.
4024 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
4025 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04004026 } finally {
4027 Binder.restoreCallingIdentity(ident);
4028 }
Wink Saville948282b2013-08-29 08:55:16 -07004029 }
Wink Saville7788c612013-08-29 14:57:08 -07004030
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004031 @Override
4032 public void setAirplaneMode(boolean enable) {
4033 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004034 final long ident = Binder.clearCallingIdentity();
4035 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004036 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09004037 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07004038 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4039 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08004040 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07004041 } finally {
4042 Binder.restoreCallingIdentity(ident);
4043 }
4044 }
4045
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004046 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004047 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004048 Vpn userVpn = mVpns.get(userId);
4049 if (userVpn != null) {
4050 loge("Starting user already has a VPN");
4051 return;
4052 }
Paul Jensene75b9e32015-04-06 11:54:53 -04004053 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004054 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09004055 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4056 updateLockdownVpn();
4057 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004058 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004059 }
4060
4061 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004062 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004063 Vpn userVpn = mVpns.get(userId);
4064 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004065 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004066 return;
4067 }
Robin Lee17e61832016-05-09 13:46:28 +01004068 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004069 mVpns.delete(userId);
4070 }
4071 }
4072
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004073 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004074 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004075 final int vpnsSize = mVpns.size();
4076 for (int i = 0; i < vpnsSize; i++) {
4077 Vpn vpn = mVpns.valueAt(i);
4078 vpn.onUserAdded(userId);
4079 }
4080 }
4081 }
4082
4083 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004084 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004085 final int vpnsSize = mVpns.size();
4086 for (int i = 0; i < vpnsSize; i++) {
4087 Vpn vpn = mVpns.valueAt(i);
4088 vpn.onUserRemoved(userId);
4089 }
4090 }
4091 }
4092
Robin Lee89e7a692016-02-29 14:38:17 +00004093 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004094 synchronized (mVpns) {
4095 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4096 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4097 updateLockdownVpn();
4098 } else {
4099 startAlwaysOnVpn(userId);
4100 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004101 }
4102 }
4103
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004104 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4105 @Override
4106 public void onReceive(Context context, Intent intent) {
4107 final String action = intent.getAction();
4108 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4109 if (userId == UserHandle.USER_NULL) return;
4110
Robin Lee323f29d2016-05-04 16:38:06 +01004111 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004112 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004113 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004114 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004115 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4116 onUserAdded(userId);
4117 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4118 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004119 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4120 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004121 }
4122 }
4123 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004124
Robin Lee95204e02017-01-27 11:59:22 +00004125 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4126 @Override
4127 public void onReceive(Context context, Intent intent) {
4128 // Try creating lockdown tracker, since user present usually means
4129 // unlocked keystore.
4130 updateLockdownVpn();
4131 mContext.unregisterReceiver(this);
4132 }
4133 };
4134
Robert Greenwalta67be032014-05-16 15:49:14 -07004135 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4136 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004137 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4138 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004139
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004140 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4141 // Map from UID to number of NetworkRequests that UID has filed.
4142 @GuardedBy("mUidToNetworkRequestCount")
4143 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4144
Robert Greenwalta67be032014-05-16 15:49:14 -07004145 private static class NetworkFactoryInfo {
4146 public final String name;
4147 public final Messenger messenger;
4148 public final AsyncChannel asyncChannel;
4149
4150 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4151 this.name = name;
4152 this.messenger = messenger;
4153 this.asyncChannel = asyncChannel;
4154 }
4155 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004156
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004157 private void ensureNetworkRequestHasType(NetworkRequest request) {
4158 if (request.type == NetworkRequest.Type.NONE) {
4159 throw new IllegalArgumentException(
4160 "All NetworkRequests in ConnectivityService must have a type");
4161 }
4162 }
4163
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004164 /**
4165 * Tracks info about the requester.
4166 * Also used to notice when the calling process dies so we can self-expire
4167 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004169 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004170 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004171 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004172 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173 final int mPid;
4174 final int mUid;
4175 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004176
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004177 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004178 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004179 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004180 mPendingIntent = pi;
4181 messenger = null;
4182 mBinder = null;
4183 mPid = getCallingPid();
4184 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004185 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004186 }
4187
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004188 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004189 super();
4190 messenger = m;
4191 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004192 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004193 mBinder = binder;
4194 mPid = getCallingPid();
4195 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004196 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004197 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198
4199 try {
4200 mBinder.linkToDeath(this, 0);
4201 } catch (RemoteException e) {
4202 binderDied();
4203 }
4204 }
4205
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004206 private void enforceRequestCountLimit() {
4207 synchronized (mUidToNetworkRequestCount) {
4208 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4209 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004210 throw new ServiceSpecificException(
4211 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004212 }
4213 mUidToNetworkRequestCount.put(mUid, networkRequests);
4214 }
4215 }
4216
Robert Greenwalt9258c642014-03-26 16:47:06 -07004217 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004218 if (mBinder != null) {
4219 mBinder.unlinkToDeath(this, 0);
4220 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004221 }
4222
4223 public void binderDied() {
4224 log("ConnectivityService NetworkRequestInfo binderDied(" +
4225 request + ", " + mBinder + ")");
4226 releaseNetworkRequest(request);
4227 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004228
4229 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004230 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004231 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004232 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004233 }
4234
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004235 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4236 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4237 if (badCapability != null) {
4238 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004239 }
4240 }
4241
Chalard Jeanb03a6222018-04-11 21:09:10 +09004242 // This checks that the passed capabilities either do not request a specific SSID, or the
4243 // calling app has permission to do so.
4244 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
4245 int callerPid, int callerUid) {
Chalard Jeanb5120ca2018-04-16 12:25:22 +09004246 if (null != nc.getSSID() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jeanb03a6222018-04-11 21:09:10 +09004247 throw new SecurityException("Insufficient permissions to request a specific SSID");
4248 }
4249 }
4250
Erik Kline9d598e12015-07-13 16:37:51 +09004251 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004252 final SortedSet<Integer> thresholds = new TreeSet();
4253 synchronized (nai) {
4254 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4255 if (nri.request.networkCapabilities.hasSignalStrength() &&
4256 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4257 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4258 }
4259 }
4260 }
Erik Kline9d598e12015-07-13 16:37:51 +09004261 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004262 }
4263
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004264 private void updateSignalStrengthThresholds(
4265 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4266 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004267 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004268 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4269
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004270 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004271 String detail;
4272 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4273 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4274 } else {
4275 detail = reason;
4276 }
4277 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4278 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4279 }
4280
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004281 nai.asyncChannel.sendMessage(
4282 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004283 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004284 }
4285
Etan Cohen859748f2017-04-03 17:42:34 -07004286 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4287 if (nc == null) {
4288 return;
4289 }
4290 NetworkSpecifier ns = nc.getNetworkSpecifier();
4291 if (ns == null) {
4292 return;
4293 }
4294 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4295 ns.assertValidFromUid(Binder.getCallingUid());
4296 }
4297
Robert Greenwalt9258c642014-03-26 16:47:06 -07004298 @Override
4299 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004300 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004301 final NetworkRequest.Type type = (networkCapabilities == null)
4302 ? NetworkRequest.Type.TRACK_DEFAULT
4303 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004304 // If the requested networkCapabilities is null, take them instead from
4305 // the default network request. This allows callers to keep track of
4306 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004307 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004308 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004309 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004310 enforceAccessPermission();
4311 } else {
4312 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4313 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004314 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4315 // of the app when the request is filed, but we never change the request if the app
4316 // changes network state. http://b/29964605
4317 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004318 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004319 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004320 ensureSufficientPermissionsForRequest(networkCapabilities,
4321 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004322 // Set the UID range for this request to the single UID of the requester, or to an empty
4323 // set of UIDs if the caller has the appropriate permission and UIDs have not been set.
Chalard Jeandda156a2018-01-10 21:19:32 +09004324 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4325 // are no visible methods to set the UIDs, an app could use reflection to try and get
4326 // networks for other apps so it's essential that the UIDs are overwritten.
Chalard Jeanb552c462018-02-21 18:43:54 +09004327 restrictRequestUidsForCaller(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004328
Etan Cohenba07c8c2017-02-05 10:42:27 -08004329 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004330 throw new IllegalArgumentException("Bad timeout specified");
4331 }
Etan Cohen859748f2017-04-03 17:42:34 -07004332 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004333
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004334 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004335 nextNetworkRequestId(), type);
4336 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004337 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004338
4339 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004340 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004341 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004342 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004343 }
4344 return networkRequest;
4345 }
4346
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004347 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004348 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004349 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004350 } else {
4351 enforceChangePermission();
4352 }
4353 }
4354
fenglub15e72b2015-03-20 11:29:56 -07004355 @Override
fengludb571472015-04-21 17:12:05 -07004356 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004357 enforceAccessPermission();
4358 NetworkAgentInfo nai = null;
4359 if (network == null) {
4360 return false;
4361 }
4362 synchronized (mNetworkForNetId) {
4363 nai = mNetworkForNetId.get(network.netId);
4364 }
4365 if (nai != null) {
4366 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4367 return true;
4368 }
4369 return false;
4370 }
4371
Felipe Lemeee27cab2016-06-20 16:36:29 -07004372 private boolean isSystem(int uid) {
4373 return uid < Process.FIRST_APPLICATION_UID;
4374 }
fenglub15e72b2015-03-20 11:29:56 -07004375
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004376 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004377 final int uid = Binder.getCallingUid();
4378 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004379 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004380 return;
4381 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004382 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4383 // Policy already enforced.
4384 return;
4385 }
4386 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4387 // If UID is restricted, don't allow them to bring up metered APNs.
4388 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004389 }
4390 }
4391
Robert Greenwalt9258c642014-03-26 16:47:06 -07004392 @Override
4393 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4394 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004395 checkNotNull(operation, "PendingIntent cannot be null.");
4396 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4397 enforceNetworkRequestPermissions(networkCapabilities);
4398 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004399 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004400 ensureSufficientPermissionsForRequest(networkCapabilities,
4401 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohen859748f2017-04-03 17:42:34 -07004402 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004403 restrictRequestUidsForCaller(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004404
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004405 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004406 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4407 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004408 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004409 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4410 nri));
4411 return networkRequest;
4412 }
4413
Jeremy Joslin79294842014-12-03 17:15:28 -08004414 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4415 mHandler.sendMessageDelayed(
4416 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4417 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4418 }
4419
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004420 @Override
4421 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004422 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004423 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4424 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004425 }
4426
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004427 // In order to implement the compatibility measure for pre-M apps that call
4428 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4429 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4430 // This ensures it has permission to do so.
4431 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4432 if (nc == null) {
4433 return false;
4434 }
4435 int[] transportTypes = nc.getTransportTypes();
4436 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4437 return false;
4438 }
4439 try {
4440 mContext.enforceCallingOrSelfPermission(
4441 android.Manifest.permission.ACCESS_WIFI_STATE,
4442 "ConnectivityService");
4443 } catch (SecurityException e) {
4444 return false;
4445 }
4446 return true;
4447 }
4448
Robert Greenwalt9258c642014-03-26 16:47:06 -07004449 @Override
4450 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4451 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004452 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4453 enforceAccessPermission();
4454 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004455
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004456 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004457 ensureSufficientPermissionsForRequest(networkCapabilities,
4458 Binder.getCallingPid(), Binder.getCallingUid());
Chalard Jeanb552c462018-02-21 18:43:54 +09004459 restrictRequestUidsForCaller(nc);
Chalard Jean26aa91a2018-03-20 19:13:57 +09004460 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4461 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4462 // onLost and onAvailable callbacks when networks move in and out of the background.
4463 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4464 // can't request networks.
4465 restrictBackgroundRequestForCaller(nc);
4466 ensureValidNetworkSpecifier(nc);
Etan Cohena7434272017-04-03 12:17:51 -07004467
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004468 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004469 NetworkRequest.Type.LISTEN);
4470 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004471 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004472
4473 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4474 return networkRequest;
4475 }
4476
4477 @Override
4478 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4479 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004480 checkNotNull(operation, "PendingIntent cannot be null.");
4481 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4482 enforceAccessPermission();
4483 }
Etan Cohen859748f2017-04-03 17:42:34 -07004484 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeanb03a6222018-04-11 21:09:10 +09004485 ensureSufficientPermissionsForRequest(networkCapabilities,
4486 Binder.getCallingPid(), Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004487
Chalard Jeandda156a2018-01-10 21:19:32 +09004488 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeanb552c462018-02-21 18:43:54 +09004489 restrictRequestUidsForCaller(nc);
Chalard Jeandda156a2018-01-10 21:19:32 +09004490
4491 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004492 NetworkRequest.Type.LISTEN);
4493 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004494 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004495
4496 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004497 }
4498
Erik Klineacdd6392016-07-07 16:50:58 +09004499 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004500 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004501 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004502 mHandler.sendMessage(mHandler.obtainMessage(
4503 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004504 }
4505
4506 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004507 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004508 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004509 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4510 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004511 }
4512
Robert Greenwalta67be032014-05-16 15:49:14 -07004513 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004514 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004515 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4516 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4517 }
4518
4519 @Override
4520 public void unregisterNetworkFactory(Messenger messenger) {
4521 enforceConnectivityInternalPermission();
4522 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4523 }
4524
4525 private void handleUnregisterNetworkFactory(Messenger messenger) {
4526 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4527 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004528 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004529 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004530 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004531 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004532 }
4533
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534 /**
4535 * NetworkAgentInfo supporting a request by requestId.
4536 * These have already been vetted (their Capabilities satisfy the request)
4537 * and the are the highest scored network available.
4538 * the are keyed off the Requests requestId.
4539 */
Hugo Benichicd952782017-09-20 11:20:14 +09004540 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4541 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4543 new SparseArray<NetworkAgentInfo>();
4544
Paul Jensen31a94f42015-02-13 14:18:39 -05004545 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4546 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004547 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4548 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004549 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4550 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4551 // there may not be a strict 1:1 correlation between the two.
4552 @GuardedBy("mNetworkForNetId")
4553 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004554
Robert Greenwalt7b816022014-04-18 15:25:25 -07004555 // NetworkAgentInfo keyed off its connecting messenger
4556 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004557 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004558 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4559 new HashMap<Messenger, NetworkAgentInfo>();
4560
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004561 @GuardedBy("mBlockedAppUids")
4562 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4563
Paul Jensen2c311d62014-11-17 12:34:51 -05004564 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004565 private final NetworkRequest mDefaultRequest;
4566
Erik Klineda4bfa82015-04-30 12:58:40 +09004567 // Request used to optionally keep mobile data active even when higher
4568 // priority networks like Wi-Fi are active.
4569 private final NetworkRequest mDefaultMobileDataRequest;
4570
Hugo Benichicd952782017-09-20 11:20:14 +09004571 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4572 synchronized (mNetworkForRequestId) {
4573 return mNetworkForRequestId.get(requestId);
4574 }
4575 }
4576
4577 private void clearNetworkForRequest(int requestId) {
4578 synchronized (mNetworkForRequestId) {
4579 mNetworkForRequestId.remove(requestId);
4580 }
4581 }
4582
4583 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4584 synchronized (mNetworkForRequestId) {
4585 mNetworkForRequestId.put(requestId, nai);
4586 }
4587 }
4588
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004589 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004590 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004591 }
4592
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004593 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004594 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004595 }
4596
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004597 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4598 return nri.request.requestId == mDefaultRequest.requestId;
4599 }
4600
Paul Jensen31a94f42015-02-13 14:18:39 -05004601 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004602 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004603 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004604 enforceConnectivityInternalPermission();
4605
Rubin Xu1bb5c082017-09-05 18:40:49 +01004606 LinkProperties lp = new LinkProperties(linkProperties);
4607 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004608 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4609 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004610 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004611 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004612 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004613 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004614 // Make sure the network capabilities reflect what the agent info says.
4615 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004616 synchronized (this) {
4617 nai.networkMonitor.systemReady = mSystemReady;
4618 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004619 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4620 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004621 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004622 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004623 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004624 }
4625
Erik Kline117e7f32018-03-04 21:01:01 +09004626 private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004627 if (VDBG) log("Got NetworkAgent Messenger");
Erik Kline117e7f32018-03-04 21:01:01 +09004628 mNetworkAgentInfos.put(nai.messenger, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004629 synchronized (mNetworkForNetId) {
Erik Kline117e7f32018-03-04 21:01:01 +09004630 mNetworkForNetId.put(nai.network.netId, nai);
Paul Jensen31a94f42015-02-13 14:18:39 -05004631 }
Erik Kline117e7f32018-03-04 21:01:01 +09004632 nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
4633 NetworkInfo networkInfo = nai.networkInfo;
4634 nai.networkInfo = null;
4635 updateNetworkInfo(nai, networkInfo);
4636 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004637 }
4638
4639 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4640 LinkProperties newLp = networkAgent.linkProperties;
4641 int netId = networkAgent.network.netId;
4642
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004643 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4644 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004645 if (networkAgent.clatd != null) {
4646 networkAgent.clatd.fixupLinkProperties(oldLp);
4647 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004648
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004649 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004650 updateMtu(newLp, oldLp);
4651 // TODO - figure out what to do for clat
4652// for (LinkProperties lp : newLp.getStackedLinks()) {
4653// updateMtu(lp, null);
4654// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004655 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004656
Erik Kline94887872016-04-05 13:30:49 +09004657 updateRoutes(newLp, oldLp, netId);
4658 updateDnses(newLp, oldLp, netId);
dalyk1fcb7392018-03-05 12:42:22 -05004659 // Make sure LinkProperties represents the latest private DNS status.
4660 // This does not need to be done before updateDnses because the
4661 // LinkProperties are not the source of the private DNS configuration.
4662 // updateDnses will fetch the private DNS configuration from DnsManager.
4663 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004664
Hugo Benichi6f62b732017-06-27 15:13:20 +09004665 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004666 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004667 if (isDefaultNetwork(networkAgent)) {
4668 handleApplyDefaultProxy(newLp.getHttpProxy());
4669 } else {
4670 updateProxy(newLp, oldLp, networkAgent);
4671 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004672 // TODO - move this check to cover the whole function
4673 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004674 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004675 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4676 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004677
4678 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004679 }
4680
Joel Scherpelz668370b2017-06-08 15:35:21 +09004681 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004682 // Marks are only available on WiFi interaces. Checking for
4683 // marks on unsupported interfaces is harmless.
4684 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4685 return;
4686 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004687
Joel Scherpelz668370b2017-06-08 15:35:21 +09004688 int mark = mContext.getResources().getInteger(
4689 com.android.internal.R.integer.config_networkWakeupPacketMark);
4690 int mask = mContext.getResources().getInteger(
4691 com.android.internal.R.integer.config_networkWakeupPacketMask);
4692
4693 // Mask/mark of zero will not detect anything interesting.
4694 // Don't install rules unless both values are nonzero.
4695 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004696 return;
4697 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004698
4699 final String prefix = "iface:" + iface;
4700 try {
4701 if (add) {
4702 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4703 } else {
4704 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4705 }
4706 } catch (Exception e) {
4707 loge("Exception modifying wakeup packet monitoring: " + e);
4708 }
4709
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004710 }
4711
4712 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4713 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004714 CompareResult<String> interfaceDiff = new CompareResult<String>(
4715 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4716 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004717 for (String iface : interfaceDiff.added) {
4718 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004719 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004720 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004721 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004722 } catch (Exception e) {
4723 loge("Exception adding interface: " + e);
4724 }
4725 }
4726 for (String iface : interfaceDiff.removed) {
4727 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004728 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004729 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004730 mNetd.removeInterfaceFromNetwork(iface, netId);
4731 } catch (Exception e) {
4732 loge("Exception removing interface: " + e);
4733 }
4734 }
4735 }
4736
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004737 /**
4738 * Have netd update routes from oldLp to newLp.
4739 * @return true if routes changed between oldLp and newLp
4740 */
4741 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004742 // Compare the route diff to determine which routes should be added and removed.
4743 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4744 oldLp != null ? oldLp.getAllRoutes() : null,
4745 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004746
4747 // add routes before removing old in case it helps with continuous connectivity
4748
4749 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4750 for (RouteInfo route : routeDiff.added) {
4751 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004752 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004753 try {
4754 mNetd.addRoute(netId, route);
4755 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004756 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4757 loge("Exception in addRoute for non-gateway: " + e);
4758 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004759 }
4760 }
4761 for (RouteInfo route : routeDiff.added) {
4762 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004763 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004764 try {
4765 mNetd.addRoute(netId, route);
4766 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004767 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4768 loge("Exception in addRoute for gateway: " + e);
4769 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004770 }
4771 }
4772
4773 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004774 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004775 try {
4776 mNetd.removeRoute(netId, route);
4777 } catch (Exception e) {
4778 loge("Exception in removeRoute: " + e);
4779 }
4780 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004781 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004782 }
Erik Kline41368502015-06-17 13:19:54 +09004783
Erik Kline94887872016-04-05 13:30:49 +09004784 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4785 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4786 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004787 }
Erik Kline94887872016-04-05 13:30:49 +09004788
Erik Kline1742fe12017-12-13 19:40:49 +09004789 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4790 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4791
Erik Klinea24d4592018-01-11 21:07:29 +09004792 if (DBG) {
4793 final Collection<InetAddress> dnses = newLp.getDnsServers();
4794 log("Setting DNS servers for network " + netId + " to " + dnses);
4795 }
Erik Kline94887872016-04-05 13:30:49 +09004796 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004797 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004798 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004799 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004800 }
Erik Kline4edba012017-04-07 15:29:29 +09004801 }
4802
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004803 private String getNetworkPermission(NetworkCapabilities nc) {
4804 // TODO: make these permission strings AIDL constants instead.
4805 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4806 return NetworkManagementService.PERMISSION_SYSTEM;
4807 }
4808 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4809 return NetworkManagementService.PERMISSION_NETWORK;
4810 }
4811 return null;
4812 }
4813
Paul Jensen3d194ea2015-06-16 14:27:36 -04004814 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004815 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4816 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4817 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004818 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004819 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004820 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004821 if (nai.everConnected &&
4822 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4823 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004824 // does not cause any request (that is not a listen) currently matching that agent to
4825 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004826 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004827 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004828 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004829 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004830 }
4831
Paul Jensen3d194ea2015-06-16 14:27:36 -04004832 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004833 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004834 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004835 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004836 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004837 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004838 }
Paul Jensene0988542015-06-25 15:30:08 -04004839 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004840 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004841 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004842 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004843 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004844 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004845 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004846 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004847 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004848 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004849 if (nai.isSuspended()) {
4850 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4851 } else {
4852 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4853 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004854
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004855 return newNc;
4856 }
4857
4858 /**
4859 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4860 *
4861 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4862 * capabilities we manage and store in {@code nai}, such as validated status and captive
4863 * portal status)
4864 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4865 * potentially triggers rematches.
4866 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4867 * change.)
4868 *
4869 * @param oldScore score of the network before any of the changes that prompted us
4870 * to call this function.
4871 * @param nai the network having its capabilities updated.
4872 * @param nc the new network capabilities.
4873 */
4874 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4875 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4876
4877 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004878
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004879 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004880 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004881 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004882 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004883 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004884 } catch (RemoteException e) {
4885 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004886 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004887 }
4888
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004889 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004890 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004891 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004892 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004893 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004894
Chalard Jeanf213ca12018-01-16 18:43:05 +09004895 updateUids(nai, prevNc, newNc);
4896
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004897 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004898 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4899 // the change we're processing can't affect any requests, it can only affect the listens
4900 // on this network. We might have been called by rematchNetworkAndRequests when a
4901 // network changed foreground state.
4902 processListenRequests(nai, true);
4903 } else {
4904 // If the requestable capabilities have changed or the score changed, we can't have been
4905 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004906 rematchAllNetworksAndRequests(nai, oldScore);
4907 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004908 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004909
4910 // Report changes that are interesting for network statistics tracking.
4911 if (prevNc != null) {
4912 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004913 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004914 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004915 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004916 if (meteredChanged || roamingChanged) {
4917 notifyIfacesChangedForNetworkStats();
4918 }
4919 }
4920
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004921 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004922 // Tell VPNs about updated capabilities, since they may need to
4923 // bubble those changes through.
4924 synchronized (mVpns) {
4925 for (int i = 0; i < mVpns.size(); i++) {
4926 final Vpn vpn = mVpns.valueAt(i);
4927 vpn.updateCapabilities();
4928 }
4929 }
4930 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 }
4932
Chalard Jeanf213ca12018-01-16 18:43:05 +09004933 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4934 NetworkCapabilities newNc) {
4935 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4936 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4937 if (null == prevRanges) prevRanges = new ArraySet<>();
4938 if (null == newRanges) newRanges = new ArraySet<>();
4939 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4940
4941 prevRanges.removeAll(newRanges);
4942 newRanges.removeAll(prevRangesCopy);
4943
4944 try {
4945 if (!newRanges.isEmpty()) {
4946 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4947 newRanges.toArray(addedRangesArray);
4948 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4949 }
4950 if (!prevRanges.isEmpty()) {
4951 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4952 prevRanges.toArray(removedRangesArray);
4953 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4954 }
4955 } catch (Exception e) {
4956 // Never crash!
4957 loge("Exception in updateUids: " + e);
4958 }
4959 }
4960
Hugo Benichief502882017-09-01 01:23:32 +00004961 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Erik Kline79c6d052018-03-21 07:18:33 -07004962 if (getNetworkAgentInfoForNetId(nai.network.netId) != nai) {
Hugo Benichief502882017-09-01 01:23:32 +00004963 // Ignore updates for disconnected networks
4964 return;
4965 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004966 // newLp is already a defensive copy.
4967 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004968 if (VDBG) {
4969 log("Update of LinkProperties for " + nai.name() +
4970 "; created=" + nai.created +
4971 "; everConnected=" + nai.everConnected);
4972 }
4973 LinkProperties oldLp = nai.linkProperties;
4974 synchronized (nai) {
4975 nai.linkProperties = newLp;
4976 }
4977 if (nai.everConnected) {
4978 updateLinkProperties(nai, oldLp);
4979 }
4980 }
4981
Paul Jensenc8b9a742014-09-30 15:37:41 -04004982 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004983 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4984 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004985 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004986 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004987 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4988 }
4989 }
4990
Robert Greenwalt7b816022014-04-18 15:25:25 -07004991 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4992 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004993 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004994 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4995 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004996 }
4997 }
4998
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004999 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
5000 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08005001 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005002 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08005003 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
5004 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08005005 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005006 sendIntent(nri.mPendingIntent, intent);
5007 }
5008 // else not handled
5009 }
5010
5011 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
5012 mPendingIntentWakeLock.acquire();
5013 try {
5014 if (DBG) log("Sending " + pendingIntent);
5015 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
5016 } catch (PendingIntent.CanceledException e) {
5017 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
5018 mPendingIntentWakeLock.release();
5019 releasePendingNetworkRequest(pendingIntent);
5020 }
5021 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
5022 }
5023
5024 @Override
5025 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
5026 String resultData, Bundle resultExtras) {
5027 if (DBG) log("Finished sending " + pendingIntent);
5028 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08005029 // Release with a delay so the receiving client has an opportunity to put in its
5030 // own request.
5031 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005032 }
5033
Chalard Jeanf19db372018-01-26 19:24:40 +09005034 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005035 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09005036 if (nri.messenger == null) {
5037 return; // Default request has no msgr
5038 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005039 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09005040 // TODO: check if defensive copies of data is needed.
5041 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005042 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09005043 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
5044 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005045 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005046 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09005047 case ConnectivityManager.CALLBACK_AVAILABLE: {
5048 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
5049 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
5050 break;
5051 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005052 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005053 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005054 break;
5055 }
5056 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09005057 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeanb03a6222018-04-11 21:09:10 +09005058 final NetworkCapabilities nc = networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jeanb552c462018-02-21 18:43:54 +09005059 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
Chalard Jeandda156a2018-01-10 21:19:32 +09005060 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005061 break;
5062 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005063 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09005064 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07005065 break;
5066 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005067 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005068 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07005069 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005070 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005071 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09005072 String notification = ConnectivityManager.getCallbackName(notificationType);
5073 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005074 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005075 nri.messenger.send(msg);
5076 } catch (RemoteException e) {
5077 // may occur naturally in the race of binder death.
5078 loge("RemoteException caught trying to send a callback msg for " + nri.request);
5079 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005080 }
5081
Hugo Benichidba33db2017-03-23 22:40:44 +09005082 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5083 bundle.putParcelable(t.getClass().getSimpleName(), t);
5084 }
5085
Paul Jensenc8b9a742014-09-30 15:37:41 -04005086 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005087 if (nai.numRequestNetworkRequests() != 0) {
5088 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5089 NetworkRequest nr = nai.requestAt(i);
5090 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005091 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005092 loge("Dead network still had at least " + nr);
5093 break;
5094 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005095 }
5096 nai.asyncChannel.disconnect();
5097 }
5098
Robert Greenwalt7b816022014-04-18 15:25:25 -07005099 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5100 if (oldNetwork == null) {
5101 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5102 return;
5103 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005104 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005105
5106 // If we get here it means that the last linger timeout for this network expired. So there
5107 // must be no other active linger timers, and we must stop lingering.
5108 oldNetwork.clearLingerState();
5109
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005110 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005111 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005112 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005113 } else {
5114 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005115 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5116 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005117 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005118 }
5119
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005120 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005121 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005122 setupDataActivityTracking(newNetwork);
5123 try {
5124 mNetd.setDefaultNetId(newNetwork.network.netId);
5125 } catch (Exception e) {
5126 loge("Exception setting default network :" + e);
5127 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005128
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005129 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005130 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005131 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005132 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005133 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005134 }
5135
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005136 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005137 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5138 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5139 NetworkRequest nr = nri.request;
5140 if (!nr.isListen()) continue;
5141 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5142 nai.removeRequest(nri.request.requestId);
5143 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5144 }
5145 }
5146
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005147 if (capabilitiesChanged) {
5148 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5149 }
5150
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005151 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5152 NetworkRequest nr = nri.request;
5153 if (!nr.isListen()) continue;
5154 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5155 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005156 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005157 }
5158 }
5159 }
5160
Paul Jensen2161a8e2014-09-11 11:00:39 -04005161 // Handles a network appearing or improving its score.
5162 //
5163 // - Evaluates all current NetworkRequests that can be
5164 // satisfied by newNetwork, and reassigns to newNetwork
5165 // any such requests for which newNetwork is the best.
5166 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005167 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005168 // needed. A network is needed if it is the best network for
5169 // one or more NetworkRequests, or if it is a VPN.
5170 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005171 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005172 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005173 //
5174 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5175 // networks that have no chance (i.e. even if validated)
5176 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005177 //
5178 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5179 // it does not remove NetworkRequests that other Networks could better satisfy.
5180 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5181 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5182 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005183 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005184 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005185 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5186 // performed to tear down unvalidated networks that have no chance (i.e. even if
5187 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005188 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005189 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005190 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005191 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005192 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005193 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005194
5195 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5196 final int score = newNetwork.getCurrentScore();
5197
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005198 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005199
Paul Jensen2161a8e2014-09-11 11:00:39 -04005200 // Find and migrate to this Network any NetworkRequests for
5201 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005202 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005203 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005204 NetworkCapabilities nc = newNetwork.networkCapabilities;
5205 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005206 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005207 // Process requests in the first pass and listens in the second pass. This allows us to
5208 // change a network's capabilities depending on which requests it has. This is only
5209 // correct if the change in capabilities doesn't affect whether the network satisfies
5210 // requests or not, and doesn't affect the network's score.
5211 if (nri.request.isListen()) continue;
5212
Hugo Benichicd952782017-09-20 11:20:14 +09005213 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005214 final boolean satisfies = newNetwork.satisfies(nri.request);
5215 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005216 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005217 log("Network " + newNetwork.name() + " was already satisfying" +
5218 " request " + nri.request.requestId + ". No change.");
5219 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005220 keep = true;
5221 continue;
5222 }
5223
5224 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005225 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005226 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005227 // next check if it's better than any current network we're using for
5228 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005229 if (VDBG) {
5230 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005231 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005232 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005233 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005234 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005235 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005236 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005237 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005238 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005239 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005240 affectedNetworks.add(currentNetwork);
5241 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005242 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005243 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005244 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005245 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005246 if (!newNetwork.addRequest(nri.request)) {
5247 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5248 }
5249 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005250 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005251 // Tell NetworkFactories about the new score, so they can stop
5252 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005253 // TODO - this could get expensive if we have alot of requests for this
5254 // network. Think about if there is a way to reduce this. Push
5255 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005256 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005257 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005258 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005259 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005260 if (currentNetwork != null) {
5261 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5262 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005263 }
5264 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005265 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005266 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5267 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005268 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005269 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5270 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5271 // This means this code doesn't have to handle the case where "currentNetwork" no
5272 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5273 if (DBG) {
5274 log("Network " + newNetwork.name() + " stopped satisfying" +
5275 " request " + nri.request.requestId);
5276 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005277 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005278 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005279 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005280 sendUpdatedScoreToFactories(nri.request, 0);
5281 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005282 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5283 newNetwork.name() +
5284 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005285 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005286 // TODO: Technically, sending CALLBACK_LOST here is
5287 // incorrect if there is a replacement network currently
5288 // connected that can satisfy nri, which is a request
5289 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005290 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5291 // so this code is only incorrect for a network that loses
5292 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005293 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005294 }
5295 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005296 if (isNewDefault) {
5297 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005298 makeDefault(newNetwork);
5299 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005300 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005301 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005302 // Have a new default network, release the transition wakelock in
5303 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005304 }
5305
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005306 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5307 Slog.wtf(TAG, String.format(
5308 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005309 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005310 }
5311 if (newNetwork.getCurrentScore() != score) {
5312 Slog.wtf(TAG, String.format(
5313 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005314 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005315 }
5316
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005317 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005318 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5319 // If the network went from background to foreground or vice versa, we need to update
5320 // its foreground state. It is safe to do this after rematching the requests because
5321 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5322 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005323 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005324 } else {
5325 processListenRequests(newNetwork, false);
5326 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005327
Paul Jensencf4c2c62015-07-01 14:16:32 -04005328 // do this after the default net is switched, but
5329 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005330 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005331
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005332 // Linger any networks that are no longer needed. This should be done after sending the
5333 // available callback for newNetwork.
5334 for (NetworkAgentInfo nai : affectedNetworks) {
5335 updateLingerState(nai, now);
5336 }
5337 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5338 // does not need to be done in any particular order.
5339 updateLingerState(newNetwork, now);
5340
Paul Jensencf4c2c62015-07-01 14:16:32 -04005341 if (isNewDefault) {
5342 // Maintain the illusion: since the legacy API only
5343 // understands one network at a time, we must pretend
5344 // that the current default network disconnected before
5345 // the new one connected.
5346 if (oldDefaultNetwork != null) {
5347 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5348 oldDefaultNetwork, true);
5349 }
5350 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5351 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5352 notifyLockdownVpn(newNetwork);
5353 }
5354
Robert Greenwalt7b816022014-04-18 15:25:25 -07005355 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005356 // Notify battery stats service about this network, both the normal
5357 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005358 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005359 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005360 final IBatteryStats bs = BatteryStatsService.getService();
5361 final int type = newNetwork.networkInfo.getType();
5362
5363 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5364 bs.noteNetworkInterfaceType(baseIface, type);
5365 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5366 final String stackedIface = stacked.getInterfaceName();
5367 bs.noteNetworkInterfaceType(stackedIface, type);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005368 }
5369 } catch (RemoteException ignored) {
5370 }
5371
Robert Greenwalt152ed372014-12-17 17:19:53 -08005372 // This has to happen after the notifyNetworkCallbacks as that tickles each
5373 // ConnectivityManager instance so that legacy requests correctly bind dns
5374 // requests to this network. The legacy users are listening for this bcast
5375 // and will generally do a dns request so they can ensureRouteToHost and if
5376 // they do that before the callbacks happen they'll use the default network.
5377 //
5378 // TODO: Is there still a race here? We send the broadcast
5379 // after sending the callback, but if the app can receive the
5380 // broadcast before the callback, it might still break.
5381 //
5382 // This *does* introduce a race where if the user uses the new api
5383 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5384 // they may get old info. Reverse this after the old startUsing api is removed.
5385 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005386 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5387 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005388 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005389 // legacy type tracker filters out repeat adds
5390 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5391 }
5392 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005393
5394 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5395 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5396 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5397 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5398 if (newNetwork.isVPN()) {
5399 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5400 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005401 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005402 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5403 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005404 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005405 if (nai.getLingerExpiry() > 0) {
5406 // This network has active linger timers and no requests, but is not
5407 // lingering. Linger it.
5408 //
5409 // One way (the only way?) this can happen if this network is unvalidated
5410 // and became unneeded due to another network improving its score to the
5411 // point where this network will no longer be able to satisfy any requests
5412 // even if it validates.
5413 updateLingerState(nai, now);
5414 } else {
5415 if (DBG) log("Reaping " + nai.name());
5416 teardownUnneededNetwork(nai);
5417 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005418 }
5419 }
5420 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005421 }
5422
Paul Jensen1c7ba022015-06-16 14:27:36 -04005423 /**
5424 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5425 * being disconnected.
5426 * @param changed If only one Network's score or capabilities have been modified since the last
5427 * time this function was called, pass this Network in this argument, otherwise pass
5428 * null.
5429 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5430 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5431 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5432 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5433 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005434 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005435 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005436 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5437 // to avoid the slowness. It is not simply enough to process just "changed", for
5438 // example in the case where "changed"'s score decreases and another network should begin
5439 // satifying a NetworkRequest that "changed" currently satisfies.
5440
5441 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5442 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5443 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005444 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005445 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005446 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005447 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005448 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5449 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5450 // Rematch higher scoring networks first to prevent requests first matching a lower
5451 // scoring network and then a higher scoring network, which could produce multiple
5452 // callbacks and inadvertently unlinger networks.
5453 Arrays.sort(nais);
5454 for (NetworkAgentInfo nai : nais) {
5455 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005456 // Only reap the last time through the loop. Reaping before all rematching
5457 // is complete could incorrectly teardown a network that hasn't yet been
5458 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005459 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005460 : ReapUnvalidatedNetworks.REAP,
5461 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005462 }
5463 }
5464 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005465
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005466 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005467 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005468 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005469 // For now only update icons for default connection.
5470 // TODO: Update WiFi and cellular icons separately. b/17237507
5471 if (!isDefaultNetwork(nai)) return;
5472
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005473 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005474 // Don't repeat publish.
5475 if (newInetCondition == mDefaultInetConditionPublished) return;
5476
5477 mDefaultInetConditionPublished = newInetCondition;
5478 sendInetConditionBroadcast(nai.networkInfo);
5479 }
5480
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005481 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005482 synchronized (mVpns) {
5483 if (mLockdownTracker != null) {
5484 if (nai != null && nai.isVPN()) {
5485 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5486 } else {
5487 mLockdownTracker.onNetworkInfoChanged();
5488 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005489 }
5490 }
5491 }
5492
Robert Greenwalt7b816022014-04-18 15:25:25 -07005493 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005494 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005495 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005496 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005497 synchronized (networkAgent) {
5498 oldInfo = networkAgent.networkInfo;
5499 networkAgent.networkInfo = newInfo;
5500 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005501 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005502
Robert Greenwalt7b816022014-04-18 15:25:25 -07005503 if (DBG) {
5504 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5505 (oldInfo == null ? "null" : oldInfo.getState()) +
5506 " to " + state);
5507 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005508
Robin Lee585e2482016-05-01 23:00:00 +01005509 if (!networkAgent.created
5510 && (state == NetworkInfo.State.CONNECTED
5511 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005512
5513 // A network that has just connected has zero requests and is thus a foreground network.
5514 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5515
Robert Greenwalt7b816022014-04-18 15:25:25 -07005516 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005517 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005518 if (networkAgent.isVPN()) {
5519 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005520 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5521 (networkAgent.networkMisc == null ||
5522 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005523 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005524 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005525 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005526 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005527 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005528 loge("Error creating network " + networkAgent.network.netId + ": "
5529 + e.getMessage());
5530 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005531 }
Paul Jenseneec75412014-08-04 12:21:19 -04005532 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005533 }
5534
5535 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5536 networkAgent.everConnected = true;
5537
Erik Kline79c6d052018-03-21 07:18:33 -07005538 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005539 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005540 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005541
Paul Jensenca8f16a2014-05-09 12:47:55 -04005542 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005543 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005544
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005545 if (networkAgent.isVPN()) {
5546 // Temporarily disable the default proxy (not global).
5547 synchronized (mProxyLock) {
5548 if (!mDefaultProxyDisabled) {
5549 mDefaultProxyDisabled = true;
5550 if (mGlobalProxy == null && mDefaultProxy != null) {
5551 sendProxyBroadcast(null);
5552 }
5553 }
5554 }
5555 // TODO: support proxy per network.
5556 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005557
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005558 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5559 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5560 // capabilities, so it only needs to be done once on initial connect, not every time the
5561 // network's capabilities change. Note that we do this before rematching the network,
5562 // so we could decide to tear it down immediately afterwards. That's fine though - on
5563 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5564 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005565 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005566
Paul Jensen2161a8e2014-09-11 11:00:39 -04005567 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005568 final long now = SystemClock.elapsedRealtime();
5569 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005570
5571 // This has to happen after matching the requests, because callbacks are just requests.
5572 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005573 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005574 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005575 if (networkAgent.isVPN()) {
5576 synchronized (mProxyLock) {
5577 if (mDefaultProxyDisabled) {
5578 mDefaultProxyDisabled = false;
5579 if (mGlobalProxy == null && mDefaultProxy != null) {
5580 sendProxyBroadcast(mDefaultProxy);
5581 }
5582 }
5583 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005584 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005585 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005586 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5587 state == NetworkInfo.State.SUSPENDED) {
5588 // going into or coming out of SUSPEND: rescore and notify
5589 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005590 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005591 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005592 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5593 networkAgent.networkCapabilities);
5594 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5595 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005596 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5597 ConnectivityManager.CALLBACK_SUSPENDED :
5598 ConnectivityManager.CALLBACK_RESUMED));
5599 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005600 }
5601 }
5602
Robert Greenwaltac96c522014-06-03 16:43:57 -07005603 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005604 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005605 if (score < 0) {
5606 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5607 "). Bumping score to min of 0");
5608 score = 0;
5609 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005610
Paul Jensen2161a8e2014-09-11 11:00:39 -04005611 final int oldScore = nai.getCurrentScore();
5612 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005613
Paul Jensen85cf78e2015-06-25 13:25:07 -04005614 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005615
Paul Jensenc8b9a742014-09-30 15:37:41 -04005616 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005617 }
5618
Erik Klinec75d4fa2017-02-15 19:59:17 +09005619 // Notify only this one new request of the current state. Transfer all the
5620 // current state by calling NetworkCapabilities and LinkProperties callbacks
5621 // so that callers can be guaranteed to have as close to atomicity in state
5622 // transfer as can be supported by this current API.
5623 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005624 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005625 if (nri.mPendingIntent != null) {
5626 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5627 // Attempt no subsequent state pushes where intents are involved.
5628 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005629 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005630
5631 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005632 }
5633
Robert Greenwalt8d482522015-06-24 13:23:42 -07005634 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005635 // The NetworkInfo we actually send out has no bearing on the real
5636 // state of affairs. For example, if the default connection is mobile,
5637 // and a request for HIPRI has just gone away, we need to pretend that
5638 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5639 // the state to DISCONNECTED, even though the network is of type MOBILE
5640 // and is still connected.
5641 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5642 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005643 if (state != DetailedState.DISCONNECTED) {
5644 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005645 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005646 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005647 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005648 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5649 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5650 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5651 if (info.isFailover()) {
5652 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5653 nai.networkInfo.setFailover(false);
5654 }
5655 if (info.getReason() != null) {
5656 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5657 }
5658 if (info.getExtraInfo() != null) {
5659 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5660 }
5661 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005662 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005663 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005664 if (newDefaultAgent != null) {
5665 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5666 newDefaultAgent.networkInfo);
5667 } else {
5668 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5669 }
5670 }
5671 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5672 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005673 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005674 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005675 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005676 }
5677 }
5678 }
5679
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005680 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005681 if (VDBG) {
5682 String notification = ConnectivityManager.getCallbackName(notifyType);
5683 log("notifyType " + notification + " for " + networkAgent.name());
5684 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005685 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5686 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005687 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5688 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005689 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5690 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005691 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005692 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005693 } else {
5694 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5695 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005696 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005697 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005698
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005699 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5700 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5701 }
5702
Jeff Sharkey69736342014-12-08 14:50:12 -08005703 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005704 * Returns the list of all interfaces that could be used by network traffic that does not
5705 * explicitly specify a network. This includes the default network, but also all VPNs that are
5706 * currently connected.
5707 *
5708 * Must be called on the handler thread.
5709 */
5710 private Network[] getDefaultNetworks() {
5711 ArrayList<Network> defaultNetworks = new ArrayList<>();
5712 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5713 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5714 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5715 defaultNetworks.add(nai.network);
5716 }
5717 }
5718 return defaultNetworks.toArray(new Network[0]);
5719 }
5720
5721 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005722 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5723 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005724 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005725 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005726 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005727 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005728 } catch (Exception ignored) {
5729 }
5730 }
5731
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005732 @Override
5733 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005734 int user = UserHandle.getUserId(Binder.getCallingUid());
5735 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005736 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005737 return mVpns.get(user).addAddress(address, prefixLength);
5738 }
5739 }
5740
5741 @Override
5742 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005743 int user = UserHandle.getUserId(Binder.getCallingUid());
5744 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005745 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005746 return mVpns.get(user).removeAddress(address, prefixLength);
5747 }
5748 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005749
5750 @Override
5751 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005752 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005753 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005754 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005755 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005756 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005757 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005758 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005759 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005760 }
5761 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005762 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005763
5764 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005765 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005766 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005767 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005768 }
5769
5770 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005771 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5772 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5773 enforceKeepalivePermission();
5774 mKeepaliveTracker.startNattKeepalive(
5775 getNetworkAgentInfoForNetwork(network),
5776 intervalSeconds, messenger, binder,
5777 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5778 }
5779
5780 @Override
5781 public void stopKeepalive(Network network, int slot) {
5782 mHandler.sendMessage(mHandler.obtainMessage(
5783 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5784 }
5785
5786 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005787 public void factoryReset() {
5788 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005789
5790 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5791 return;
5792 }
5793
Robin Lee3b3dd942015-05-12 18:14:58 +01005794 final int userId = UserHandle.getCallingUserId();
5795
Stuart Scottf1fb3972015-04-02 18:00:02 -07005796 // Turn airplane mode off
5797 setAirplaneMode(false);
5798
Stuart Scotte3e314d2015-04-20 14:07:45 -07005799 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5800 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005801 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005802 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005803 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005804 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005805 }
5806
Stuart Scotte3e314d2015-04-20 14:07:45 -07005807 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005808 // Remove always-on package
5809 synchronized (mVpns) {
5810 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5811 if (alwaysOnPackage != null) {
5812 setAlwaysOnVpnPackage(userId, null, false);
5813 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5814 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005815
Hugo Benichi69744342017-11-27 10:57:16 +09005816 // Turn Always-on VPN off
5817 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5818 final long ident = Binder.clearCallingIdentity();
5819 try {
5820 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5821 mLockdownEnabled = false;
5822 setLockdownTracker(null);
5823 } finally {
5824 Binder.restoreCallingIdentity(ident);
5825 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005826 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005827
Hugo Benichi69744342017-11-27 10:57:16 +09005828 // Turn VPN off
5829 VpnConfig vpnConfig = getVpnConfig(userId);
5830 if (vpnConfig != null) {
5831 if (vpnConfig.legacy) {
5832 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5833 } else {
5834 // Prevent this app (packagename = vpnConfig.user) from initiating
5835 // VPN connections in the future without user intervention.
5836 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005837
Hugo Benichi69744342017-11-27 10:57:16 +09005838 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5839 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005840 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005841 }
5842 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005843
5844 Settings.Global.putString(mContext.getContentResolver(),
5845 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005846 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005847
Ricky Wai44dcbde2018-01-23 04:09:45 +00005848 @Override
5849 public byte[] getNetworkWatchlistConfigHash() {
5850 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5851 if (nwm == null) {
5852 loge("Unable to get NetworkWatchlistManager");
5853 return null;
5854 }
5855 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5856 return nwm.getWatchlistConfigHash();
5857 }
5858
Paul Jensencf4c2c62015-07-01 14:16:32 -04005859 @VisibleForTesting
5860 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5861 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5862 return new NetworkMonitor(context, handler, nai, defaultRequest);
5863 }
Erik Kline48f12f22016-04-14 17:30:59 +09005864
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005865 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005866 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5867 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005868 }
5869
5870 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005871 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5872 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5873 }
5874
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005875 @VisibleForTesting
5876 public boolean hasService(String name) {
5877 return ServiceManager.checkService(name) != null;
5878 }
5879
Hugo Benichi64901e52017-10-19 14:42:40 +09005880 @VisibleForTesting
5881 protected IpConnectivityMetrics.Logger metricsLogger() {
5882 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5883 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005884 }
5885
5886 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005887 int[] transports = nai.networkCapabilities.getTransportTypes();
5888 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005889 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005890
5891 private static boolean toBool(int encodedBoolean) {
5892 return encodedBoolean != 0; // Only 0 means false.
5893 }
5894
5895 private static int encodeBool(boolean b) {
5896 return b ? 1 : 0;
5897 }
mswest46386886f2018-03-12 10:34:34 -07005898
5899 @Override
5900 public void onShellCommand(FileDescriptor in, FileDescriptor out,
5901 FileDescriptor err, String[] args, ShellCallback callback,
5902 ResultReceiver resultReceiver) {
5903 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
5904 }
5905
5906 private class ShellCmd extends ShellCommand {
5907
5908 @Override
5909 public int onCommand(String cmd) {
5910 if (cmd == null) {
5911 return handleDefaultCommands(cmd);
5912 }
5913 final PrintWriter pw = getOutPrintWriter();
5914 try {
5915 switch (cmd) {
5916 case "airplane-mode":
5917 final String action = getNextArg();
5918 if ("enable".equals(action)) {
5919 setAirplaneMode(true);
5920 return 0;
5921 } else if ("disable".equals(action)) {
5922 setAirplaneMode(false);
5923 return 0;
5924 } else if (action == null) {
5925 final ContentResolver cr = mContext.getContentResolver();
5926 final int enabled = Settings.Global.getInt(cr,
5927 Settings.Global.AIRPLANE_MODE_ON);
5928 pw.println(enabled == 0 ? "disabled" : "enabled");
5929 return 0;
5930 } else {
5931 onHelp();
5932 return -1;
5933 }
5934 default:
5935 return handleDefaultCommands(cmd);
5936 }
5937 } catch (Exception e) {
5938 pw.println(e);
5939 }
5940 return -1;
5941 }
5942
5943 @Override
5944 public void onHelp() {
5945 PrintWriter pw = getOutPrintWriter();
5946 pw.println("Connectivity service commands:");
5947 pw.println(" help");
5948 pw.println(" Print this help text.");
5949 pw.println(" airplane-mode [enable|disable]");
5950 pw.println(" Turn airplane mode on or off.");
5951 pw.println(" airplane-mode");
5952 pw.println(" Get airplane mode.");
5953 }
5954 }
Erik Kline79c6d052018-03-21 07:18:33 -07005955}