blob: a2d8aa0b78e390173f7047dad1204c10ca9ccc5d [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080082import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070083import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040084import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070086import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070088import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.Looper;
90import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070091import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070092import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070093import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070094import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080096import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090097import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.SystemProperties;
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;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900134import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900135import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700136import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600137import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400138import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900139import com.android.server.connectivity.NetworkNotificationManager;
140import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400141import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700142import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800143import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700144import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700145import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700146import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600147
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700148import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700149
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import org.xmlpull.v1.XmlPullParser;
151import org.xmlpull.v1.XmlPullParserException;
152
153import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700155import java.io.FileNotFoundException;
156import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700157import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700159import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700160import java.net.InetAddress;
161import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700162import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700163import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700165import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700166import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700167import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700168import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700169import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700170import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600171import java.util.SortedSet;
172import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
174/**
175 * @hide
176 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800177public class ConnectivityService extends IConnectivityManager.Stub
178 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900179 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900181 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700182 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Jake Hamby786e71a2014-02-06 14:43:50 -0800184 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900185 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700186
Jeff Sharkey899223b2012-08-04 15:24:58 -0700187 // TODO: create better separation between radio types and network types
188
Robert Greenwalt42acef32009-08-12 16:08:25 -0700189 // how long to wait before switching back to a radio's default network
190 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
191 // system property that can override the above value
192 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
193 "android.telephony.apn-restore";
194
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900195 // How long to wait before putting up a "This network doesn't have an Internet connection,
196 // connect anyway?" dialog after the user selects a network that doesn't validate.
197 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
198
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900199 // Default to 30s linger time-out. Modifiable only for testing.
200 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
201 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
202 @VisibleForTesting
203 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
204
Jeremy Joslin79294842014-12-03 17:15:28 -0800205 // How long to delay to removal of a pending intent based request.
206 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
207 private final int mReleasePendingIntentDelayMs;
208
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800209 private Tethering mTethering;
210
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700211 private final PermissionMonitor mPermissionMonitor;
212
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700213 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700214
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700215 @GuardedBy("mVpns")
216 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700217
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700218 private boolean mLockdownEnabled;
219 private LockdownVpnTracker mLockdownTracker;
220
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700221 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
222 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700223 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600224 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700225 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700226 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600227 @GuardedBy("mRulesLock")
228 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
229 /** Flag indicating if background data is restricted. */
230 @GuardedBy("mRulesLock")
231 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700232
Erik Klineda4bfa82015-04-30 12:58:40 +0900233 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700235 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700236 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800238 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700241 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700243 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800244 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700245 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700246
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700247 private String mCurrentTcpBufferSizes;
248
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700249 private static final int ENABLED = 1;
250 private static final int DISABLED = 0;
251
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900252 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900253 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
254 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900255
Paul Jensenb10e37f2014-11-25 12:33:08 -0500256 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400257 // Tear down networks that have no chance (e.g. even if validated) of becoming
258 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500259 // all networks have been rematched against all NetworkRequests.
260 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400261 // Don't reap networks. This should be passed when some networks have not yet been
262 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500263 DONT_REAP
264 };
265
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900266 private enum UnneededFor {
267 LINGER, // Determine whether this network is unneeded and should be lingered.
268 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
269 }
270
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700271 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700272 * used internally to change our mobile data enabled flag
273 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700274 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700275
276 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700277 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700278 * from one net to another. Clear happens when we get a new
279 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
280 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700281 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700282 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283
Robert Greenwalt434203a2010-10-11 16:00:27 -0700284 /**
285 * used internally to reload global proxy settings
286 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700287 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700288
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700289 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400290 * PAC manager has received new port.
291 */
292 private static final int EVENT_PROXY_HAS_CHANGED = 16;
293
Robert Greenwalte049c232014-04-11 15:53:27 -0700294 /**
295 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700296 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700297 */
298 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
299
Robert Greenwalt7b816022014-04-18 15:25:25 -0700300 /**
301 * used internally when registering NetworkAgents
302 * obj = Messenger
303 */
304 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
305
Robert Greenwalt9258c642014-03-26 16:47:06 -0700306 /**
307 * used to add a network request
308 * includes a NetworkRequestInfo
309 */
310 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
311
312 /**
313 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900314 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700315 * cancel it.
316 * includes a NetworkRequestInfo
317 */
318 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
319
320 /**
321 * used to add a network listener - no request
322 * includes a NetworkRequestInfo
323 */
324 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
325
326 /**
327 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400328 * arg1 = UID of caller
329 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700330 */
331 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
332
Robert Greenwalta67be032014-05-16 15:49:14 -0700333 /**
334 * used internally when registering NetworkFactories
335 * obj = Messenger
336 */
337 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
338
Robert Greenwalt27711812014-06-25 16:45:57 -0700339 /**
340 * used internally to expire a wakelock when transitioning
341 * from one net to another. Expire happens when we fail to find
342 * a new network (typically after 1 minute) -
343 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
344 * a replacement network.
345 */
346 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
347
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700348 /**
349 * Used internally to indicate the system is ready.
350 */
351 private static final int EVENT_SYSTEM_READY = 25;
352
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800353 /**
354 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400355 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800356 */
357 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
358
359 /**
360 * used to remove a pending intent and its associated network request.
361 * arg1 = UID of caller
362 * obj = PendingIntent
363 */
364 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
365
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900366 /**
367 * used to specify whether a network should be used even if unvalidated.
368 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
369 * arg2 = whether to remember this choice in the future (1 or 0)
370 * obj = network
371 */
372 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
373
374 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900375 * used to specify whether a network should not be penalized when it becomes unvalidated.
376 */
377 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
378
379 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900380 * used to ask the user to confirm a connection to an unvalidated network.
381 * obj = network
382 */
383 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700384
Erik Klineda4bfa82015-04-30 12:58:40 +0900385 /**
386 * used internally to (re)configure mobile data always-on settings.
387 */
388 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
389
Paul Jensen694f2b82015-06-17 14:15:39 -0400390 /**
391 * used to add a network listener with a pending intent
392 * obj = NetworkRequestInfo
393 */
394 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
395
Erik Klineacdd6392016-07-07 16:50:58 +0900396 /**
397 * Indicates a caller has requested to have its callback invoked with
398 * the latest LinkProperties or NetworkCapabilities.
399 *
400 * arg1 = UID of caller
401 * obj = NetworkRequest
402 */
403 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
404 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
405
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900406 /**
407 * Used internally to (re)configure avoid bad wifi setting.
408 */
409 private static final int EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI = 34;
410
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900411 /** Handler thread used for both of the handlers below. */
412 @VisibleForTesting
413 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700414 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700415 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700416 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700417 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700418
Mike Lockwood0f79b542009-08-14 14:18:49 -0400419 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800420 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400421
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700422 private PowerManager.WakeLock mNetTransitionWakeLock;
423 private String mNetTransitionWakeLockCausedBy = "";
424 private int mNetTransitionWakeLockSerialNumber;
425 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800426 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700427
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700428 // used in DBG mode to track inet condition reports
429 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
430 private ArrayList mInetLog;
431
Robert Greenwalt434203a2010-10-11 16:00:27 -0700432 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400433 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700434 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700435 private boolean mDefaultProxyDisabled = false;
436
Robert Greenwalt434203a2010-10-11 16:00:27 -0700437 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400438 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700439
Jason Monk602b2322013-07-03 17:04:33 -0400440 private PacManager mPacManager = null;
441
Erik Klineda4bfa82015-04-30 12:58:40 +0900442 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700443
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400444 private UserManager mUserManager;
445
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700446 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700447 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700448
Robert Greenwalt50393202011-06-21 17:26:14 -0700449 // the set of network types that can only be enabled by system/sig apps
450 List mProtectedNetworks;
451
John Spurlockbf991a82013-06-24 14:20:23 -0400452 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700453
Wink Savilleab9321d2013-06-29 21:10:57 -0700454 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400455
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900456 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900457 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900458 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900459
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700460 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
461 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700462 private final static int MAX_NET_ID = 65535;
463 private int mNextNetId = MIN_NET_ID;
464
Robert Greenwalt34524f02014-05-18 16:22:10 -0700465 // sequence number of NetworkRequests
466 private int mNextNetworkRequestId = 1;
467
Erik Kline7523eb32015-07-09 18:24:03 +0900468 // NetworkRequest activity String log entries.
469 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
470 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
471
Hugo Benichic2ae2872016-07-11 11:05:12 +0900472 // NetworkInfo blocked and unblocked String log entries
473 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
474 private static final int MAX_NETWORK_INFO_LOGS = 100;
475 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
476
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700477 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
478 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400479 private static class ValidationLog {
480 final Network mNetwork;
481 final String mNetworkExtraInfo;
482 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483
Paul Jensen0808eb82016-06-03 13:51:21 -0400484 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
485 mNetwork = network;
486 mNetworkExtraInfo = networkExtraInfo;
487 mLog = log;
488 }
489 }
490 private final ArrayDeque<ValidationLog> mValidationLogs =
491 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
492
493 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700494 synchronized(mValidationLogs) {
495 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
496 mValidationLogs.removeLast();
497 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400498 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700499 }
500 }
501
Hugo Benichif9fdf872016-07-28 17:53:06 +0900502 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900503
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700504 /**
505 * Implements support for the legacy "one network per network type" model.
506 *
507 * We used to have a static array of NetworkStateTrackers, one for each
508 * network type, but that doesn't work any more now that we can have,
509 * for example, more that one wifi network. This class stores all the
510 * NetworkAgentInfo objects that support a given type, but the legacy
511 * API will only see the first one.
512 *
513 * It serves two main purposes:
514 *
515 * 1. Provide information about "the network for a given type" (since this
516 * API only supports one).
517 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
518 * the first network for a given type changes, or if the default network
519 * changes.
520 */
521 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900522
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900523 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700526 /**
527 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
528 * Each list holds references to all NetworkAgentInfos that are used to
529 * satisfy requests for that network type.
530 *
531 * This array is built out at startup such that an unsupported network
532 * doesn't get an ArrayList instance, making this a tristate:
533 * unsupported, supported but not active and active.
534 *
535 * The actual lists are populated when we scan the network types that
536 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900537 *
538 * Threading model:
539 * - addSupportedType() is only called in the constructor
540 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
541 * They are therefore not thread-safe with respect to each other.
542 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
543 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
544 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700545 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900546 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700547
548 public LegacyTypeTracker() {
549 mTypeLists = (ArrayList<NetworkAgentInfo>[])
550 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
551 }
552
553 public void addSupportedType(int type) {
554 if (mTypeLists[type] != null) {
555 throw new IllegalStateException(
556 "legacy list for type " + type + "already initialized");
557 }
558 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
559 }
560
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 public boolean isTypeSupported(int type) {
562 return isNetworkTypeValid(type) && mTypeLists[type] != null;
563 }
564
565 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900566 synchronized (mTypeLists) {
567 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
568 return mTypeLists[type].get(0);
569 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700570 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900571 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 }
573
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900575 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900576 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900578 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900579 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 }
581 }
582
583 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 public void add(int type, NetworkAgentInfo nai) {
585 if (!isTypeSupported(type)) {
586 return; // Invalid network type.
587 }
588 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
589
590 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
591 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 return;
593 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900594 synchronized (mTypeLists) {
595 list.add(nai);
596 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900597
598 // 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 +0900599 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900600 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700601 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
602 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700603 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700604 }
605
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900607 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
609 if (list == null || list.isEmpty()) {
610 return;
611 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900612 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613
Hugo Benichi78caa2582016-06-21 09:48:07 +0900614 synchronized (mTypeLists) {
615 if (!list.remove(nai)) {
616 return;
617 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 }
619
Robert Greenwalt8d482522015-06-24 13:23:42 -0700620 final DetailedState state = DetailedState.DISCONNECTED;
621
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900622 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700623 maybeLogBroadcast(nai, state, type, wasDefault);
624 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900625 }
626
627 if (!list.isEmpty() && wasFirstNetwork) {
628 if (DBG) log("Other network available for type " + type +
629 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700631 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
632 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900633 }
634 }
635
636 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900637 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
638 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700639 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900640 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700641 }
642 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700643
Robert Greenwalt8d482522015-06-24 13:23:42 -0700644 // send out another legacy broadcast - currently only used for suspend/unsuspend
645 // toggle
646 public void update(NetworkAgentInfo nai) {
647 final boolean isDefault = isDefaultNetwork(nai);
648 final DetailedState state = nai.networkInfo.getDetailedState();
649 for (int type = 0; type < mTypeLists.length; type++) {
650 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700651 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900652 final boolean isFirst = contains && (nai == list.get(0));
653 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700654 maybeLogBroadcast(nai, state, type, isDefault);
655 sendLegacyNetworkBroadcast(nai, state, type);
656 }
657 }
658 }
659
Lorenzo Colittia793a672014-07-31 23:20:17 +0900660 private String naiToString(NetworkAgentInfo nai) {
661 String name = (nai != null) ? nai.name() : "null";
662 String state = (nai.networkInfo != null) ?
663 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
664 "???/???";
665 return name + " " + state;
666 }
667
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700668 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900669 pw.println("mLegacyTypeTracker:");
670 pw.increaseIndent();
671 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700672 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900673 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700674 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900675 pw.println();
676 pw.println("Current state:");
677 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900678 synchronized (mTypeLists) {
679 for (int type = 0; type < mTypeLists.length; type++) {
680 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
681 for (NetworkAgentInfo nai : mTypeLists[type]) {
682 pw.println(type + " " + naiToString(nai));
683 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900684 }
685 }
686 pw.decreaseIndent();
687 pw.decreaseIndent();
688 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700689 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 }
691 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
692
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900693 @VisibleForTesting
694 protected HandlerThread createHandlerThread() {
695 return new HandlerThread("ConnectivityServiceThread");
696 }
697
Jeff Sharkey899223b2012-08-04 15:24:58 -0700698 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700699 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900700 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
701 }
702
703 @VisibleForTesting
704 protected ConnectivityService(Context context, INetworkManagementService netManager,
705 INetworkStatsService statsService, INetworkPolicyManager policyManager,
706 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800707 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800708
Hugo Benichif9fdf872016-07-28 17:53:06 +0900709 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900710 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900711 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900712 mNetworkRequests.put(mDefaultRequest, defaultNRI);
713 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900714
715 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900716 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700717
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900718 mHandlerThread = createHandlerThread();
719 mHandlerThread.start();
720 mHandler = new InternalHandler(mHandlerThread.getLooper());
721 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700722
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800723 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800724 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
725 String id = Settings.Secure.getString(context.getContentResolver(),
726 Settings.Secure.ANDROID_ID);
727 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700728 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800729 SystemProperties.set("net.hostname", name);
730 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800731 }
732
Jeremy Joslin79294842014-12-03 17:15:28 -0800733 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
734 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
735
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900736 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
737
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700738 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700739 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800740 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700741 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700742 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700743 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700744
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700745 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600746 mPolicyManager.setConnectivityListener(mPolicyListener);
747 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700748 } catch (RemoteException e) {
749 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700750 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700751 }
752
753 final PowerManager powerManager = (PowerManager) context.getSystemService(
754 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700755 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
756 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
757 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800758 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700759
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700760 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700761
Wink Saville51f456f2013-04-23 14:26:51 -0700762 // TODO: What is the "correct" way to do determine if this is a wifi only device?
763 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
764 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700765 String[] naStrings = context.getResources().getStringArray(
766 com.android.internal.R.array.networkAttributes);
767 for (String naString : naStrings) {
768 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700769 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700770 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700771 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800772 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700773 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700775 }
Wink Saville51f456f2013-04-23 14:26:51 -0700776 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
777 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
778 n.type);
779 continue;
780 }
Wink Saville975c8482011-04-07 14:23:45 -0700781 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800782 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700783 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700784 continue;
785 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700786 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700787
Wink Saville975c8482011-04-07 14:23:45 -0700788 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700789 mNetworksDefined++;
790 } catch(Exception e) {
791 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700792 }
793 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700794
795 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
796 if (mNetConfigs[TYPE_VPN] == null) {
797 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
798 // don't need to add TYPE_VPN to mNetConfigs.
799 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
800 mNetworksDefined++; // used only in the log() statement below.
801 }
802
Wink Saville5e56bc52013-07-29 15:00:57 -0700803 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700804
Robert Greenwalt50393202011-06-21 17:26:14 -0700805 mProtectedNetworks = new ArrayList<Integer>();
806 int[] protectedNetworks = context.getResources().getIntArray(
807 com.android.internal.R.array.config_protectedNetworks);
808 for (int p : protectedNetworks) {
809 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
810 mProtectedNetworks.add(p);
811 } else {
812 if (DBG) loge("Ignoring protectedNetwork " + p);
813 }
814 }
815
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700816 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
817 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700818
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800819 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800820
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700821 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
822
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700823 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700824 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100825 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700826 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700827 intentFilter.addAction(Intent.ACTION_USER_ADDED);
828 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000829 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700830 mContext.registerReceiverAsUser(
831 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900832
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700833 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700834 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700835 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700836 } catch (RemoteException e) {
837 loge("Error registering observer :" + e);
838 }
839
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700840 if (DBG) {
841 mInetLog = new ArrayList();
842 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700843
Erik Klineda4bfa82015-04-30 12:58:40 +0900844 mSettingsObserver = new SettingsObserver(mContext, mHandler);
845 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800846
John Spurlockbf991a82013-06-24 14:20:23 -0400847 mDataConnectionStats = new DataConnectionStats(mContext);
848 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400849
Jason Monkdecd2952013-10-10 14:02:51 -0400850 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700851
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400852 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900853
854 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900855 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
856 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900857
858 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
859 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
860 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
861 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
862 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
863 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
864 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900865
866 intentFilter = new IntentFilter();
867 intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
868 mContext.registerReceiverAsUser(new BroadcastReceiver() {
869 public void onReceive(Context context, Intent intent) {
870 mHandler.sendEmptyMessage(EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
871 }
872 }, UserHandle.ALL, intentFilter, null, null);
873 updateAvoidBadWifi();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700875
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900876 private NetworkRequest createInternetRequestForTransport(
877 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900878 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900879 netCap.addCapability(NET_CAPABILITY_INTERNET);
880 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900881 if (transportType > -1) {
882 netCap.addTransportType(transportType);
883 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900884 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900885 }
886
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900887 // Used only for testing.
888 // TODO: Delete this and either:
889 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
890 // changing ContentResolver to make registerContentObserver non-final).
891 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
892 // by subclassing SettingsObserver.
893 @VisibleForTesting
894 void updateMobileDataAlwaysOn() {
895 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
896 }
897
Erik Klineda4bfa82015-04-30 12:58:40 +0900898 private void handleMobileDataAlwaysOn() {
899 final boolean enable = (Settings.Global.getInt(
900 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
901 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
902 if (enable == isEnabled) {
903 return; // Nothing to do.
904 }
905
906 if (enable) {
907 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900908 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900909 } else {
910 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
911 }
912 }
913
914 private void registerSettingsCallbacks() {
915 // Watch for global HTTP proxy changes.
916 mSettingsObserver.observe(
917 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
918 EVENT_APPLY_GLOBAL_HTTP_PROXY);
919
920 // Watch for whether or not to keep mobile data always on.
921 mSettingsObserver.observe(
922 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
923 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900924
925 // Watch for whether to automatically switch away from wifi networks that lose Internet
926 // access.
927 mSettingsObserver.observe(
928 Settings.Global.getUriFor(Settings.Global.NETWORK_AVOID_BAD_WIFI),
929 EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900930 }
931
Robert Greenwalt34524f02014-05-18 16:22:10 -0700932 private synchronized int nextNetworkRequestId() {
933 return mNextNetworkRequestId++;
934 }
935
Paul Jensen67b0b072015-06-10 11:22:17 -0400936 @VisibleForTesting
937 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400938 synchronized (mNetworkForNetId) {
939 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
940 int netId = mNextNetId;
941 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
942 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500943 if (!mNetIdInUse.get(netId)) {
944 mNetIdInUse.put(netId, true);
945 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400946 }
947 }
948 }
949 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700950 }
951
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600952 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800953 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600954 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
955 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800956 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600957 state = nai.getNetworkState();
958 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600960 final NetworkInfo info = new NetworkInfo(networkType, 0,
961 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
963 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600964 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
965 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800966 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600967 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600968 return state;
969 } else {
970 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400972 }
973
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800974 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
975 if (network == null) {
976 return null;
977 }
978 synchronized (mNetworkForNetId) {
979 return mNetworkForNetId.get(network.netId);
980 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600981 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900983 private Network[] getVpnUnderlyingNetworks(int uid) {
984 if (!mLockdownEnabled) {
985 int user = UserHandle.getUserId(uid);
986 synchronized (mVpns) {
987 Vpn vpn = mVpns.get(user);
988 if (vpn != null && vpn.appliesToUid(uid)) {
989 return vpn.getUnderlyingNetworks();
990 }
991 }
992 }
993 return null;
994 }
995
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800996 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400997 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800998
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900999 final Network[] networks = getVpnUnderlyingNetworks(uid);
1000 if (networks != null) {
1001 // getUnderlyingNetworks() returns:
1002 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1003 // empty array => the VPN explicitly said "no default network".
1004 // non-empty array => the VPN specified one or more default networks; we use the
1005 // first one.
1006 if (networks.length > 0) {
1007 nai = getNetworkAgentInfoForNetwork(networks[0]);
1008 } else {
1009 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001010 }
1011 }
1012
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001013 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001014 return nai.getNetworkState();
1015 } else {
1016 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001017 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001018 }
1019
1020 /**
1021 * Check if UID should be blocked from using the network with the given LinkProperties.
1022 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001023 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1024 boolean ignoreBlocked) {
1025 // Networks aren't blocked when ignoring blocked status
1026 if (ignoreBlocked) return false;
1027 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001028 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001029
1030 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001031 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001032
Robin Lee17e61832016-05-09 13:46:28 +01001033 synchronized (mVpns) {
1034 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1035 if (vpn != null && vpn.isBlockingUid(uid)) {
1036 return true;
1037 }
1038 }
1039
Robert Greenwalt12e67352014-05-13 21:41:06 -07001040 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001041 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001042 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001043 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001044 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001045
Felipe Lemed31a97f2016-05-06 14:53:50 -07001046 boolean allowed = true;
1047 // Check Data Saver Mode first...
1048 if (networkMetered) {
1049 if ((uidRules & RULE_REJECT_METERED) != 0) {
1050 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1051 // Explicitly blacklisted.
1052 allowed = false;
1053 } else {
1054 allowed = !mRestrictBackground
1055 || (uidRules & RULE_ALLOW_METERED) != 0
1056 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1057 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1058 + " mRestrictBackground=" + mRestrictBackground
1059 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1060 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1061 + ": " + allowed);
1062 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001063 }
Felipe Leme781ba142016-05-09 16:24:48 -07001064 // ...then power restrictions.
1065 if (allowed) {
1066 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001067 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001068 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001069 }
1070 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 }
1072
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001073 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001074 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1075 return;
1076 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001077 boolean removed = false;
1078 boolean added = false;
1079 synchronized (mBlockedAppUids) {
1080 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1081 added = true;
1082 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1083 removed = true;
1084 }
1085 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001086 if (added) {
1087 log("Returning blocked NetworkInfo to uid=" + uid);
1088 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1089 } else if (removed) {
1090 log("Returning unblocked NetworkInfo to uid=" + uid);
1091 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1092 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001093 }
1094
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001095 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001096 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1097 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1098 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1099 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001100 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001101 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001102 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1103
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001104 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001105 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001106 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001107 if (mLockdownTracker != null) {
1108 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001109 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001110
1111 // TODO: apply metered state closer to NetworkAgentInfo
1112 final long token = Binder.clearCallingIdentity();
1113 try {
1114 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1115 } catch (RemoteException e) {
1116 } finally {
1117 Binder.restoreCallingIdentity(token);
1118 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001119 }
1120
1121 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 * Return NetworkInfo for the active (i.e., connected) network interface.
1123 * It is assumed that at most one network is active at a time. If more
1124 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001125 * @return the info for the active network, or {@code null} if none is
1126 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001128 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001130 enforceAccessPermission();
1131 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001132 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001133 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001134 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1135 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 }
1137
Paul Jensen31a94f42015-02-13 14:18:39 -05001138 @Override
1139 public Network getActiveNetwork() {
1140 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001141 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001142 }
1143
1144 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001145 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001146 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001148 }
1149
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001150 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001151 final int user = UserHandle.getUserId(uid);
1152 int vpnNetId = NETID_UNSET;
1153 synchronized (mVpns) {
1154 final Vpn vpn = mVpns.get(user);
1155 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1156 }
1157 NetworkAgentInfo nai;
1158 if (vpnNetId != NETID_UNSET) {
1159 synchronized (mNetworkForNetId) {
1160 nai = mNetworkForNetId.get(vpnNetId);
1161 }
1162 if (nai != null) return nai.network;
1163 }
1164 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001165 if (nai != null
1166 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1167 nai = null;
1168 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001169 return nai != null ? nai.network : null;
1170 }
1171
Lorenzo Colitti18660282016-07-04 12:55:44 +09001172 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001173 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1174 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 final int uid = Binder.getCallingUid();
1176 NetworkState state = getUnfilteredActiveNetworkState(uid);
1177 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001178 }
1179
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001180 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001181 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001182 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001183 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001184 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001185 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001186 }
1187
1188 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 public NetworkInfo getNetworkInfo(int networkType) {
1190 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001191 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001192 if (getVpnUnderlyingNetworks(uid) != null) {
1193 // A VPN is active, so we may need to return one of its underlying networks. This
1194 // information is not available in LegacyTypeTracker, so we have to get it from
1195 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001196 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001197 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001198 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001199 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001200 }
1201 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001202 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
1205
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001206 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001207 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001208 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001209 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001211 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001212 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001213 return state.networkInfo;
1214 } else {
1215 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001216 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001217 }
1218
1219 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 public NetworkInfo[] getAllNetworkInfo() {
1221 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001222 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001223 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1224 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001225 NetworkInfo info = getNetworkInfo(networkType);
1226 if (info != null) {
1227 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001230 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001233 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001234 public Network getNetworkForType(int networkType) {
1235 enforceAccessPermission();
1236 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001237 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1238 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001240 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001241 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001242 }
1243
1244 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001245 public Network[] getAllNetworks() {
1246 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001247 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001248 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001249 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001250 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001251 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001252 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001253 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001254 }
1255
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001256 @Override
1257 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1258 // The basic principle is: if an app's traffic could possibly go over a
1259 // network, without the app doing anything multinetwork-specific,
1260 // (hence, by "default"), then include that network's capabilities in
1261 // the array.
1262 //
1263 // In the normal case, app traffic only goes over the system's default
1264 // network connection, so that's the only network returned.
1265 //
1266 // With a VPN in force, some app traffic may go into the VPN, and thus
1267 // over whatever underlying networks the VPN specifies, while other app
1268 // traffic may go over the system default network (e.g.: a split-tunnel
1269 // VPN, or an app disallowed by the VPN), so the set of networks
1270 // returned includes the VPN's underlying networks and the system
1271 // default.
1272 enforceAccessPermission();
1273
1274 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1275
1276 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001277 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001278 if (nc != null) {
1279 result.put(nai.network, nc);
1280 }
1281
1282 if (!mLockdownEnabled) {
1283 synchronized (mVpns) {
1284 Vpn vpn = mVpns.get(userId);
1285 if (vpn != null) {
1286 Network[] networks = vpn.getUnderlyingNetworks();
1287 if (networks != null) {
1288 for (Network network : networks) {
1289 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001290 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001291 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001292 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001293 }
1294 }
1295 }
1296 }
1297 }
1298 }
1299
1300 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1301 out = result.values().toArray(out);
1302 return out;
1303 }
1304
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001305 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001306 public boolean isNetworkSupported(int networkType) {
1307 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001308 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001309 }
1310
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001311 /**
1312 * Return LinkProperties for the active (i.e., connected) default
1313 * network interface. It is assumed that at most one default network
1314 * is active at a time. If more than one is active, it is indeterminate
1315 * which will be returned.
1316 * @return the ip properties for the active network, or {@code null} if
1317 * none is active
1318 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001319 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001320 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001321 enforceAccessPermission();
1322 final int uid = Binder.getCallingUid();
1323 NetworkState state = getUnfilteredActiveNetworkState(uid);
1324 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001325 }
1326
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001327 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001328 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001329 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001330 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1331 if (nai != null) {
1332 synchronized (nai) {
1333 return new LinkProperties(nai.linkProperties);
1334 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001335 }
1336 return null;
1337 }
1338
Robert Greenwalt12e67352014-05-13 21:41:06 -07001339 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001340 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001341 public LinkProperties getLinkProperties(Network network) {
1342 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001343 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001344 if (nai != null) {
1345 synchronized (nai) {
1346 return new LinkProperties(nai.linkProperties);
1347 }
1348 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001349 return null;
1350 }
1351
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001352 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001353 if (nai != null) {
1354 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001355 if (nai.networkCapabilities != null) {
1356 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001357 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001358 }
1359 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001360 return null;
1361 }
1362
1363 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001364 public NetworkCapabilities getNetworkCapabilities(Network network) {
1365 enforceAccessPermission();
1366 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1367 }
1368
1369 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001370 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001371 // Require internal since we're handing out IMSI details
1372 enforceConnectivityInternalPermission();
1373
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001374 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001375 for (Network network : getAllNetworks()) {
1376 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1377 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001378 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001379 }
1380 }
1381 return result.toArray(new NetworkState[result.size()]);
1382 }
1383
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001384 @Override
1385 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1386 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001387 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001388 final long token = Binder.clearCallingIdentity();
1389 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001390 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1391 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001392 try {
1393 return mPolicyManager.getNetworkQuotaInfo(state);
1394 } catch (RemoteException e) {
1395 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001396 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001397 return null;
1398 } finally {
1399 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001400 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001401 }
1402
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001403 @Override
1404 public boolean isActiveNetworkMetered() {
1405 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001406
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001407 final NetworkInfo info = getActiveNetworkInfo();
1408 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001409 }
1410
Jeff Sharkey216c1812012-08-05 14:29:23 -07001411 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1412 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001413 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001414 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001415 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001416 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001417 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001418
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001419 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 * Ensure that a network route exists to deliver traffic to the specified
1421 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001422 * @param networkType the type of the network over which traffic to the
1423 * specified host is to be routed
1424 * @param hostAddress the IP address of the host to which the route is
1425 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 * @return {@code true} on success, {@code false} on failure
1427 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001428 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001429 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001431 if (mProtectedNetworks.contains(networkType)) {
1432 enforceConnectivityInternalPermission();
1433 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001434
Chad Brubakerc0234532014-02-14 13:24:29 -08001435 InetAddress addr;
1436 try {
1437 addr = InetAddress.getByAddress(hostAddress);
1438 } catch (UnknownHostException e) {
1439 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1440 return false;
1441 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001444 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 return false;
1446 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001447
1448 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1449 if (nai == null) {
1450 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1451 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1452 } else {
1453 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1454 }
1455 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001456 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001457
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001458 DetailedState netState;
1459 synchronized (nai) {
1460 netState = nai.networkInfo.getDetailedState();
1461 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001462
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001463 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001464 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001465 log("requestRouteToHostAddress on down network "
1466 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001467 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001468 }
1469 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001471
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001472 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001473 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001474 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001475 LinkProperties lp;
1476 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001477 synchronized (nai) {
1478 lp = nai.linkProperties;
1479 netId = nai.network.netId;
1480 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001481 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001482 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1483 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001484 } finally {
1485 Binder.restoreCallingIdentity(token);
1486 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001487 }
1488
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001489 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001490 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001491 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001492 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001493 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001494 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001495 if (bestRoute.getGateway().equals(addr)) {
1496 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001497 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001498 } else {
1499 // if we will connect to this through another route, add a direct route
1500 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001501 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001502 }
1503 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001504 if (DBG) log("Adding legacy route " + bestRoute +
1505 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001506 try {
1507 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1508 } catch (Exception e) {
1509 // never crash - catch them all
1510 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001511 return false;
1512 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001513 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001516 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1517 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001518 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001519 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001520 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001521 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001522 }
1523
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001524 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001525 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001526 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001527 if (oldRules == uidRules) return;
1528
Felipe Leme781ba142016-05-09 16:24:48 -07001529 if (uidRules == RULE_NONE) {
1530 mUidRules.delete(uid);
1531 } else {
1532 mUidRules.put(uid, uidRules);
1533 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001534 }
1535
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001536 // TODO: notify UID when it has requested targeted updates
1537 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001538
1539 @Override
1540 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001541 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001542 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001543 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001544 }
1545
1546 synchronized (mRulesLock) {
1547 mMeteredIfaces.clear();
1548 for (String iface : meteredIfaces) {
1549 mMeteredIfaces.add(iface);
1550 }
1551 }
1552 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001553
1554 @Override
1555 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1556 // caller is NPMS, since we only register with them
1557 if (LOGD_RULES) {
1558 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1559 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001560
1561 synchronized (mRulesLock) {
1562 mRestrictBackground = restrictBackground;
1563 }
1564
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001565 if (restrictBackground) {
1566 log("onRestrictBackgroundChanged(true): disabling tethering");
1567 mTethering.untetherAll();
1568 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001569 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001570
1571 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001572 public void onUidPoliciesChanged(int uid, int uidPolicies) {
1573 // caller is NPMS, since we only register with them
Felipe Leme019fcd22016-04-19 10:24:39 -07001574 if (LOGD_RULES) {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001575 log("onUidRulesChanged(uid=" + uid + ", uidPolicies=" + uidPolicies + ")");
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001576 }
1577 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001578 };
1579
Robin Lee3b3dd942015-05-12 18:14:58 +01001580 /**
1581 * Require that the caller is either in the same user or has appropriate permission to interact
1582 * across users.
1583 *
1584 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1585 */
1586 private void enforceCrossUserPermission(int userId) {
1587 if (userId == UserHandle.getCallingUserId()) {
1588 // Not a cross-user call.
1589 return;
1590 }
1591 mContext.enforceCallingOrSelfPermission(
1592 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1593 "ConnectivityService");
1594 }
1595
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001596 private void enforceInternetPermission() {
1597 mContext.enforceCallingOrSelfPermission(
1598 android.Manifest.permission.INTERNET,
1599 "ConnectivityService");
1600 }
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001603 mContext.enforceCallingOrSelfPermission(
1604 android.Manifest.permission.ACCESS_NETWORK_STATE,
1605 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607
1608 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001609 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
1611
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001612 private void enforceTetherAccessPermission() {
1613 mContext.enforceCallingOrSelfPermission(
1614 android.Manifest.permission.ACCESS_NETWORK_STATE,
1615 "ConnectivityService");
1616 }
1617
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001618 private void enforceConnectivityInternalPermission() {
1619 mContext.enforceCallingOrSelfPermission(
1620 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1621 "ConnectivityService");
1622 }
1623
Hugo Benichi514da602016-07-19 15:59:27 +09001624 private void enforceConnectivityRestrictedNetworksPermission() {
1625 try {
1626 mContext.enforceCallingOrSelfPermission(
1627 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1628 "ConnectivityService");
1629 return;
1630 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1631 enforceConnectivityInternalPermission();
1632 }
1633
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001634 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001635 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001636 }
1637
Lorenzo Colitti18660282016-07-04 12:55:44 +09001638 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001639 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001640 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001641 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001642 }
1643
1644 private void sendInetConditionBroadcast(NetworkInfo info) {
1645 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1646 }
1647
Wink Saville628b0852011-08-04 15:01:58 -07001648 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001649 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001650 info = new NetworkInfo(info);
1651 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001652 }
1653
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001654 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001655 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001656 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 if (info.isFailover()) {
1658 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1659 info.setFailover(false);
1660 }
1661 if (info.getReason() != null) {
1662 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1663 }
1664 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001665 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1666 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001668 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001669 return intent;
1670 }
1671
1672 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1673 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1674 }
1675
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001676 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001677 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1678 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1679 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001680 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001681 final long ident = Binder.clearCallingIdentity();
1682 try {
1683 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1684 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1685 } finally {
1686 Binder.restoreCallingIdentity(ident);
1687 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001688 }
1689
Mike Lockwood0f79b542009-08-14 14:18:49 -04001690 private void sendStickyBroadcast(Intent intent) {
1691 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001692 if (!mSystemReady) {
1693 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001694 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001695 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001696 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001697 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001698 }
1699
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001700 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001701 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001702 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001703 final NetworkInfo ni = intent.getParcelableExtra(
1704 ConnectivityManager.EXTRA_NETWORK_INFO);
1705 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1706 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1707 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001708 } else {
1709 BroadcastOptions opts = BroadcastOptions.makeBasic();
1710 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1711 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001712 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001713 final IBatteryStats bs = BatteryStatsService.getService();
1714 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001715 bs.noteConnectivityChanged(intent.getIntExtra(
1716 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1717 ni != null ? ni.getState().toString() : "?");
1718 } catch (RemoteException e) {
1719 }
1720 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001721 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001722 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001723 } finally {
1724 Binder.restoreCallingIdentity(ident);
1725 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001726 }
1727 }
1728
1729 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001730 loadGlobalProxy();
1731
Mike Lockwood0f79b542009-08-14 14:18:49 -04001732 synchronized(this) {
1733 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001734 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001735 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001736 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001737 }
1738 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001739 // load the global proxy at startup
1740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001741
Robin Lee244ce8e2016-01-05 18:03:46 +00001742 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1743 // for user to unlock device too.
1744 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001745
Erik Klineda4bfa82015-04-30 12:58:40 +09001746 // Configure whether mobile data is always on.
1747 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1748
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001749 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001750
1751 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001755 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001756 *
1757 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001758 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001759 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001760 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1761 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001762
1763 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001764 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001765
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 if (networkAgent.networkCapabilities.hasTransport(
1767 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001768 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1769 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001770 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001771 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001772 } else if (networkAgent.networkCapabilities.hasTransport(
1773 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001774 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1775 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001776 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001777 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001778 } else {
1779 // do not track any other networks
1780 timeout = 0;
1781 }
1782
Robert Greenwalt7b816022014-04-18 15:25:25 -07001783 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001784 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001785 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001786 } catch (Exception e) {
1787 // You shall not crash!
1788 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001789 }
1790 }
1791 }
1792
1793 /**
1794 * Remove data activity tracking when network disconnects.
1795 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001796 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1797 final String iface = networkAgent.linkProperties.getInterfaceName();
1798 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001799
Robert Greenwalt7b816022014-04-18 15:25:25 -07001800 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1801 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001802 try {
1803 // the call fails silently if no idletimer setup for this interface
1804 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001805 } catch (Exception e) {
1806 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001807 }
1808 }
1809 }
1810
1811 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001812 * Reads the network specific MTU size from reources.
1813 * and set it on it's iface.
1814 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001815 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1816 final String iface = newLp.getInterfaceName();
1817 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001818 if (oldLp == null && mtu == 0) {
1819 // Silently ignore unset MTU value.
1820 return;
1821 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001822 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1823 if (VDBG) log("identical MTU - not setting");
1824 return;
1825 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001826 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001827 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001828 return;
1829 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001830
w1997615afd812014-08-05 15:18:11 -07001831 // Cannot set MTU without interface name
1832 if (TextUtils.isEmpty(iface)) {
1833 loge("Setting MTU size with null iface.");
1834 return;
1835 }
1836
Robert Greenwalt7b816022014-04-18 15:25:25 -07001837 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001838 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001839 mNetd.setMtu(iface, mtu);
1840 } catch (Exception e) {
1841 Slog.e(TAG, "exception in setMtu()" + e);
1842 }
1843 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001844
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001845 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001846 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1847
1848 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001849 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001850 protected int getDefaultTcpRwnd() {
1851 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1852 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001853
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001854 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1855 if (isDefaultNetwork(nai) == false) {
1856 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001857 }
1858
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001859 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1860 String[] values = null;
1861 if (tcpBufferSizes != null) {
1862 values = tcpBufferSizes.split(",");
1863 }
1864
1865 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001866 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001867 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1868 values = tcpBufferSizes.split(",");
1869 }
1870
1871 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1872
1873 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001874 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001875
1876 final String prefix = "/sys/kernel/ipv4/tcp_";
1877 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1878 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1879 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1880 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1881 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1882 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1883 mCurrentTcpBufferSizes = tcpBufferSizes;
1884 } catch (IOException e) {
1885 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001886 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001887
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001888 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001889 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001890 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1891 if (rwndValue != 0) {
1892 SystemProperties.set(sysctlKey, rwndValue.toString());
1893 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001894 }
1895
Mattias Falk8b47b362011-08-23 14:15:13 +02001896 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001897 /*
1898 * Tell the VMs to toss their DNS caches
1899 */
1900 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1901 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001902 /*
1903 * Connectivity events can happen before boot has completed ...
1904 */
1905 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001906 final long ident = Binder.clearCallingIdentity();
1907 try {
1908 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1909 } finally {
1910 Binder.restoreCallingIdentity(ident);
1911 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001912 }
1913
Robert Greenwalt562cc542014-05-15 18:07:26 -07001914 @Override
1915 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001916 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1917 NETWORK_RESTORE_DELAY_PROP_NAME);
1918 if(restoreDefaultNetworkDelayStr != null &&
1919 restoreDefaultNetworkDelayStr.length() != 0) {
1920 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001921 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001922 } catch (NumberFormatException e) {
1923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001925 // if the system property isn't set, use the value for the apn type
1926 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1927
1928 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1929 (mNetConfigs[networkType] != null)) {
1930 ret = mNetConfigs[networkType].restoreTime;
1931 }
1932 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001935 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001936 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001937 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001938 }
1939 return false;
1940 }
1941
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001942 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1943 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1944 final long DIAG_TIME_MS = 5000;
1945 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1946 // Start gathering diagnostic information.
1947 netDiags.add(new NetworkDiagnostics(
1948 nai.network,
1949 new LinkProperties(nai.linkProperties), // Must be a copy.
1950 DIAG_TIME_MS));
1951 }
1952
1953 for (NetworkDiagnostics netDiag : netDiags) {
1954 pw.println();
1955 netDiag.waitForMeasurements();
1956 netDiag.dump(pw);
1957 }
1958 }
1959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001961 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1962 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001963 if (mContext.checkCallingOrSelfPermission(
1964 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001966 pw.println("Permission Denial: can't dump ConnectivityService " +
1967 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1968 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 return;
1970 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001971
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001972 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001973 dumpNetworkDiagnostics(pw);
1974 return;
1975 }
Erik Kline379747a2015-06-05 17:47:34 +09001976
Lorenzo Colittie3805462015-06-03 11:18:24 +09001977 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001978 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001979 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001980 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001981 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001982 pw.println();
1983
Paul Jensen85cf78e2015-06-25 13:25:07 -04001984 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001985 pw.print("Active default network: ");
1986 if (defaultNai == null) {
1987 pw.println("none");
1988 } else {
1989 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001991 pw.println();
1992
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001993 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001994 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001995 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1996 pw.println(nai.toString());
1997 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001998 pw.println(String.format(
1999 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
2000 nai.numForegroundNetworkRequests(),
2001 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
2002 nai.numBackgroundNetworkRequests(),
2003 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002004 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002005 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2006 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002007 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002008 pw.decreaseIndent();
2009 pw.println("Lingered:");
2010 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002011 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002012 pw.decreaseIndent();
2013 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002014 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002015 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002016 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002017
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002018 pw.println("Metered Interfaces:");
2019 pw.increaseIndent();
2020 for (String value : mMeteredIfaces) {
2021 pw.println(value);
2022 }
2023 pw.decreaseIndent();
2024 pw.println();
2025
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002026 pw.print("Restrict background: ");
2027 pw.println(mRestrictBackground);
2028 pw.println();
2029
Felipe Leme46c4fc32016-05-04 09:21:43 -07002030 pw.println("Status for known UIDs:");
2031 pw.increaseIndent();
2032 final int size = mUidRules.size();
2033 for (int i = 0; i < size; i++) {
2034 final int uid = mUidRules.keyAt(i);
2035 pw.print("UID=");
2036 pw.print(uid);
2037 final int uidRules = mUidRules.get(uid, RULE_NONE);
2038 pw.print(" rules=");
2039 pw.print(uidRulesToString(uidRules));
2040 pw.println();
2041 }
2042 pw.println();
2043 pw.decreaseIndent();
2044
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002045 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002046 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002047 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2048 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002049 }
2050 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002051 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002052
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002053 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002054
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002055 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002056 pw.print("mNetTransitionWakeLock: currently " +
2057 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2058 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2059 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2060 } else {
2061 pw.println(", last requested never");
2062 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002063 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002064
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002065 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002066 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002067
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002068 pw.println();
2069 mKeepaliveTracker.dump(pw);
2070
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002071 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002072
Lorenzo Colittie3805462015-06-03 11:18:24 +09002073 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002074 pw.println();
2075 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002076 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002077 for(int i = 0; i < mInetLog.size(); i++) {
2078 pw.println(mInetLog.get(i));
2079 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002080 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002081 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002082
2083 if (argsContain(args, "--short") == false) {
2084 pw.println();
2085 synchronized (mValidationLogs) {
2086 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002087 for (ValidationLog p : mValidationLogs) {
2088 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002089 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002090 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002091 pw.decreaseIndent();
2092 }
2093 }
Erik Kline7523eb32015-07-09 18:24:03 +09002094
2095 pw.println();
2096 pw.println("mNetworkRequestInfoLogs (most recent first):");
2097 pw.increaseIndent();
2098 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2099 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002100
2101 pw.println();
2102 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2103 pw.increaseIndent();
2104 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2105 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 }
2108
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002109 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002110 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002111 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002112 if (officialNai != null && officialNai.equals(nai)) return true;
2113 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002114 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002115 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002116 " - " + nai);
2117 }
2118 return false;
2119 }
2120
Robert Greenwalt42acef32009-08-12 16:08:25 -07002121 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002122 private class NetworkStateTrackerHandler extends Handler {
2123 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002124 super(looper);
2125 }
2126
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002127 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002129 default:
2130 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002131 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 handleAsyncChannelHalfConnect(msg);
2133 break;
2134 }
2135 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2136 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2137 if (nai != null) nai.asyncChannel.disconnect();
2138 break;
2139 }
2140 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2141 handleAsyncChannelDisconnected(msg);
2142 break;
2143 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002144 }
2145 return true;
2146 }
2147
2148 private void maybeHandleNetworkAgentMessage(Message msg) {
2149 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2150 if (nai == null) {
2151 if (VDBG) {
2152 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2153 log(String.format("%s from unknown NetworkAgent", what));
2154 }
2155 return;
2156 }
2157
2158 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002159 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002160 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2161 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002162 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2163 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002164 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002165 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002166 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002167 break;
2168 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002169 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002170 if (VDBG) {
2171 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002172 "; created=" + nai.created +
2173 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002174 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002175 LinkProperties oldLp = nai.linkProperties;
2176 synchronized (nai) {
2177 nai.linkProperties = (LinkProperties)msg.obj;
2178 }
Robin Lee585e2482016-05-01 23:00:00 +01002179 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002180 break;
2181 }
2182 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002183 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002184 updateNetworkInfo(nai, info);
2185 break;
2186 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002187 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002188 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002189 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002190 break;
2191 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002192 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002193 try {
2194 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002195 } catch (Exception e) {
2196 // Never crash!
2197 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002198 }
2199 break;
2200 }
2201 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002202 try {
2203 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002204 } catch (Exception e) {
2205 // Never crash!
2206 loge("Exception in removeVpnUidRanges: " + e);
2207 }
2208 break;
2209 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002210 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002211 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2212 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002213 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002214 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002215 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002216 break;
2217 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002218 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002219 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2220 break;
2221 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002222 }
2223 }
2224
2225 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2226 switch (msg.what) {
2227 default:
2228 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002229 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002230 final NetworkAgentInfo nai;
2231 synchronized (mNetworkForNetId) {
2232 nai = mNetworkForNetId.get(msg.arg2);
2233 }
2234 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002235 final boolean valid =
2236 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002237 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002238 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2239 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002240 if (valid != nai.lastValidated) {
2241 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002242 nai.lastValidated = valid;
2243 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002244 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002245 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2246 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002247 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002248 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002249 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002250 Bundle redirectUrlBundle = new Bundle();
2251 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002252 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002253 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002254 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002255 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002256 if (wasValidated && !nai.lastValidated) {
2257 handleNetworkUnvalidated(nai);
2258 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002259 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002260 break;
2261 }
Paul Jensen869868be2014-05-15 10:33:05 -04002262 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002263 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002264 final boolean visible = (msg.arg1 != 0);
2265 final NetworkAgentInfo nai;
2266 synchronized (mNetworkForNetId) {
2267 nai = mNetworkForNetId.get(netId);
2268 }
2269 // If captive portal status has changed, update capabilities.
2270 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002271 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002272 nai.lastCaptivePortalDetected = visible;
2273 nai.everCaptivePortalDetected |= visible;
Hugo Benichif15b2822016-09-15 18:18:48 +09002274 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002275 }
2276 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002277 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002278 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002279 if (nai == null) {
2280 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2281 break;
2282 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002283 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002284 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002285 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002286 }
Paul Jensen869868be2014-05-15 10:33:05 -04002287 }
Paul Jensen869868be2014-05-15 10:33:05 -04002288 break;
2289 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002290 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002291 return true;
2292 }
2293
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002294 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2295 switch (msg.what) {
2296 default:
2297 return false;
2298 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2299 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2300 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2301 handleLingerComplete(nai);
2302 }
2303 break;
2304 }
2305 }
2306 return true;
2307 }
2308
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002309 @Override
2310 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002311 if (!maybeHandleAsyncChannelMessage(msg) &&
2312 !maybeHandleNetworkMonitorMessage(msg) &&
2313 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002314 maybeHandleNetworkAgentMessage(msg);
2315 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002316 }
2317 }
2318
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002319 private void updateLingerState(NetworkAgentInfo nai, long now) {
2320 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2321 // 2. If the network was lingering and there are now requests, unlinger it.
2322 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2323 // one lingered request, start lingering.
2324 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002325 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002326 if (DBG) log("Unlingering " + nai.name());
2327 nai.unlinger();
2328 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002329 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002330 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002331 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002332 nai.linger();
2333 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2334 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2335 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002336 }
2337
Robert Greenwalt7b816022014-04-18 15:25:25 -07002338 private void handleAsyncChannelHalfConnect(Message msg) {
2339 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002340 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2342 if (VDBG) log("NetworkFactory connected");
2343 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002345 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002346 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002347 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002348 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 }
2350 } else {
2351 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002352 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 }
2354 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2355 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2356 if (VDBG) log("NetworkAgent connected");
2357 // A network agent has requested a connection. Establish the connection.
2358 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2359 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2360 } else {
2361 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002362 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002363 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002364 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002365 synchronized (mNetworkForNetId) {
2366 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002367 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002368 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002369 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002370 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002371 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002372 }
2373 }
2374 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002375
Robert Greenwalt7b816022014-04-18 15:25:25 -07002376 private void handleAsyncChannelDisconnected(Message msg) {
2377 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2378 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002379 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002380 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002382 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002383 // TODO - if we move the logic to the network agent (have them disconnect
2384 // because they lost all their requests or because their score isn't good)
2385 // then they would disconnect organically, report their new state and then
2386 // disconnect the channel.
2387 if (nai.networkInfo.isConnected()) {
2388 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2389 null, null);
2390 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002391 final boolean wasDefault = isDefaultNetwork(nai);
2392 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002393 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002394 // Log default network disconnection before required book-keeping.
2395 // Let rematchAllNetworksAndRequests() below record a new default network event
2396 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2397 // whose timestamps tell how long it takes to recover a default network.
2398 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002399 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002400 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002401 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2402 // by other networks that are already connected. Perhaps that can be done by
2403 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2404 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002405 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002406 mKeepaliveTracker.handleStopAllKeepalives(nai,
2407 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002408 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002409 mNetworkAgentInfos.remove(msg.replyTo);
2410 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002411 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002412 // Remove the NetworkAgent, but don't mark the netId as
2413 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002414 mNetworkForNetId.remove(nai.network.netId);
2415 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002416 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002417 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2418 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002419 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2420 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2421 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002422 sendUpdatedScoreToFactories(request, 0);
2423 }
2424 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002425 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002426 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002427 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002428 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002429 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002430 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002431 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002432 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002433 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002434 if (nai.created) {
2435 // Tell netd to clean up the configuration for this network
2436 // (routing rules, DNS, etc).
2437 // This may be slow as it requires a lot of netd shelling out to ip and
2438 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2439 // after we've rematched networks with requests which should make a potential
2440 // fallback network the default or requested a new network from the
2441 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2442 // long time.
2443 try {
2444 mNetd.removeNetwork(nai.network.netId);
2445 } catch (Exception e) {
2446 loge("Exception removing network: " + e);
2447 }
2448 }
2449 synchronized (mNetworkForNetId) {
2450 mNetIdInUse.delete(nai.network.netId);
2451 }
2452 } else {
2453 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2454 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002455 }
2456 }
2457
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002458 // If this method proves to be too slow then we can maintain a separate
2459 // pendingIntent => NetworkRequestInfo map.
2460 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2461 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2462 Intent intent = pendingIntent.getIntent();
2463 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2464 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2465 if (existingPendingIntent != null &&
2466 existingPendingIntent.getIntent().filterEquals(intent)) {
2467 return entry.getValue();
2468 }
2469 }
2470 return null;
2471 }
2472
2473 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2474 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2475
2476 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2477 if (existingRequest != null) { // remove the existing request.
2478 if (DBG) log("Replacing " + existingRequest.request + " with "
2479 + nri.request + " because their intents matched.");
2480 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2481 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002482 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002483 }
2484
Erik Klineda4bfa82015-04-30 12:58:40 +09002485 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002486 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002487 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002488 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002489 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002490 if (nri.request.networkCapabilities.hasSignalStrength() &&
2491 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2492 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002493 }
2494 }
2495 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002496 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002497 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002498 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002499 }
2500 }
2501
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002502 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2503 int callingUid) {
2504 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2505 if (nri != null) {
2506 handleReleaseNetworkRequest(nri.request, callingUid);
2507 }
2508 }
2509
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002510 // Determines whether the network is the best (or could become the best, if it validated), for
2511 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2512 // on the value of reason:
2513 //
2514 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2515 // then it should be torn down.
2516 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2517 // then it should be lingered.
2518 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2519 final int numRequests;
2520 switch (reason) {
2521 case TEARDOWN:
2522 numRequests = nai.numRequestNetworkRequests();
2523 break;
2524 case LINGER:
2525 numRequests = nai.numForegroundNetworkRequests();
2526 break;
2527 default:
2528 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2529 return true;
2530 }
2531
2532 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002533 return false;
2534 }
Paul Jensene0988542015-06-25 15:30:08 -04002535 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002536 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2537 // Background requests don't affect lingering.
2538 continue;
2539 }
2540
Paul Jensene0988542015-06-25 15:30:08 -04002541 // If this Network is already the highest scoring Network for a request, or if
2542 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002543 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002544 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002545 // Note that this catches two important cases:
2546 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2547 // is currently satisfying the request. This is desirable when
2548 // cellular ends up validating but WiFi does not.
2549 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002550 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002551 // WiFi ends up validating and out scoring cellular.
2552 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2553 nai.getCurrentScoreAsValidated())) {
2554 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002555 }
2556 }
Paul Jensene0988542015-06-25 15:30:08 -04002557 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002558 }
2559
Erik Klineacdd6392016-07-07 16:50:58 +09002560 private NetworkRequestInfo getNriForAppRequest(
2561 NetworkRequest request, int callingUid, String requestedOperation) {
2562 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2563
Robert Greenwalt9258c642014-03-26 16:47:06 -07002564 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002565 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002566 log(String.format("UID %d attempted to %s for unowned request %s",
2567 callingUid, requestedOperation, nri));
2568 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002569 }
Erik Klineacdd6392016-07-07 16:50:58 +09002570 }
2571
2572 return nri;
2573 }
2574
2575 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2576 String description, int callbackType) {
2577 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2578 if (nri == null) return;
2579
2580 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2581 // The network that is satisfying this request may have changed since
2582 // the application requested the update.
2583 //
2584 // - If the request is no longer satisfied, don't send any updates.
2585 // - If the request is satisfied by a different network, it is the
2586 // caller's responsibility to check that the Network object in the
2587 // callback matches the network that was returned in the last
2588 // onAvailable() callback for this request.
2589 if (nai == null) return;
2590 callCallbackForRequest(nri, nai, callbackType, 0);
2591 }
2592
2593 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2594 handleRequestCallbackUpdate(request, callingUid,
2595 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2596 }
2597
2598 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2599 handleRequestCallbackUpdate(request, callingUid,
2600 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2601 }
2602
Erik Kline57faba92015-11-25 12:49:38 +09002603 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2604 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2605 nri.request.requestId) == null) {
2606 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2607 }
2608 }
2609
Erik Klineacdd6392016-07-07 16:50:58 +09002610 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2611 final NetworkRequestInfo nri = getNriForAppRequest(
2612 request, callingUid, "release NetworkRequest");
Erik Kline57faba92015-11-25 12:49:38 +09002613 if (nri != null) {
2614 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2615 }
2616 }
Erik Klineacdd6392016-07-07 16:50:58 +09002617
Erik Kline57faba92015-11-25 12:49:38 +09002618 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2619 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2620 if (VDBG || (DBG && nri.request.isRequest())) {
2621 log("releasing " + nri.request + " (" + logCallbackType + ")");
2622 }
Erik Klineacdd6392016-07-07 16:50:58 +09002623 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002624 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002625 synchronized (mUidToNetworkRequestCount) {
2626 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2627 if (requests < 1) {
2628 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2629 nri.mUid);
2630 } else if (requests == 1) {
2631 mUidToNetworkRequestCount.removeAt(
2632 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2633 } else {
2634 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2635 }
2636 }
2637 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2638 if (nri.request.isRequest()) {
2639 boolean wasKept = false;
2640 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2641 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002642 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002643 nai.removeRequest(nri.request.requestId);
2644 if (VDBG) {
2645 log(" Removing from current network " + nai.name() +
2646 ", leaving " + nai.numNetworkRequests() + " requests.");
2647 }
2648 // If there are still lingered requests on this network, don't tear it down,
2649 // but resume lingering instead.
2650 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002651 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002652 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2653 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002654 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002655 wasKept = true;
2656 }
2657 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002658 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2659 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002660 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002661 }
Erik Klineacdd6392016-07-07 16:50:58 +09002662 }
2663
2664 // TODO: remove this code once we know that the Slog.wtf is never hit.
2665 //
2666 // Find all networks that are satisfying this request and remove the request
2667 // from their request lists.
2668 // TODO - it's my understanding that for a request there is only a single
2669 // network satisfying it, so this loop is wasteful
2670 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2671 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2672 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2673 otherNai.name() + ", but mNetworkAgentInfos says " +
2674 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002675 }
2676 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002677
Erik Klineacdd6392016-07-07 16:50:58 +09002678 // Maintain the illusion. When this request arrived, we might have pretended
2679 // that a network connected to serve it, even though the network was already
2680 // connected. Now that this request has gone away, we might have to pretend
2681 // that the network disconnected. LegacyTypeTracker will generate that
2682 // phantom disconnect for this type.
2683 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2684 boolean doRemove = true;
2685 if (wasKept) {
2686 // check if any of the remaining requests for this network are for the
2687 // same legacy type - if so, don't remove the nai
2688 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2689 NetworkRequest otherRequest = nai.requestAt(i);
2690 if (otherRequest.legacyType == nri.request.legacyType &&
2691 otherRequest.isRequest()) {
2692 if (DBG) log(" still have other legacy request - leaving");
2693 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002694 }
2695 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002696 }
2697
Erik Klineacdd6392016-07-07 16:50:58 +09002698 if (doRemove) {
2699 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002700 }
2701 }
Erik Klineacdd6392016-07-07 16:50:58 +09002702
2703 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2704 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2705 nri.request);
2706 }
2707 } else {
2708 // listens don't have a singular affectedNetwork. Check all networks to see
2709 // if this listen request applies and remove it.
2710 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2711 nai.removeRequest(nri.request.requestId);
2712 if (nri.request.networkCapabilities.hasSignalStrength() &&
2713 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2714 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2715 }
2716 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002717 }
Erik Kline57faba92015-11-25 12:49:38 +09002718 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002719 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002720
Lorenzo Colitti18660282016-07-04 12:55:44 +09002721 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2723 enforceConnectivityInternalPermission();
2724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2725 accept ? 1 : 0, always ? 1: 0, network));
2726 }
2727
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002728 @Override
2729 public void setAvoidUnvalidated(Network network) {
2730 enforceConnectivityInternalPermission();
2731 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2732 }
2733
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002734 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2735 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2736 " accept=" + accept + " always=" + always);
2737
2738 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2739 if (nai == null) {
2740 // Nothing to do.
2741 return;
2742 }
2743
2744 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002745 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002746 return;
2747 }
2748
2749 if (!nai.networkMisc.explicitlySelected) {
2750 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2751 }
2752
2753 if (accept != nai.networkMisc.acceptUnvalidated) {
2754 int oldScore = nai.getCurrentScore();
2755 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002756 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002757 sendUpdatedScoreToFactories(nai);
2758 }
2759
2760 if (always) {
2761 nai.asyncChannel.sendMessage(
2762 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2763 }
2764
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002765 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002766 // Tell the NetworkAgent to not automatically reconnect to the network.
2767 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2768 // Teardown the nework.
2769 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002770 }
2771
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002772 }
2773
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002774 private void handleSetAvoidUnvalidated(Network network) {
2775 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2776 if (nai == null || nai.lastValidated) {
2777 // Nothing to do. The network either disconnected or revalidated.
2778 return;
2779 }
2780 if (!nai.avoidUnvalidated) {
2781 int oldScore = nai.getCurrentScore();
2782 nai.avoidUnvalidated = true;
2783 rematchAllNetworksAndRequests(nai, oldScore);
2784 sendUpdatedScoreToFactories(nai);
2785 }
2786 }
2787
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002788 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002789 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002790 mHandler.sendMessageDelayed(
2791 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2792 PROMPT_UNVALIDATED_DELAY_MS);
2793 }
2794
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002795 private boolean mAvoidBadWifi = true;
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002796
Hugo Benichic8e9e122016-09-14 23:23:08 +00002797 public boolean avoidBadWifi() {
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002798 return mAvoidBadWifi;
2799 }
2800
2801 @VisibleForTesting
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002802 /** Whether the device or carrier configuration disables avoiding bad wifi by default. */
2803 public boolean configRestrictsAvoidBadWifi() {
2804 return mContext.getResources().getInteger(R.integer.config_networkAvoidBadWifi) == 0;
2805 }
2806
2807 /** Whether we should display a notification when wifi becomes unvalidated. */
2808 public boolean shouldNotifyWifiUnvalidated() {
2809 return configRestrictsAvoidBadWifi() &&
2810 Settings.Global.getString(mContext.getContentResolver(),
2811 Settings.Global.NETWORK_AVOID_BAD_WIFI) == null;
2812 }
2813
2814 private boolean updateAvoidBadWifi() {
2815 boolean settingAvoidBadWifi = "1".equals(Settings.Global.getString(
2816 mContext.getContentResolver(), Settings.Global.NETWORK_AVOID_BAD_WIFI));
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002817
2818 boolean prev = mAvoidBadWifi;
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002819 mAvoidBadWifi = settingAvoidBadWifi || !configRestrictsAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002820 return mAvoidBadWifi != prev;
Hugo Benichic8e9e122016-09-14 23:23:08 +00002821 }
2822
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002823 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2824 final String action;
2825 switch (type) {
2826 case NO_INTERNET:
2827 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2828 break;
2829 case LOST_INTERNET:
2830 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2831 break;
2832 default:
2833 Slog.wtf(TAG, "Unknown notification type " + type);
2834 return;
2835 }
2836
2837 Intent intent = new Intent(action);
2838 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2839 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2840 intent.setClassName("com.android.settings",
2841 "com.android.settings.wifi.WifiNoInternetDialog");
2842
2843 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2844 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2845 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2846 }
2847
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002848 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002849 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002850 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2851
2852 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2853 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002854 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002855 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002856 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2857 return;
2858 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002859 showValidationNotification(nai, NotificationType.NO_INTERNET);
2860 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002861
Lorenzo Colitti73b209382016-09-15 22:18:09 +09002862 // TODO: Delete this like updateMobileDataAlwaysOn above.
2863 @VisibleForTesting
2864 void updateNetworkAvoidBadWifi() {
2865 mHandler.sendEmptyMessage(EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
2866 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002867
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002868 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2869 NetworkCapabilities nc = nai.networkCapabilities;
2870 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002871
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002872 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002873 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2874 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002875 }
2876
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002877 private class InternalHandler extends Handler {
2878 public InternalHandler(Looper looper) {
2879 super(looper);
2880 }
2881
2882 @Override
2883 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002884 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002885 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002886 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002887 String causedBy = null;
2888 synchronized (ConnectivityService.this) {
2889 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2890 mNetTransitionWakeLock.isHeld()) {
2891 mNetTransitionWakeLock.release();
2892 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002893 } else {
2894 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002895 }
2896 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002897 if (VDBG) {
2898 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2899 log("Failed to find a new network - expiring NetTransition Wakelock");
2900 } else {
2901 log("NetTransition Wakelock (" +
2902 (causedBy == null ? "unknown" : causedBy) +
2903 " cleared because we found a replacement network");
2904 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002905 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002906 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002907 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002908 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002909 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002910 break;
2911 }
Jason Monkdecd2952013-10-10 14:02:51 -04002912 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002913 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002914 break;
2915 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002916 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002917 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2918 break;
2919 }
2920 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2921 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002922 break;
2923 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002924 case EVENT_REGISTER_NETWORK_AGENT: {
2925 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2926 break;
2927 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002928 case EVENT_REGISTER_NETWORK_REQUEST:
2929 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002930 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002931 break;
2932 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002933 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2934 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002935 handleRegisterNetworkRequestWithIntent(msg);
2936 break;
2937 }
Erik Kline57faba92015-11-25 12:49:38 +09002938 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2939 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2940 handleTimedOutNetworkRequest(nri);
2941 break;
2942 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002943 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2944 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2945 break;
2946 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002947 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002948 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002949 break;
2950 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002951 case EVENT_SET_ACCEPT_UNVALIDATED: {
2952 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2953 break;
2954 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002955 case EVENT_SET_AVOID_UNVALIDATED: {
2956 handleSetAvoidUnvalidated((Network) msg.obj);
2957 break;
2958 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002959 case EVENT_PROMPT_UNVALIDATED: {
2960 handlePromptUnvalidated((Network) msg.obj);
2961 break;
2962 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002963 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2964 handleMobileDataAlwaysOn();
2965 break;
2966 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002967 case EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI: {
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002968 if (updateAvoidBadWifi()) {
2969 rematchAllNetworksAndRequests(null, 0);
2970 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002971 break;
2972 }
Erik Klineacdd6392016-07-07 16:50:58 +09002973 case EVENT_REQUEST_LINKPROPERTIES:
2974 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2975 break;
2976 case EVENT_REQUEST_NETCAPABILITIES:
2977 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2978 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002979 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2980 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2981 mKeepaliveTracker.handleStartKeepalive(msg);
2982 break;
2983 }
2984 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2985 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2986 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2987 int slot = msg.arg1;
2988 int reason = msg.arg2;
2989 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2990 break;
2991 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002992 case EVENT_SYSTEM_READY: {
2993 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2994 nai.networkMonitor.systemReady = true;
2995 }
2996 break;
2997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 }
2999 }
3000 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003001
3002 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003003 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003004 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003005 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003006 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003007 final int status = mTethering.tether(iface);
3008 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
3009 try {
3010 mPolicyManager.onTetheringChanged(iface, true);
3011 } catch (RemoteException e) {
3012 }
3013 }
3014 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003015 } else {
3016 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3017 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003018 }
3019
3020 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003021 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003022 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003023 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003024
3025 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003026 final int status = mTethering.untether(iface);
3027 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
3028 try {
3029 mPolicyManager.onTetheringChanged(iface, false);
3030 } catch (RemoteException e) {
3031 }
3032 }
3033 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003034 } else {
3035 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3036 }
3037 }
3038
3039 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003040 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003041 public int getLastTetherError(String iface) {
3042 enforceTetherAccessPermission();
3043
3044 if (isTetheringSupported()) {
3045 return mTethering.getLastTetherError(iface);
3046 } else {
3047 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3048 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003049 }
3050
3051 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003052 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003053 public String[] getTetherableUsbRegexs() {
3054 enforceTetherAccessPermission();
3055 if (isTetheringSupported()) {
3056 return mTethering.getTetherableUsbRegexs();
3057 } else {
3058 return new String[0];
3059 }
3060 }
3061
Lorenzo Colitti18660282016-07-04 12:55:44 +09003062 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003063 public String[] getTetherableWifiRegexs() {
3064 enforceTetherAccessPermission();
3065 if (isTetheringSupported()) {
3066 return mTethering.getTetherableWifiRegexs();
3067 } else {
3068 return new String[0];
3069 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003070 }
3071
Lorenzo Colitti18660282016-07-04 12:55:44 +09003072 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003073 public String[] getTetherableBluetoothRegexs() {
3074 enforceTetherAccessPermission();
3075 if (isTetheringSupported()) {
3076 return mTethering.getTetherableBluetoothRegexs();
3077 } else {
3078 return new String[0];
3079 }
3080 }
3081
Lorenzo Colitti18660282016-07-04 12:55:44 +09003082 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003083 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003084 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003085 if (isTetheringSupported()) {
3086 return mTethering.setUsbTethering(enable);
3087 } else {
3088 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3089 }
3090 }
3091
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003092 // TODO - move iface listing, queries, etc to new module
3093 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003094 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003095 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003096 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003097 return mTethering.getTetherableIfaces();
3098 }
3099
Lorenzo Colitti18660282016-07-04 12:55:44 +09003100 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003101 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003102 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003103 return mTethering.getTetheredIfaces();
3104 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003105
Lorenzo Colitti18660282016-07-04 12:55:44 +09003106 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003107 public String[] getTetheringErroredIfaces() {
3108 enforceTetherAccessPermission();
3109 return mTethering.getErroredIfaces();
3110 }
3111
Lorenzo Colitti18660282016-07-04 12:55:44 +09003112 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003113 public String[] getTetheredDhcpRanges() {
3114 enforceConnectivityInternalPermission();
3115 return mTethering.getTetheredDhcpRanges();
3116 }
3117
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003118 // if ro.tether.denied = true we default to no tethering
3119 // gservices could set the secure setting to 1 though to enable it on a build where it
3120 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003121 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003122 public boolean isTetheringSupported() {
3123 enforceTetherAccessPermission();
3124 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003125 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003126 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3127 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003128 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
3129 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003130 mTethering.getTetherableWifiRegexs().length != 0 ||
3131 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3132 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003133 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003134
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003135 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003136 public void startTethering(int type, ResultReceiver receiver,
3137 boolean showProvisioningUi) {
3138 ConnectivityManager.enforceTetherChangePermission(mContext);
3139 if (!isTetheringSupported()) {
3140 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3141 return;
3142 }
3143 mTethering.startTethering(type, receiver, showProvisioningUi);
3144 }
3145
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003146 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003147 public void stopTethering(int type) {
3148 ConnectivityManager.enforceTetherChangePermission(mContext);
3149 mTethering.stopTethering(type);
3150 }
3151
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003152 // Called when we lose the default network and have no replacement yet.
3153 // This will automatically be cleared after X seconds or a new default network
3154 // becomes CONNECTED, whichever happens first. The timer is started by the
3155 // first caller and not restarted by subsequent callers.
3156 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003157 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003158 synchronized (this) {
3159 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003160 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003161 mNetTransitionWakeLock.acquire();
3162 mNetTransitionWakeLockCausedBy = forWhom;
3163 }
3164 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003165 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003166 mNetTransitionWakeLockTimeout);
3167 return;
3168 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003169
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003170 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003171 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003172 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003173 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003174 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003175 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003176 }
3177
Lorenzo Colitti18660282016-07-04 12:55:44 +09003178 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003179 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003180 enforceAccessPermission();
3181 enforceInternetPermission();
3182
Paul Jensenbfd17b72015-04-07 12:43:13 -04003183 NetworkAgentInfo nai;
3184 if (network == null) {
3185 nai = getDefaultNetwork();
3186 } else {
3187 nai = getNetworkAgentInfoForNetwork(network);
3188 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003189 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3190 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3191 return;
3192 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003193 // Revalidate if the app report does not match our current validated state.
3194 if (hasConnectivity == nai.lastValidated) return;
3195 final int uid = Binder.getCallingUid();
3196 if (DBG) {
3197 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3198 ") by " + uid);
3199 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003200 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003201 // Validating a network that has not yet connected could result in a call to
3202 // rematchNetworkAndRequests() which is not meant to work on such networks.
3203 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003204
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003205 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003206
3207 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3208 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003209 }
3210
Paul Jensencee9b512015-05-06 07:32:40 -04003211 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003212 // this information is already available as a world read/writable jvm property
3213 // so this API change wouldn't have a benifit. It also breaks the passing
3214 // of proxy info to all the JVMs.
3215 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003216 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003217 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003218 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3219 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003220 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003221 }
3222
Lorenzo Colitti18660282016-07-04 12:55:44 +09003223 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003224 public ProxyInfo getProxyForNetwork(Network network) {
3225 if (network == null) return getDefaultProxy();
3226 final ProxyInfo globalProxy = getGlobalProxy();
3227 if (globalProxy != null) return globalProxy;
3228 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3229 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3230 // caller may not have.
3231 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3232 if (nai == null) return null;
3233 synchronized (nai) {
3234 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3235 if (proxyInfo == null) return null;
3236 return new ProxyInfo(proxyInfo);
3237 }
3238 }
3239
Paul Jensene0bef712014-12-10 15:12:18 -05003240 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3241 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3242 // proxy is null then there is no proxy in place).
3243 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3244 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3245 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3246 proxy = null;
3247 }
3248 return proxy;
3249 }
3250
3251 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3252 // better for determining if a new proxy broadcast is necessary:
3253 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3254 // avoid unnecessary broadcasts.
3255 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3256 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3257 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3258 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3259 // all set.
3260 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3261 a = canonicalizeProxyInfo(a);
3262 b = canonicalizeProxyInfo(b);
3263 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3264 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3265 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3266 }
3267
Jason Monk207900c2014-04-25 15:00:09 -04003268 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003269 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003270
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003271 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003272 if (proxyProperties == mGlobalProxy) return;
3273 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3274 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3275
3276 String host = "";
3277 int port = 0;
3278 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003279 String pacFileUrl = "";
3280 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003281 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003282 if (!proxyProperties.isValid()) {
3283 if (DBG)
3284 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3285 return;
3286 }
Jason Monk207900c2014-04-25 15:00:09 -04003287 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003288 host = mGlobalProxy.getHost();
3289 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003290 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003291 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003292 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003293 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003294 } else {
3295 mGlobalProxy = null;
3296 }
3297 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003298 final long token = Binder.clearCallingIdentity();
3299 try {
3300 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3301 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3302 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3303 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003304 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003305 } finally {
3306 Binder.restoreCallingIdentity(token);
3307 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003308
Jason Monkcf0f97a2014-10-02 15:39:38 -04003309 if (mGlobalProxy == null) {
3310 proxyProperties = mDefaultProxy;
3311 }
3312 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003313 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003314 }
3315
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003316 private void loadGlobalProxy() {
3317 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003318 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3319 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3320 String exclList = Settings.Global.getString(res,
3321 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003322 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3323 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003324 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003325 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003326 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003327 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003328 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003329 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003330 if (!proxyProperties.isValid()) {
3331 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3332 return;
3333 }
3334
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003335 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003336 mGlobalProxy = proxyProperties;
3337 }
3338 }
3339 }
3340
Jason Monk207900c2014-04-25 15:00:09 -04003341 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003342 // this information is already available as a world read/writable jvm property
3343 // so this API change wouldn't have a benifit. It also breaks the passing
3344 // of proxy info to all the JVMs.
3345 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003346 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003347 return mGlobalProxy;
3348 }
3349 }
3350
Jason Monk207900c2014-04-25 15:00:09 -04003351 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003352 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003353 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003354 proxy = null;
3355 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003356 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003357 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003358 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003359 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003360 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3361 return;
3362 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003363
3364 // This call could be coming from the PacManager, containing the port of the local
3365 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3366 // global (to get the correct local port), and send a broadcast.
3367 // TODO: Switch PacManager to have its own message to send back rather than
3368 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003369 if ((mGlobalProxy != null) && (proxy != null)
3370 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003371 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3372 mGlobalProxy = proxy;
3373 sendProxyBroadcast(mGlobalProxy);
3374 return;
3375 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003376 mDefaultProxy = proxy;
3377
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003378 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003379 if (!mDefaultProxyDisabled) {
3380 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003381 }
3382 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003383 }
3384
Paul Jensene0bef712014-12-10 15:12:18 -05003385 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3386 // This method gets called when any network changes proxy, but the broadcast only ever contains
3387 // the default proxy (even if it hasn't changed).
3388 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3389 // world where an app might be bound to a non-default network.
3390 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3391 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3392 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3393
3394 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3395 sendProxyBroadcast(getDefaultProxy());
3396 }
3397 }
3398
Robert Greenwalt434203a2010-10-11 16:00:27 -07003399 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003400 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3401 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 if (!TextUtils.isEmpty(proxy)) {
3403 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003404 if (data.length == 0) {
3405 return;
3406 }
3407
Robert Greenwalt434203a2010-10-11 16:00:27 -07003408 String proxyHost = data[0];
3409 int proxyPort = 8080;
3410 if (data.length > 1) {
3411 try {
3412 proxyPort = Integer.parseInt(data[1]);
3413 } catch (NumberFormatException e) {
3414 return;
3415 }
3416 }
Jason Monk207900c2014-04-25 15:00:09 -04003417 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003418 setGlobalProxy(p);
3419 }
3420 }
3421
Jason Monk207900c2014-04-25 15:00:09 -04003422 private void sendProxyBroadcast(ProxyInfo proxy) {
3423 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003424 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003425 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003427 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3428 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003429 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003430 final long ident = Binder.clearCallingIdentity();
3431 try {
3432 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3433 } finally {
3434 Binder.restoreCallingIdentity(ident);
3435 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003436 }
3437
3438 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003439 final private HashMap<Uri, Integer> mUriEventMap;
3440 final private Context mContext;
3441 final private Handler mHandler;
3442
3443 SettingsObserver(Context context, Handler handler) {
3444 super(null);
3445 mUriEventMap = new HashMap<Uri, Integer>();
3446 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003447 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003448 }
3449
Erik Klineda4bfa82015-04-30 12:58:40 +09003450 void observe(Uri uri, int what) {
3451 mUriEventMap.put(uri, what);
3452 final ContentResolver resolver = mContext.getContentResolver();
3453 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003454 }
3455
3456 @Override
3457 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003458 Slog.wtf(TAG, "Should never be reached.");
3459 }
3460
3461 @Override
3462 public void onChange(boolean selfChange, Uri uri) {
3463 final Integer what = mUriEventMap.get(uri);
3464 if (what != null) {
3465 mHandler.obtainMessage(what.intValue()).sendToTarget();
3466 } else {
3467 loge("No matching event to send for URI=" + uri);
3468 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003469 }
3470 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003471
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003472 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003473 Slog.d(TAG, s);
3474 }
3475
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003476 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003477 Slog.e(TAG, s);
3478 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003479
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003480 private static <T> T checkNotNull(T value, String message) {
3481 if (value == null) {
3482 throw new NullPointerException(message);
3483 }
3484 return value;
3485 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003486
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003487 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003488 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003489 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3490 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3491 *
3492 * @param oldPackage Package name of the application which currently controls VPN, which will
3493 * be replaced. If there is no such application, this should should either be
3494 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3495 * @param newPackage Package name of the application which should gain control of VPN, or
3496 * {@code null} to disable.
3497 * @param userId User for whom to prepare the new VPN.
3498 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003499 * @hide
3500 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003501 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003502 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3503 int userId) {
3504 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003505 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003506
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003507 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003508 Vpn vpn = mVpns.get(userId);
3509 if (vpn != null) {
3510 return vpn.prepare(oldPackage, newPackage);
3511 } else {
3512 return false;
3513 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003514 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003515 }
3516
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003517 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003518 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3519 * This method is used by system-privileged apps.
3520 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3521 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3522 *
3523 * @param packageName The package for which authorization state should change.
3524 * @param userId User for whom {@code packageName} is installed.
3525 * @param authorized {@code true} if this app should be able to start a VPN connection without
3526 * explicit user approval, {@code false} if not.
3527 *
Jeff Davidson05542602014-08-11 14:07:27 -07003528 * @hide
3529 */
3530 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003531 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3532 enforceCrossUserPermission(userId);
3533
Jeff Davidson05542602014-08-11 14:07:27 -07003534 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003535 Vpn vpn = mVpns.get(userId);
3536 if (vpn != null) {
3537 vpn.setPackageAuthorization(packageName, authorized);
3538 }
Jeff Davidson05542602014-08-11 14:07:27 -07003539 }
3540 }
3541
3542 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003543 * Configure a TUN interface and return its file descriptor. Parameters
3544 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003545 * and not available in ConnectivityManager. Permissions are checked in
3546 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003547 * @hide
3548 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003549 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003550 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003551 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003552 int user = UserHandle.getUserId(Binder.getCallingUid());
3553 synchronized(mVpns) {
3554 return mVpns.get(user).establish(config);
3555 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003556 }
3557
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003558 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003559 * Start legacy VPN, controlling native daemons as needed. Creates a
3560 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003561 */
3562 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003563 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003564 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003565 final LinkProperties egress = getActiveLinkProperties();
3566 if (egress == null) {
3567 throw new IllegalStateException("Missing active network connection");
3568 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003569 int user = UserHandle.getUserId(Binder.getCallingUid());
3570 synchronized(mVpns) {
3571 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3572 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003573 }
3574
3575 /**
3576 * Return the information of the ongoing legacy VPN. This method is used
3577 * by VpnSettings and not available in ConnectivityManager. Permissions
3578 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003579 */
3580 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003581 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3582 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003583
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003584 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003585 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003586 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003587 }
3588
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003589 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003590 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3591 * and not available in ConnectivityManager.
3592 */
3593 @Override
3594 public VpnInfo[] getAllVpnInfo() {
3595 enforceConnectivityInternalPermission();
3596 if (mLockdownEnabled) {
3597 return new VpnInfo[0];
3598 }
3599
3600 synchronized(mVpns) {
3601 List<VpnInfo> infoList = new ArrayList<>();
3602 for (int i = 0; i < mVpns.size(); i++) {
3603 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3604 if (info != null) {
3605 infoList.add(info);
3606 }
3607 }
3608 return infoList.toArray(new VpnInfo[infoList.size()]);
3609 }
3610 }
3611
3612 /**
3613 * @return VPN information for accounting, or null if we can't retrieve all required
3614 * information, e.g primary underlying iface.
3615 */
3616 @Nullable
3617 private VpnInfo createVpnInfo(Vpn vpn) {
3618 VpnInfo info = vpn.getVpnInfo();
3619 if (info == null) {
3620 return null;
3621 }
3622 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3623 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3624 // the underlyingNetworks list.
3625 if (underlyingNetworks == null) {
3626 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3627 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3628 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3629 }
3630 } else if (underlyingNetworks.length > 0) {
3631 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3632 if (linkProperties != null) {
3633 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3634 }
3635 }
3636 return info.primaryUnderlyingIface == null ? null : info;
3637 }
3638
3639 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003640 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3641 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003642 * Permissions are checked in Vpn class.
3643 * @hide
3644 */
3645 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003646 public VpnConfig getVpnConfig(int userId) {
3647 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003648 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003649 Vpn vpn = mVpns.get(userId);
3650 if (vpn != null) {
3651 return vpn.getVpnConfig();
3652 } else {
3653 return null;
3654 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003655 }
3656 }
3657
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003658 @Override
3659 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003660 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3661 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3662 return false;
3663 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003664
3665 // Tear down existing lockdown if profile was removed
3666 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3667 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003668 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3669 final VpnProfile profile = VpnProfile.decode(
3670 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003671 if (profile == null) {
3672 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3673 setLockdownTracker(null);
3674 return true;
3675 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003676 int user = UserHandle.getUserId(Binder.getCallingUid());
3677 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003678 Vpn vpn = mVpns.get(user);
3679 if (vpn == null) {
3680 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3681 return false;
3682 }
3683 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003684 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003685 } else {
3686 setLockdownTracker(null);
3687 }
3688
3689 return true;
3690 }
3691
3692 /**
3693 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3694 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3695 */
3696 private void setLockdownTracker(LockdownVpnTracker tracker) {
3697 // Shutdown any existing tracker
3698 final LockdownVpnTracker existing = mLockdownTracker;
3699 mLockdownTracker = null;
3700 if (existing != null) {
3701 existing.shutdown();
3702 }
3703
3704 try {
3705 if (tracker != null) {
3706 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003707 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003708 mLockdownTracker = tracker;
3709 mLockdownTracker.init();
3710 } else {
3711 mNetd.setFirewallEnabled(false);
3712 }
3713 } catch (RemoteException e) {
3714 // ignored; NMS lives inside system_server
3715 }
3716 }
3717
3718 private void throwIfLockdownEnabled() {
3719 if (mLockdownEnabled) {
3720 throw new IllegalStateException("Unavailable in lockdown mode");
3721 }
3722 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003723
Robin Lee244ce8e2016-01-05 18:03:46 +00003724 /**
Robin Lee17e61832016-05-09 13:46:28 +01003725 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3726 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003727 *
Robin Lee17e61832016-05-09 13:46:28 +01003728 * @return {@code true} if the service was started, the service was already connected, or there
3729 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003730 */
Robin Lee17e61832016-05-09 13:46:28 +01003731 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003732 synchronized (mVpns) {
3733 Vpn vpn = mVpns.get(userId);
3734 if (vpn == null) {
3735 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3736 // exists already.
3737 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3738 return false;
3739 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003740
Robin Lee812800c2016-05-13 15:38:08 +01003741 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003742 }
3743 }
3744
3745 @Override
Robin Leedc679712016-05-03 13:23:03 +01003746 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003747 enforceConnectivityInternalPermission();
3748 enforceCrossUserPermission(userId);
3749
3750 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3751 if (LockdownVpnTracker.isEnabled()) {
3752 return false;
3753 }
3754
Robin Lee244ce8e2016-01-05 18:03:46 +00003755 synchronized (mVpns) {
3756 Vpn vpn = mVpns.get(userId);
3757 if (vpn == null) {
3758 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3759 return false;
3760 }
Robin Lee17e61832016-05-09 13:46:28 +01003761 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003762 return false;
3763 }
Robin Lee17e61832016-05-09 13:46:28 +01003764 if (!startAlwaysOnVpn(userId)) {
3765 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003766 return false;
3767 }
Robin Lee17e61832016-05-09 13:46:28 +01003768
Robin Lee812800c2016-05-13 15:38:08 +01003769 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003770 }
3771 return true;
3772 }
3773
3774 @Override
3775 public String getAlwaysOnVpnPackage(int userId) {
3776 enforceConnectivityInternalPermission();
3777 enforceCrossUserPermission(userId);
3778
3779 synchronized (mVpns) {
3780 Vpn vpn = mVpns.get(userId);
3781 if (vpn == null) {
3782 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3783 return null;
3784 }
3785 return vpn.getAlwaysOnPackage();
3786 }
3787 }
3788
Wink Savilleab9321d2013-06-29 21:10:57 -07003789 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003790 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003791 // TODO: Remove? Any reason to trigger a provisioning check?
3792 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003793 }
3794
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003795 /** Location to an updatable file listing carrier provisioning urls.
3796 * An example:
3797 *
3798 * <?xml version="1.0" encoding="utf-8"?>
3799 * <provisioningUrls>
3800 * <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 -07003801 * </provisioningUrls>
3802 */
3803 private static final String PROVISIONING_URL_PATH =
3804 "/data/misc/radio/provisioning_urls.xml";
3805 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003806
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003807 /** XML tag for root element. */
3808 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3809 /** XML tag for individual url */
3810 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003811 /** XML attribute for mcc */
3812 private static final String ATTR_MCC = "mcc";
3813 /** XML attribute for mnc */
3814 private static final String ATTR_MNC = "mnc";
3815
Paul Jensen434dde82015-06-11 09:43:30 -04003816 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003817 FileReader fileReader = null;
3818 XmlPullParser parser = null;
3819 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003820
3821 try {
3822 fileReader = new FileReader(mProvisioningUrlFile);
3823 parser = Xml.newPullParser();
3824 parser.setInput(fileReader);
3825 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3826
3827 while (true) {
3828 XmlUtils.nextElement(parser);
3829
3830 String element = parser.getName();
3831 if (element == null) break;
3832
Paul Jensen434dde82015-06-11 09:43:30 -04003833 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003834 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3835 try {
3836 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3837 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3838 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3839 parser.next();
3840 if (parser.getEventType() == XmlPullParser.TEXT) {
3841 return parser.getText();
3842 }
3843 }
3844 }
3845 } catch (NumberFormatException e) {
3846 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3847 }
3848 }
3849 }
3850 return null;
3851 } catch (FileNotFoundException e) {
3852 loge("Carrier Provisioning Urls file not found");
3853 } catch (XmlPullParserException e) {
3854 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3855 } catch (IOException e) {
3856 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3857 } finally {
3858 if (fileReader != null) {
3859 try {
3860 fileReader.close();
3861 } catch (IOException e) {}
3862 }
3863 }
3864 return null;
3865 }
3866
Wink Saville42d4f082013-07-20 20:31:59 -07003867 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003868 public String getMobileProvisioningUrl() {
3869 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003870 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003871 if (TextUtils.isEmpty(url)) {
3872 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003873 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003874 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003875 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003876 }
Wink Saville8cf35602013-07-10 23:00:07 -07003877 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003878 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003879 String phoneNumber = mTelephonyManager.getLine1Number();
3880 if (TextUtils.isEmpty(phoneNumber)) {
3881 phoneNumber = "0000000000";
3882 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003883 url = String.format(url,
3884 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3885 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003886 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003887 }
3888
Wink Savilleab9321d2013-06-29 21:10:57 -07003889 return url;
3890 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003891
Wink Saville948282b2013-08-29 08:55:16 -07003892 @Override
3893 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003894 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003895 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003896 final long ident = Binder.clearCallingIdentity();
3897 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003898 // Concatenate the range of types onto the range of NetIDs.
3899 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3900 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003901 } finally {
3902 Binder.restoreCallingIdentity(ident);
3903 }
Wink Saville948282b2013-08-29 08:55:16 -07003904 }
Wink Saville7788c612013-08-29 14:57:08 -07003905
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003906 @Override
3907 public void setAirplaneMode(boolean enable) {
3908 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003909 final long ident = Binder.clearCallingIdentity();
3910 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003911 final ContentResolver cr = mContext.getContentResolver();
3912 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3913 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3914 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003915 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003916 } finally {
3917 Binder.restoreCallingIdentity(ident);
3918 }
3919 }
3920
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003921 private void onUserStart(int userId) {
3922 synchronized(mVpns) {
3923 Vpn userVpn = mVpns.get(userId);
3924 if (userVpn != null) {
3925 loge("Starting user already has a VPN");
3926 return;
3927 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003928 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003929 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003930
3931 final ContentResolver cr = mContext.getContentResolver();
3932 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3933 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3934 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3935 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3936 if (alwaysOnPackage != null) {
3937 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3938 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003939 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003940 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3941 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003942 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003943 }
3944
3945 private void onUserStop(int userId) {
3946 synchronized(mVpns) {
3947 Vpn userVpn = mVpns.get(userId);
3948 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003949 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003950 return;
3951 }
Robin Lee17e61832016-05-09 13:46:28 +01003952 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003953 mVpns.delete(userId);
3954 }
3955 }
3956
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003957 private void onUserAdded(int userId) {
3958 synchronized(mVpns) {
3959 final int vpnsSize = mVpns.size();
3960 for (int i = 0; i < vpnsSize; i++) {
3961 Vpn vpn = mVpns.valueAt(i);
3962 vpn.onUserAdded(userId);
3963 }
3964 }
3965 }
3966
3967 private void onUserRemoved(int userId) {
3968 synchronized(mVpns) {
3969 final int vpnsSize = mVpns.size();
3970 for (int i = 0; i < vpnsSize; i++) {
3971 Vpn vpn = mVpns.valueAt(i);
3972 vpn.onUserRemoved(userId);
3973 }
3974 }
3975 }
3976
Robin Lee89e7a692016-02-29 14:38:17 +00003977 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003978 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3979 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3980 updateLockdownVpn();
3981 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003982 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003983 }
3984 }
3985
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003986 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3987 @Override
3988 public void onReceive(Context context, Intent intent) {
3989 final String action = intent.getAction();
3990 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3991 if (userId == UserHandle.USER_NULL) return;
3992
Robin Lee323f29d2016-05-04 16:38:06 +01003993 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003994 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003995 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003996 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003997 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3998 onUserAdded(userId);
3999 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4000 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004001 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4002 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004003 }
4004 }
4005 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004006
Robert Greenwalta67be032014-05-16 15:49:14 -07004007 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4008 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004009 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4010 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004011
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004012 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4013 // Map from UID to number of NetworkRequests that UID has filed.
4014 @GuardedBy("mUidToNetworkRequestCount")
4015 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4016
Robert Greenwalta67be032014-05-16 15:49:14 -07004017 private static class NetworkFactoryInfo {
4018 public final String name;
4019 public final Messenger messenger;
4020 public final AsyncChannel asyncChannel;
4021
4022 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4023 this.name = name;
4024 this.messenger = messenger;
4025 this.asyncChannel = asyncChannel;
4026 }
4027 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004028
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004029 private void ensureNetworkRequestHasType(NetworkRequest request) {
4030 if (request.type == NetworkRequest.Type.NONE) {
4031 throw new IllegalArgumentException(
4032 "All NetworkRequests in ConnectivityService must have a type");
4033 }
4034 }
4035
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004036 /**
4037 * Tracks info about the requester.
4038 * Also used to notice when the calling process dies so we can self-expire
4039 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004040 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004041 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004042 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004043 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004045 final int mPid;
4046 final int mUid;
4047 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004048
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004049 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004050 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004051 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004052 mPendingIntent = pi;
4053 messenger = null;
4054 mBinder = null;
4055 mPid = getCallingPid();
4056 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004057 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004058 }
4059
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004060 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061 super();
4062 messenger = m;
4063 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004064 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004065 mBinder = binder;
4066 mPid = getCallingPid();
4067 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004068 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004069 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004070
4071 try {
4072 mBinder.linkToDeath(this, 0);
4073 } catch (RemoteException e) {
4074 binderDied();
4075 }
4076 }
4077
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004078 private void enforceRequestCountLimit() {
4079 synchronized (mUidToNetworkRequestCount) {
4080 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4081 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4082 throw new IllegalArgumentException("Too many NetworkRequests filed");
4083 }
4084 mUidToNetworkRequestCount.put(mUid, networkRequests);
4085 }
4086 }
4087
Robert Greenwalt9258c642014-03-26 16:47:06 -07004088 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004089 if (mBinder != null) {
4090 mBinder.unlinkToDeath(this, 0);
4091 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004092 }
4093
4094 public void binderDied() {
4095 log("ConnectivityService NetworkRequestInfo binderDied(" +
4096 request + ", " + mBinder + ")");
4097 releaseNetworkRequest(request);
4098 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004099
4100 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004101 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004102 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004103 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004104 }
4105
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004106 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4107 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4108 if (badCapability != null) {
4109 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004110 }
4111 }
4112
Erik Kline9d598e12015-07-13 16:37:51 +09004113 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004114 final SortedSet<Integer> thresholds = new TreeSet();
4115 synchronized (nai) {
4116 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4117 if (nri.request.networkCapabilities.hasSignalStrength() &&
4118 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4119 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4120 }
4121 }
4122 }
Erik Kline9d598e12015-07-13 16:37:51 +09004123 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004124 }
4125
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004126 private void updateSignalStrengthThresholds(
4127 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4128 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004129 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004130 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4131
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004132 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004133 String detail;
4134 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4135 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4136 } else {
4137 detail = reason;
4138 }
4139 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4140 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4141 }
4142
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004143 nai.asyncChannel.sendMessage(
4144 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004145 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004146 }
4147
Robert Greenwalt9258c642014-03-26 16:47:06 -07004148 @Override
4149 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004150 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004151 final NetworkRequest.Type type = (networkCapabilities == null)
4152 ? NetworkRequest.Type.TRACK_DEFAULT
4153 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004154 // If the requested networkCapabilities is null, take them instead from
4155 // the default network request. This allows callers to keep track of
4156 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004157 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004158 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4159 enforceAccessPermission();
4160 } else {
4161 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4162 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004163 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4164 // of the app when the request is filed, but we never change the request if the app
4165 // changes network state. http://b/29964605
4166 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004167 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004168 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004169
Robert Greenwalt6078b502014-06-11 16:05:07 -07004170 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 throw new IllegalArgumentException("Bad timeout specified");
4172 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004173
Etan Cohenddb9ef02015-11-18 10:56:15 -08004174 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4175 .equals(networkCapabilities.getNetworkSpecifier())) {
4176 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4177 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4178 }
4179
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004180 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004181 nextNetworkRequestId(), type);
4182 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004183 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004184
4185 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004186 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004187 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004188 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004189 }
4190 return networkRequest;
4191 }
4192
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004193 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004194 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004195 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004196 } else {
4197 enforceChangePermission();
4198 }
4199 }
4200
fenglub15e72b2015-03-20 11:29:56 -07004201 @Override
fengludb571472015-04-21 17:12:05 -07004202 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004203 enforceAccessPermission();
4204 NetworkAgentInfo nai = null;
4205 if (network == null) {
4206 return false;
4207 }
4208 synchronized (mNetworkForNetId) {
4209 nai = mNetworkForNetId.get(network.netId);
4210 }
4211 if (nai != null) {
4212 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4213 return true;
4214 }
4215 return false;
4216 }
4217
Felipe Lemeee27cab2016-06-20 16:36:29 -07004218 private boolean isSystem(int uid) {
4219 return uid < Process.FIRST_APPLICATION_UID;
4220 }
fenglub15e72b2015-03-20 11:29:56 -07004221
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004222 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004223 final int uid = Binder.getCallingUid();
4224 if (isSystem(uid)) {
4225 return;
4226 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004227 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004228 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004229 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004230 synchronized(mRulesLock) {
4231 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4232 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004233 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4234 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004235 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004236 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004237 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004238 }
4239 }
4240 }
4241
Robert Greenwalt9258c642014-03-26 16:47:06 -07004242 @Override
4243 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4244 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004245 checkNotNull(operation, "PendingIntent cannot be null.");
4246 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4247 enforceNetworkRequestPermissions(networkCapabilities);
4248 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004249 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004250
4251 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004252 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4253 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004254 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004255 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4256 nri));
4257 return networkRequest;
4258 }
4259
Jeremy Joslin79294842014-12-03 17:15:28 -08004260 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4261 mHandler.sendMessageDelayed(
4262 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4263 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4264 }
4265
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004266 @Override
4267 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004268 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004269 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4270 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004271 }
4272
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004273 // In order to implement the compatibility measure for pre-M apps that call
4274 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4275 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4276 // This ensures it has permission to do so.
4277 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4278 if (nc == null) {
4279 return false;
4280 }
4281 int[] transportTypes = nc.getTransportTypes();
4282 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4283 return false;
4284 }
4285 try {
4286 mContext.enforceCallingOrSelfPermission(
4287 android.Manifest.permission.ACCESS_WIFI_STATE,
4288 "ConnectivityService");
4289 } catch (SecurityException e) {
4290 return false;
4291 }
4292 return true;
4293 }
4294
Robert Greenwalt9258c642014-03-26 16:47:06 -07004295 @Override
4296 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4297 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004298 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4299 enforceAccessPermission();
4300 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004301
Erik Kline7523eb32015-07-09 18:24:03 +09004302 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004303 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4304 NetworkRequest.Type.LISTEN);
4305 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004306 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004307
4308 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4309 return networkRequest;
4310 }
4311
4312 @Override
4313 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4314 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004315 checkNotNull(operation, "PendingIntent cannot be null.");
4316 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4317 enforceAccessPermission();
4318 }
4319
Erik Kline7523eb32015-07-09 18:24:03 +09004320 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004321 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4322 NetworkRequest.Type.LISTEN);
4323 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004324 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004325
4326 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004327 }
4328
4329 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004330 public void requestLinkProperties(NetworkRequest networkRequest) {
4331 ensureNetworkRequestHasType(networkRequest);
4332 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4333 mHandler.sendMessage(mHandler.obtainMessage(
4334 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4335 }
4336
4337 @Override
4338 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4339 ensureNetworkRequestHasType(networkRequest);
4340 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4341 mHandler.sendMessage(mHandler.obtainMessage(
4342 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4343 }
4344
4345 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004346 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004347 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004348 mHandler.sendMessage(mHandler.obtainMessage(
4349 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004350 }
4351
4352 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004353 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004354 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004355 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4356 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004357 }
4358
Robert Greenwalta67be032014-05-16 15:49:14 -07004359 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004360 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004361 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4362 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4363 }
4364
4365 @Override
4366 public void unregisterNetworkFactory(Messenger messenger) {
4367 enforceConnectivityInternalPermission();
4368 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4369 }
4370
4371 private void handleUnregisterNetworkFactory(Messenger messenger) {
4372 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4373 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004374 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004375 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004376 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004377 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004378 }
4379
Robert Greenwalt7b816022014-04-18 15:25:25 -07004380 /**
4381 * NetworkAgentInfo supporting a request by requestId.
4382 * These have already been vetted (their Capabilities satisfy the request)
4383 * and the are the highest scored network available.
4384 * the are keyed off the Requests requestId.
4385 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004386 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004387 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4388 new SparseArray<NetworkAgentInfo>();
4389
Paul Jensen31a94f42015-02-13 14:18:39 -05004390 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4391 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004392 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4393 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004394 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4395 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4396 // there may not be a strict 1:1 correlation between the two.
4397 @GuardedBy("mNetworkForNetId")
4398 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004399
Robert Greenwalt7b816022014-04-18 15:25:25 -07004400 // NetworkAgentInfo keyed off its connecting messenger
4401 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004402 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004403 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4404 new HashMap<Messenger, NetworkAgentInfo>();
4405
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004406 @GuardedBy("mBlockedAppUids")
4407 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4408
Paul Jensen2c311d62014-11-17 12:34:51 -05004409 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004410 private final NetworkRequest mDefaultRequest;
4411
Erik Klineda4bfa82015-04-30 12:58:40 +09004412 // Request used to optionally keep mobile data active even when higher
4413 // priority networks like Wi-Fi are active.
4414 private final NetworkRequest mDefaultMobileDataRequest;
4415
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004416 private NetworkAgentInfo getDefaultNetwork() {
4417 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4418 }
4419
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004420 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004421 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004422 }
4423
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004424 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4425 return nri.request.requestId == mDefaultRequest.requestId;
4426 }
4427
Paul Jensen31a94f42015-02-13 14:18:39 -05004428 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004429 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004430 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004431 enforceConnectivityInternalPermission();
4432
Paul Jensen2c311d62014-11-17 12:34:51 -05004433 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4434 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004435 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004436 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4437 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004438 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004439 synchronized (this) {
4440 nai.networkMonitor.systemReady = mSystemReady;
4441 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004442 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4443 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004444 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004445 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004446 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004447 }
4448
4449 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4450 if (VDBG) log("Got NetworkAgent Messenger");
4451 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004452 synchronized (mNetworkForNetId) {
4453 mNetworkForNetId.put(na.network.netId, na);
4454 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004455 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4456 NetworkInfo networkInfo = na.networkInfo;
4457 na.networkInfo = null;
4458 updateNetworkInfo(na, networkInfo);
4459 }
4460
4461 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4462 LinkProperties newLp = networkAgent.linkProperties;
4463 int netId = networkAgent.network.netId;
4464
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004465 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4466 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004467 if (networkAgent.clatd != null) {
4468 networkAgent.clatd.fixupLinkProperties(oldLp);
4469 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004470
Paul Jensen992f2522014-04-28 10:33:11 -04004471 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004472 updateMtu(newLp, oldLp);
4473 // TODO - figure out what to do for clat
4474// for (LinkProperties lp : newLp.getStackedLinks()) {
4475// updateMtu(lp, null);
4476// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004477 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004478
Erik Kline94887872016-04-05 13:30:49 +09004479 updateRoutes(newLp, oldLp, netId);
4480 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004481
Paul Jensen3b759822014-05-13 11:44:01 -04004482 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004483 if (isDefaultNetwork(networkAgent)) {
4484 handleApplyDefaultProxy(newLp.getHttpProxy());
4485 } else {
4486 updateProxy(newLp, oldLp, networkAgent);
4487 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004488 // TODO - move this check to cover the whole function
4489 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004490 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004491 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4492 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004493
4494 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004495 }
4496
Lorenzo Colitti95439462014-10-09 13:44:48 +09004497 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4498 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4499 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004500
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004501 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004502 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4503 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004504 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004505 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004506 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004507 }
Paul Jensen992f2522014-04-28 10:33:11 -04004508
4509 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4510 CompareResult<String> interfaceDiff = new CompareResult<String>();
4511 if (oldLp != null) {
4512 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4513 } else if (newLp != null) {
4514 interfaceDiff.added = newLp.getAllInterfaceNames();
4515 }
4516 for (String iface : interfaceDiff.added) {
4517 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004518 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004519 mNetd.addInterfaceToNetwork(iface, netId);
4520 } catch (Exception e) {
4521 loge("Exception adding interface: " + e);
4522 }
4523 }
4524 for (String iface : interfaceDiff.removed) {
4525 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004526 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004527 mNetd.removeInterfaceFromNetwork(iface, netId);
4528 } catch (Exception e) {
4529 loge("Exception removing interface: " + e);
4530 }
4531 }
4532 }
4533
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004534 /**
4535 * Have netd update routes from oldLp to newLp.
4536 * @return true if routes changed between oldLp and newLp
4537 */
4538 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004539 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4540 if (oldLp != null) {
4541 routeDiff = oldLp.compareAllRoutes(newLp);
4542 } else if (newLp != null) {
4543 routeDiff.added = newLp.getAllRoutes();
4544 }
4545
4546 // add routes before removing old in case it helps with continuous connectivity
4547
4548 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4549 for (RouteInfo route : routeDiff.added) {
4550 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004551 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004552 try {
4553 mNetd.addRoute(netId, route);
4554 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004555 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4556 loge("Exception in addRoute for non-gateway: " + e);
4557 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004558 }
4559 }
4560 for (RouteInfo route : routeDiff.added) {
4561 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004562 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004563 try {
4564 mNetd.addRoute(netId, route);
4565 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004566 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4567 loge("Exception in addRoute for gateway: " + e);
4568 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 }
4570 }
4571
4572 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004573 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004574 try {
4575 mNetd.removeRoute(netId, route);
4576 } catch (Exception e) {
4577 loge("Exception in removeRoute: " + e);
4578 }
4579 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004580 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004581 }
Erik Kline41368502015-06-17 13:19:54 +09004582
Erik Kline94887872016-04-05 13:30:49 +09004583 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4584 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4585 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004586 }
Erik Kline94887872016-04-05 13:30:49 +09004587
4588 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004589 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004590 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004591 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004592 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4593 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004594 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004595 }
4596 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4597 if (defaultNai != null && defaultNai.network.netId == netId) {
4598 setDefaultDnsSystemProperties(dnses);
4599 }
4600 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004601 }
4602
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004603 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4604 int last = 0;
4605 for (InetAddress dns : dnses) {
4606 ++last;
4607 String key = "net.dns" + last;
4608 String value = dns.getHostAddress();
4609 SystemProperties.set(key, value);
4610 }
4611 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4612 String key = "net.dns" + i;
4613 SystemProperties.set(key, "");
4614 }
4615 mNumDnsEntries = last;
4616 }
4617
Paul Jensen3d194ea2015-06-16 14:27:36 -04004618 /**
4619 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4620 * augmented with any stateful capabilities implied from {@code networkAgent}
4621 * (e.g., validated status and captive portal status).
4622 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004623 * @param oldScore score of the network before any of the changes that prompted us
4624 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004625 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004626 * @param networkCapabilities the new network capabilities.
4627 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004628 private void updateCapabilities(
4629 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004630 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4631 networkCapabilities)) {
4632 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4633 + nai.networkCapabilities + " -> " + networkCapabilities);
4634 }
4635
Paul Jensen3d194ea2015-06-16 14:27:36 -04004636 // Don't modify caller's NetworkCapabilities.
4637 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004638 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004639 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4640 } else {
4641 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4642 }
Paul Jensene0988542015-06-25 15:30:08 -04004643 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004644 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4645 } else {
4646 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4647 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004648 if (nai.isBackgroundNetwork()) {
4649 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4650 } else {
4651 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4652 }
4653
4654 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4655
4656 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4657 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4658 try {
4659 mNetd.setNetworkPermission(nai.network.netId,
4660 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4661 null : NetworkManagementService.PERMISSION_SYSTEM);
4662 } catch (RemoteException e) {
4663 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004664 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004665 }
4666
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004667 final NetworkCapabilities prevNc = nai.networkCapabilities;
4668 synchronized (nai) {
4669 nai.networkCapabilities = networkCapabilities;
4670 }
4671 if (nai.getCurrentScore() == oldScore &&
4672 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4673 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4674 // the change we're processing can't affect any requests, it can only affect the listens
4675 // on this network. We might have been called by rematchNetworkAndRequests when a
4676 // network changed foreground state.
4677 processListenRequests(nai, true);
4678 } else {
4679 // If the requestable capabilities have changed or the score changed, we can't have been
4680 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004681 rematchAllNetworksAndRequests(nai, oldScore);
4682 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004683 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004684 }
4685
Paul Jensenc8b9a742014-09-30 15:37:41 -04004686 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004687 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4688 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004689 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004690 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004691 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4692 }
4693 }
4694
Robert Greenwalt7b816022014-04-18 15:25:25 -07004695 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4696 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004697 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004698 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4699 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004700 }
4701 }
4702
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004703 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4704 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004705 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004706 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004707 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4708 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004709 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004710 sendIntent(nri.mPendingIntent, intent);
4711 }
4712 // else not handled
4713 }
4714
4715 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4716 mPendingIntentWakeLock.acquire();
4717 try {
4718 if (DBG) log("Sending " + pendingIntent);
4719 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4720 } catch (PendingIntent.CanceledException e) {
4721 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4722 mPendingIntentWakeLock.release();
4723 releasePendingNetworkRequest(pendingIntent);
4724 }
4725 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4726 }
4727
4728 @Override
4729 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4730 String resultData, Bundle resultExtras) {
4731 if (DBG) log("Finished sending " + pendingIntent);
4732 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004733 // Release with a delay so the receiving client has an opportunity to put in its
4734 // own request.
4735 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004736 }
4737
Robert Greenwalt9258c642014-03-26 16:47:06 -07004738 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004739 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004740 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004741 Bundle bundle = new Bundle();
4742 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4743 new NetworkRequest(nri.request));
4744 Message msg = Message.obtain();
4745 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4746 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4747 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4748 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004749 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004750 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004751 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004752 break;
4753 }
4754 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4755 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4756 new NetworkCapabilities(networkAgent.networkCapabilities));
4757 break;
4758 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004759 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004760 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4761 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004762 break;
4763 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004764 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004765 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004766 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004767 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004768 if (VDBG) {
4769 log("sending notification " + notifyTypeToName(notificationType) +
4770 " for " + nri.request);
4771 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004772 nri.messenger.send(msg);
4773 } catch (RemoteException e) {
4774 // may occur naturally in the race of binder death.
4775 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4776 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004777 }
4778
Paul Jensenc8b9a742014-09-30 15:37:41 -04004779 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004780 if (nai.numRequestNetworkRequests() != 0) {
4781 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4782 NetworkRequest nr = nai.requestAt(i);
4783 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004784 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004785 loge("Dead network still had at least " + nr);
4786 break;
4787 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004788 }
4789 nai.asyncChannel.disconnect();
4790 }
4791
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4793 if (oldNetwork == null) {
4794 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4795 return;
4796 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004797 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004798
4799 // If we get here it means that the last linger timeout for this network expired. So there
4800 // must be no other active linger timers, and we must stop lingering.
4801 oldNetwork.clearLingerState();
4802
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004803 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004804 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004805 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004806 } else {
4807 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004808 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4809 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004810 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004811 }
4812
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004813 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004814 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004815 setupDataActivityTracking(newNetwork);
4816 try {
4817 mNetd.setDefaultNetId(newNetwork.network.netId);
4818 } catch (Exception e) {
4819 loge("Exception setting default network :" + e);
4820 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004821 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004822 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004823 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004824 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004825 }
4826
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004827 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004828 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4829 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4830 NetworkRequest nr = nri.request;
4831 if (!nr.isListen()) continue;
4832 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4833 nai.removeRequest(nri.request.requestId);
4834 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4835 }
4836 }
4837
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004838 if (capabilitiesChanged) {
4839 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4840 }
4841
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004842 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4843 NetworkRequest nr = nri.request;
4844 if (!nr.isListen()) continue;
4845 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4846 nai.addRequest(nr);
4847 notifyNetworkCallback(nai, nri);
4848 }
4849 }
4850 }
4851
Paul Jensen2161a8e2014-09-11 11:00:39 -04004852 // Handles a network appearing or improving its score.
4853 //
4854 // - Evaluates all current NetworkRequests that can be
4855 // satisfied by newNetwork, and reassigns to newNetwork
4856 // any such requests for which newNetwork is the best.
4857 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004858 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004859 // needed. A network is needed if it is the best network for
4860 // one or more NetworkRequests, or if it is a VPN.
4861 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004862 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004863 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004864 //
4865 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4866 // networks that have no chance (i.e. even if validated)
4867 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004868 //
4869 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4870 // it does not remove NetworkRequests that other Networks could better satisfy.
4871 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4872 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4873 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004874 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004875 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004876 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4877 // performed to tear down unvalidated networks that have no chance (i.e. even if
4878 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004879 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004880 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004881 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004882 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004883 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004884 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004885
4886 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4887 final int score = newNetwork.getCurrentScore();
4888
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004889 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004890
Paul Jensen2161a8e2014-09-11 11:00:39 -04004891 // Find and migrate to this Network any NetworkRequests for
4892 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004893 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004894 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004895 NetworkCapabilities nc = newNetwork.networkCapabilities;
4896 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004897 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004898 // Process requests in the first pass and listens in the second pass. This allows us to
4899 // change a network's capabilities depending on which requests it has. This is only
4900 // correct if the change in capabilities doesn't affect whether the network satisfies
4901 // requests or not, and doesn't affect the network's score.
4902 if (nri.request.isListen()) continue;
4903
Paul Jensencf4c2c62015-07-01 14:16:32 -04004904 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4905 final boolean satisfies = newNetwork.satisfies(nri.request);
4906 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004907 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004908 log("Network " + newNetwork.name() + " was already satisfying" +
4909 " request " + nri.request.requestId + ". No change.");
4910 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004911 keep = true;
4912 continue;
4913 }
4914
4915 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004916 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004917 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004918 // next check if it's better than any current network we're using for
4919 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004920 if (VDBG) {
4921 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004922 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004923 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004924 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004925 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004926 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004927 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004928 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004929 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004930 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004931 affectedNetworks.add(currentNetwork);
4932 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004933 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004934 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004935 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004936 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004937 if (!newNetwork.addRequest(nri.request)) {
4938 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4939 }
4940 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004942 // Tell NetworkFactories about the new score, so they can stop
4943 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004944 // TODO - this could get expensive if we have alot of requests for this
4945 // network. Think about if there is a way to reduce this. Push
4946 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004947 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004948 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004949 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004950 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004951 if (currentNetwork != null) {
4952 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4953 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004954 }
4955 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004956 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004957 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4958 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004959 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004960 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4961 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4962 // This means this code doesn't have to handle the case where "currentNetwork" no
4963 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4964 if (DBG) {
4965 log("Network " + newNetwork.name() + " stopped satisfying" +
4966 " request " + nri.request.requestId);
4967 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004968 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004969 if (currentNetwork == newNetwork) {
4970 mNetworkForRequestId.remove(nri.request.requestId);
4971 sendUpdatedScoreToFactories(nri.request, 0);
4972 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004973 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4974 newNetwork.name() +
4975 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004976 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004977 // TODO: Technically, sending CALLBACK_LOST here is
4978 // incorrect if there is a replacement network currently
4979 // connected that can satisfy nri, which is a request
4980 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004981 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4982 // so this code is only incorrect for a network that loses
4983 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004984 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004985 }
4986 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004987 if (isNewDefault) {
4988 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004989 makeDefault(newNetwork);
4990 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4991 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004992 synchronized (ConnectivityService.this) {
4993 // have a new default network, release the transition wakelock in
4994 // a second if it's held. The second pause is to allow apps
4995 // to reconnect over the new network
4996 if (mNetTransitionWakeLock.isHeld()) {
4997 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4998 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4999 mNetTransitionWakeLockSerialNumber, 0),
5000 1000);
5001 }
5002 }
5003 }
5004
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005005 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5006 Slog.wtf(TAG, String.format(
5007 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
5008 nc, newNetwork.networkCapabilities));
5009 }
5010 if (newNetwork.getCurrentScore() != score) {
5011 Slog.wtf(TAG, String.format(
5012 "BUG: %s changed score during rematch: %d -> %d",
5013 score, newNetwork.getCurrentScore()));
5014 }
5015
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005016 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005017 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5018 // If the network went from background to foreground or vice versa, we need to update
5019 // its foreground state. It is safe to do this after rematching the requests because
5020 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5021 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005022 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005023 } else {
5024 processListenRequests(newNetwork, false);
5025 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005026
Paul Jensencf4c2c62015-07-01 14:16:32 -04005027 // do this after the default net is switched, but
5028 // before LegacyTypeTracker sends legacy broadcasts
5029 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
5030
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005031 // Linger any networks that are no longer needed. This should be done after sending the
5032 // available callback for newNetwork.
5033 for (NetworkAgentInfo nai : affectedNetworks) {
5034 updateLingerState(nai, now);
5035 }
5036 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5037 // does not need to be done in any particular order.
5038 updateLingerState(newNetwork, now);
5039
Paul Jensencf4c2c62015-07-01 14:16:32 -04005040 if (isNewDefault) {
5041 // Maintain the illusion: since the legacy API only
5042 // understands one network at a time, we must pretend
5043 // that the current default network disconnected before
5044 // the new one connected.
5045 if (oldDefaultNetwork != null) {
5046 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5047 oldDefaultNetwork, true);
5048 }
5049 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5050 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5051 notifyLockdownVpn(newNetwork);
5052 }
5053
Robert Greenwalt7b816022014-04-18 15:25:25 -07005054 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005055 // Notify battery stats service about this network, both the normal
5056 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005057 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005058 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005059 final IBatteryStats bs = BatteryStatsService.getService();
5060 final int type = newNetwork.networkInfo.getType();
5061
5062 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5063 bs.noteNetworkInterfaceType(baseIface, type);
5064 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5065 final String stackedIface = stacked.getInterfaceName();
5066 bs.noteNetworkInterfaceType(stackedIface, type);
5067 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5068 }
5069 } catch (RemoteException ignored) {
5070 }
5071
Robert Greenwalt152ed372014-12-17 17:19:53 -08005072 // This has to happen after the notifyNetworkCallbacks as that tickles each
5073 // ConnectivityManager instance so that legacy requests correctly bind dns
5074 // requests to this network. The legacy users are listening for this bcast
5075 // and will generally do a dns request so they can ensureRouteToHost and if
5076 // they do that before the callbacks happen they'll use the default network.
5077 //
5078 // TODO: Is there still a race here? We send the broadcast
5079 // after sending the callback, but if the app can receive the
5080 // broadcast before the callback, it might still break.
5081 //
5082 // This *does* introduce a race where if the user uses the new api
5083 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5084 // they may get old info. Reverse this after the old startUsing api is removed.
5085 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005086 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5087 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005088 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005089 // legacy type tracker filters out repeat adds
5090 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5091 }
5092 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005093
5094 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5095 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5096 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5097 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5098 if (newNetwork.isVPN()) {
5099 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5100 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005101 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005102 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5103 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005104 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005105 if (nai.getLingerExpiry() > 0) {
5106 // This network has active linger timers and no requests, but is not
5107 // lingering. Linger it.
5108 //
5109 // One way (the only way?) this can happen if this network is unvalidated
5110 // and became unneeded due to another network improving its score to the
5111 // point where this network will no longer be able to satisfy any requests
5112 // even if it validates.
5113 updateLingerState(nai, now);
5114 } else {
5115 if (DBG) log("Reaping " + nai.name());
5116 teardownUnneededNetwork(nai);
5117 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005118 }
5119 }
5120 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005121 }
5122
Paul Jensen1c7ba022015-06-16 14:27:36 -04005123 /**
5124 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5125 * being disconnected.
5126 * @param changed If only one Network's score or capabilities have been modified since the last
5127 * time this function was called, pass this Network in this argument, otherwise pass
5128 * null.
5129 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5130 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5131 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5132 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5133 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005134 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005135 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005136 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5137 // to avoid the slowness. It is not simply enough to process just "changed", for
5138 // example in the case where "changed"'s score decreases and another network should begin
5139 // satifying a NetworkRequest that "changed" currently satisfies.
5140
5141 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5142 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5143 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005144 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005145 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005146 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005147 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005148 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5149 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5150 // Rematch higher scoring networks first to prevent requests first matching a lower
5151 // scoring network and then a higher scoring network, which could produce multiple
5152 // callbacks and inadvertently unlinger networks.
5153 Arrays.sort(nais);
5154 for (NetworkAgentInfo nai : nais) {
5155 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005156 // Only reap the last time through the loop. Reaping before all rematching
5157 // is complete could incorrectly teardown a network that hasn't yet been
5158 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005159 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005160 : ReapUnvalidatedNetworks.REAP,
5161 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005162 }
5163 }
5164 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005165
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005166 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005167 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005168 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005169 // For now only update icons for default connection.
5170 // TODO: Update WiFi and cellular icons separately. b/17237507
5171 if (!isDefaultNetwork(nai)) return;
5172
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005173 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005174 // Don't repeat publish.
5175 if (newInetCondition == mDefaultInetConditionPublished) return;
5176
5177 mDefaultInetConditionPublished = newInetCondition;
5178 sendInetConditionBroadcast(nai.networkInfo);
5179 }
5180
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005181 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5182 if (mLockdownTracker != null) {
5183 if (nai != null && nai.isVPN()) {
5184 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5185 } else {
5186 mLockdownTracker.onNetworkInfoChanged();
5187 }
5188 }
5189 }
5190
Robert Greenwalt7b816022014-04-18 15:25:25 -07005191 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5192 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005193 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005194 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005195 synchronized (networkAgent) {
5196 oldInfo = networkAgent.networkInfo;
5197 networkAgent.networkInfo = newInfo;
5198 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005199 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005200
5201 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005202 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5203 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5204 notifyIfacesChangedForNetworkStats();
5205 } else if (VDBG) log("ignoring duplicate network state non-change");
5206 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005207 return;
5208 }
5209 if (DBG) {
5210 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5211 (oldInfo == null ? "null" : oldInfo.getState()) +
5212 " to " + state);
5213 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005214
Robin Lee585e2482016-05-01 23:00:00 +01005215 if (!networkAgent.created
5216 && (state == NetworkInfo.State.CONNECTED
5217 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005218
5219 // A network that has just connected has zero requests and is thus a foreground network.
5220 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5221
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005223 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005224 if (networkAgent.isVPN()) {
5225 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005226 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5227 (networkAgent.networkMisc == null ||
5228 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005229 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005230 mNetd.createPhysicalNetwork(networkAgent.network.netId,
5231 networkAgent.networkCapabilities.hasCapability(
5232 NET_CAPABILITY_NOT_RESTRICTED) ?
5233 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005234 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005235 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005236 loge("Error creating network " + networkAgent.network.netId + ": "
5237 + e.getMessage());
5238 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005239 }
Paul Jenseneec75412014-08-04 12:21:19 -04005240 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005241 }
5242
5243 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5244 networkAgent.everConnected = true;
5245
Robert Greenwalt7b816022014-04-18 15:25:25 -07005246 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005247 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005248
Paul Jensenca8f16a2014-05-09 12:47:55 -04005249 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005250 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005251
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005252 if (networkAgent.isVPN()) {
5253 // Temporarily disable the default proxy (not global).
5254 synchronized (mProxyLock) {
5255 if (!mDefaultProxyDisabled) {
5256 mDefaultProxyDisabled = true;
5257 if (mGlobalProxy == null && mDefaultProxy != null) {
5258 sendProxyBroadcast(null);
5259 }
5260 }
5261 }
5262 // TODO: support proxy per network.
5263 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005264
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005265 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5266 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5267 // capabilities, so it only needs to be done once on initial connect, not every time the
5268 // network's capabilities change. Note that we do this before rematching the network,
5269 // so we could decide to tear it down immediately afterwards. That's fine though - on
5270 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5271 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005272 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005273
Paul Jensen2161a8e2014-09-11 11:00:39 -04005274 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005275 final long now = SystemClock.elapsedRealtime();
5276 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005277
5278 // This has to happen after matching the requests, because callbacks are just requests.
5279 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005280 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005281 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005282 if (networkAgent.isVPN()) {
5283 synchronized (mProxyLock) {
5284 if (mDefaultProxyDisabled) {
5285 mDefaultProxyDisabled = false;
5286 if (mGlobalProxy == null && mDefaultProxy != null) {
5287 sendProxyBroadcast(mDefaultProxy);
5288 }
5289 }
5290 }
5291 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005292 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5293 state == NetworkInfo.State.SUSPENDED) {
5294 // going into or coming out of SUSPEND: rescore and notify
5295 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005296 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005297 }
5298 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5299 ConnectivityManager.CALLBACK_SUSPENDED :
5300 ConnectivityManager.CALLBACK_RESUMED));
5301 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005302 }
5303 }
5304
Robert Greenwaltac96c522014-06-03 16:43:57 -07005305 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005306 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005307 if (score < 0) {
5308 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5309 "). Bumping score to min of 0");
5310 score = 0;
5311 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005312
Paul Jensen2161a8e2014-09-11 11:00:39 -04005313 final int oldScore = nai.getCurrentScore();
5314 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005315
Paul Jensen85cf78e2015-06-25 13:25:07 -04005316 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005317
Paul Jensenc8b9a742014-09-30 15:37:41 -04005318 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005319 }
5320
Robert Greenwalt9258c642014-03-26 16:47:06 -07005321 // notify only this one new request of the current state
5322 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5323 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005324 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005325 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005326 } else {
5327 sendPendingIntentForRequest(nri, nai, notifyType);
5328 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005329 }
5330
Robert Greenwalt8d482522015-06-24 13:23:42 -07005331 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005332 // The NetworkInfo we actually send out has no bearing on the real
5333 // state of affairs. For example, if the default connection is mobile,
5334 // and a request for HIPRI has just gone away, we need to pretend that
5335 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5336 // the state to DISCONNECTED, even though the network is of type MOBILE
5337 // and is still connected.
5338 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5339 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005340 if (state != DetailedState.DISCONNECTED) {
5341 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005342 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005343 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005344 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005345 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5346 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5347 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5348 if (info.isFailover()) {
5349 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5350 nai.networkInfo.setFailover(false);
5351 }
5352 if (info.getReason() != null) {
5353 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5354 }
5355 if (info.getExtraInfo() != null) {
5356 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5357 }
5358 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005359 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005360 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005361 if (newDefaultAgent != null) {
5362 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5363 newDefaultAgent.networkInfo);
5364 } else {
5365 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5366 }
5367 }
5368 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5369 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005370 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005371 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005372 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005373 }
5374 }
5375 }
5376
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005377 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005378 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005379 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5380 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005381 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5382 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005383 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5384 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005385 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005386 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005387 } else {
5388 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5389 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005390 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005391 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005392
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005393 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5394 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5395 }
5396
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005397 private String notifyTypeToName(int notifyType) {
5398 switch (notifyType) {
5399 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5400 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5401 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5402 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5403 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5404 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5405 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5406 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5407 }
5408 return "UNKNOWN";
5409 }
5410
Jeff Sharkey69736342014-12-08 14:50:12 -08005411 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005412 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5413 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005414 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005415 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005416 try {
5417 mStatsService.forceUpdateIfaces();
5418 } catch (Exception ignored) {
5419 }
5420 }
5421
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005422 @Override
5423 public boolean addVpnAddress(String address, int prefixLength) {
5424 throwIfLockdownEnabled();
5425 int user = UserHandle.getUserId(Binder.getCallingUid());
5426 synchronized (mVpns) {
5427 return mVpns.get(user).addAddress(address, prefixLength);
5428 }
5429 }
5430
5431 @Override
5432 public boolean removeVpnAddress(String address, int prefixLength) {
5433 throwIfLockdownEnabled();
5434 int user = UserHandle.getUserId(Binder.getCallingUid());
5435 synchronized (mVpns) {
5436 return mVpns.get(user).removeAddress(address, prefixLength);
5437 }
5438 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005439
5440 @Override
5441 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5442 throwIfLockdownEnabled();
5443 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005444 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005445 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005446 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005447 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005448 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005449 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005450 }
5451 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005452 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005453
5454 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005455 public String getCaptivePortalServerUrl() {
5456 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5457 }
5458
5459 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005460 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5461 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5462 enforceKeepalivePermission();
5463 mKeepaliveTracker.startNattKeepalive(
5464 getNetworkAgentInfoForNetwork(network),
5465 intervalSeconds, messenger, binder,
5466 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5467 }
5468
5469 @Override
5470 public void stopKeepalive(Network network, int slot) {
5471 mHandler.sendMessage(mHandler.obtainMessage(
5472 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5473 }
5474
5475 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005476 public void factoryReset() {
5477 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005478
5479 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5480 return;
5481 }
5482
Robin Lee3b3dd942015-05-12 18:14:58 +01005483 final int userId = UserHandle.getCallingUserId();
5484
Stuart Scottf1fb3972015-04-02 18:00:02 -07005485 // Turn airplane mode off
5486 setAirplaneMode(false);
5487
Stuart Scotte3e314d2015-04-20 14:07:45 -07005488 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5489 // Untether
5490 for (String tether : getTetheredIfaces()) {
5491 untether(tether);
5492 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005493 }
5494
Stuart Scotte3e314d2015-04-20 14:07:45 -07005495 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005496 // Remove always-on package
5497 synchronized (mVpns) {
5498 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5499 if (alwaysOnPackage != null) {
5500 setAlwaysOnVpnPackage(userId, null, false);
5501 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5502 }
5503 }
5504
Stuart Scotte3e314d2015-04-20 14:07:45 -07005505 // Turn VPN off
5506 VpnConfig vpnConfig = getVpnConfig(userId);
5507 if (vpnConfig != null) {
5508 if (vpnConfig.legacy) {
5509 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5510 } else {
5511 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5512 // in the future without user intervention.
5513 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005514
Victor Changb04a5ea2016-05-30 20:36:30 +01005515 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005516 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005517 }
5518 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005519
5520 Settings.Global.putString(mContext.getContentResolver(),
5521 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005522 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005523
5524 @VisibleForTesting
5525 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5526 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5527 return new NetworkMonitor(context, handler, nai, defaultRequest);
5528 }
Erik Kline48f12f22016-04-14 17:30:59 +09005529
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005530 @VisibleForTesting
5531 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5532 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5533 }
5534
Hugo Benichicfddd682016-05-31 16:28:06 +09005535 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005536 int newNetid = NETID_UNSET;
5537 int prevNetid = NETID_UNSET;
5538 int[] transports = new int[0];
5539 boolean hadIPv4 = false;
5540 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005541
Hugo Benichi5f16f762016-04-20 12:09:33 +09005542 if (newNai != null) {
5543 newNetid = newNai.network.netId;
5544 transports = newNai.networkCapabilities.getTransportTypes();
5545 }
5546 if (prevNai != null) {
5547 prevNetid = prevNai.network.netId;
5548 final LinkProperties lp = prevNai.linkProperties;
5549 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5550 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5551 }
5552
Hugo Benichicfddd682016-05-31 16:28:06 +09005553 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5554 }
5555
5556 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5557 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559}