blob: 7572dfe0c53deb2bac904dad0785fa5973b7a8ab [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070032import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070034import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090042import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090078import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
Erik Kline065ab6e2016-10-02 18:02:14 +090081import android.net.util.AvoidBadWifiTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080083import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070084import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040085import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070087import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070089import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070092import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070094import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070095import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080097import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090098import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700100import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400101import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700103import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700106import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600107import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700108import android.util.LocalLog;
109import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600110import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700111import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800112import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700113import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500114import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700116import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Wink Savilleab9321d2013-06-29 21:10:57 -0700118import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400119import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400120import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700122import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700123import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700124import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800125import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700126import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700127import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700128import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900129import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900130import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700131import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700132import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400133import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900134import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700135import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900136import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900137import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700138import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600139import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400140import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900141import com.android.server.connectivity.NetworkNotificationManager;
142import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400143import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700144import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800145import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700146import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700147import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700148import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600149
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700150import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700151
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700152import org.xmlpull.v1.XmlPullParser;
153import org.xmlpull.v1.XmlPullParserException;
154
155import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700157import java.io.FileNotFoundException;
158import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700159import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700161import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700162import java.net.InetAddress;
163import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700164import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700166import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700167import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700168import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700169import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700170import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700171import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700172import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600173import java.util.SortedSet;
174import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
176/**
177 * @hide
178 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800179public class ConnectivityService extends IConnectivityManager.Stub
180 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900181 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900183 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700184 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Jake Hamby786e71a2014-02-06 14:43:50 -0800186 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900187 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700188
Jeff Sharkey899223b2012-08-04 15:24:58 -0700189 // TODO: create better separation between radio types and network types
190
Robert Greenwalt42acef32009-08-12 16:08:25 -0700191 // how long to wait before switching back to a radio's default network
192 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
193 // system property that can override the above value
194 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
195 "android.telephony.apn-restore";
196
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900197 // How long to wait before putting up a "This network doesn't have an Internet connection,
198 // connect anyway?" dialog after the user selects a network that doesn't validate.
199 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
200
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900201 // Default to 30s linger time-out. Modifiable only for testing.
202 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
203 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
204 @VisibleForTesting
205 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
206
Jeremy Joslin79294842014-12-03 17:15:28 -0800207 // How long to delay to removal of a pending intent based request.
208 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
209 private final int mReleasePendingIntentDelayMs;
210
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800211 private Tethering mTethering;
212
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700213 private final PermissionMonitor mPermissionMonitor;
214
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700215 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700216
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700217 @GuardedBy("mVpns")
218 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700219
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700220 private boolean mLockdownEnabled;
221 private LockdownVpnTracker mLockdownTracker;
222
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700223 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
224 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700225 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600226 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700227 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700228 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600229 @GuardedBy("mRulesLock")
230 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
231 /** Flag indicating if background data is restricted. */
232 @GuardedBy("mRulesLock")
233 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700234
Erik Klineda4bfa82015-04-30 12:58:40 +0900235 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700237 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700238 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800240 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700243 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700245 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800246 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700247 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700248
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700249 private String mCurrentTcpBufferSizes;
250
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700251 private static final int ENABLED = 1;
252 private static final int DISABLED = 0;
253
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900254 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900255 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
256 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900257
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400259 // Tear down networks that have no chance (e.g. even if validated) of becoming
260 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500261 // all networks have been rematched against all NetworkRequests.
262 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400263 // Don't reap networks. This should be passed when some networks have not yet been
264 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500265 DONT_REAP
266 };
267
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900268 private enum UnneededFor {
269 LINGER, // Determine whether this network is unneeded and should be lingered.
270 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
271 }
272
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700273 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700274 * used internally to change our mobile data enabled flag
275 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700276 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700277
278 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700279 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700280 * from one net to another. Clear happens when we get a new
281 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
282 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700285
Robert Greenwalt434203a2010-10-11 16:00:27 -0700286 /**
287 * used internally to reload global proxy settings
288 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700289 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700290
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700291 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400292 * PAC manager has received new port.
293 */
294 private static final int EVENT_PROXY_HAS_CHANGED = 16;
295
Robert Greenwalte049c232014-04-11 15:53:27 -0700296 /**
297 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700298 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700299 */
300 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
301
Robert Greenwalt7b816022014-04-18 15:25:25 -0700302 /**
303 * used internally when registering NetworkAgents
304 * obj = Messenger
305 */
306 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
307
Robert Greenwalt9258c642014-03-26 16:47:06 -0700308 /**
309 * used to add a network request
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
313
314 /**
315 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900316 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700317 * cancel it.
318 * includes a NetworkRequestInfo
319 */
320 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
321
322 /**
323 * used to add a network listener - no request
324 * includes a NetworkRequestInfo
325 */
326 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
327
328 /**
329 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400330 * arg1 = UID of caller
331 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700332 */
333 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
334
Robert Greenwalta67be032014-05-16 15:49:14 -0700335 /**
336 * used internally when registering NetworkFactories
337 * obj = Messenger
338 */
339 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
340
Robert Greenwalt27711812014-06-25 16:45:57 -0700341 /**
342 * used internally to expire a wakelock when transitioning
343 * from one net to another. Expire happens when we fail to find
344 * a new network (typically after 1 minute) -
345 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
346 * a replacement network.
347 */
348 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
349
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700350 /**
351 * Used internally to indicate the system is ready.
352 */
353 private static final int EVENT_SYSTEM_READY = 25;
354
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800355 /**
356 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400357 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800358 */
359 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
360
361 /**
362 * used to remove a pending intent and its associated network request.
363 * arg1 = UID of caller
364 * obj = PendingIntent
365 */
366 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
367
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900368 /**
369 * used to specify whether a network should be used even if unvalidated.
370 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
371 * arg2 = whether to remember this choice in the future (1 or 0)
372 * obj = network
373 */
374 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
375
376 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900377 * used to specify whether a network should not be penalized when it becomes unvalidated.
378 */
379 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
380
381 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900382 * used to ask the user to confirm a connection to an unvalidated network.
383 * obj = network
384 */
385 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700386
Erik Klineda4bfa82015-04-30 12:58:40 +0900387 /**
388 * used internally to (re)configure mobile data always-on settings.
389 */
390 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
391
Paul Jensen694f2b82015-06-17 14:15:39 -0400392 /**
393 * used to add a network listener with a pending intent
394 * obj = NetworkRequestInfo
395 */
396 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
397
Erik Klineacdd6392016-07-07 16:50:58 +0900398 /**
399 * Indicates a caller has requested to have its callback invoked with
400 * the latest LinkProperties or NetworkCapabilities.
401 *
402 * arg1 = UID of caller
403 * obj = NetworkRequest
404 */
405 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
406 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
407
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900408 /** Handler thread used for both of the handlers below. */
409 @VisibleForTesting
410 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700411 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700412 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700413 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700414 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700415
Mike Lockwood0f79b542009-08-14 14:18:49 -0400416 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800417 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400418
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700419 private PowerManager.WakeLock mNetTransitionWakeLock;
420 private String mNetTransitionWakeLockCausedBy = "";
421 private int mNetTransitionWakeLockSerialNumber;
422 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800423 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700424
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700425 // used in DBG mode to track inet condition reports
426 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
427 private ArrayList mInetLog;
428
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400430 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700431 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700432 private boolean mDefaultProxyDisabled = false;
433
Robert Greenwalt434203a2010-10-11 16:00:27 -0700434 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400435 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700436
Jason Monk602b2322013-07-03 17:04:33 -0400437 private PacManager mPacManager = null;
438
Erik Klineda4bfa82015-04-30 12:58:40 +0900439 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700440
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400441 private UserManager mUserManager;
442
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700443 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700444 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700445
Robert Greenwalt50393202011-06-21 17:26:14 -0700446 // the set of network types that can only be enabled by system/sig apps
447 List mProtectedNetworks;
448
John Spurlockbf991a82013-06-24 14:20:23 -0400449 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700450
Wink Savilleab9321d2013-06-29 21:10:57 -0700451 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400452
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900453 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900454 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900455 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900456
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700457 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
458 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700459 private final static int MAX_NET_ID = 65535;
460 private int mNextNetId = MIN_NET_ID;
461
Robert Greenwalt34524f02014-05-18 16:22:10 -0700462 // sequence number of NetworkRequests
463 private int mNextNetworkRequestId = 1;
464
Erik Kline7523eb32015-07-09 18:24:03 +0900465 // NetworkRequest activity String log entries.
466 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
467 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
468
Hugo Benichic2ae2872016-07-11 11:05:12 +0900469 // NetworkInfo blocked and unblocked String log entries
470 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
471 private static final int MAX_NETWORK_INFO_LOGS = 100;
472 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
473
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700474 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
475 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400476 private static class ValidationLog {
477 final Network mNetwork;
478 final String mNetworkExtraInfo;
479 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700480
Paul Jensen0808eb82016-06-03 13:51:21 -0400481 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
482 mNetwork = network;
483 mNetworkExtraInfo = networkExtraInfo;
484 mLog = log;
485 }
486 }
487 private final ArrayDeque<ValidationLog> mValidationLogs =
488 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
489
490 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700491 synchronized(mValidationLogs) {
492 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
493 mValidationLogs.removeLast();
494 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400495 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700496 }
497 }
498
Hugo Benichif9fdf872016-07-28 17:53:06 +0900499 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900500
Erik Kline065ab6e2016-10-02 18:02:14 +0900501 @VisibleForTesting
502 final AvoidBadWifiTracker mAvoidBadWifiTracker;
503
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
Jeremy Joslin79294842014-12-03 17:15:28 -0800723 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
724 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
725
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900726 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
727
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700729 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800730 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700731 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700732 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700733 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700734
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700735 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600736 mPolicyManager.setConnectivityListener(mPolicyListener);
737 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700738 } catch (RemoteException e) {
739 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700740 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700741 }
742
743 final PowerManager powerManager = (PowerManager) context.getSystemService(
744 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700745 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
746 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
747 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800748 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700749
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700750 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700751
Wink Saville51f456f2013-04-23 14:26:51 -0700752 // TODO: What is the "correct" way to do determine if this is a wifi only device?
753 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
754 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755 String[] naStrings = context.getResources().getStringArray(
756 com.android.internal.R.array.networkAttributes);
757 for (String naString : naStrings) {
758 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700759 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700760 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700761 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800762 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700763 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700764 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700765 }
Wink Saville51f456f2013-04-23 14:26:51 -0700766 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
767 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
768 n.type);
769 continue;
770 }
Wink Saville975c8482011-04-07 14:23:45 -0700771 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800772 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700773 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700774 continue;
775 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700776 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700777
Wink Saville975c8482011-04-07 14:23:45 -0700778 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700779 mNetworksDefined++;
780 } catch(Exception e) {
781 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700782 }
783 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700784
785 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
786 if (mNetConfigs[TYPE_VPN] == null) {
787 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
788 // don't need to add TYPE_VPN to mNetConfigs.
789 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
790 mNetworksDefined++; // used only in the log() statement below.
791 }
792
Wink Saville5e56bc52013-07-29 15:00:57 -0700793 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700794
Robert Greenwalt50393202011-06-21 17:26:14 -0700795 mProtectedNetworks = new ArrayList<Integer>();
796 int[] protectedNetworks = context.getResources().getIntArray(
797 com.android.internal.R.array.config_protectedNetworks);
798 for (int p : protectedNetworks) {
799 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
800 mProtectedNetworks.add(p);
801 } else {
802 if (DBG) loge("Ignoring protectedNetwork " + p);
803 }
804 }
805
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700806 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
807 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700808
Christopher Wiley497c1472016-10-11 13:26:03 -0700809 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
810 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800811
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700812 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
813
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700814 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700815 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100816 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700817 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700818 intentFilter.addAction(Intent.ACTION_USER_ADDED);
819 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000820 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700821 mContext.registerReceiverAsUser(
822 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900823
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700824 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700825 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700826 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700827 } catch (RemoteException e) {
828 loge("Error registering observer :" + e);
829 }
830
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700831 if (DBG) {
832 mInetLog = new ArrayList();
833 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700834
Erik Klineda4bfa82015-04-30 12:58:40 +0900835 mSettingsObserver = new SettingsObserver(mContext, mHandler);
836 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800837
John Spurlockbf991a82013-06-24 14:20:23 -0400838 mDataConnectionStats = new DataConnectionStats(mContext);
839 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400840
Jason Monkdecd2952013-10-10 14:02:51 -0400841 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700842
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400843 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900844
845 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900846 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
847 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900848
849 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
850 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
851 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
852 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
853 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
854 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
855 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900856
Erik Kline065ab6e2016-10-02 18:02:14 +0900857 mAvoidBadWifiTracker = createAvoidBadWifiTracker(
858 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Erik Kline6c0782f2016-12-12 21:21:40 +0900859 mAvoidBadWifiTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700861
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900862 private NetworkRequest createInternetRequestForTransport(
863 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900864 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900865 netCap.addCapability(NET_CAPABILITY_INTERNET);
866 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900867 if (transportType > -1) {
868 netCap.addTransportType(transportType);
869 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900870 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900871 }
872
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900873 // Used only for testing.
874 // TODO: Delete this and either:
875 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
876 // changing ContentResolver to make registerContentObserver non-final).
877 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
878 // by subclassing SettingsObserver.
879 @VisibleForTesting
880 void updateMobileDataAlwaysOn() {
881 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
882 }
883
Erik Klineda4bfa82015-04-30 12:58:40 +0900884 private void handleMobileDataAlwaysOn() {
885 final boolean enable = (Settings.Global.getInt(
886 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
887 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
888 if (enable == isEnabled) {
889 return; // Nothing to do.
890 }
891
892 if (enable) {
893 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900894 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900895 } else {
896 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
897 }
898 }
899
900 private void registerSettingsCallbacks() {
901 // Watch for global HTTP proxy changes.
902 mSettingsObserver.observe(
903 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
904 EVENT_APPLY_GLOBAL_HTTP_PROXY);
905
906 // Watch for whether or not to keep mobile data always on.
907 mSettingsObserver.observe(
908 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
909 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
910 }
911
Robert Greenwalt34524f02014-05-18 16:22:10 -0700912 private synchronized int nextNetworkRequestId() {
913 return mNextNetworkRequestId++;
914 }
915
Paul Jensen67b0b072015-06-10 11:22:17 -0400916 @VisibleForTesting
917 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400918 synchronized (mNetworkForNetId) {
919 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
920 int netId = mNextNetId;
921 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
922 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500923 if (!mNetIdInUse.get(netId)) {
924 mNetIdInUse.put(netId, true);
925 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400926 }
927 }
928 }
929 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700930 }
931
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600932 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600934 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
935 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600937 state = nai.getNetworkState();
938 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600940 final NetworkInfo info = new NetworkInfo(networkType, 0,
941 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
943 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600944 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
945 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600947 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600948 return state;
949 } else {
950 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400952 }
953
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800954 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
955 if (network == null) {
956 return null;
957 }
958 synchronized (mNetworkForNetId) {
959 return mNetworkForNetId.get(network.netId);
960 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600961 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900963 private Network[] getVpnUnderlyingNetworks(int uid) {
964 if (!mLockdownEnabled) {
965 int user = UserHandle.getUserId(uid);
966 synchronized (mVpns) {
967 Vpn vpn = mVpns.get(user);
968 if (vpn != null && vpn.appliesToUid(uid)) {
969 return vpn.getUnderlyingNetworks();
970 }
971 }
972 }
973 return null;
974 }
975
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800976 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400977 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800978
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900979 final Network[] networks = getVpnUnderlyingNetworks(uid);
980 if (networks != null) {
981 // getUnderlyingNetworks() returns:
982 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
983 // empty array => the VPN explicitly said "no default network".
984 // non-empty array => the VPN specified one or more default networks; we use the
985 // first one.
986 if (networks.length > 0) {
987 nai = getNetworkAgentInfoForNetwork(networks[0]);
988 } else {
989 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800990 }
991 }
992
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600994 return nai.getNetworkState();
995 } else {
996 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800997 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400998 }
999
1000 /**
1001 * Check if UID should be blocked from using the network with the given LinkProperties.
1002 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001003 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1004 boolean ignoreBlocked) {
1005 // Networks aren't blocked when ignoring blocked status
1006 if (ignoreBlocked) return false;
1007 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001008 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001009
1010 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001011 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001012
Robin Lee17e61832016-05-09 13:46:28 +01001013 synchronized (mVpns) {
1014 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1015 if (vpn != null && vpn.isBlockingUid(uid)) {
1016 return true;
1017 }
1018 }
1019
Robert Greenwalt12e67352014-05-13 21:41:06 -07001020 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001021 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001022 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001023 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001024 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001025
Felipe Lemed31a97f2016-05-06 14:53:50 -07001026 boolean allowed = true;
1027 // Check Data Saver Mode first...
1028 if (networkMetered) {
1029 if ((uidRules & RULE_REJECT_METERED) != 0) {
1030 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1031 // Explicitly blacklisted.
1032 allowed = false;
1033 } else {
1034 allowed = !mRestrictBackground
1035 || (uidRules & RULE_ALLOW_METERED) != 0
1036 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1037 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1038 + " mRestrictBackground=" + mRestrictBackground
1039 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1040 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1041 + ": " + allowed);
1042 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001043 }
Felipe Leme781ba142016-05-09 16:24:48 -07001044 // ...then power restrictions.
1045 if (allowed) {
1046 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001047 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001048 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001049 }
1050 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001051 }
1052
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001053 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001054 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1055 return;
1056 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001057 boolean removed = false;
1058 boolean added = false;
1059 synchronized (mBlockedAppUids) {
1060 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1061 added = true;
1062 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1063 removed = true;
1064 }
1065 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001066 if (added) {
1067 log("Returning blocked NetworkInfo to uid=" + uid);
1068 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1069 } else if (removed) {
1070 log("Returning unblocked NetworkInfo to uid=" + uid);
1071 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1072 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001073 }
1074
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001076 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1077 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1078 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1079 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001080 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001081 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001082 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1083
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001084 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001086 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001087 if (mLockdownTracker != null) {
1088 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001089 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001090
1091 // TODO: apply metered state closer to NetworkAgentInfo
1092 final long token = Binder.clearCallingIdentity();
1093 try {
1094 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1095 } catch (RemoteException e) {
1096 } finally {
1097 Binder.restoreCallingIdentity(token);
1098 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001099 }
1100
1101 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 * Return NetworkInfo for the active (i.e., connected) network interface.
1103 * It is assumed that at most one network is active at a time. If more
1104 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001105 * @return the info for the active network, or {@code null} if none is
1106 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001108 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001110 enforceAccessPermission();
1111 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001112 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001113 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001114 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1115 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
1117
Paul Jensen31a94f42015-02-13 14:18:39 -05001118 @Override
1119 public Network getActiveNetwork() {
1120 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001121 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001122 }
1123
1124 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001125 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001126 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001127 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001128 }
1129
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001131 final int user = UserHandle.getUserId(uid);
1132 int vpnNetId = NETID_UNSET;
1133 synchronized (mVpns) {
1134 final Vpn vpn = mVpns.get(user);
1135 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1136 }
1137 NetworkAgentInfo nai;
1138 if (vpnNetId != NETID_UNSET) {
1139 synchronized (mNetworkForNetId) {
1140 nai = mNetworkForNetId.get(vpnNetId);
1141 }
1142 if (nai != null) return nai.network;
1143 }
1144 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001145 if (nai != null
1146 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1147 nai = null;
1148 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001149 return nai != null ? nai.network : null;
1150 }
1151
Lorenzo Colitti18660282016-07-04 12:55:44 +09001152 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001153 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1154 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 final int uid = Binder.getCallingUid();
1156 NetworkState state = getUnfilteredActiveNetworkState(uid);
1157 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001158 }
1159
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001160 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001161 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001163 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001164 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001165 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001166 }
1167
1168 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 public NetworkInfo getNetworkInfo(int networkType) {
1170 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001172 if (getVpnUnderlyingNetworks(uid) != null) {
1173 // A VPN is active, so we may need to return one of its underlying networks. This
1174 // information is not available in LegacyTypeTracker, so we have to get it from
1175 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001176 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001177 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001178 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001179 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001180 }
1181 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001182 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001187 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001188 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001189 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001191 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001193 return state.networkInfo;
1194 } else {
1195 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001196 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001197 }
1198
1199 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 public NetworkInfo[] getAllNetworkInfo() {
1201 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001202 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001203 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1204 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001205 NetworkInfo info = getNetworkInfo(networkType);
1206 if (info != null) {
1207 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001210 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
1212
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001213 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001214 public Network getNetworkForType(int networkType) {
1215 enforceAccessPermission();
1216 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001217 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1218 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001219 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001220 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001222 }
1223
1224 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001225 public Network[] getAllNetworks() {
1226 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001227 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001228 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001229 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001230 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001231 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001232 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001233 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001234 }
1235
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001236 @Override
1237 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1238 // The basic principle is: if an app's traffic could possibly go over a
1239 // network, without the app doing anything multinetwork-specific,
1240 // (hence, by "default"), then include that network's capabilities in
1241 // the array.
1242 //
1243 // In the normal case, app traffic only goes over the system's default
1244 // network connection, so that's the only network returned.
1245 //
1246 // With a VPN in force, some app traffic may go into the VPN, and thus
1247 // over whatever underlying networks the VPN specifies, while other app
1248 // traffic may go over the system default network (e.g.: a split-tunnel
1249 // VPN, or an app disallowed by the VPN), so the set of networks
1250 // returned includes the VPN's underlying networks and the system
1251 // default.
1252 enforceAccessPermission();
1253
1254 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1255
1256 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001257 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001258 if (nc != null) {
1259 result.put(nai.network, nc);
1260 }
1261
1262 if (!mLockdownEnabled) {
1263 synchronized (mVpns) {
1264 Vpn vpn = mVpns.get(userId);
1265 if (vpn != null) {
1266 Network[] networks = vpn.getUnderlyingNetworks();
1267 if (networks != null) {
1268 for (Network network : networks) {
1269 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001270 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001271 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001272 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001273 }
1274 }
1275 }
1276 }
1277 }
1278 }
1279
1280 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1281 out = result.values().toArray(out);
1282 return out;
1283 }
1284
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001285 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001286 public boolean isNetworkSupported(int networkType) {
1287 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001288 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001289 }
1290
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001291 /**
1292 * Return LinkProperties for the active (i.e., connected) default
1293 * network interface. It is assumed that at most one default network
1294 * is active at a time. If more than one is active, it is indeterminate
1295 * which will be returned.
1296 * @return the ip properties for the active network, or {@code null} if
1297 * none is active
1298 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001299 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001300 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001301 enforceAccessPermission();
1302 final int uid = Binder.getCallingUid();
1303 NetworkState state = getUnfilteredActiveNetworkState(uid);
1304 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001305 }
1306
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001307 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001308 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001309 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001310 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1311 if (nai != null) {
1312 synchronized (nai) {
1313 return new LinkProperties(nai.linkProperties);
1314 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001315 }
1316 return null;
1317 }
1318
Robert Greenwalt12e67352014-05-13 21:41:06 -07001319 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001320 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001321 public LinkProperties getLinkProperties(Network network) {
1322 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001323 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001324 if (nai != null) {
1325 synchronized (nai) {
1326 return new LinkProperties(nai.linkProperties);
1327 }
1328 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001329 return null;
1330 }
1331
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001332 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001333 if (nai != null) {
1334 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001335 if (nai.networkCapabilities != null) {
1336 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001337 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001338 }
1339 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001340 return null;
1341 }
1342
1343 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001344 public NetworkCapabilities getNetworkCapabilities(Network network) {
1345 enforceAccessPermission();
1346 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1347 }
1348
1349 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001350 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001351 // Require internal since we're handing out IMSI details
1352 enforceConnectivityInternalPermission();
1353
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001354 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001355 for (Network network : getAllNetworks()) {
1356 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1357 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001358 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001359 }
1360 }
1361 return result.toArray(new NetworkState[result.size()]);
1362 }
1363
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001364 @Override
1365 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1366 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001367 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001368 final long token = Binder.clearCallingIdentity();
1369 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001370 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1371 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001372 try {
1373 return mPolicyManager.getNetworkQuotaInfo(state);
1374 } catch (RemoteException e) {
1375 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001376 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001377 return null;
1378 } finally {
1379 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001380 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001381 }
1382
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001383 @Override
1384 public boolean isActiveNetworkMetered() {
1385 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001386
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001387 final NetworkInfo info = getActiveNetworkInfo();
1388 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001389 }
1390
Jeff Sharkey216c1812012-08-05 14:29:23 -07001391 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1392 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001393 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001394 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001395 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001396 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001397 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001398
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001399 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 * Ensure that a network route exists to deliver traffic to the specified
1401 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001402 * @param networkType the type of the network over which traffic to the
1403 * specified host is to be routed
1404 * @param hostAddress the IP address of the host to which the route is
1405 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 * @return {@code true} on success, {@code false} on failure
1407 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001408 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001411 if (mProtectedNetworks.contains(networkType)) {
1412 enforceConnectivityInternalPermission();
1413 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001414
Chad Brubakerc0234532014-02-14 13:24:29 -08001415 InetAddress addr;
1416 try {
1417 addr = InetAddress.getByAddress(hostAddress);
1418 } catch (UnknownHostException e) {
1419 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1420 return false;
1421 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001424 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 return false;
1426 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001427
1428 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1429 if (nai == null) {
1430 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1431 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1432 } else {
1433 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1434 }
1435 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001436 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001438 DetailedState netState;
1439 synchronized (nai) {
1440 netState = nai.networkInfo.getDetailedState();
1441 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001442
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001443 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001444 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001445 log("requestRouteToHostAddress on down network "
1446 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001447 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001448 }
1449 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001451
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001452 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001453 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001454 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001455 LinkProperties lp;
1456 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001457 synchronized (nai) {
1458 lp = nai.linkProperties;
1459 netId = nai.network.netId;
1460 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001461 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001462 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1463 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001464 } finally {
1465 Binder.restoreCallingIdentity(token);
1466 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001467 }
1468
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001469 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001470 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001471 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001472 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001473 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001474 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001475 if (bestRoute.getGateway().equals(addr)) {
1476 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001477 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001478 } else {
1479 // if we will connect to this through another route, add a direct route
1480 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001481 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001482 }
1483 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001484 if (DBG) log("Adding legacy route " + bestRoute +
1485 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001486 try {
1487 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1488 } catch (Exception e) {
1489 // never crash - catch them all
1490 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001491 return false;
1492 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001493 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1497 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001498 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001499 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001500 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001501 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 }
1503
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001504 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001505 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001506 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001507 if (oldRules == uidRules) return;
1508
Felipe Leme781ba142016-05-09 16:24:48 -07001509 if (uidRules == RULE_NONE) {
1510 mUidRules.delete(uid);
1511 } else {
1512 mUidRules.put(uid, uidRules);
1513 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001514 }
1515
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001516 // TODO: notify UID when it has requested targeted updates
1517 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001518
1519 @Override
1520 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001521 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001522 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001523 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001524 }
1525
1526 synchronized (mRulesLock) {
1527 mMeteredIfaces.clear();
1528 for (String iface : meteredIfaces) {
1529 mMeteredIfaces.add(iface);
1530 }
1531 }
1532 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001533
1534 @Override
1535 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1536 // caller is NPMS, since we only register with them
1537 if (LOGD_RULES) {
1538 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1539 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001540
1541 synchronized (mRulesLock) {
1542 mRestrictBackground = restrictBackground;
1543 }
1544
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001545 if (restrictBackground) {
1546 log("onRestrictBackgroundChanged(true): disabling tethering");
1547 mTethering.untetherAll();
1548 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001549 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001550
1551 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001552 public void onUidPoliciesChanged(int uid, int uidPolicies) {
1553 // caller is NPMS, since we only register with them
Felipe Leme019fcd22016-04-19 10:24:39 -07001554 if (LOGD_RULES) {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001555 log("onUidRulesChanged(uid=" + uid + ", uidPolicies=" + uidPolicies + ")");
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001556 }
1557 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001558 };
1559
Robin Lee3b3dd942015-05-12 18:14:58 +01001560 /**
1561 * Require that the caller is either in the same user or has appropriate permission to interact
1562 * across users.
1563 *
1564 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1565 */
1566 private void enforceCrossUserPermission(int userId) {
1567 if (userId == UserHandle.getCallingUserId()) {
1568 // Not a cross-user call.
1569 return;
1570 }
1571 mContext.enforceCallingOrSelfPermission(
1572 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1573 "ConnectivityService");
1574 }
1575
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001576 private void enforceInternetPermission() {
1577 mContext.enforceCallingOrSelfPermission(
1578 android.Manifest.permission.INTERNET,
1579 "ConnectivityService");
1580 }
1581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001583 mContext.enforceCallingOrSelfPermission(
1584 android.Manifest.permission.ACCESS_NETWORK_STATE,
1585 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587
1588 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001589 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 }
1591
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001592 private void enforceTetherAccessPermission() {
1593 mContext.enforceCallingOrSelfPermission(
1594 android.Manifest.permission.ACCESS_NETWORK_STATE,
1595 "ConnectivityService");
1596 }
1597
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001598 private void enforceConnectivityInternalPermission() {
1599 mContext.enforceCallingOrSelfPermission(
1600 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1601 "ConnectivityService");
1602 }
1603
Hugo Benichi514da602016-07-19 15:59:27 +09001604 private void enforceConnectivityRestrictedNetworksPermission() {
1605 try {
1606 mContext.enforceCallingOrSelfPermission(
1607 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1608 "ConnectivityService");
1609 return;
1610 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1611 enforceConnectivityInternalPermission();
1612 }
1613
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001614 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001615 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001616 }
1617
Lorenzo Colitti18660282016-07-04 12:55:44 +09001618 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001619 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001620 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001621 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001622 }
1623
1624 private void sendInetConditionBroadcast(NetworkInfo info) {
1625 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1626 }
1627
Wink Saville628b0852011-08-04 15:01:58 -07001628 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001629 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001630 info = new NetworkInfo(info);
1631 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001632 }
1633
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001634 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001635 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001636 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 if (info.isFailover()) {
1638 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1639 info.setFailover(false);
1640 }
1641 if (info.getReason() != null) {
1642 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1643 }
1644 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001645 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1646 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001648 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001649 return intent;
1650 }
1651
1652 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1653 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1654 }
1655
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001656 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001657 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1658 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1659 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001660 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001661 final long ident = Binder.clearCallingIdentity();
1662 try {
1663 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1664 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1665 } finally {
1666 Binder.restoreCallingIdentity(ident);
1667 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001668 }
1669
Mike Lockwood0f79b542009-08-14 14:18:49 -04001670 private void sendStickyBroadcast(Intent intent) {
1671 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001672 if (!mSystemReady) {
1673 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001674 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001675 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001676 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001677 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001678 }
1679
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001680 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001681 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001682 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001683 final NetworkInfo ni = intent.getParcelableExtra(
1684 ConnectivityManager.EXTRA_NETWORK_INFO);
1685 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1686 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1687 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001688 } else {
1689 BroadcastOptions opts = BroadcastOptions.makeBasic();
1690 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1691 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001692 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001693 final IBatteryStats bs = BatteryStatsService.getService();
1694 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001695 bs.noteConnectivityChanged(intent.getIntExtra(
1696 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1697 ni != null ? ni.getState().toString() : "?");
1698 } catch (RemoteException e) {
1699 }
1700 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001701 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001702 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001703 } finally {
1704 Binder.restoreCallingIdentity(ident);
1705 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001706 }
1707 }
1708
1709 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001710 loadGlobalProxy();
1711
Mike Lockwood0f79b542009-08-14 14:18:49 -04001712 synchronized(this) {
1713 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001714 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001715 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001716 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001717 }
1718 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001719 // load the global proxy at startup
1720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001721
Robin Lee244ce8e2016-01-05 18:03:46 +00001722 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1723 // for user to unlock device too.
1724 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001725
Erik Klineda4bfa82015-04-30 12:58:40 +09001726 // Configure whether mobile data is always on.
1727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1728
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001729 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001730
1731 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
1733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001735 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001736 *
1737 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001738 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001739 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001740 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1741 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001742
1743 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001744 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001745
Robert Greenwalt7b816022014-04-18 15:25:25 -07001746 if (networkAgent.networkCapabilities.hasTransport(
1747 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001748 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1749 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001750 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001751 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001752 } else if (networkAgent.networkCapabilities.hasTransport(
1753 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001754 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1755 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001756 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001757 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001758 } else {
1759 // do not track any other networks
1760 timeout = 0;
1761 }
1762
Robert Greenwalt7b816022014-04-18 15:25:25 -07001763 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001764 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001765 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001766 } catch (Exception e) {
1767 // You shall not crash!
1768 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001769 }
1770 }
1771 }
1772
1773 /**
1774 * Remove data activity tracking when network disconnects.
1775 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001776 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1777 final String iface = networkAgent.linkProperties.getInterfaceName();
1778 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001779
Robert Greenwalt7b816022014-04-18 15:25:25 -07001780 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1781 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001782 try {
1783 // the call fails silently if no idletimer setup for this interface
1784 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001785 } catch (Exception e) {
1786 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001787 }
1788 }
1789 }
1790
1791 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001792 * Reads the network specific MTU size from reources.
1793 * and set it on it's iface.
1794 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001795 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1796 final String iface = newLp.getInterfaceName();
1797 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001798 if (oldLp == null && mtu == 0) {
1799 // Silently ignore unset MTU value.
1800 return;
1801 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001802 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1803 if (VDBG) log("identical MTU - not setting");
1804 return;
1805 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001806 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001807 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001808 return;
1809 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001810
w1997615afd812014-08-05 15:18:11 -07001811 // Cannot set MTU without interface name
1812 if (TextUtils.isEmpty(iface)) {
1813 loge("Setting MTU size with null iface.");
1814 return;
1815 }
1816
Robert Greenwalt7b816022014-04-18 15:25:25 -07001817 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001818 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001819 mNetd.setMtu(iface, mtu);
1820 } catch (Exception e) {
1821 Slog.e(TAG, "exception in setMtu()" + e);
1822 }
1823 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001824
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001825 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001826 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1827
1828 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001829 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001830 protected int getDefaultTcpRwnd() {
1831 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1832 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001833
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001834 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1835 if (isDefaultNetwork(nai) == false) {
1836 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001837 }
1838
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001839 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1840 String[] values = null;
1841 if (tcpBufferSizes != null) {
1842 values = tcpBufferSizes.split(",");
1843 }
1844
1845 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001846 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001847 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1848 values = tcpBufferSizes.split(",");
1849 }
1850
1851 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1852
1853 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001854 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001855
1856 final String prefix = "/sys/kernel/ipv4/tcp_";
1857 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1858 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1859 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1860 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1861 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1862 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1863 mCurrentTcpBufferSizes = tcpBufferSizes;
1864 } catch (IOException e) {
1865 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001866 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001867
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001868 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001869 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001870 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1871 if (rwndValue != 0) {
1872 SystemProperties.set(sysctlKey, rwndValue.toString());
1873 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001874 }
1875
Mattias Falk8b47b362011-08-23 14:15:13 +02001876 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001877 /*
1878 * Tell the VMs to toss their DNS caches
1879 */
1880 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1881 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001882 /*
1883 * Connectivity events can happen before boot has completed ...
1884 */
1885 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001886 final long ident = Binder.clearCallingIdentity();
1887 try {
1888 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1889 } finally {
1890 Binder.restoreCallingIdentity(ident);
1891 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001892 }
1893
Robert Greenwalt562cc542014-05-15 18:07:26 -07001894 @Override
1895 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001896 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1897 NETWORK_RESTORE_DELAY_PROP_NAME);
1898 if(restoreDefaultNetworkDelayStr != null &&
1899 restoreDefaultNetworkDelayStr.length() != 0) {
1900 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001901 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001902 } catch (NumberFormatException e) {
1903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001905 // if the system property isn't set, use the value for the apn type
1906 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1907
1908 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1909 (mNetConfigs[networkType] != null)) {
1910 ret = mNetConfigs[networkType].restoreTime;
1911 }
1912 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
1914
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001915 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001916 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001917 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001918 }
1919 return false;
1920 }
1921
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001922 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1923 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1924 final long DIAG_TIME_MS = 5000;
1925 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1926 // Start gathering diagnostic information.
1927 netDiags.add(new NetworkDiagnostics(
1928 nai.network,
1929 new LinkProperties(nai.linkProperties), // Must be a copy.
1930 DIAG_TIME_MS));
1931 }
1932
1933 for (NetworkDiagnostics netDiag : netDiags) {
1934 pw.println();
1935 netDiag.waitForMeasurements();
1936 netDiag.dump(pw);
1937 }
1938 }
1939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001941 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1942 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001943 if (mContext.checkCallingOrSelfPermission(
1944 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001946 pw.println("Permission Denial: can't dump ConnectivityService " +
1947 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1948 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 return;
1950 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001951
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001952 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001953 dumpNetworkDiagnostics(pw);
1954 return;
1955 }
Erik Kline379747a2015-06-05 17:47:34 +09001956
Lorenzo Colittie3805462015-06-03 11:18:24 +09001957 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001958 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001959 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001960 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001961 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001962 pw.println();
1963
Paul Jensen85cf78e2015-06-25 13:25:07 -04001964 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001965 pw.print("Active default network: ");
1966 if (defaultNai == null) {
1967 pw.println("none");
1968 } else {
1969 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001971 pw.println();
1972
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001973 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001974 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001975 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1976 pw.println(nai.toString());
1977 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001978 pw.println(String.format(
1979 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1980 nai.numForegroundNetworkRequests(),
1981 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1982 nai.numBackgroundNetworkRequests(),
1983 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001984 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001985 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1986 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001987 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001988 pw.decreaseIndent();
1989 pw.println("Lingered:");
1990 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001991 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001992 pw.decreaseIndent();
1993 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001994 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001995 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001996 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001997
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001998 pw.println("Metered Interfaces:");
1999 pw.increaseIndent();
2000 for (String value : mMeteredIfaces) {
2001 pw.println(value);
2002 }
2003 pw.decreaseIndent();
2004 pw.println();
2005
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002006 pw.print("Restrict background: ");
2007 pw.println(mRestrictBackground);
2008 pw.println();
2009
Felipe Leme46c4fc32016-05-04 09:21:43 -07002010 pw.println("Status for known UIDs:");
2011 pw.increaseIndent();
2012 final int size = mUidRules.size();
2013 for (int i = 0; i < size; i++) {
2014 final int uid = mUidRules.keyAt(i);
2015 pw.print("UID=");
2016 pw.print(uid);
2017 final int uidRules = mUidRules.get(uid, RULE_NONE);
2018 pw.print(" rules=");
2019 pw.print(uidRulesToString(uidRules));
2020 pw.println();
2021 }
2022 pw.println();
2023 pw.decreaseIndent();
2024
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002025 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002026 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002027 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2028 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002029 }
2030 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002031 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002032
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002033 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002034
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002035 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002036 pw.print("mNetTransitionWakeLock: currently " +
2037 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2038 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2039 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2040 } else {
2041 pw.println(", last requested never");
2042 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002043 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002044
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002045 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002046 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002047
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002048 pw.println();
2049 mKeepaliveTracker.dump(pw);
2050
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002051 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002052 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002053
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002054 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09002055 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002056 pw.println();
2057 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002058 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002059 for(int i = 0; i < mInetLog.size(); i++) {
2060 pw.println(mInetLog.get(i));
2061 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002062 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002063 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002064
2065 if (argsContain(args, "--short") == false) {
2066 pw.println();
2067 synchronized (mValidationLogs) {
2068 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002069 for (ValidationLog p : mValidationLogs) {
2070 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002071 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002072 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002073 pw.decreaseIndent();
2074 }
2075 }
Erik Kline7523eb32015-07-09 18:24:03 +09002076
2077 pw.println();
2078 pw.println("mNetworkRequestInfoLogs (most recent first):");
2079 pw.increaseIndent();
2080 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2081 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002082
2083 pw.println();
2084 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2085 pw.increaseIndent();
2086 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2087 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002091 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002092 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002093 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002094 if (officialNai != null && officialNai.equals(nai)) return true;
2095 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002096 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002097 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002098 " - " + nai);
2099 }
2100 return false;
2101 }
2102
Robert Greenwalt42acef32009-08-12 16:08:25 -07002103 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002104 private class NetworkStateTrackerHandler extends Handler {
2105 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002106 super(looper);
2107 }
2108
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002109 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002111 default:
2112 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002113 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 handleAsyncChannelHalfConnect(msg);
2115 break;
2116 }
2117 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2118 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2119 if (nai != null) nai.asyncChannel.disconnect();
2120 break;
2121 }
2122 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2123 handleAsyncChannelDisconnected(msg);
2124 break;
2125 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002126 }
2127 return true;
2128 }
2129
2130 private void maybeHandleNetworkAgentMessage(Message msg) {
2131 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2132 if (nai == null) {
2133 if (VDBG) {
2134 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2135 log(String.format("%s from unknown NetworkAgent", what));
2136 }
2137 return;
2138 }
2139
2140 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002141 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002142 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2143 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002144 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2145 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002146 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002147 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002148 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002149 break;
2150 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002151 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 if (VDBG) {
2153 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002154 "; created=" + nai.created +
2155 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002156 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002157 LinkProperties oldLp = nai.linkProperties;
2158 synchronized (nai) {
2159 nai.linkProperties = (LinkProperties)msg.obj;
2160 }
Robin Lee585e2482016-05-01 23:00:00 +01002161 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002162 break;
2163 }
2164 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002165 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 updateNetworkInfo(nai, info);
2167 break;
2168 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002169 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002170 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002171 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002172 break;
2173 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002174 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002175 try {
2176 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002177 } catch (Exception e) {
2178 // Never crash!
2179 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002180 }
2181 break;
2182 }
2183 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002184 try {
2185 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002186 } catch (Exception e) {
2187 // Never crash!
2188 loge("Exception in removeVpnUidRanges: " + e);
2189 }
2190 break;
2191 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002192 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002193 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2194 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002195 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002196 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002197 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002198 break;
2199 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002200 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002201 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2202 break;
2203 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002204 }
2205 }
2206
2207 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2208 switch (msg.what) {
2209 default:
2210 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002211 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002212 final NetworkAgentInfo nai;
2213 synchronized (mNetworkForNetId) {
2214 nai = mNetworkForNetId.get(msg.arg2);
2215 }
2216 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002217 final boolean valid =
2218 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002219 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002220 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2221 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002222 if (valid != nai.lastValidated) {
2223 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002224 nai.lastValidated = valid;
2225 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002226 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002227 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2228 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002229 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002230 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002231 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002232 Bundle redirectUrlBundle = new Bundle();
2233 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002234 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002235 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002236 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002237 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002238 if (wasValidated && !nai.lastValidated) {
2239 handleNetworkUnvalidated(nai);
2240 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002241 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002242 break;
2243 }
Paul Jensen869868be2014-05-15 10:33:05 -04002244 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002245 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002246 final boolean visible = (msg.arg1 != 0);
2247 final NetworkAgentInfo nai;
2248 synchronized (mNetworkForNetId) {
2249 nai = mNetworkForNetId.get(netId);
2250 }
Calvin Onbe96da12016-10-11 15:10:46 -07002251 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002252 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002253 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002254 nai.lastCaptivePortalDetected = visible;
2255 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002256 if (nai.lastCaptivePortalDetected &&
2257 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2258 if (DBG) log("Avoiding captive portal network: " + nai.name());
2259 nai.asyncChannel.sendMessage(
2260 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2261 teardownUnneededNetwork(nai);
2262 break;
2263 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002264 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002265 }
2266 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002267 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002268 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002269 if (nai == null) {
2270 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2271 break;
2272 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002273 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002274 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002275 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002276 }
Paul Jensen869868be2014-05-15 10:33:05 -04002277 }
Paul Jensen869868be2014-05-15 10:33:05 -04002278 break;
2279 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002280 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002281 return true;
2282 }
2283
Calvin Onbe96da12016-10-11 15:10:46 -07002284 private int getCaptivePortalMode() {
2285 return Settings.Global.getInt(mContext.getContentResolver(),
2286 Settings.Global.CAPTIVE_PORTAL_MODE,
2287 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2288 }
2289
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002290 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2291 switch (msg.what) {
2292 default:
2293 return false;
2294 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2295 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2296 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2297 handleLingerComplete(nai);
2298 }
2299 break;
2300 }
2301 }
2302 return true;
2303 }
2304
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002305 @Override
2306 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002307 if (!maybeHandleAsyncChannelMessage(msg) &&
2308 !maybeHandleNetworkMonitorMessage(msg) &&
2309 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002310 maybeHandleNetworkAgentMessage(msg);
2311 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002312 }
2313 }
2314
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002315 private void updateLingerState(NetworkAgentInfo nai, long now) {
2316 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2317 // 2. If the network was lingering and there are now requests, unlinger it.
2318 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2319 // one lingered request, start lingering.
2320 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002321 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002322 if (DBG) log("Unlingering " + nai.name());
2323 nai.unlinger();
2324 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002325 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002326 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002327 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002328 nai.linger();
2329 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2330 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2331 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002332 }
2333
Robert Greenwalt7b816022014-04-18 15:25:25 -07002334 private void handleAsyncChannelHalfConnect(Message msg) {
2335 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002336 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002337 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2338 if (VDBG) log("NetworkFactory connected");
2339 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002340 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002341 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002342 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002343 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002344 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 }
2346 } else {
2347 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002348 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349 }
2350 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2351 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2352 if (VDBG) log("NetworkAgent connected");
2353 // A network agent has requested a connection. Establish the connection.
2354 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2355 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2356 } else {
2357 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002358 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002359 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002360 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002361 synchronized (mNetworkForNetId) {
2362 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002363 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002364 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002365 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002366 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002367 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002368 }
2369 }
2370 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002371
Robert Greenwalt7b816022014-04-18 15:25:25 -07002372 private void handleAsyncChannelDisconnected(Message msg) {
2373 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2374 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002375 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002376 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002377 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002378 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002379 // TODO - if we move the logic to the network agent (have them disconnect
2380 // because they lost all their requests or because their score isn't good)
2381 // then they would disconnect organically, report their new state and then
2382 // disconnect the channel.
2383 if (nai.networkInfo.isConnected()) {
2384 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2385 null, null);
2386 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002387 final boolean wasDefault = isDefaultNetwork(nai);
2388 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002389 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002390 // Log default network disconnection before required book-keeping.
2391 // Let rematchAllNetworksAndRequests() below record a new default network event
2392 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2393 // whose timestamps tell how long it takes to recover a default network.
2394 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002395 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002396 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002397 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2398 // by other networks that are already connected. Perhaps that can be done by
2399 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2400 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002401 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002402 mKeepaliveTracker.handleStopAllKeepalives(nai,
2403 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002404 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002405 mNetworkAgentInfos.remove(msg.replyTo);
2406 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002407 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002408 // Remove the NetworkAgent, but don't mark the netId as
2409 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002410 mNetworkForNetId.remove(nai.network.netId);
2411 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002412 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002413 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2414 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002415 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2416 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2417 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002418 sendUpdatedScoreToFactories(request, 0);
2419 }
2420 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002421 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002422 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002423 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002424 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002425 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002426 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002427 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002428 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002429 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002430 if (nai.created) {
2431 // Tell netd to clean up the configuration for this network
2432 // (routing rules, DNS, etc).
2433 // This may be slow as it requires a lot of netd shelling out to ip and
2434 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2435 // after we've rematched networks with requests which should make a potential
2436 // fallback network the default or requested a new network from the
2437 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2438 // long time.
2439 try {
2440 mNetd.removeNetwork(nai.network.netId);
2441 } catch (Exception e) {
2442 loge("Exception removing network: " + e);
2443 }
2444 }
2445 synchronized (mNetworkForNetId) {
2446 mNetIdInUse.delete(nai.network.netId);
2447 }
2448 } else {
2449 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2450 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002451 }
2452 }
2453
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002454 // If this method proves to be too slow then we can maintain a separate
2455 // pendingIntent => NetworkRequestInfo map.
2456 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2457 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2458 Intent intent = pendingIntent.getIntent();
2459 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2460 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2461 if (existingPendingIntent != null &&
2462 existingPendingIntent.getIntent().filterEquals(intent)) {
2463 return entry.getValue();
2464 }
2465 }
2466 return null;
2467 }
2468
2469 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2470 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2471
2472 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2473 if (existingRequest != null) { // remove the existing request.
2474 if (DBG) log("Replacing " + existingRequest.request + " with "
2475 + nri.request + " because their intents matched.");
2476 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2477 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002478 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002479 }
2480
Erik Klineda4bfa82015-04-30 12:58:40 +09002481 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002482 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002483 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002484 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002485 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002486 if (nri.request.networkCapabilities.hasSignalStrength() &&
2487 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2488 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002489 }
2490 }
2491 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002492 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002493 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002494 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002495 }
2496 }
2497
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002498 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2499 int callingUid) {
2500 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2501 if (nri != null) {
2502 handleReleaseNetworkRequest(nri.request, callingUid);
2503 }
2504 }
2505
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002506 // Determines whether the network is the best (or could become the best, if it validated), for
2507 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2508 // on the value of reason:
2509 //
2510 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2511 // then it should be torn down.
2512 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2513 // then it should be lingered.
2514 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2515 final int numRequests;
2516 switch (reason) {
2517 case TEARDOWN:
2518 numRequests = nai.numRequestNetworkRequests();
2519 break;
2520 case LINGER:
2521 numRequests = nai.numForegroundNetworkRequests();
2522 break;
2523 default:
2524 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2525 return true;
2526 }
2527
2528 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002529 return false;
2530 }
Paul Jensene0988542015-06-25 15:30:08 -04002531 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002532 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2533 // Background requests don't affect lingering.
2534 continue;
2535 }
2536
Paul Jensene0988542015-06-25 15:30:08 -04002537 // If this Network is already the highest scoring Network for a request, or if
2538 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002539 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002540 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002541 // Note that this catches two important cases:
2542 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2543 // is currently satisfying the request. This is desirable when
2544 // cellular ends up validating but WiFi does not.
2545 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002546 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002547 // WiFi ends up validating and out scoring cellular.
2548 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2549 nai.getCurrentScoreAsValidated())) {
2550 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002551 }
2552 }
Paul Jensene0988542015-06-25 15:30:08 -04002553 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002554 }
2555
Erik Klineacdd6392016-07-07 16:50:58 +09002556 private NetworkRequestInfo getNriForAppRequest(
2557 NetworkRequest request, int callingUid, String requestedOperation) {
2558 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2559
Robert Greenwalt9258c642014-03-26 16:47:06 -07002560 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002561 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002562 log(String.format("UID %d attempted to %s for unowned request %s",
2563 callingUid, requestedOperation, nri));
2564 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002565 }
Erik Klineacdd6392016-07-07 16:50:58 +09002566 }
2567
2568 return nri;
2569 }
2570
2571 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2572 String description, int callbackType) {
2573 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2574 if (nri == null) return;
2575
2576 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2577 // The network that is satisfying this request may have changed since
2578 // the application requested the update.
2579 //
2580 // - If the request is no longer satisfied, don't send any updates.
2581 // - If the request is satisfied by a different network, it is the
2582 // caller's responsibility to check that the Network object in the
2583 // callback matches the network that was returned in the last
2584 // onAvailable() callback for this request.
2585 if (nai == null) return;
2586 callCallbackForRequest(nri, nai, callbackType, 0);
2587 }
2588
2589 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2590 handleRequestCallbackUpdate(request, callingUid,
2591 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2592 }
2593
2594 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2595 handleRequestCallbackUpdate(request, callingUid,
2596 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2597 }
2598
Erik Kline57faba92015-11-25 12:49:38 +09002599 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2600 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2601 nri.request.requestId) == null) {
2602 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2603 }
2604 }
2605
Erik Klineacdd6392016-07-07 16:50:58 +09002606 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2607 final NetworkRequestInfo nri = getNriForAppRequest(
2608 request, callingUid, "release NetworkRequest");
Erik Kline57faba92015-11-25 12:49:38 +09002609 if (nri != null) {
2610 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2611 }
2612 }
Erik Klineacdd6392016-07-07 16:50:58 +09002613
Erik Kline57faba92015-11-25 12:49:38 +09002614 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2615 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2616 if (VDBG || (DBG && nri.request.isRequest())) {
2617 log("releasing " + nri.request + " (" + logCallbackType + ")");
2618 }
Erik Klineacdd6392016-07-07 16:50:58 +09002619 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002620 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002621 synchronized (mUidToNetworkRequestCount) {
2622 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2623 if (requests < 1) {
2624 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2625 nri.mUid);
2626 } else if (requests == 1) {
2627 mUidToNetworkRequestCount.removeAt(
2628 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2629 } else {
2630 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2631 }
2632 }
2633 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2634 if (nri.request.isRequest()) {
2635 boolean wasKept = false;
2636 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2637 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002638 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002639 nai.removeRequest(nri.request.requestId);
2640 if (VDBG) {
2641 log(" Removing from current network " + nai.name() +
2642 ", leaving " + nai.numNetworkRequests() + " requests.");
2643 }
2644 // If there are still lingered requests on this network, don't tear it down,
2645 // but resume lingering instead.
2646 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002647 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002648 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2649 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002650 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002651 wasKept = true;
2652 }
2653 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002654 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2655 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002656 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002657 }
Erik Klineacdd6392016-07-07 16:50:58 +09002658 }
2659
2660 // TODO: remove this code once we know that the Slog.wtf is never hit.
2661 //
2662 // Find all networks that are satisfying this request and remove the request
2663 // from their request lists.
2664 // TODO - it's my understanding that for a request there is only a single
2665 // network satisfying it, so this loop is wasteful
2666 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2667 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2668 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2669 otherNai.name() + ", but mNetworkAgentInfos says " +
2670 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002671 }
2672 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002673
Erik Klineacdd6392016-07-07 16:50:58 +09002674 // Maintain the illusion. When this request arrived, we might have pretended
2675 // that a network connected to serve it, even though the network was already
2676 // connected. Now that this request has gone away, we might have to pretend
2677 // that the network disconnected. LegacyTypeTracker will generate that
2678 // phantom disconnect for this type.
2679 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2680 boolean doRemove = true;
2681 if (wasKept) {
2682 // check if any of the remaining requests for this network are for the
2683 // same legacy type - if so, don't remove the nai
2684 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2685 NetworkRequest otherRequest = nai.requestAt(i);
2686 if (otherRequest.legacyType == nri.request.legacyType &&
2687 otherRequest.isRequest()) {
2688 if (DBG) log(" still have other legacy request - leaving");
2689 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002690 }
2691 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002692 }
2693
Erik Klineacdd6392016-07-07 16:50:58 +09002694 if (doRemove) {
2695 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002696 }
2697 }
Erik Klineacdd6392016-07-07 16:50:58 +09002698
2699 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2700 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2701 nri.request);
2702 }
2703 } else {
2704 // listens don't have a singular affectedNetwork. Check all networks to see
2705 // if this listen request applies and remove it.
2706 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2707 nai.removeRequest(nri.request.requestId);
2708 if (nri.request.networkCapabilities.hasSignalStrength() &&
2709 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2710 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2711 }
2712 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002713 }
Erik Kline57faba92015-11-25 12:49:38 +09002714 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002715 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002716
Lorenzo Colitti18660282016-07-04 12:55:44 +09002717 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002718 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2719 enforceConnectivityInternalPermission();
2720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2721 accept ? 1 : 0, always ? 1: 0, network));
2722 }
2723
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002724 @Override
2725 public void setAvoidUnvalidated(Network network) {
2726 enforceConnectivityInternalPermission();
2727 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2728 }
2729
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002730 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2731 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2732 " accept=" + accept + " always=" + always);
2733
2734 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2735 if (nai == null) {
2736 // Nothing to do.
2737 return;
2738 }
2739
2740 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002741 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002742 return;
2743 }
2744
2745 if (!nai.networkMisc.explicitlySelected) {
2746 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2747 }
2748
2749 if (accept != nai.networkMisc.acceptUnvalidated) {
2750 int oldScore = nai.getCurrentScore();
2751 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002752 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002753 sendUpdatedScoreToFactories(nai);
2754 }
2755
2756 if (always) {
2757 nai.asyncChannel.sendMessage(
2758 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2759 }
2760
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002761 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002762 // Tell the NetworkAgent to not automatically reconnect to the network.
2763 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2764 // Teardown the nework.
2765 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002766 }
2767
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002768 }
2769
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002770 private void handleSetAvoidUnvalidated(Network network) {
2771 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2772 if (nai == null || nai.lastValidated) {
2773 // Nothing to do. The network either disconnected or revalidated.
2774 return;
2775 }
2776 if (!nai.avoidUnvalidated) {
2777 int oldScore = nai.getCurrentScore();
2778 nai.avoidUnvalidated = true;
2779 rematchAllNetworksAndRequests(nai, oldScore);
2780 sendUpdatedScoreToFactories(nai);
2781 }
2782 }
2783
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002784 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002785 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002786 mHandler.sendMessageDelayed(
2787 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2788 PROMPT_UNVALIDATED_DELAY_MS);
2789 }
2790
Hugo Benichic8e9e122016-09-14 23:23:08 +00002791 public boolean avoidBadWifi() {
Erik Kline065ab6e2016-10-02 18:02:14 +09002792 return mAvoidBadWifiTracker.currentValue();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002793 }
2794
Erik Kline065ab6e2016-10-02 18:02:14 +09002795 private void rematchForAvoidBadWifiUpdate() {
2796 rematchAllNetworksAndRequests(null, 0);
2797 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2798 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2799 sendUpdatedScoreToFactories(nai);
2800 }
2801 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002802 }
2803
Erik Kline065ab6e2016-10-02 18:02:14 +09002804 // TODO: Evaluate whether this is of interest to other consumers of
2805 // AvoidBadWifiTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002806 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Erik Kline065ab6e2016-10-02 18:02:14 +09002807 final boolean configRestrict = mAvoidBadWifiTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002808 if (!configRestrict) {
2809 pw.println("Bad Wi-Fi avoidance: unrestricted");
2810 return;
2811 }
2812
2813 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2814 pw.increaseIndent();
2815 pw.println("Config restrict: " + configRestrict);
2816
Erik Kline065ab6e2016-10-02 18:02:14 +09002817 final String value = mAvoidBadWifiTracker.getSettingsValue();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002818 String description;
2819 // Can't use a switch statement because strings are legal case labels, but null is not.
2820 if ("0".equals(value)) {
2821 description = "get stuck";
2822 } else if (value == null) {
2823 description = "prompt";
2824 } else if ("1".equals(value)) {
2825 description = "avoid";
2826 } else {
2827 description = value + " (?)";
2828 }
2829 pw.println("User setting: " + description);
2830 pw.println("Network overrides:");
2831 pw.increaseIndent();
2832 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2833 if (nai.avoidUnvalidated) {
2834 pw.println(nai.name());
2835 }
2836 }
2837 pw.decreaseIndent();
2838 pw.decreaseIndent();
2839 }
2840
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002841 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2842 final String action;
2843 switch (type) {
2844 case NO_INTERNET:
2845 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2846 break;
2847 case LOST_INTERNET:
2848 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2849 break;
2850 default:
2851 Slog.wtf(TAG, "Unknown notification type " + type);
2852 return;
2853 }
2854
2855 Intent intent = new Intent(action);
2856 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2857 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2858 intent.setClassName("com.android.settings",
2859 "com.android.settings.wifi.WifiNoInternetDialog");
2860
2861 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2862 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2863 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2864 }
2865
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002866 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002867 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002868 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2869
2870 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2871 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002872 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002873 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002874 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2875 return;
2876 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002877 showValidationNotification(nai, NotificationType.NO_INTERNET);
2878 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002879
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002880 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2881 NetworkCapabilities nc = nai.networkCapabilities;
2882 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002883
Erik Kline065ab6e2016-10-02 18:02:14 +09002884 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
2885 mAvoidBadWifiTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002886 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2887 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002888 }
2889
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002890 private class InternalHandler extends Handler {
2891 public InternalHandler(Looper looper) {
2892 super(looper);
2893 }
2894
2895 @Override
2896 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002897 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002898 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002899 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002900 String causedBy = null;
2901 synchronized (ConnectivityService.this) {
2902 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2903 mNetTransitionWakeLock.isHeld()) {
2904 mNetTransitionWakeLock.release();
2905 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002906 } else {
2907 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002908 }
2909 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002910 if (VDBG) {
2911 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2912 log("Failed to find a new network - expiring NetTransition Wakelock");
2913 } else {
2914 log("NetTransition Wakelock (" +
2915 (causedBy == null ? "unknown" : causedBy) +
2916 " cleared because we found a replacement network");
2917 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002918 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002919 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002920 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002921 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002923 break;
2924 }
Jason Monkdecd2952013-10-10 14:02:51 -04002925 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002926 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002927 break;
2928 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002929 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002930 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2931 break;
2932 }
2933 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2934 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002935 break;
2936 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002937 case EVENT_REGISTER_NETWORK_AGENT: {
2938 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2939 break;
2940 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002941 case EVENT_REGISTER_NETWORK_REQUEST:
2942 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002943 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002944 break;
2945 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002946 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2947 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002948 handleRegisterNetworkRequestWithIntent(msg);
2949 break;
2950 }
Erik Kline57faba92015-11-25 12:49:38 +09002951 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2952 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2953 handleTimedOutNetworkRequest(nri);
2954 break;
2955 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002956 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2957 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2958 break;
2959 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002960 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002961 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002962 break;
2963 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002964 case EVENT_SET_ACCEPT_UNVALIDATED: {
2965 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2966 break;
2967 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002968 case EVENT_SET_AVOID_UNVALIDATED: {
2969 handleSetAvoidUnvalidated((Network) msg.obj);
2970 break;
2971 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002972 case EVENT_PROMPT_UNVALIDATED: {
2973 handlePromptUnvalidated((Network) msg.obj);
2974 break;
2975 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002976 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2977 handleMobileDataAlwaysOn();
2978 break;
2979 }
Erik Klineacdd6392016-07-07 16:50:58 +09002980 case EVENT_REQUEST_LINKPROPERTIES:
2981 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2982 break;
2983 case EVENT_REQUEST_NETCAPABILITIES:
2984 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2985 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002986 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2987 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2988 mKeepaliveTracker.handleStartKeepalive(msg);
2989 break;
2990 }
2991 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2992 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2993 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2994 int slot = msg.arg1;
2995 int reason = msg.arg2;
2996 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2997 break;
2998 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002999 case EVENT_SYSTEM_READY: {
3000 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3001 nai.networkMonitor.systemReady = true;
3002 }
3003 break;
3004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 }
3006 }
3007 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003008
3009 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003010 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003011 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003012 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003013 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003014 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003015 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003016 } else {
3017 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3018 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003019 }
3020
3021 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003022 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003023 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003024 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003025
3026 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003027 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003028 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003029 } else {
3030 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3031 }
3032 }
3033
3034 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003035 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003036 public int getLastTetherError(String iface) {
3037 enforceTetherAccessPermission();
3038
3039 if (isTetheringSupported()) {
3040 return mTethering.getLastTetherError(iface);
3041 } else {
3042 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3043 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003044 }
3045
3046 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003047 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003048 public String[] getTetherableUsbRegexs() {
3049 enforceTetherAccessPermission();
3050 if (isTetheringSupported()) {
3051 return mTethering.getTetherableUsbRegexs();
3052 } else {
3053 return new String[0];
3054 }
3055 }
3056
Lorenzo Colitti18660282016-07-04 12:55:44 +09003057 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003058 public String[] getTetherableWifiRegexs() {
3059 enforceTetherAccessPermission();
3060 if (isTetheringSupported()) {
3061 return mTethering.getTetherableWifiRegexs();
3062 } else {
3063 return new String[0];
3064 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003065 }
3066
Lorenzo Colitti18660282016-07-04 12:55:44 +09003067 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003068 public String[] getTetherableBluetoothRegexs() {
3069 enforceTetherAccessPermission();
3070 if (isTetheringSupported()) {
3071 return mTethering.getTetherableBluetoothRegexs();
3072 } else {
3073 return new String[0];
3074 }
3075 }
3076
Lorenzo Colitti18660282016-07-04 12:55:44 +09003077 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003078 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003079 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003080 if (isTetheringSupported()) {
3081 return mTethering.setUsbTethering(enable);
3082 } else {
3083 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3084 }
3085 }
3086
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003087 // TODO - move iface listing, queries, etc to new module
3088 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003089 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003090 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003091 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003092 return mTethering.getTetherableIfaces();
3093 }
3094
Lorenzo Colitti18660282016-07-04 12:55:44 +09003095 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003096 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003097 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003098 return mTethering.getTetheredIfaces();
3099 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003100
Lorenzo Colitti18660282016-07-04 12:55:44 +09003101 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003102 public String[] getTetheringErroredIfaces() {
3103 enforceTetherAccessPermission();
3104 return mTethering.getErroredIfaces();
3105 }
3106
Lorenzo Colitti18660282016-07-04 12:55:44 +09003107 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003108 public String[] getTetheredDhcpRanges() {
3109 enforceConnectivityInternalPermission();
3110 return mTethering.getTetheredDhcpRanges();
3111 }
3112
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003113 // if ro.tether.denied = true we default to no tethering
3114 // gservices could set the secure setting to 1 though to enable it on a build where it
3115 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003116 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003117 public boolean isTetheringSupported() {
3118 enforceTetherAccessPermission();
3119 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003120 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003121 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3122 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003123 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
3124 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003125 mTethering.getTetherableWifiRegexs().length != 0 ||
3126 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3127 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003128 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003129
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003130 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003131 public void startTethering(int type, ResultReceiver receiver,
3132 boolean showProvisioningUi) {
3133 ConnectivityManager.enforceTetherChangePermission(mContext);
3134 if (!isTetheringSupported()) {
3135 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3136 return;
3137 }
3138 mTethering.startTethering(type, receiver, showProvisioningUi);
3139 }
3140
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003141 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003142 public void stopTethering(int type) {
3143 ConnectivityManager.enforceTetherChangePermission(mContext);
3144 mTethering.stopTethering(type);
3145 }
3146
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003147 // Called when we lose the default network and have no replacement yet.
3148 // This will automatically be cleared after X seconds or a new default network
3149 // becomes CONNECTED, whichever happens first. The timer is started by the
3150 // first caller and not restarted by subsequent callers.
3151 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003152 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003153 synchronized (this) {
3154 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003155 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003156 mNetTransitionWakeLock.acquire();
3157 mNetTransitionWakeLockCausedBy = forWhom;
3158 }
3159 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003160 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003161 mNetTransitionWakeLockTimeout);
3162 return;
3163 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003164
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003165 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003166 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003167 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003168 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003169 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003170 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003171 }
3172
Lorenzo Colitti18660282016-07-04 12:55:44 +09003173 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003174 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003175 enforceAccessPermission();
3176 enforceInternetPermission();
3177
Paul Jensenbfd17b72015-04-07 12:43:13 -04003178 NetworkAgentInfo nai;
3179 if (network == null) {
3180 nai = getDefaultNetwork();
3181 } else {
3182 nai = getNetworkAgentInfoForNetwork(network);
3183 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003184 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3185 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3186 return;
3187 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003188 // Revalidate if the app report does not match our current validated state.
3189 if (hasConnectivity == nai.lastValidated) return;
3190 final int uid = Binder.getCallingUid();
3191 if (DBG) {
3192 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3193 ") by " + uid);
3194 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003195 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003196 // Validating a network that has not yet connected could result in a call to
3197 // rematchNetworkAndRequests() which is not meant to work on such networks.
3198 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003199
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003200 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003201
3202 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3203 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003204 }
3205
Paul Jensencee9b512015-05-06 07:32:40 -04003206 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003207 // this information is already available as a world read/writable jvm property
3208 // so this API change wouldn't have a benifit. It also breaks the passing
3209 // of proxy info to all the JVMs.
3210 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003211 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003212 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003213 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3214 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003215 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003216 }
3217
Lorenzo Colitti18660282016-07-04 12:55:44 +09003218 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003219 public ProxyInfo getProxyForNetwork(Network network) {
3220 if (network == null) return getDefaultProxy();
3221 final ProxyInfo globalProxy = getGlobalProxy();
3222 if (globalProxy != null) return globalProxy;
3223 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3224 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3225 // caller may not have.
3226 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3227 if (nai == null) return null;
3228 synchronized (nai) {
3229 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3230 if (proxyInfo == null) return null;
3231 return new ProxyInfo(proxyInfo);
3232 }
3233 }
3234
Paul Jensene0bef712014-12-10 15:12:18 -05003235 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3236 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3237 // proxy is null then there is no proxy in place).
3238 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3239 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3240 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3241 proxy = null;
3242 }
3243 return proxy;
3244 }
3245
3246 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3247 // better for determining if a new proxy broadcast is necessary:
3248 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3249 // avoid unnecessary broadcasts.
3250 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3251 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3252 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3253 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3254 // all set.
3255 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3256 a = canonicalizeProxyInfo(a);
3257 b = canonicalizeProxyInfo(b);
3258 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3259 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3260 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3261 }
3262
Jason Monk207900c2014-04-25 15:00:09 -04003263 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003264 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003265
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003266 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003267 if (proxyProperties == mGlobalProxy) return;
3268 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3269 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3270
3271 String host = "";
3272 int port = 0;
3273 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003274 String pacFileUrl = "";
3275 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003276 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003277 if (!proxyProperties.isValid()) {
3278 if (DBG)
3279 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3280 return;
3281 }
Jason Monk207900c2014-04-25 15:00:09 -04003282 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003283 host = mGlobalProxy.getHost();
3284 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003285 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003286 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003287 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003288 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003289 } else {
3290 mGlobalProxy = null;
3291 }
3292 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003293 final long token = Binder.clearCallingIdentity();
3294 try {
3295 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3296 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3297 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3298 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003299 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003300 } finally {
3301 Binder.restoreCallingIdentity(token);
3302 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003303
Jason Monkcf0f97a2014-10-02 15:39:38 -04003304 if (mGlobalProxy == null) {
3305 proxyProperties = mDefaultProxy;
3306 }
3307 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003308 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003309 }
3310
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003311 private void loadGlobalProxy() {
3312 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003313 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3314 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3315 String exclList = Settings.Global.getString(res,
3316 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003317 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3318 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003319 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003320 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003321 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003322 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003323 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003324 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003325 if (!proxyProperties.isValid()) {
3326 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3327 return;
3328 }
3329
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003330 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003331 mGlobalProxy = proxyProperties;
3332 }
3333 }
3334 }
3335
Jason Monk207900c2014-04-25 15:00:09 -04003336 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003337 // this information is already available as a world read/writable jvm property
3338 // so this API change wouldn't have a benifit. It also breaks the passing
3339 // of proxy info to all the JVMs.
3340 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003341 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003342 return mGlobalProxy;
3343 }
3344 }
3345
Jason Monk207900c2014-04-25 15:00:09 -04003346 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003347 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003348 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003349 proxy = null;
3350 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003351 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003352 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003353 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003354 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003355 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3356 return;
3357 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003358
3359 // This call could be coming from the PacManager, containing the port of the local
3360 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3361 // global (to get the correct local port), and send a broadcast.
3362 // TODO: Switch PacManager to have its own message to send back rather than
3363 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003364 if ((mGlobalProxy != null) && (proxy != null)
3365 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003366 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3367 mGlobalProxy = proxy;
3368 sendProxyBroadcast(mGlobalProxy);
3369 return;
3370 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003371 mDefaultProxy = proxy;
3372
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003373 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003374 if (!mDefaultProxyDisabled) {
3375 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003376 }
3377 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003378 }
3379
Paul Jensene0bef712014-12-10 15:12:18 -05003380 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3381 // This method gets called when any network changes proxy, but the broadcast only ever contains
3382 // the default proxy (even if it hasn't changed).
3383 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3384 // world where an app might be bound to a non-default network.
3385 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3386 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3387 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3388
3389 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3390 sendProxyBroadcast(getDefaultProxy());
3391 }
3392 }
3393
Robert Greenwalt434203a2010-10-11 16:00:27 -07003394 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003395 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3396 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003397 if (!TextUtils.isEmpty(proxy)) {
3398 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003399 if (data.length == 0) {
3400 return;
3401 }
3402
Robert Greenwalt434203a2010-10-11 16:00:27 -07003403 String proxyHost = data[0];
3404 int proxyPort = 8080;
3405 if (data.length > 1) {
3406 try {
3407 proxyPort = Integer.parseInt(data[1]);
3408 } catch (NumberFormatException e) {
3409 return;
3410 }
3411 }
Jason Monk207900c2014-04-25 15:00:09 -04003412 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003413 setGlobalProxy(p);
3414 }
3415 }
3416
Jason Monk207900c2014-04-25 15:00:09 -04003417 private void sendProxyBroadcast(ProxyInfo proxy) {
3418 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003419 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003420 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003421 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003422 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3423 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003424 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003425 final long ident = Binder.clearCallingIdentity();
3426 try {
3427 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3428 } finally {
3429 Binder.restoreCallingIdentity(ident);
3430 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003431 }
3432
3433 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003434 final private HashMap<Uri, Integer> mUriEventMap;
3435 final private Context mContext;
3436 final private Handler mHandler;
3437
3438 SettingsObserver(Context context, Handler handler) {
3439 super(null);
3440 mUriEventMap = new HashMap<Uri, Integer>();
3441 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003442 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003443 }
3444
Erik Klineda4bfa82015-04-30 12:58:40 +09003445 void observe(Uri uri, int what) {
3446 mUriEventMap.put(uri, what);
3447 final ContentResolver resolver = mContext.getContentResolver();
3448 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003449 }
3450
3451 @Override
3452 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003453 Slog.wtf(TAG, "Should never be reached.");
3454 }
3455
3456 @Override
3457 public void onChange(boolean selfChange, Uri uri) {
3458 final Integer what = mUriEventMap.get(uri);
3459 if (what != null) {
3460 mHandler.obtainMessage(what.intValue()).sendToTarget();
3461 } else {
3462 loge("No matching event to send for URI=" + uri);
3463 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003464 }
3465 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003466
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003467 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003468 Slog.d(TAG, s);
3469 }
3470
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003471 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003472 Slog.e(TAG, s);
3473 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003474
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003475 private static <T> T checkNotNull(T value, String message) {
3476 if (value == null) {
3477 throw new NullPointerException(message);
3478 }
3479 return value;
3480 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003481
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003482 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003483 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003484 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3485 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3486 *
3487 * @param oldPackage Package name of the application which currently controls VPN, which will
3488 * be replaced. If there is no such application, this should should either be
3489 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3490 * @param newPackage Package name of the application which should gain control of VPN, or
3491 * {@code null} to disable.
3492 * @param userId User for whom to prepare the new VPN.
3493 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003494 * @hide
3495 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003496 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003497 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3498 int userId) {
3499 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003500 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003501
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003502 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003503 Vpn vpn = mVpns.get(userId);
3504 if (vpn != null) {
3505 return vpn.prepare(oldPackage, newPackage);
3506 } else {
3507 return false;
3508 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003509 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003510 }
3511
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003512 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003513 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3514 * This method is used by system-privileged apps.
3515 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3516 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3517 *
3518 * @param packageName The package for which authorization state should change.
3519 * @param userId User for whom {@code packageName} is installed.
3520 * @param authorized {@code true} if this app should be able to start a VPN connection without
3521 * explicit user approval, {@code false} if not.
3522 *
Jeff Davidson05542602014-08-11 14:07:27 -07003523 * @hide
3524 */
3525 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003526 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3527 enforceCrossUserPermission(userId);
3528
Jeff Davidson05542602014-08-11 14:07:27 -07003529 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003530 Vpn vpn = mVpns.get(userId);
3531 if (vpn != null) {
3532 vpn.setPackageAuthorization(packageName, authorized);
3533 }
Jeff Davidson05542602014-08-11 14:07:27 -07003534 }
3535 }
3536
3537 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003538 * Configure a TUN interface and return its file descriptor. Parameters
3539 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003540 * and not available in ConnectivityManager. Permissions are checked in
3541 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003542 * @hide
3543 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003544 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003545 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003546 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003547 int user = UserHandle.getUserId(Binder.getCallingUid());
3548 synchronized(mVpns) {
3549 return mVpns.get(user).establish(config);
3550 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003551 }
3552
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003553 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003554 * Start legacy VPN, controlling native daemons as needed. Creates a
3555 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003556 */
3557 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003558 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003559 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003560 final LinkProperties egress = getActiveLinkProperties();
3561 if (egress == null) {
3562 throw new IllegalStateException("Missing active network connection");
3563 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003564 int user = UserHandle.getUserId(Binder.getCallingUid());
3565 synchronized(mVpns) {
3566 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3567 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003568 }
3569
3570 /**
3571 * Return the information of the ongoing legacy VPN. This method is used
3572 * by VpnSettings and not available in ConnectivityManager. Permissions
3573 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003574 */
3575 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003576 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3577 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003578
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003579 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003580 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003581 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003582 }
3583
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003584 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003585 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3586 * and not available in ConnectivityManager.
3587 */
3588 @Override
3589 public VpnInfo[] getAllVpnInfo() {
3590 enforceConnectivityInternalPermission();
3591 if (mLockdownEnabled) {
3592 return new VpnInfo[0];
3593 }
3594
3595 synchronized(mVpns) {
3596 List<VpnInfo> infoList = new ArrayList<>();
3597 for (int i = 0; i < mVpns.size(); i++) {
3598 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3599 if (info != null) {
3600 infoList.add(info);
3601 }
3602 }
3603 return infoList.toArray(new VpnInfo[infoList.size()]);
3604 }
3605 }
3606
3607 /**
3608 * @return VPN information for accounting, or null if we can't retrieve all required
3609 * information, e.g primary underlying iface.
3610 */
3611 @Nullable
3612 private VpnInfo createVpnInfo(Vpn vpn) {
3613 VpnInfo info = vpn.getVpnInfo();
3614 if (info == null) {
3615 return null;
3616 }
3617 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3618 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3619 // the underlyingNetworks list.
3620 if (underlyingNetworks == null) {
3621 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3622 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3623 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3624 }
3625 } else if (underlyingNetworks.length > 0) {
3626 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3627 if (linkProperties != null) {
3628 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3629 }
3630 }
3631 return info.primaryUnderlyingIface == null ? null : info;
3632 }
3633
3634 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003635 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3636 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003637 * Permissions are checked in Vpn class.
3638 * @hide
3639 */
3640 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003641 public VpnConfig getVpnConfig(int userId) {
3642 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003643 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003644 Vpn vpn = mVpns.get(userId);
3645 if (vpn != null) {
3646 return vpn.getVpnConfig();
3647 } else {
3648 return null;
3649 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003650 }
3651 }
3652
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003653 @Override
3654 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003655 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3656 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3657 return false;
3658 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003659
3660 // Tear down existing lockdown if profile was removed
3661 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3662 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003663 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3664 final VpnProfile profile = VpnProfile.decode(
3665 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003666 if (profile == null) {
3667 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3668 setLockdownTracker(null);
3669 return true;
3670 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003671 int user = UserHandle.getUserId(Binder.getCallingUid());
3672 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003673 Vpn vpn = mVpns.get(user);
3674 if (vpn == null) {
3675 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3676 return false;
3677 }
3678 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003679 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003680 } else {
3681 setLockdownTracker(null);
3682 }
3683
3684 return true;
3685 }
3686
3687 /**
3688 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3689 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3690 */
3691 private void setLockdownTracker(LockdownVpnTracker tracker) {
3692 // Shutdown any existing tracker
3693 final LockdownVpnTracker existing = mLockdownTracker;
3694 mLockdownTracker = null;
3695 if (existing != null) {
3696 existing.shutdown();
3697 }
3698
3699 try {
3700 if (tracker != null) {
3701 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003702 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003703 mLockdownTracker = tracker;
3704 mLockdownTracker.init();
3705 } else {
3706 mNetd.setFirewallEnabled(false);
3707 }
3708 } catch (RemoteException e) {
3709 // ignored; NMS lives inside system_server
3710 }
3711 }
3712
3713 private void throwIfLockdownEnabled() {
3714 if (mLockdownEnabled) {
3715 throw new IllegalStateException("Unavailable in lockdown mode");
3716 }
3717 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003718
Robin Lee244ce8e2016-01-05 18:03:46 +00003719 /**
Robin Lee17e61832016-05-09 13:46:28 +01003720 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3721 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003722 *
Robin Lee17e61832016-05-09 13:46:28 +01003723 * @return {@code true} if the service was started, the service was already connected, or there
3724 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003725 */
Robin Lee17e61832016-05-09 13:46:28 +01003726 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003727 synchronized (mVpns) {
3728 Vpn vpn = mVpns.get(userId);
3729 if (vpn == null) {
3730 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3731 // exists already.
3732 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3733 return false;
3734 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003735
Robin Lee812800c2016-05-13 15:38:08 +01003736 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003737 }
3738 }
3739
3740 @Override
Robin Leedc679712016-05-03 13:23:03 +01003741 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003742 enforceConnectivityInternalPermission();
3743 enforceCrossUserPermission(userId);
3744
3745 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3746 if (LockdownVpnTracker.isEnabled()) {
3747 return false;
3748 }
3749
Robin Lee244ce8e2016-01-05 18:03:46 +00003750 synchronized (mVpns) {
3751 Vpn vpn = mVpns.get(userId);
3752 if (vpn == null) {
3753 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3754 return false;
3755 }
Robin Lee17e61832016-05-09 13:46:28 +01003756 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003757 return false;
3758 }
Robin Lee17e61832016-05-09 13:46:28 +01003759 if (!startAlwaysOnVpn(userId)) {
3760 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003761 return false;
3762 }
Robin Lee17e61832016-05-09 13:46:28 +01003763
Robin Lee812800c2016-05-13 15:38:08 +01003764 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003765 }
3766 return true;
3767 }
3768
3769 @Override
3770 public String getAlwaysOnVpnPackage(int userId) {
3771 enforceConnectivityInternalPermission();
3772 enforceCrossUserPermission(userId);
3773
3774 synchronized (mVpns) {
3775 Vpn vpn = mVpns.get(userId);
3776 if (vpn == null) {
3777 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3778 return null;
3779 }
3780 return vpn.getAlwaysOnPackage();
3781 }
3782 }
3783
Wink Savilleab9321d2013-06-29 21:10:57 -07003784 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003785 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003786 // TODO: Remove? Any reason to trigger a provisioning check?
3787 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003788 }
3789
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003790 /** Location to an updatable file listing carrier provisioning urls.
3791 * An example:
3792 *
3793 * <?xml version="1.0" encoding="utf-8"?>
3794 * <provisioningUrls>
3795 * <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 -07003796 * </provisioningUrls>
3797 */
3798 private static final String PROVISIONING_URL_PATH =
3799 "/data/misc/radio/provisioning_urls.xml";
3800 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003801
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003802 /** XML tag for root element. */
3803 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3804 /** XML tag for individual url */
3805 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003806 /** XML attribute for mcc */
3807 private static final String ATTR_MCC = "mcc";
3808 /** XML attribute for mnc */
3809 private static final String ATTR_MNC = "mnc";
3810
Paul Jensen434dde82015-06-11 09:43:30 -04003811 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003812 FileReader fileReader = null;
3813 XmlPullParser parser = null;
3814 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003815
3816 try {
3817 fileReader = new FileReader(mProvisioningUrlFile);
3818 parser = Xml.newPullParser();
3819 parser.setInput(fileReader);
3820 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3821
3822 while (true) {
3823 XmlUtils.nextElement(parser);
3824
3825 String element = parser.getName();
3826 if (element == null) break;
3827
Paul Jensen434dde82015-06-11 09:43:30 -04003828 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003829 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3830 try {
3831 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3832 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3833 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3834 parser.next();
3835 if (parser.getEventType() == XmlPullParser.TEXT) {
3836 return parser.getText();
3837 }
3838 }
3839 }
3840 } catch (NumberFormatException e) {
3841 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3842 }
3843 }
3844 }
3845 return null;
3846 } catch (FileNotFoundException e) {
3847 loge("Carrier Provisioning Urls file not found");
3848 } catch (XmlPullParserException e) {
3849 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3850 } catch (IOException e) {
3851 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3852 } finally {
3853 if (fileReader != null) {
3854 try {
3855 fileReader.close();
3856 } catch (IOException e) {}
3857 }
3858 }
3859 return null;
3860 }
3861
Wink Saville42d4f082013-07-20 20:31:59 -07003862 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003863 public String getMobileProvisioningUrl() {
3864 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003865 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003866 if (TextUtils.isEmpty(url)) {
3867 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003868 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003869 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003870 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003871 }
Wink Saville8cf35602013-07-10 23:00:07 -07003872 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003873 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003874 String phoneNumber = mTelephonyManager.getLine1Number();
3875 if (TextUtils.isEmpty(phoneNumber)) {
3876 phoneNumber = "0000000000";
3877 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003878 url = String.format(url,
3879 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3880 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003881 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003882 }
3883
Wink Savilleab9321d2013-06-29 21:10:57 -07003884 return url;
3885 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003886
Wink Saville948282b2013-08-29 08:55:16 -07003887 @Override
3888 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003889 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003890 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003891 final long ident = Binder.clearCallingIdentity();
3892 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003893 // Concatenate the range of types onto the range of NetIDs.
3894 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3895 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003896 } finally {
3897 Binder.restoreCallingIdentity(ident);
3898 }
Wink Saville948282b2013-08-29 08:55:16 -07003899 }
Wink Saville7788c612013-08-29 14:57:08 -07003900
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003901 @Override
3902 public void setAirplaneMode(boolean enable) {
3903 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003904 final long ident = Binder.clearCallingIdentity();
3905 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003906 final ContentResolver cr = mContext.getContentResolver();
3907 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3908 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3909 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003910 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003911 } finally {
3912 Binder.restoreCallingIdentity(ident);
3913 }
3914 }
3915
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003916 private void onUserStart(int userId) {
3917 synchronized(mVpns) {
3918 Vpn userVpn = mVpns.get(userId);
3919 if (userVpn != null) {
3920 loge("Starting user already has a VPN");
3921 return;
3922 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003923 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003924 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003925
3926 final ContentResolver cr = mContext.getContentResolver();
3927 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3928 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3929 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3930 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3931 if (alwaysOnPackage != null) {
3932 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3933 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003934 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003935 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3936 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003937 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003938 }
3939
3940 private void onUserStop(int userId) {
3941 synchronized(mVpns) {
3942 Vpn userVpn = mVpns.get(userId);
3943 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003944 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003945 return;
3946 }
Robin Lee17e61832016-05-09 13:46:28 +01003947 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003948 mVpns.delete(userId);
3949 }
3950 }
3951
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003952 private void onUserAdded(int userId) {
3953 synchronized(mVpns) {
3954 final int vpnsSize = mVpns.size();
3955 for (int i = 0; i < vpnsSize; i++) {
3956 Vpn vpn = mVpns.valueAt(i);
3957 vpn.onUserAdded(userId);
3958 }
3959 }
3960 }
3961
3962 private void onUserRemoved(int userId) {
3963 synchronized(mVpns) {
3964 final int vpnsSize = mVpns.size();
3965 for (int i = 0; i < vpnsSize; i++) {
3966 Vpn vpn = mVpns.valueAt(i);
3967 vpn.onUserRemoved(userId);
3968 }
3969 }
3970 }
3971
Robin Lee89e7a692016-02-29 14:38:17 +00003972 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003973 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3974 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3975 updateLockdownVpn();
3976 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003977 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003978 }
3979 }
3980
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003981 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3982 @Override
3983 public void onReceive(Context context, Intent intent) {
3984 final String action = intent.getAction();
3985 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3986 if (userId == UserHandle.USER_NULL) return;
3987
Robin Lee323f29d2016-05-04 16:38:06 +01003988 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003989 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003990 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003991 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003992 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3993 onUserAdded(userId);
3994 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3995 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003996 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3997 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003998 }
3999 }
4000 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004001
Robert Greenwalta67be032014-05-16 15:49:14 -07004002 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4003 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004004 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4005 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004006
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004007 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4008 // Map from UID to number of NetworkRequests that UID has filed.
4009 @GuardedBy("mUidToNetworkRequestCount")
4010 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4011
Robert Greenwalta67be032014-05-16 15:49:14 -07004012 private static class NetworkFactoryInfo {
4013 public final String name;
4014 public final Messenger messenger;
4015 public final AsyncChannel asyncChannel;
4016
4017 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4018 this.name = name;
4019 this.messenger = messenger;
4020 this.asyncChannel = asyncChannel;
4021 }
4022 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004024 private void ensureNetworkRequestHasType(NetworkRequest request) {
4025 if (request.type == NetworkRequest.Type.NONE) {
4026 throw new IllegalArgumentException(
4027 "All NetworkRequests in ConnectivityService must have a type");
4028 }
4029 }
4030
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004031 /**
4032 * Tracks info about the requester.
4033 * Also used to notice when the calling process dies so we can self-expire
4034 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004035 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004036 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004037 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004038 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004039 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004040 final int mPid;
4041 final int mUid;
4042 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004043
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004044 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004045 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004046 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004047 mPendingIntent = pi;
4048 messenger = null;
4049 mBinder = null;
4050 mPid = getCallingPid();
4051 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004052 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004053 }
4054
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004055 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004056 super();
4057 messenger = m;
4058 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004059 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 mBinder = binder;
4061 mPid = getCallingPid();
4062 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004063 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004064 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004065
4066 try {
4067 mBinder.linkToDeath(this, 0);
4068 } catch (RemoteException e) {
4069 binderDied();
4070 }
4071 }
4072
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004073 private void enforceRequestCountLimit() {
4074 synchronized (mUidToNetworkRequestCount) {
4075 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4076 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4077 throw new IllegalArgumentException("Too many NetworkRequests filed");
4078 }
4079 mUidToNetworkRequestCount.put(mUid, networkRequests);
4080 }
4081 }
4082
Robert Greenwalt9258c642014-03-26 16:47:06 -07004083 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004084 if (mBinder != null) {
4085 mBinder.unlinkToDeath(this, 0);
4086 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004087 }
4088
4089 public void binderDied() {
4090 log("ConnectivityService NetworkRequestInfo binderDied(" +
4091 request + ", " + mBinder + ")");
4092 releaseNetworkRequest(request);
4093 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004094
4095 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004096 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004097 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004098 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004099 }
4100
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004101 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4102 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4103 if (badCapability != null) {
4104 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004105 }
4106 }
4107
Erik Kline9d598e12015-07-13 16:37:51 +09004108 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004109 final SortedSet<Integer> thresholds = new TreeSet();
4110 synchronized (nai) {
4111 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4112 if (nri.request.networkCapabilities.hasSignalStrength() &&
4113 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4114 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4115 }
4116 }
4117 }
Erik Kline9d598e12015-07-13 16:37:51 +09004118 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004119 }
4120
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004121 private void updateSignalStrengthThresholds(
4122 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4123 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004124 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004125 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4126
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004127 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004128 String detail;
4129 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4130 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4131 } else {
4132 detail = reason;
4133 }
4134 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4135 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4136 }
4137
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004138 nai.asyncChannel.sendMessage(
4139 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004140 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004141 }
4142
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 @Override
4144 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004145 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004146 final NetworkRequest.Type type = (networkCapabilities == null)
4147 ? NetworkRequest.Type.TRACK_DEFAULT
4148 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004149 // If the requested networkCapabilities is null, take them instead from
4150 // the default network request. This allows callers to keep track of
4151 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004152 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004153 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4154 enforceAccessPermission();
4155 } else {
4156 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4157 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004158 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4159 // of the app when the request is filed, but we never change the request if the app
4160 // changes network state. http://b/29964605
4161 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004162 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004163 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004164
Robert Greenwalt6078b502014-06-11 16:05:07 -07004165 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004166 throw new IllegalArgumentException("Bad timeout specified");
4167 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004168
Etan Cohenddb9ef02015-11-18 10:56:15 -08004169 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4170 .equals(networkCapabilities.getNetworkSpecifier())) {
4171 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4172 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4173 }
4174
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004175 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004176 nextNetworkRequestId(), type);
4177 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004178 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004179
4180 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004181 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004182 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004183 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004184 }
4185 return networkRequest;
4186 }
4187
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004188 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004189 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004190 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004191 } else {
4192 enforceChangePermission();
4193 }
4194 }
4195
fenglub15e72b2015-03-20 11:29:56 -07004196 @Override
fengludb571472015-04-21 17:12:05 -07004197 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004198 enforceAccessPermission();
4199 NetworkAgentInfo nai = null;
4200 if (network == null) {
4201 return false;
4202 }
4203 synchronized (mNetworkForNetId) {
4204 nai = mNetworkForNetId.get(network.netId);
4205 }
4206 if (nai != null) {
4207 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4208 return true;
4209 }
4210 return false;
4211 }
4212
Felipe Lemeee27cab2016-06-20 16:36:29 -07004213 private boolean isSystem(int uid) {
4214 return uid < Process.FIRST_APPLICATION_UID;
4215 }
fenglub15e72b2015-03-20 11:29:56 -07004216
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004217 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004218 final int uid = Binder.getCallingUid();
4219 if (isSystem(uid)) {
4220 return;
4221 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004222 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004223 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004224 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004225 synchronized(mRulesLock) {
4226 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4227 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004228 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4229 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004230 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004231 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004232 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004233 }
4234 }
4235 }
4236
Robert Greenwalt9258c642014-03-26 16:47:06 -07004237 @Override
4238 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4239 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004240 checkNotNull(operation, "PendingIntent cannot be null.");
4241 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4242 enforceNetworkRequestPermissions(networkCapabilities);
4243 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004244 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004245
4246 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004247 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4248 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004249 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004250 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4251 nri));
4252 return networkRequest;
4253 }
4254
Jeremy Joslin79294842014-12-03 17:15:28 -08004255 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4256 mHandler.sendMessageDelayed(
4257 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4258 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4259 }
4260
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004261 @Override
4262 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004263 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004264 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4265 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004266 }
4267
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004268 // In order to implement the compatibility measure for pre-M apps that call
4269 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4270 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4271 // This ensures it has permission to do so.
4272 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4273 if (nc == null) {
4274 return false;
4275 }
4276 int[] transportTypes = nc.getTransportTypes();
4277 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4278 return false;
4279 }
4280 try {
4281 mContext.enforceCallingOrSelfPermission(
4282 android.Manifest.permission.ACCESS_WIFI_STATE,
4283 "ConnectivityService");
4284 } catch (SecurityException e) {
4285 return false;
4286 }
4287 return true;
4288 }
4289
Robert Greenwalt9258c642014-03-26 16:47:06 -07004290 @Override
4291 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4292 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004293 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4294 enforceAccessPermission();
4295 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004296
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004297 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4298 if (!ConnectivityManager.checkChangePermission(mContext)) {
4299 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4300 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4301 // onLost and onAvailable callbacks when networks move in and out of the background.
4302 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4303 // can't request networks.
4304 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4305 }
4306
4307 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004308 NetworkRequest.Type.LISTEN);
4309 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004310 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004311
4312 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4313 return networkRequest;
4314 }
4315
4316 @Override
4317 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4318 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004319 checkNotNull(operation, "PendingIntent cannot be null.");
4320 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4321 enforceAccessPermission();
4322 }
4323
Erik Kline7523eb32015-07-09 18:24:03 +09004324 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004325 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4326 NetworkRequest.Type.LISTEN);
4327 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004328 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004329
4330 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004331 }
4332
4333 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004334 public void requestLinkProperties(NetworkRequest networkRequest) {
4335 ensureNetworkRequestHasType(networkRequest);
4336 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4337 mHandler.sendMessage(mHandler.obtainMessage(
4338 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4339 }
4340
4341 @Override
4342 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4343 ensureNetworkRequestHasType(networkRequest);
4344 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4345 mHandler.sendMessage(mHandler.obtainMessage(
4346 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4347 }
4348
4349 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004350 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004351 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004352 mHandler.sendMessage(mHandler.obtainMessage(
4353 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004354 }
4355
4356 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004357 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004358 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004359 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4360 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004361 }
4362
Robert Greenwalta67be032014-05-16 15:49:14 -07004363 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004364 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004365 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4366 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4367 }
4368
4369 @Override
4370 public void unregisterNetworkFactory(Messenger messenger) {
4371 enforceConnectivityInternalPermission();
4372 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4373 }
4374
4375 private void handleUnregisterNetworkFactory(Messenger messenger) {
4376 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4377 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004378 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004379 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004380 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004381 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004382 }
4383
Robert Greenwalt7b816022014-04-18 15:25:25 -07004384 /**
4385 * NetworkAgentInfo supporting a request by requestId.
4386 * These have already been vetted (their Capabilities satisfy the request)
4387 * and the are the highest scored network available.
4388 * the are keyed off the Requests requestId.
4389 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004390 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004391 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4392 new SparseArray<NetworkAgentInfo>();
4393
Paul Jensen31a94f42015-02-13 14:18:39 -05004394 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4395 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004396 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4397 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004398 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4399 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4400 // there may not be a strict 1:1 correlation between the two.
4401 @GuardedBy("mNetworkForNetId")
4402 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004403
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 // NetworkAgentInfo keyed off its connecting messenger
4405 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004406 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004407 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4408 new HashMap<Messenger, NetworkAgentInfo>();
4409
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004410 @GuardedBy("mBlockedAppUids")
4411 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4412
Paul Jensen2c311d62014-11-17 12:34:51 -05004413 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004414 private final NetworkRequest mDefaultRequest;
4415
Erik Klineda4bfa82015-04-30 12:58:40 +09004416 // Request used to optionally keep mobile data active even when higher
4417 // priority networks like Wi-Fi are active.
4418 private final NetworkRequest mDefaultMobileDataRequest;
4419
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004420 private NetworkAgentInfo getDefaultNetwork() {
4421 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4422 }
4423
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004424 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004425 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004426 }
4427
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004428 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4429 return nri.request.requestId == mDefaultRequest.requestId;
4430 }
4431
Paul Jensen31a94f42015-02-13 14:18:39 -05004432 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004433 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004434 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004435 enforceConnectivityInternalPermission();
4436
Paul Jensen2c311d62014-11-17 12:34:51 -05004437 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4438 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004439 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004440 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4441 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004442 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004443 synchronized (this) {
4444 nai.networkMonitor.systemReady = mSystemReady;
4445 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004446 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4447 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004448 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004449 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004450 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004451 }
4452
4453 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4454 if (VDBG) log("Got NetworkAgent Messenger");
4455 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004456 synchronized (mNetworkForNetId) {
4457 mNetworkForNetId.put(na.network.netId, na);
4458 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004459 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4460 NetworkInfo networkInfo = na.networkInfo;
4461 na.networkInfo = null;
4462 updateNetworkInfo(na, networkInfo);
4463 }
4464
4465 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4466 LinkProperties newLp = networkAgent.linkProperties;
4467 int netId = networkAgent.network.netId;
4468
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004469 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4470 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004471 if (networkAgent.clatd != null) {
4472 networkAgent.clatd.fixupLinkProperties(oldLp);
4473 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004474
Paul Jensen992f2522014-04-28 10:33:11 -04004475 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 updateMtu(newLp, oldLp);
4477 // TODO - figure out what to do for clat
4478// for (LinkProperties lp : newLp.getStackedLinks()) {
4479// updateMtu(lp, null);
4480// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004481 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004482
Erik Kline94887872016-04-05 13:30:49 +09004483 updateRoutes(newLp, oldLp, netId);
4484 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004485
Paul Jensen3b759822014-05-13 11:44:01 -04004486 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004487 if (isDefaultNetwork(networkAgent)) {
4488 handleApplyDefaultProxy(newLp.getHttpProxy());
4489 } else {
4490 updateProxy(newLp, oldLp, networkAgent);
4491 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004492 // TODO - move this check to cover the whole function
4493 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004494 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004495 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4496 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004497
4498 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004499 }
4500
Lorenzo Colitti95439462014-10-09 13:44:48 +09004501 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4502 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4503 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004504
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004505 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004506 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4507 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004508 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004509 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004510 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004511 }
Paul Jensen992f2522014-04-28 10:33:11 -04004512
4513 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4514 CompareResult<String> interfaceDiff = new CompareResult<String>();
4515 if (oldLp != null) {
4516 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4517 } else if (newLp != null) {
4518 interfaceDiff.added = newLp.getAllInterfaceNames();
4519 }
4520 for (String iface : interfaceDiff.added) {
4521 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004522 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004523 mNetd.addInterfaceToNetwork(iface, netId);
4524 } catch (Exception e) {
4525 loge("Exception adding interface: " + e);
4526 }
4527 }
4528 for (String iface : interfaceDiff.removed) {
4529 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004530 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004531 mNetd.removeInterfaceFromNetwork(iface, netId);
4532 } catch (Exception e) {
4533 loge("Exception removing interface: " + e);
4534 }
4535 }
4536 }
4537
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004538 /**
4539 * Have netd update routes from oldLp to newLp.
4540 * @return true if routes changed between oldLp and newLp
4541 */
4542 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4544 if (oldLp != null) {
4545 routeDiff = oldLp.compareAllRoutes(newLp);
4546 } else if (newLp != null) {
4547 routeDiff.added = newLp.getAllRoutes();
4548 }
4549
4550 // add routes before removing old in case it helps with continuous connectivity
4551
4552 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4553 for (RouteInfo route : routeDiff.added) {
4554 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004555 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 try {
4557 mNetd.addRoute(netId, route);
4558 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004559 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4560 loge("Exception in addRoute for non-gateway: " + e);
4561 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004562 }
4563 }
4564 for (RouteInfo route : routeDiff.added) {
4565 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004566 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 try {
4568 mNetd.addRoute(netId, route);
4569 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004570 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4571 loge("Exception in addRoute for gateway: " + e);
4572 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004573 }
4574 }
4575
4576 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004577 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004578 try {
4579 mNetd.removeRoute(netId, route);
4580 } catch (Exception e) {
4581 loge("Exception in removeRoute: " + e);
4582 }
4583 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004584 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004585 }
Erik Kline41368502015-06-17 13:19:54 +09004586
Erik Kline94887872016-04-05 13:30:49 +09004587 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4588 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4589 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004590 }
Erik Kline94887872016-04-05 13:30:49 +09004591
4592 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004593 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004594 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004595 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004596 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4597 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004598 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004599 }
Erik Kline94887872016-04-05 13:30:49 +09004600 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004601 }
4602
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004603 private String getNetworkPermission(NetworkCapabilities nc) {
4604 // TODO: make these permission strings AIDL constants instead.
4605 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4606 return NetworkManagementService.PERMISSION_SYSTEM;
4607 }
4608 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4609 return NetworkManagementService.PERMISSION_NETWORK;
4610 }
4611 return null;
4612 }
4613
Paul Jensen3d194ea2015-06-16 14:27:36 -04004614 /**
4615 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4616 * augmented with any stateful capabilities implied from {@code networkAgent}
4617 * (e.g., validated status and captive portal status).
4618 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004619 * @param oldScore score of the network before any of the changes that prompted us
4620 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004621 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004622 * @param networkCapabilities the new network capabilities.
4623 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004624 private void updateCapabilities(
4625 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004626 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4627 networkCapabilities)) {
4628 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4629 + nai.networkCapabilities + " -> " + networkCapabilities);
4630 }
4631
Paul Jensen3d194ea2015-06-16 14:27:36 -04004632 // Don't modify caller's NetworkCapabilities.
4633 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004634 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004635 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4636 } else {
4637 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4638 }
Paul Jensene0988542015-06-25 15:30:08 -04004639 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004640 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4641 } else {
4642 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4643 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004644 if (nai.isBackgroundNetwork()) {
4645 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4646 } else {
4647 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4648 }
4649
4650 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4651
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004652 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4653 final String newPermission = getNetworkPermission(networkCapabilities);
4654 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004655 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004656 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004657 } catch (RemoteException e) {
4658 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004659 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004660 }
4661
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004662 final NetworkCapabilities prevNc = nai.networkCapabilities;
4663 synchronized (nai) {
4664 nai.networkCapabilities = networkCapabilities;
4665 }
4666 if (nai.getCurrentScore() == oldScore &&
4667 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4668 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4669 // the change we're processing can't affect any requests, it can only affect the listens
4670 // on this network. We might have been called by rematchNetworkAndRequests when a
4671 // network changed foreground state.
4672 processListenRequests(nai, true);
4673 } else {
4674 // If the requestable capabilities have changed or the score changed, we can't have been
4675 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004676 rematchAllNetworksAndRequests(nai, oldScore);
4677 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004678 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004679 }
4680
Paul Jensenc8b9a742014-09-30 15:37:41 -04004681 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004682 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4683 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004684 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004685 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004686 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4687 }
4688 }
4689
Robert Greenwalt7b816022014-04-18 15:25:25 -07004690 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4691 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004692 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004693 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4694 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004695 }
4696 }
4697
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004698 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4699 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004700 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004701 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004702 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4703 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004704 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004705 sendIntent(nri.mPendingIntent, intent);
4706 }
4707 // else not handled
4708 }
4709
4710 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4711 mPendingIntentWakeLock.acquire();
4712 try {
4713 if (DBG) log("Sending " + pendingIntent);
4714 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4715 } catch (PendingIntent.CanceledException e) {
4716 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4717 mPendingIntentWakeLock.release();
4718 releasePendingNetworkRequest(pendingIntent);
4719 }
4720 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4721 }
4722
4723 @Override
4724 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4725 String resultData, Bundle resultExtras) {
4726 if (DBG) log("Finished sending " + pendingIntent);
4727 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004728 // Release with a delay so the receiving client has an opportunity to put in its
4729 // own request.
4730 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004731 }
4732
Robert Greenwalt9258c642014-03-26 16:47:06 -07004733 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004734 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004735 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004736 Bundle bundle = new Bundle();
4737 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4738 new NetworkRequest(nri.request));
4739 Message msg = Message.obtain();
4740 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4741 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4742 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4743 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004744 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004745 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004746 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004747 break;
4748 }
4749 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4750 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4751 new NetworkCapabilities(networkAgent.networkCapabilities));
4752 break;
4753 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004754 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004755 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4756 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004757 break;
4758 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004759 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004760 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004761 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004762 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004763 if (VDBG) {
4764 log("sending notification " + notifyTypeToName(notificationType) +
4765 " for " + nri.request);
4766 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004767 nri.messenger.send(msg);
4768 } catch (RemoteException e) {
4769 // may occur naturally in the race of binder death.
4770 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4771 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004772 }
4773
Paul Jensenc8b9a742014-09-30 15:37:41 -04004774 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004775 if (nai.numRequestNetworkRequests() != 0) {
4776 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4777 NetworkRequest nr = nai.requestAt(i);
4778 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004779 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004780 loge("Dead network still had at least " + nr);
4781 break;
4782 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004783 }
4784 nai.asyncChannel.disconnect();
4785 }
4786
Robert Greenwalt7b816022014-04-18 15:25:25 -07004787 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4788 if (oldNetwork == null) {
4789 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4790 return;
4791 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004792 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004793
4794 // If we get here it means that the last linger timeout for this network expired. So there
4795 // must be no other active linger timers, and we must stop lingering.
4796 oldNetwork.clearLingerState();
4797
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004798 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004799 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004800 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004801 } else {
4802 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004803 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4804 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004805 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004806 }
4807
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004808 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004809 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004810 setupDataActivityTracking(newNetwork);
4811 try {
4812 mNetd.setDefaultNetId(newNetwork.network.netId);
4813 } catch (Exception e) {
4814 loge("Exception setting default network :" + e);
4815 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004816 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004817 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004818 updateTcpBufferSizes(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004819 }
4820
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004821 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004822 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4823 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4824 NetworkRequest nr = nri.request;
4825 if (!nr.isListen()) continue;
4826 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4827 nai.removeRequest(nri.request.requestId);
4828 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4829 }
4830 }
4831
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004832 if (capabilitiesChanged) {
4833 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4834 }
4835
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004836 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4837 NetworkRequest nr = nri.request;
4838 if (!nr.isListen()) continue;
4839 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4840 nai.addRequest(nr);
4841 notifyNetworkCallback(nai, nri);
4842 }
4843 }
4844 }
4845
Paul Jensen2161a8e2014-09-11 11:00:39 -04004846 // Handles a network appearing or improving its score.
4847 //
4848 // - Evaluates all current NetworkRequests that can be
4849 // satisfied by newNetwork, and reassigns to newNetwork
4850 // any such requests for which newNetwork is the best.
4851 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004852 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004853 // needed. A network is needed if it is the best network for
4854 // one or more NetworkRequests, or if it is a VPN.
4855 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004856 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004857 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004858 //
4859 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4860 // networks that have no chance (i.e. even if validated)
4861 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004862 //
4863 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4864 // it does not remove NetworkRequests that other Networks could better satisfy.
4865 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4866 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4867 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004868 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004869 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004870 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4871 // performed to tear down unvalidated networks that have no chance (i.e. even if
4872 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004873 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004874 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004875 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004876 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004877 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004878 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004879
4880 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4881 final int score = newNetwork.getCurrentScore();
4882
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004883 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004884
Paul Jensen2161a8e2014-09-11 11:00:39 -04004885 // Find and migrate to this Network any NetworkRequests for
4886 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004887 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004888 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004889 NetworkCapabilities nc = newNetwork.networkCapabilities;
4890 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004891 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004892 // Process requests in the first pass and listens in the second pass. This allows us to
4893 // change a network's capabilities depending on which requests it has. This is only
4894 // correct if the change in capabilities doesn't affect whether the network satisfies
4895 // requests or not, and doesn't affect the network's score.
4896 if (nri.request.isListen()) continue;
4897
Paul Jensencf4c2c62015-07-01 14:16:32 -04004898 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4899 final boolean satisfies = newNetwork.satisfies(nri.request);
4900 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004901 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004902 log("Network " + newNetwork.name() + " was already satisfying" +
4903 " request " + nri.request.requestId + ". No change.");
4904 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004905 keep = true;
4906 continue;
4907 }
4908
4909 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004910 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004911 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004912 // next check if it's better than any current network we're using for
4913 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004914 if (VDBG) {
4915 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004916 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004917 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004918 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004919 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004920 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004921 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004922 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004923 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004924 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004925 affectedNetworks.add(currentNetwork);
4926 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004927 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004928 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004929 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004930 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004931 if (!newNetwork.addRequest(nri.request)) {
4932 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4933 }
4934 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004935 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004936 // Tell NetworkFactories about the new score, so they can stop
4937 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004938 // TODO - this could get expensive if we have alot of requests for this
4939 // network. Think about if there is a way to reduce this. Push
4940 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004941 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004942 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004943 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004944 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004945 if (currentNetwork != null) {
4946 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4947 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004948 }
4949 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004950 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004951 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4952 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004953 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004954 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4955 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4956 // This means this code doesn't have to handle the case where "currentNetwork" no
4957 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4958 if (DBG) {
4959 log("Network " + newNetwork.name() + " stopped satisfying" +
4960 " request " + nri.request.requestId);
4961 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004962 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004963 if (currentNetwork == newNetwork) {
4964 mNetworkForRequestId.remove(nri.request.requestId);
4965 sendUpdatedScoreToFactories(nri.request, 0);
4966 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004967 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4968 newNetwork.name() +
4969 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004970 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004971 // TODO: Technically, sending CALLBACK_LOST here is
4972 // incorrect if there is a replacement network currently
4973 // connected that can satisfy nri, which is a request
4974 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004975 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4976 // so this code is only incorrect for a network that loses
4977 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004978 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004979 }
4980 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004981 if (isNewDefault) {
4982 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004983 makeDefault(newNetwork);
4984 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4985 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004986 synchronized (ConnectivityService.this) {
4987 // have a new default network, release the transition wakelock in
4988 // a second if it's held. The second pause is to allow apps
4989 // to reconnect over the new network
4990 if (mNetTransitionWakeLock.isHeld()) {
4991 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4992 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4993 mNetTransitionWakeLockSerialNumber, 0),
4994 1000);
4995 }
4996 }
4997 }
4998
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004999 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5000 Slog.wtf(TAG, String.format(
5001 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
5002 nc, newNetwork.networkCapabilities));
5003 }
5004 if (newNetwork.getCurrentScore() != score) {
5005 Slog.wtf(TAG, String.format(
5006 "BUG: %s changed score during rematch: %d -> %d",
5007 score, newNetwork.getCurrentScore()));
5008 }
5009
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005010 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005011 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5012 // If the network went from background to foreground or vice versa, we need to update
5013 // its foreground state. It is safe to do this after rematching the requests because
5014 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5015 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005016 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005017 } else {
5018 processListenRequests(newNetwork, false);
5019 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005020
Paul Jensencf4c2c62015-07-01 14:16:32 -04005021 // do this after the default net is switched, but
5022 // before LegacyTypeTracker sends legacy broadcasts
5023 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
5024
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005025 // Linger any networks that are no longer needed. This should be done after sending the
5026 // available callback for newNetwork.
5027 for (NetworkAgentInfo nai : affectedNetworks) {
5028 updateLingerState(nai, now);
5029 }
5030 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5031 // does not need to be done in any particular order.
5032 updateLingerState(newNetwork, now);
5033
Paul Jensencf4c2c62015-07-01 14:16:32 -04005034 if (isNewDefault) {
5035 // Maintain the illusion: since the legacy API only
5036 // understands one network at a time, we must pretend
5037 // that the current default network disconnected before
5038 // the new one connected.
5039 if (oldDefaultNetwork != null) {
5040 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5041 oldDefaultNetwork, true);
5042 }
5043 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5044 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5045 notifyLockdownVpn(newNetwork);
5046 }
5047
Robert Greenwalt7b816022014-04-18 15:25:25 -07005048 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005049 // Notify battery stats service about this network, both the normal
5050 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005051 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005052 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005053 final IBatteryStats bs = BatteryStatsService.getService();
5054 final int type = newNetwork.networkInfo.getType();
5055
5056 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5057 bs.noteNetworkInterfaceType(baseIface, type);
5058 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5059 final String stackedIface = stacked.getInterfaceName();
5060 bs.noteNetworkInterfaceType(stackedIface, type);
5061 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5062 }
5063 } catch (RemoteException ignored) {
5064 }
5065
Robert Greenwalt152ed372014-12-17 17:19:53 -08005066 // This has to happen after the notifyNetworkCallbacks as that tickles each
5067 // ConnectivityManager instance so that legacy requests correctly bind dns
5068 // requests to this network. The legacy users are listening for this bcast
5069 // and will generally do a dns request so they can ensureRouteToHost and if
5070 // they do that before the callbacks happen they'll use the default network.
5071 //
5072 // TODO: Is there still a race here? We send the broadcast
5073 // after sending the callback, but if the app can receive the
5074 // broadcast before the callback, it might still break.
5075 //
5076 // This *does* introduce a race where if the user uses the new api
5077 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5078 // they may get old info. Reverse this after the old startUsing api is removed.
5079 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005080 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5081 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005082 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005083 // legacy type tracker filters out repeat adds
5084 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5085 }
5086 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005087
5088 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5089 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5090 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5091 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5092 if (newNetwork.isVPN()) {
5093 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5094 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005095 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005096 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5097 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005098 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005099 if (nai.getLingerExpiry() > 0) {
5100 // This network has active linger timers and no requests, but is not
5101 // lingering. Linger it.
5102 //
5103 // One way (the only way?) this can happen if this network is unvalidated
5104 // and became unneeded due to another network improving its score to the
5105 // point where this network will no longer be able to satisfy any requests
5106 // even if it validates.
5107 updateLingerState(nai, now);
5108 } else {
5109 if (DBG) log("Reaping " + nai.name());
5110 teardownUnneededNetwork(nai);
5111 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005112 }
5113 }
5114 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115 }
5116
Paul Jensen1c7ba022015-06-16 14:27:36 -04005117 /**
5118 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5119 * being disconnected.
5120 * @param changed If only one Network's score or capabilities have been modified since the last
5121 * time this function was called, pass this Network in this argument, otherwise pass
5122 * null.
5123 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5124 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5125 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5126 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5127 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005128 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005129 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005130 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5131 // to avoid the slowness. It is not simply enough to process just "changed", for
5132 // example in the case where "changed"'s score decreases and another network should begin
5133 // satifying a NetworkRequest that "changed" currently satisfies.
5134
5135 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5136 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5137 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005138 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005139 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005140 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005141 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005142 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5143 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5144 // Rematch higher scoring networks first to prevent requests first matching a lower
5145 // scoring network and then a higher scoring network, which could produce multiple
5146 // callbacks and inadvertently unlinger networks.
5147 Arrays.sort(nais);
5148 for (NetworkAgentInfo nai : nais) {
5149 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005150 // Only reap the last time through the loop. Reaping before all rematching
5151 // is complete could incorrectly teardown a network that hasn't yet been
5152 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005153 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005154 : ReapUnvalidatedNetworks.REAP,
5155 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005156 }
5157 }
5158 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005159
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005160 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005161 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005162 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005163 // For now only update icons for default connection.
5164 // TODO: Update WiFi and cellular icons separately. b/17237507
5165 if (!isDefaultNetwork(nai)) return;
5166
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005167 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005168 // Don't repeat publish.
5169 if (newInetCondition == mDefaultInetConditionPublished) return;
5170
5171 mDefaultInetConditionPublished = newInetCondition;
5172 sendInetConditionBroadcast(nai.networkInfo);
5173 }
5174
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005175 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5176 if (mLockdownTracker != null) {
5177 if (nai != null && nai.isVPN()) {
5178 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5179 } else {
5180 mLockdownTracker.onNetworkInfoChanged();
5181 }
5182 }
5183 }
5184
Robert Greenwalt7b816022014-04-18 15:25:25 -07005185 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5186 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005187 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005188 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005189 synchronized (networkAgent) {
5190 oldInfo = networkAgent.networkInfo;
5191 networkAgent.networkInfo = newInfo;
5192 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005193 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005194
5195 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005196 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5197 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5198 notifyIfacesChangedForNetworkStats();
5199 } else if (VDBG) log("ignoring duplicate network state non-change");
5200 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005201 return;
5202 }
5203 if (DBG) {
5204 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5205 (oldInfo == null ? "null" : oldInfo.getState()) +
5206 " to " + state);
5207 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005208
Robin Lee585e2482016-05-01 23:00:00 +01005209 if (!networkAgent.created
5210 && (state == NetworkInfo.State.CONNECTED
5211 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005212
5213 // A network that has just connected has zero requests and is thus a foreground network.
5214 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5215
Robert Greenwalt7b816022014-04-18 15:25:25 -07005216 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005217 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005218 if (networkAgent.isVPN()) {
5219 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005220 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5221 (networkAgent.networkMisc == null ||
5222 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005223 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005224 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005225 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005226 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005227 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005228 loge("Error creating network " + networkAgent.network.netId + ": "
5229 + e.getMessage());
5230 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005231 }
Paul Jenseneec75412014-08-04 12:21:19 -04005232 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005233 }
5234
5235 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5236 networkAgent.everConnected = true;
5237
Robert Greenwalt7b816022014-04-18 15:25:25 -07005238 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005239 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005240
Paul Jensenca8f16a2014-05-09 12:47:55 -04005241 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005242 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005243
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005244 if (networkAgent.isVPN()) {
5245 // Temporarily disable the default proxy (not global).
5246 synchronized (mProxyLock) {
5247 if (!mDefaultProxyDisabled) {
5248 mDefaultProxyDisabled = true;
5249 if (mGlobalProxy == null && mDefaultProxy != null) {
5250 sendProxyBroadcast(null);
5251 }
5252 }
5253 }
5254 // TODO: support proxy per network.
5255 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005256
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005257 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5258 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5259 // capabilities, so it only needs to be done once on initial connect, not every time the
5260 // network's capabilities change. Note that we do this before rematching the network,
5261 // so we could decide to tear it down immediately afterwards. That's fine though - on
5262 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5263 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005264 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005265
Paul Jensen2161a8e2014-09-11 11:00:39 -04005266 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005267 final long now = SystemClock.elapsedRealtime();
5268 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005269
5270 // This has to happen after matching the requests, because callbacks are just requests.
5271 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005272 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005273 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005274 if (networkAgent.isVPN()) {
5275 synchronized (mProxyLock) {
5276 if (mDefaultProxyDisabled) {
5277 mDefaultProxyDisabled = false;
5278 if (mGlobalProxy == null && mDefaultProxy != null) {
5279 sendProxyBroadcast(mDefaultProxy);
5280 }
5281 }
5282 }
5283 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005284 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5285 state == NetworkInfo.State.SUSPENDED) {
5286 // going into or coming out of SUSPEND: rescore and notify
5287 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005288 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005289 }
5290 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5291 ConnectivityManager.CALLBACK_SUSPENDED :
5292 ConnectivityManager.CALLBACK_RESUMED));
5293 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005294 }
5295 }
5296
Robert Greenwaltac96c522014-06-03 16:43:57 -07005297 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005298 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005299 if (score < 0) {
5300 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5301 "). Bumping score to min of 0");
5302 score = 0;
5303 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005304
Paul Jensen2161a8e2014-09-11 11:00:39 -04005305 final int oldScore = nai.getCurrentScore();
5306 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005307
Paul Jensen85cf78e2015-06-25 13:25:07 -04005308 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005309
Paul Jensenc8b9a742014-09-30 15:37:41 -04005310 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005311 }
5312
Robert Greenwalt9258c642014-03-26 16:47:06 -07005313 // notify only this one new request of the current state
5314 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5315 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Etan Cohen681fcda2016-10-27 15:05:50 -07005316 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005317 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005318 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005319 } else {
5320 sendPendingIntentForRequest(nri, nai, notifyType);
5321 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005322 }
5323
Robert Greenwalt8d482522015-06-24 13:23:42 -07005324 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005325 // The NetworkInfo we actually send out has no bearing on the real
5326 // state of affairs. For example, if the default connection is mobile,
5327 // and a request for HIPRI has just gone away, we need to pretend that
5328 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5329 // the state to DISCONNECTED, even though the network is of type MOBILE
5330 // and is still connected.
5331 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5332 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005333 if (state != DetailedState.DISCONNECTED) {
5334 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005335 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005336 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005337 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005338 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5339 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5340 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5341 if (info.isFailover()) {
5342 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5343 nai.networkInfo.setFailover(false);
5344 }
5345 if (info.getReason() != null) {
5346 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5347 }
5348 if (info.getExtraInfo() != null) {
5349 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5350 }
5351 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005352 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005353 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005354 if (newDefaultAgent != null) {
5355 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5356 newDefaultAgent.networkInfo);
5357 } else {
5358 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5359 }
5360 }
5361 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5362 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005363 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005364 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005365 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005366 }
5367 }
5368 }
5369
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005370 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005371 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005372 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5373 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005374 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5375 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005376 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5377 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005378 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005379 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005380 } else {
5381 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5382 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005383 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005384 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005385
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005386 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5387 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5388 }
5389
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005390 private String notifyTypeToName(int notifyType) {
5391 switch (notifyType) {
5392 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5393 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5394 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5395 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5396 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5397 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5398 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5399 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5400 }
5401 return "UNKNOWN";
5402 }
5403
Jeff Sharkey69736342014-12-08 14:50:12 -08005404 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005405 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5406 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005407 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005408 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005409 try {
5410 mStatsService.forceUpdateIfaces();
5411 } catch (Exception ignored) {
5412 }
5413 }
5414
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005415 @Override
5416 public boolean addVpnAddress(String address, int prefixLength) {
5417 throwIfLockdownEnabled();
5418 int user = UserHandle.getUserId(Binder.getCallingUid());
5419 synchronized (mVpns) {
5420 return mVpns.get(user).addAddress(address, prefixLength);
5421 }
5422 }
5423
5424 @Override
5425 public boolean removeVpnAddress(String address, int prefixLength) {
5426 throwIfLockdownEnabled();
5427 int user = UserHandle.getUserId(Binder.getCallingUid());
5428 synchronized (mVpns) {
5429 return mVpns.get(user).removeAddress(address, prefixLength);
5430 }
5431 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005432
5433 @Override
5434 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5435 throwIfLockdownEnabled();
5436 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005437 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005438 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005439 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005440 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005441 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005442 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005443 }
5444 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005445 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005446
5447 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005448 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005449 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005450 }
5451
5452 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005453 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5454 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5455 enforceKeepalivePermission();
5456 mKeepaliveTracker.startNattKeepalive(
5457 getNetworkAgentInfoForNetwork(network),
5458 intervalSeconds, messenger, binder,
5459 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5460 }
5461
5462 @Override
5463 public void stopKeepalive(Network network, int slot) {
5464 mHandler.sendMessage(mHandler.obtainMessage(
5465 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5466 }
5467
5468 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005469 public void factoryReset() {
5470 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005471
5472 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5473 return;
5474 }
5475
Robin Lee3b3dd942015-05-12 18:14:58 +01005476 final int userId = UserHandle.getCallingUserId();
5477
Stuart Scottf1fb3972015-04-02 18:00:02 -07005478 // Turn airplane mode off
5479 setAirplaneMode(false);
5480
Stuart Scotte3e314d2015-04-20 14:07:45 -07005481 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5482 // Untether
5483 for (String tether : getTetheredIfaces()) {
5484 untether(tether);
5485 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005486 }
5487
Stuart Scotte3e314d2015-04-20 14:07:45 -07005488 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005489 // Remove always-on package
5490 synchronized (mVpns) {
5491 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5492 if (alwaysOnPackage != null) {
5493 setAlwaysOnVpnPackage(userId, null, false);
5494 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5495 }
5496 }
5497
Stuart Scotte3e314d2015-04-20 14:07:45 -07005498 // Turn VPN off
5499 VpnConfig vpnConfig = getVpnConfig(userId);
5500 if (vpnConfig != null) {
5501 if (vpnConfig.legacy) {
5502 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5503 } else {
5504 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5505 // in the future without user intervention.
5506 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005507
Victor Changb04a5ea2016-05-30 20:36:30 +01005508 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005509 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005510 }
5511 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005512
5513 Settings.Global.putString(mContext.getContentResolver(),
5514 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005515 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005516
5517 @VisibleForTesting
5518 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5519 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5520 return new NetworkMonitor(context, handler, nai, defaultRequest);
5521 }
Erik Kline48f12f22016-04-14 17:30:59 +09005522
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005523 @VisibleForTesting
Erik Kline065ab6e2016-10-02 18:02:14 +09005524 AvoidBadWifiTracker createAvoidBadWifiTracker(Context c, Handler h, Runnable r) {
5525 return new AvoidBadWifiTracker(c, h, r);
5526 }
5527
5528 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005529 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5530 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5531 }
5532
Hugo Benichicfddd682016-05-31 16:28:06 +09005533 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005534 int newNetid = NETID_UNSET;
5535 int prevNetid = NETID_UNSET;
5536 int[] transports = new int[0];
5537 boolean hadIPv4 = false;
5538 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005539
Hugo Benichi5f16f762016-04-20 12:09:33 +09005540 if (newNai != null) {
5541 newNetid = newNai.network.netId;
5542 transports = newNai.networkCapabilities.getTransportTypes();
5543 }
5544 if (prevNai != null) {
5545 prevNetid = prevNai.network.netId;
5546 final LinkProperties lp = prevNai.linkProperties;
5547 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5548 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5549 }
5550
Hugo Benichicfddd682016-05-31 16:28:06 +09005551 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5552 }
5553
5554 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5555 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557}