blob: 8883c4b3f29c40aaa33b7690c552fb6d6ee14804 [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;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070032import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070034import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090042import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090078import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
Erik Kline065ab6e2016-10-02 18:02:14 +090081import android.net.util.AvoidBadWifiTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080083import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070084import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040085import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070087import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070089import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070092import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070094import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070095import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080097import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090098import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700100import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400101import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700103import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600107import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700108import android.util.LocalLog;
109import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600110import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700113import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500114import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700116import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Wink Savilleab9321d2013-06-29 21:10:57 -0700118import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400119import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400120import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700122import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700123import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700124import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800125import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700126import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700127import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700128import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900129import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900130import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700131import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700132import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400133import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900134import com.android.server.connectivity.KeepaliveTracker;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900135import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900136import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700137import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600138import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400139import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900140import com.android.server.connectivity.NetworkNotificationManager;
141import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400142import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700143import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800144import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700145import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700146import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700147import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600148
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700149import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700150
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700151import org.xmlpull.v1.XmlPullParser;
152import org.xmlpull.v1.XmlPullParserException;
153
154import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700156import java.io.FileNotFoundException;
157import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700158import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700160import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700161import java.net.InetAddress;
162import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700163import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700165import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700166import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700167import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700168import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700169import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700170import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700171import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600172import java.util.SortedSet;
173import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
175/**
176 * @hide
177 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800178public class ConnectivityService extends IConnectivityManager.Stub
179 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900180 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900182 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700183 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Jake Hamby786e71a2014-02-06 14:43:50 -0800185 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900186 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700187
Jeff Sharkey899223b2012-08-04 15:24:58 -0700188 // TODO: create better separation between radio types and network types
189
Robert Greenwalt42acef32009-08-12 16:08:25 -0700190 // how long to wait before switching back to a radio's default network
191 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
192 // system property that can override the above value
193 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
194 "android.telephony.apn-restore";
195
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900196 // How long to wait before putting up a "This network doesn't have an Internet connection,
197 // connect anyway?" dialog after the user selects a network that doesn't validate.
198 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
199
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900200 // Default to 30s linger time-out. Modifiable only for testing.
201 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
202 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
203 @VisibleForTesting
204 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
205
Jeremy Joslin79294842014-12-03 17:15:28 -0800206 // How long to delay to removal of a pending intent based request.
207 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
208 private final int mReleasePendingIntentDelayMs;
209
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800210 private Tethering mTethering;
211
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700212 private final PermissionMonitor mPermissionMonitor;
213
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700214 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700215
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700216 @GuardedBy("mVpns")
217 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700218
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700219 private boolean mLockdownEnabled;
220 private LockdownVpnTracker mLockdownTracker;
221
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700222 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
223 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700224 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600225 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700226 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700227 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600228 @GuardedBy("mRulesLock")
229 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
230 /** Flag indicating if background data is restricted. */
231 @GuardedBy("mRulesLock")
232 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700233
Erik Klineda4bfa82015-04-30 12:58:40 +0900234 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700236 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700237 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800239 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
241 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700242 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700244 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800245 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700246 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700247
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700248 private String mCurrentTcpBufferSizes;
249
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700250 private static final int ENABLED = 1;
251 private static final int DISABLED = 0;
252
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900253 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900254 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
255 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900256
Paul Jensenb10e37f2014-11-25 12:33:08 -0500257 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400258 // Tear down networks that have no chance (e.g. even if validated) of becoming
259 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500260 // all networks have been rematched against all NetworkRequests.
261 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400262 // Don't reap networks. This should be passed when some networks have not yet been
263 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500264 DONT_REAP
265 };
266
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900267 private enum UnneededFor {
268 LINGER, // Determine whether this network is unneeded and should be lingered.
269 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
270 }
271
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700272 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700273 * used internally to change our mobile data enabled flag
274 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700275 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700276
277 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700278 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700279 * from one net to another. Clear happens when we get a new
280 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
281 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700282 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700283 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700284
Robert Greenwalt434203a2010-10-11 16:00:27 -0700285 /**
286 * used internally to reload global proxy settings
287 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700288 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700289
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700290 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400291 * PAC manager has received new port.
292 */
293 private static final int EVENT_PROXY_HAS_CHANGED = 16;
294
Robert Greenwalte049c232014-04-11 15:53:27 -0700295 /**
296 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700297 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700298 */
299 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
300
Robert Greenwalt7b816022014-04-18 15:25:25 -0700301 /**
302 * used internally when registering NetworkAgents
303 * obj = Messenger
304 */
305 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
306
Robert Greenwalt9258c642014-03-26 16:47:06 -0700307 /**
308 * used to add a network request
309 * includes a NetworkRequestInfo
310 */
311 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
312
313 /**
314 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900315 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700316 * cancel it.
317 * includes a NetworkRequestInfo
318 */
319 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
320
321 /**
322 * used to add a network listener - no request
323 * includes a NetworkRequestInfo
324 */
325 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
326
327 /**
328 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400329 * arg1 = UID of caller
330 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700331 */
332 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
333
Robert Greenwalta67be032014-05-16 15:49:14 -0700334 /**
335 * used internally when registering NetworkFactories
336 * obj = Messenger
337 */
338 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
339
Robert Greenwalt27711812014-06-25 16:45:57 -0700340 /**
341 * used internally to expire a wakelock when transitioning
342 * from one net to another. Expire happens when we fail to find
343 * a new network (typically after 1 minute) -
344 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
345 * a replacement network.
346 */
347 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
348
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700349 /**
350 * Used internally to indicate the system is ready.
351 */
352 private static final int EVENT_SYSTEM_READY = 25;
353
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800354 /**
355 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400356 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800357 */
358 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
359
360 /**
361 * used to remove a pending intent and its associated network request.
362 * arg1 = UID of caller
363 * obj = PendingIntent
364 */
365 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
366
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900367 /**
368 * used to specify whether a network should be used even if unvalidated.
369 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
370 * arg2 = whether to remember this choice in the future (1 or 0)
371 * obj = network
372 */
373 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
374
375 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900376 * used to specify whether a network should not be penalized when it becomes unvalidated.
377 */
378 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
379
380 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900381 * used to ask the user to confirm a connection to an unvalidated network.
382 * obj = network
383 */
384 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700385
Erik Klineda4bfa82015-04-30 12:58:40 +0900386 /**
387 * used internally to (re)configure mobile data always-on settings.
388 */
389 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
390
Paul Jensen694f2b82015-06-17 14:15:39 -0400391 /**
392 * used to add a network listener with a pending intent
393 * obj = NetworkRequestInfo
394 */
395 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
396
Erik Klineacdd6392016-07-07 16:50:58 +0900397 /**
398 * Indicates a caller has requested to have its callback invoked with
399 * the latest LinkProperties or NetworkCapabilities.
400 *
401 * arg1 = UID of caller
402 * obj = NetworkRequest
403 */
404 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
405 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
406
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900407 /** Handler thread used for both of the handlers below. */
408 @VisibleForTesting
409 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700410 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700411 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700412 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700413 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700414
Mike Lockwood0f79b542009-08-14 14:18:49 -0400415 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800416 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400417
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700418 private PowerManager.WakeLock mNetTransitionWakeLock;
419 private String mNetTransitionWakeLockCausedBy = "";
420 private int mNetTransitionWakeLockSerialNumber;
421 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800422 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700423
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700424 // used in DBG mode to track inet condition reports
425 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
426 private ArrayList mInetLog;
427
Robert Greenwalt434203a2010-10-11 16:00:27 -0700428 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400429 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700430 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700431 private boolean mDefaultProxyDisabled = false;
432
Robert Greenwalt434203a2010-10-11 16:00:27 -0700433 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400434 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700435
Jason Monk602b2322013-07-03 17:04:33 -0400436 private PacManager mPacManager = null;
437
Erik Klineda4bfa82015-04-30 12:58:40 +0900438 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700439
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400440 private UserManager mUserManager;
441
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700442 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700443 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700444
Robert Greenwalt50393202011-06-21 17:26:14 -0700445 // the set of network types that can only be enabled by system/sig apps
446 List mProtectedNetworks;
447
John Spurlockbf991a82013-06-24 14:20:23 -0400448 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700449
Wink Savilleab9321d2013-06-29 21:10:57 -0700450 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400451
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900452 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900453 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900454 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900455
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700456 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
457 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700458 private final static int MAX_NET_ID = 65535;
459 private int mNextNetId = MIN_NET_ID;
460
Robert Greenwalt34524f02014-05-18 16:22:10 -0700461 // sequence number of NetworkRequests
462 private int mNextNetworkRequestId = 1;
463
Erik Kline7523eb32015-07-09 18:24:03 +0900464 // NetworkRequest activity String log entries.
465 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
466 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
467
Hugo Benichic2ae2872016-07-11 11:05:12 +0900468 // NetworkInfo blocked and unblocked String log entries
469 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
470 private static final int MAX_NETWORK_INFO_LOGS = 100;
471 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
472
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700473 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
474 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400475 private static class ValidationLog {
476 final Network mNetwork;
477 final String mNetworkExtraInfo;
478 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700479
Paul Jensen0808eb82016-06-03 13:51:21 -0400480 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
481 mNetwork = network;
482 mNetworkExtraInfo = networkExtraInfo;
483 mLog = log;
484 }
485 }
486 private final ArrayDeque<ValidationLog> mValidationLogs =
487 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
488
489 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700490 synchronized(mValidationLogs) {
491 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
492 mValidationLogs.removeLast();
493 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400494 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700495 }
496 }
497
Hugo Benichif9fdf872016-07-28 17:53:06 +0900498 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900499
Erik Kline065ab6e2016-10-02 18:02:14 +0900500 @VisibleForTesting
501 final AvoidBadWifiTracker mAvoidBadWifiTracker;
502
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700503 /**
504 * Implements support for the legacy "one network per network type" model.
505 *
506 * We used to have a static array of NetworkStateTrackers, one for each
507 * network type, but that doesn't work any more now that we can have,
508 * for example, more that one wifi network. This class stores all the
509 * NetworkAgentInfo objects that support a given type, but the legacy
510 * API will only see the first one.
511 *
512 * It serves two main purposes:
513 *
514 * 1. Provide information about "the network for a given type" (since this
515 * API only supports one).
516 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
517 * the first network for a given type changes, or if the default network
518 * changes.
519 */
520 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900521
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900522 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900523 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 /**
526 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
527 * Each list holds references to all NetworkAgentInfos that are used to
528 * satisfy requests for that network type.
529 *
530 * This array is built out at startup such that an unsupported network
531 * doesn't get an ArrayList instance, making this a tristate:
532 * unsupported, supported but not active and active.
533 *
534 * The actual lists are populated when we scan the network types that
535 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900536 *
537 * Threading model:
538 * - addSupportedType() is only called in the constructor
539 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
540 * They are therefore not thread-safe with respect to each other.
541 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
542 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
543 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700544 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900545 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700546
547 public LegacyTypeTracker() {
548 mTypeLists = (ArrayList<NetworkAgentInfo>[])
549 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
550 }
551
552 public void addSupportedType(int type) {
553 if (mTypeLists[type] != null) {
554 throw new IllegalStateException(
555 "legacy list for type " + type + "already initialized");
556 }
557 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
558 }
559
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 public boolean isTypeSupported(int type) {
561 return isNetworkTypeValid(type) && mTypeLists[type] != null;
562 }
563
564 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900565 synchronized (mTypeLists) {
566 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
567 return mTypeLists[type].get(0);
568 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700569 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900570 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 }
572
Robert Greenwalt8d482522015-06-24 13:23:42 -0700573 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900574 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900575 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700576 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900577 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900578 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900579 }
580 }
581
582 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700583 public void add(int type, NetworkAgentInfo nai) {
584 if (!isTypeSupported(type)) {
585 return; // Invalid network type.
586 }
587 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
588
589 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
590 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700591 return;
592 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900593 synchronized (mTypeLists) {
594 list.add(nai);
595 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900596
597 // 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 +0900598 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900599 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700600 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
601 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700602 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700603 }
604
Lorenzo Colittia793a672014-07-31 23:20:17 +0900605 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900606 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
608 if (list == null || list.isEmpty()) {
609 return;
610 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900611 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900612
Hugo Benichi78caa2582016-06-21 09:48:07 +0900613 synchronized (mTypeLists) {
614 if (!list.remove(nai)) {
615 return;
616 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900617 }
618
Robert Greenwalt8d482522015-06-24 13:23:42 -0700619 final DetailedState state = DetailedState.DISCONNECTED;
620
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700622 maybeLogBroadcast(nai, state, type, wasDefault);
623 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 }
625
626 if (!list.isEmpty() && wasFirstNetwork) {
627 if (DBG) log("Other network available for type " + type +
628 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900629 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700630 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
631 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 }
633 }
634
635 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900636 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
637 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700638 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900639 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700640 }
641 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700642
Robert Greenwalt8d482522015-06-24 13:23:42 -0700643 // send out another legacy broadcast - currently only used for suspend/unsuspend
644 // toggle
645 public void update(NetworkAgentInfo nai) {
646 final boolean isDefault = isDefaultNetwork(nai);
647 final DetailedState state = nai.networkInfo.getDetailedState();
648 for (int type = 0; type < mTypeLists.length; type++) {
649 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700650 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900651 final boolean isFirst = contains && (nai == list.get(0));
652 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700653 maybeLogBroadcast(nai, state, type, isDefault);
654 sendLegacyNetworkBroadcast(nai, state, type);
655 }
656 }
657 }
658
Lorenzo Colittia793a672014-07-31 23:20:17 +0900659 private String naiToString(NetworkAgentInfo nai) {
660 String name = (nai != null) ? nai.name() : "null";
661 String state = (nai.networkInfo != null) ?
662 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
663 "???/???";
664 return name + " " + state;
665 }
666
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700667 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900668 pw.println("mLegacyTypeTracker:");
669 pw.increaseIndent();
670 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700671 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900672 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700673 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900674 pw.println();
675 pw.println("Current state:");
676 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900677 synchronized (mTypeLists) {
678 for (int type = 0; type < mTypeLists.length; type++) {
679 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
680 for (NetworkAgentInfo nai : mTypeLists[type]) {
681 pw.println(type + " " + naiToString(nai));
682 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900683 }
684 }
685 pw.decreaseIndent();
686 pw.decreaseIndent();
687 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700688 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700689 }
690 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
691
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900692 @VisibleForTesting
693 protected HandlerThread createHandlerThread() {
694 return new HandlerThread("ConnectivityServiceThread");
695 }
696
Jeff Sharkey899223b2012-08-04 15:24:58 -0700697 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700698 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900699 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
700 }
701
702 @VisibleForTesting
703 protected ConnectivityService(Context context, INetworkManagementService netManager,
704 INetworkStatsService statsService, INetworkPolicyManager policyManager,
705 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800706 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800707
Hugo Benichif9fdf872016-07-28 17:53:06 +0900708 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900709 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900710 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900711 mNetworkRequests.put(mDefaultRequest, defaultNRI);
712 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900713
714 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900715 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700716
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900717 mHandlerThread = createHandlerThread();
718 mHandlerThread.start();
719 mHandler = new InternalHandler(mHandlerThread.getLooper());
720 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700721
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800722 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800723 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
724 String id = Settings.Secure.getString(context.getContentResolver(),
725 Settings.Secure.ANDROID_ID);
726 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700727 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800728 SystemProperties.set("net.hostname", name);
729 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800730 }
731
Jeremy Joslin79294842014-12-03 17:15:28 -0800732 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
733 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
734
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900735 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
736
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700737 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700738 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800739 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700740 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700741 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700742 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700743
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700744 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600745 mPolicyManager.setConnectivityListener(mPolicyListener);
746 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700747 } catch (RemoteException e) {
748 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700749 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700750 }
751
752 final PowerManager powerManager = (PowerManager) context.getSystemService(
753 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700754 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
755 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
756 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800757 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700758
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700759 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700760
Wink Saville51f456f2013-04-23 14:26:51 -0700761 // TODO: What is the "correct" way to do determine if this is a wifi only device?
762 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
763 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700764 String[] naStrings = context.getResources().getStringArray(
765 com.android.internal.R.array.networkAttributes);
766 for (String naString : naStrings) {
767 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700768 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700769 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700770 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800771 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700772 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700773 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700774 }
Wink Saville51f456f2013-04-23 14:26:51 -0700775 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
776 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
777 n.type);
778 continue;
779 }
Wink Saville975c8482011-04-07 14:23:45 -0700780 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800781 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700782 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700783 continue;
784 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700785 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700786
Wink Saville975c8482011-04-07 14:23:45 -0700787 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700788 mNetworksDefined++;
789 } catch(Exception e) {
790 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700791 }
792 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700793
794 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
795 if (mNetConfigs[TYPE_VPN] == null) {
796 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
797 // don't need to add TYPE_VPN to mNetConfigs.
798 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
799 mNetworksDefined++; // used only in the log() statement below.
800 }
801
Wink Saville5e56bc52013-07-29 15:00:57 -0700802 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700803
Robert Greenwalt50393202011-06-21 17:26:14 -0700804 mProtectedNetworks = new ArrayList<Integer>();
805 int[] protectedNetworks = context.getResources().getIntArray(
806 com.android.internal.R.array.config_protectedNetworks);
807 for (int p : protectedNetworks) {
808 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
809 mProtectedNetworks.add(p);
810 } else {
811 if (DBG) loge("Ignoring protectedNetwork " + p);
812 }
813 }
814
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700815 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
816 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700817
Christopher Wileyd73faf02016-09-16 11:14:36 -0700818 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800819
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700820 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
821
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700822 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700823 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100824 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700825 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700826 intentFilter.addAction(Intent.ACTION_USER_ADDED);
827 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000828 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700829 mContext.registerReceiverAsUser(
830 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900831
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700832 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700833 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700834 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700835 } catch (RemoteException e) {
836 loge("Error registering observer :" + e);
837 }
838
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700839 if (DBG) {
840 mInetLog = new ArrayList();
841 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700842
Erik Klineda4bfa82015-04-30 12:58:40 +0900843 mSettingsObserver = new SettingsObserver(mContext, mHandler);
844 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800845
John Spurlockbf991a82013-06-24 14:20:23 -0400846 mDataConnectionStats = new DataConnectionStats(mContext);
847 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400848
Jason Monkdecd2952013-10-10 14:02:51 -0400849 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700850
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400851 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900852
853 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900854 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
855 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900856
857 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
858 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
859 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
860 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
861 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
862 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
863 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900864
Erik Kline065ab6e2016-10-02 18:02:14 +0900865 mAvoidBadWifiTracker = createAvoidBadWifiTracker(
866 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700868
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900869 private NetworkRequest createInternetRequestForTransport(
870 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900871 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900872 netCap.addCapability(NET_CAPABILITY_INTERNET);
873 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900874 if (transportType > -1) {
875 netCap.addTransportType(transportType);
876 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900877 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900878 }
879
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900880 // Used only for testing.
881 // TODO: Delete this and either:
882 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
883 // changing ContentResolver to make registerContentObserver non-final).
884 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
885 // by subclassing SettingsObserver.
886 @VisibleForTesting
887 void updateMobileDataAlwaysOn() {
888 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
889 }
890
Erik Klineda4bfa82015-04-30 12:58:40 +0900891 private void handleMobileDataAlwaysOn() {
892 final boolean enable = (Settings.Global.getInt(
893 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
894 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
895 if (enable == isEnabled) {
896 return; // Nothing to do.
897 }
898
899 if (enable) {
900 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900901 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900902 } else {
903 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
904 }
905 }
906
907 private void registerSettingsCallbacks() {
908 // Watch for global HTTP proxy changes.
909 mSettingsObserver.observe(
910 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
911 EVENT_APPLY_GLOBAL_HTTP_PROXY);
912
913 // Watch for whether or not to keep mobile data always on.
914 mSettingsObserver.observe(
915 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
916 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
917 }
918
Robert Greenwalt34524f02014-05-18 16:22:10 -0700919 private synchronized int nextNetworkRequestId() {
920 return mNextNetworkRequestId++;
921 }
922
Paul Jensen67b0b072015-06-10 11:22:17 -0400923 @VisibleForTesting
924 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400925 synchronized (mNetworkForNetId) {
926 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
927 int netId = mNextNetId;
928 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
929 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500930 if (!mNetIdInUse.get(netId)) {
931 mNetIdInUse.put(netId, true);
932 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400933 }
934 }
935 }
936 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700937 }
938
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600939 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800940 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600941 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
942 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800943 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600944 state = nai.getNetworkState();
945 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600947 final NetworkInfo info = new NetworkInfo(networkType, 0,
948 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800949 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
950 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600951 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
952 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800953 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600954 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600955 return state;
956 } else {
957 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800958 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400959 }
960
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800961 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
962 if (network == null) {
963 return null;
964 }
965 synchronized (mNetworkForNetId) {
966 return mNetworkForNetId.get(network.netId);
967 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600968 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800969
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900970 private Network[] getVpnUnderlyingNetworks(int uid) {
971 if (!mLockdownEnabled) {
972 int user = UserHandle.getUserId(uid);
973 synchronized (mVpns) {
974 Vpn vpn = mVpns.get(user);
975 if (vpn != null && vpn.appliesToUid(uid)) {
976 return vpn.getUnderlyingNetworks();
977 }
978 }
979 }
980 return null;
981 }
982
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400984 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800985
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900986 final Network[] networks = getVpnUnderlyingNetworks(uid);
987 if (networks != null) {
988 // getUnderlyingNetworks() returns:
989 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
990 // empty array => the VPN explicitly said "no default network".
991 // non-empty array => the VPN specified one or more default networks; we use the
992 // first one.
993 if (networks.length > 0) {
994 nai = getNetworkAgentInfoForNetwork(networks[0]);
995 } else {
996 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800997 }
998 }
999
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001000 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001001 return nai.getNetworkState();
1002 } else {
1003 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001005 }
1006
1007 /**
1008 * Check if UID should be blocked from using the network with the given LinkProperties.
1009 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001010 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1011 boolean ignoreBlocked) {
1012 // Networks aren't blocked when ignoring blocked status
1013 if (ignoreBlocked) return false;
1014 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001015 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001016
1017 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001018 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001019
Robin Lee17e61832016-05-09 13:46:28 +01001020 synchronized (mVpns) {
1021 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1022 if (vpn != null && vpn.isBlockingUid(uid)) {
1023 return true;
1024 }
1025 }
1026
Robert Greenwalt12e67352014-05-13 21:41:06 -07001027 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001028 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001029 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001030 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001031 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001032
Felipe Lemed31a97f2016-05-06 14:53:50 -07001033 boolean allowed = true;
1034 // Check Data Saver Mode first...
1035 if (networkMetered) {
1036 if ((uidRules & RULE_REJECT_METERED) != 0) {
1037 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1038 // Explicitly blacklisted.
1039 allowed = false;
1040 } else {
1041 allowed = !mRestrictBackground
1042 || (uidRules & RULE_ALLOW_METERED) != 0
1043 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1044 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1045 + " mRestrictBackground=" + mRestrictBackground
1046 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1047 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1048 + ": " + allowed);
1049 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001050 }
Felipe Leme781ba142016-05-09 16:24:48 -07001051 // ...then power restrictions.
1052 if (allowed) {
1053 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001054 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001055 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001056 }
1057 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001058 }
1059
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001060 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001061 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1062 return;
1063 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001064 boolean removed = false;
1065 boolean added = false;
1066 synchronized (mBlockedAppUids) {
1067 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1068 added = true;
1069 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1070 removed = true;
1071 }
1072 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001073 if (added) {
1074 log("Returning blocked NetworkInfo to uid=" + uid);
1075 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1076 } else if (removed) {
1077 log("Returning unblocked NetworkInfo to uid=" + uid);
1078 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1079 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001080 }
1081
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001082 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1084 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1085 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1086 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001087 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001088 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001089 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1090
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001091 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001092 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001093 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001094 if (mLockdownTracker != null) {
1095 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001096 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001097
1098 // TODO: apply metered state closer to NetworkAgentInfo
1099 final long token = Binder.clearCallingIdentity();
1100 try {
1101 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1102 } catch (RemoteException e) {
1103 } finally {
1104 Binder.restoreCallingIdentity(token);
1105 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001106 }
1107
1108 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 * Return NetworkInfo for the active (i.e., connected) network interface.
1110 * It is assumed that at most one network is active at a time. If more
1111 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001112 * @return the info for the active network, or {@code null} if none is
1113 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001115 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001117 enforceAccessPermission();
1118 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001119 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001121 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1122 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 }
1124
Paul Jensen31a94f42015-02-13 14:18:39 -05001125 @Override
1126 public Network getActiveNetwork() {
1127 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001128 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001129 }
1130
1131 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001132 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001133 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001134 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001135 }
1136
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001138 final int user = UserHandle.getUserId(uid);
1139 int vpnNetId = NETID_UNSET;
1140 synchronized (mVpns) {
1141 final Vpn vpn = mVpns.get(user);
1142 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1143 }
1144 NetworkAgentInfo nai;
1145 if (vpnNetId != NETID_UNSET) {
1146 synchronized (mNetworkForNetId) {
1147 nai = mNetworkForNetId.get(vpnNetId);
1148 }
1149 if (nai != null) return nai.network;
1150 }
1151 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001152 if (nai != null
1153 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1154 nai = null;
1155 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001156 return nai != null ? nai.network : null;
1157 }
1158
Lorenzo Colitti18660282016-07-04 12:55:44 +09001159 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001160 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1161 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001162 final int uid = Binder.getCallingUid();
1163 NetworkState state = getUnfilteredActiveNetworkState(uid);
1164 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001165 }
1166
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001168 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001169 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001172 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 }
1174
1175 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 public NetworkInfo getNetworkInfo(int networkType) {
1177 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001178 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001179 if (getVpnUnderlyingNetworks(uid) != null) {
1180 // A VPN is active, so we may need to return one of its underlying networks. This
1181 // information is not available in LegacyTypeTracker, so we have to get it from
1182 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001183 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001184 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001185 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001186 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001187 }
1188 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001189 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
1192
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001193 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001194 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001195 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001196 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001197 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001198 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001199 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001200 return state.networkInfo;
1201 } else {
1202 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001203 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001204 }
1205
1206 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 public NetworkInfo[] getAllNetworkInfo() {
1208 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001209 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001210 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1211 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 NetworkInfo info = getNetworkInfo(networkType);
1213 if (info != null) {
1214 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001217 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001220 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001221 public Network getNetworkForType(int networkType) {
1222 enforceAccessPermission();
1223 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001224 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1225 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001226 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001227 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001228 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001229 }
1230
1231 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001232 public Network[] getAllNetworks() {
1233 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001234 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001235 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001236 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001237 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001238 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001239 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001240 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001241 }
1242
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001243 @Override
1244 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1245 // The basic principle is: if an app's traffic could possibly go over a
1246 // network, without the app doing anything multinetwork-specific,
1247 // (hence, by "default"), then include that network's capabilities in
1248 // the array.
1249 //
1250 // In the normal case, app traffic only goes over the system's default
1251 // network connection, so that's the only network returned.
1252 //
1253 // With a VPN in force, some app traffic may go into the VPN, and thus
1254 // over whatever underlying networks the VPN specifies, while other app
1255 // traffic may go over the system default network (e.g.: a split-tunnel
1256 // VPN, or an app disallowed by the VPN), so the set of networks
1257 // returned includes the VPN's underlying networks and the system
1258 // default.
1259 enforceAccessPermission();
1260
1261 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1262
1263 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001264 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001265 if (nc != null) {
1266 result.put(nai.network, nc);
1267 }
1268
1269 if (!mLockdownEnabled) {
1270 synchronized (mVpns) {
1271 Vpn vpn = mVpns.get(userId);
1272 if (vpn != null) {
1273 Network[] networks = vpn.getUnderlyingNetworks();
1274 if (networks != null) {
1275 for (Network network : networks) {
1276 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001277 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001278 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001279 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001280 }
1281 }
1282 }
1283 }
1284 }
1285 }
1286
1287 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1288 out = result.values().toArray(out);
1289 return out;
1290 }
1291
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001292 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001293 public boolean isNetworkSupported(int networkType) {
1294 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001295 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001296 }
1297
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001298 /**
1299 * Return LinkProperties for the active (i.e., connected) default
1300 * network interface. It is assumed that at most one default network
1301 * is active at a time. If more than one is active, it is indeterminate
1302 * which will be returned.
1303 * @return the ip properties for the active network, or {@code null} if
1304 * none is active
1305 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001306 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001307 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001308 enforceAccessPermission();
1309 final int uid = Binder.getCallingUid();
1310 NetworkState state = getUnfilteredActiveNetworkState(uid);
1311 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001312 }
1313
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001314 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001315 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001316 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001317 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1318 if (nai != null) {
1319 synchronized (nai) {
1320 return new LinkProperties(nai.linkProperties);
1321 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001322 }
1323 return null;
1324 }
1325
Robert Greenwalt12e67352014-05-13 21:41:06 -07001326 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001327 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001328 public LinkProperties getLinkProperties(Network network) {
1329 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001330 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001331 if (nai != null) {
1332 synchronized (nai) {
1333 return new LinkProperties(nai.linkProperties);
1334 }
1335 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001336 return null;
1337 }
1338
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001339 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001340 if (nai != null) {
1341 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001342 if (nai.networkCapabilities != null) {
1343 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001344 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001345 }
1346 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001347 return null;
1348 }
1349
1350 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001351 public NetworkCapabilities getNetworkCapabilities(Network network) {
1352 enforceAccessPermission();
1353 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1354 }
1355
1356 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001357 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001358 // Require internal since we're handing out IMSI details
1359 enforceConnectivityInternalPermission();
1360
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001361 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001362 for (Network network : getAllNetworks()) {
1363 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1364 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001365 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001366 }
1367 }
1368 return result.toArray(new NetworkState[result.size()]);
1369 }
1370
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001371 @Override
1372 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1373 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001374 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001375 final long token = Binder.clearCallingIdentity();
1376 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001377 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1378 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001379 try {
1380 return mPolicyManager.getNetworkQuotaInfo(state);
1381 } catch (RemoteException e) {
1382 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001383 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001384 return null;
1385 } finally {
1386 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001387 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001388 }
1389
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001390 @Override
1391 public boolean isActiveNetworkMetered() {
1392 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001393
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001394 final NetworkInfo info = getActiveNetworkInfo();
1395 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001396 }
1397
Jeff Sharkey216c1812012-08-05 14:29:23 -07001398 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1399 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001400 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001401 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001402 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001403 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001404 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001405
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001406 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 * Ensure that a network route exists to deliver traffic to the specified
1408 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001409 * @param networkType the type of the network over which traffic to the
1410 * specified host is to be routed
1411 * @param hostAddress the IP address of the host to which the route is
1412 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 * @return {@code true} on success, {@code false} on failure
1414 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001415 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001416 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001418 if (mProtectedNetworks.contains(networkType)) {
1419 enforceConnectivityInternalPermission();
1420 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001421
Chad Brubakerc0234532014-02-14 13:24:29 -08001422 InetAddress addr;
1423 try {
1424 addr = InetAddress.getByAddress(hostAddress);
1425 } catch (UnknownHostException e) {
1426 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1427 return false;
1428 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001431 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 return false;
1433 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001434
1435 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1436 if (nai == null) {
1437 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1438 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1439 } else {
1440 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1441 }
1442 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001443 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001444
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001445 DetailedState netState;
1446 synchronized (nai) {
1447 netState = nai.networkInfo.getDetailedState();
1448 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001449
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001450 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001451 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001452 log("requestRouteToHostAddress on down network "
1453 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001454 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001455 }
1456 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001458
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001459 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001460 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001461 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001462 LinkProperties lp;
1463 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001464 synchronized (nai) {
1465 lp = nai.linkProperties;
1466 netId = nai.network.netId;
1467 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001468 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001469 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1470 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001471 } finally {
1472 Binder.restoreCallingIdentity(token);
1473 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001474 }
1475
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001476 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001477 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001478 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001479 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001480 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001481 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001482 if (bestRoute.getGateway().equals(addr)) {
1483 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001484 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001485 } else {
1486 // if we will connect to this through another route, add a direct route
1487 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001488 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001489 }
1490 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001491 if (DBG) log("Adding legacy route " + bestRoute +
1492 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001493 try {
1494 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1495 } catch (Exception e) {
1496 // never crash - catch them all
1497 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001498 return false;
1499 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001500 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001503 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1504 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001505 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001506 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001507 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001508 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001509 }
1510
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001511 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001512 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001513 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001514 if (oldRules == uidRules) return;
1515
Felipe Leme781ba142016-05-09 16:24:48 -07001516 if (uidRules == RULE_NONE) {
1517 mUidRules.delete(uid);
1518 } else {
1519 mUidRules.put(uid, uidRules);
1520 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001521 }
1522
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001523 // TODO: notify UID when it has requested targeted updates
1524 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001525
1526 @Override
1527 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001528 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001529 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001530 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001531 }
1532
1533 synchronized (mRulesLock) {
1534 mMeteredIfaces.clear();
1535 for (String iface : meteredIfaces) {
1536 mMeteredIfaces.add(iface);
1537 }
1538 }
1539 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001540
1541 @Override
1542 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1543 // caller is NPMS, since we only register with them
1544 if (LOGD_RULES) {
1545 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1546 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001547
1548 synchronized (mRulesLock) {
1549 mRestrictBackground = restrictBackground;
1550 }
1551
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001552 if (restrictBackground) {
1553 log("onRestrictBackgroundChanged(true): disabling tethering");
1554 mTethering.untetherAll();
1555 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001556 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001557
1558 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001559 public void onUidPoliciesChanged(int uid, int uidPolicies) {
1560 // caller is NPMS, since we only register with them
Felipe Leme019fcd22016-04-19 10:24:39 -07001561 if (LOGD_RULES) {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001562 log("onUidRulesChanged(uid=" + uid + ", uidPolicies=" + uidPolicies + ")");
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001563 }
1564 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001565 };
1566
Robin Lee3b3dd942015-05-12 18:14:58 +01001567 /**
1568 * Require that the caller is either in the same user or has appropriate permission to interact
1569 * across users.
1570 *
1571 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1572 */
1573 private void enforceCrossUserPermission(int userId) {
1574 if (userId == UserHandle.getCallingUserId()) {
1575 // Not a cross-user call.
1576 return;
1577 }
1578 mContext.enforceCallingOrSelfPermission(
1579 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1580 "ConnectivityService");
1581 }
1582
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001583 private void enforceInternetPermission() {
1584 mContext.enforceCallingOrSelfPermission(
1585 android.Manifest.permission.INTERNET,
1586 "ConnectivityService");
1587 }
1588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001590 mContext.enforceCallingOrSelfPermission(
1591 android.Manifest.permission.ACCESS_NETWORK_STATE,
1592 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
1594
1595 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001596 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 }
1598
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001599 private void enforceTetherAccessPermission() {
1600 mContext.enforceCallingOrSelfPermission(
1601 android.Manifest.permission.ACCESS_NETWORK_STATE,
1602 "ConnectivityService");
1603 }
1604
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001605 private void enforceConnectivityInternalPermission() {
1606 mContext.enforceCallingOrSelfPermission(
1607 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1608 "ConnectivityService");
1609 }
1610
Hugo Benichi514da602016-07-19 15:59:27 +09001611 private void enforceConnectivityRestrictedNetworksPermission() {
1612 try {
1613 mContext.enforceCallingOrSelfPermission(
1614 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1615 "ConnectivityService");
1616 return;
1617 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1618 enforceConnectivityInternalPermission();
1619 }
1620
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001621 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001622 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001623 }
1624
Lorenzo Colitti18660282016-07-04 12:55:44 +09001625 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001626 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001627 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001628 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001629 }
1630
1631 private void sendInetConditionBroadcast(NetworkInfo info) {
1632 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1633 }
1634
Wink Saville628b0852011-08-04 15:01:58 -07001635 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001636 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001637 info = new NetworkInfo(info);
1638 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001639 }
1640
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001641 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001642 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001643 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 if (info.isFailover()) {
1645 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1646 info.setFailover(false);
1647 }
1648 if (info.getReason() != null) {
1649 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1650 }
1651 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001652 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1653 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001655 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001656 return intent;
1657 }
1658
1659 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1660 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1661 }
1662
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001663 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001664 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1665 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1666 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001667 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001668 final long ident = Binder.clearCallingIdentity();
1669 try {
1670 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1671 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1672 } finally {
1673 Binder.restoreCallingIdentity(ident);
1674 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001675 }
1676
Mike Lockwood0f79b542009-08-14 14:18:49 -04001677 private void sendStickyBroadcast(Intent intent) {
1678 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001679 if (!mSystemReady) {
1680 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001681 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001682 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001683 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001684 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001685 }
1686
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001687 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001688 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001689 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001690 final NetworkInfo ni = intent.getParcelableExtra(
1691 ConnectivityManager.EXTRA_NETWORK_INFO);
1692 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1693 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1694 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001695 } else {
1696 BroadcastOptions opts = BroadcastOptions.makeBasic();
1697 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1698 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001699 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001700 final IBatteryStats bs = BatteryStatsService.getService();
1701 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001702 bs.noteConnectivityChanged(intent.getIntExtra(
1703 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1704 ni != null ? ni.getState().toString() : "?");
1705 } catch (RemoteException e) {
1706 }
1707 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001708 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001709 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001710 } finally {
1711 Binder.restoreCallingIdentity(ident);
1712 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001713 }
1714 }
1715
1716 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001717 loadGlobalProxy();
1718
Mike Lockwood0f79b542009-08-14 14:18:49 -04001719 synchronized(this) {
1720 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001721 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001722 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001723 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001724 }
1725 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001726 // load the global proxy at startup
1727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001728
Robin Lee244ce8e2016-01-05 18:03:46 +00001729 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1730 // for user to unlock device too.
1731 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001732
Erik Klineda4bfa82015-04-30 12:58:40 +09001733 // Configure whether mobile data is always on.
1734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1735
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001736 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001737
1738 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001742 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001743 *
1744 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001745 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001746 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001747 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1748 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001749
1750 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001751 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001752
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 if (networkAgent.networkCapabilities.hasTransport(
1754 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001755 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1756 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001757 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001758 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001759 } else if (networkAgent.networkCapabilities.hasTransport(
1760 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001761 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1762 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001763 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001764 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001765 } else {
1766 // do not track any other networks
1767 timeout = 0;
1768 }
1769
Robert Greenwalt7b816022014-04-18 15:25:25 -07001770 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001771 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001772 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001773 } catch (Exception e) {
1774 // You shall not crash!
1775 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001776 }
1777 }
1778 }
1779
1780 /**
1781 * Remove data activity tracking when network disconnects.
1782 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001783 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1784 final String iface = networkAgent.linkProperties.getInterfaceName();
1785 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001786
Robert Greenwalt7b816022014-04-18 15:25:25 -07001787 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1788 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001789 try {
1790 // the call fails silently if no idletimer setup for this interface
1791 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001792 } catch (Exception e) {
1793 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001794 }
1795 }
1796 }
1797
1798 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001799 * Reads the network specific MTU size from reources.
1800 * and set it on it's iface.
1801 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001802 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1803 final String iface = newLp.getInterfaceName();
1804 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001805 if (oldLp == null && mtu == 0) {
1806 // Silently ignore unset MTU value.
1807 return;
1808 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001809 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1810 if (VDBG) log("identical MTU - not setting");
1811 return;
1812 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001813 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001814 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001815 return;
1816 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001817
w1997615afd812014-08-05 15:18:11 -07001818 // Cannot set MTU without interface name
1819 if (TextUtils.isEmpty(iface)) {
1820 loge("Setting MTU size with null iface.");
1821 return;
1822 }
1823
Robert Greenwalt7b816022014-04-18 15:25:25 -07001824 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001825 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001826 mNetd.setMtu(iface, mtu);
1827 } catch (Exception e) {
1828 Slog.e(TAG, "exception in setMtu()" + e);
1829 }
1830 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001831
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001832 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001833 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1834
1835 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001836 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001837 protected int getDefaultTcpRwnd() {
1838 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1839 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001840
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001841 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1842 if (isDefaultNetwork(nai) == false) {
1843 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001844 }
1845
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001846 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1847 String[] values = null;
1848 if (tcpBufferSizes != null) {
1849 values = tcpBufferSizes.split(",");
1850 }
1851
1852 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001853 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001854 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1855 values = tcpBufferSizes.split(",");
1856 }
1857
1858 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1859
1860 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001861 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001862
1863 final String prefix = "/sys/kernel/ipv4/tcp_";
1864 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1865 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1866 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1867 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1868 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1869 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1870 mCurrentTcpBufferSizes = tcpBufferSizes;
1871 } catch (IOException e) {
1872 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001873 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001874
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001875 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001876 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001877 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1878 if (rwndValue != 0) {
1879 SystemProperties.set(sysctlKey, rwndValue.toString());
1880 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001881 }
1882
Mattias Falk8b47b362011-08-23 14:15:13 +02001883 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001884 /*
1885 * Tell the VMs to toss their DNS caches
1886 */
1887 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1888 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001889 /*
1890 * Connectivity events can happen before boot has completed ...
1891 */
1892 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001893 final long ident = Binder.clearCallingIdentity();
1894 try {
1895 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1896 } finally {
1897 Binder.restoreCallingIdentity(ident);
1898 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001899 }
1900
Robert Greenwalt562cc542014-05-15 18:07:26 -07001901 @Override
1902 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001903 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1904 NETWORK_RESTORE_DELAY_PROP_NAME);
1905 if(restoreDefaultNetworkDelayStr != null &&
1906 restoreDefaultNetworkDelayStr.length() != 0) {
1907 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001908 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001909 } catch (NumberFormatException e) {
1910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001912 // if the system property isn't set, use the value for the apn type
1913 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1914
1915 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1916 (mNetConfigs[networkType] != null)) {
1917 ret = mNetConfigs[networkType].restoreTime;
1918 }
1919 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 }
1921
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001922 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001923 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001924 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001925 }
1926 return false;
1927 }
1928
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001929 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1930 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1931 final long DIAG_TIME_MS = 5000;
1932 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1933 // Start gathering diagnostic information.
1934 netDiags.add(new NetworkDiagnostics(
1935 nai.network,
1936 new LinkProperties(nai.linkProperties), // Must be a copy.
1937 DIAG_TIME_MS));
1938 }
1939
1940 for (NetworkDiagnostics netDiag : netDiags) {
1941 pw.println();
1942 netDiag.waitForMeasurements();
1943 netDiag.dump(pw);
1944 }
1945 }
1946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001948 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1949 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001950 if (mContext.checkCallingOrSelfPermission(
1951 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001953 pw.println("Permission Denial: can't dump ConnectivityService " +
1954 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1955 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 return;
1957 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001958
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001959 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001960 dumpNetworkDiagnostics(pw);
1961 return;
1962 }
Erik Kline379747a2015-06-05 17:47:34 +09001963
Lorenzo Colittie3805462015-06-03 11:18:24 +09001964 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001965 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001966 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001967 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001968 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001969 pw.println();
1970
Paul Jensen85cf78e2015-06-25 13:25:07 -04001971 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001972 pw.print("Active default network: ");
1973 if (defaultNai == null) {
1974 pw.println("none");
1975 } else {
1976 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001978 pw.println();
1979
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001980 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001981 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001982 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1983 pw.println(nai.toString());
1984 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001985 pw.println(String.format(
1986 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1987 nai.numForegroundNetworkRequests(),
1988 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1989 nai.numBackgroundNetworkRequests(),
1990 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001991 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001992 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1993 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001994 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001995 pw.decreaseIndent();
1996 pw.println("Lingered:");
1997 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001998 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001999 pw.decreaseIndent();
2000 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002001 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002002 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002003 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002004
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002005 pw.println("Metered Interfaces:");
2006 pw.increaseIndent();
2007 for (String value : mMeteredIfaces) {
2008 pw.println(value);
2009 }
2010 pw.decreaseIndent();
2011 pw.println();
2012
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002013 pw.print("Restrict background: ");
2014 pw.println(mRestrictBackground);
2015 pw.println();
2016
Felipe Leme46c4fc32016-05-04 09:21:43 -07002017 pw.println("Status for known UIDs:");
2018 pw.increaseIndent();
2019 final int size = mUidRules.size();
2020 for (int i = 0; i < size; i++) {
2021 final int uid = mUidRules.keyAt(i);
2022 pw.print("UID=");
2023 pw.print(uid);
2024 final int uidRules = mUidRules.get(uid, RULE_NONE);
2025 pw.print(" rules=");
2026 pw.print(uidRulesToString(uidRules));
2027 pw.println();
2028 }
2029 pw.println();
2030 pw.decreaseIndent();
2031
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002032 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002033 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002034 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2035 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002036 }
2037 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002038 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002039
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002040 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002041
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002042 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002043 pw.print("mNetTransitionWakeLock: currently " +
2044 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2045 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2046 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2047 } else {
2048 pw.println(", last requested never");
2049 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002050 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002051
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002052 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002053 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002054
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002055 pw.println();
2056 mKeepaliveTracker.dump(pw);
2057
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002058 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002059 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002060
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002061 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09002062 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002063 pw.println();
2064 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002065 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002066 for(int i = 0; i < mInetLog.size(); i++) {
2067 pw.println(mInetLog.get(i));
2068 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002069 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002070 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002071
2072 if (argsContain(args, "--short") == false) {
2073 pw.println();
2074 synchronized (mValidationLogs) {
2075 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002076 for (ValidationLog p : mValidationLogs) {
2077 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002078 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002079 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002080 pw.decreaseIndent();
2081 }
2082 }
Erik Kline7523eb32015-07-09 18:24:03 +09002083
2084 pw.println();
2085 pw.println("mNetworkRequestInfoLogs (most recent first):");
2086 pw.increaseIndent();
2087 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2088 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002089
2090 pw.println();
2091 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2092 pw.increaseIndent();
2093 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2094 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
2097
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002098 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002099 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002100 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002101 if (officialNai != null && officialNai.equals(nai)) return true;
2102 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002103 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002104 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002105 " - " + nai);
2106 }
2107 return false;
2108 }
2109
Robert Greenwalt42acef32009-08-12 16:08:25 -07002110 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002111 private class NetworkStateTrackerHandler extends Handler {
2112 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002113 super(looper);
2114 }
2115
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002116 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002118 default:
2119 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002120 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 handleAsyncChannelHalfConnect(msg);
2122 break;
2123 }
2124 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2125 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2126 if (nai != null) nai.asyncChannel.disconnect();
2127 break;
2128 }
2129 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2130 handleAsyncChannelDisconnected(msg);
2131 break;
2132 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002133 }
2134 return true;
2135 }
2136
2137 private void maybeHandleNetworkAgentMessage(Message msg) {
2138 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2139 if (nai == null) {
2140 if (VDBG) {
2141 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2142 log(String.format("%s from unknown NetworkAgent", what));
2143 }
2144 return;
2145 }
2146
2147 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002148 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002149 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2150 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002151 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2152 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002153 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002154 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002155 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002156 break;
2157 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002158 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002159 if (VDBG) {
2160 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002161 "; created=" + nai.created +
2162 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002164 LinkProperties oldLp = nai.linkProperties;
2165 synchronized (nai) {
2166 nai.linkProperties = (LinkProperties)msg.obj;
2167 }
Robin Lee585e2482016-05-01 23:00:00 +01002168 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002169 break;
2170 }
2171 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002172 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 updateNetworkInfo(nai, info);
2174 break;
2175 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002176 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002177 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002178 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002179 break;
2180 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002181 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002182 try {
2183 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002184 } catch (Exception e) {
2185 // Never crash!
2186 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002187 }
2188 break;
2189 }
2190 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002191 try {
2192 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002193 } catch (Exception e) {
2194 // Never crash!
2195 loge("Exception in removeVpnUidRanges: " + e);
2196 }
2197 break;
2198 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002199 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002200 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2201 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002202 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002203 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002204 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002205 break;
2206 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002207 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002208 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2209 break;
2210 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002211 }
2212 }
2213
2214 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2215 switch (msg.what) {
2216 default:
2217 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002218 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002219 final NetworkAgentInfo nai;
2220 synchronized (mNetworkForNetId) {
2221 nai = mNetworkForNetId.get(msg.arg2);
2222 }
2223 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002224 final boolean valid =
2225 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002226 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002227 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2228 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002229 if (valid != nai.lastValidated) {
2230 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002231 nai.lastValidated = valid;
2232 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002233 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002234 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2235 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002236 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002237 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002238 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002239 Bundle redirectUrlBundle = new Bundle();
2240 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002241 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002242 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002243 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002244 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002245 if (wasValidated && !nai.lastValidated) {
2246 handleNetworkUnvalidated(nai);
2247 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002248 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002249 break;
2250 }
Paul Jensen869868be2014-05-15 10:33:05 -04002251 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002252 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002253 final boolean visible = (msg.arg1 != 0);
2254 final NetworkAgentInfo nai;
2255 synchronized (mNetworkForNetId) {
2256 nai = mNetworkForNetId.get(netId);
2257 }
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 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002287 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002288 return true;
2289 }
2290
Calvin Onbe96da12016-10-11 15:10:46 -07002291 private int getCaptivePortalMode() {
2292 return Settings.Global.getInt(mContext.getContentResolver(),
2293 Settings.Global.CAPTIVE_PORTAL_MODE,
2294 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2295 }
2296
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002297 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2298 switch (msg.what) {
2299 default:
2300 return false;
2301 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2302 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2303 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2304 handleLingerComplete(nai);
2305 }
2306 break;
2307 }
2308 }
2309 return true;
2310 }
2311
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002312 @Override
2313 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002314 if (!maybeHandleAsyncChannelMessage(msg) &&
2315 !maybeHandleNetworkMonitorMessage(msg) &&
2316 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002317 maybeHandleNetworkAgentMessage(msg);
2318 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002319 }
2320 }
2321
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002322 private void updateLingerState(NetworkAgentInfo nai, long now) {
2323 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2324 // 2. If the network was lingering and there are now requests, unlinger it.
2325 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2326 // one lingered request, start lingering.
2327 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002328 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002329 if (DBG) log("Unlingering " + nai.name());
2330 nai.unlinger();
2331 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002332 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002333 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002334 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002335 nai.linger();
2336 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2337 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2338 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002339 }
2340
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341 private void handleAsyncChannelHalfConnect(Message msg) {
2342 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002343 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002344 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2345 if (VDBG) log("NetworkFactory connected");
2346 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002347 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002348 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002349 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002350 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002351 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002352 }
2353 } else {
2354 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002355 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002356 }
2357 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2358 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2359 if (VDBG) log("NetworkAgent connected");
2360 // A network agent has requested a connection. Establish the connection.
2361 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2362 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2363 } else {
2364 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002365 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002366 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002367 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002368 synchronized (mNetworkForNetId) {
2369 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002370 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002371 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002372 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002373 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002374 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002375 }
2376 }
2377 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002378
Robert Greenwalt7b816022014-04-18 15:25:25 -07002379 private void handleAsyncChannelDisconnected(Message msg) {
2380 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2381 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002383 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002384 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002385 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002386 // TODO - if we move the logic to the network agent (have them disconnect
2387 // because they lost all their requests or because their score isn't good)
2388 // then they would disconnect organically, report their new state and then
2389 // disconnect the channel.
2390 if (nai.networkInfo.isConnected()) {
2391 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2392 null, null);
2393 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002394 final boolean wasDefault = isDefaultNetwork(nai);
2395 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002396 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002397 // Log default network disconnection before required book-keeping.
2398 // Let rematchAllNetworksAndRequests() below record a new default network event
2399 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2400 // whose timestamps tell how long it takes to recover a default network.
2401 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002402 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002403 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002404 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2405 // by other networks that are already connected. Perhaps that can be done by
2406 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2407 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002408 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002409 mKeepaliveTracker.handleStopAllKeepalives(nai,
2410 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002411 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002412 mNetworkAgentInfos.remove(msg.replyTo);
2413 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002414 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002415 // Remove the NetworkAgent, but don't mark the netId as
2416 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002417 mNetworkForNetId.remove(nai.network.netId);
2418 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002419 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002420 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2421 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002422 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2423 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2424 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002425 sendUpdatedScoreToFactories(request, 0);
2426 }
2427 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002428 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002429 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002430 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002431 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002432 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002433 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002434 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002435 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002436 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002437 if (nai.created) {
2438 // Tell netd to clean up the configuration for this network
2439 // (routing rules, DNS, etc).
2440 // This may be slow as it requires a lot of netd shelling out to ip and
2441 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2442 // after we've rematched networks with requests which should make a potential
2443 // fallback network the default or requested a new network from the
2444 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2445 // long time.
2446 try {
2447 mNetd.removeNetwork(nai.network.netId);
2448 } catch (Exception e) {
2449 loge("Exception removing network: " + e);
2450 }
2451 }
2452 synchronized (mNetworkForNetId) {
2453 mNetIdInUse.delete(nai.network.netId);
2454 }
2455 } else {
2456 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2457 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002458 }
2459 }
2460
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002461 // If this method proves to be too slow then we can maintain a separate
2462 // pendingIntent => NetworkRequestInfo map.
2463 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2464 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2465 Intent intent = pendingIntent.getIntent();
2466 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2467 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2468 if (existingPendingIntent != null &&
2469 existingPendingIntent.getIntent().filterEquals(intent)) {
2470 return entry.getValue();
2471 }
2472 }
2473 return null;
2474 }
2475
2476 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2477 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2478
2479 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2480 if (existingRequest != null) { // remove the existing request.
2481 if (DBG) log("Replacing " + existingRequest.request + " with "
2482 + nri.request + " because their intents matched.");
2483 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2484 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002485 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002486 }
2487
Erik Klineda4bfa82015-04-30 12:58:40 +09002488 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002489 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002490 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002491 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002492 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002493 if (nri.request.networkCapabilities.hasSignalStrength() &&
2494 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2495 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002496 }
2497 }
2498 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002499 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002500 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002501 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002502 }
2503 }
2504
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002505 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2506 int callingUid) {
2507 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2508 if (nri != null) {
2509 handleReleaseNetworkRequest(nri.request, callingUid);
2510 }
2511 }
2512
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002513 // Determines whether the network is the best (or could become the best, if it validated), for
2514 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2515 // on the value of reason:
2516 //
2517 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2518 // then it should be torn down.
2519 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2520 // then it should be lingered.
2521 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2522 final int numRequests;
2523 switch (reason) {
2524 case TEARDOWN:
2525 numRequests = nai.numRequestNetworkRequests();
2526 break;
2527 case LINGER:
2528 numRequests = nai.numForegroundNetworkRequests();
2529 break;
2530 default:
2531 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2532 return true;
2533 }
2534
2535 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002536 return false;
2537 }
Paul Jensene0988542015-06-25 15:30:08 -04002538 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002539 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2540 // Background requests don't affect lingering.
2541 continue;
2542 }
2543
Paul Jensene0988542015-06-25 15:30:08 -04002544 // If this Network is already the highest scoring Network for a request, or if
2545 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002546 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002547 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002548 // Note that this catches two important cases:
2549 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2550 // is currently satisfying the request. This is desirable when
2551 // cellular ends up validating but WiFi does not.
2552 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002553 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002554 // WiFi ends up validating and out scoring cellular.
2555 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2556 nai.getCurrentScoreAsValidated())) {
2557 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002558 }
2559 }
Paul Jensene0988542015-06-25 15:30:08 -04002560 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002561 }
2562
Erik Klineacdd6392016-07-07 16:50:58 +09002563 private NetworkRequestInfo getNriForAppRequest(
2564 NetworkRequest request, int callingUid, String requestedOperation) {
2565 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2566
Robert Greenwalt9258c642014-03-26 16:47:06 -07002567 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002568 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002569 log(String.format("UID %d attempted to %s for unowned request %s",
2570 callingUid, requestedOperation, nri));
2571 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002572 }
Erik Klineacdd6392016-07-07 16:50:58 +09002573 }
2574
2575 return nri;
2576 }
2577
2578 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2579 String description, int callbackType) {
2580 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2581 if (nri == null) return;
2582
2583 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2584 // The network that is satisfying this request may have changed since
2585 // the application requested the update.
2586 //
2587 // - If the request is no longer satisfied, don't send any updates.
2588 // - If the request is satisfied by a different network, it is the
2589 // caller's responsibility to check that the Network object in the
2590 // callback matches the network that was returned in the last
2591 // onAvailable() callback for this request.
2592 if (nai == null) return;
2593 callCallbackForRequest(nri, nai, callbackType, 0);
2594 }
2595
2596 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2597 handleRequestCallbackUpdate(request, callingUid,
2598 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2599 }
2600
2601 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2602 handleRequestCallbackUpdate(request, callingUid,
2603 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2604 }
2605
Erik Kline57faba92015-11-25 12:49:38 +09002606 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2607 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2608 nri.request.requestId) == null) {
2609 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2610 }
2611 }
2612
Erik Klineacdd6392016-07-07 16:50:58 +09002613 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2614 final NetworkRequestInfo nri = getNriForAppRequest(
2615 request, callingUid, "release NetworkRequest");
Erik Kline57faba92015-11-25 12:49:38 +09002616 if (nri != null) {
2617 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2618 }
2619 }
Erik Klineacdd6392016-07-07 16:50:58 +09002620
Erik Kline57faba92015-11-25 12:49:38 +09002621 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2622 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2623 if (VDBG || (DBG && nri.request.isRequest())) {
2624 log("releasing " + nri.request + " (" + logCallbackType + ")");
2625 }
Erik Klineacdd6392016-07-07 16:50:58 +09002626 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002627 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002628 synchronized (mUidToNetworkRequestCount) {
2629 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2630 if (requests < 1) {
2631 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2632 nri.mUid);
2633 } else if (requests == 1) {
2634 mUidToNetworkRequestCount.removeAt(
2635 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2636 } else {
2637 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2638 }
2639 }
2640 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2641 if (nri.request.isRequest()) {
2642 boolean wasKept = false;
2643 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2644 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002645 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002646 nai.removeRequest(nri.request.requestId);
2647 if (VDBG) {
2648 log(" Removing from current network " + nai.name() +
2649 ", leaving " + nai.numNetworkRequests() + " requests.");
2650 }
2651 // If there are still lingered requests on this network, don't tear it down,
2652 // but resume lingering instead.
2653 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002654 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002655 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2656 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002657 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002658 wasKept = true;
2659 }
2660 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002661 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2662 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002663 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002664 }
Erik Klineacdd6392016-07-07 16:50:58 +09002665 }
2666
2667 // TODO: remove this code once we know that the Slog.wtf is never hit.
2668 //
2669 // Find all networks that are satisfying this request and remove the request
2670 // from their request lists.
2671 // TODO - it's my understanding that for a request there is only a single
2672 // network satisfying it, so this loop is wasteful
2673 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2674 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2675 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2676 otherNai.name() + ", but mNetworkAgentInfos says " +
2677 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002678 }
2679 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002680
Erik Klineacdd6392016-07-07 16:50:58 +09002681 // Maintain the illusion. When this request arrived, we might have pretended
2682 // that a network connected to serve it, even though the network was already
2683 // connected. Now that this request has gone away, we might have to pretend
2684 // that the network disconnected. LegacyTypeTracker will generate that
2685 // phantom disconnect for this type.
2686 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2687 boolean doRemove = true;
2688 if (wasKept) {
2689 // check if any of the remaining requests for this network are for the
2690 // same legacy type - if so, don't remove the nai
2691 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2692 NetworkRequest otherRequest = nai.requestAt(i);
2693 if (otherRequest.legacyType == nri.request.legacyType &&
2694 otherRequest.isRequest()) {
2695 if (DBG) log(" still have other legacy request - leaving");
2696 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002697 }
2698 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002699 }
2700
Erik Klineacdd6392016-07-07 16:50:58 +09002701 if (doRemove) {
2702 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002703 }
2704 }
Erik Klineacdd6392016-07-07 16:50:58 +09002705
2706 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2707 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2708 nri.request);
2709 }
2710 } else {
2711 // listens don't have a singular affectedNetwork. Check all networks to see
2712 // if this listen request applies and remove it.
2713 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2714 nai.removeRequest(nri.request.requestId);
2715 if (nri.request.networkCapabilities.hasSignalStrength() &&
2716 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2717 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2718 }
2719 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002720 }
Erik Kline57faba92015-11-25 12:49:38 +09002721 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002722 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002723
Lorenzo Colitti18660282016-07-04 12:55:44 +09002724 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002725 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2726 enforceConnectivityInternalPermission();
2727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2728 accept ? 1 : 0, always ? 1: 0, network));
2729 }
2730
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002731 @Override
2732 public void setAvoidUnvalidated(Network network) {
2733 enforceConnectivityInternalPermission();
2734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2735 }
2736
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002737 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2738 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2739 " accept=" + accept + " always=" + always);
2740
2741 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2742 if (nai == null) {
2743 // Nothing to do.
2744 return;
2745 }
2746
2747 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002748 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002749 return;
2750 }
2751
2752 if (!nai.networkMisc.explicitlySelected) {
2753 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2754 }
2755
2756 if (accept != nai.networkMisc.acceptUnvalidated) {
2757 int oldScore = nai.getCurrentScore();
2758 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002759 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002760 sendUpdatedScoreToFactories(nai);
2761 }
2762
2763 if (always) {
2764 nai.asyncChannel.sendMessage(
2765 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2766 }
2767
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002768 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002769 // Tell the NetworkAgent to not automatically reconnect to the network.
2770 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2771 // Teardown the nework.
2772 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002773 }
2774
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002775 }
2776
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002777 private void handleSetAvoidUnvalidated(Network network) {
2778 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2779 if (nai == null || nai.lastValidated) {
2780 // Nothing to do. The network either disconnected or revalidated.
2781 return;
2782 }
2783 if (!nai.avoidUnvalidated) {
2784 int oldScore = nai.getCurrentScore();
2785 nai.avoidUnvalidated = true;
2786 rematchAllNetworksAndRequests(nai, oldScore);
2787 sendUpdatedScoreToFactories(nai);
2788 }
2789 }
2790
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002791 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002792 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002793 mHandler.sendMessageDelayed(
2794 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2795 PROMPT_UNVALIDATED_DELAY_MS);
2796 }
2797
Hugo Benichic8e9e122016-09-14 23:23:08 +00002798 public boolean avoidBadWifi() {
Erik Kline065ab6e2016-10-02 18:02:14 +09002799 return mAvoidBadWifiTracker.currentValue();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002800 }
2801
Erik Kline065ab6e2016-10-02 18:02:14 +09002802 private void rematchForAvoidBadWifiUpdate() {
2803 rematchAllNetworksAndRequests(null, 0);
2804 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2805 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2806 sendUpdatedScoreToFactories(nai);
2807 }
2808 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002809 }
2810
Erik Kline065ab6e2016-10-02 18:02:14 +09002811 // TODO: Evaluate whether this is of interest to other consumers of
2812 // AvoidBadWifiTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002813 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Erik Kline065ab6e2016-10-02 18:02:14 +09002814 final boolean configRestrict = mAvoidBadWifiTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002815 if (!configRestrict) {
2816 pw.println("Bad Wi-Fi avoidance: unrestricted");
2817 return;
2818 }
2819
2820 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2821 pw.increaseIndent();
2822 pw.println("Config restrict: " + configRestrict);
2823
Erik Kline065ab6e2016-10-02 18:02:14 +09002824 final String value = mAvoidBadWifiTracker.getSettingsValue();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002825 String description;
2826 // Can't use a switch statement because strings are legal case labels, but null is not.
2827 if ("0".equals(value)) {
2828 description = "get stuck";
2829 } else if (value == null) {
2830 description = "prompt";
2831 } else if ("1".equals(value)) {
2832 description = "avoid";
2833 } else {
2834 description = value + " (?)";
2835 }
2836 pw.println("User setting: " + description);
2837 pw.println("Network overrides:");
2838 pw.increaseIndent();
2839 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2840 if (nai.avoidUnvalidated) {
2841 pw.println(nai.name());
2842 }
2843 }
2844 pw.decreaseIndent();
2845 pw.decreaseIndent();
2846 }
2847
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002848 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2849 final String action;
2850 switch (type) {
2851 case NO_INTERNET:
2852 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2853 break;
2854 case LOST_INTERNET:
2855 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2856 break;
2857 default:
2858 Slog.wtf(TAG, "Unknown notification type " + type);
2859 return;
2860 }
2861
2862 Intent intent = new Intent(action);
2863 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2864 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2865 intent.setClassName("com.android.settings",
2866 "com.android.settings.wifi.WifiNoInternetDialog");
2867
2868 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2869 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2870 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2871 }
2872
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002873 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002874 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002875 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2876
2877 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2878 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002879 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002880 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002881 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2882 return;
2883 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002884 showValidationNotification(nai, NotificationType.NO_INTERNET);
2885 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002886
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002887 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2888 NetworkCapabilities nc = nai.networkCapabilities;
2889 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002890
Erik Kline065ab6e2016-10-02 18:02:14 +09002891 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
2892 mAvoidBadWifiTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002893 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2894 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002895 }
2896
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002897 private class InternalHandler extends Handler {
2898 public InternalHandler(Looper looper) {
2899 super(looper);
2900 }
2901
2902 @Override
2903 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002904 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002905 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002906 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002907 String causedBy = null;
2908 synchronized (ConnectivityService.this) {
2909 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2910 mNetTransitionWakeLock.isHeld()) {
2911 mNetTransitionWakeLock.release();
2912 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002913 } else {
2914 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002915 }
2916 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002917 if (VDBG) {
2918 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2919 log("Failed to find a new network - expiring NetTransition Wakelock");
2920 } else {
2921 log("NetTransition Wakelock (" +
2922 (causedBy == null ? "unknown" : causedBy) +
2923 " cleared because we found a replacement network");
2924 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002925 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002926 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002927 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002928 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002929 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002930 break;
2931 }
Jason Monkdecd2952013-10-10 14:02:51 -04002932 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002933 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002934 break;
2935 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002936 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002937 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2938 break;
2939 }
2940 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2941 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002942 break;
2943 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002944 case EVENT_REGISTER_NETWORK_AGENT: {
2945 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2946 break;
2947 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002948 case EVENT_REGISTER_NETWORK_REQUEST:
2949 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002950 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002951 break;
2952 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002953 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2954 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002955 handleRegisterNetworkRequestWithIntent(msg);
2956 break;
2957 }
Erik Kline57faba92015-11-25 12:49:38 +09002958 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2959 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2960 handleTimedOutNetworkRequest(nri);
2961 break;
2962 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002963 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2964 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2965 break;
2966 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002967 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002968 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002969 break;
2970 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002971 case EVENT_SET_ACCEPT_UNVALIDATED: {
2972 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2973 break;
2974 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002975 case EVENT_SET_AVOID_UNVALIDATED: {
2976 handleSetAvoidUnvalidated((Network) msg.obj);
2977 break;
2978 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002979 case EVENT_PROMPT_UNVALIDATED: {
2980 handlePromptUnvalidated((Network) msg.obj);
2981 break;
2982 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002983 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2984 handleMobileDataAlwaysOn();
2985 break;
2986 }
Erik Klineacdd6392016-07-07 16:50:58 +09002987 case EVENT_REQUEST_LINKPROPERTIES:
2988 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2989 break;
2990 case EVENT_REQUEST_NETCAPABILITIES:
2991 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2992 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002993 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2994 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2995 mKeepaliveTracker.handleStartKeepalive(msg);
2996 break;
2997 }
2998 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2999 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
3000 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
3001 int slot = msg.arg1;
3002 int reason = msg.arg2;
3003 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
3004 break;
3005 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003006 case EVENT_SYSTEM_READY: {
3007 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3008 nai.networkMonitor.systemReady = true;
3009 }
3010 break;
3011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 }
3013 }
3014 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003015
3016 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003017 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003018 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003019 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003020 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003021 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003022 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003023 } else {
3024 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3025 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003026 }
3027
3028 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003029 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003030 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003031 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003032
3033 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003034 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003035 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003036 } else {
3037 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3038 }
3039 }
3040
3041 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003042 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003043 public int getLastTetherError(String iface) {
3044 enforceTetherAccessPermission();
3045
3046 if (isTetheringSupported()) {
3047 return mTethering.getLastTetherError(iface);
3048 } else {
3049 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3050 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003051 }
3052
3053 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003054 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003055 public String[] getTetherableUsbRegexs() {
3056 enforceTetherAccessPermission();
3057 if (isTetheringSupported()) {
3058 return mTethering.getTetherableUsbRegexs();
3059 } else {
3060 return new String[0];
3061 }
3062 }
3063
Lorenzo Colitti18660282016-07-04 12:55:44 +09003064 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003065 public String[] getTetherableWifiRegexs() {
3066 enforceTetherAccessPermission();
3067 if (isTetheringSupported()) {
3068 return mTethering.getTetherableWifiRegexs();
3069 } else {
3070 return new String[0];
3071 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003072 }
3073
Lorenzo Colitti18660282016-07-04 12:55:44 +09003074 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003075 public String[] getTetherableBluetoothRegexs() {
3076 enforceTetherAccessPermission();
3077 if (isTetheringSupported()) {
3078 return mTethering.getTetherableBluetoothRegexs();
3079 } else {
3080 return new String[0];
3081 }
3082 }
3083
Lorenzo Colitti18660282016-07-04 12:55:44 +09003084 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003085 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003086 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003087 if (isTetheringSupported()) {
3088 return mTethering.setUsbTethering(enable);
3089 } else {
3090 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3091 }
3092 }
3093
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003094 // TODO - move iface listing, queries, etc to new module
3095 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003096 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003097 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003098 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003099 return mTethering.getTetherableIfaces();
3100 }
3101
Lorenzo Colitti18660282016-07-04 12:55:44 +09003102 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003103 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003104 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003105 return mTethering.getTetheredIfaces();
3106 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003107
Lorenzo Colitti18660282016-07-04 12:55:44 +09003108 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003109 public String[] getTetheringErroredIfaces() {
3110 enforceTetherAccessPermission();
3111 return mTethering.getErroredIfaces();
3112 }
3113
Lorenzo Colitti18660282016-07-04 12:55:44 +09003114 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003115 public String[] getTetheredDhcpRanges() {
3116 enforceConnectivityInternalPermission();
3117 return mTethering.getTetheredDhcpRanges();
3118 }
3119
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003120 // if ro.tether.denied = true we default to no tethering
3121 // gservices could set the secure setting to 1 though to enable it on a build where it
3122 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003123 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003124 public boolean isTetheringSupported() {
3125 enforceTetherAccessPermission();
3126 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003127 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003128 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3129 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003130 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
3131 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003132 mTethering.getTetherableWifiRegexs().length != 0 ||
3133 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3134 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003135 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003136
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003137 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003138 public void startTethering(int type, ResultReceiver receiver,
3139 boolean showProvisioningUi) {
3140 ConnectivityManager.enforceTetherChangePermission(mContext);
3141 if (!isTetheringSupported()) {
3142 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3143 return;
3144 }
3145 mTethering.startTethering(type, receiver, showProvisioningUi);
3146 }
3147
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003148 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003149 public void stopTethering(int type) {
3150 ConnectivityManager.enforceTetherChangePermission(mContext);
3151 mTethering.stopTethering(type);
3152 }
3153
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003154 // Called when we lose the default network and have no replacement yet.
3155 // This will automatically be cleared after X seconds or a new default network
3156 // becomes CONNECTED, whichever happens first. The timer is started by the
3157 // first caller and not restarted by subsequent callers.
3158 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003159 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003160 synchronized (this) {
3161 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003162 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003163 mNetTransitionWakeLock.acquire();
3164 mNetTransitionWakeLockCausedBy = forWhom;
3165 }
3166 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003167 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003168 mNetTransitionWakeLockTimeout);
3169 return;
3170 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003171
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003172 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003173 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003174 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003175 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003176 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003177 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003178 }
3179
Lorenzo Colitti18660282016-07-04 12:55:44 +09003180 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003181 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003182 enforceAccessPermission();
3183 enforceInternetPermission();
3184
Paul Jensenbfd17b72015-04-07 12:43:13 -04003185 NetworkAgentInfo nai;
3186 if (network == null) {
3187 nai = getDefaultNetwork();
3188 } else {
3189 nai = getNetworkAgentInfoForNetwork(network);
3190 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003191 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3192 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3193 return;
3194 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003195 // Revalidate if the app report does not match our current validated state.
3196 if (hasConnectivity == nai.lastValidated) return;
3197 final int uid = Binder.getCallingUid();
3198 if (DBG) {
3199 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3200 ") by " + uid);
3201 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003202 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003203 // Validating a network that has not yet connected could result in a call to
3204 // rematchNetworkAndRequests() which is not meant to work on such networks.
3205 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003206
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003207 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003208
3209 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3210 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003211 }
3212
Paul Jensencee9b512015-05-06 07:32:40 -04003213 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003214 // this information is already available as a world read/writable jvm property
3215 // so this API change wouldn't have a benifit. It also breaks the passing
3216 // of proxy info to all the JVMs.
3217 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003218 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003219 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003220 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3221 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003222 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003223 }
3224
Lorenzo Colitti18660282016-07-04 12:55:44 +09003225 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003226 public ProxyInfo getProxyForNetwork(Network network) {
3227 if (network == null) return getDefaultProxy();
3228 final ProxyInfo globalProxy = getGlobalProxy();
3229 if (globalProxy != null) return globalProxy;
3230 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3231 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3232 // caller may not have.
3233 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3234 if (nai == null) return null;
3235 synchronized (nai) {
3236 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3237 if (proxyInfo == null) return null;
3238 return new ProxyInfo(proxyInfo);
3239 }
3240 }
3241
Paul Jensene0bef712014-12-10 15:12:18 -05003242 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3243 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3244 // proxy is null then there is no proxy in place).
3245 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3246 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3247 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3248 proxy = null;
3249 }
3250 return proxy;
3251 }
3252
3253 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3254 // better for determining if a new proxy broadcast is necessary:
3255 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3256 // avoid unnecessary broadcasts.
3257 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3258 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3259 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3260 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3261 // all set.
3262 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3263 a = canonicalizeProxyInfo(a);
3264 b = canonicalizeProxyInfo(b);
3265 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3266 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3267 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3268 }
3269
Jason Monk207900c2014-04-25 15:00:09 -04003270 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003271 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003272
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003273 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003274 if (proxyProperties == mGlobalProxy) return;
3275 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3276 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3277
3278 String host = "";
3279 int port = 0;
3280 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003281 String pacFileUrl = "";
3282 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003283 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003284 if (!proxyProperties.isValid()) {
3285 if (DBG)
3286 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3287 return;
3288 }
Jason Monk207900c2014-04-25 15:00:09 -04003289 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003290 host = mGlobalProxy.getHost();
3291 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003292 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003293 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003294 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003295 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003296 } else {
3297 mGlobalProxy = null;
3298 }
3299 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003300 final long token = Binder.clearCallingIdentity();
3301 try {
3302 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3303 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3304 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3305 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003306 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003307 } finally {
3308 Binder.restoreCallingIdentity(token);
3309 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003310
Jason Monkcf0f97a2014-10-02 15:39:38 -04003311 if (mGlobalProxy == null) {
3312 proxyProperties = mDefaultProxy;
3313 }
3314 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003315 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003316 }
3317
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003318 private void loadGlobalProxy() {
3319 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003320 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3321 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3322 String exclList = Settings.Global.getString(res,
3323 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003324 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3325 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003326 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003327 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003328 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003329 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003330 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003331 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003332 if (!proxyProperties.isValid()) {
3333 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3334 return;
3335 }
3336
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003337 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003338 mGlobalProxy = proxyProperties;
3339 }
3340 }
3341 }
3342
Jason Monk207900c2014-04-25 15:00:09 -04003343 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003344 // this information is already available as a world read/writable jvm property
3345 // so this API change wouldn't have a benifit. It also breaks the passing
3346 // of proxy info to all the JVMs.
3347 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003348 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003349 return mGlobalProxy;
3350 }
3351 }
3352
Jason Monk207900c2014-04-25 15:00:09 -04003353 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003354 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003355 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003356 proxy = null;
3357 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003358 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003359 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003360 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003361 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003362 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3363 return;
3364 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003365
3366 // This call could be coming from the PacManager, containing the port of the local
3367 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3368 // global (to get the correct local port), and send a broadcast.
3369 // TODO: Switch PacManager to have its own message to send back rather than
3370 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003371 if ((mGlobalProxy != null) && (proxy != null)
3372 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003373 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3374 mGlobalProxy = proxy;
3375 sendProxyBroadcast(mGlobalProxy);
3376 return;
3377 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003378 mDefaultProxy = proxy;
3379
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003380 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003381 if (!mDefaultProxyDisabled) {
3382 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003383 }
3384 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003385 }
3386
Paul Jensene0bef712014-12-10 15:12:18 -05003387 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3388 // This method gets called when any network changes proxy, but the broadcast only ever contains
3389 // the default proxy (even if it hasn't changed).
3390 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3391 // world where an app might be bound to a non-default network.
3392 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3393 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3394 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3395
3396 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3397 sendProxyBroadcast(getDefaultProxy());
3398 }
3399 }
3400
Robert Greenwalt434203a2010-10-11 16:00:27 -07003401 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003402 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3403 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003404 if (!TextUtils.isEmpty(proxy)) {
3405 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003406 if (data.length == 0) {
3407 return;
3408 }
3409
Robert Greenwalt434203a2010-10-11 16:00:27 -07003410 String proxyHost = data[0];
3411 int proxyPort = 8080;
3412 if (data.length > 1) {
3413 try {
3414 proxyPort = Integer.parseInt(data[1]);
3415 } catch (NumberFormatException e) {
3416 return;
3417 }
3418 }
Jason Monk207900c2014-04-25 15:00:09 -04003419 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003420 setGlobalProxy(p);
3421 }
3422 }
3423
Jason Monk207900c2014-04-25 15:00:09 -04003424 private void sendProxyBroadcast(ProxyInfo proxy) {
3425 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003426 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003427 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003428 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003429 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3430 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003431 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003432 final long ident = Binder.clearCallingIdentity();
3433 try {
3434 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3435 } finally {
3436 Binder.restoreCallingIdentity(ident);
3437 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003438 }
3439
3440 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003441 final private HashMap<Uri, Integer> mUriEventMap;
3442 final private Context mContext;
3443 final private Handler mHandler;
3444
3445 SettingsObserver(Context context, Handler handler) {
3446 super(null);
3447 mUriEventMap = new HashMap<Uri, Integer>();
3448 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003449 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003450 }
3451
Erik Klineda4bfa82015-04-30 12:58:40 +09003452 void observe(Uri uri, int what) {
3453 mUriEventMap.put(uri, what);
3454 final ContentResolver resolver = mContext.getContentResolver();
3455 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003456 }
3457
3458 @Override
3459 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003460 Slog.wtf(TAG, "Should never be reached.");
3461 }
3462
3463 @Override
3464 public void onChange(boolean selfChange, Uri uri) {
3465 final Integer what = mUriEventMap.get(uri);
3466 if (what != null) {
3467 mHandler.obtainMessage(what.intValue()).sendToTarget();
3468 } else {
3469 loge("No matching event to send for URI=" + uri);
3470 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003471 }
3472 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003473
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003474 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003475 Slog.d(TAG, s);
3476 }
3477
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003478 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003479 Slog.e(TAG, s);
3480 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003481
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003482 private static <T> T checkNotNull(T value, String message) {
3483 if (value == null) {
3484 throw new NullPointerException(message);
3485 }
3486 return value;
3487 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003488
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003489 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003490 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003491 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3492 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3493 *
3494 * @param oldPackage Package name of the application which currently controls VPN, which will
3495 * be replaced. If there is no such application, this should should either be
3496 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3497 * @param newPackage Package name of the application which should gain control of VPN, or
3498 * {@code null} to disable.
3499 * @param userId User for whom to prepare the new VPN.
3500 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003501 * @hide
3502 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003503 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003504 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3505 int userId) {
3506 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003507 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003508
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003509 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003510 Vpn vpn = mVpns.get(userId);
3511 if (vpn != null) {
3512 return vpn.prepare(oldPackage, newPackage);
3513 } else {
3514 return false;
3515 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003516 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003517 }
3518
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003519 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003520 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3521 * This method is used by system-privileged apps.
3522 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3523 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3524 *
3525 * @param packageName The package for which authorization state should change.
3526 * @param userId User for whom {@code packageName} is installed.
3527 * @param authorized {@code true} if this app should be able to start a VPN connection without
3528 * explicit user approval, {@code false} if not.
3529 *
Jeff Davidson05542602014-08-11 14:07:27 -07003530 * @hide
3531 */
3532 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003533 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3534 enforceCrossUserPermission(userId);
3535
Jeff Davidson05542602014-08-11 14:07:27 -07003536 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003537 Vpn vpn = mVpns.get(userId);
3538 if (vpn != null) {
3539 vpn.setPackageAuthorization(packageName, authorized);
3540 }
Jeff Davidson05542602014-08-11 14:07:27 -07003541 }
3542 }
3543
3544 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003545 * Configure a TUN interface and return its file descriptor. Parameters
3546 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003547 * and not available in ConnectivityManager. Permissions are checked in
3548 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003549 * @hide
3550 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003551 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003552 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003553 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003554 int user = UserHandle.getUserId(Binder.getCallingUid());
3555 synchronized(mVpns) {
3556 return mVpns.get(user).establish(config);
3557 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003558 }
3559
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003560 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003561 * Start legacy VPN, controlling native daemons as needed. Creates a
3562 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003563 */
3564 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003565 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003566 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003567 final LinkProperties egress = getActiveLinkProperties();
3568 if (egress == null) {
3569 throw new IllegalStateException("Missing active network connection");
3570 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003571 int user = UserHandle.getUserId(Binder.getCallingUid());
3572 synchronized(mVpns) {
3573 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3574 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003575 }
3576
3577 /**
3578 * Return the information of the ongoing legacy VPN. This method is used
3579 * by VpnSettings and not available in ConnectivityManager. Permissions
3580 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003581 */
3582 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003583 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3584 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003585
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003586 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003587 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003588 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003589 }
3590
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003591 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003592 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3593 * and not available in ConnectivityManager.
3594 */
3595 @Override
3596 public VpnInfo[] getAllVpnInfo() {
3597 enforceConnectivityInternalPermission();
3598 if (mLockdownEnabled) {
3599 return new VpnInfo[0];
3600 }
3601
3602 synchronized(mVpns) {
3603 List<VpnInfo> infoList = new ArrayList<>();
3604 for (int i = 0; i < mVpns.size(); i++) {
3605 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3606 if (info != null) {
3607 infoList.add(info);
3608 }
3609 }
3610 return infoList.toArray(new VpnInfo[infoList.size()]);
3611 }
3612 }
3613
3614 /**
3615 * @return VPN information for accounting, or null if we can't retrieve all required
3616 * information, e.g primary underlying iface.
3617 */
3618 @Nullable
3619 private VpnInfo createVpnInfo(Vpn vpn) {
3620 VpnInfo info = vpn.getVpnInfo();
3621 if (info == null) {
3622 return null;
3623 }
3624 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3625 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3626 // the underlyingNetworks list.
3627 if (underlyingNetworks == null) {
3628 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3629 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3630 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3631 }
3632 } else if (underlyingNetworks.length > 0) {
3633 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3634 if (linkProperties != null) {
3635 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3636 }
3637 }
3638 return info.primaryUnderlyingIface == null ? null : info;
3639 }
3640
3641 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003642 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3643 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003644 * Permissions are checked in Vpn class.
3645 * @hide
3646 */
3647 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003648 public VpnConfig getVpnConfig(int userId) {
3649 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003650 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003651 Vpn vpn = mVpns.get(userId);
3652 if (vpn != null) {
3653 return vpn.getVpnConfig();
3654 } else {
3655 return null;
3656 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003657 }
3658 }
3659
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003660 @Override
3661 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003662 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3663 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3664 return false;
3665 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003666
3667 // Tear down existing lockdown if profile was removed
3668 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3669 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003670 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3671 final VpnProfile profile = VpnProfile.decode(
3672 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003673 if (profile == null) {
3674 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3675 setLockdownTracker(null);
3676 return true;
3677 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003678 int user = UserHandle.getUserId(Binder.getCallingUid());
3679 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003680 Vpn vpn = mVpns.get(user);
3681 if (vpn == null) {
3682 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3683 return false;
3684 }
3685 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003686 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003687 } else {
3688 setLockdownTracker(null);
3689 }
3690
3691 return true;
3692 }
3693
3694 /**
3695 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3696 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3697 */
3698 private void setLockdownTracker(LockdownVpnTracker tracker) {
3699 // Shutdown any existing tracker
3700 final LockdownVpnTracker existing = mLockdownTracker;
3701 mLockdownTracker = null;
3702 if (existing != null) {
3703 existing.shutdown();
3704 }
3705
3706 try {
3707 if (tracker != null) {
3708 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003709 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003710 mLockdownTracker = tracker;
3711 mLockdownTracker.init();
3712 } else {
3713 mNetd.setFirewallEnabled(false);
3714 }
3715 } catch (RemoteException e) {
3716 // ignored; NMS lives inside system_server
3717 }
3718 }
3719
3720 private void throwIfLockdownEnabled() {
3721 if (mLockdownEnabled) {
3722 throw new IllegalStateException("Unavailable in lockdown mode");
3723 }
3724 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003725
Robin Lee244ce8e2016-01-05 18:03:46 +00003726 /**
Robin Lee17e61832016-05-09 13:46:28 +01003727 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3728 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003729 *
Robin Lee17e61832016-05-09 13:46:28 +01003730 * @return {@code true} if the service was started, the service was already connected, or there
3731 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003732 */
Robin Lee17e61832016-05-09 13:46:28 +01003733 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003734 synchronized (mVpns) {
3735 Vpn vpn = mVpns.get(userId);
3736 if (vpn == null) {
3737 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3738 // exists already.
3739 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3740 return false;
3741 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003742
Robin Lee812800c2016-05-13 15:38:08 +01003743 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003744 }
3745 }
3746
3747 @Override
Robin Leedc679712016-05-03 13:23:03 +01003748 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003749 enforceConnectivityInternalPermission();
3750 enforceCrossUserPermission(userId);
3751
3752 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3753 if (LockdownVpnTracker.isEnabled()) {
3754 return false;
3755 }
3756
Robin Lee244ce8e2016-01-05 18:03:46 +00003757 synchronized (mVpns) {
3758 Vpn vpn = mVpns.get(userId);
3759 if (vpn == null) {
3760 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3761 return false;
3762 }
Robin Lee17e61832016-05-09 13:46:28 +01003763 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003764 return false;
3765 }
Robin Lee17e61832016-05-09 13:46:28 +01003766 if (!startAlwaysOnVpn(userId)) {
3767 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003768 return false;
3769 }
Robin Lee17e61832016-05-09 13:46:28 +01003770
Robin Lee812800c2016-05-13 15:38:08 +01003771 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003772 }
3773 return true;
3774 }
3775
3776 @Override
3777 public String getAlwaysOnVpnPackage(int userId) {
3778 enforceConnectivityInternalPermission();
3779 enforceCrossUserPermission(userId);
3780
3781 synchronized (mVpns) {
3782 Vpn vpn = mVpns.get(userId);
3783 if (vpn == null) {
3784 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3785 return null;
3786 }
3787 return vpn.getAlwaysOnPackage();
3788 }
3789 }
3790
Wink Savilleab9321d2013-06-29 21:10:57 -07003791 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003792 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003793 // TODO: Remove? Any reason to trigger a provisioning check?
3794 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003795 }
3796
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003797 /** Location to an updatable file listing carrier provisioning urls.
3798 * An example:
3799 *
3800 * <?xml version="1.0" encoding="utf-8"?>
3801 * <provisioningUrls>
3802 * <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 -07003803 * </provisioningUrls>
3804 */
3805 private static final String PROVISIONING_URL_PATH =
3806 "/data/misc/radio/provisioning_urls.xml";
3807 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003808
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003809 /** XML tag for root element. */
3810 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3811 /** XML tag for individual url */
3812 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003813 /** XML attribute for mcc */
3814 private static final String ATTR_MCC = "mcc";
3815 /** XML attribute for mnc */
3816 private static final String ATTR_MNC = "mnc";
3817
Paul Jensen434dde82015-06-11 09:43:30 -04003818 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003819 FileReader fileReader = null;
3820 XmlPullParser parser = null;
3821 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003822
3823 try {
3824 fileReader = new FileReader(mProvisioningUrlFile);
3825 parser = Xml.newPullParser();
3826 parser.setInput(fileReader);
3827 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3828
3829 while (true) {
3830 XmlUtils.nextElement(parser);
3831
3832 String element = parser.getName();
3833 if (element == null) break;
3834
Paul Jensen434dde82015-06-11 09:43:30 -04003835 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003836 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3837 try {
3838 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3839 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3840 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3841 parser.next();
3842 if (parser.getEventType() == XmlPullParser.TEXT) {
3843 return parser.getText();
3844 }
3845 }
3846 }
3847 } catch (NumberFormatException e) {
3848 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3849 }
3850 }
3851 }
3852 return null;
3853 } catch (FileNotFoundException e) {
3854 loge("Carrier Provisioning Urls file not found");
3855 } catch (XmlPullParserException e) {
3856 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3857 } catch (IOException e) {
3858 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3859 } finally {
3860 if (fileReader != null) {
3861 try {
3862 fileReader.close();
3863 } catch (IOException e) {}
3864 }
3865 }
3866 return null;
3867 }
3868
Wink Saville42d4f082013-07-20 20:31:59 -07003869 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003870 public String getMobileProvisioningUrl() {
3871 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003872 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003873 if (TextUtils.isEmpty(url)) {
3874 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003875 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003876 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003877 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003878 }
Wink Saville8cf35602013-07-10 23:00:07 -07003879 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003880 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003881 String phoneNumber = mTelephonyManager.getLine1Number();
3882 if (TextUtils.isEmpty(phoneNumber)) {
3883 phoneNumber = "0000000000";
3884 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003885 url = String.format(url,
3886 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3887 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003888 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003889 }
3890
Wink Savilleab9321d2013-06-29 21:10:57 -07003891 return url;
3892 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003893
Wink Saville948282b2013-08-29 08:55:16 -07003894 @Override
3895 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003896 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003897 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003898 final long ident = Binder.clearCallingIdentity();
3899 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003900 // Concatenate the range of types onto the range of NetIDs.
3901 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3902 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003903 } finally {
3904 Binder.restoreCallingIdentity(ident);
3905 }
Wink Saville948282b2013-08-29 08:55:16 -07003906 }
Wink Saville7788c612013-08-29 14:57:08 -07003907
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003908 @Override
3909 public void setAirplaneMode(boolean enable) {
3910 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003911 final long ident = Binder.clearCallingIdentity();
3912 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003913 final ContentResolver cr = mContext.getContentResolver();
3914 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3915 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3916 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003917 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003918 } finally {
3919 Binder.restoreCallingIdentity(ident);
3920 }
3921 }
3922
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003923 private void onUserStart(int userId) {
3924 synchronized(mVpns) {
3925 Vpn userVpn = mVpns.get(userId);
3926 if (userVpn != null) {
3927 loge("Starting user already has a VPN");
3928 return;
3929 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003930 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003931 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003932
3933 final ContentResolver cr = mContext.getContentResolver();
3934 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3935 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3936 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3937 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3938 if (alwaysOnPackage != null) {
3939 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3940 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003941 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003942 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3943 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003944 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003945 }
3946
3947 private void onUserStop(int userId) {
3948 synchronized(mVpns) {
3949 Vpn userVpn = mVpns.get(userId);
3950 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003951 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003952 return;
3953 }
Robin Lee17e61832016-05-09 13:46:28 +01003954 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003955 mVpns.delete(userId);
3956 }
3957 }
3958
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003959 private void onUserAdded(int userId) {
3960 synchronized(mVpns) {
3961 final int vpnsSize = mVpns.size();
3962 for (int i = 0; i < vpnsSize; i++) {
3963 Vpn vpn = mVpns.valueAt(i);
3964 vpn.onUserAdded(userId);
3965 }
3966 }
3967 }
3968
3969 private void onUserRemoved(int userId) {
3970 synchronized(mVpns) {
3971 final int vpnsSize = mVpns.size();
3972 for (int i = 0; i < vpnsSize; i++) {
3973 Vpn vpn = mVpns.valueAt(i);
3974 vpn.onUserRemoved(userId);
3975 }
3976 }
3977 }
3978
Robin Lee89e7a692016-02-29 14:38:17 +00003979 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003980 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3981 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3982 updateLockdownVpn();
3983 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003984 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003985 }
3986 }
3987
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003988 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3989 @Override
3990 public void onReceive(Context context, Intent intent) {
3991 final String action = intent.getAction();
3992 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3993 if (userId == UserHandle.USER_NULL) return;
3994
Robin Lee323f29d2016-05-04 16:38:06 +01003995 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003996 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003997 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003998 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003999 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4000 onUserAdded(userId);
4001 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4002 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004003 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4004 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004005 }
4006 }
4007 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004008
Robert Greenwalta67be032014-05-16 15:49:14 -07004009 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4010 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004011 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4012 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004013
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004014 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4015 // Map from UID to number of NetworkRequests that UID has filed.
4016 @GuardedBy("mUidToNetworkRequestCount")
4017 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4018
Robert Greenwalta67be032014-05-16 15:49:14 -07004019 private static class NetworkFactoryInfo {
4020 public final String name;
4021 public final Messenger messenger;
4022 public final AsyncChannel asyncChannel;
4023
4024 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4025 this.name = name;
4026 this.messenger = messenger;
4027 this.asyncChannel = asyncChannel;
4028 }
4029 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004030
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004031 private void ensureNetworkRequestHasType(NetworkRequest request) {
4032 if (request.type == NetworkRequest.Type.NONE) {
4033 throw new IllegalArgumentException(
4034 "All NetworkRequests in ConnectivityService must have a type");
4035 }
4036 }
4037
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004038 /**
4039 * Tracks info about the requester.
4040 * Also used to notice when the calling process dies so we can self-expire
4041 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004043 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004045 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004046 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004047 final int mPid;
4048 final int mUid;
4049 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004050
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004051 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004052 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004053 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004054 mPendingIntent = pi;
4055 messenger = null;
4056 mBinder = null;
4057 mPid = getCallingPid();
4058 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004059 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004060 }
4061
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004062 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004063 super();
4064 messenger = m;
4065 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004066 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004067 mBinder = binder;
4068 mPid = getCallingPid();
4069 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004070 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004071 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004072
4073 try {
4074 mBinder.linkToDeath(this, 0);
4075 } catch (RemoteException e) {
4076 binderDied();
4077 }
4078 }
4079
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004080 private void enforceRequestCountLimit() {
4081 synchronized (mUidToNetworkRequestCount) {
4082 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4083 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4084 throw new IllegalArgumentException("Too many NetworkRequests filed");
4085 }
4086 mUidToNetworkRequestCount.put(mUid, networkRequests);
4087 }
4088 }
4089
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004091 if (mBinder != null) {
4092 mBinder.unlinkToDeath(this, 0);
4093 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004094 }
4095
4096 public void binderDied() {
4097 log("ConnectivityService NetworkRequestInfo binderDied(" +
4098 request + ", " + mBinder + ")");
4099 releaseNetworkRequest(request);
4100 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004101
4102 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004103 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004104 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004105 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004106 }
4107
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004108 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4109 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4110 if (badCapability != null) {
4111 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004112 }
4113 }
4114
Erik Kline9d598e12015-07-13 16:37:51 +09004115 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004116 final SortedSet<Integer> thresholds = new TreeSet();
4117 synchronized (nai) {
4118 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4119 if (nri.request.networkCapabilities.hasSignalStrength() &&
4120 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4121 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4122 }
4123 }
4124 }
Erik Kline9d598e12015-07-13 16:37:51 +09004125 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004126 }
4127
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004128 private void updateSignalStrengthThresholds(
4129 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4130 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004131 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004132 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4133
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004134 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004135 String detail;
4136 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4137 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4138 } else {
4139 detail = reason;
4140 }
4141 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4142 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4143 }
4144
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004145 nai.asyncChannel.sendMessage(
4146 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004147 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004148 }
4149
Robert Greenwalt9258c642014-03-26 16:47:06 -07004150 @Override
4151 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004152 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004153 final NetworkRequest.Type type = (networkCapabilities == null)
4154 ? NetworkRequest.Type.TRACK_DEFAULT
4155 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004156 // If the requested networkCapabilities is null, take them instead from
4157 // the default network request. This allows callers to keep track of
4158 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004159 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004160 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4161 enforceAccessPermission();
4162 } else {
4163 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4164 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004165 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4166 // of the app when the request is filed, but we never change the request if the app
4167 // changes network state. http://b/29964605
4168 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004169 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004170 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004171
Robert Greenwalt6078b502014-06-11 16:05:07 -07004172 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173 throw new IllegalArgumentException("Bad timeout specified");
4174 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004175
Etan Cohenddb9ef02015-11-18 10:56:15 -08004176 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4177 .equals(networkCapabilities.getNetworkSpecifier())) {
4178 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4179 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4180 }
4181
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004182 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004183 nextNetworkRequestId(), type);
4184 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004185 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004186
4187 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004188 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004189 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004190 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004191 }
4192 return networkRequest;
4193 }
4194
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004195 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004196 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004197 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004198 } else {
4199 enforceChangePermission();
4200 }
4201 }
4202
fenglub15e72b2015-03-20 11:29:56 -07004203 @Override
fengludb571472015-04-21 17:12:05 -07004204 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004205 enforceAccessPermission();
4206 NetworkAgentInfo nai = null;
4207 if (network == null) {
4208 return false;
4209 }
4210 synchronized (mNetworkForNetId) {
4211 nai = mNetworkForNetId.get(network.netId);
4212 }
4213 if (nai != null) {
4214 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4215 return true;
4216 }
4217 return false;
4218 }
4219
Felipe Lemeee27cab2016-06-20 16:36:29 -07004220 private boolean isSystem(int uid) {
4221 return uid < Process.FIRST_APPLICATION_UID;
4222 }
fenglub15e72b2015-03-20 11:29:56 -07004223
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004224 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004225 final int uid = Binder.getCallingUid();
4226 if (isSystem(uid)) {
4227 return;
4228 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004229 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004230 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004231 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004232 synchronized(mRulesLock) {
4233 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4234 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004235 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4236 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004237 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004238 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004239 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004240 }
4241 }
4242 }
4243
Robert Greenwalt9258c642014-03-26 16:47:06 -07004244 @Override
4245 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4246 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004247 checkNotNull(operation, "PendingIntent cannot be null.");
4248 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4249 enforceNetworkRequestPermissions(networkCapabilities);
4250 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004251 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004252
4253 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004254 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4255 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004256 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004257 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4258 nri));
4259 return networkRequest;
4260 }
4261
Jeremy Joslin79294842014-12-03 17:15:28 -08004262 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4263 mHandler.sendMessageDelayed(
4264 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4265 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4266 }
4267
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004268 @Override
4269 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004270 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004271 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4272 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004273 }
4274
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004275 // In order to implement the compatibility measure for pre-M apps that call
4276 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4277 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4278 // This ensures it has permission to do so.
4279 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4280 if (nc == null) {
4281 return false;
4282 }
4283 int[] transportTypes = nc.getTransportTypes();
4284 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4285 return false;
4286 }
4287 try {
4288 mContext.enforceCallingOrSelfPermission(
4289 android.Manifest.permission.ACCESS_WIFI_STATE,
4290 "ConnectivityService");
4291 } catch (SecurityException e) {
4292 return false;
4293 }
4294 return true;
4295 }
4296
Robert Greenwalt9258c642014-03-26 16:47:06 -07004297 @Override
4298 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4299 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004300 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4301 enforceAccessPermission();
4302 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004303
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004304 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4305 if (!ConnectivityManager.checkChangePermission(mContext)) {
4306 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4307 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4308 // onLost and onAvailable callbacks when networks move in and out of the background.
4309 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4310 // can't request networks.
4311 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4312 }
4313
4314 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004315 NetworkRequest.Type.LISTEN);
4316 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004317 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004318
4319 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4320 return networkRequest;
4321 }
4322
4323 @Override
4324 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4325 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004326 checkNotNull(operation, "PendingIntent cannot be null.");
4327 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4328 enforceAccessPermission();
4329 }
4330
Erik Kline7523eb32015-07-09 18:24:03 +09004331 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004332 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4333 NetworkRequest.Type.LISTEN);
4334 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004335 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004336
4337 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004338 }
4339
4340 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004341 public void requestLinkProperties(NetworkRequest networkRequest) {
4342 ensureNetworkRequestHasType(networkRequest);
4343 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4344 mHandler.sendMessage(mHandler.obtainMessage(
4345 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4346 }
4347
4348 @Override
4349 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4350 ensureNetworkRequestHasType(networkRequest);
4351 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4352 mHandler.sendMessage(mHandler.obtainMessage(
4353 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4354 }
4355
4356 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004357 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004358 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004359 mHandler.sendMessage(mHandler.obtainMessage(
4360 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004361 }
4362
4363 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004364 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004365 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004366 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4367 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004368 }
4369
Robert Greenwalta67be032014-05-16 15:49:14 -07004370 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004371 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004372 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4373 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4374 }
4375
4376 @Override
4377 public void unregisterNetworkFactory(Messenger messenger) {
4378 enforceConnectivityInternalPermission();
4379 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4380 }
4381
4382 private void handleUnregisterNetworkFactory(Messenger messenger) {
4383 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4384 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004385 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004386 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004387 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004388 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004389 }
4390
Robert Greenwalt7b816022014-04-18 15:25:25 -07004391 /**
4392 * NetworkAgentInfo supporting a request by requestId.
4393 * These have already been vetted (their Capabilities satisfy the request)
4394 * and the are the highest scored network available.
4395 * the are keyed off the Requests requestId.
4396 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004397 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4399 new SparseArray<NetworkAgentInfo>();
4400
Paul Jensen31a94f42015-02-13 14:18:39 -05004401 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4402 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004403 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4404 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004405 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4406 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4407 // there may not be a strict 1:1 correlation between the two.
4408 @GuardedBy("mNetworkForNetId")
4409 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004410
Robert Greenwalt7b816022014-04-18 15:25:25 -07004411 // NetworkAgentInfo keyed off its connecting messenger
4412 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004413 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004414 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4415 new HashMap<Messenger, NetworkAgentInfo>();
4416
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004417 @GuardedBy("mBlockedAppUids")
4418 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4419
Paul Jensen2c311d62014-11-17 12:34:51 -05004420 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004421 private final NetworkRequest mDefaultRequest;
4422
Erik Klineda4bfa82015-04-30 12:58:40 +09004423 // Request used to optionally keep mobile data active even when higher
4424 // priority networks like Wi-Fi are active.
4425 private final NetworkRequest mDefaultMobileDataRequest;
4426
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004427 private NetworkAgentInfo getDefaultNetwork() {
4428 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4429 }
4430
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004431 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004432 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004433 }
4434
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004435 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4436 return nri.request.requestId == mDefaultRequest.requestId;
4437 }
4438
Paul Jensen31a94f42015-02-13 14:18:39 -05004439 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004440 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004441 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004442 enforceConnectivityInternalPermission();
4443
Paul Jensen2c311d62014-11-17 12:34:51 -05004444 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4445 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004446 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004447 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4448 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004449 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004450 synchronized (this) {
4451 nai.networkMonitor.systemReady = mSystemReady;
4452 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004453 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4454 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004455 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004456 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004457 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004458 }
4459
4460 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4461 if (VDBG) log("Got NetworkAgent Messenger");
4462 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004463 synchronized (mNetworkForNetId) {
4464 mNetworkForNetId.put(na.network.netId, na);
4465 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004466 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4467 NetworkInfo networkInfo = na.networkInfo;
4468 na.networkInfo = null;
4469 updateNetworkInfo(na, networkInfo);
4470 }
4471
4472 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4473 LinkProperties newLp = networkAgent.linkProperties;
4474 int netId = networkAgent.network.netId;
4475
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004476 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4477 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004478 if (networkAgent.clatd != null) {
4479 networkAgent.clatd.fixupLinkProperties(oldLp);
4480 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004481
Paul Jensen992f2522014-04-28 10:33:11 -04004482 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004483 updateMtu(newLp, oldLp);
4484 // TODO - figure out what to do for clat
4485// for (LinkProperties lp : newLp.getStackedLinks()) {
4486// updateMtu(lp, null);
4487// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004488 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004489
Erik Kline94887872016-04-05 13:30:49 +09004490 updateRoutes(newLp, oldLp, netId);
4491 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004492
Paul Jensen3b759822014-05-13 11:44:01 -04004493 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004494 if (isDefaultNetwork(networkAgent)) {
4495 handleApplyDefaultProxy(newLp.getHttpProxy());
4496 } else {
4497 updateProxy(newLp, oldLp, networkAgent);
4498 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004499 // TODO - move this check to cover the whole function
4500 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004501 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004502 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4503 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004504
4505 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004506 }
4507
Lorenzo Colitti95439462014-10-09 13:44:48 +09004508 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4509 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4510 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004511
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004512 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004513 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4514 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004515 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004516 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004517 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004518 }
Paul Jensen992f2522014-04-28 10:33:11 -04004519
4520 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4521 CompareResult<String> interfaceDiff = new CompareResult<String>();
4522 if (oldLp != null) {
4523 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4524 } else if (newLp != null) {
4525 interfaceDiff.added = newLp.getAllInterfaceNames();
4526 }
4527 for (String iface : interfaceDiff.added) {
4528 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004529 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004530 mNetd.addInterfaceToNetwork(iface, netId);
4531 } catch (Exception e) {
4532 loge("Exception adding interface: " + e);
4533 }
4534 }
4535 for (String iface : interfaceDiff.removed) {
4536 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004537 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004538 mNetd.removeInterfaceFromNetwork(iface, netId);
4539 } catch (Exception e) {
4540 loge("Exception removing interface: " + e);
4541 }
4542 }
4543 }
4544
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004545 /**
4546 * Have netd update routes from oldLp to newLp.
4547 * @return true if routes changed between oldLp and newLp
4548 */
4549 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004550 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4551 if (oldLp != null) {
4552 routeDiff = oldLp.compareAllRoutes(newLp);
4553 } else if (newLp != null) {
4554 routeDiff.added = newLp.getAllRoutes();
4555 }
4556
4557 // add routes before removing old in case it helps with continuous connectivity
4558
4559 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4560 for (RouteInfo route : routeDiff.added) {
4561 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004562 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004563 try {
4564 mNetd.addRoute(netId, route);
4565 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004566 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4567 loge("Exception in addRoute for non-gateway: " + e);
4568 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 }
4570 }
4571 for (RouteInfo route : routeDiff.added) {
4572 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004573 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004574 try {
4575 mNetd.addRoute(netId, route);
4576 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004577 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4578 loge("Exception in addRoute for gateway: " + e);
4579 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004580 }
4581 }
4582
4583 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004584 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004585 try {
4586 mNetd.removeRoute(netId, route);
4587 } catch (Exception e) {
4588 loge("Exception in removeRoute: " + e);
4589 }
4590 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004591 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004592 }
Erik Kline41368502015-06-17 13:19:54 +09004593
Erik Kline94887872016-04-05 13:30:49 +09004594 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4595 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4596 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004597 }
Erik Kline94887872016-04-05 13:30:49 +09004598
4599 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004600 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004601 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004602 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004603 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4604 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004605 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004606 }
4607 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4608 if (defaultNai != null && defaultNai.network.netId == netId) {
4609 setDefaultDnsSystemProperties(dnses);
4610 }
4611 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004612 }
4613
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004614 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4615 int last = 0;
4616 for (InetAddress dns : dnses) {
4617 ++last;
4618 String key = "net.dns" + last;
4619 String value = dns.getHostAddress();
4620 SystemProperties.set(key, value);
4621 }
4622 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4623 String key = "net.dns" + i;
4624 SystemProperties.set(key, "");
4625 }
4626 mNumDnsEntries = last;
4627 }
4628
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004629 private String getNetworkPermission(NetworkCapabilities nc) {
4630 // TODO: make these permission strings AIDL constants instead.
4631 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4632 return NetworkManagementService.PERMISSION_SYSTEM;
4633 }
4634 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4635 return NetworkManagementService.PERMISSION_NETWORK;
4636 }
4637 return null;
4638 }
4639
Paul Jensen3d194ea2015-06-16 14:27:36 -04004640 /**
4641 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4642 * augmented with any stateful capabilities implied from {@code networkAgent}
4643 * (e.g., validated status and captive portal status).
4644 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004645 * @param oldScore score of the network before any of the changes that prompted us
4646 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004647 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004648 * @param networkCapabilities the new network capabilities.
4649 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004650 private void updateCapabilities(
4651 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004652 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4653 networkCapabilities)) {
4654 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4655 + nai.networkCapabilities + " -> " + networkCapabilities);
4656 }
4657
Paul Jensen3d194ea2015-06-16 14:27:36 -04004658 // Don't modify caller's NetworkCapabilities.
4659 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004660 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004661 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4662 } else {
4663 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4664 }
Paul Jensene0988542015-06-25 15:30:08 -04004665 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004666 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4667 } else {
4668 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4669 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004670 if (nai.isBackgroundNetwork()) {
4671 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4672 } else {
4673 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4674 }
4675
4676 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4677
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004678 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4679 final String newPermission = getNetworkPermission(networkCapabilities);
4680 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004681 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004682 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004683 } catch (RemoteException e) {
4684 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004685 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004686 }
4687
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004688 final NetworkCapabilities prevNc = nai.networkCapabilities;
4689 synchronized (nai) {
4690 nai.networkCapabilities = networkCapabilities;
4691 }
4692 if (nai.getCurrentScore() == oldScore &&
4693 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4694 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4695 // the change we're processing can't affect any requests, it can only affect the listens
4696 // on this network. We might have been called by rematchNetworkAndRequests when a
4697 // network changed foreground state.
4698 processListenRequests(nai, true);
4699 } else {
4700 // If the requestable capabilities have changed or the score changed, we can't have been
4701 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004702 rematchAllNetworksAndRequests(nai, oldScore);
4703 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004704 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004705 }
4706
Paul Jensenc8b9a742014-09-30 15:37:41 -04004707 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004708 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4709 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004710 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004711 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004712 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4713 }
4714 }
4715
Robert Greenwalt7b816022014-04-18 15:25:25 -07004716 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4717 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004718 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004719 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4720 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004721 }
4722 }
4723
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004724 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4725 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004726 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004727 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004728 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4729 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004730 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004731 sendIntent(nri.mPendingIntent, intent);
4732 }
4733 // else not handled
4734 }
4735
4736 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4737 mPendingIntentWakeLock.acquire();
4738 try {
4739 if (DBG) log("Sending " + pendingIntent);
4740 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4741 } catch (PendingIntent.CanceledException e) {
4742 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4743 mPendingIntentWakeLock.release();
4744 releasePendingNetworkRequest(pendingIntent);
4745 }
4746 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4747 }
4748
4749 @Override
4750 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4751 String resultData, Bundle resultExtras) {
4752 if (DBG) log("Finished sending " + pendingIntent);
4753 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004754 // Release with a delay so the receiving client has an opportunity to put in its
4755 // own request.
4756 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004757 }
4758
Robert Greenwalt9258c642014-03-26 16:47:06 -07004759 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004760 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004761 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004762 Bundle bundle = new Bundle();
4763 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4764 new NetworkRequest(nri.request));
4765 Message msg = Message.obtain();
4766 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4767 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4768 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4769 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004770 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004771 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004772 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004773 break;
4774 }
4775 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4776 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4777 new NetworkCapabilities(networkAgent.networkCapabilities));
4778 break;
4779 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004780 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004781 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4782 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004783 break;
4784 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004785 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004786 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004787 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004788 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004789 if (VDBG) {
4790 log("sending notification " + notifyTypeToName(notificationType) +
4791 " for " + nri.request);
4792 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004793 nri.messenger.send(msg);
4794 } catch (RemoteException e) {
4795 // may occur naturally in the race of binder death.
4796 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4797 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004798 }
4799
Paul Jensenc8b9a742014-09-30 15:37:41 -04004800 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004801 if (nai.numRequestNetworkRequests() != 0) {
4802 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4803 NetworkRequest nr = nai.requestAt(i);
4804 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004805 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004806 loge("Dead network still had at least " + nr);
4807 break;
4808 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004809 }
4810 nai.asyncChannel.disconnect();
4811 }
4812
Robert Greenwalt7b816022014-04-18 15:25:25 -07004813 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4814 if (oldNetwork == null) {
4815 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4816 return;
4817 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004818 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004819
4820 // If we get here it means that the last linger timeout for this network expired. So there
4821 // must be no other active linger timers, and we must stop lingering.
4822 oldNetwork.clearLingerState();
4823
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004824 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004825 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004826 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004827 } else {
4828 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004829 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4830 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004831 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004832 }
4833
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004834 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004835 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004836 setupDataActivityTracking(newNetwork);
4837 try {
4838 mNetd.setDefaultNetId(newNetwork.network.netId);
4839 } catch (Exception e) {
4840 loge("Exception setting default network :" + e);
4841 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004842 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004843 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004844 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004845 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004846 }
4847
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004848 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004849 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4850 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4851 NetworkRequest nr = nri.request;
4852 if (!nr.isListen()) continue;
4853 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4854 nai.removeRequest(nri.request.requestId);
4855 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4856 }
4857 }
4858
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004859 if (capabilitiesChanged) {
4860 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4861 }
4862
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004863 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4864 NetworkRequest nr = nri.request;
4865 if (!nr.isListen()) continue;
4866 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4867 nai.addRequest(nr);
4868 notifyNetworkCallback(nai, nri);
4869 }
4870 }
4871 }
4872
Paul Jensen2161a8e2014-09-11 11:00:39 -04004873 // Handles a network appearing or improving its score.
4874 //
4875 // - Evaluates all current NetworkRequests that can be
4876 // satisfied by newNetwork, and reassigns to newNetwork
4877 // any such requests for which newNetwork is the best.
4878 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004879 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004880 // needed. A network is needed if it is the best network for
4881 // one or more NetworkRequests, or if it is a VPN.
4882 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004883 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004884 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004885 //
4886 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4887 // networks that have no chance (i.e. even if validated)
4888 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004889 //
4890 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4891 // it does not remove NetworkRequests that other Networks could better satisfy.
4892 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4893 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4894 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004895 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004896 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004897 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4898 // performed to tear down unvalidated networks that have no chance (i.e. even if
4899 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004900 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004901 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004902 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004903 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004904 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004905 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004906
4907 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4908 final int score = newNetwork.getCurrentScore();
4909
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004910 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004911
Paul Jensen2161a8e2014-09-11 11:00:39 -04004912 // Find and migrate to this Network any NetworkRequests for
4913 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004914 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004915 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004916 NetworkCapabilities nc = newNetwork.networkCapabilities;
4917 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004918 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004919 // Process requests in the first pass and listens in the second pass. This allows us to
4920 // change a network's capabilities depending on which requests it has. This is only
4921 // correct if the change in capabilities doesn't affect whether the network satisfies
4922 // requests or not, and doesn't affect the network's score.
4923 if (nri.request.isListen()) continue;
4924
Paul Jensencf4c2c62015-07-01 14:16:32 -04004925 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4926 final boolean satisfies = newNetwork.satisfies(nri.request);
4927 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004928 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004929 log("Network " + newNetwork.name() + " was already satisfying" +
4930 " request " + nri.request.requestId + ". No change.");
4931 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004932 keep = true;
4933 continue;
4934 }
4935
4936 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004937 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004938 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004939 // next check if it's better than any current network we're using for
4940 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 if (VDBG) {
4942 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004943 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004944 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004945 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004946 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004947 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004948 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004949 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004950 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004951 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004952 affectedNetworks.add(currentNetwork);
4953 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004954 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004955 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004956 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004957 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004958 if (!newNetwork.addRequest(nri.request)) {
4959 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4960 }
4961 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004962 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004963 // Tell NetworkFactories about the new score, so they can stop
4964 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004965 // TODO - this could get expensive if we have alot of requests for this
4966 // network. Think about if there is a way to reduce this. Push
4967 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004968 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004969 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004970 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004971 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004972 if (currentNetwork != null) {
4973 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4974 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004975 }
4976 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004977 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004978 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4979 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004980 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004981 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4982 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4983 // This means this code doesn't have to handle the case where "currentNetwork" no
4984 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4985 if (DBG) {
4986 log("Network " + newNetwork.name() + " stopped satisfying" +
4987 " request " + nri.request.requestId);
4988 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004989 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004990 if (currentNetwork == newNetwork) {
4991 mNetworkForRequestId.remove(nri.request.requestId);
4992 sendUpdatedScoreToFactories(nri.request, 0);
4993 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004994 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4995 newNetwork.name() +
4996 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004997 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004998 // TODO: Technically, sending CALLBACK_LOST here is
4999 // incorrect if there is a replacement network currently
5000 // connected that can satisfy nri, which is a request
5001 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005002 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5003 // so this code is only incorrect for a network that loses
5004 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005005 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005006 }
5007 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005008 if (isNewDefault) {
5009 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005010 makeDefault(newNetwork);
5011 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
5012 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005013 synchronized (ConnectivityService.this) {
5014 // have a new default network, release the transition wakelock in
5015 // a second if it's held. The second pause is to allow apps
5016 // to reconnect over the new network
5017 if (mNetTransitionWakeLock.isHeld()) {
5018 mHandler.sendMessageDelayed(mHandler.obtainMessage(
5019 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
5020 mNetTransitionWakeLockSerialNumber, 0),
5021 1000);
5022 }
5023 }
5024 }
5025
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005026 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5027 Slog.wtf(TAG, String.format(
5028 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
5029 nc, newNetwork.networkCapabilities));
5030 }
5031 if (newNetwork.getCurrentScore() != score) {
5032 Slog.wtf(TAG, String.format(
5033 "BUG: %s changed score during rematch: %d -> %d",
5034 score, newNetwork.getCurrentScore()));
5035 }
5036
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005037 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005038 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5039 // If the network went from background to foreground or vice versa, we need to update
5040 // its foreground state. It is safe to do this after rematching the requests because
5041 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5042 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005043 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005044 } else {
5045 processListenRequests(newNetwork, false);
5046 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005047
Paul Jensencf4c2c62015-07-01 14:16:32 -04005048 // do this after the default net is switched, but
5049 // before LegacyTypeTracker sends legacy broadcasts
5050 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
5051
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005052 // Linger any networks that are no longer needed. This should be done after sending the
5053 // available callback for newNetwork.
5054 for (NetworkAgentInfo nai : affectedNetworks) {
5055 updateLingerState(nai, now);
5056 }
5057 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5058 // does not need to be done in any particular order.
5059 updateLingerState(newNetwork, now);
5060
Paul Jensencf4c2c62015-07-01 14:16:32 -04005061 if (isNewDefault) {
5062 // Maintain the illusion: since the legacy API only
5063 // understands one network at a time, we must pretend
5064 // that the current default network disconnected before
5065 // the new one connected.
5066 if (oldDefaultNetwork != null) {
5067 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5068 oldDefaultNetwork, true);
5069 }
5070 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5071 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5072 notifyLockdownVpn(newNetwork);
5073 }
5074
Robert Greenwalt7b816022014-04-18 15:25:25 -07005075 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005076 // Notify battery stats service about this network, both the normal
5077 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005078 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005079 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005080 final IBatteryStats bs = BatteryStatsService.getService();
5081 final int type = newNetwork.networkInfo.getType();
5082
5083 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5084 bs.noteNetworkInterfaceType(baseIface, type);
5085 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5086 final String stackedIface = stacked.getInterfaceName();
5087 bs.noteNetworkInterfaceType(stackedIface, type);
5088 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5089 }
5090 } catch (RemoteException ignored) {
5091 }
5092
Robert Greenwalt152ed372014-12-17 17:19:53 -08005093 // This has to happen after the notifyNetworkCallbacks as that tickles each
5094 // ConnectivityManager instance so that legacy requests correctly bind dns
5095 // requests to this network. The legacy users are listening for this bcast
5096 // and will generally do a dns request so they can ensureRouteToHost and if
5097 // they do that before the callbacks happen they'll use the default network.
5098 //
5099 // TODO: Is there still a race here? We send the broadcast
5100 // after sending the callback, but if the app can receive the
5101 // broadcast before the callback, it might still break.
5102 //
5103 // This *does* introduce a race where if the user uses the new api
5104 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5105 // they may get old info. Reverse this after the old startUsing api is removed.
5106 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005107 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5108 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005109 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005110 // legacy type tracker filters out repeat adds
5111 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5112 }
5113 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005114
5115 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5116 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5117 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5118 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5119 if (newNetwork.isVPN()) {
5120 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5121 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005122 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005123 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5124 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005125 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005126 if (nai.getLingerExpiry() > 0) {
5127 // This network has active linger timers and no requests, but is not
5128 // lingering. Linger it.
5129 //
5130 // One way (the only way?) this can happen if this network is unvalidated
5131 // and became unneeded due to another network improving its score to the
5132 // point where this network will no longer be able to satisfy any requests
5133 // even if it validates.
5134 updateLingerState(nai, now);
5135 } else {
5136 if (DBG) log("Reaping " + nai.name());
5137 teardownUnneededNetwork(nai);
5138 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005139 }
5140 }
5141 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005142 }
5143
Paul Jensen1c7ba022015-06-16 14:27:36 -04005144 /**
5145 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5146 * being disconnected.
5147 * @param changed If only one Network's score or capabilities have been modified since the last
5148 * time this function was called, pass this Network in this argument, otherwise pass
5149 * null.
5150 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5151 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5152 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5153 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5154 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005155 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005156 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005157 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5158 // to avoid the slowness. It is not simply enough to process just "changed", for
5159 // example in the case where "changed"'s score decreases and another network should begin
5160 // satifying a NetworkRequest that "changed" currently satisfies.
5161
5162 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5163 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5164 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005165 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005166 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005167 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005168 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005169 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5170 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5171 // Rematch higher scoring networks first to prevent requests first matching a lower
5172 // scoring network and then a higher scoring network, which could produce multiple
5173 // callbacks and inadvertently unlinger networks.
5174 Arrays.sort(nais);
5175 for (NetworkAgentInfo nai : nais) {
5176 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005177 // Only reap the last time through the loop. Reaping before all rematching
5178 // is complete could incorrectly teardown a network that hasn't yet been
5179 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005180 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005181 : ReapUnvalidatedNetworks.REAP,
5182 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005183 }
5184 }
5185 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005186
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005187 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005188 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005189 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005190 // For now only update icons for default connection.
5191 // TODO: Update WiFi and cellular icons separately. b/17237507
5192 if (!isDefaultNetwork(nai)) return;
5193
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005194 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005195 // Don't repeat publish.
5196 if (newInetCondition == mDefaultInetConditionPublished) return;
5197
5198 mDefaultInetConditionPublished = newInetCondition;
5199 sendInetConditionBroadcast(nai.networkInfo);
5200 }
5201
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005202 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5203 if (mLockdownTracker != null) {
5204 if (nai != null && nai.isVPN()) {
5205 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5206 } else {
5207 mLockdownTracker.onNetworkInfoChanged();
5208 }
5209 }
5210 }
5211
Robert Greenwalt7b816022014-04-18 15:25:25 -07005212 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5213 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005214 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005215 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005216 synchronized (networkAgent) {
5217 oldInfo = networkAgent.networkInfo;
5218 networkAgent.networkInfo = newInfo;
5219 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005220 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005221
5222 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005223 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5224 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5225 notifyIfacesChangedForNetworkStats();
5226 } else if (VDBG) log("ignoring duplicate network state non-change");
5227 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005228 return;
5229 }
5230 if (DBG) {
5231 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5232 (oldInfo == null ? "null" : oldInfo.getState()) +
5233 " to " + state);
5234 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005235
Robin Lee585e2482016-05-01 23:00:00 +01005236 if (!networkAgent.created
5237 && (state == NetworkInfo.State.CONNECTED
5238 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005239
5240 // A network that has just connected has zero requests and is thus a foreground network.
5241 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5242
Robert Greenwalt7b816022014-04-18 15:25:25 -07005243 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005244 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005245 if (networkAgent.isVPN()) {
5246 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005247 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5248 (networkAgent.networkMisc == null ||
5249 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005250 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005251 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005252 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005253 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005254 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005255 loge("Error creating network " + networkAgent.network.netId + ": "
5256 + e.getMessage());
5257 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005258 }
Paul Jenseneec75412014-08-04 12:21:19 -04005259 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005260 }
5261
5262 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5263 networkAgent.everConnected = true;
5264
Robert Greenwalt7b816022014-04-18 15:25:25 -07005265 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005266 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005267
Paul Jensenca8f16a2014-05-09 12:47:55 -04005268 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005269 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005270
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005271 if (networkAgent.isVPN()) {
5272 // Temporarily disable the default proxy (not global).
5273 synchronized (mProxyLock) {
5274 if (!mDefaultProxyDisabled) {
5275 mDefaultProxyDisabled = true;
5276 if (mGlobalProxy == null && mDefaultProxy != null) {
5277 sendProxyBroadcast(null);
5278 }
5279 }
5280 }
5281 // TODO: support proxy per network.
5282 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005283
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005284 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5285 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5286 // capabilities, so it only needs to be done once on initial connect, not every time the
5287 // network's capabilities change. Note that we do this before rematching the network,
5288 // so we could decide to tear it down immediately afterwards. That's fine though - on
5289 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5290 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005291 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005292
Paul Jensen2161a8e2014-09-11 11:00:39 -04005293 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005294 final long now = SystemClock.elapsedRealtime();
5295 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005296
5297 // This has to happen after matching the requests, because callbacks are just requests.
5298 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005299 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005300 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005301 if (networkAgent.isVPN()) {
5302 synchronized (mProxyLock) {
5303 if (mDefaultProxyDisabled) {
5304 mDefaultProxyDisabled = false;
5305 if (mGlobalProxy == null && mDefaultProxy != null) {
5306 sendProxyBroadcast(mDefaultProxy);
5307 }
5308 }
5309 }
5310 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005311 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5312 state == NetworkInfo.State.SUSPENDED) {
5313 // going into or coming out of SUSPEND: rescore and notify
5314 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005315 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005316 }
5317 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5318 ConnectivityManager.CALLBACK_SUSPENDED :
5319 ConnectivityManager.CALLBACK_RESUMED));
5320 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005321 }
5322 }
5323
Robert Greenwaltac96c522014-06-03 16:43:57 -07005324 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005325 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005326 if (score < 0) {
5327 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5328 "). Bumping score to min of 0");
5329 score = 0;
5330 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005331
Paul Jensen2161a8e2014-09-11 11:00:39 -04005332 final int oldScore = nai.getCurrentScore();
5333 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005334
Paul Jensen85cf78e2015-06-25 13:25:07 -04005335 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005336
Paul Jensenc8b9a742014-09-30 15:37:41 -04005337 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005338 }
5339
Robert Greenwalt9258c642014-03-26 16:47:06 -07005340 // notify only this one new request of the current state
5341 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5342 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005343 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005344 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005345 } else {
5346 sendPendingIntentForRequest(nri, nai, notifyType);
5347 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005348 }
5349
Robert Greenwalt8d482522015-06-24 13:23:42 -07005350 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005351 // The NetworkInfo we actually send out has no bearing on the real
5352 // state of affairs. For example, if the default connection is mobile,
5353 // and a request for HIPRI has just gone away, we need to pretend that
5354 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5355 // the state to DISCONNECTED, even though the network is of type MOBILE
5356 // and is still connected.
5357 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5358 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005359 if (state != DetailedState.DISCONNECTED) {
5360 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005361 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005362 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005363 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005364 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5365 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5366 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5367 if (info.isFailover()) {
5368 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5369 nai.networkInfo.setFailover(false);
5370 }
5371 if (info.getReason() != null) {
5372 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5373 }
5374 if (info.getExtraInfo() != null) {
5375 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5376 }
5377 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005378 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005379 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005380 if (newDefaultAgent != null) {
5381 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5382 newDefaultAgent.networkInfo);
5383 } else {
5384 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5385 }
5386 }
5387 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5388 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005389 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005390 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005391 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005392 }
5393 }
5394 }
5395
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005396 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005397 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005398 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5399 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005400 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5401 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005402 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5403 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005404 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005405 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005406 } else {
5407 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5408 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005409 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005410 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005411
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005412 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5413 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5414 }
5415
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005416 private String notifyTypeToName(int notifyType) {
5417 switch (notifyType) {
5418 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5419 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5420 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5421 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5422 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5423 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5424 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5425 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5426 }
5427 return "UNKNOWN";
5428 }
5429
Jeff Sharkey69736342014-12-08 14:50:12 -08005430 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005431 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5432 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005433 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005434 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005435 try {
5436 mStatsService.forceUpdateIfaces();
5437 } catch (Exception ignored) {
5438 }
5439 }
5440
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005441 @Override
5442 public boolean addVpnAddress(String address, int prefixLength) {
5443 throwIfLockdownEnabled();
5444 int user = UserHandle.getUserId(Binder.getCallingUid());
5445 synchronized (mVpns) {
5446 return mVpns.get(user).addAddress(address, prefixLength);
5447 }
5448 }
5449
5450 @Override
5451 public boolean removeVpnAddress(String address, int prefixLength) {
5452 throwIfLockdownEnabled();
5453 int user = UserHandle.getUserId(Binder.getCallingUid());
5454 synchronized (mVpns) {
5455 return mVpns.get(user).removeAddress(address, prefixLength);
5456 }
5457 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005458
5459 @Override
5460 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5461 throwIfLockdownEnabled();
5462 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005463 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005464 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005465 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005466 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005467 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005468 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005469 }
5470 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005471 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005472
5473 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005474 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005475 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005476 }
5477
5478 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005479 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5480 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5481 enforceKeepalivePermission();
5482 mKeepaliveTracker.startNattKeepalive(
5483 getNetworkAgentInfoForNetwork(network),
5484 intervalSeconds, messenger, binder,
5485 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5486 }
5487
5488 @Override
5489 public void stopKeepalive(Network network, int slot) {
5490 mHandler.sendMessage(mHandler.obtainMessage(
5491 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5492 }
5493
5494 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005495 public void factoryReset() {
5496 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005497
5498 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5499 return;
5500 }
5501
Robin Lee3b3dd942015-05-12 18:14:58 +01005502 final int userId = UserHandle.getCallingUserId();
5503
Stuart Scottf1fb3972015-04-02 18:00:02 -07005504 // Turn airplane mode off
5505 setAirplaneMode(false);
5506
Stuart Scotte3e314d2015-04-20 14:07:45 -07005507 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5508 // Untether
5509 for (String tether : getTetheredIfaces()) {
5510 untether(tether);
5511 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005512 }
5513
Stuart Scotte3e314d2015-04-20 14:07:45 -07005514 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005515 // Remove always-on package
5516 synchronized (mVpns) {
5517 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5518 if (alwaysOnPackage != null) {
5519 setAlwaysOnVpnPackage(userId, null, false);
5520 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5521 }
5522 }
5523
Stuart Scotte3e314d2015-04-20 14:07:45 -07005524 // Turn VPN off
5525 VpnConfig vpnConfig = getVpnConfig(userId);
5526 if (vpnConfig != null) {
5527 if (vpnConfig.legacy) {
5528 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5529 } else {
5530 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5531 // in the future without user intervention.
5532 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005533
Victor Changb04a5ea2016-05-30 20:36:30 +01005534 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005535 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005536 }
5537 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005538
5539 Settings.Global.putString(mContext.getContentResolver(),
5540 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005541 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005542
5543 @VisibleForTesting
5544 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5545 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5546 return new NetworkMonitor(context, handler, nai, defaultRequest);
5547 }
Erik Kline48f12f22016-04-14 17:30:59 +09005548
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005549 @VisibleForTesting
Erik Kline065ab6e2016-10-02 18:02:14 +09005550 AvoidBadWifiTracker createAvoidBadWifiTracker(Context c, Handler h, Runnable r) {
5551 return new AvoidBadWifiTracker(c, h, r);
5552 }
5553
5554 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005555 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5556 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5557 }
5558
Hugo Benichicfddd682016-05-31 16:28:06 +09005559 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005560 int newNetid = NETID_UNSET;
5561 int prevNetid = NETID_UNSET;
5562 int[] transports = new int[0];
5563 boolean hadIPv4 = false;
5564 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005565
Hugo Benichi5f16f762016-04-20 12:09:33 +09005566 if (newNai != null) {
5567 newNetid = newNai.network.netId;
5568 transports = newNai.networkCapabilities.getTransportTypes();
5569 }
5570 if (prevNai != null) {
5571 prevNetid = prevNai.network.netId;
5572 final LinkProperties lp = prevNai.linkProperties;
5573 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5574 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5575 }
5576
Hugo Benichicfddd682016-05-31 16:28:06 +09005577 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5578 }
5579
5580 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5581 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583}