blob: ff079adc7c211cb346833031f260ee6712ebe2c1 [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;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090081import android.net.util.MultinetworkPolicyTracker;
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;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070099import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400100import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700102import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700103import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700104import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600106import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700107import android.util.LocalLog;
108import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600109import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700110import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800111import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700112import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500113import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700115import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400119import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700121import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700123import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800124import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700125import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700126import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700127import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900128import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900129import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700130import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700131import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400132import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900133import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700134import com.android.server.connectivity.MockableSystemProperties;
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
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900210 private MockableSystemProperties mSystemProperties;
211
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800212 private Tethering mTethering;
213
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700214 private final PermissionMonitor mPermissionMonitor;
215
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700216 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700217
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700218 @GuardedBy("mVpns")
219 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700220
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700221 private boolean mLockdownEnabled;
222 private LockdownVpnTracker mLockdownTracker;
223
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700224 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
225 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700226 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600227 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700228 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700229 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600230 @GuardedBy("mRulesLock")
231 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
232 /** Flag indicating if background data is restricted. */
233 @GuardedBy("mRulesLock")
234 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235
Erik Klineda4bfa82015-04-30 12:58:40 +0900236 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700238 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700239 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800241 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
243 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700244 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700246 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800247 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700248 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700249
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700250 private String mCurrentTcpBufferSizes;
251
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700252 private static final int ENABLED = 1;
253 private static final int DISABLED = 0;
254
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900255 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900256 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
257 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900258
Paul Jensenb10e37f2014-11-25 12:33:08 -0500259 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400260 // Tear down networks that have no chance (e.g. even if validated) of becoming
261 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 // all networks have been rematched against all NetworkRequests.
263 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400264 // Don't reap networks. This should be passed when some networks have not yet been
265 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500266 DONT_REAP
267 };
268
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900269 private enum UnneededFor {
270 LINGER, // Determine whether this network is unneeded and should be lingered.
271 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
272 }
273
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700275 * used internally to change our mobile data enabled flag
276 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700277 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278
279 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700280 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700281 * from one net to another. Clear happens when we get a new
282 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
283 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700286
Robert Greenwalt434203a2010-10-11 16:00:27 -0700287 /**
288 * used internally to reload global proxy settings
289 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700290 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700291
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700292 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400293 * PAC manager has received new port.
294 */
295 private static final int EVENT_PROXY_HAS_CHANGED = 16;
296
Robert Greenwalte049c232014-04-11 15:53:27 -0700297 /**
298 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700299 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700300 */
301 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
302
Robert Greenwalt7b816022014-04-18 15:25:25 -0700303 /**
304 * used internally when registering NetworkAgents
305 * obj = Messenger
306 */
307 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
308
Robert Greenwalt9258c642014-03-26 16:47:06 -0700309 /**
310 * used to add a network request
311 * includes a NetworkRequestInfo
312 */
313 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
314
315 /**
316 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900317 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700318 * cancel it.
319 * includes a NetworkRequestInfo
320 */
321 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
322
323 /**
324 * used to add a network listener - no request
325 * includes a NetworkRequestInfo
326 */
327 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
328
329 /**
330 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400331 * arg1 = UID of caller
332 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700333 */
334 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
335
Robert Greenwalta67be032014-05-16 15:49:14 -0700336 /**
337 * used internally when registering NetworkFactories
338 * obj = Messenger
339 */
340 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
341
Robert Greenwalt27711812014-06-25 16:45:57 -0700342 /**
343 * used internally to expire a wakelock when transitioning
344 * from one net to another. Expire happens when we fail to find
345 * a new network (typically after 1 minute) -
346 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
347 * a replacement network.
348 */
349 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
350
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700351 /**
352 * Used internally to indicate the system is ready.
353 */
354 private static final int EVENT_SYSTEM_READY = 25;
355
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800356 /**
357 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400358 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800359 */
360 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
361
362 /**
363 * used to remove a pending intent and its associated network request.
364 * arg1 = UID of caller
365 * obj = PendingIntent
366 */
367 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
368
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900369 /**
370 * used to specify whether a network should be used even if unvalidated.
371 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
372 * arg2 = whether to remember this choice in the future (1 or 0)
373 * obj = network
374 */
375 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
376
377 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900378 * used to specify whether a network should not be penalized when it becomes unvalidated.
379 */
380 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
381
382 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900383 * used to ask the user to confirm a connection to an unvalidated network.
384 * obj = network
385 */
386 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700387
Erik Klineda4bfa82015-04-30 12:58:40 +0900388 /**
389 * used internally to (re)configure mobile data always-on settings.
390 */
391 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
392
Paul Jensen694f2b82015-06-17 14:15:39 -0400393 /**
394 * used to add a network listener with a pending intent
395 * obj = NetworkRequestInfo
396 */
397 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
398
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900399 /** Handler thread used for both of the handlers below. */
400 @VisibleForTesting
401 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700402 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700403 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700404 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700405 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700406
Mike Lockwood0f79b542009-08-14 14:18:49 -0400407 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800408 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400409
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700410 private PowerManager.WakeLock mNetTransitionWakeLock;
411 private String mNetTransitionWakeLockCausedBy = "";
412 private int mNetTransitionWakeLockSerialNumber;
413 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800414 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700415
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700416 // used in DBG mode to track inet condition reports
417 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
418 private ArrayList mInetLog;
419
Robert Greenwalt434203a2010-10-11 16:00:27 -0700420 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400421 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700422 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700423 private boolean mDefaultProxyDisabled = false;
424
Robert Greenwalt434203a2010-10-11 16:00:27 -0700425 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400426 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427
Jason Monk602b2322013-07-03 17:04:33 -0400428 private PacManager mPacManager = null;
429
Erik Klineda4bfa82015-04-30 12:58:40 +0900430 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700431
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400432 private UserManager mUserManager;
433
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700434 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700435 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700436
Robert Greenwalt50393202011-06-21 17:26:14 -0700437 // the set of network types that can only be enabled by system/sig apps
438 List mProtectedNetworks;
439
John Spurlockbf991a82013-06-24 14:20:23 -0400440 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700441
Wink Savilleab9321d2013-06-29 21:10:57 -0700442 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400443
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900444 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900445 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900446 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900447
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700448 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
449 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700450 private final static int MAX_NET_ID = 65535;
451 private int mNextNetId = MIN_NET_ID;
452
Robert Greenwalt34524f02014-05-18 16:22:10 -0700453 // sequence number of NetworkRequests
454 private int mNextNetworkRequestId = 1;
455
Erik Kline7523eb32015-07-09 18:24:03 +0900456 // NetworkRequest activity String log entries.
457 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
458 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
459
Hugo Benichic2ae2872016-07-11 11:05:12 +0900460 // NetworkInfo blocked and unblocked String log entries
461 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
462 private static final int MAX_NETWORK_INFO_LOGS = 100;
463 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
464
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700465 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
466 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400467 private static class ValidationLog {
468 final Network mNetwork;
469 final String mNetworkExtraInfo;
470 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700471
Paul Jensen0808eb82016-06-03 13:51:21 -0400472 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
473 mNetwork = network;
474 mNetworkExtraInfo = networkExtraInfo;
475 mLog = log;
476 }
477 }
478 private final ArrayDeque<ValidationLog> mValidationLogs =
479 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
480
481 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700482 synchronized(mValidationLogs) {
483 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
484 mValidationLogs.removeLast();
485 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400486 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700487 }
488 }
489
Hugo Benichif9fdf872016-07-28 17:53:06 +0900490 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900491
Erik Kline065ab6e2016-10-02 18:02:14 +0900492 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900493 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900494
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700495 /**
496 * Implements support for the legacy "one network per network type" model.
497 *
498 * We used to have a static array of NetworkStateTrackers, one for each
499 * network type, but that doesn't work any more now that we can have,
500 * for example, more that one wifi network. This class stores all the
501 * NetworkAgentInfo objects that support a given type, but the legacy
502 * API will only see the first one.
503 *
504 * It serves two main purposes:
505 *
506 * 1. Provide information about "the network for a given type" (since this
507 * API only supports one).
508 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
509 * the first network for a given type changes, or if the default network
510 * changes.
511 */
512 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900514 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700517 /**
518 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
519 * Each list holds references to all NetworkAgentInfos that are used to
520 * satisfy requests for that network type.
521 *
522 * This array is built out at startup such that an unsupported network
523 * doesn't get an ArrayList instance, making this a tristate:
524 * unsupported, supported but not active and active.
525 *
526 * The actual lists are populated when we scan the network types that
527 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900528 *
529 * Threading model:
530 * - addSupportedType() is only called in the constructor
531 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
532 * They are therefore not thread-safe with respect to each other.
533 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
534 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
535 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700536 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900537 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538
539 public LegacyTypeTracker() {
540 mTypeLists = (ArrayList<NetworkAgentInfo>[])
541 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
542 }
543
544 public void addSupportedType(int type) {
545 if (mTypeLists[type] != null) {
546 throw new IllegalStateException(
547 "legacy list for type " + type + "already initialized");
548 }
549 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
550 }
551
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 public boolean isTypeSupported(int type) {
553 return isNetworkTypeValid(type) && mTypeLists[type] != null;
554 }
555
556 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900557 synchronized (mTypeLists) {
558 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
559 return mTypeLists[type].get(0);
560 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900562 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
564
Robert Greenwalt8d482522015-06-24 13:23:42 -0700565 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900566 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900567 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700568 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900570 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900571 }
572 }
573
574 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 public void add(int type, NetworkAgentInfo nai) {
576 if (!isTypeSupported(type)) {
577 return; // Invalid network type.
578 }
579 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
580
581 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
582 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700583 return;
584 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900585 synchronized (mTypeLists) {
586 list.add(nai);
587 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900588
589 // 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 +0900590 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900591 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700592 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
593 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700594 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 }
596
Lorenzo Colittia793a672014-07-31 23:20:17 +0900597 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900598 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
600 if (list == null || list.isEmpty()) {
601 return;
602 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900603 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604
Hugo Benichi78caa2582016-06-21 09:48:07 +0900605 synchronized (mTypeLists) {
606 if (!list.remove(nai)) {
607 return;
608 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609 }
610
Robert Greenwalt8d482522015-06-24 13:23:42 -0700611 final DetailedState state = DetailedState.DISCONNECTED;
612
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900613 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700614 maybeLogBroadcast(nai, state, type, wasDefault);
615 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616 }
617
618 if (!list.isEmpty() && wasFirstNetwork) {
619 if (DBG) log("Other network available for type " + type +
620 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700622 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
623 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 }
625 }
626
627 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900628 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
629 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900631 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 }
633 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700634
Robert Greenwalt8d482522015-06-24 13:23:42 -0700635 // send out another legacy broadcast - currently only used for suspend/unsuspend
636 // toggle
637 public void update(NetworkAgentInfo nai) {
638 final boolean isDefault = isDefaultNetwork(nai);
639 final DetailedState state = nai.networkInfo.getDetailedState();
640 for (int type = 0; type < mTypeLists.length; type++) {
641 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700642 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900643 final boolean isFirst = contains && (nai == list.get(0));
644 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 maybeLogBroadcast(nai, state, type, isDefault);
646 sendLegacyNetworkBroadcast(nai, state, type);
647 }
648 }
649 }
650
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 private String naiToString(NetworkAgentInfo nai) {
652 String name = (nai != null) ? nai.name() : "null";
653 String state = (nai.networkInfo != null) ?
654 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
655 "???/???";
656 return name + " " + state;
657 }
658
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700659 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900660 pw.println("mLegacyTypeTracker:");
661 pw.increaseIndent();
662 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700663 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900664 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900666 pw.println();
667 pw.println("Current state:");
668 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900669 synchronized (mTypeLists) {
670 for (int type = 0; type < mTypeLists.length; type++) {
671 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
672 for (NetworkAgentInfo nai : mTypeLists[type]) {
673 pw.println(type + " " + naiToString(nai));
674 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900675 }
676 }
677 pw.decreaseIndent();
678 pw.decreaseIndent();
679 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700680 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700681 }
682 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
683
Jeff Sharkey899223b2012-08-04 15:24:58 -0700684 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700685 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900686 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
687 }
688
689 @VisibleForTesting
690 protected ConnectivityService(Context context, INetworkManagementService netManager,
691 INetworkStatsService statsService, INetworkPolicyManager policyManager,
692 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800693 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800694
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900695 mSystemProperties = getSystemProperties();
696
Hugo Benichif9fdf872016-07-28 17:53:06 +0900697 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900698 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900699 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900700 mNetworkRequests.put(mDefaultRequest, defaultNRI);
701 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900702
703 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900704 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700705
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900706 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900707 mHandlerThread.start();
708 mHandler = new InternalHandler(mHandlerThread.getLooper());
709 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700710
Jeremy Joslin79294842014-12-03 17:15:28 -0800711 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
712 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
713
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900714 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900715
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700716 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700717 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800718 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700719 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700720 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700721 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700722
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700723 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600724 mPolicyManager.setConnectivityListener(mPolicyListener);
725 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700726 } catch (RemoteException e) {
727 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700728 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 }
730
731 final PowerManager powerManager = (PowerManager) context.getSystemService(
732 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700733 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
734 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
735 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800736 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700737
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700738 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700739
Wink Saville51f456f2013-04-23 14:26:51 -0700740 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900741 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700742 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700743 String[] naStrings = context.getResources().getStringArray(
744 com.android.internal.R.array.networkAttributes);
745 for (String naString : naStrings) {
746 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700747 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700748 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700749 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800750 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700751 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700752 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700753 }
Wink Saville51f456f2013-04-23 14:26:51 -0700754 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
755 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
756 n.type);
757 continue;
758 }
Wink Saville975c8482011-04-07 14:23:45 -0700759 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800760 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700761 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700762 continue;
763 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700764 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700765
Wink Saville975c8482011-04-07 14:23:45 -0700766 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700767 mNetworksDefined++;
768 } catch(Exception e) {
769 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700770 }
771 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700772
773 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
774 if (mNetConfigs[TYPE_VPN] == null) {
775 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
776 // don't need to add TYPE_VPN to mNetConfigs.
777 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
778 mNetworksDefined++; // used only in the log() statement below.
779 }
780
Wink Saville5e56bc52013-07-29 15:00:57 -0700781 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700782
Robert Greenwalt50393202011-06-21 17:26:14 -0700783 mProtectedNetworks = new ArrayList<Integer>();
784 int[] protectedNetworks = context.getResources().getIntArray(
785 com.android.internal.R.array.config_protectedNetworks);
786 for (int p : protectedNetworks) {
787 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
788 mProtectedNetworks.add(p);
789 } else {
790 if (DBG) loge("Ignoring protectedNetwork " + p);
791 }
792 }
793
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900794 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
795 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700796
Christopher Wiley497c1472016-10-11 13:26:03 -0700797 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
798 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800799
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700800 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
801
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700802 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700803 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100804 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700805 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700806 intentFilter.addAction(Intent.ACTION_USER_ADDED);
807 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000808 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700809 mContext.registerReceiverAsUser(
810 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000811 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
812 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900813
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700814 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700815 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700816 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700817 } catch (RemoteException e) {
818 loge("Error registering observer :" + e);
819 }
820
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700821 if (DBG) {
822 mInetLog = new ArrayList();
823 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700824
Erik Klineda4bfa82015-04-30 12:58:40 +0900825 mSettingsObserver = new SettingsObserver(mContext, mHandler);
826 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800827
John Spurlockbf991a82013-06-24 14:20:23 -0400828 mDataConnectionStats = new DataConnectionStats(mContext);
829 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400830
Jason Monkdecd2952013-10-10 14:02:51 -0400831 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700832
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400833 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900834
835 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900836 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
837 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900838
839 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
840 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
841 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
842 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
843 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
844 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
845 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900846
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900847 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900848 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900849 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700851
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900852 private NetworkRequest createInternetRequestForTransport(
853 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900854 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900855 netCap.addCapability(NET_CAPABILITY_INTERNET);
856 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900857 if (transportType > -1) {
858 netCap.addTransportType(transportType);
859 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900860 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900861 }
862
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900863 // Used only for testing.
864 // TODO: Delete this and either:
865 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
866 // changing ContentResolver to make registerContentObserver non-final).
867 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
868 // by subclassing SettingsObserver.
869 @VisibleForTesting
870 void updateMobileDataAlwaysOn() {
871 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
872 }
873
Erik Klineda4bfa82015-04-30 12:58:40 +0900874 private void handleMobileDataAlwaysOn() {
875 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900876 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900877 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
878 if (enable == isEnabled) {
879 return; // Nothing to do.
880 }
881
882 if (enable) {
883 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900884 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900885 } else {
886 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
887 }
888 }
889
890 private void registerSettingsCallbacks() {
891 // Watch for global HTTP proxy changes.
892 mSettingsObserver.observe(
893 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
894 EVENT_APPLY_GLOBAL_HTTP_PROXY);
895
896 // Watch for whether or not to keep mobile data always on.
897 mSettingsObserver.observe(
898 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
899 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
900 }
901
Robert Greenwalt34524f02014-05-18 16:22:10 -0700902 private synchronized int nextNetworkRequestId() {
903 return mNextNetworkRequestId++;
904 }
905
Paul Jensen67b0b072015-06-10 11:22:17 -0400906 @VisibleForTesting
907 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400908 synchronized (mNetworkForNetId) {
909 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
910 int netId = mNextNetId;
911 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
912 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500913 if (!mNetIdInUse.get(netId)) {
914 mNetIdInUse.put(netId, true);
915 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400916 }
917 }
918 }
919 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700920 }
921
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600922 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800923 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600924 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
925 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800926 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600927 state = nai.getNetworkState();
928 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800929 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600930 final NetworkInfo info = new NetworkInfo(networkType, 0,
931 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800932 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
933 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600934 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
935 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600937 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600938 return state;
939 } else {
940 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800941 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400942 }
943
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800944 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
945 if (network == null) {
946 return null;
947 }
948 synchronized (mNetworkForNetId) {
949 return mNetworkForNetId.get(network.netId);
950 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600951 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900953 private Network[] getVpnUnderlyingNetworks(int uid) {
954 if (!mLockdownEnabled) {
955 int user = UserHandle.getUserId(uid);
956 synchronized (mVpns) {
957 Vpn vpn = mVpns.get(user);
958 if (vpn != null && vpn.appliesToUid(uid)) {
959 return vpn.getUnderlyingNetworks();
960 }
961 }
962 }
963 return null;
964 }
965
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800966 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400967 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800968
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900969 final Network[] networks = getVpnUnderlyingNetworks(uid);
970 if (networks != null) {
971 // getUnderlyingNetworks() returns:
972 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
973 // empty array => the VPN explicitly said "no default network".
974 // non-empty array => the VPN specified one or more default networks; we use the
975 // first one.
976 if (networks.length > 0) {
977 nai = getNetworkAgentInfoForNetwork(networks[0]);
978 } else {
979 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800980 }
981 }
982
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600984 return nai.getNetworkState();
985 } else {
986 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800987 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400988 }
989
990 /**
991 * Check if UID should be blocked from using the network with the given LinkProperties.
992 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600993 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
994 boolean ignoreBlocked) {
995 // Networks aren't blocked when ignoring blocked status
996 if (ignoreBlocked) return false;
997 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700998 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600999
1000 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001001 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001002
Robin Lee17e61832016-05-09 13:46:28 +01001003 synchronized (mVpns) {
1004 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1005 if (vpn != null && vpn.isBlockingUid(uid)) {
1006 return true;
1007 }
1008 }
1009
Robert Greenwalt12e67352014-05-13 21:41:06 -07001010 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001011 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001012 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001013 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001014 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001015
Felipe Lemed31a97f2016-05-06 14:53:50 -07001016 boolean allowed = true;
1017 // Check Data Saver Mode first...
1018 if (networkMetered) {
1019 if ((uidRules & RULE_REJECT_METERED) != 0) {
1020 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1021 // Explicitly blacklisted.
1022 allowed = false;
1023 } else {
1024 allowed = !mRestrictBackground
1025 || (uidRules & RULE_ALLOW_METERED) != 0
1026 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1027 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1028 + " mRestrictBackground=" + mRestrictBackground
1029 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1030 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1031 + ": " + allowed);
1032 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001033 }
Felipe Leme781ba142016-05-09 16:24:48 -07001034 // ...then power restrictions.
1035 if (allowed) {
1036 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001037 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001038 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001039 }
1040 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001041 }
1042
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001043 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001044 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1045 return;
1046 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001047 boolean removed = false;
1048 boolean added = false;
1049 synchronized (mBlockedAppUids) {
1050 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1051 added = true;
1052 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1053 removed = true;
1054 }
1055 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001056 if (added) {
1057 log("Returning blocked NetworkInfo to uid=" + uid);
1058 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1059 } else if (removed) {
1060 log("Returning unblocked NetworkInfo to uid=" + uid);
1061 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1062 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001063 }
1064
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001065 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001066 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1067 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1068 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1069 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001070 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001071 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001072 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1073
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001074 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001075 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001077 if (mLockdownTracker != null) {
1078 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001079 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001080
1081 // TODO: apply metered state closer to NetworkAgentInfo
1082 final long token = Binder.clearCallingIdentity();
1083 try {
1084 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1085 } catch (RemoteException e) {
1086 } finally {
1087 Binder.restoreCallingIdentity(token);
1088 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001089 }
1090
1091 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 * Return NetworkInfo for the active (i.e., connected) network interface.
1093 * It is assumed that at most one network is active at a time. If more
1094 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001095 * @return the info for the active network, or {@code null} if none is
1096 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001098 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001100 enforceAccessPermission();
1101 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001102 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001103 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001104 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1105 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
1107
Paul Jensen31a94f42015-02-13 14:18:39 -05001108 @Override
1109 public Network getActiveNetwork() {
1110 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001111 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001112 }
1113
1114 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001116 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001117 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001118 }
1119
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001121 final int user = UserHandle.getUserId(uid);
1122 int vpnNetId = NETID_UNSET;
1123 synchronized (mVpns) {
1124 final Vpn vpn = mVpns.get(user);
1125 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1126 }
1127 NetworkAgentInfo nai;
1128 if (vpnNetId != NETID_UNSET) {
1129 synchronized (mNetworkForNetId) {
1130 nai = mNetworkForNetId.get(vpnNetId);
1131 }
1132 if (nai != null) return nai.network;
1133 }
1134 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001135 if (nai != null
1136 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1137 nai = null;
1138 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001139 return nai != null ? nai.network : null;
1140 }
1141
Lorenzo Colitti18660282016-07-04 12:55:44 +09001142 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001143 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1144 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001145 final int uid = Binder.getCallingUid();
1146 NetworkState state = getUnfilteredActiveNetworkState(uid);
1147 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001148 }
1149
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001150 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001151 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001152 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001153 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001154 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001155 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001156 }
1157
1158 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 public NetworkInfo getNetworkInfo(int networkType) {
1160 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001161 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001162 if (getVpnUnderlyingNetworks(uid) != null) {
1163 // A VPN is active, so we may need to return one of its underlying networks. This
1164 // information is not available in LegacyTypeTracker, so we have to get it from
1165 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001166 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001167 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001168 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001169 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001170 }
1171 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001172 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001173 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 }
1175
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001176 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001177 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001179 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001180 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001181 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001182 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001183 return state.networkInfo;
1184 } else {
1185 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001186 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001187 }
1188
1189 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 public NetworkInfo[] getAllNetworkInfo() {
1191 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001192 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001193 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1194 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001195 NetworkInfo info = getNetworkInfo(networkType);
1196 if (info != null) {
1197 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001200 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 }
1202
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001203 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001204 public Network getNetworkForType(int networkType) {
1205 enforceAccessPermission();
1206 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001207 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1208 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001209 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001210 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001211 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001212 }
1213
1214 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001215 public Network[] getAllNetworks() {
1216 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001217 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001218 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001219 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001220 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001221 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001222 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001223 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001224 }
1225
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001226 @Override
1227 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1228 // The basic principle is: if an app's traffic could possibly go over a
1229 // network, without the app doing anything multinetwork-specific,
1230 // (hence, by "default"), then include that network's capabilities in
1231 // the array.
1232 //
1233 // In the normal case, app traffic only goes over the system's default
1234 // network connection, so that's the only network returned.
1235 //
1236 // With a VPN in force, some app traffic may go into the VPN, and thus
1237 // over whatever underlying networks the VPN specifies, while other app
1238 // traffic may go over the system default network (e.g.: a split-tunnel
1239 // VPN, or an app disallowed by the VPN), so the set of networks
1240 // returned includes the VPN's underlying networks and the system
1241 // default.
1242 enforceAccessPermission();
1243
1244 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1245
1246 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001247 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001248 if (nc != null) {
1249 result.put(nai.network, nc);
1250 }
1251
1252 if (!mLockdownEnabled) {
1253 synchronized (mVpns) {
1254 Vpn vpn = mVpns.get(userId);
1255 if (vpn != null) {
1256 Network[] networks = vpn.getUnderlyingNetworks();
1257 if (networks != null) {
1258 for (Network network : networks) {
1259 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001260 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001261 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001262 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001263 }
1264 }
1265 }
1266 }
1267 }
1268 }
1269
1270 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1271 out = result.values().toArray(out);
1272 return out;
1273 }
1274
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001275 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001276 public boolean isNetworkSupported(int networkType) {
1277 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001278 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001279 }
1280
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001281 /**
1282 * Return LinkProperties for the active (i.e., connected) default
1283 * network interface. It is assumed that at most one default network
1284 * is active at a time. If more than one is active, it is indeterminate
1285 * which will be returned.
1286 * @return the ip properties for the active network, or {@code null} if
1287 * none is active
1288 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001289 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001290 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001291 enforceAccessPermission();
1292 final int uid = Binder.getCallingUid();
1293 NetworkState state = getUnfilteredActiveNetworkState(uid);
1294 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001295 }
1296
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001297 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001298 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001299 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001300 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1301 if (nai != null) {
1302 synchronized (nai) {
1303 return new LinkProperties(nai.linkProperties);
1304 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001305 }
1306 return null;
1307 }
1308
Robert Greenwalt12e67352014-05-13 21:41:06 -07001309 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001310 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001311 public LinkProperties getLinkProperties(Network network) {
1312 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001313 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001314 if (nai != null) {
1315 synchronized (nai) {
1316 return new LinkProperties(nai.linkProperties);
1317 }
1318 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001319 return null;
1320 }
1321
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001322 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001323 if (nai != null) {
1324 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001325 if (nai.networkCapabilities != null) {
1326 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001327 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001328 }
1329 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001330 return null;
1331 }
1332
1333 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001334 public NetworkCapabilities getNetworkCapabilities(Network network) {
1335 enforceAccessPermission();
1336 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1337 }
1338
1339 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001340 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001341 // Require internal since we're handing out IMSI details
1342 enforceConnectivityInternalPermission();
1343
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001344 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001345 for (Network network : getAllNetworks()) {
1346 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1347 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001348 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001349 }
1350 }
1351 return result.toArray(new NetworkState[result.size()]);
1352 }
1353
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001354 @Override
1355 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1356 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001357 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001358 final long token = Binder.clearCallingIdentity();
1359 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001360 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1361 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001362 try {
1363 return mPolicyManager.getNetworkQuotaInfo(state);
1364 } catch (RemoteException e) {
1365 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001366 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001367 return null;
1368 } finally {
1369 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001370 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001371 }
1372
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001373 @Override
1374 public boolean isActiveNetworkMetered() {
1375 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001376
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001377 final NetworkInfo info = getActiveNetworkInfo();
1378 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001379 }
1380
Jeff Sharkey216c1812012-08-05 14:29:23 -07001381 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1382 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001383 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001384 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001385 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001386 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001387 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001388
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001389 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 * Ensure that a network route exists to deliver traffic to the specified
1391 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001392 * @param networkType the type of the network over which traffic to the
1393 * specified host is to be routed
1394 * @param hostAddress the IP address of the host to which the route is
1395 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 * @return {@code true} on success, {@code false} on failure
1397 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001398 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001399 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001401 if (mProtectedNetworks.contains(networkType)) {
1402 enforceConnectivityInternalPermission();
1403 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001404
Chad Brubakerc0234532014-02-14 13:24:29 -08001405 InetAddress addr;
1406 try {
1407 addr = InetAddress.getByAddress(hostAddress);
1408 } catch (UnknownHostException e) {
1409 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1410 return false;
1411 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001414 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 return false;
1416 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001417
1418 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1419 if (nai == null) {
1420 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1421 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1422 } else {
1423 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1424 }
1425 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001426 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001427
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001428 DetailedState netState;
1429 synchronized (nai) {
1430 netState = nai.networkInfo.getDetailedState();
1431 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001432
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001433 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001434 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001435 log("requestRouteToHostAddress on down network "
1436 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001437 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001438 }
1439 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001441
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001442 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001443 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001444 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001445 LinkProperties lp;
1446 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001447 synchronized (nai) {
1448 lp = nai.linkProperties;
1449 netId = nai.network.netId;
1450 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001451 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001452 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1453 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001454 } finally {
1455 Binder.restoreCallingIdentity(token);
1456 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001457 }
1458
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001459 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001460 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001461 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001462 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001463 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001464 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001465 if (bestRoute.getGateway().equals(addr)) {
1466 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001467 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001468 } else {
1469 // if we will connect to this through another route, add a direct route
1470 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001471 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001472 }
1473 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001474 if (DBG) log("Adding legacy route " + bestRoute +
1475 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001476 try {
1477 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1478 } catch (Exception e) {
1479 // never crash - catch them all
1480 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001481 return false;
1482 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001483 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 }
1485
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001486 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1487 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001488 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001489 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001490 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001491 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001492 }
1493
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001494 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001495 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001496 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001497 if (oldRules == uidRules) return;
1498
Felipe Leme781ba142016-05-09 16:24:48 -07001499 if (uidRules == RULE_NONE) {
1500 mUidRules.delete(uid);
1501 } else {
1502 mUidRules.put(uid, uidRules);
1503 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001504 }
1505
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001506 // TODO: notify UID when it has requested targeted updates
1507 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001508
1509 @Override
1510 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001511 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001512 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001513 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001514 }
1515
1516 synchronized (mRulesLock) {
1517 mMeteredIfaces.clear();
1518 for (String iface : meteredIfaces) {
1519 mMeteredIfaces.add(iface);
1520 }
1521 }
1522 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001523
1524 @Override
1525 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1526 // caller is NPMS, since we only register with them
1527 if (LOGD_RULES) {
1528 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1529 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001530
1531 synchronized (mRulesLock) {
1532 mRestrictBackground = restrictBackground;
1533 }
1534
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001535 if (restrictBackground) {
1536 log("onRestrictBackgroundChanged(true): disabling tethering");
1537 mTethering.untetherAll();
1538 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001539 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001540
1541 @Override
1542 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1543 if (LOGD_RULES) {
1544 // caller is NPMS, since we only register with them
1545 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1546 + whitelisted + ")");
1547 }
1548 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001549 @Override
1550 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1551 if (LOGD_RULES) {
1552 // caller is NPMS, since we only register with them
1553 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1554 + blacklisted + ")");
1555 }
1556 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001557 };
1558
Robin Lee3b3dd942015-05-12 18:14:58 +01001559 /**
1560 * Require that the caller is either in the same user or has appropriate permission to interact
1561 * across users.
1562 *
1563 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1564 */
1565 private void enforceCrossUserPermission(int userId) {
1566 if (userId == UserHandle.getCallingUserId()) {
1567 // Not a cross-user call.
1568 return;
1569 }
1570 mContext.enforceCallingOrSelfPermission(
1571 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1572 "ConnectivityService");
1573 }
1574
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001575 private void enforceInternetPermission() {
1576 mContext.enforceCallingOrSelfPermission(
1577 android.Manifest.permission.INTERNET,
1578 "ConnectivityService");
1579 }
1580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001582 mContext.enforceCallingOrSelfPermission(
1583 android.Manifest.permission.ACCESS_NETWORK_STATE,
1584 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586
1587 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001588 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001591 private void enforceTetherAccessPermission() {
1592 mContext.enforceCallingOrSelfPermission(
1593 android.Manifest.permission.ACCESS_NETWORK_STATE,
1594 "ConnectivityService");
1595 }
1596
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001597 private void enforceConnectivityInternalPermission() {
1598 mContext.enforceCallingOrSelfPermission(
1599 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1600 "ConnectivityService");
1601 }
1602
Hugo Benichi514da602016-07-19 15:59:27 +09001603 private void enforceConnectivityRestrictedNetworksPermission() {
1604 try {
1605 mContext.enforceCallingOrSelfPermission(
1606 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1607 "ConnectivityService");
1608 return;
1609 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1610 enforceConnectivityInternalPermission();
1611 }
1612
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001613 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001614 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001615 }
1616
Lorenzo Colitti18660282016-07-04 12:55:44 +09001617 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001618 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001619 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001620 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001621 }
1622
1623 private void sendInetConditionBroadcast(NetworkInfo info) {
1624 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1625 }
1626
Wink Saville628b0852011-08-04 15:01:58 -07001627 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001628 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001629 info = new NetworkInfo(info);
1630 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001631 }
1632
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001633 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001634 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001635 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 if (info.isFailover()) {
1637 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1638 info.setFailover(false);
1639 }
1640 if (info.getReason() != null) {
1641 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1642 }
1643 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001644 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1645 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001647 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001648 return intent;
1649 }
1650
1651 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1652 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1653 }
1654
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001655 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001656 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1657 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1658 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001659 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001660 final long ident = Binder.clearCallingIdentity();
1661 try {
1662 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1663 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1664 } finally {
1665 Binder.restoreCallingIdentity(ident);
1666 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001667 }
1668
Mike Lockwood0f79b542009-08-14 14:18:49 -04001669 private void sendStickyBroadcast(Intent intent) {
1670 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001671 if (!mSystemReady) {
1672 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001673 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001674 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001675 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001676 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001677 }
1678
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001679 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001680 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001681 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001682 final NetworkInfo ni = intent.getParcelableExtra(
1683 ConnectivityManager.EXTRA_NETWORK_INFO);
1684 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1685 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1686 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001687 } else {
1688 BroadcastOptions opts = BroadcastOptions.makeBasic();
1689 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1690 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001691 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001692 final IBatteryStats bs = BatteryStatsService.getService();
1693 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001694 bs.noteConnectivityChanged(intent.getIntExtra(
1695 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1696 ni != null ? ni.getState().toString() : "?");
1697 } catch (RemoteException e) {
1698 }
1699 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001700 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001701 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001702 } finally {
1703 Binder.restoreCallingIdentity(ident);
1704 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001705 }
1706 }
1707
1708 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001709 loadGlobalProxy();
1710
Mike Lockwood0f79b542009-08-14 14:18:49 -04001711 synchronized(this) {
1712 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001713 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001714 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001715 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001716 }
1717 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001718 // load the global proxy at startup
1719 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001720
Robin Lee244ce8e2016-01-05 18:03:46 +00001721 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1722 // for user to unlock device too.
1723 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001724
Erik Klineda4bfa82015-04-30 12:58:40 +09001725 // Configure whether mobile data is always on.
1726 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1727
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001728 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001729
1730 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
1732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001735 *
1736 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001737 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001738 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1740 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001741
1742 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001743 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001744
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 if (networkAgent.networkCapabilities.hasTransport(
1746 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001747 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1748 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001749 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001750 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001751 } else if (networkAgent.networkCapabilities.hasTransport(
1752 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001753 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1754 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001755 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001756 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001757 } else {
1758 // do not track any other networks
1759 timeout = 0;
1760 }
1761
Robert Greenwalt7b816022014-04-18 15:25:25 -07001762 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001763 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001764 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001765 } catch (Exception e) {
1766 // You shall not crash!
1767 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001768 }
1769 }
1770 }
1771
1772 /**
1773 * Remove data activity tracking when network disconnects.
1774 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001775 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1776 final String iface = networkAgent.linkProperties.getInterfaceName();
1777 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001778
Robert Greenwalt7b816022014-04-18 15:25:25 -07001779 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1780 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001781 try {
1782 // the call fails silently if no idletimer setup for this interface
1783 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001784 } catch (Exception e) {
1785 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001786 }
1787 }
1788 }
1789
1790 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001791 * Reads the network specific MTU size from reources.
1792 * and set it on it's iface.
1793 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001794 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1795 final String iface = newLp.getInterfaceName();
1796 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001797 if (oldLp == null && mtu == 0) {
1798 // Silently ignore unset MTU value.
1799 return;
1800 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001801 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1802 if (VDBG) log("identical MTU - not setting");
1803 return;
1804 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001805 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001806 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001807 return;
1808 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001809
w1997615afd812014-08-05 15:18:11 -07001810 // Cannot set MTU without interface name
1811 if (TextUtils.isEmpty(iface)) {
1812 loge("Setting MTU size with null iface.");
1813 return;
1814 }
1815
Robert Greenwalt7b816022014-04-18 15:25:25 -07001816 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001817 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001818 mNetd.setMtu(iface, mtu);
1819 } catch (Exception e) {
1820 Slog.e(TAG, "exception in setMtu()" + e);
1821 }
1822 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001823
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001824 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001825 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1826
1827 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001828 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001829 protected MockableSystemProperties getSystemProperties() {
1830 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001831 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001832
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001833 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1834 if (isDefaultNetwork(nai) == false) {
1835 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001836 }
1837
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001838 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1839 String[] values = null;
1840 if (tcpBufferSizes != null) {
1841 values = tcpBufferSizes.split(",");
1842 }
1843
1844 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001845 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001846 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1847 values = tcpBufferSizes.split(",");
1848 }
1849
1850 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1851
1852 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001853 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001854
1855 final String prefix = "/sys/kernel/ipv4/tcp_";
1856 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1857 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1858 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1859 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1860 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1861 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1862 mCurrentTcpBufferSizes = tcpBufferSizes;
1863 } catch (IOException e) {
1864 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001865 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001866
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001867 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001868 Settings.Global.TCP_DEFAULT_INIT_RWND,
1869 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001870 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1871 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001872 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001873 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001874 }
1875
Mattias Falk8b47b362011-08-23 14:15:13 +02001876 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001877 /*
1878 * Tell the VMs to toss their DNS caches
1879 */
1880 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1881 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001882 /*
1883 * Connectivity events can happen before boot has completed ...
1884 */
1885 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001886 final long ident = Binder.clearCallingIdentity();
1887 try {
1888 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1889 } finally {
1890 Binder.restoreCallingIdentity(ident);
1891 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001892 }
1893
Robert Greenwalt562cc542014-05-15 18:07:26 -07001894 @Override
1895 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001896 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001897 NETWORK_RESTORE_DELAY_PROP_NAME);
1898 if(restoreDefaultNetworkDelayStr != null &&
1899 restoreDefaultNetworkDelayStr.length() != 0) {
1900 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001901 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001902 } catch (NumberFormatException e) {
1903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001905 // if the system property isn't set, use the value for the apn type
1906 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1907
1908 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1909 (mNetConfigs[networkType] != null)) {
1910 ret = mNetConfigs[networkType].restoreTime;
1911 }
1912 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
1914
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001915 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001916 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001917 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001918 }
1919 return false;
1920 }
1921
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001922 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1923 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1924 final long DIAG_TIME_MS = 5000;
1925 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1926 // Start gathering diagnostic information.
1927 netDiags.add(new NetworkDiagnostics(
1928 nai.network,
1929 new LinkProperties(nai.linkProperties), // Must be a copy.
1930 DIAG_TIME_MS));
1931 }
1932
1933 for (NetworkDiagnostics netDiag : netDiags) {
1934 pw.println();
1935 netDiag.waitForMeasurements();
1936 netDiag.dump(pw);
1937 }
1938 }
1939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001941 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1942 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001943 if (mContext.checkCallingOrSelfPermission(
1944 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001946 pw.println("Permission Denial: can't dump ConnectivityService " +
1947 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1948 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 return;
1950 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001951
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001952 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001953 dumpNetworkDiagnostics(pw);
1954 return;
1955 }
Erik Kline379747a2015-06-05 17:47:34 +09001956
Lorenzo Colittie3805462015-06-03 11:18:24 +09001957 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001958 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001959 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001960 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001961 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001962 pw.println();
1963
Paul Jensen85cf78e2015-06-25 13:25:07 -04001964 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001965 pw.print("Active default network: ");
1966 if (defaultNai == null) {
1967 pw.println("none");
1968 } else {
1969 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001971 pw.println();
1972
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001973 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001974 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001975 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1976 pw.println(nai.toString());
1977 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001978 pw.println(String.format(
1979 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1980 nai.numForegroundNetworkRequests(),
1981 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1982 nai.numBackgroundNetworkRequests(),
1983 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001984 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001985 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1986 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001987 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001988 pw.decreaseIndent();
1989 pw.println("Lingered:");
1990 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001991 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001992 pw.decreaseIndent();
1993 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001994 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001995 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001996 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001997
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001998 pw.println("Metered Interfaces:");
1999 pw.increaseIndent();
2000 for (String value : mMeteredIfaces) {
2001 pw.println(value);
2002 }
2003 pw.decreaseIndent();
2004 pw.println();
2005
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002006 pw.print("Restrict background: ");
2007 pw.println(mRestrictBackground);
2008 pw.println();
2009
Felipe Leme46c4fc32016-05-04 09:21:43 -07002010 pw.println("Status for known UIDs:");
2011 pw.increaseIndent();
2012 final int size = mUidRules.size();
2013 for (int i = 0; i < size; i++) {
2014 final int uid = mUidRules.keyAt(i);
2015 pw.print("UID=");
2016 pw.print(uid);
2017 final int uidRules = mUidRules.get(uid, RULE_NONE);
2018 pw.print(" rules=");
2019 pw.print(uidRulesToString(uidRules));
2020 pw.println();
2021 }
2022 pw.println();
2023 pw.decreaseIndent();
2024
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002025 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002026 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002027 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2028 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002029 }
2030 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002031 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002032
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002033 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002034
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002035 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002036 pw.print("mNetTransitionWakeLock: currently " +
2037 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2038 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2039 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2040 } else {
2041 pw.println(", last requested never");
2042 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002043 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002044
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002045 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002046 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002047
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002048 pw.println();
2049 mKeepaliveTracker.dump(pw);
2050
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002051 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002052 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002053
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002054 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09002055 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002056 pw.println();
2057 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002058 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002059 for(int i = 0; i < mInetLog.size(); i++) {
2060 pw.println(mInetLog.get(i));
2061 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002062 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002063 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002064
2065 if (argsContain(args, "--short") == false) {
2066 pw.println();
2067 synchronized (mValidationLogs) {
2068 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002069 for (ValidationLog p : mValidationLogs) {
2070 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002071 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002072 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002073 pw.decreaseIndent();
2074 }
2075 }
Erik Kline7523eb32015-07-09 18:24:03 +09002076
2077 pw.println();
2078 pw.println("mNetworkRequestInfoLogs (most recent first):");
2079 pw.increaseIndent();
2080 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2081 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002082
2083 pw.println();
2084 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2085 pw.increaseIndent();
2086 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2087 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002091 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002092 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002093 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002094 if (officialNai != null && officialNai.equals(nai)) return true;
2095 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002096 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002097 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002098 " - " + nai);
2099 }
2100 return false;
2101 }
2102
Robert Greenwalt42acef32009-08-12 16:08:25 -07002103 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002104 private class NetworkStateTrackerHandler extends Handler {
2105 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002106 super(looper);
2107 }
2108
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002109 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002111 default:
2112 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002113 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 handleAsyncChannelHalfConnect(msg);
2115 break;
2116 }
2117 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2118 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2119 if (nai != null) nai.asyncChannel.disconnect();
2120 break;
2121 }
2122 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2123 handleAsyncChannelDisconnected(msg);
2124 break;
2125 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002126 }
2127 return true;
2128 }
2129
2130 private void maybeHandleNetworkAgentMessage(Message msg) {
2131 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2132 if (nai == null) {
2133 if (VDBG) {
2134 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2135 log(String.format("%s from unknown NetworkAgent", what));
2136 }
2137 return;
2138 }
2139
2140 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002141 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002142 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2143 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002144 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2145 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002146 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002147 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002148 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002149 break;
2150 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002151 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 if (VDBG) {
2153 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002154 "; created=" + nai.created +
2155 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002156 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002157 LinkProperties oldLp = nai.linkProperties;
2158 synchronized (nai) {
2159 nai.linkProperties = (LinkProperties)msg.obj;
2160 }
Robin Lee585e2482016-05-01 23:00:00 +01002161 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002162 break;
2163 }
2164 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002165 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 updateNetworkInfo(nai, info);
2167 break;
2168 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002169 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002170 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002171 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002172 break;
2173 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002174 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002175 try {
2176 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002177 } catch (Exception e) {
2178 // Never crash!
2179 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002180 }
2181 break;
2182 }
2183 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002184 try {
2185 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002186 } catch (Exception e) {
2187 // Never crash!
2188 loge("Exception in removeVpnUidRanges: " + e);
2189 }
2190 break;
2191 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002192 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002193 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2194 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002195 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002196 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002197 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002198 break;
2199 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002200 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002201 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2202 break;
2203 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002204 }
2205 }
2206
2207 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2208 switch (msg.what) {
2209 default:
2210 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002211 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002212 final NetworkAgentInfo nai;
2213 synchronized (mNetworkForNetId) {
2214 nai = mNetworkForNetId.get(msg.arg2);
2215 }
2216 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002217 final boolean valid =
2218 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002219 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002220 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2221 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002222 if (valid != nai.lastValidated) {
2223 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002224 nai.lastValidated = valid;
2225 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002226 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002227 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2228 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002229 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002230 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002231 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002232 Bundle redirectUrlBundle = new Bundle();
2233 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002234 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002235 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002236 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002237 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002238 if (wasValidated && !nai.lastValidated) {
2239 handleNetworkUnvalidated(nai);
2240 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002241 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002242 break;
2243 }
Paul Jensen869868be2014-05-15 10:33:05 -04002244 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002245 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002246 final boolean visible = (msg.arg1 != 0);
2247 final NetworkAgentInfo nai;
2248 synchronized (mNetworkForNetId) {
2249 nai = mNetworkForNetId.get(netId);
2250 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002251 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002252 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002253 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002254 nai.lastCaptivePortalDetected = visible;
2255 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002256 if (nai.lastCaptivePortalDetected &&
2257 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2258 if (DBG) log("Avoiding captive portal network: " + nai.name());
2259 nai.asyncChannel.sendMessage(
2260 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2261 teardownUnneededNetwork(nai);
2262 break;
2263 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002264 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002265 }
2266 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002267 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002268 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002269 if (nai == null) {
2270 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2271 break;
2272 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002273 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002274 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002275 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002276 }
Paul Jensen869868be2014-05-15 10:33:05 -04002277 }
Paul Jensen869868be2014-05-15 10:33:05 -04002278 break;
2279 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002280 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002281 return true;
2282 }
2283
Calvin On1f64f3f2016-10-11 15:10:46 -07002284 private int getCaptivePortalMode() {
2285 return Settings.Global.getInt(mContext.getContentResolver(),
2286 Settings.Global.CAPTIVE_PORTAL_MODE,
2287 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2288 }
2289
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002290 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2291 switch (msg.what) {
2292 default:
2293 return false;
2294 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2295 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2296 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2297 handleLingerComplete(nai);
2298 }
2299 break;
2300 }
2301 }
2302 return true;
2303 }
2304
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002305 @Override
2306 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002307 if (!maybeHandleAsyncChannelMessage(msg) &&
2308 !maybeHandleNetworkMonitorMessage(msg) &&
2309 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002310 maybeHandleNetworkAgentMessage(msg);
2311 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002312 }
2313 }
2314
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002315 private void updateLingerState(NetworkAgentInfo nai, long now) {
2316 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2317 // 2. If the network was lingering and there are now requests, unlinger it.
2318 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2319 // one lingered request, start lingering.
2320 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002321 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002322 if (DBG) log("Unlingering " + nai.name());
2323 nai.unlinger();
2324 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002325 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002326 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002327 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002328 nai.linger();
2329 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2330 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2331 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002332 }
2333
Robert Greenwalt7b816022014-04-18 15:25:25 -07002334 private void handleAsyncChannelHalfConnect(Message msg) {
2335 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002336 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002337 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2338 if (VDBG) log("NetworkFactory connected");
2339 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002340 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002341 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002342 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002343 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002344 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 }
2346 } else {
2347 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002348 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 }
2350 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2351 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2352 if (VDBG) log("NetworkAgent connected");
2353 // A network agent has requested a connection. Establish the connection.
2354 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2355 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2356 } else {
2357 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002358 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002359 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002360 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002361 synchronized (mNetworkForNetId) {
2362 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002363 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002364 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002365 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002366 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002367 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002368 }
2369 }
2370 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002371
Robert Greenwalt7b816022014-04-18 15:25:25 -07002372 private void handleAsyncChannelDisconnected(Message msg) {
2373 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2374 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002375 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002376 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002377 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002378 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002379 // TODO - if we move the logic to the network agent (have them disconnect
2380 // because they lost all their requests or because their score isn't good)
2381 // then they would disconnect organically, report their new state and then
2382 // disconnect the channel.
2383 if (nai.networkInfo.isConnected()) {
2384 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2385 null, null);
2386 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002387 final boolean wasDefault = isDefaultNetwork(nai);
2388 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002389 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002390 // Log default network disconnection before required book-keeping.
2391 // Let rematchAllNetworksAndRequests() below record a new default network event
2392 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2393 // whose timestamps tell how long it takes to recover a default network.
2394 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002395 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002396 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002397 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2398 // by other networks that are already connected. Perhaps that can be done by
2399 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2400 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002401 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002402 mKeepaliveTracker.handleStopAllKeepalives(nai,
2403 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002404 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002405 mNetworkAgentInfos.remove(msg.replyTo);
2406 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002407 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002408 // Remove the NetworkAgent, but don't mark the netId as
2409 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002410 mNetworkForNetId.remove(nai.network.netId);
2411 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002412 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002413 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2414 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002415 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2416 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2417 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002418 sendUpdatedScoreToFactories(request, 0);
2419 }
2420 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002421 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002422 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002423 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002424 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002425 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002426 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002427 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002428 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002429 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002430 if (nai.created) {
2431 // Tell netd to clean up the configuration for this network
2432 // (routing rules, DNS, etc).
2433 // This may be slow as it requires a lot of netd shelling out to ip and
2434 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2435 // after we've rematched networks with requests which should make a potential
2436 // fallback network the default or requested a new network from the
2437 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2438 // long time.
2439 try {
2440 mNetd.removeNetwork(nai.network.netId);
2441 } catch (Exception e) {
2442 loge("Exception removing network: " + e);
2443 }
2444 }
2445 synchronized (mNetworkForNetId) {
2446 mNetIdInUse.delete(nai.network.netId);
2447 }
2448 } else {
2449 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2450 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002451 }
2452 }
2453
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002454 // If this method proves to be too slow then we can maintain a separate
2455 // pendingIntent => NetworkRequestInfo map.
2456 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2457 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2458 Intent intent = pendingIntent.getIntent();
2459 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2460 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2461 if (existingPendingIntent != null &&
2462 existingPendingIntent.getIntent().filterEquals(intent)) {
2463 return entry.getValue();
2464 }
2465 }
2466 return null;
2467 }
2468
2469 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2470 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2471
2472 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2473 if (existingRequest != null) { // remove the existing request.
2474 if (DBG) log("Replacing " + existingRequest.request + " with "
2475 + nri.request + " because their intents matched.");
2476 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2477 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002478 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002479 }
2480
Erik Klineda4bfa82015-04-30 12:58:40 +09002481 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002482 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002483 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002484 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002485 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002486 if (nri.request.networkCapabilities.hasSignalStrength() &&
2487 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2488 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002489 }
2490 }
2491 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002492 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002493 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002494 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002495 }
2496 }
2497
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002498 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2499 int callingUid) {
2500 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2501 if (nri != null) {
2502 handleReleaseNetworkRequest(nri.request, callingUid);
2503 }
2504 }
2505
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002506 // Determines whether the network is the best (or could become the best, if it validated), for
2507 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2508 // on the value of reason:
2509 //
2510 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2511 // then it should be torn down.
2512 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2513 // then it should be lingered.
2514 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2515 final int numRequests;
2516 switch (reason) {
2517 case TEARDOWN:
2518 numRequests = nai.numRequestNetworkRequests();
2519 break;
2520 case LINGER:
2521 numRequests = nai.numForegroundNetworkRequests();
2522 break;
2523 default:
2524 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2525 return true;
2526 }
2527
2528 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002529 return false;
2530 }
Paul Jensene0988542015-06-25 15:30:08 -04002531 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002532 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2533 // Background requests don't affect lingering.
2534 continue;
2535 }
2536
Paul Jensene0988542015-06-25 15:30:08 -04002537 // If this Network is already the highest scoring Network for a request, or if
2538 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002539 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002540 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002541 // Note that this catches two important cases:
2542 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2543 // is currently satisfying the request. This is desirable when
2544 // cellular ends up validating but WiFi does not.
2545 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002546 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002547 // WiFi ends up validating and out scoring cellular.
2548 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2549 nai.getCurrentScoreAsValidated())) {
2550 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002551 }
2552 }
Paul Jensene0988542015-06-25 15:30:08 -04002553 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002554 }
2555
Erik Klineacdd6392016-07-07 16:50:58 +09002556 private NetworkRequestInfo getNriForAppRequest(
2557 NetworkRequest request, int callingUid, String requestedOperation) {
2558 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2559
Robert Greenwalt9258c642014-03-26 16:47:06 -07002560 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002561 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002562 log(String.format("UID %d attempted to %s for unowned request %s",
2563 callingUid, requestedOperation, nri));
2564 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002565 }
Erik Klineacdd6392016-07-07 16:50:58 +09002566 }
2567
2568 return nri;
2569 }
2570
Erik Kline3841a482015-11-25 12:49:38 +09002571 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2572 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2573 nri.request.requestId) == null) {
2574 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2575 }
2576 }
2577
Erik Klineacdd6392016-07-07 16:50:58 +09002578 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2579 final NetworkRequestInfo nri = getNriForAppRequest(
2580 request, callingUid, "release NetworkRequest");
Erik Kline3841a482015-11-25 12:49:38 +09002581 if (nri != null) {
2582 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2583 }
2584 }
Erik Klineacdd6392016-07-07 16:50:58 +09002585
Erik Kline3841a482015-11-25 12:49:38 +09002586 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2587 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2588 if (VDBG || (DBG && nri.request.isRequest())) {
2589 log("releasing " + nri.request + " (" + logCallbackType + ")");
2590 }
Erik Klineacdd6392016-07-07 16:50:58 +09002591 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002592 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002593 synchronized (mUidToNetworkRequestCount) {
2594 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2595 if (requests < 1) {
2596 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2597 nri.mUid);
2598 } else if (requests == 1) {
2599 mUidToNetworkRequestCount.removeAt(
2600 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2601 } else {
2602 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2603 }
2604 }
2605 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2606 if (nri.request.isRequest()) {
2607 boolean wasKept = false;
2608 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2609 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002610 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002611 nai.removeRequest(nri.request.requestId);
2612 if (VDBG) {
2613 log(" Removing from current network " + nai.name() +
2614 ", leaving " + nai.numNetworkRequests() + " requests.");
2615 }
2616 // If there are still lingered requests on this network, don't tear it down,
2617 // but resume lingering instead.
2618 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002619 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002620 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2621 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002622 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002623 wasKept = true;
2624 }
2625 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002626 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2627 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002628 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002629 }
Erik Klineacdd6392016-07-07 16:50:58 +09002630 }
2631
2632 // TODO: remove this code once we know that the Slog.wtf is never hit.
2633 //
2634 // Find all networks that are satisfying this request and remove the request
2635 // from their request lists.
2636 // TODO - it's my understanding that for a request there is only a single
2637 // network satisfying it, so this loop is wasteful
2638 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2639 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2640 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2641 otherNai.name() + ", but mNetworkAgentInfos says " +
2642 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002643 }
2644 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002645
Erik Klineacdd6392016-07-07 16:50:58 +09002646 // Maintain the illusion. When this request arrived, we might have pretended
2647 // that a network connected to serve it, even though the network was already
2648 // connected. Now that this request has gone away, we might have to pretend
2649 // that the network disconnected. LegacyTypeTracker will generate that
2650 // phantom disconnect for this type.
2651 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2652 boolean doRemove = true;
2653 if (wasKept) {
2654 // check if any of the remaining requests for this network are for the
2655 // same legacy type - if so, don't remove the nai
2656 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2657 NetworkRequest otherRequest = nai.requestAt(i);
2658 if (otherRequest.legacyType == nri.request.legacyType &&
2659 otherRequest.isRequest()) {
2660 if (DBG) log(" still have other legacy request - leaving");
2661 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002662 }
2663 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002664 }
2665
Erik Klineacdd6392016-07-07 16:50:58 +09002666 if (doRemove) {
2667 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002668 }
2669 }
Erik Klineacdd6392016-07-07 16:50:58 +09002670
2671 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2672 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2673 nri.request);
2674 }
2675 } else {
2676 // listens don't have a singular affectedNetwork. Check all networks to see
2677 // if this listen request applies and remove it.
2678 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2679 nai.removeRequest(nri.request.requestId);
2680 if (nri.request.networkCapabilities.hasSignalStrength() &&
2681 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2682 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2683 }
2684 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002685 }
Erik Kline3841a482015-11-25 12:49:38 +09002686 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002687 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002688
Lorenzo Colitti18660282016-07-04 12:55:44 +09002689 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002690 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2691 enforceConnectivityInternalPermission();
2692 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2693 accept ? 1 : 0, always ? 1: 0, network));
2694 }
2695
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002696 @Override
2697 public void setAvoidUnvalidated(Network network) {
2698 enforceConnectivityInternalPermission();
2699 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2700 }
2701
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002702 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2703 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2704 " accept=" + accept + " always=" + always);
2705
2706 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2707 if (nai == null) {
2708 // Nothing to do.
2709 return;
2710 }
2711
2712 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002713 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002714 return;
2715 }
2716
2717 if (!nai.networkMisc.explicitlySelected) {
2718 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2719 }
2720
2721 if (accept != nai.networkMisc.acceptUnvalidated) {
2722 int oldScore = nai.getCurrentScore();
2723 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002724 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002725 sendUpdatedScoreToFactories(nai);
2726 }
2727
2728 if (always) {
2729 nai.asyncChannel.sendMessage(
2730 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2731 }
2732
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002733 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002734 // Tell the NetworkAgent to not automatically reconnect to the network.
2735 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2736 // Teardown the nework.
2737 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002738 }
2739
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002740 }
2741
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002742 private void handleSetAvoidUnvalidated(Network network) {
2743 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2744 if (nai == null || nai.lastValidated) {
2745 // Nothing to do. The network either disconnected or revalidated.
2746 return;
2747 }
2748 if (!nai.avoidUnvalidated) {
2749 int oldScore = nai.getCurrentScore();
2750 nai.avoidUnvalidated = true;
2751 rematchAllNetworksAndRequests(nai, oldScore);
2752 sendUpdatedScoreToFactories(nai);
2753 }
2754 }
2755
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002756 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002757 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002758 mHandler.sendMessageDelayed(
2759 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2760 PROMPT_UNVALIDATED_DELAY_MS);
2761 }
2762
Hugo Benichic8e9e122016-09-14 23:23:08 +00002763 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002764 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002765 }
2766
Erik Kline065ab6e2016-10-02 18:02:14 +09002767 private void rematchForAvoidBadWifiUpdate() {
2768 rematchAllNetworksAndRequests(null, 0);
2769 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2770 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2771 sendUpdatedScoreToFactories(nai);
2772 }
2773 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002774 }
2775
Erik Kline065ab6e2016-10-02 18:02:14 +09002776 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002777 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002778 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002779 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002780 if (!configRestrict) {
2781 pw.println("Bad Wi-Fi avoidance: unrestricted");
2782 return;
2783 }
2784
2785 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2786 pw.increaseIndent();
2787 pw.println("Config restrict: " + configRestrict);
2788
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002789 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002790 String description;
2791 // Can't use a switch statement because strings are legal case labels, but null is not.
2792 if ("0".equals(value)) {
2793 description = "get stuck";
2794 } else if (value == null) {
2795 description = "prompt";
2796 } else if ("1".equals(value)) {
2797 description = "avoid";
2798 } else {
2799 description = value + " (?)";
2800 }
2801 pw.println("User setting: " + description);
2802 pw.println("Network overrides:");
2803 pw.increaseIndent();
2804 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2805 if (nai.avoidUnvalidated) {
2806 pw.println(nai.name());
2807 }
2808 }
2809 pw.decreaseIndent();
2810 pw.decreaseIndent();
2811 }
2812
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002813 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2814 final String action;
2815 switch (type) {
2816 case NO_INTERNET:
2817 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2818 break;
2819 case LOST_INTERNET:
2820 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2821 break;
2822 default:
2823 Slog.wtf(TAG, "Unknown notification type " + type);
2824 return;
2825 }
2826
2827 Intent intent = new Intent(action);
2828 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2829 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2830 intent.setClassName("com.android.settings",
2831 "com.android.settings.wifi.WifiNoInternetDialog");
2832
2833 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2834 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2835 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2836 }
2837
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002838 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002839 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002840 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2841
2842 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2843 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002844 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002845 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002846 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2847 return;
2848 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002849 showValidationNotification(nai, NotificationType.NO_INTERNET);
2850 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002851
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002852 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2853 NetworkCapabilities nc = nai.networkCapabilities;
2854 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002855
Erik Kline065ab6e2016-10-02 18:02:14 +09002856 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002857 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002858 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2859 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002860 }
2861
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002862 private class InternalHandler extends Handler {
2863 public InternalHandler(Looper looper) {
2864 super(looper);
2865 }
2866
2867 @Override
2868 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002869 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002870 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002871 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002872 String causedBy = null;
2873 synchronized (ConnectivityService.this) {
2874 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2875 mNetTransitionWakeLock.isHeld()) {
2876 mNetTransitionWakeLock.release();
2877 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002878 } else {
2879 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002880 }
2881 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002882 if (VDBG) {
2883 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2884 log("Failed to find a new network - expiring NetTransition Wakelock");
2885 } else {
2886 log("NetTransition Wakelock (" +
2887 (causedBy == null ? "unknown" : causedBy) +
2888 " cleared because we found a replacement network");
2889 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002890 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002891 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002892 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002893 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002894 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002895 break;
2896 }
Jason Monkdecd2952013-10-10 14:02:51 -04002897 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002898 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002899 break;
2900 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002901 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002902 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2903 break;
2904 }
2905 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2906 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002907 break;
2908 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002909 case EVENT_REGISTER_NETWORK_AGENT: {
2910 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2911 break;
2912 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002913 case EVENT_REGISTER_NETWORK_REQUEST:
2914 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002915 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002916 break;
2917 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002918 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2919 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002920 handleRegisterNetworkRequestWithIntent(msg);
2921 break;
2922 }
Erik Kline3841a482015-11-25 12:49:38 +09002923 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2924 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2925 handleTimedOutNetworkRequest(nri);
2926 break;
2927 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002928 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2929 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2930 break;
2931 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002932 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002933 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002934 break;
2935 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002936 case EVENT_SET_ACCEPT_UNVALIDATED: {
2937 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2938 break;
2939 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002940 case EVENT_SET_AVOID_UNVALIDATED: {
2941 handleSetAvoidUnvalidated((Network) msg.obj);
2942 break;
2943 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002944 case EVENT_PROMPT_UNVALIDATED: {
2945 handlePromptUnvalidated((Network) msg.obj);
2946 break;
2947 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002948 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2949 handleMobileDataAlwaysOn();
2950 break;
2951 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002952 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2953 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2954 mKeepaliveTracker.handleStartKeepalive(msg);
2955 break;
2956 }
2957 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2958 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2959 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2960 int slot = msg.arg1;
2961 int reason = msg.arg2;
2962 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2963 break;
2964 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002965 case EVENT_SYSTEM_READY: {
2966 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2967 nai.networkMonitor.systemReady = true;
2968 }
2969 break;
2970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 }
2972 }
2973 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002974
2975 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002976 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002977 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002978 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002979 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002980 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002981 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002982 } else {
2983 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2984 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002985 }
2986
2987 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002988 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002989 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002990 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002991
2992 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002993 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002994 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002995 } else {
2996 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2997 }
2998 }
2999
3000 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003001 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003002 public int getLastTetherError(String iface) {
3003 enforceTetherAccessPermission();
3004
3005 if (isTetheringSupported()) {
3006 return mTethering.getLastTetherError(iface);
3007 } else {
3008 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3009 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003010 }
3011
3012 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003013 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003014 public String[] getTetherableUsbRegexs() {
3015 enforceTetherAccessPermission();
3016 if (isTetheringSupported()) {
3017 return mTethering.getTetherableUsbRegexs();
3018 } else {
3019 return new String[0];
3020 }
3021 }
3022
Lorenzo Colitti18660282016-07-04 12:55:44 +09003023 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003024 public String[] getTetherableWifiRegexs() {
3025 enforceTetherAccessPermission();
3026 if (isTetheringSupported()) {
3027 return mTethering.getTetherableWifiRegexs();
3028 } else {
3029 return new String[0];
3030 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003031 }
3032
Lorenzo Colitti18660282016-07-04 12:55:44 +09003033 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003034 public String[] getTetherableBluetoothRegexs() {
3035 enforceTetherAccessPermission();
3036 if (isTetheringSupported()) {
3037 return mTethering.getTetherableBluetoothRegexs();
3038 } else {
3039 return new String[0];
3040 }
3041 }
3042
Lorenzo Colitti18660282016-07-04 12:55:44 +09003043 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003044 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003045 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003046 if (isTetheringSupported()) {
3047 return mTethering.setUsbTethering(enable);
3048 } else {
3049 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3050 }
3051 }
3052
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003053 // TODO - move iface listing, queries, etc to new module
3054 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003055 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003056 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003057 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003058 return mTethering.getTetherableIfaces();
3059 }
3060
Lorenzo Colitti18660282016-07-04 12:55:44 +09003061 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003062 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003063 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003064 return mTethering.getTetheredIfaces();
3065 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003066
Lorenzo Colitti18660282016-07-04 12:55:44 +09003067 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003068 public String[] getTetheringErroredIfaces() {
3069 enforceTetherAccessPermission();
3070 return mTethering.getErroredIfaces();
3071 }
3072
Lorenzo Colitti18660282016-07-04 12:55:44 +09003073 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003074 public String[] getTetheredDhcpRanges() {
3075 enforceConnectivityInternalPermission();
3076 return mTethering.getTetheredDhcpRanges();
3077 }
3078
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003079 // if ro.tether.denied = true we default to no tethering
3080 // gservices could set the secure setting to 1 though to enable it on a build where it
3081 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003082 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003083 public boolean isTetheringSupported() {
3084 enforceTetherAccessPermission();
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09003085 int defaultVal = (mSystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003086 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003087 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3088 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003089
3090 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3091 boolean adminUser = false;
3092 final long token = Binder.clearCallingIdentity();
3093 try {
3094 adminUser = mUserManager.isAdminUser();
3095 } finally {
3096 Binder.restoreCallingIdentity(token);
3097 }
3098
3099 return tetherEnabledInSettings && adminUser &&
Erik Klined781fba2017-01-23 13:01:58 +09003100 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003101 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003102
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003103 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09003104 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003105 ConnectivityManager.enforceTetherChangePermission(mContext);
3106 if (!isTetheringSupported()) {
3107 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3108 return;
3109 }
3110 mTethering.startTethering(type, receiver, showProvisioningUi);
3111 }
3112
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003113 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003114 public void stopTethering(int type) {
3115 ConnectivityManager.enforceTetherChangePermission(mContext);
3116 mTethering.stopTethering(type);
3117 }
3118
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003119 // Called when we lose the default network and have no replacement yet.
3120 // This will automatically be cleared after X seconds or a new default network
3121 // becomes CONNECTED, whichever happens first. The timer is started by the
3122 // first caller and not restarted by subsequent callers.
3123 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003124 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003125 synchronized (this) {
3126 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003127 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003128 mNetTransitionWakeLock.acquire();
3129 mNetTransitionWakeLockCausedBy = forWhom;
3130 }
3131 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003132 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003133 mNetTransitionWakeLockTimeout);
3134 return;
3135 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003136
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003137 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003138 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003139 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003140 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003141 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003142 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003143 }
3144
Lorenzo Colitti18660282016-07-04 12:55:44 +09003145 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003146 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003147 enforceAccessPermission();
3148 enforceInternetPermission();
3149
Paul Jensenbfd17b72015-04-07 12:43:13 -04003150 NetworkAgentInfo nai;
3151 if (network == null) {
3152 nai = getDefaultNetwork();
3153 } else {
3154 nai = getNetworkAgentInfoForNetwork(network);
3155 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003156 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3157 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3158 return;
3159 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003160 // Revalidate if the app report does not match our current validated state.
3161 if (hasConnectivity == nai.lastValidated) return;
3162 final int uid = Binder.getCallingUid();
3163 if (DBG) {
3164 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3165 ") by " + uid);
3166 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003167 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003168 // Validating a network that has not yet connected could result in a call to
3169 // rematchNetworkAndRequests() which is not meant to work on such networks.
3170 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003171
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003172 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003173
3174 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3175 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003176 }
3177
Paul Jensencee9b512015-05-06 07:32:40 -04003178 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003179 // this information is already available as a world read/writable jvm property
3180 // so this API change wouldn't have a benifit. It also breaks the passing
3181 // of proxy info to all the JVMs.
3182 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003183 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003184 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003185 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3186 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003187 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003188 }
3189
Lorenzo Colitti18660282016-07-04 12:55:44 +09003190 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003191 public ProxyInfo getProxyForNetwork(Network network) {
3192 if (network == null) return getDefaultProxy();
3193 final ProxyInfo globalProxy = getGlobalProxy();
3194 if (globalProxy != null) return globalProxy;
3195 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3196 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3197 // caller may not have.
3198 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3199 if (nai == null) return null;
3200 synchronized (nai) {
3201 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3202 if (proxyInfo == null) return null;
3203 return new ProxyInfo(proxyInfo);
3204 }
3205 }
3206
Paul Jensene0bef712014-12-10 15:12:18 -05003207 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3208 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3209 // proxy is null then there is no proxy in place).
3210 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3211 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3212 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3213 proxy = null;
3214 }
3215 return proxy;
3216 }
3217
3218 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3219 // better for determining if a new proxy broadcast is necessary:
3220 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3221 // avoid unnecessary broadcasts.
3222 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3223 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3224 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3225 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3226 // all set.
3227 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3228 a = canonicalizeProxyInfo(a);
3229 b = canonicalizeProxyInfo(b);
3230 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3231 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3232 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3233 }
3234
Jason Monk207900c2014-04-25 15:00:09 -04003235 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003236 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003237
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003238 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003239 if (proxyProperties == mGlobalProxy) return;
3240 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3241 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3242
3243 String host = "";
3244 int port = 0;
3245 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003246 String pacFileUrl = "";
3247 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003248 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003249 if (!proxyProperties.isValid()) {
3250 if (DBG)
3251 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3252 return;
3253 }
Jason Monk207900c2014-04-25 15:00:09 -04003254 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003255 host = mGlobalProxy.getHost();
3256 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003257 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003258 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003259 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003260 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003261 } else {
3262 mGlobalProxy = null;
3263 }
3264 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003265 final long token = Binder.clearCallingIdentity();
3266 try {
3267 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3268 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3269 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3270 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003271 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003272 } finally {
3273 Binder.restoreCallingIdentity(token);
3274 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003275
Jason Monkcf0f97a2014-10-02 15:39:38 -04003276 if (mGlobalProxy == null) {
3277 proxyProperties = mDefaultProxy;
3278 }
3279 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003280 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003281 }
3282
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003283 private void loadGlobalProxy() {
3284 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003285 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3286 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3287 String exclList = Settings.Global.getString(res,
3288 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003289 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3290 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003291 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003292 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003293 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003294 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003295 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003296 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003297 if (!proxyProperties.isValid()) {
3298 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3299 return;
3300 }
3301
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003302 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003303 mGlobalProxy = proxyProperties;
3304 }
3305 }
3306 }
3307
Jason Monk207900c2014-04-25 15:00:09 -04003308 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003309 // this information is already available as a world read/writable jvm property
3310 // so this API change wouldn't have a benifit. It also breaks the passing
3311 // of proxy info to all the JVMs.
3312 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003313 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003314 return mGlobalProxy;
3315 }
3316 }
3317
Jason Monk207900c2014-04-25 15:00:09 -04003318 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003319 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003320 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003321 proxy = null;
3322 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003323 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003324 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003325 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003326 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003327 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3328 return;
3329 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003330
3331 // This call could be coming from the PacManager, containing the port of the local
3332 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3333 // global (to get the correct local port), and send a broadcast.
3334 // TODO: Switch PacManager to have its own message to send back rather than
3335 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003336 if ((mGlobalProxy != null) && (proxy != null)
3337 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003338 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3339 mGlobalProxy = proxy;
3340 sendProxyBroadcast(mGlobalProxy);
3341 return;
3342 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003343 mDefaultProxy = proxy;
3344
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003345 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003346 if (!mDefaultProxyDisabled) {
3347 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003348 }
3349 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003350 }
3351
Paul Jensene0bef712014-12-10 15:12:18 -05003352 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3353 // This method gets called when any network changes proxy, but the broadcast only ever contains
3354 // the default proxy (even if it hasn't changed).
3355 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3356 // world where an app might be bound to a non-default network.
3357 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3358 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3359 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3360
3361 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3362 sendProxyBroadcast(getDefaultProxy());
3363 }
3364 }
3365
Robert Greenwalt434203a2010-10-11 16:00:27 -07003366 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003367 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3368 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003369 if (!TextUtils.isEmpty(proxy)) {
3370 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003371 if (data.length == 0) {
3372 return;
3373 }
3374
Robert Greenwalt434203a2010-10-11 16:00:27 -07003375 String proxyHost = data[0];
3376 int proxyPort = 8080;
3377 if (data.length > 1) {
3378 try {
3379 proxyPort = Integer.parseInt(data[1]);
3380 } catch (NumberFormatException e) {
3381 return;
3382 }
3383 }
Jason Monk207900c2014-04-25 15:00:09 -04003384 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003385 setGlobalProxy(p);
3386 }
3387 }
3388
Jason Monk207900c2014-04-25 15:00:09 -04003389 private void sendProxyBroadcast(ProxyInfo proxy) {
3390 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003391 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003392 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003393 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003394 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3395 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003396 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003397 final long ident = Binder.clearCallingIdentity();
3398 try {
3399 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3400 } finally {
3401 Binder.restoreCallingIdentity(ident);
3402 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003403 }
3404
3405 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003406 final private HashMap<Uri, Integer> mUriEventMap;
3407 final private Context mContext;
3408 final private Handler mHandler;
3409
3410 SettingsObserver(Context context, Handler handler) {
3411 super(null);
3412 mUriEventMap = new HashMap<Uri, Integer>();
3413 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003414 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003415 }
3416
Erik Klineda4bfa82015-04-30 12:58:40 +09003417 void observe(Uri uri, int what) {
3418 mUriEventMap.put(uri, what);
3419 final ContentResolver resolver = mContext.getContentResolver();
3420 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003421 }
3422
3423 @Override
3424 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003425 Slog.wtf(TAG, "Should never be reached.");
3426 }
3427
3428 @Override
3429 public void onChange(boolean selfChange, Uri uri) {
3430 final Integer what = mUriEventMap.get(uri);
3431 if (what != null) {
3432 mHandler.obtainMessage(what.intValue()).sendToTarget();
3433 } else {
3434 loge("No matching event to send for URI=" + uri);
3435 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003436 }
3437 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003438
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003439 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003440 Slog.d(TAG, s);
3441 }
3442
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003443 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003444 Slog.e(TAG, s);
3445 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003446
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003447 private static <T> T checkNotNull(T value, String message) {
3448 if (value == null) {
3449 throw new NullPointerException(message);
3450 }
3451 return value;
3452 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003453
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003454 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003455 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003456 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3457 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3458 *
3459 * @param oldPackage Package name of the application which currently controls VPN, which will
3460 * be replaced. If there is no such application, this should should either be
3461 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3462 * @param newPackage Package name of the application which should gain control of VPN, or
3463 * {@code null} to disable.
3464 * @param userId User for whom to prepare the new VPN.
3465 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003466 * @hide
3467 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003468 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003469 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3470 int userId) {
3471 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003472 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003473
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003474 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003475 Vpn vpn = mVpns.get(userId);
3476 if (vpn != null) {
3477 return vpn.prepare(oldPackage, newPackage);
3478 } else {
3479 return false;
3480 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003481 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003482 }
3483
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003484 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003485 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3486 * This method is used by system-privileged apps.
3487 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3488 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3489 *
3490 * @param packageName The package for which authorization state should change.
3491 * @param userId User for whom {@code packageName} is installed.
3492 * @param authorized {@code true} if this app should be able to start a VPN connection without
3493 * explicit user approval, {@code false} if not.
3494 *
Jeff Davidson05542602014-08-11 14:07:27 -07003495 * @hide
3496 */
3497 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003498 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3499 enforceCrossUserPermission(userId);
3500
Jeff Davidson05542602014-08-11 14:07:27 -07003501 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003502 Vpn vpn = mVpns.get(userId);
3503 if (vpn != null) {
3504 vpn.setPackageAuthorization(packageName, authorized);
3505 }
Jeff Davidson05542602014-08-11 14:07:27 -07003506 }
3507 }
3508
3509 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003510 * Configure a TUN interface and return its file descriptor. Parameters
3511 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003512 * and not available in ConnectivityManager. Permissions are checked in
3513 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003514 * @hide
3515 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003516 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003517 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003518 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003519 int user = UserHandle.getUserId(Binder.getCallingUid());
3520 synchronized(mVpns) {
3521 return mVpns.get(user).establish(config);
3522 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003523 }
3524
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003525 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003526 * Start legacy VPN, controlling native daemons as needed. Creates a
3527 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003528 */
3529 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003530 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003531 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003532 final LinkProperties egress = getActiveLinkProperties();
3533 if (egress == null) {
3534 throw new IllegalStateException("Missing active network connection");
3535 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003536 int user = UserHandle.getUserId(Binder.getCallingUid());
3537 synchronized(mVpns) {
3538 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3539 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003540 }
3541
3542 /**
3543 * Return the information of the ongoing legacy VPN. This method is used
3544 * by VpnSettings and not available in ConnectivityManager. Permissions
3545 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003546 */
3547 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003548 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3549 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003550
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003551 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003552 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003553 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003554 }
3555
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003556 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003557 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3558 * and not available in ConnectivityManager.
3559 */
3560 @Override
3561 public VpnInfo[] getAllVpnInfo() {
3562 enforceConnectivityInternalPermission();
3563 if (mLockdownEnabled) {
3564 return new VpnInfo[0];
3565 }
3566
3567 synchronized(mVpns) {
3568 List<VpnInfo> infoList = new ArrayList<>();
3569 for (int i = 0; i < mVpns.size(); i++) {
3570 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3571 if (info != null) {
3572 infoList.add(info);
3573 }
3574 }
3575 return infoList.toArray(new VpnInfo[infoList.size()]);
3576 }
3577 }
3578
3579 /**
3580 * @return VPN information for accounting, or null if we can't retrieve all required
3581 * information, e.g primary underlying iface.
3582 */
3583 @Nullable
3584 private VpnInfo createVpnInfo(Vpn vpn) {
3585 VpnInfo info = vpn.getVpnInfo();
3586 if (info == null) {
3587 return null;
3588 }
3589 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3590 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3591 // the underlyingNetworks list.
3592 if (underlyingNetworks == null) {
3593 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3594 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3595 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3596 }
3597 } else if (underlyingNetworks.length > 0) {
3598 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3599 if (linkProperties != null) {
3600 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3601 }
3602 }
3603 return info.primaryUnderlyingIface == null ? null : info;
3604 }
3605
3606 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003607 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3608 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003609 * Permissions are checked in Vpn class.
3610 * @hide
3611 */
3612 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003613 public VpnConfig getVpnConfig(int userId) {
3614 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003615 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003616 Vpn vpn = mVpns.get(userId);
3617 if (vpn != null) {
3618 return vpn.getVpnConfig();
3619 } else {
3620 return null;
3621 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003622 }
3623 }
3624
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003625 @Override
3626 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003627 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3628 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3629 return false;
3630 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003631
3632 // Tear down existing lockdown if profile was removed
3633 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3634 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003635 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3636 if (profileTag == null) {
3637 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3638 return false;
3639 }
3640 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003641 final VpnProfile profile = VpnProfile.decode(
3642 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003643 if (profile == null) {
3644 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3645 setLockdownTracker(null);
3646 return true;
3647 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003648 int user = UserHandle.getUserId(Binder.getCallingUid());
3649 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003650 Vpn vpn = mVpns.get(user);
3651 if (vpn == null) {
3652 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3653 return false;
3654 }
3655 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003656 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003657 } else {
3658 setLockdownTracker(null);
3659 }
3660
3661 return true;
3662 }
3663
3664 /**
3665 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3666 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3667 */
3668 private void setLockdownTracker(LockdownVpnTracker tracker) {
3669 // Shutdown any existing tracker
3670 final LockdownVpnTracker existing = mLockdownTracker;
3671 mLockdownTracker = null;
3672 if (existing != null) {
3673 existing.shutdown();
3674 }
3675
3676 try {
3677 if (tracker != null) {
3678 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003679 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003680 mLockdownTracker = tracker;
3681 mLockdownTracker.init();
3682 } else {
3683 mNetd.setFirewallEnabled(false);
3684 }
3685 } catch (RemoteException e) {
3686 // ignored; NMS lives inside system_server
3687 }
3688 }
3689
3690 private void throwIfLockdownEnabled() {
3691 if (mLockdownEnabled) {
3692 throw new IllegalStateException("Unavailable in lockdown mode");
3693 }
3694 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003695
Robin Lee244ce8e2016-01-05 18:03:46 +00003696 /**
Robin Lee17e61832016-05-09 13:46:28 +01003697 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3698 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003699 *
Robin Lee17e61832016-05-09 13:46:28 +01003700 * @return {@code true} if the service was started, the service was already connected, or there
3701 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003702 */
Robin Lee17e61832016-05-09 13:46:28 +01003703 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003704 synchronized (mVpns) {
3705 Vpn vpn = mVpns.get(userId);
3706 if (vpn == null) {
3707 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3708 // exists already.
3709 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3710 return false;
3711 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003712
Robin Lee812800c2016-05-13 15:38:08 +01003713 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003714 }
3715 }
3716
3717 @Override
Robin Leedc679712016-05-03 13:23:03 +01003718 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003719 enforceConnectivityInternalPermission();
3720 enforceCrossUserPermission(userId);
3721
3722 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3723 if (LockdownVpnTracker.isEnabled()) {
3724 return false;
3725 }
3726
Robin Lee244ce8e2016-01-05 18:03:46 +00003727 synchronized (mVpns) {
3728 Vpn vpn = mVpns.get(userId);
3729 if (vpn == null) {
3730 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3731 return false;
3732 }
Robin Lee17e61832016-05-09 13:46:28 +01003733 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003734 return false;
3735 }
Robin Lee17e61832016-05-09 13:46:28 +01003736 if (!startAlwaysOnVpn(userId)) {
3737 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003738 return false;
3739 }
Robin Lee17e61832016-05-09 13:46:28 +01003740
Robin Lee812800c2016-05-13 15:38:08 +01003741 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003742 }
3743 return true;
3744 }
3745
3746 @Override
3747 public String getAlwaysOnVpnPackage(int userId) {
3748 enforceConnectivityInternalPermission();
3749 enforceCrossUserPermission(userId);
3750
3751 synchronized (mVpns) {
3752 Vpn vpn = mVpns.get(userId);
3753 if (vpn == null) {
3754 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3755 return null;
3756 }
3757 return vpn.getAlwaysOnPackage();
3758 }
3759 }
3760
Wink Savilleab9321d2013-06-29 21:10:57 -07003761 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003762 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003763 // TODO: Remove? Any reason to trigger a provisioning check?
3764 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003765 }
3766
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003767 /** Location to an updatable file listing carrier provisioning urls.
3768 * An example:
3769 *
3770 * <?xml version="1.0" encoding="utf-8"?>
3771 * <provisioningUrls>
3772 * <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 -07003773 * </provisioningUrls>
3774 */
3775 private static final String PROVISIONING_URL_PATH =
3776 "/data/misc/radio/provisioning_urls.xml";
3777 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003778
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003779 /** XML tag for root element. */
3780 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3781 /** XML tag for individual url */
3782 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003783 /** XML attribute for mcc */
3784 private static final String ATTR_MCC = "mcc";
3785 /** XML attribute for mnc */
3786 private static final String ATTR_MNC = "mnc";
3787
Paul Jensen434dde82015-06-11 09:43:30 -04003788 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003789 FileReader fileReader = null;
3790 XmlPullParser parser = null;
3791 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003792
3793 try {
3794 fileReader = new FileReader(mProvisioningUrlFile);
3795 parser = Xml.newPullParser();
3796 parser.setInput(fileReader);
3797 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3798
3799 while (true) {
3800 XmlUtils.nextElement(parser);
3801
3802 String element = parser.getName();
3803 if (element == null) break;
3804
Paul Jensen434dde82015-06-11 09:43:30 -04003805 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003806 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3807 try {
3808 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3809 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3810 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3811 parser.next();
3812 if (parser.getEventType() == XmlPullParser.TEXT) {
3813 return parser.getText();
3814 }
3815 }
3816 }
3817 } catch (NumberFormatException e) {
3818 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3819 }
3820 }
3821 }
3822 return null;
3823 } catch (FileNotFoundException e) {
3824 loge("Carrier Provisioning Urls file not found");
3825 } catch (XmlPullParserException e) {
3826 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3827 } catch (IOException e) {
3828 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3829 } finally {
3830 if (fileReader != null) {
3831 try {
3832 fileReader.close();
3833 } catch (IOException e) {}
3834 }
3835 }
3836 return null;
3837 }
3838
Wink Saville42d4f082013-07-20 20:31:59 -07003839 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003840 public String getMobileProvisioningUrl() {
3841 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003842 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003843 if (TextUtils.isEmpty(url)) {
3844 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003845 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003846 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003847 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003848 }
Wink Saville8cf35602013-07-10 23:00:07 -07003849 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003850 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003851 String phoneNumber = mTelephonyManager.getLine1Number();
3852 if (TextUtils.isEmpty(phoneNumber)) {
3853 phoneNumber = "0000000000";
3854 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003855 url = String.format(url,
3856 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3857 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003858 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003859 }
3860
Wink Savilleab9321d2013-06-29 21:10:57 -07003861 return url;
3862 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003863
Wink Saville948282b2013-08-29 08:55:16 -07003864 @Override
3865 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003866 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003867 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003868 final long ident = Binder.clearCallingIdentity();
3869 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003870 // Concatenate the range of types onto the range of NetIDs.
3871 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3872 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003873 } finally {
3874 Binder.restoreCallingIdentity(ident);
3875 }
Wink Saville948282b2013-08-29 08:55:16 -07003876 }
Wink Saville7788c612013-08-29 14:57:08 -07003877
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003878 @Override
3879 public void setAirplaneMode(boolean enable) {
3880 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003881 final long ident = Binder.clearCallingIdentity();
3882 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003883 final ContentResolver cr = mContext.getContentResolver();
3884 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3885 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3886 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003887 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003888 } finally {
3889 Binder.restoreCallingIdentity(ident);
3890 }
3891 }
3892
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003893 private void onUserStart(int userId) {
3894 synchronized(mVpns) {
3895 Vpn userVpn = mVpns.get(userId);
3896 if (userVpn != null) {
3897 loge("Starting user already has a VPN");
3898 return;
3899 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003900 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003901 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003902
3903 final ContentResolver cr = mContext.getContentResolver();
3904 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3905 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3906 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3907 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3908 if (alwaysOnPackage != null) {
3909 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3910 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003911 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003912 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3913 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003914 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003915 }
3916
3917 private void onUserStop(int userId) {
3918 synchronized(mVpns) {
3919 Vpn userVpn = mVpns.get(userId);
3920 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003921 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003922 return;
3923 }
Robin Lee17e61832016-05-09 13:46:28 +01003924 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003925 mVpns.delete(userId);
3926 }
3927 }
3928
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003929 private void onUserAdded(int userId) {
3930 synchronized(mVpns) {
3931 final int vpnsSize = mVpns.size();
3932 for (int i = 0; i < vpnsSize; i++) {
3933 Vpn vpn = mVpns.valueAt(i);
3934 vpn.onUserAdded(userId);
3935 }
3936 }
3937 }
3938
3939 private void onUserRemoved(int userId) {
3940 synchronized(mVpns) {
3941 final int vpnsSize = mVpns.size();
3942 for (int i = 0; i < vpnsSize; i++) {
3943 Vpn vpn = mVpns.valueAt(i);
3944 vpn.onUserRemoved(userId);
3945 }
3946 }
3947 }
3948
Robin Lee89e7a692016-02-29 14:38:17 +00003949 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003950 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3951 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3952 updateLockdownVpn();
3953 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003954 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003955 }
3956 }
3957
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003958 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3959 @Override
3960 public void onReceive(Context context, Intent intent) {
3961 final String action = intent.getAction();
3962 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3963 if (userId == UserHandle.USER_NULL) return;
3964
Robin Lee323f29d2016-05-04 16:38:06 +01003965 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003966 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003967 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003968 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003969 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3970 onUserAdded(userId);
3971 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3972 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003973 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3974 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003975 }
3976 }
3977 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003978
Robin Lee95204e02017-01-27 11:59:22 +00003979 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3980 @Override
3981 public void onReceive(Context context, Intent intent) {
3982 // Try creating lockdown tracker, since user present usually means
3983 // unlocked keystore.
3984 updateLockdownVpn();
3985 mContext.unregisterReceiver(this);
3986 }
3987 };
3988
Robert Greenwalta67be032014-05-16 15:49:14 -07003989 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3990 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003991 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3992 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003993
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003994 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3995 // Map from UID to number of NetworkRequests that UID has filed.
3996 @GuardedBy("mUidToNetworkRequestCount")
3997 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3998
Robert Greenwalta67be032014-05-16 15:49:14 -07003999 private static class NetworkFactoryInfo {
4000 public final String name;
4001 public final Messenger messenger;
4002 public final AsyncChannel asyncChannel;
4003
4004 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4005 this.name = name;
4006 this.messenger = messenger;
4007 this.asyncChannel = asyncChannel;
4008 }
4009 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004010
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004011 private void ensureNetworkRequestHasType(NetworkRequest request) {
4012 if (request.type == NetworkRequest.Type.NONE) {
4013 throw new IllegalArgumentException(
4014 "All NetworkRequests in ConnectivityService must have a type");
4015 }
4016 }
4017
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004018 /**
4019 * Tracks info about the requester.
4020 * Also used to notice when the calling process dies so we can self-expire
4021 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004025 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004026 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004027 final int mPid;
4028 final int mUid;
4029 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004030
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004031 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004032 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004033 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004034 mPendingIntent = pi;
4035 messenger = null;
4036 mBinder = null;
4037 mPid = getCallingPid();
4038 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004039 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004040 }
4041
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004042 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004043 super();
4044 messenger = m;
4045 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004046 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004047 mBinder = binder;
4048 mPid = getCallingPid();
4049 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004050 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004051 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004052
4053 try {
4054 mBinder.linkToDeath(this, 0);
4055 } catch (RemoteException e) {
4056 binderDied();
4057 }
4058 }
4059
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004060 private void enforceRequestCountLimit() {
4061 synchronized (mUidToNetworkRequestCount) {
4062 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4063 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4064 throw new IllegalArgumentException("Too many NetworkRequests filed");
4065 }
4066 mUidToNetworkRequestCount.put(mUid, networkRequests);
4067 }
4068 }
4069
Robert Greenwalt9258c642014-03-26 16:47:06 -07004070 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004071 if (mBinder != null) {
4072 mBinder.unlinkToDeath(this, 0);
4073 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004074 }
4075
4076 public void binderDied() {
4077 log("ConnectivityService NetworkRequestInfo binderDied(" +
4078 request + ", " + mBinder + ")");
4079 releaseNetworkRequest(request);
4080 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004081
4082 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004083 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004084 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004085 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 }
4087
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004088 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4089 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4090 if (badCapability != null) {
4091 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004092 }
4093 }
4094
Erik Kline9d598e12015-07-13 16:37:51 +09004095 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004096 final SortedSet<Integer> thresholds = new TreeSet();
4097 synchronized (nai) {
4098 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4099 if (nri.request.networkCapabilities.hasSignalStrength() &&
4100 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4101 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4102 }
4103 }
4104 }
Erik Kline9d598e12015-07-13 16:37:51 +09004105 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004106 }
4107
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004108 private void updateSignalStrengthThresholds(
4109 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4110 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004111 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004112 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4113
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004114 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004115 String detail;
4116 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4117 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4118 } else {
4119 detail = reason;
4120 }
4121 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4122 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4123 }
4124
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004125 nai.asyncChannel.sendMessage(
4126 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004127 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004128 }
4129
Robert Greenwalt9258c642014-03-26 16:47:06 -07004130 @Override
4131 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004132 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004133 final NetworkRequest.Type type = (networkCapabilities == null)
4134 ? NetworkRequest.Type.TRACK_DEFAULT
4135 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004136 // If the requested networkCapabilities is null, take them instead from
4137 // the default network request. This allows callers to keep track of
4138 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004139 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004140 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4141 enforceAccessPermission();
4142 } else {
4143 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4144 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004145 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4146 // of the app when the request is filed, but we never change the request if the app
4147 // changes network state. http://b/29964605
4148 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004149 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004150 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004151
Etan Cohenba07c8c2017-02-05 10:42:27 -08004152 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004153 throw new IllegalArgumentException("Bad timeout specified");
4154 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004155
Etan Cohenddb9ef02015-11-18 10:56:15 -08004156 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4157 .equals(networkCapabilities.getNetworkSpecifier())) {
4158 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4159 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4160 }
4161
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004162 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004163 nextNetworkRequestId(), type);
4164 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004165 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004166
4167 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004168 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004169 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004170 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 }
4172 return networkRequest;
4173 }
4174
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004175 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004176 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004177 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004178 } else {
4179 enforceChangePermission();
4180 }
4181 }
4182
fenglub15e72b2015-03-20 11:29:56 -07004183 @Override
fengludb571472015-04-21 17:12:05 -07004184 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004185 enforceAccessPermission();
4186 NetworkAgentInfo nai = null;
4187 if (network == null) {
4188 return false;
4189 }
4190 synchronized (mNetworkForNetId) {
4191 nai = mNetworkForNetId.get(network.netId);
4192 }
4193 if (nai != null) {
4194 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4195 return true;
4196 }
4197 return false;
4198 }
4199
Felipe Lemeee27cab2016-06-20 16:36:29 -07004200 private boolean isSystem(int uid) {
4201 return uid < Process.FIRST_APPLICATION_UID;
4202 }
fenglub15e72b2015-03-20 11:29:56 -07004203
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004204 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004205 final int uid = Binder.getCallingUid();
4206 if (isSystem(uid)) {
4207 return;
4208 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004209 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004210 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004211 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004212 synchronized(mRulesLock) {
4213 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4214 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004215 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4216 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004217 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004218 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004219 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004220 }
4221 }
4222 }
4223
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224 @Override
4225 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4226 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004227 checkNotNull(operation, "PendingIntent cannot be null.");
4228 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4229 enforceNetworkRequestPermissions(networkCapabilities);
4230 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004231 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004232
4233 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004234 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4235 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004236 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004237 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4238 nri));
4239 return networkRequest;
4240 }
4241
Jeremy Joslin79294842014-12-03 17:15:28 -08004242 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4243 mHandler.sendMessageDelayed(
4244 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4245 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4246 }
4247
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004248 @Override
4249 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004250 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4252 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004253 }
4254
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004255 // In order to implement the compatibility measure for pre-M apps that call
4256 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4257 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4258 // This ensures it has permission to do so.
4259 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4260 if (nc == null) {
4261 return false;
4262 }
4263 int[] transportTypes = nc.getTransportTypes();
4264 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4265 return false;
4266 }
4267 try {
4268 mContext.enforceCallingOrSelfPermission(
4269 android.Manifest.permission.ACCESS_WIFI_STATE,
4270 "ConnectivityService");
4271 } catch (SecurityException e) {
4272 return false;
4273 }
4274 return true;
4275 }
4276
Robert Greenwalt9258c642014-03-26 16:47:06 -07004277 @Override
4278 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4279 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004280 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4281 enforceAccessPermission();
4282 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004283
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004284 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4285 if (!ConnectivityManager.checkChangePermission(mContext)) {
4286 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4287 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4288 // onLost and onAvailable callbacks when networks move in and out of the background.
4289 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4290 // can't request networks.
4291 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4292 }
4293
4294 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004295 NetworkRequest.Type.LISTEN);
4296 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004297 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004298
4299 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4300 return networkRequest;
4301 }
4302
4303 @Override
4304 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4305 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004306 checkNotNull(operation, "PendingIntent cannot be null.");
4307 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4308 enforceAccessPermission();
4309 }
4310
Erik Kline7523eb32015-07-09 18:24:03 +09004311 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004312 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4313 NetworkRequest.Type.LISTEN);
4314 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004315 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004316
4317 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004318 }
4319
Erik Klineacdd6392016-07-07 16:50:58 +09004320 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004321 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004322 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004323 mHandler.sendMessage(mHandler.obtainMessage(
4324 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004325 }
4326
4327 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004328 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004329 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004330 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4331 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004332 }
4333
Robert Greenwalta67be032014-05-16 15:49:14 -07004334 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004335 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004336 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4337 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4338 }
4339
4340 @Override
4341 public void unregisterNetworkFactory(Messenger messenger) {
4342 enforceConnectivityInternalPermission();
4343 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4344 }
4345
4346 private void handleUnregisterNetworkFactory(Messenger messenger) {
4347 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4348 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004349 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004350 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004351 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004352 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004353 }
4354
Robert Greenwalt7b816022014-04-18 15:25:25 -07004355 /**
4356 * NetworkAgentInfo supporting a request by requestId.
4357 * These have already been vetted (their Capabilities satisfy the request)
4358 * and the are the highest scored network available.
4359 * the are keyed off the Requests requestId.
4360 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004361 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004362 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4363 new SparseArray<NetworkAgentInfo>();
4364
Paul Jensen31a94f42015-02-13 14:18:39 -05004365 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4366 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004367 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4368 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004369 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4370 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4371 // there may not be a strict 1:1 correlation between the two.
4372 @GuardedBy("mNetworkForNetId")
4373 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004374
Robert Greenwalt7b816022014-04-18 15:25:25 -07004375 // NetworkAgentInfo keyed off its connecting messenger
4376 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004377 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004378 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4379 new HashMap<Messenger, NetworkAgentInfo>();
4380
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004381 @GuardedBy("mBlockedAppUids")
4382 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4383
Paul Jensen2c311d62014-11-17 12:34:51 -05004384 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004385 private final NetworkRequest mDefaultRequest;
4386
Erik Klineda4bfa82015-04-30 12:58:40 +09004387 // Request used to optionally keep mobile data active even when higher
4388 // priority networks like Wi-Fi are active.
4389 private final NetworkRequest mDefaultMobileDataRequest;
4390
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004391 private NetworkAgentInfo getDefaultNetwork() {
4392 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4393 }
4394
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004395 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004396 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004397 }
4398
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004399 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4400 return nri.request.requestId == mDefaultRequest.requestId;
4401 }
4402
Paul Jensen31a94f42015-02-13 14:18:39 -05004403 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004405 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004406 enforceConnectivityInternalPermission();
4407
Paul Jensen2c311d62014-11-17 12:34:51 -05004408 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4409 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004410 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004411 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4412 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004413 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004414 synchronized (this) {
4415 nai.networkMonitor.systemReady = mSystemReady;
4416 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004417 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4418 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004419 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004420 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004421 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004422 }
4423
4424 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4425 if (VDBG) log("Got NetworkAgent Messenger");
4426 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004427 synchronized (mNetworkForNetId) {
4428 mNetworkForNetId.put(na.network.netId, na);
4429 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4431 NetworkInfo networkInfo = na.networkInfo;
4432 na.networkInfo = null;
4433 updateNetworkInfo(na, networkInfo);
4434 }
4435
4436 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4437 LinkProperties newLp = networkAgent.linkProperties;
4438 int netId = networkAgent.network.netId;
4439
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004440 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4441 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004442 if (networkAgent.clatd != null) {
4443 networkAgent.clatd.fixupLinkProperties(oldLp);
4444 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004445
Paul Jensen992f2522014-04-28 10:33:11 -04004446 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004447 updateMtu(newLp, oldLp);
4448 // TODO - figure out what to do for clat
4449// for (LinkProperties lp : newLp.getStackedLinks()) {
4450// updateMtu(lp, null);
4451// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004452 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004453
Erik Kline94887872016-04-05 13:30:49 +09004454 updateRoutes(newLp, oldLp, netId);
4455 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004456
Paul Jensen3b759822014-05-13 11:44:01 -04004457 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004458 if (isDefaultNetwork(networkAgent)) {
4459 handleApplyDefaultProxy(newLp.getHttpProxy());
4460 } else {
4461 updateProxy(newLp, oldLp, networkAgent);
4462 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004463 // TODO - move this check to cover the whole function
4464 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004465 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004466 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4467 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004468
4469 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004470 }
4471
Lorenzo Colitti95439462014-10-09 13:44:48 +09004472 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4473 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4474 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004475
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004476 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004477 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4478 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004479 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004480 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004481 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004482 }
Paul Jensen992f2522014-04-28 10:33:11 -04004483
4484 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4485 CompareResult<String> interfaceDiff = new CompareResult<String>();
4486 if (oldLp != null) {
4487 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4488 } else if (newLp != null) {
4489 interfaceDiff.added = newLp.getAllInterfaceNames();
4490 }
4491 for (String iface : interfaceDiff.added) {
4492 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004493 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004494 mNetd.addInterfaceToNetwork(iface, netId);
4495 } catch (Exception e) {
4496 loge("Exception adding interface: " + e);
4497 }
4498 }
4499 for (String iface : interfaceDiff.removed) {
4500 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004501 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004502 mNetd.removeInterfaceFromNetwork(iface, netId);
4503 } catch (Exception e) {
4504 loge("Exception removing interface: " + e);
4505 }
4506 }
4507 }
4508
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004509 /**
4510 * Have netd update routes from oldLp to newLp.
4511 * @return true if routes changed between oldLp and newLp
4512 */
4513 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004514 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4515 if (oldLp != null) {
4516 routeDiff = oldLp.compareAllRoutes(newLp);
4517 } else if (newLp != null) {
4518 routeDiff.added = newLp.getAllRoutes();
4519 }
4520
4521 // add routes before removing old in case it helps with continuous connectivity
4522
4523 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4524 for (RouteInfo route : routeDiff.added) {
4525 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004526 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004527 try {
4528 mNetd.addRoute(netId, route);
4529 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004530 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4531 loge("Exception in addRoute for non-gateway: " + e);
4532 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 }
4534 }
4535 for (RouteInfo route : routeDiff.added) {
4536 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004537 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 try {
4539 mNetd.addRoute(netId, route);
4540 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004541 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4542 loge("Exception in addRoute for gateway: " + e);
4543 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004544 }
4545 }
4546
4547 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004548 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004549 try {
4550 mNetd.removeRoute(netId, route);
4551 } catch (Exception e) {
4552 loge("Exception in removeRoute: " + e);
4553 }
4554 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004555 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 }
Erik Kline41368502015-06-17 13:19:54 +09004557
Erik Kline94887872016-04-05 13:30:49 +09004558 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4559 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4560 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004561 }
Erik Kline94887872016-04-05 13:30:49 +09004562
4563 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004564 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004565 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004566 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004567 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4568 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004569 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004570 }
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004571 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4572 if (defaultNai != null && defaultNai.network.netId == netId) {
4573 setDefaultDnsSystemProperties(dnses);
4574 }
Erik Kline94887872016-04-05 13:30:49 +09004575 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004576 }
4577
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004578 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4579 int last = 0;
4580 for (InetAddress dns : dnses) {
4581 ++last;
4582 String key = "net.dns" + last;
4583 String value = dns.getHostAddress();
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09004584 mSystemProperties.set(key, value);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004585 }
4586 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4587 String key = "net.dns" + i;
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09004588 mSystemProperties.set(key, "");
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004589 }
4590 mNumDnsEntries = last;
4591 }
4592
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004593 private String getNetworkPermission(NetworkCapabilities nc) {
4594 // TODO: make these permission strings AIDL constants instead.
4595 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4596 return NetworkManagementService.PERMISSION_SYSTEM;
4597 }
4598 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4599 return NetworkManagementService.PERMISSION_NETWORK;
4600 }
4601 return null;
4602 }
4603
Paul Jensen3d194ea2015-06-16 14:27:36 -04004604 /**
4605 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4606 * augmented with any stateful capabilities implied from {@code networkAgent}
4607 * (e.g., validated status and captive portal status).
4608 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004609 * @param oldScore score of the network before any of the changes that prompted us
4610 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004611 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004612 * @param networkCapabilities the new network capabilities.
4613 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004614 private void updateCapabilities(
4615 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004616 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4617 networkCapabilities)) {
4618 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4619 + nai.networkCapabilities + " -> " + networkCapabilities);
4620 }
4621
Paul Jensen3d194ea2015-06-16 14:27:36 -04004622 // Don't modify caller's NetworkCapabilities.
4623 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004624 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004625 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4626 } else {
4627 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4628 }
Paul Jensene0988542015-06-25 15:30:08 -04004629 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004630 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4631 } else {
4632 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4633 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004634 if (nai.isBackgroundNetwork()) {
4635 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4636 } else {
4637 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4638 }
4639
4640 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4641
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004642 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4643 final String newPermission = getNetworkPermission(networkCapabilities);
4644 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004645 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004646 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004647 } catch (RemoteException e) {
4648 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004649 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004650 }
4651
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004652 final NetworkCapabilities prevNc = nai.networkCapabilities;
4653 synchronized (nai) {
4654 nai.networkCapabilities = networkCapabilities;
4655 }
4656 if (nai.getCurrentScore() == oldScore &&
4657 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4658 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4659 // the change we're processing can't affect any requests, it can only affect the listens
4660 // on this network. We might have been called by rematchNetworkAndRequests when a
4661 // network changed foreground state.
4662 processListenRequests(nai, true);
4663 } else {
4664 // If the requestable capabilities have changed or the score changed, we can't have been
4665 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004666 rematchAllNetworksAndRequests(nai, oldScore);
4667 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004668 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004669 }
4670
Paul Jensenc8b9a742014-09-30 15:37:41 -04004671 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004672 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4673 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004674 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004675 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004676 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4677 }
4678 }
4679
Robert Greenwalt7b816022014-04-18 15:25:25 -07004680 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4681 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004682 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004683 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4684 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004685 }
4686 }
4687
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004688 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4689 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004690 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004691 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004692 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4693 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004694 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004695 sendIntent(nri.mPendingIntent, intent);
4696 }
4697 // else not handled
4698 }
4699
4700 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4701 mPendingIntentWakeLock.acquire();
4702 try {
4703 if (DBG) log("Sending " + pendingIntent);
4704 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4705 } catch (PendingIntent.CanceledException e) {
4706 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4707 mPendingIntentWakeLock.release();
4708 releasePendingNetworkRequest(pendingIntent);
4709 }
4710 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4711 }
4712
4713 @Override
4714 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4715 String resultData, Bundle resultExtras) {
4716 if (DBG) log("Finished sending " + pendingIntent);
4717 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004718 // Release with a delay so the receiving client has an opportunity to put in its
4719 // own request.
4720 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004721 }
4722
Robert Greenwalt9258c642014-03-26 16:47:06 -07004723 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004724 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004725 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004726 Bundle bundle = new Bundle();
4727 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4728 new NetworkRequest(nri.request));
4729 Message msg = Message.obtain();
4730 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4731 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4732 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4733 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004734 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004735 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004736 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004737 break;
4738 }
4739 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4740 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4741 new NetworkCapabilities(networkAgent.networkCapabilities));
4742 break;
4743 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004744 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004745 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4746 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004747 break;
4748 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004749 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004750 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004751 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004752 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004753 if (VDBG) {
4754 log("sending notification " + notifyTypeToName(notificationType) +
4755 " for " + nri.request);
4756 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004757 nri.messenger.send(msg);
4758 } catch (RemoteException e) {
4759 // may occur naturally in the race of binder death.
4760 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4761 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004762 }
4763
Paul Jensenc8b9a742014-09-30 15:37:41 -04004764 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004765 if (nai.numRequestNetworkRequests() != 0) {
4766 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4767 NetworkRequest nr = nai.requestAt(i);
4768 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004769 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004770 loge("Dead network still had at least " + nr);
4771 break;
4772 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004773 }
4774 nai.asyncChannel.disconnect();
4775 }
4776
Robert Greenwalt7b816022014-04-18 15:25:25 -07004777 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4778 if (oldNetwork == null) {
4779 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4780 return;
4781 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004782 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004783
4784 // If we get here it means that the last linger timeout for this network expired. So there
4785 // must be no other active linger timers, and we must stop lingering.
4786 oldNetwork.clearLingerState();
4787
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004788 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004789 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004790 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004791 } else {
4792 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004793 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4794 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004795 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004796 }
4797
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004798 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004799 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004800 setupDataActivityTracking(newNetwork);
4801 try {
4802 mNetd.setDefaultNetId(newNetwork.network.netId);
4803 } catch (Exception e) {
4804 loge("Exception setting default network :" + e);
4805 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004806 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004807 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004808 updateTcpBufferSizes(newNetwork);
Lorenzo Colittic02ac732017-01-06 10:25:02 +09004809 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004810 }
4811
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004812 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004813 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4814 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4815 NetworkRequest nr = nri.request;
4816 if (!nr.isListen()) continue;
4817 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4818 nai.removeRequest(nri.request.requestId);
4819 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4820 }
4821 }
4822
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004823 if (capabilitiesChanged) {
4824 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4825 }
4826
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004827 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4828 NetworkRequest nr = nri.request;
4829 if (!nr.isListen()) continue;
4830 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4831 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004832 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004833 }
4834 }
4835 }
4836
Paul Jensen2161a8e2014-09-11 11:00:39 -04004837 // Handles a network appearing or improving its score.
4838 //
4839 // - Evaluates all current NetworkRequests that can be
4840 // satisfied by newNetwork, and reassigns to newNetwork
4841 // any such requests for which newNetwork is the best.
4842 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004843 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004844 // needed. A network is needed if it is the best network for
4845 // one or more NetworkRequests, or if it is a VPN.
4846 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004847 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004848 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004849 //
4850 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4851 // networks that have no chance (i.e. even if validated)
4852 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004853 //
4854 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4855 // it does not remove NetworkRequests that other Networks could better satisfy.
4856 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4857 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4858 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004859 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004860 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004861 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4862 // performed to tear down unvalidated networks that have no chance (i.e. even if
4863 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004864 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004865 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004866 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004867 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004868 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004869 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004870
4871 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4872 final int score = newNetwork.getCurrentScore();
4873
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004874 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004875
Paul Jensen2161a8e2014-09-11 11:00:39 -04004876 // Find and migrate to this Network any NetworkRequests for
4877 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004878 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004879 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004880 NetworkCapabilities nc = newNetwork.networkCapabilities;
4881 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004882 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004883 // Process requests in the first pass and listens in the second pass. This allows us to
4884 // change a network's capabilities depending on which requests it has. This is only
4885 // correct if the change in capabilities doesn't affect whether the network satisfies
4886 // requests or not, and doesn't affect the network's score.
4887 if (nri.request.isListen()) continue;
4888
Paul Jensencf4c2c62015-07-01 14:16:32 -04004889 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4890 final boolean satisfies = newNetwork.satisfies(nri.request);
4891 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004892 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004893 log("Network " + newNetwork.name() + " was already satisfying" +
4894 " request " + nri.request.requestId + ". No change.");
4895 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004896 keep = true;
4897 continue;
4898 }
4899
4900 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004901 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004902 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004903 // next check if it's better than any current network we're using for
4904 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004905 if (VDBG) {
4906 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004907 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004908 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004909 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004910 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004911 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004912 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004913 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004914 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004915 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004916 affectedNetworks.add(currentNetwork);
4917 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004918 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004919 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004920 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004921 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004922 if (!newNetwork.addRequest(nri.request)) {
4923 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4924 }
4925 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004926 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004927 // Tell NetworkFactories about the new score, so they can stop
4928 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004929 // TODO - this could get expensive if we have alot of requests for this
4930 // network. Think about if there is a way to reduce this. Push
4931 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004932 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004933 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004934 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004935 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004936 if (currentNetwork != null) {
4937 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4938 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004939 }
4940 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004941 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004942 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4943 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004944 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004945 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4946 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4947 // This means this code doesn't have to handle the case where "currentNetwork" no
4948 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4949 if (DBG) {
4950 log("Network " + newNetwork.name() + " stopped satisfying" +
4951 " request " + nri.request.requestId);
4952 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004953 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004954 if (currentNetwork == newNetwork) {
4955 mNetworkForRequestId.remove(nri.request.requestId);
4956 sendUpdatedScoreToFactories(nri.request, 0);
4957 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004958 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4959 newNetwork.name() +
4960 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004961 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004962 // TODO: Technically, sending CALLBACK_LOST here is
4963 // incorrect if there is a replacement network currently
4964 // connected that can satisfy nri, which is a request
4965 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004966 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4967 // so this code is only incorrect for a network that loses
4968 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004969 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004970 }
4971 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004972 if (isNewDefault) {
4973 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004974 makeDefault(newNetwork);
4975 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4976 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004977 synchronized (ConnectivityService.this) {
4978 // have a new default network, release the transition wakelock in
4979 // a second if it's held. The second pause is to allow apps
4980 // to reconnect over the new network
4981 if (mNetTransitionWakeLock.isHeld()) {
4982 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4983 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4984 mNetTransitionWakeLockSerialNumber, 0),
4985 1000);
4986 }
4987 }
4988 }
4989
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004990 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4991 Slog.wtf(TAG, String.format(
4992 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4993 nc, newNetwork.networkCapabilities));
4994 }
4995 if (newNetwork.getCurrentScore() != score) {
4996 Slog.wtf(TAG, String.format(
4997 "BUG: %s changed score during rematch: %d -> %d",
4998 score, newNetwork.getCurrentScore()));
4999 }
5000
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005001 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005002 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5003 // If the network went from background to foreground or vice versa, we need to update
5004 // its foreground state. It is safe to do this after rematching the requests because
5005 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5006 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005007 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005008 } else {
5009 processListenRequests(newNetwork, false);
5010 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005011
Paul Jensencf4c2c62015-07-01 14:16:32 -04005012 // do this after the default net is switched, but
5013 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005014 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005015
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005016 // Linger any networks that are no longer needed. This should be done after sending the
5017 // available callback for newNetwork.
5018 for (NetworkAgentInfo nai : affectedNetworks) {
5019 updateLingerState(nai, now);
5020 }
5021 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5022 // does not need to be done in any particular order.
5023 updateLingerState(newNetwork, now);
5024
Paul Jensencf4c2c62015-07-01 14:16:32 -04005025 if (isNewDefault) {
5026 // Maintain the illusion: since the legacy API only
5027 // understands one network at a time, we must pretend
5028 // that the current default network disconnected before
5029 // the new one connected.
5030 if (oldDefaultNetwork != null) {
5031 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5032 oldDefaultNetwork, true);
5033 }
5034 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5035 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5036 notifyLockdownVpn(newNetwork);
5037 }
5038
Robert Greenwalt7b816022014-04-18 15:25:25 -07005039 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005040 // Notify battery stats service about this network, both the normal
5041 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005042 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005043 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005044 final IBatteryStats bs = BatteryStatsService.getService();
5045 final int type = newNetwork.networkInfo.getType();
5046
5047 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5048 bs.noteNetworkInterfaceType(baseIface, type);
5049 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5050 final String stackedIface = stacked.getInterfaceName();
5051 bs.noteNetworkInterfaceType(stackedIface, type);
5052 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5053 }
5054 } catch (RemoteException ignored) {
5055 }
5056
Robert Greenwalt152ed372014-12-17 17:19:53 -08005057 // This has to happen after the notifyNetworkCallbacks as that tickles each
5058 // ConnectivityManager instance so that legacy requests correctly bind dns
5059 // requests to this network. The legacy users are listening for this bcast
5060 // and will generally do a dns request so they can ensureRouteToHost and if
5061 // they do that before the callbacks happen they'll use the default network.
5062 //
5063 // TODO: Is there still a race here? We send the broadcast
5064 // after sending the callback, but if the app can receive the
5065 // broadcast before the callback, it might still break.
5066 //
5067 // This *does* introduce a race where if the user uses the new api
5068 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5069 // they may get old info. Reverse this after the old startUsing api is removed.
5070 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005071 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5072 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005073 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005074 // legacy type tracker filters out repeat adds
5075 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5076 }
5077 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005078
5079 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5080 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5081 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5082 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5083 if (newNetwork.isVPN()) {
5084 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5085 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005086 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005087 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5088 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005089 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005090 if (nai.getLingerExpiry() > 0) {
5091 // This network has active linger timers and no requests, but is not
5092 // lingering. Linger it.
5093 //
5094 // One way (the only way?) this can happen if this network is unvalidated
5095 // and became unneeded due to another network improving its score to the
5096 // point where this network will no longer be able to satisfy any requests
5097 // even if it validates.
5098 updateLingerState(nai, now);
5099 } else {
5100 if (DBG) log("Reaping " + nai.name());
5101 teardownUnneededNetwork(nai);
5102 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005103 }
5104 }
5105 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005106 }
5107
Paul Jensen1c7ba022015-06-16 14:27:36 -04005108 /**
5109 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5110 * being disconnected.
5111 * @param changed If only one Network's score or capabilities have been modified since the last
5112 * time this function was called, pass this Network in this argument, otherwise pass
5113 * null.
5114 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5115 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5116 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5117 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5118 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005119 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005120 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005121 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5122 // to avoid the slowness. It is not simply enough to process just "changed", for
5123 // example in the case where "changed"'s score decreases and another network should begin
5124 // satifying a NetworkRequest that "changed" currently satisfies.
5125
5126 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5127 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5128 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005129 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005130 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005131 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005132 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005133 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5134 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5135 // Rematch higher scoring networks first to prevent requests first matching a lower
5136 // scoring network and then a higher scoring network, which could produce multiple
5137 // callbacks and inadvertently unlinger networks.
5138 Arrays.sort(nais);
5139 for (NetworkAgentInfo nai : nais) {
5140 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005141 // Only reap the last time through the loop. Reaping before all rematching
5142 // is complete could incorrectly teardown a network that hasn't yet been
5143 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005144 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005145 : ReapUnvalidatedNetworks.REAP,
5146 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005147 }
5148 }
5149 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005150
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005151 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005152 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005153 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005154 // For now only update icons for default connection.
5155 // TODO: Update WiFi and cellular icons separately. b/17237507
5156 if (!isDefaultNetwork(nai)) return;
5157
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005158 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005159 // Don't repeat publish.
5160 if (newInetCondition == mDefaultInetConditionPublished) return;
5161
5162 mDefaultInetConditionPublished = newInetCondition;
5163 sendInetConditionBroadcast(nai.networkInfo);
5164 }
5165
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005166 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5167 if (mLockdownTracker != null) {
5168 if (nai != null && nai.isVPN()) {
5169 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5170 } else {
5171 mLockdownTracker.onNetworkInfoChanged();
5172 }
5173 }
5174 }
5175
Robert Greenwalt7b816022014-04-18 15:25:25 -07005176 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005177 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005178 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005179 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005180 synchronized (networkAgent) {
5181 oldInfo = networkAgent.networkInfo;
5182 networkAgent.networkInfo = newInfo;
5183 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005184 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005185
5186 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005187 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5188 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5189 notifyIfacesChangedForNetworkStats();
5190 } else if (VDBG) log("ignoring duplicate network state non-change");
5191 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005192 return;
5193 }
5194 if (DBG) {
5195 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5196 (oldInfo == null ? "null" : oldInfo.getState()) +
5197 " to " + state);
5198 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005199
Robin Lee585e2482016-05-01 23:00:00 +01005200 if (!networkAgent.created
5201 && (state == NetworkInfo.State.CONNECTED
5202 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005203
5204 // A network that has just connected has zero requests and is thus a foreground network.
5205 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5206
Robert Greenwalt7b816022014-04-18 15:25:25 -07005207 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005208 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005209 if (networkAgent.isVPN()) {
5210 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005211 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5212 (networkAgent.networkMisc == null ||
5213 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005214 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005215 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005216 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005217 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005218 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005219 loge("Error creating network " + networkAgent.network.netId + ": "
5220 + e.getMessage());
5221 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222 }
Paul Jenseneec75412014-08-04 12:21:19 -04005223 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005224 }
5225
5226 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5227 networkAgent.everConnected = true;
5228
Robert Greenwalt7b816022014-04-18 15:25:25 -07005229 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005230 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005231
Paul Jensenca8f16a2014-05-09 12:47:55 -04005232 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005233 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005234
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005235 if (networkAgent.isVPN()) {
5236 // Temporarily disable the default proxy (not global).
5237 synchronized (mProxyLock) {
5238 if (!mDefaultProxyDisabled) {
5239 mDefaultProxyDisabled = true;
5240 if (mGlobalProxy == null && mDefaultProxy != null) {
5241 sendProxyBroadcast(null);
5242 }
5243 }
5244 }
5245 // TODO: support proxy per network.
5246 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005247
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005248 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5249 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5250 // capabilities, so it only needs to be done once on initial connect, not every time the
5251 // network's capabilities change. Note that we do this before rematching the network,
5252 // so we could decide to tear it down immediately afterwards. That's fine though - on
5253 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5254 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005255 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005256
Paul Jensen2161a8e2014-09-11 11:00:39 -04005257 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005258 final long now = SystemClock.elapsedRealtime();
5259 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005260
5261 // This has to happen after matching the requests, because callbacks are just requests.
5262 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005263 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005264 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005265 if (networkAgent.isVPN()) {
5266 synchronized (mProxyLock) {
5267 if (mDefaultProxyDisabled) {
5268 mDefaultProxyDisabled = false;
5269 if (mGlobalProxy == null && mDefaultProxy != null) {
5270 sendProxyBroadcast(mDefaultProxy);
5271 }
5272 }
5273 }
5274 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005275 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5276 state == NetworkInfo.State.SUSPENDED) {
5277 // going into or coming out of SUSPEND: rescore and notify
5278 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005279 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005280 }
5281 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5282 ConnectivityManager.CALLBACK_SUSPENDED :
5283 ConnectivityManager.CALLBACK_RESUMED));
5284 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005285 }
5286 }
5287
Robert Greenwaltac96c522014-06-03 16:43:57 -07005288 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005289 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005290 if (score < 0) {
5291 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5292 "). Bumping score to min of 0");
5293 score = 0;
5294 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005295
Paul Jensen2161a8e2014-09-11 11:00:39 -04005296 final int oldScore = nai.getCurrentScore();
5297 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005298
Paul Jensen85cf78e2015-06-25 13:25:07 -04005299 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005300
Paul Jensenc8b9a742014-09-30 15:37:41 -04005301 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005302 }
5303
Erik Klinec75d4fa2017-02-15 19:59:17 +09005304 // Notify only this one new request of the current state. Transfer all the
5305 // current state by calling NetworkCapabilities and LinkProperties callbacks
5306 // so that callers can be guaranteed to have as close to atomicity in state
5307 // transfer as can be supported by this current API.
5308 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005309 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005310 if (nri.mPendingIntent != null) {
5311 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5312 // Attempt no subsequent state pushes where intents are involved.
5313 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005314 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005315
5316 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5317 // Whether a network is currently suspended is also an important
5318 // element of state to be transferred (it would not otherwise be
5319 // delivered by any currently available mechanism).
5320 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5321 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5322 }
5323 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5324 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005325 }
5326
Robert Greenwalt8d482522015-06-24 13:23:42 -07005327 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005328 // The NetworkInfo we actually send out has no bearing on the real
5329 // state of affairs. For example, if the default connection is mobile,
5330 // and a request for HIPRI has just gone away, we need to pretend that
5331 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5332 // the state to DISCONNECTED, even though the network is of type MOBILE
5333 // and is still connected.
5334 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5335 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005336 if (state != DetailedState.DISCONNECTED) {
5337 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005338 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005339 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005340 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005341 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5342 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5343 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5344 if (info.isFailover()) {
5345 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5346 nai.networkInfo.setFailover(false);
5347 }
5348 if (info.getReason() != null) {
5349 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5350 }
5351 if (info.getExtraInfo() != null) {
5352 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5353 }
5354 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005355 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005356 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005357 if (newDefaultAgent != null) {
5358 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5359 newDefaultAgent.networkInfo);
5360 } else {
5361 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5362 }
5363 }
5364 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5365 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005366 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005367 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005368 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005369 }
5370 }
5371 }
5372
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005373 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005374 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005375 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5376 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005377 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5378 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005379 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5380 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005381 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005382 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005383 } else {
5384 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5385 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005386 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005387 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005388
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005389 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5390 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5391 }
5392
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005393 private String notifyTypeToName(int notifyType) {
5394 switch (notifyType) {
5395 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5396 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5397 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5398 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5399 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5400 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5401 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5402 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5403 }
5404 return "UNKNOWN";
5405 }
5406
Jeff Sharkey69736342014-12-08 14:50:12 -08005407 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005408 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5409 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005410 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005411 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005412 try {
5413 mStatsService.forceUpdateIfaces();
5414 } catch (Exception ignored) {
5415 }
5416 }
5417
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005418 @Override
5419 public boolean addVpnAddress(String address, int prefixLength) {
5420 throwIfLockdownEnabled();
5421 int user = UserHandle.getUserId(Binder.getCallingUid());
5422 synchronized (mVpns) {
5423 return mVpns.get(user).addAddress(address, prefixLength);
5424 }
5425 }
5426
5427 @Override
5428 public boolean removeVpnAddress(String address, int prefixLength) {
5429 throwIfLockdownEnabled();
5430 int user = UserHandle.getUserId(Binder.getCallingUid());
5431 synchronized (mVpns) {
5432 return mVpns.get(user).removeAddress(address, prefixLength);
5433 }
5434 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005435
5436 @Override
5437 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5438 throwIfLockdownEnabled();
5439 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005440 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005441 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005442 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005443 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005444 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005445 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005446 }
5447 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005448 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005449
5450 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005451 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005452 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005453 }
5454
5455 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005456 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5457 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5458 enforceKeepalivePermission();
5459 mKeepaliveTracker.startNattKeepalive(
5460 getNetworkAgentInfoForNetwork(network),
5461 intervalSeconds, messenger, binder,
5462 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5463 }
5464
5465 @Override
5466 public void stopKeepalive(Network network, int slot) {
5467 mHandler.sendMessage(mHandler.obtainMessage(
5468 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5469 }
5470
5471 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005472 public void factoryReset() {
5473 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005474
5475 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5476 return;
5477 }
5478
Robin Lee3b3dd942015-05-12 18:14:58 +01005479 final int userId = UserHandle.getCallingUserId();
5480
Stuart Scottf1fb3972015-04-02 18:00:02 -07005481 // Turn airplane mode off
5482 setAirplaneMode(false);
5483
Stuart Scotte3e314d2015-04-20 14:07:45 -07005484 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5485 // Untether
5486 for (String tether : getTetheredIfaces()) {
5487 untether(tether);
5488 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005489 }
5490
Stuart Scotte3e314d2015-04-20 14:07:45 -07005491 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005492 // Remove always-on package
5493 synchronized (mVpns) {
5494 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5495 if (alwaysOnPackage != null) {
5496 setAlwaysOnVpnPackage(userId, null, false);
5497 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5498 }
5499 }
5500
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005501 // Turn Always-on VPN off
5502 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5503 final long ident = Binder.clearCallingIdentity();
5504 try {
5505 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5506 mLockdownEnabled = false;
5507 setLockdownTracker(null);
5508 } finally {
5509 Binder.restoreCallingIdentity(ident);
5510 }
5511 }
5512
Stuart Scotte3e314d2015-04-20 14:07:45 -07005513 // Turn VPN off
5514 VpnConfig vpnConfig = getVpnConfig(userId);
5515 if (vpnConfig != null) {
5516 if (vpnConfig.legacy) {
5517 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5518 } else {
5519 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5520 // in the future without user intervention.
5521 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005522
Victor Changb04a5ea2016-05-30 20:36:30 +01005523 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005524 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005525 }
5526 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005527
5528 Settings.Global.putString(mContext.getContentResolver(),
5529 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005530 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005531
5532 @VisibleForTesting
5533 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5534 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5535 return new NetworkMonitor(context, handler, nai, defaultRequest);
5536 }
Erik Kline48f12f22016-04-14 17:30:59 +09005537
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005538 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005539 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5540 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005541 }
5542
5543 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005544 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5545 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5546 }
5547
Hugo Benichicfddd682016-05-31 16:28:06 +09005548 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005549 int newNetid = NETID_UNSET;
5550 int prevNetid = NETID_UNSET;
5551 int[] transports = new int[0];
5552 boolean hadIPv4 = false;
5553 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005554
Hugo Benichi5f16f762016-04-20 12:09:33 +09005555 if (newNai != null) {
5556 newNetid = newNai.network.netId;
5557 transports = newNai.networkCapabilities.getTransportTypes();
5558 }
5559 if (prevNai != null) {
5560 prevNetid = prevNai.network.netId;
5561 final LinkProperties lp = prevNai.linkProperties;
5562 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5563 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5564 }
5565
Hugo Benichicfddd682016-05-31 16:28:06 +09005566 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5567 }
5568
5569 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5570 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572}