blob: 13a6cd63003dfb67b5836f00655a077b3392387f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070032import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070034import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060037import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070038import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090042import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070050import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090051import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070052import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090054import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070056import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070059import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070063import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070065import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070067import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070068import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090078import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090081import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080083import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070084import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040085import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070087import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070089import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070092import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070094import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070095import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080097import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090098import android.os.SystemClock;
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
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900398 private static String eventName(int what) {
399 return sMagicDecoderRing.get(what, Integer.toString(what));
400 }
401
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900402 /** Handler thread used for both of the handlers below. */
403 @VisibleForTesting
404 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700405 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700406 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700407 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700408 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700409
Mike Lockwood0f79b542009-08-14 14:18:49 -0400410 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800411 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400412
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700413 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700414 private int mNetTransitionWakeLockSerialNumber;
415 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800416 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700417
Robert Greenwalt434203a2010-10-11 16:00:27 -0700418 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400419 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700420 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700421 private boolean mDefaultProxyDisabled = false;
422
Robert Greenwalt434203a2010-10-11 16:00:27 -0700423 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400424 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700425
Jason Monk602b2322013-07-03 17:04:33 -0400426 private PacManager mPacManager = null;
427
Erik Klineda4bfa82015-04-30 12:58:40 +0900428 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400430 private UserManager mUserManager;
431
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700432 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700433 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700434
Robert Greenwalt50393202011-06-21 17:26:14 -0700435 // the set of network types that can only be enabled by system/sig apps
436 List mProtectedNetworks;
437
John Spurlockbf991a82013-06-24 14:20:23 -0400438 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700439
Wink Savilleab9321d2013-06-29 21:10:57 -0700440 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400441
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900442 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900443 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900444 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900445
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700446 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
447 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700448 private final static int MAX_NET_ID = 65535;
449 private int mNextNetId = MIN_NET_ID;
450
Robert Greenwalt34524f02014-05-18 16:22:10 -0700451 // sequence number of NetworkRequests
452 private int mNextNetworkRequestId = 1;
453
Erik Kline7523eb32015-07-09 18:24:03 +0900454 // NetworkRequest activity String log entries.
455 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
456 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
457
Hugo Benichic2ae2872016-07-11 11:05:12 +0900458 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900459 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900460 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
461
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900462 private static final int MAX_WAKELOCK_LOGS = 20;
463 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
464
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700465 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
466 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400467 private static class ValidationLog {
468 final Network mNetwork;
469 final String mNetworkExtraInfo;
470 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700471
Paul Jensen0808eb82016-06-03 13:51:21 -0400472 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
473 mNetwork = network;
474 mNetworkExtraInfo = networkExtraInfo;
475 mLog = log;
476 }
477 }
478 private final ArrayDeque<ValidationLog> mValidationLogs =
479 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
480
481 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700482 synchronized(mValidationLogs) {
483 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
484 mValidationLogs.removeLast();
485 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400486 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700487 }
488 }
489
Hugo Benichif9fdf872016-07-28 17:53:06 +0900490 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900491
Erik Kline065ab6e2016-10-02 18:02:14 +0900492 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900493 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900494
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700495 /**
496 * Implements support for the legacy "one network per network type" model.
497 *
498 * We used to have a static array of NetworkStateTrackers, one for each
499 * network type, but that doesn't work any more now that we can have,
500 * for example, more that one wifi network. This class stores all the
501 * NetworkAgentInfo objects that support a given type, but the legacy
502 * API will only see the first one.
503 *
504 * It serves two main purposes:
505 *
506 * 1. Provide information about "the network for a given type" (since this
507 * API only supports one).
508 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
509 * the first network for a given type changes, or if the default network
510 * changes.
511 */
512 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900514 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700517 /**
518 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
519 * Each list holds references to all NetworkAgentInfos that are used to
520 * satisfy requests for that network type.
521 *
522 * This array is built out at startup such that an unsupported network
523 * doesn't get an ArrayList instance, making this a tristate:
524 * unsupported, supported but not active and active.
525 *
526 * The actual lists are populated when we scan the network types that
527 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900528 *
529 * Threading model:
530 * - addSupportedType() is only called in the constructor
531 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
532 * They are therefore not thread-safe with respect to each other.
533 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
534 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
535 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700536 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900537 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538
539 public LegacyTypeTracker() {
540 mTypeLists = (ArrayList<NetworkAgentInfo>[])
541 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
542 }
543
544 public void addSupportedType(int type) {
545 if (mTypeLists[type] != null) {
546 throw new IllegalStateException(
547 "legacy list for type " + type + "already initialized");
548 }
549 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
550 }
551
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700552 public boolean isTypeSupported(int type) {
553 return isNetworkTypeValid(type) && mTypeLists[type] != null;
554 }
555
556 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900557 synchronized (mTypeLists) {
558 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
559 return mTypeLists[type].get(0);
560 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900562 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
564
Robert Greenwalt8d482522015-06-24 13:23:42 -0700565 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900566 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900567 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700568 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900570 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900571 }
572 }
573
574 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 public void add(int type, NetworkAgentInfo nai) {
576 if (!isTypeSupported(type)) {
577 return; // Invalid network type.
578 }
579 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
580
581 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
582 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700583 return;
584 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900585 synchronized (mTypeLists) {
586 list.add(nai);
587 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900588
589 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900590 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900591 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700592 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
593 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700594 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 }
596
Lorenzo Colittia793a672014-07-31 23:20:17 +0900597 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900598 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
600 if (list == null || list.isEmpty()) {
601 return;
602 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900603 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900604
Hugo Benichi78caa2582016-06-21 09:48:07 +0900605 synchronized (mTypeLists) {
606 if (!list.remove(nai)) {
607 return;
608 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609 }
610
Robert Greenwalt8d482522015-06-24 13:23:42 -0700611 final DetailedState state = DetailedState.DISCONNECTED;
612
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900613 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700614 maybeLogBroadcast(nai, state, type, wasDefault);
615 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616 }
617
618 if (!list.isEmpty() && wasFirstNetwork) {
619 if (DBG) log("Other network available for type " + type +
620 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700622 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
623 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900624 }
625 }
626
627 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900628 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
629 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700630 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900631 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 }
633 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700634
Robert Greenwalt8d482522015-06-24 13:23:42 -0700635 // send out another legacy broadcast - currently only used for suspend/unsuspend
636 // toggle
637 public void update(NetworkAgentInfo nai) {
638 final boolean isDefault = isDefaultNetwork(nai);
639 final DetailedState state = nai.networkInfo.getDetailedState();
640 for (int type = 0; type < mTypeLists.length; type++) {
641 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700642 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900643 final boolean isFirst = contains && (nai == list.get(0));
644 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 maybeLogBroadcast(nai, state, type, isDefault);
646 sendLegacyNetworkBroadcast(nai, state, type);
647 }
648 }
649 }
650
Lorenzo Colittia793a672014-07-31 23:20:17 +0900651 private String naiToString(NetworkAgentInfo nai) {
652 String name = (nai != null) ? nai.name() : "null";
653 String state = (nai.networkInfo != null) ?
654 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
655 "???/???";
656 return name + " " + state;
657 }
658
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700659 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900660 pw.println("mLegacyTypeTracker:");
661 pw.increaseIndent();
662 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700663 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900664 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900666 pw.println();
667 pw.println("Current state:");
668 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900669 synchronized (mTypeLists) {
670 for (int type = 0; type < mTypeLists.length; type++) {
671 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
672 for (NetworkAgentInfo nai : mTypeLists[type]) {
673 pw.println(type + " " + naiToString(nai));
674 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900675 }
676 }
677 pw.decreaseIndent();
678 pw.decreaseIndent();
679 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700680 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700681 }
682 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
683
Jeff Sharkey899223b2012-08-04 15:24:58 -0700684 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700685 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900686 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
687 }
688
689 @VisibleForTesting
690 protected ConnectivityService(Context context, INetworkManagementService netManager,
691 INetworkStatsService statsService, INetworkPolicyManager policyManager,
692 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800693 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800694
Hugo Benichif9fdf872016-07-28 17:53:06 +0900695 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900696 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900697 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900698 mNetworkRequests.put(mDefaultRequest, defaultNRI);
699 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900700
701 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900702 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700703
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900704 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900705 mHandlerThread.start();
706 mHandler = new InternalHandler(mHandlerThread.getLooper());
707 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700708
Jeremy Joslin79294842014-12-03 17:15:28 -0800709 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
710 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
711
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900712 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
713
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700714 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700715 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800716 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700717 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700718 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700719 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700720
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700721 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600722 mPolicyManager.setConnectivityListener(mPolicyListener);
723 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700724 } catch (RemoteException e) {
725 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700726 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700727 }
728
729 final PowerManager powerManager = (PowerManager) context.getSystemService(
730 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700731 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
732 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
733 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800734 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700735
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700736 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700737
Wink Saville51f456f2013-04-23 14:26:51 -0700738 // TODO: What is the "correct" way to do determine if this is a wifi only device?
739 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
740 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700741 String[] naStrings = context.getResources().getStringArray(
742 com.android.internal.R.array.networkAttributes);
743 for (String naString : naStrings) {
744 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700745 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700746 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700747 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800748 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700749 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700750 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700751 }
Wink Saville51f456f2013-04-23 14:26:51 -0700752 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
753 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
754 n.type);
755 continue;
756 }
Wink Saville975c8482011-04-07 14:23:45 -0700757 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800758 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700759 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700760 continue;
761 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700762 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700763
Wink Saville975c8482011-04-07 14:23:45 -0700764 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700765 mNetworksDefined++;
766 } catch(Exception e) {
767 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700768 }
769 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700770
771 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
772 if (mNetConfigs[TYPE_VPN] == null) {
773 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
774 // don't need to add TYPE_VPN to mNetConfigs.
775 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
776 mNetworksDefined++; // used only in the log() statement below.
777 }
778
Wink Saville5e56bc52013-07-29 15:00:57 -0700779 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700780
Robert Greenwalt50393202011-06-21 17:26:14 -0700781 mProtectedNetworks = new ArrayList<Integer>();
782 int[] protectedNetworks = context.getResources().getIntArray(
783 com.android.internal.R.array.config_protectedNetworks);
784 for (int p : protectedNetworks) {
785 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
786 mProtectedNetworks.add(p);
787 } else {
788 if (DBG) loge("Ignoring protectedNetwork " + p);
789 }
790 }
791
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700792 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
793 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700794
Christopher Wiley497c1472016-10-11 13:26:03 -0700795 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
796 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800797
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700798 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
799
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700800 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700801 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100802 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700803 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700804 intentFilter.addAction(Intent.ACTION_USER_ADDED);
805 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000806 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700807 mContext.registerReceiverAsUser(
808 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000809 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
810 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900811
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700812 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700813 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700814 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700815 } catch (RemoteException e) {
816 loge("Error registering observer :" + e);
817 }
818
Erik Klineda4bfa82015-04-30 12:58:40 +0900819 mSettingsObserver = new SettingsObserver(mContext, mHandler);
820 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800821
John Spurlockbf991a82013-06-24 14:20:23 -0400822 mDataConnectionStats = new DataConnectionStats(mContext);
823 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400824
Jason Monkdecd2952013-10-10 14:02:51 -0400825 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700826
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400827 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900828
829 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900830 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
831 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900832
833 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
834 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
835 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
836 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
837 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
838 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
839 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900840
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900841 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900842 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900843 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700845
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900846 private NetworkRequest createInternetRequestForTransport(
847 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900848 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900849 netCap.addCapability(NET_CAPABILITY_INTERNET);
850 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900851 if (transportType > -1) {
852 netCap.addTransportType(transportType);
853 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900854 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900855 }
856
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900857 // Used only for testing.
858 // TODO: Delete this and either:
859 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
860 // changing ContentResolver to make registerContentObserver non-final).
861 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
862 // by subclassing SettingsObserver.
863 @VisibleForTesting
864 void updateMobileDataAlwaysOn() {
865 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
866 }
867
Erik Klineda4bfa82015-04-30 12:58:40 +0900868 private void handleMobileDataAlwaysOn() {
869 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900870 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900871 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
872 if (enable == isEnabled) {
873 return; // Nothing to do.
874 }
875
876 if (enable) {
877 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900878 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900879 } else {
880 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
881 }
882 }
883
884 private void registerSettingsCallbacks() {
885 // Watch for global HTTP proxy changes.
886 mSettingsObserver.observe(
887 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
888 EVENT_APPLY_GLOBAL_HTTP_PROXY);
889
890 // Watch for whether or not to keep mobile data always on.
891 mSettingsObserver.observe(
892 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
893 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
894 }
895
Robert Greenwalt34524f02014-05-18 16:22:10 -0700896 private synchronized int nextNetworkRequestId() {
897 return mNextNetworkRequestId++;
898 }
899
Paul Jensen67b0b072015-06-10 11:22:17 -0400900 @VisibleForTesting
901 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400902 synchronized (mNetworkForNetId) {
903 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
904 int netId = mNextNetId;
905 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
906 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500907 if (!mNetIdInUse.get(netId)) {
908 mNetIdInUse.put(netId, true);
909 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400910 }
911 }
912 }
913 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700914 }
915
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600916 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800917 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600918 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
919 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800920 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600921 state = nai.getNetworkState();
922 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800923 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600924 final NetworkInfo info = new NetworkInfo(networkType, 0,
925 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800926 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
927 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600928 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
929 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800930 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600931 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600932 return state;
933 } else {
934 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400936 }
937
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800938 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
939 if (network == null) {
940 return null;
941 }
942 synchronized (mNetworkForNetId) {
943 return mNetworkForNetId.get(network.netId);
944 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600945 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800946
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900947 private Network[] getVpnUnderlyingNetworks(int uid) {
948 if (!mLockdownEnabled) {
949 int user = UserHandle.getUserId(uid);
950 synchronized (mVpns) {
951 Vpn vpn = mVpns.get(user);
952 if (vpn != null && vpn.appliesToUid(uid)) {
953 return vpn.getUnderlyingNetworks();
954 }
955 }
956 }
957 return null;
958 }
959
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400961 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800962
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900963 final Network[] networks = getVpnUnderlyingNetworks(uid);
964 if (networks != null) {
965 // getUnderlyingNetworks() returns:
966 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
967 // empty array => the VPN explicitly said "no default network".
968 // non-empty array => the VPN specified one or more default networks; we use the
969 // first one.
970 if (networks.length > 0) {
971 nai = getNetworkAgentInfoForNetwork(networks[0]);
972 } else {
973 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800974 }
975 }
976
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800977 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600978 return nai.getNetworkState();
979 } else {
980 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800981 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400982 }
983
984 /**
985 * Check if UID should be blocked from using the network with the given LinkProperties.
986 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600987 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
988 boolean ignoreBlocked) {
989 // Networks aren't blocked when ignoring blocked status
990 if (ignoreBlocked) return false;
991 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -0700992 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600993
994 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700995 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700996
Robin Lee17e61832016-05-09 13:46:28 +0100997 synchronized (mVpns) {
998 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
999 if (vpn != null && vpn.isBlockingUid(uid)) {
1000 return true;
1001 }
1002 }
1003
Robert Greenwalt12e67352014-05-13 21:41:06 -07001004 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001005 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001006 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001007 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001008 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001009
Felipe Lemed31a97f2016-05-06 14:53:50 -07001010 boolean allowed = true;
1011 // Check Data Saver Mode first...
1012 if (networkMetered) {
1013 if ((uidRules & RULE_REJECT_METERED) != 0) {
1014 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1015 // Explicitly blacklisted.
1016 allowed = false;
1017 } else {
1018 allowed = !mRestrictBackground
1019 || (uidRules & RULE_ALLOW_METERED) != 0
1020 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1021 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1022 + " mRestrictBackground=" + mRestrictBackground
1023 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1024 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1025 + ": " + allowed);
1026 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001027 }
Felipe Leme781ba142016-05-09 16:24:48 -07001028 // ...then power restrictions.
1029 if (allowed) {
1030 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001031 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001032 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001033 }
1034 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001035 }
1036
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001037 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001038 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1039 return;
1040 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001041 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001042 synchronized (mBlockedAppUids) {
1043 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001044 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001045 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001046 blocked = false;
1047 } else {
1048 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001049 }
1050 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001051 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1052 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1053 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001054 }
1055
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001056 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001057 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1058 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1059 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1060 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001061 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001062 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001063 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1064
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001065 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001066 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001067 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001068 if (mLockdownTracker != null) {
1069 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001070 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001071
1072 // TODO: apply metered state closer to NetworkAgentInfo
1073 final long token = Binder.clearCallingIdentity();
1074 try {
1075 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1076 } catch (RemoteException e) {
1077 } finally {
1078 Binder.restoreCallingIdentity(token);
1079 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001080 }
1081
1082 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 * Return NetworkInfo for the active (i.e., connected) network interface.
1084 * It is assumed that at most one network is active at a time. If more
1085 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001086 * @return the info for the active network, or {@code null} if none is
1087 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001089 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001091 enforceAccessPermission();
1092 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001093 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001094 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001095 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1096 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 }
1098
Paul Jensen31a94f42015-02-13 14:18:39 -05001099 @Override
1100 public Network getActiveNetwork() {
1101 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001102 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001103 }
1104
1105 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001106 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001107 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001108 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001109 }
1110
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001111 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001112 final int user = UserHandle.getUserId(uid);
1113 int vpnNetId = NETID_UNSET;
1114 synchronized (mVpns) {
1115 final Vpn vpn = mVpns.get(user);
1116 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1117 }
1118 NetworkAgentInfo nai;
1119 if (vpnNetId != NETID_UNSET) {
1120 synchronized (mNetworkForNetId) {
1121 nai = mNetworkForNetId.get(vpnNetId);
1122 }
1123 if (nai != null) return nai.network;
1124 }
1125 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001126 if (nai != null
1127 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1128 nai = null;
1129 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001130 return nai != null ? nai.network : null;
1131 }
1132
Lorenzo Colitti18660282016-07-04 12:55:44 +09001133 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001134 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1135 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001136 final int uid = Binder.getCallingUid();
1137 NetworkState state = getUnfilteredActiveNetworkState(uid);
1138 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001139 }
1140
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001142 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001143 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001144 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001145 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001146 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001147 }
1148
1149 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 public NetworkInfo getNetworkInfo(int networkType) {
1151 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001152 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001153 if (getVpnUnderlyingNetworks(uid) != null) {
1154 // A VPN is active, so we may need to return one of its underlying networks. This
1155 // information is not available in LegacyTypeTracker, so we have to get it from
1156 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001157 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001158 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001159 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001160 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001161 }
1162 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001163 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001164 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
1166
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001168 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001169 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001170 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001172 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001173 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001174 return state.networkInfo;
1175 } else {
1176 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001177 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001178 }
1179
1180 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 public NetworkInfo[] getAllNetworkInfo() {
1182 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001183 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001184 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1185 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 NetworkInfo info = getNetworkInfo(networkType);
1187 if (info != null) {
1188 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001191 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 }
1193
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001194 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001195 public Network getNetworkForType(int networkType) {
1196 enforceAccessPermission();
1197 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001198 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1199 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001201 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001202 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001203 }
1204
1205 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001206 public Network[] getAllNetworks() {
1207 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001208 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001209 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001210 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001211 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001212 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001213 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001214 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001215 }
1216
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001217 @Override
1218 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1219 // The basic principle is: if an app's traffic could possibly go over a
1220 // network, without the app doing anything multinetwork-specific,
1221 // (hence, by "default"), then include that network's capabilities in
1222 // the array.
1223 //
1224 // In the normal case, app traffic only goes over the system's default
1225 // network connection, so that's the only network returned.
1226 //
1227 // With a VPN in force, some app traffic may go into the VPN, and thus
1228 // over whatever underlying networks the VPN specifies, while other app
1229 // traffic may go over the system default network (e.g.: a split-tunnel
1230 // VPN, or an app disallowed by the VPN), so the set of networks
1231 // returned includes the VPN's underlying networks and the system
1232 // default.
1233 enforceAccessPermission();
1234
1235 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1236
1237 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001238 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001239 if (nc != null) {
1240 result.put(nai.network, nc);
1241 }
1242
1243 if (!mLockdownEnabled) {
1244 synchronized (mVpns) {
1245 Vpn vpn = mVpns.get(userId);
1246 if (vpn != null) {
1247 Network[] networks = vpn.getUnderlyingNetworks();
1248 if (networks != null) {
1249 for (Network network : networks) {
1250 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001251 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001252 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001253 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001254 }
1255 }
1256 }
1257 }
1258 }
1259 }
1260
1261 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1262 out = result.values().toArray(out);
1263 return out;
1264 }
1265
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001266 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001267 public boolean isNetworkSupported(int networkType) {
1268 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001269 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001270 }
1271
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001272 /**
1273 * Return LinkProperties for the active (i.e., connected) default
1274 * network interface. It is assumed that at most one default network
1275 * is active at a time. If more than one is active, it is indeterminate
1276 * which will be returned.
1277 * @return the ip properties for the active network, or {@code null} if
1278 * none is active
1279 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001280 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001281 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001282 enforceAccessPermission();
1283 final int uid = Binder.getCallingUid();
1284 NetworkState state = getUnfilteredActiveNetworkState(uid);
1285 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001286 }
1287
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001288 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001289 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001290 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001291 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1292 if (nai != null) {
1293 synchronized (nai) {
1294 return new LinkProperties(nai.linkProperties);
1295 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001296 }
1297 return null;
1298 }
1299
Robert Greenwalt12e67352014-05-13 21:41:06 -07001300 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001301 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001302 public LinkProperties getLinkProperties(Network network) {
1303 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001304 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001305 if (nai != null) {
1306 synchronized (nai) {
1307 return new LinkProperties(nai.linkProperties);
1308 }
1309 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001310 return null;
1311 }
1312
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001313 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001314 if (nai != null) {
1315 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001316 if (nai.networkCapabilities != null) {
1317 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001318 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001319 }
1320 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001321 return null;
1322 }
1323
1324 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001325 public NetworkCapabilities getNetworkCapabilities(Network network) {
1326 enforceAccessPermission();
1327 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1328 }
1329
1330 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001331 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001332 // Require internal since we're handing out IMSI details
1333 enforceConnectivityInternalPermission();
1334
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001335 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001336 for (Network network : getAllNetworks()) {
1337 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1338 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001339 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001340 }
1341 }
1342 return result.toArray(new NetworkState[result.size()]);
1343 }
1344
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001345 @Override
1346 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1347 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001348 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001349 final long token = Binder.clearCallingIdentity();
1350 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001351 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1352 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001353 try {
1354 return mPolicyManager.getNetworkQuotaInfo(state);
1355 } catch (RemoteException e) {
1356 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001357 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001358 return null;
1359 } finally {
1360 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001361 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001362 }
1363
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001364 @Override
1365 public boolean isActiveNetworkMetered() {
1366 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001367
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001368 final NetworkInfo info = getActiveNetworkInfo();
1369 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001370 }
1371
Jeff Sharkey216c1812012-08-05 14:29:23 -07001372 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1373 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001374 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001375 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001376 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001377 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001378 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001379
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001380 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 * Ensure that a network route exists to deliver traffic to the specified
1382 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001383 * @param networkType the type of the network over which traffic to the
1384 * specified host is to be routed
1385 * @param hostAddress the IP address of the host to which the route is
1386 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 * @return {@code true} on success, {@code false} on failure
1388 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001389 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001390 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001392 if (mProtectedNetworks.contains(networkType)) {
1393 enforceConnectivityInternalPermission();
1394 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001395
Chad Brubakerc0234532014-02-14 13:24:29 -08001396 InetAddress addr;
1397 try {
1398 addr = InetAddress.getByAddress(hostAddress);
1399 } catch (UnknownHostException e) {
1400 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1401 return false;
1402 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001405 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 return false;
1407 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001408
1409 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1410 if (nai == null) {
1411 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1412 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1413 } else {
1414 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1415 }
1416 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001417 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001418
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001419 DetailedState netState;
1420 synchronized (nai) {
1421 netState = nai.networkInfo.getDetailedState();
1422 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001423
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001424 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001425 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001426 log("requestRouteToHostAddress on down network "
1427 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001428 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001429 }
1430 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001432
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001433 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001434 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001435 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001436 LinkProperties lp;
1437 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001438 synchronized (nai) {
1439 lp = nai.linkProperties;
1440 netId = nai.network.netId;
1441 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001442 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001443 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1444 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001445 } finally {
1446 Binder.restoreCallingIdentity(token);
1447 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001448 }
1449
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001450 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001451 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001452 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001453 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001454 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001455 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001456 if (bestRoute.getGateway().equals(addr)) {
1457 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001458 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001459 } else {
1460 // if we will connect to this through another route, add a direct route
1461 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001462 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001463 }
1464 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001465 if (DBG) log("Adding legacy route " + bestRoute +
1466 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001467 try {
1468 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1469 } catch (Exception e) {
1470 // never crash - catch them all
1471 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001472 return false;
1473 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001474 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
1476
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001477 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1478 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001479 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001480 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001481 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001482 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001483 }
1484
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001485 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001486 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001487 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001488 if (oldRules == uidRules) return;
1489
Felipe Leme781ba142016-05-09 16:24:48 -07001490 if (uidRules == RULE_NONE) {
1491 mUidRules.delete(uid);
1492 } else {
1493 mUidRules.put(uid, uidRules);
1494 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001495 }
1496
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001497 // TODO: notify UID when it has requested targeted updates
1498 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001499
1500 @Override
1501 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001502 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001503 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001504 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001505 }
1506
1507 synchronized (mRulesLock) {
1508 mMeteredIfaces.clear();
1509 for (String iface : meteredIfaces) {
1510 mMeteredIfaces.add(iface);
1511 }
1512 }
1513 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001514
1515 @Override
1516 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1517 // caller is NPMS, since we only register with them
1518 if (LOGD_RULES) {
1519 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1520 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001521
1522 synchronized (mRulesLock) {
1523 mRestrictBackground = restrictBackground;
1524 }
1525
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001526 if (restrictBackground) {
1527 log("onRestrictBackgroundChanged(true): disabling tethering");
1528 mTethering.untetherAll();
1529 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001530 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001531
1532 @Override
1533 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1534 if (LOGD_RULES) {
1535 // caller is NPMS, since we only register with them
1536 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1537 + whitelisted + ")");
1538 }
1539 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001540 @Override
1541 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1542 if (LOGD_RULES) {
1543 // caller is NPMS, since we only register with them
1544 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1545 + blacklisted + ")");
1546 }
1547 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001548 };
1549
Robin Lee3b3dd942015-05-12 18:14:58 +01001550 /**
1551 * Require that the caller is either in the same user or has appropriate permission to interact
1552 * across users.
1553 *
1554 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1555 */
1556 private void enforceCrossUserPermission(int userId) {
1557 if (userId == UserHandle.getCallingUserId()) {
1558 // Not a cross-user call.
1559 return;
1560 }
1561 mContext.enforceCallingOrSelfPermission(
1562 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1563 "ConnectivityService");
1564 }
1565
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001566 private void enforceInternetPermission() {
1567 mContext.enforceCallingOrSelfPermission(
1568 android.Manifest.permission.INTERNET,
1569 "ConnectivityService");
1570 }
1571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001573 mContext.enforceCallingOrSelfPermission(
1574 android.Manifest.permission.ACCESS_NETWORK_STATE,
1575 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 }
1577
1578 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001579 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001582 private void enforceTetherAccessPermission() {
1583 mContext.enforceCallingOrSelfPermission(
1584 android.Manifest.permission.ACCESS_NETWORK_STATE,
1585 "ConnectivityService");
1586 }
1587
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001588 private void enforceConnectivityInternalPermission() {
1589 mContext.enforceCallingOrSelfPermission(
1590 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1591 "ConnectivityService");
1592 }
1593
Hugo Benichi514da602016-07-19 15:59:27 +09001594 private void enforceConnectivityRestrictedNetworksPermission() {
1595 try {
1596 mContext.enforceCallingOrSelfPermission(
1597 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1598 "ConnectivityService");
1599 return;
1600 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1601 enforceConnectivityInternalPermission();
1602 }
1603
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001604 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001605 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001606 }
1607
Lorenzo Colitti18660282016-07-04 12:55:44 +09001608 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001609 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001610 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001611 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001612 }
1613
1614 private void sendInetConditionBroadcast(NetworkInfo info) {
1615 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1616 }
1617
Wink Saville628b0852011-08-04 15:01:58 -07001618 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001619 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001620 info = new NetworkInfo(info);
1621 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001622 }
1623
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001624 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001625 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001626 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 if (info.isFailover()) {
1628 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1629 info.setFailover(false);
1630 }
1631 if (info.getReason() != null) {
1632 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1633 }
1634 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001635 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1636 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001638 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001639 return intent;
1640 }
1641
1642 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1643 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1644 }
1645
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001646 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001647 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1648 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1649 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001650 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001651 final long ident = Binder.clearCallingIdentity();
1652 try {
1653 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1654 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1655 } finally {
1656 Binder.restoreCallingIdentity(ident);
1657 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001658 }
1659
Mike Lockwood0f79b542009-08-14 14:18:49 -04001660 private void sendStickyBroadcast(Intent intent) {
1661 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001662 if (!mSystemReady) {
1663 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001664 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001665 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001666 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001667 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001668 }
1669
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001670 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001671 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001672 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001673 final NetworkInfo ni = intent.getParcelableExtra(
1674 ConnectivityManager.EXTRA_NETWORK_INFO);
1675 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1676 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1677 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001678 } else {
1679 BroadcastOptions opts = BroadcastOptions.makeBasic();
1680 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1681 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001682 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001683 final IBatteryStats bs = BatteryStatsService.getService();
1684 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001685 bs.noteConnectivityChanged(intent.getIntExtra(
1686 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1687 ni != null ? ni.getState().toString() : "?");
1688 } catch (RemoteException e) {
1689 }
1690 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001691 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001692 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001693 } finally {
1694 Binder.restoreCallingIdentity(ident);
1695 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001696 }
1697 }
1698
1699 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001700 loadGlobalProxy();
1701
Mike Lockwood0f79b542009-08-14 14:18:49 -04001702 synchronized(this) {
1703 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001704 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001705 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001706 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001707 }
1708 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001709 // load the global proxy at startup
1710 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001711
Robin Lee244ce8e2016-01-05 18:03:46 +00001712 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1713 // for user to unlock device too.
1714 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001715
Erik Klineda4bfa82015-04-30 12:58:40 +09001716 // Configure whether mobile data is always on.
1717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1718
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001719 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001720
1721 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 }
1723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001725 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001726 *
1727 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001728 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001729 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001730 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1731 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001732
1733 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001735
Robert Greenwalt7b816022014-04-18 15:25:25 -07001736 if (networkAgent.networkCapabilities.hasTransport(
1737 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001738 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1739 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001740 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001741 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001742 } else if (networkAgent.networkCapabilities.hasTransport(
1743 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001744 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1745 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001746 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001747 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001748 } else {
1749 // do not track any other networks
1750 timeout = 0;
1751 }
1752
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001754 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001755 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001756 } catch (Exception e) {
1757 // You shall not crash!
1758 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001759 }
1760 }
1761 }
1762
1763 /**
1764 * Remove data activity tracking when network disconnects.
1765 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1767 final String iface = networkAgent.linkProperties.getInterfaceName();
1768 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001769
Robert Greenwalt7b816022014-04-18 15:25:25 -07001770 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1771 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001772 try {
1773 // the call fails silently if no idletimer setup for this interface
1774 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001775 } catch (Exception e) {
1776 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001777 }
1778 }
1779 }
1780
1781 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001782 * Reads the network specific MTU size from reources.
1783 * and set it on it's iface.
1784 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001785 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1786 final String iface = newLp.getInterfaceName();
1787 final int mtu = newLp.getMtu();
Pierre Imaiaccd5fc2016-02-08 16:01:40 +09001788 if (oldLp == null && mtu == 0) {
1789 // Silently ignore unset MTU value.
1790 return;
1791 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001792 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1793 if (VDBG) log("identical MTU - not setting");
1794 return;
1795 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001796 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001797 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001798 return;
1799 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001800
w1997615afd812014-08-05 15:18:11 -07001801 // Cannot set MTU without interface name
1802 if (TextUtils.isEmpty(iface)) {
1803 loge("Setting MTU size with null iface.");
1804 return;
1805 }
1806
Robert Greenwalt7b816022014-04-18 15:25:25 -07001807 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001808 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001809 mNetd.setMtu(iface, mtu);
1810 } catch (Exception e) {
1811 Slog.e(TAG, "exception in setMtu()" + e);
1812 }
1813 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001814
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001815 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001816 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1817
1818 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001819 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001820 protected int getDefaultTcpRwnd() {
1821 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1822 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001823
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001824 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1825 if (isDefaultNetwork(nai) == false) {
1826 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001827 }
1828
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001829 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1830 String[] values = null;
1831 if (tcpBufferSizes != null) {
1832 values = tcpBufferSizes.split(",");
1833 }
1834
1835 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001836 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001837 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1838 values = tcpBufferSizes.split(",");
1839 }
1840
1841 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1842
1843 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001844 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001845
1846 final String prefix = "/sys/kernel/ipv4/tcp_";
1847 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1848 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1849 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1850 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1851 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1852 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1853 mCurrentTcpBufferSizes = tcpBufferSizes;
1854 } catch (IOException e) {
1855 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001856 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001857
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001858 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001859 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001860 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1861 if (rwndValue != 0) {
1862 SystemProperties.set(sysctlKey, rwndValue.toString());
1863 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001864 }
1865
Mattias Falk8b47b362011-08-23 14:15:13 +02001866 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001867 /*
1868 * Tell the VMs to toss their DNS caches
1869 */
1870 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1871 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001872 /*
1873 * Connectivity events can happen before boot has completed ...
1874 */
1875 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001876 final long ident = Binder.clearCallingIdentity();
1877 try {
1878 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1879 } finally {
1880 Binder.restoreCallingIdentity(ident);
1881 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001882 }
1883
Robert Greenwalt562cc542014-05-15 18:07:26 -07001884 @Override
1885 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001886 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1887 NETWORK_RESTORE_DELAY_PROP_NAME);
1888 if(restoreDefaultNetworkDelayStr != null &&
1889 restoreDefaultNetworkDelayStr.length() != 0) {
1890 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001891 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001892 } catch (NumberFormatException e) {
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001895 // if the system property isn't set, use the value for the apn type
1896 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1897
1898 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1899 (mNetConfigs[networkType] != null)) {
1900 ret = mNetConfigs[networkType].restoreTime;
1901 }
1902 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
1904
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001905 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001906 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001907 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001908 }
1909 return false;
1910 }
1911
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001912 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1913 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1914 final long DIAG_TIME_MS = 5000;
1915 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1916 // Start gathering diagnostic information.
1917 netDiags.add(new NetworkDiagnostics(
1918 nai.network,
1919 new LinkProperties(nai.linkProperties), // Must be a copy.
1920 DIAG_TIME_MS));
1921 }
1922
1923 for (NetworkDiagnostics netDiag : netDiags) {
1924 pw.println();
1925 netDiag.waitForMeasurements();
1926 netDiag.dump(pw);
1927 }
1928 }
1929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001931 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1932 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001933 if (mContext.checkCallingOrSelfPermission(
1934 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001936 pw.println("Permission Denial: can't dump ConnectivityService " +
1937 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1938 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 return;
1940 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001941
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001942 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001943 dumpNetworkDiagnostics(pw);
1944 return;
1945 }
Erik Kline379747a2015-06-05 17:47:34 +09001946
Lorenzo Colittie3805462015-06-03 11:18:24 +09001947 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001948 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001949 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001950 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001951 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001952 pw.println();
1953
Paul Jensen85cf78e2015-06-25 13:25:07 -04001954 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001955 pw.print("Active default network: ");
1956 if (defaultNai == null) {
1957 pw.println("none");
1958 } else {
1959 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001961 pw.println();
1962
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001963 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001964 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001965 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1966 pw.println(nai.toString());
1967 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001968 pw.println(String.format(
1969 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1970 nai.numForegroundNetworkRequests(),
1971 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1972 nai.numBackgroundNetworkRequests(),
1973 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001974 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001975 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1976 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001977 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001978 pw.decreaseIndent();
1979 pw.println("Lingered:");
1980 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001981 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001982 pw.decreaseIndent();
1983 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001984 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001985 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001986 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001987
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001988 pw.println("Metered Interfaces:");
1989 pw.increaseIndent();
1990 for (String value : mMeteredIfaces) {
1991 pw.println(value);
1992 }
1993 pw.decreaseIndent();
1994 pw.println();
1995
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001996 pw.print("Restrict background: ");
1997 pw.println(mRestrictBackground);
1998 pw.println();
1999
Felipe Leme46c4fc32016-05-04 09:21:43 -07002000 pw.println("Status for known UIDs:");
2001 pw.increaseIndent();
2002 final int size = mUidRules.size();
2003 for (int i = 0; i < size; i++) {
2004 final int uid = mUidRules.keyAt(i);
2005 pw.print("UID=");
2006 pw.print(uid);
2007 final int uidRules = mUidRules.get(uid, RULE_NONE);
2008 pw.print(" rules=");
2009 pw.print(uidRulesToString(uidRules));
2010 pw.println();
2011 }
2012 pw.println();
2013 pw.decreaseIndent();
2014
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002015 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002016 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002017 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2018 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002019 }
2020 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002021 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002022
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002023 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002024
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002025 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002026 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002027
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002028 pw.println();
2029 mKeepaliveTracker.dump(pw);
2030
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002031 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002032 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002033
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002034 if (argsContain(args, "--short") == false) {
2035 pw.println();
2036 synchronized (mValidationLogs) {
2037 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002038 for (ValidationLog p : mValidationLogs) {
2039 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002040 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002041 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002042 pw.decreaseIndent();
2043 }
2044 }
Erik Kline7523eb32015-07-09 18:24:03 +09002045
2046 pw.println();
2047 pw.println("mNetworkRequestInfoLogs (most recent first):");
2048 pw.increaseIndent();
2049 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2050 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002051
2052 pw.println();
2053 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2054 pw.increaseIndent();
2055 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2056 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002057
2058 pw.println();
2059 pw.println("NetTransition WakeLock activity (most recent first):");
2060 pw.increaseIndent();
2061 mWakelockLogs.reverseDump(fd, pw, args);
2062 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002066 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002067 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002068 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002069 if (officialNai != null && officialNai.equals(nai)) return true;
2070 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002071 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002072 " - " + nai);
2073 }
2074 return false;
2075 }
2076
Robert Greenwalt42acef32009-08-12 16:08:25 -07002077 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002078 private class NetworkStateTrackerHandler extends Handler {
2079 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002080 super(looper);
2081 }
2082
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002083 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002085 default:
2086 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002087 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002088 handleAsyncChannelHalfConnect(msg);
2089 break;
2090 }
2091 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2092 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2093 if (nai != null) nai.asyncChannel.disconnect();
2094 break;
2095 }
2096 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2097 handleAsyncChannelDisconnected(msg);
2098 break;
2099 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002100 }
2101 return true;
2102 }
2103
2104 private void maybeHandleNetworkAgentMessage(Message msg) {
2105 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2106 if (nai == null) {
2107 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002108 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002109 }
2110 return;
2111 }
2112
2113 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002115 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2116 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002117 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2118 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002119 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002120 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002121 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002122 break;
2123 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002124 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002125 if (VDBG) {
2126 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002127 "; created=" + nai.created +
2128 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002129 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002130 LinkProperties oldLp = nai.linkProperties;
2131 synchronized (nai) {
2132 nai.linkProperties = (LinkProperties)msg.obj;
2133 }
Robin Lee585e2482016-05-01 23:00:00 +01002134 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 break;
2136 }
2137 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002138 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 updateNetworkInfo(nai, info);
2140 break;
2141 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002142 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002143 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002144 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002145 break;
2146 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002147 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002148 try {
2149 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002150 } catch (Exception e) {
2151 // Never crash!
2152 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002153 }
2154 break;
2155 }
2156 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002157 try {
2158 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002159 } catch (Exception e) {
2160 // Never crash!
2161 loge("Exception in removeVpnUidRanges: " + e);
2162 }
2163 break;
2164 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002165 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002166 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2167 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002168 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002169 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002170 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002171 break;
2172 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002173 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002174 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2175 break;
2176 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002177 }
2178 }
2179
2180 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2181 switch (msg.what) {
2182 default:
2183 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002184 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002185 final NetworkAgentInfo nai;
2186 synchronized (mNetworkForNetId) {
2187 nai = mNetworkForNetId.get(msg.arg2);
2188 }
2189 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002190 final boolean valid =
2191 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002192 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002193 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2194 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002195 if (valid != nai.lastValidated) {
2196 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002197 nai.lastValidated = valid;
2198 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002199 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002200 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2201 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002202 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002203 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002204 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002205 Bundle redirectUrlBundle = new Bundle();
2206 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002207 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002208 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002209 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002210 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002211 if (wasValidated && !nai.lastValidated) {
2212 handleNetworkUnvalidated(nai);
2213 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002214 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002215 break;
2216 }
Paul Jensen869868be2014-05-15 10:33:05 -04002217 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002218 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002219 final boolean visible = (msg.arg1 != 0);
2220 final NetworkAgentInfo nai;
2221 synchronized (mNetworkForNetId) {
2222 nai = mNetworkForNetId.get(netId);
2223 }
Calvin On1f64f3f2016-10-11 15:10:46 -07002224 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002225 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002226 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002227 nai.lastCaptivePortalDetected = visible;
2228 nai.everCaptivePortalDetected |= visible;
Calvin On1f64f3f2016-10-11 15:10:46 -07002229 if (nai.lastCaptivePortalDetected &&
2230 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2231 if (DBG) log("Avoiding captive portal network: " + nai.name());
2232 nai.asyncChannel.sendMessage(
2233 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2234 teardownUnneededNetwork(nai);
2235 break;
2236 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002237 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002238 }
2239 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002240 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002241 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002242 if (nai == null) {
2243 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2244 break;
2245 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002246 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002247 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002248 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002249 }
Paul Jensen869868be2014-05-15 10:33:05 -04002250 }
Paul Jensen869868be2014-05-15 10:33:05 -04002251 break;
2252 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002253 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002254 return true;
2255 }
2256
Calvin On1f64f3f2016-10-11 15:10:46 -07002257 private int getCaptivePortalMode() {
2258 return Settings.Global.getInt(mContext.getContentResolver(),
2259 Settings.Global.CAPTIVE_PORTAL_MODE,
2260 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2261 }
2262
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002263 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2264 switch (msg.what) {
2265 default:
2266 return false;
2267 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2268 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2269 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2270 handleLingerComplete(nai);
2271 }
2272 break;
2273 }
2274 }
2275 return true;
2276 }
2277
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002278 @Override
2279 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002280 if (!maybeHandleAsyncChannelMessage(msg) &&
2281 !maybeHandleNetworkMonitorMessage(msg) &&
2282 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002283 maybeHandleNetworkAgentMessage(msg);
2284 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002285 }
2286 }
2287
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002288 private void updateLingerState(NetworkAgentInfo nai, long now) {
2289 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2290 // 2. If the network was lingering and there are now requests, unlinger it.
2291 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2292 // one lingered request, start lingering.
2293 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002294 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002295 if (DBG) log("Unlingering " + nai.name());
2296 nai.unlinger();
2297 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002298 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002299 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002300 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002301 nai.linger();
2302 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2303 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2304 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002305 }
2306
Robert Greenwalt7b816022014-04-18 15:25:25 -07002307 private void handleAsyncChannelHalfConnect(Message msg) {
2308 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002309 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002310 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2311 if (VDBG) log("NetworkFactory connected");
2312 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002313 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002314 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002315 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002316 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002317 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002318 }
2319 } else {
2320 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002321 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002322 }
2323 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2324 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2325 if (VDBG) log("NetworkAgent connected");
2326 // A network agent has requested a connection. Establish the connection.
2327 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2328 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2329 } else {
2330 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002331 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002332 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002333 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002334 synchronized (mNetworkForNetId) {
2335 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002336 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002337 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002338 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002339 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002340 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002341 }
2342 }
2343 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002344
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 private void handleAsyncChannelDisconnected(Message msg) {
2346 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2347 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002348 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002349 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002350 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002351 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002352 // TODO - if we move the logic to the network agent (have them disconnect
2353 // because they lost all their requests or because their score isn't good)
2354 // then they would disconnect organically, report their new state and then
2355 // disconnect the channel.
2356 if (nai.networkInfo.isConnected()) {
2357 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2358 null, null);
2359 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002360 final boolean wasDefault = isDefaultNetwork(nai);
2361 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002362 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002363 // Log default network disconnection before required book-keeping.
2364 // Let rematchAllNetworksAndRequests() below record a new default network event
2365 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2366 // whose timestamps tell how long it takes to recover a default network.
2367 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002368 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002369 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002370 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2371 // by other networks that are already connected. Perhaps that can be done by
2372 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2373 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002374 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002375 mKeepaliveTracker.handleStopAllKeepalives(nai,
2376 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002377 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002378 mNetworkAgentInfos.remove(msg.replyTo);
2379 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002380 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002381 // Remove the NetworkAgent, but don't mark the netId as
2382 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002383 mNetworkForNetId.remove(nai.network.netId);
2384 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002385 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002386 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2387 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002388 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2389 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2390 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002391 sendUpdatedScoreToFactories(request, 0);
2392 }
2393 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002394 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002395 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002396 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002397 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002398 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002399 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002400 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002401 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002402 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002403 if (nai.created) {
2404 // Tell netd to clean up the configuration for this network
2405 // (routing rules, DNS, etc).
2406 // This may be slow as it requires a lot of netd shelling out to ip and
2407 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2408 // after we've rematched networks with requests which should make a potential
2409 // fallback network the default or requested a new network from the
2410 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2411 // long time.
2412 try {
2413 mNetd.removeNetwork(nai.network.netId);
2414 } catch (Exception e) {
2415 loge("Exception removing network: " + e);
2416 }
2417 }
2418 synchronized (mNetworkForNetId) {
2419 mNetIdInUse.delete(nai.network.netId);
2420 }
2421 } else {
2422 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2423 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002424 }
2425 }
2426
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002427 // If this method proves to be too slow then we can maintain a separate
2428 // pendingIntent => NetworkRequestInfo map.
2429 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2430 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2431 Intent intent = pendingIntent.getIntent();
2432 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2433 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2434 if (existingPendingIntent != null &&
2435 existingPendingIntent.getIntent().filterEquals(intent)) {
2436 return entry.getValue();
2437 }
2438 }
2439 return null;
2440 }
2441
2442 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2443 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2444
2445 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2446 if (existingRequest != null) { // remove the existing request.
2447 if (DBG) log("Replacing " + existingRequest.request + " with "
2448 + nri.request + " because their intents matched.");
2449 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2450 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002451 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002452 }
2453
Erik Klineda4bfa82015-04-30 12:58:40 +09002454 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002455 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002456 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002457 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002458 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002459 if (nri.request.networkCapabilities.hasSignalStrength() &&
2460 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2461 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002462 }
2463 }
2464 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002465 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002466 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002467 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002468 }
2469 }
2470
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002471 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2472 int callingUid) {
2473 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2474 if (nri != null) {
2475 handleReleaseNetworkRequest(nri.request, callingUid);
2476 }
2477 }
2478
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002479 // Determines whether the network is the best (or could become the best, if it validated), for
2480 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2481 // on the value of reason:
2482 //
2483 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2484 // then it should be torn down.
2485 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2486 // then it should be lingered.
2487 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2488 final int numRequests;
2489 switch (reason) {
2490 case TEARDOWN:
2491 numRequests = nai.numRequestNetworkRequests();
2492 break;
2493 case LINGER:
2494 numRequests = nai.numForegroundNetworkRequests();
2495 break;
2496 default:
2497 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2498 return true;
2499 }
2500
2501 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002502 return false;
2503 }
Paul Jensene0988542015-06-25 15:30:08 -04002504 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002505 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2506 // Background requests don't affect lingering.
2507 continue;
2508 }
2509
Paul Jensene0988542015-06-25 15:30:08 -04002510 // If this Network is already the highest scoring Network for a request, or if
2511 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002512 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002513 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002514 // Note that this catches two important cases:
2515 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2516 // is currently satisfying the request. This is desirable when
2517 // cellular ends up validating but WiFi does not.
2518 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002519 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002520 // WiFi ends up validating and out scoring cellular.
2521 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2522 nai.getCurrentScoreAsValidated())) {
2523 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002524 }
2525 }
Paul Jensene0988542015-06-25 15:30:08 -04002526 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002527 }
2528
Erik Klineacdd6392016-07-07 16:50:58 +09002529 private NetworkRequestInfo getNriForAppRequest(
2530 NetworkRequest request, int callingUid, String requestedOperation) {
2531 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2532
Robert Greenwalt9258c642014-03-26 16:47:06 -07002533 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002534 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002535 log(String.format("UID %d attempted to %s for unowned request %s",
2536 callingUid, requestedOperation, nri));
2537 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002538 }
Erik Klineacdd6392016-07-07 16:50:58 +09002539 }
2540
2541 return nri;
2542 }
2543
Erik Kline3841a482015-11-25 12:49:38 +09002544 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2545 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2546 nri.request.requestId) == null) {
2547 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2548 }
2549 }
2550
Erik Klineacdd6392016-07-07 16:50:58 +09002551 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2552 final NetworkRequestInfo nri = getNriForAppRequest(
2553 request, callingUid, "release NetworkRequest");
Erik Kline3841a482015-11-25 12:49:38 +09002554 if (nri != null) {
2555 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2556 }
2557 }
Erik Klineacdd6392016-07-07 16:50:58 +09002558
Erik Kline3841a482015-11-25 12:49:38 +09002559 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2560 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2561 if (VDBG || (DBG && nri.request.isRequest())) {
2562 log("releasing " + nri.request + " (" + logCallbackType + ")");
2563 }
Erik Klineacdd6392016-07-07 16:50:58 +09002564 nri.unlinkDeathRecipient();
Erik Kline3841a482015-11-25 12:49:38 +09002565 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002566 synchronized (mUidToNetworkRequestCount) {
2567 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2568 if (requests < 1) {
2569 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2570 nri.mUid);
2571 } else if (requests == 1) {
2572 mUidToNetworkRequestCount.removeAt(
2573 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2574 } else {
2575 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2576 }
2577 }
2578 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2579 if (nri.request.isRequest()) {
2580 boolean wasKept = false;
2581 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2582 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002583 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002584 nai.removeRequest(nri.request.requestId);
2585 if (VDBG) {
2586 log(" Removing from current network " + nai.name() +
2587 ", leaving " + nai.numNetworkRequests() + " requests.");
2588 }
2589 // If there are still lingered requests on this network, don't tear it down,
2590 // but resume lingering instead.
2591 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002592 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002593 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2594 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002595 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002596 wasKept = true;
2597 }
2598 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002599 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2600 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002601 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002602 }
Erik Klineacdd6392016-07-07 16:50:58 +09002603 }
2604
2605 // TODO: remove this code once we know that the Slog.wtf is never hit.
2606 //
2607 // Find all networks that are satisfying this request and remove the request
2608 // from their request lists.
2609 // TODO - it's my understanding that for a request there is only a single
2610 // network satisfying it, so this loop is wasteful
2611 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2612 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2613 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2614 otherNai.name() + ", but mNetworkAgentInfos says " +
2615 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002616 }
2617 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002618
Erik Klineacdd6392016-07-07 16:50:58 +09002619 // Maintain the illusion. When this request arrived, we might have pretended
2620 // that a network connected to serve it, even though the network was already
2621 // connected. Now that this request has gone away, we might have to pretend
2622 // that the network disconnected. LegacyTypeTracker will generate that
2623 // phantom disconnect for this type.
2624 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2625 boolean doRemove = true;
2626 if (wasKept) {
2627 // check if any of the remaining requests for this network are for the
2628 // same legacy type - if so, don't remove the nai
2629 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2630 NetworkRequest otherRequest = nai.requestAt(i);
2631 if (otherRequest.legacyType == nri.request.legacyType &&
2632 otherRequest.isRequest()) {
2633 if (DBG) log(" still have other legacy request - leaving");
2634 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002635 }
2636 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002637 }
2638
Erik Klineacdd6392016-07-07 16:50:58 +09002639 if (doRemove) {
2640 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002641 }
2642 }
Erik Klineacdd6392016-07-07 16:50:58 +09002643
2644 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2645 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2646 nri.request);
2647 }
2648 } else {
2649 // listens don't have a singular affectedNetwork. Check all networks to see
2650 // if this listen request applies and remove it.
2651 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2652 nai.removeRequest(nri.request.requestId);
2653 if (nri.request.networkCapabilities.hasSignalStrength() &&
2654 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2655 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2656 }
2657 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002658 }
Erik Kline3841a482015-11-25 12:49:38 +09002659 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002660 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002661
Lorenzo Colitti18660282016-07-04 12:55:44 +09002662 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002663 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2664 enforceConnectivityInternalPermission();
2665 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2666 accept ? 1 : 0, always ? 1: 0, network));
2667 }
2668
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002669 @Override
2670 public void setAvoidUnvalidated(Network network) {
2671 enforceConnectivityInternalPermission();
2672 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2673 }
2674
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002675 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2676 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2677 " accept=" + accept + " always=" + always);
2678
2679 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2680 if (nai == null) {
2681 // Nothing to do.
2682 return;
2683 }
2684
2685 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002686 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002687 return;
2688 }
2689
2690 if (!nai.networkMisc.explicitlySelected) {
2691 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2692 }
2693
2694 if (accept != nai.networkMisc.acceptUnvalidated) {
2695 int oldScore = nai.getCurrentScore();
2696 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002697 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002698 sendUpdatedScoreToFactories(nai);
2699 }
2700
2701 if (always) {
2702 nai.asyncChannel.sendMessage(
2703 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2704 }
2705
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002706 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002707 // Tell the NetworkAgent to not automatically reconnect to the network.
2708 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2709 // Teardown the nework.
2710 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002711 }
2712
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002713 }
2714
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002715 private void handleSetAvoidUnvalidated(Network network) {
2716 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2717 if (nai == null || nai.lastValidated) {
2718 // Nothing to do. The network either disconnected or revalidated.
2719 return;
2720 }
2721 if (!nai.avoidUnvalidated) {
2722 int oldScore = nai.getCurrentScore();
2723 nai.avoidUnvalidated = true;
2724 rematchAllNetworksAndRequests(nai, oldScore);
2725 sendUpdatedScoreToFactories(nai);
2726 }
2727 }
2728
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002729 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002730 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002731 mHandler.sendMessageDelayed(
2732 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2733 PROMPT_UNVALIDATED_DELAY_MS);
2734 }
2735
Hugo Benichic8e9e122016-09-14 23:23:08 +00002736 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002737 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002738 }
2739
Erik Kline065ab6e2016-10-02 18:02:14 +09002740 private void rematchForAvoidBadWifiUpdate() {
2741 rematchAllNetworksAndRequests(null, 0);
2742 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2743 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2744 sendUpdatedScoreToFactories(nai);
2745 }
2746 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002747 }
2748
Erik Kline065ab6e2016-10-02 18:02:14 +09002749 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002750 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002751 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002752 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002753 if (!configRestrict) {
2754 pw.println("Bad Wi-Fi avoidance: unrestricted");
2755 return;
2756 }
2757
2758 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2759 pw.increaseIndent();
2760 pw.println("Config restrict: " + configRestrict);
2761
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002762 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002763 String description;
2764 // Can't use a switch statement because strings are legal case labels, but null is not.
2765 if ("0".equals(value)) {
2766 description = "get stuck";
2767 } else if (value == null) {
2768 description = "prompt";
2769 } else if ("1".equals(value)) {
2770 description = "avoid";
2771 } else {
2772 description = value + " (?)";
2773 }
2774 pw.println("User setting: " + description);
2775 pw.println("Network overrides:");
2776 pw.increaseIndent();
2777 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2778 if (nai.avoidUnvalidated) {
2779 pw.println(nai.name());
2780 }
2781 }
2782 pw.decreaseIndent();
2783 pw.decreaseIndent();
2784 }
2785
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002786 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2787 final String action;
2788 switch (type) {
2789 case NO_INTERNET:
2790 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2791 break;
2792 case LOST_INTERNET:
2793 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2794 break;
2795 default:
2796 Slog.wtf(TAG, "Unknown notification type " + type);
2797 return;
2798 }
2799
2800 Intent intent = new Intent(action);
2801 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2802 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2803 intent.setClassName("com.android.settings",
2804 "com.android.settings.wifi.WifiNoInternetDialog");
2805
2806 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2807 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2808 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2809 }
2810
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002811 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002812 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002813 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2814
2815 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2816 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002817 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002818 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002819 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2820 return;
2821 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002822 showValidationNotification(nai, NotificationType.NO_INTERNET);
2823 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002824
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002825 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2826 NetworkCapabilities nc = nai.networkCapabilities;
2827 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002828
Erik Kline065ab6e2016-10-02 18:02:14 +09002829 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002830 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002831 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2832 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002833 }
2834
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002835 private class InternalHandler extends Handler {
2836 public InternalHandler(Looper looper) {
2837 super(looper);
2838 }
2839
2840 @Override
2841 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002842 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002843 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002844 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002845 handleNetworkTransitionWakelockRelease(msg.what, msg.arg1);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002846 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002847 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002848 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002849 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002850 break;
2851 }
Jason Monkdecd2952013-10-10 14:02:51 -04002852 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002853 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002854 break;
2855 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002856 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002857 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2858 break;
2859 }
2860 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2861 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002862 break;
2863 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002864 case EVENT_REGISTER_NETWORK_AGENT: {
2865 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2866 break;
2867 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002868 case EVENT_REGISTER_NETWORK_REQUEST:
2869 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002870 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002871 break;
2872 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002873 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2874 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002875 handleRegisterNetworkRequestWithIntent(msg);
2876 break;
2877 }
Erik Kline3841a482015-11-25 12:49:38 +09002878 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2879 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2880 handleTimedOutNetworkRequest(nri);
2881 break;
2882 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002883 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2884 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2885 break;
2886 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002887 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002888 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002889 break;
2890 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002891 case EVENT_SET_ACCEPT_UNVALIDATED: {
2892 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2893 break;
2894 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002895 case EVENT_SET_AVOID_UNVALIDATED: {
2896 handleSetAvoidUnvalidated((Network) msg.obj);
2897 break;
2898 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002899 case EVENT_PROMPT_UNVALIDATED: {
2900 handlePromptUnvalidated((Network) msg.obj);
2901 break;
2902 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002903 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2904 handleMobileDataAlwaysOn();
2905 break;
2906 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002907 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2908 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2909 mKeepaliveTracker.handleStartKeepalive(msg);
2910 break;
2911 }
2912 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2913 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2914 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2915 int slot = msg.arg1;
2916 int reason = msg.arg2;
2917 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2918 break;
2919 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002920 case EVENT_SYSTEM_READY: {
2921 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2922 nai.networkMonitor.systemReady = true;
2923 }
2924 break;
2925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
2927 }
2928 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002929
2930 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002931 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002932 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002933 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002934 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002935 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002936 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002937 } else {
2938 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2939 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002940 }
2941
2942 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002943 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002944 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002945 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002946
2947 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002948 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002949 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002950 } else {
2951 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2952 }
2953 }
2954
2955 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002956 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002957 public int getLastTetherError(String iface) {
2958 enforceTetherAccessPermission();
2959
2960 if (isTetheringSupported()) {
2961 return mTethering.getLastTetherError(iface);
2962 } else {
2963 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2964 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002965 }
2966
2967 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002968 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002969 public String[] getTetherableUsbRegexs() {
2970 enforceTetherAccessPermission();
2971 if (isTetheringSupported()) {
2972 return mTethering.getTetherableUsbRegexs();
2973 } else {
2974 return new String[0];
2975 }
2976 }
2977
Lorenzo Colitti18660282016-07-04 12:55:44 +09002978 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002979 public String[] getTetherableWifiRegexs() {
2980 enforceTetherAccessPermission();
2981 if (isTetheringSupported()) {
2982 return mTethering.getTetherableWifiRegexs();
2983 } else {
2984 return new String[0];
2985 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002986 }
2987
Lorenzo Colitti18660282016-07-04 12:55:44 +09002988 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002989 public String[] getTetherableBluetoothRegexs() {
2990 enforceTetherAccessPermission();
2991 if (isTetheringSupported()) {
2992 return mTethering.getTetherableBluetoothRegexs();
2993 } else {
2994 return new String[0];
2995 }
2996 }
2997
Lorenzo Colitti18660282016-07-04 12:55:44 +09002998 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002999 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003000 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003001 if (isTetheringSupported()) {
3002 return mTethering.setUsbTethering(enable);
3003 } else {
3004 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3005 }
3006 }
3007
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003008 // TODO - move iface listing, queries, etc to new module
3009 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003010 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003011 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003012 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003013 return mTethering.getTetherableIfaces();
3014 }
3015
Lorenzo Colitti18660282016-07-04 12:55:44 +09003016 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003017 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003018 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003019 return mTethering.getTetheredIfaces();
3020 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003021
Lorenzo Colitti18660282016-07-04 12:55:44 +09003022 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003023 public String[] getTetheringErroredIfaces() {
3024 enforceTetherAccessPermission();
3025 return mTethering.getErroredIfaces();
3026 }
3027
Lorenzo Colitti18660282016-07-04 12:55:44 +09003028 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003029 public String[] getTetheredDhcpRanges() {
3030 enforceConnectivityInternalPermission();
3031 return mTethering.getTetheredDhcpRanges();
3032 }
3033
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003034 // if ro.tether.denied = true we default to no tethering
3035 // gservices could set the secure setting to 1 though to enable it on a build where it
3036 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003037 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003038 public boolean isTetheringSupported() {
3039 enforceTetherAccessPermission();
3040 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003041 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003042 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3043 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003044 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
Erik Klined781fba2017-01-23 13:01:58 +09003045 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003046 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003047
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003048 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09003049 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003050 ConnectivityManager.enforceTetherChangePermission(mContext);
3051 if (!isTetheringSupported()) {
3052 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3053 return;
3054 }
3055 mTethering.startTethering(type, receiver, showProvisioningUi);
3056 }
3057
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003058 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003059 public void stopTethering(int type) {
3060 ConnectivityManager.enforceTetherChangePermission(mContext);
3061 mTethering.stopTethering(type);
3062 }
3063
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003064 // Called when we lose the default network and have no replacement yet.
3065 // This will automatically be cleared after X seconds or a new default network
3066 // becomes CONNECTED, whichever happens first. The timer is started by the
3067 // first caller and not restarted by subsequent callers.
3068 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003069 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003070 synchronized (this) {
3071 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003072 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003073 mNetTransitionWakeLock.acquire();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003074 mWakelockLogs.log(String.format("ACQUIRE %d for %s", serialNum, forWhom));
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003075 }
3076 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003077 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003078 mNetTransitionWakeLockTimeout);
3079 return;
3080 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003081
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003082 private void handleNetworkTransitionWakelockRelease(int eventId, int wantSerialNumber) {
3083 final int serialNumber;
3084 final boolean isHeld;
3085 final boolean release;
3086 synchronized (this) {
3087 serialNumber = mNetTransitionWakeLockSerialNumber;
3088 isHeld = mNetTransitionWakeLock.isHeld();
3089 release = (wantSerialNumber == serialNumber) && isHeld;
3090 if (release) {
3091 mNetTransitionWakeLock.release();
3092 }
3093 }
3094 final String result;
3095 if (release) {
3096 result = "released";
3097 } else if (!isHeld) {
3098 result = "already released";
3099 } else {
3100 result = String.format("not released (serial number was %d)", serialNumber);
3101 }
3102 String msg = String.format(
3103 "RELEASE %d by %s: %s", wantSerialNumber, eventName(eventId), result);
3104 mWakelockLogs.log(msg);
3105 if (DBG) log(msg);
3106 }
3107
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003108 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003109 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003110 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003111 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003112 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003113 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003114 }
3115
Lorenzo Colitti18660282016-07-04 12:55:44 +09003116 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003117 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003118 enforceAccessPermission();
3119 enforceInternetPermission();
3120
Paul Jensenbfd17b72015-04-07 12:43:13 -04003121 NetworkAgentInfo nai;
3122 if (network == null) {
3123 nai = getDefaultNetwork();
3124 } else {
3125 nai = getNetworkAgentInfoForNetwork(network);
3126 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003127 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3128 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3129 return;
3130 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003131 // Revalidate if the app report does not match our current validated state.
3132 if (hasConnectivity == nai.lastValidated) return;
3133 final int uid = Binder.getCallingUid();
3134 if (DBG) {
3135 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3136 ") by " + uid);
3137 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003138 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003139 // Validating a network that has not yet connected could result in a call to
3140 // rematchNetworkAndRequests() which is not meant to work on such networks.
3141 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003142
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003143 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003144
3145 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3146 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003147 }
3148
Paul Jensencee9b512015-05-06 07:32:40 -04003149 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003150 // this information is already available as a world read/writable jvm property
3151 // so this API change wouldn't have a benifit. It also breaks the passing
3152 // of proxy info to all the JVMs.
3153 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003154 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003155 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003156 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3157 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003158 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003159 }
3160
Lorenzo Colitti18660282016-07-04 12:55:44 +09003161 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003162 public ProxyInfo getProxyForNetwork(Network network) {
3163 if (network == null) return getDefaultProxy();
3164 final ProxyInfo globalProxy = getGlobalProxy();
3165 if (globalProxy != null) return globalProxy;
3166 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3167 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3168 // caller may not have.
3169 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3170 if (nai == null) return null;
3171 synchronized (nai) {
3172 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3173 if (proxyInfo == null) return null;
3174 return new ProxyInfo(proxyInfo);
3175 }
3176 }
3177
Paul Jensene0bef712014-12-10 15:12:18 -05003178 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3179 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3180 // proxy is null then there is no proxy in place).
3181 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3182 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3183 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3184 proxy = null;
3185 }
3186 return proxy;
3187 }
3188
3189 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3190 // better for determining if a new proxy broadcast is necessary:
3191 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3192 // avoid unnecessary broadcasts.
3193 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3194 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3195 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3196 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3197 // all set.
3198 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3199 a = canonicalizeProxyInfo(a);
3200 b = canonicalizeProxyInfo(b);
3201 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3202 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3203 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3204 }
3205
Jason Monk207900c2014-04-25 15:00:09 -04003206 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003207 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003208
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003209 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003210 if (proxyProperties == mGlobalProxy) return;
3211 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3212 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3213
3214 String host = "";
3215 int port = 0;
3216 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003217 String pacFileUrl = "";
3218 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003219 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003220 if (!proxyProperties.isValid()) {
3221 if (DBG)
3222 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3223 return;
3224 }
Jason Monk207900c2014-04-25 15:00:09 -04003225 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003226 host = mGlobalProxy.getHost();
3227 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003228 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003229 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003230 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003231 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003232 } else {
3233 mGlobalProxy = null;
3234 }
3235 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003236 final long token = Binder.clearCallingIdentity();
3237 try {
3238 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3239 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3240 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3241 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003242 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003243 } finally {
3244 Binder.restoreCallingIdentity(token);
3245 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003246
Jason Monkcf0f97a2014-10-02 15:39:38 -04003247 if (mGlobalProxy == null) {
3248 proxyProperties = mDefaultProxy;
3249 }
3250 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003251 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003252 }
3253
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003254 private void loadGlobalProxy() {
3255 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003256 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3257 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3258 String exclList = Settings.Global.getString(res,
3259 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003260 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3261 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003262 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003263 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003264 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003265 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003266 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003267 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003268 if (!proxyProperties.isValid()) {
3269 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3270 return;
3271 }
3272
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003273 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003274 mGlobalProxy = proxyProperties;
3275 }
3276 }
3277 }
3278
Jason Monk207900c2014-04-25 15:00:09 -04003279 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003280 // this information is already available as a world read/writable jvm property
3281 // so this API change wouldn't have a benifit. It also breaks the passing
3282 // of proxy info to all the JVMs.
3283 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003284 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003285 return mGlobalProxy;
3286 }
3287 }
3288
Jason Monk207900c2014-04-25 15:00:09 -04003289 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003290 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003291 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003292 proxy = null;
3293 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003294 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003295 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003296 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003297 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003298 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3299 return;
3300 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003301
3302 // This call could be coming from the PacManager, containing the port of the local
3303 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3304 // global (to get the correct local port), and send a broadcast.
3305 // TODO: Switch PacManager to have its own message to send back rather than
3306 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003307 if ((mGlobalProxy != null) && (proxy != null)
3308 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003309 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3310 mGlobalProxy = proxy;
3311 sendProxyBroadcast(mGlobalProxy);
3312 return;
3313 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003314 mDefaultProxy = proxy;
3315
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003316 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003317 if (!mDefaultProxyDisabled) {
3318 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003319 }
3320 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003321 }
3322
Paul Jensene0bef712014-12-10 15:12:18 -05003323 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3324 // This method gets called when any network changes proxy, but the broadcast only ever contains
3325 // the default proxy (even if it hasn't changed).
3326 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3327 // world where an app might be bound to a non-default network.
3328 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3329 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3330 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3331
3332 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3333 sendProxyBroadcast(getDefaultProxy());
3334 }
3335 }
3336
Robert Greenwalt434203a2010-10-11 16:00:27 -07003337 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003338 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3339 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003340 if (!TextUtils.isEmpty(proxy)) {
3341 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003342 if (data.length == 0) {
3343 return;
3344 }
3345
Robert Greenwalt434203a2010-10-11 16:00:27 -07003346 String proxyHost = data[0];
3347 int proxyPort = 8080;
3348 if (data.length > 1) {
3349 try {
3350 proxyPort = Integer.parseInt(data[1]);
3351 } catch (NumberFormatException e) {
3352 return;
3353 }
3354 }
Jason Monk207900c2014-04-25 15:00:09 -04003355 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003356 setGlobalProxy(p);
3357 }
3358 }
3359
Jason Monk207900c2014-04-25 15:00:09 -04003360 private void sendProxyBroadcast(ProxyInfo proxy) {
3361 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003362 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003363 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003364 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003365 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3366 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003367 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003368 final long ident = Binder.clearCallingIdentity();
3369 try {
3370 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3371 } finally {
3372 Binder.restoreCallingIdentity(ident);
3373 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003374 }
3375
3376 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003377 final private HashMap<Uri, Integer> mUriEventMap;
3378 final private Context mContext;
3379 final private Handler mHandler;
3380
3381 SettingsObserver(Context context, Handler handler) {
3382 super(null);
3383 mUriEventMap = new HashMap<Uri, Integer>();
3384 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003385 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003386 }
3387
Erik Klineda4bfa82015-04-30 12:58:40 +09003388 void observe(Uri uri, int what) {
3389 mUriEventMap.put(uri, what);
3390 final ContentResolver resolver = mContext.getContentResolver();
3391 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003392 }
3393
3394 @Override
3395 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003396 Slog.wtf(TAG, "Should never be reached.");
3397 }
3398
3399 @Override
3400 public void onChange(boolean selfChange, Uri uri) {
3401 final Integer what = mUriEventMap.get(uri);
3402 if (what != null) {
3403 mHandler.obtainMessage(what.intValue()).sendToTarget();
3404 } else {
3405 loge("No matching event to send for URI=" + uri);
3406 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003407 }
3408 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003409
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003410 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003411 Slog.d(TAG, s);
3412 }
3413
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003414 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003415 Slog.e(TAG, s);
3416 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003417
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003418 private static <T> T checkNotNull(T value, String message) {
3419 if (value == null) {
3420 throw new NullPointerException(message);
3421 }
3422 return value;
3423 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003424
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003425 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003426 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003427 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3428 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3429 *
3430 * @param oldPackage Package name of the application which currently controls VPN, which will
3431 * be replaced. If there is no such application, this should should either be
3432 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3433 * @param newPackage Package name of the application which should gain control of VPN, or
3434 * {@code null} to disable.
3435 * @param userId User for whom to prepare the new VPN.
3436 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003437 * @hide
3438 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003439 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003440 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3441 int userId) {
3442 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003443 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003444
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003445 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003446 Vpn vpn = mVpns.get(userId);
3447 if (vpn != null) {
3448 return vpn.prepare(oldPackage, newPackage);
3449 } else {
3450 return false;
3451 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003452 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003453 }
3454
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003455 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003456 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3457 * This method is used by system-privileged apps.
3458 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3459 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3460 *
3461 * @param packageName The package for which authorization state should change.
3462 * @param userId User for whom {@code packageName} is installed.
3463 * @param authorized {@code true} if this app should be able to start a VPN connection without
3464 * explicit user approval, {@code false} if not.
3465 *
Jeff Davidson05542602014-08-11 14:07:27 -07003466 * @hide
3467 */
3468 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003469 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3470 enforceCrossUserPermission(userId);
3471
Jeff Davidson05542602014-08-11 14:07:27 -07003472 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003473 Vpn vpn = mVpns.get(userId);
3474 if (vpn != null) {
3475 vpn.setPackageAuthorization(packageName, authorized);
3476 }
Jeff Davidson05542602014-08-11 14:07:27 -07003477 }
3478 }
3479
3480 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003481 * Configure a TUN interface and return its file descriptor. Parameters
3482 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003483 * and not available in ConnectivityManager. Permissions are checked in
3484 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003485 * @hide
3486 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003487 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003488 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003489 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003490 int user = UserHandle.getUserId(Binder.getCallingUid());
3491 synchronized(mVpns) {
3492 return mVpns.get(user).establish(config);
3493 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003494 }
3495
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003496 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003497 * Start legacy VPN, controlling native daemons as needed. Creates a
3498 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003499 */
3500 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003501 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003502 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003503 final LinkProperties egress = getActiveLinkProperties();
3504 if (egress == null) {
3505 throw new IllegalStateException("Missing active network connection");
3506 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003507 int user = UserHandle.getUserId(Binder.getCallingUid());
3508 synchronized(mVpns) {
3509 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3510 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003511 }
3512
3513 /**
3514 * Return the information of the ongoing legacy VPN. This method is used
3515 * by VpnSettings and not available in ConnectivityManager. Permissions
3516 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003517 */
3518 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003519 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3520 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003521
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003522 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003523 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003524 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003525 }
3526
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003527 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003528 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3529 * and not available in ConnectivityManager.
3530 */
3531 @Override
3532 public VpnInfo[] getAllVpnInfo() {
3533 enforceConnectivityInternalPermission();
3534 if (mLockdownEnabled) {
3535 return new VpnInfo[0];
3536 }
3537
3538 synchronized(mVpns) {
3539 List<VpnInfo> infoList = new ArrayList<>();
3540 for (int i = 0; i < mVpns.size(); i++) {
3541 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3542 if (info != null) {
3543 infoList.add(info);
3544 }
3545 }
3546 return infoList.toArray(new VpnInfo[infoList.size()]);
3547 }
3548 }
3549
3550 /**
3551 * @return VPN information for accounting, or null if we can't retrieve all required
3552 * information, e.g primary underlying iface.
3553 */
3554 @Nullable
3555 private VpnInfo createVpnInfo(Vpn vpn) {
3556 VpnInfo info = vpn.getVpnInfo();
3557 if (info == null) {
3558 return null;
3559 }
3560 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3561 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3562 // the underlyingNetworks list.
3563 if (underlyingNetworks == null) {
3564 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3565 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3566 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3567 }
3568 } else if (underlyingNetworks.length > 0) {
3569 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3570 if (linkProperties != null) {
3571 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3572 }
3573 }
3574 return info.primaryUnderlyingIface == null ? null : info;
3575 }
3576
3577 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003578 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3579 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003580 * Permissions are checked in Vpn class.
3581 * @hide
3582 */
3583 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003584 public VpnConfig getVpnConfig(int userId) {
3585 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003586 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003587 Vpn vpn = mVpns.get(userId);
3588 if (vpn != null) {
3589 return vpn.getVpnConfig();
3590 } else {
3591 return null;
3592 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003593 }
3594 }
3595
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003596 @Override
3597 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003598 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3599 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3600 return false;
3601 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003602
3603 // Tear down existing lockdown if profile was removed
3604 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3605 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003606 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3607 if (profileTag == null) {
3608 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3609 return false;
3610 }
3611 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003612 final VpnProfile profile = VpnProfile.decode(
3613 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003614 if (profile == null) {
3615 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3616 setLockdownTracker(null);
3617 return true;
3618 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003619 int user = UserHandle.getUserId(Binder.getCallingUid());
3620 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003621 Vpn vpn = mVpns.get(user);
3622 if (vpn == null) {
3623 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3624 return false;
3625 }
3626 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003627 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003628 } else {
3629 setLockdownTracker(null);
3630 }
3631
3632 return true;
3633 }
3634
3635 /**
3636 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3637 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3638 */
3639 private void setLockdownTracker(LockdownVpnTracker tracker) {
3640 // Shutdown any existing tracker
3641 final LockdownVpnTracker existing = mLockdownTracker;
3642 mLockdownTracker = null;
3643 if (existing != null) {
3644 existing.shutdown();
3645 }
3646
3647 try {
3648 if (tracker != null) {
3649 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003650 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003651 mLockdownTracker = tracker;
3652 mLockdownTracker.init();
3653 } else {
3654 mNetd.setFirewallEnabled(false);
3655 }
3656 } catch (RemoteException e) {
3657 // ignored; NMS lives inside system_server
3658 }
3659 }
3660
3661 private void throwIfLockdownEnabled() {
3662 if (mLockdownEnabled) {
3663 throw new IllegalStateException("Unavailable in lockdown mode");
3664 }
3665 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003666
Robin Lee244ce8e2016-01-05 18:03:46 +00003667 /**
Robin Lee17e61832016-05-09 13:46:28 +01003668 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3669 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003670 *
Robin Lee17e61832016-05-09 13:46:28 +01003671 * @return {@code true} if the service was started, the service was already connected, or there
3672 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003673 */
Robin Lee17e61832016-05-09 13:46:28 +01003674 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003675 synchronized (mVpns) {
3676 Vpn vpn = mVpns.get(userId);
3677 if (vpn == null) {
3678 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3679 // exists already.
3680 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3681 return false;
3682 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003683
Robin Lee812800c2016-05-13 15:38:08 +01003684 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003685 }
3686 }
3687
3688 @Override
Robin Leedc679712016-05-03 13:23:03 +01003689 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003690 enforceConnectivityInternalPermission();
3691 enforceCrossUserPermission(userId);
3692
3693 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3694 if (LockdownVpnTracker.isEnabled()) {
3695 return false;
3696 }
3697
Robin Lee244ce8e2016-01-05 18:03:46 +00003698 synchronized (mVpns) {
3699 Vpn vpn = mVpns.get(userId);
3700 if (vpn == null) {
3701 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3702 return false;
3703 }
Robin Lee17e61832016-05-09 13:46:28 +01003704 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003705 return false;
3706 }
Robin Lee17e61832016-05-09 13:46:28 +01003707 if (!startAlwaysOnVpn(userId)) {
3708 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003709 return false;
3710 }
Robin Lee17e61832016-05-09 13:46:28 +01003711
Robin Lee812800c2016-05-13 15:38:08 +01003712 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003713 }
3714 return true;
3715 }
3716
3717 @Override
3718 public String getAlwaysOnVpnPackage(int userId) {
3719 enforceConnectivityInternalPermission();
3720 enforceCrossUserPermission(userId);
3721
3722 synchronized (mVpns) {
3723 Vpn vpn = mVpns.get(userId);
3724 if (vpn == null) {
3725 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3726 return null;
3727 }
3728 return vpn.getAlwaysOnPackage();
3729 }
3730 }
3731
Wink Savilleab9321d2013-06-29 21:10:57 -07003732 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003733 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003734 // TODO: Remove? Any reason to trigger a provisioning check?
3735 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003736 }
3737
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003738 /** Location to an updatable file listing carrier provisioning urls.
3739 * An example:
3740 *
3741 * <?xml version="1.0" encoding="utf-8"?>
3742 * <provisioningUrls>
3743 * <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 -07003744 * </provisioningUrls>
3745 */
3746 private static final String PROVISIONING_URL_PATH =
3747 "/data/misc/radio/provisioning_urls.xml";
3748 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003749
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003750 /** XML tag for root element. */
3751 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3752 /** XML tag for individual url */
3753 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003754 /** XML attribute for mcc */
3755 private static final String ATTR_MCC = "mcc";
3756 /** XML attribute for mnc */
3757 private static final String ATTR_MNC = "mnc";
3758
Paul Jensen434dde82015-06-11 09:43:30 -04003759 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003760 FileReader fileReader = null;
3761 XmlPullParser parser = null;
3762 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003763
3764 try {
3765 fileReader = new FileReader(mProvisioningUrlFile);
3766 parser = Xml.newPullParser();
3767 parser.setInput(fileReader);
3768 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3769
3770 while (true) {
3771 XmlUtils.nextElement(parser);
3772
3773 String element = parser.getName();
3774 if (element == null) break;
3775
Paul Jensen434dde82015-06-11 09:43:30 -04003776 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003777 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3778 try {
3779 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3780 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3781 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3782 parser.next();
3783 if (parser.getEventType() == XmlPullParser.TEXT) {
3784 return parser.getText();
3785 }
3786 }
3787 }
3788 } catch (NumberFormatException e) {
3789 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3790 }
3791 }
3792 }
3793 return null;
3794 } catch (FileNotFoundException e) {
3795 loge("Carrier Provisioning Urls file not found");
3796 } catch (XmlPullParserException e) {
3797 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3798 } catch (IOException e) {
3799 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3800 } finally {
3801 if (fileReader != null) {
3802 try {
3803 fileReader.close();
3804 } catch (IOException e) {}
3805 }
3806 }
3807 return null;
3808 }
3809
Wink Saville42d4f082013-07-20 20:31:59 -07003810 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003811 public String getMobileProvisioningUrl() {
3812 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003813 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003814 if (TextUtils.isEmpty(url)) {
3815 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003816 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003817 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003818 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003819 }
Wink Saville8cf35602013-07-10 23:00:07 -07003820 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003821 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003822 String phoneNumber = mTelephonyManager.getLine1Number();
3823 if (TextUtils.isEmpty(phoneNumber)) {
3824 phoneNumber = "0000000000";
3825 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003826 url = String.format(url,
3827 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3828 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003829 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003830 }
3831
Wink Savilleab9321d2013-06-29 21:10:57 -07003832 return url;
3833 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003834
Wink Saville948282b2013-08-29 08:55:16 -07003835 @Override
3836 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003837 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003838 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003839 final long ident = Binder.clearCallingIdentity();
3840 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003841 // Concatenate the range of types onto the range of NetIDs.
3842 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3843 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003844 } finally {
3845 Binder.restoreCallingIdentity(ident);
3846 }
Wink Saville948282b2013-08-29 08:55:16 -07003847 }
Wink Saville7788c612013-08-29 14:57:08 -07003848
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003849 @Override
3850 public void setAirplaneMode(boolean enable) {
3851 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003852 final long ident = Binder.clearCallingIdentity();
3853 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003854 final ContentResolver cr = mContext.getContentResolver();
3855 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3856 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3857 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003858 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003859 } finally {
3860 Binder.restoreCallingIdentity(ident);
3861 }
3862 }
3863
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003864 private void onUserStart(int userId) {
3865 synchronized(mVpns) {
3866 Vpn userVpn = mVpns.get(userId);
3867 if (userVpn != null) {
3868 loge("Starting user already has a VPN");
3869 return;
3870 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003871 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003872 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003873
3874 final ContentResolver cr = mContext.getContentResolver();
3875 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3876 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3877 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3878 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3879 if (alwaysOnPackage != null) {
3880 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3881 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003882 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003883 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3884 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003885 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003886 }
3887
3888 private void onUserStop(int userId) {
3889 synchronized(mVpns) {
3890 Vpn userVpn = mVpns.get(userId);
3891 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003892 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003893 return;
3894 }
Robin Lee17e61832016-05-09 13:46:28 +01003895 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003896 mVpns.delete(userId);
3897 }
3898 }
3899
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003900 private void onUserAdded(int userId) {
3901 synchronized(mVpns) {
3902 final int vpnsSize = mVpns.size();
3903 for (int i = 0; i < vpnsSize; i++) {
3904 Vpn vpn = mVpns.valueAt(i);
3905 vpn.onUserAdded(userId);
3906 }
3907 }
3908 }
3909
3910 private void onUserRemoved(int userId) {
3911 synchronized(mVpns) {
3912 final int vpnsSize = mVpns.size();
3913 for (int i = 0; i < vpnsSize; i++) {
3914 Vpn vpn = mVpns.valueAt(i);
3915 vpn.onUserRemoved(userId);
3916 }
3917 }
3918 }
3919
Robin Lee89e7a692016-02-29 14:38:17 +00003920 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003921 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3922 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3923 updateLockdownVpn();
3924 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003925 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003926 }
3927 }
3928
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003929 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3930 @Override
3931 public void onReceive(Context context, Intent intent) {
3932 final String action = intent.getAction();
3933 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3934 if (userId == UserHandle.USER_NULL) return;
3935
Robin Lee323f29d2016-05-04 16:38:06 +01003936 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003937 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003938 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003939 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003940 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3941 onUserAdded(userId);
3942 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3943 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003944 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3945 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003946 }
3947 }
3948 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003949
Robin Lee95204e02017-01-27 11:59:22 +00003950 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3951 @Override
3952 public void onReceive(Context context, Intent intent) {
3953 // Try creating lockdown tracker, since user present usually means
3954 // unlocked keystore.
3955 updateLockdownVpn();
3956 mContext.unregisterReceiver(this);
3957 }
3958 };
3959
Robert Greenwalta67be032014-05-16 15:49:14 -07003960 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3961 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003962 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3963 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003964
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003965 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3966 // Map from UID to number of NetworkRequests that UID has filed.
3967 @GuardedBy("mUidToNetworkRequestCount")
3968 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3969
Robert Greenwalta67be032014-05-16 15:49:14 -07003970 private static class NetworkFactoryInfo {
3971 public final String name;
3972 public final Messenger messenger;
3973 public final AsyncChannel asyncChannel;
3974
3975 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3976 this.name = name;
3977 this.messenger = messenger;
3978 this.asyncChannel = asyncChannel;
3979 }
3980 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003981
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003982 private void ensureNetworkRequestHasType(NetworkRequest request) {
3983 if (request.type == NetworkRequest.Type.NONE) {
3984 throw new IllegalArgumentException(
3985 "All NetworkRequests in ConnectivityService must have a type");
3986 }
3987 }
3988
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003989 /**
3990 * Tracks info about the requester.
3991 * Also used to notice when the calling process dies so we can self-expire
3992 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003993 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003995 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003996 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003997 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003998 final int mPid;
3999 final int mUid;
4000 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004001
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004002 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004003 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004004 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004005 mPendingIntent = pi;
4006 messenger = null;
4007 mBinder = null;
4008 mPid = getCallingPid();
4009 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004010 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004011 }
4012
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004013 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004014 super();
4015 messenger = m;
4016 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004017 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004018 mBinder = binder;
4019 mPid = getCallingPid();
4020 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004021 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004022 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004023
4024 try {
4025 mBinder.linkToDeath(this, 0);
4026 } catch (RemoteException e) {
4027 binderDied();
4028 }
4029 }
4030
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004031 private void enforceRequestCountLimit() {
4032 synchronized (mUidToNetworkRequestCount) {
4033 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4034 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4035 throw new IllegalArgumentException("Too many NetworkRequests filed");
4036 }
4037 mUidToNetworkRequestCount.put(mUid, networkRequests);
4038 }
4039 }
4040
Robert Greenwalt9258c642014-03-26 16:47:06 -07004041 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004042 if (mBinder != null) {
4043 mBinder.unlinkToDeath(this, 0);
4044 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004045 }
4046
4047 public void binderDied() {
4048 log("ConnectivityService NetworkRequestInfo binderDied(" +
4049 request + ", " + mBinder + ")");
4050 releaseNetworkRequest(request);
4051 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004052
4053 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004054 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004055 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004056 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004057 }
4058
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004059 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4060 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4061 if (badCapability != null) {
4062 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004063 }
4064 }
4065
Erik Kline9d598e12015-07-13 16:37:51 +09004066 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004067 final SortedSet<Integer> thresholds = new TreeSet();
4068 synchronized (nai) {
4069 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4070 if (nri.request.networkCapabilities.hasSignalStrength() &&
4071 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4072 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4073 }
4074 }
4075 }
Erik Kline9d598e12015-07-13 16:37:51 +09004076 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004077 }
4078
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004079 private void updateSignalStrengthThresholds(
4080 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4081 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004082 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004083 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4084
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004085 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004086 String detail;
4087 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4088 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4089 } else {
4090 detail = reason;
4091 }
4092 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4093 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4094 }
4095
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004096 nai.asyncChannel.sendMessage(
4097 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004098 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004099 }
4100
Robert Greenwalt9258c642014-03-26 16:47:06 -07004101 @Override
4102 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004103 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004104 final NetworkRequest.Type type = (networkCapabilities == null)
4105 ? NetworkRequest.Type.TRACK_DEFAULT
4106 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004107 // If the requested networkCapabilities is null, take them instead from
4108 // the default network request. This allows callers to keep track of
4109 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004110 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004111 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4112 enforceAccessPermission();
4113 } else {
4114 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4115 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004116 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4117 // of the app when the request is filed, but we never change the request if the app
4118 // changes network state. http://b/29964605
4119 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004120 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004121 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004122
Etan Cohenba07c8c2017-02-05 10:42:27 -08004123 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004124 throw new IllegalArgumentException("Bad timeout specified");
4125 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004126
Etan Cohenddb9ef02015-11-18 10:56:15 -08004127 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4128 .equals(networkCapabilities.getNetworkSpecifier())) {
4129 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4130 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4131 }
4132
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004133 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004134 nextNetworkRequestId(), type);
4135 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004136 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004137
4138 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004139 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004141 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004142 }
4143 return networkRequest;
4144 }
4145
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004146 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004147 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004148 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004149 } else {
4150 enforceChangePermission();
4151 }
4152 }
4153
fenglub15e72b2015-03-20 11:29:56 -07004154 @Override
fengludb571472015-04-21 17:12:05 -07004155 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004156 enforceAccessPermission();
4157 NetworkAgentInfo nai = null;
4158 if (network == null) {
4159 return false;
4160 }
4161 synchronized (mNetworkForNetId) {
4162 nai = mNetworkForNetId.get(network.netId);
4163 }
4164 if (nai != null) {
4165 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4166 return true;
4167 }
4168 return false;
4169 }
4170
Felipe Lemeee27cab2016-06-20 16:36:29 -07004171 private boolean isSystem(int uid) {
4172 return uid < Process.FIRST_APPLICATION_UID;
4173 }
fenglub15e72b2015-03-20 11:29:56 -07004174
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004175 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004176 final int uid = Binder.getCallingUid();
4177 if (isSystem(uid)) {
4178 return;
4179 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004180 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004181 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004182 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004183 synchronized(mRulesLock) {
4184 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4185 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004186 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4187 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004188 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004189 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004190 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004191 }
4192 }
4193 }
4194
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 @Override
4196 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4197 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004198 checkNotNull(operation, "PendingIntent cannot be null.");
4199 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4200 enforceNetworkRequestPermissions(networkCapabilities);
4201 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004202 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004203
4204 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004205 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4206 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004207 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004208 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4209 nri));
4210 return networkRequest;
4211 }
4212
Jeremy Joslin79294842014-12-03 17:15:28 -08004213 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4214 mHandler.sendMessageDelayed(
4215 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4216 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4217 }
4218
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004219 @Override
4220 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004221 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004222 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4223 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224 }
4225
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004226 // In order to implement the compatibility measure for pre-M apps that call
4227 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4228 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4229 // This ensures it has permission to do so.
4230 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4231 if (nc == null) {
4232 return false;
4233 }
4234 int[] transportTypes = nc.getTransportTypes();
4235 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4236 return false;
4237 }
4238 try {
4239 mContext.enforceCallingOrSelfPermission(
4240 android.Manifest.permission.ACCESS_WIFI_STATE,
4241 "ConnectivityService");
4242 } catch (SecurityException e) {
4243 return false;
4244 }
4245 return true;
4246 }
4247
Robert Greenwalt9258c642014-03-26 16:47:06 -07004248 @Override
4249 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4250 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004251 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4252 enforceAccessPermission();
4253 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004254
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004255 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4256 if (!ConnectivityManager.checkChangePermission(mContext)) {
4257 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4258 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4259 // onLost and onAvailable callbacks when networks move in and out of the background.
4260 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4261 // can't request networks.
4262 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4263 }
4264
4265 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004266 NetworkRequest.Type.LISTEN);
4267 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004268 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004269
4270 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4271 return networkRequest;
4272 }
4273
4274 @Override
4275 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4276 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004277 checkNotNull(operation, "PendingIntent cannot be null.");
4278 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4279 enforceAccessPermission();
4280 }
4281
Erik Kline7523eb32015-07-09 18:24:03 +09004282 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004283 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4284 NetworkRequest.Type.LISTEN);
4285 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004286 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004287
4288 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004289 }
4290
Erik Klineacdd6392016-07-07 16:50:58 +09004291 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004292 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004293 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004294 mHandler.sendMessage(mHandler.obtainMessage(
4295 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004296 }
4297
4298 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004299 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004300 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004301 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4302 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004303 }
4304
Robert Greenwalta67be032014-05-16 15:49:14 -07004305 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004306 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004307 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4308 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4309 }
4310
4311 @Override
4312 public void unregisterNetworkFactory(Messenger messenger) {
4313 enforceConnectivityInternalPermission();
4314 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4315 }
4316
4317 private void handleUnregisterNetworkFactory(Messenger messenger) {
4318 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4319 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004320 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004321 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004322 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004323 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004324 }
4325
Robert Greenwalt7b816022014-04-18 15:25:25 -07004326 /**
4327 * NetworkAgentInfo supporting a request by requestId.
4328 * These have already been vetted (their Capabilities satisfy the request)
4329 * and the are the highest scored network available.
4330 * the are keyed off the Requests requestId.
4331 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004332 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004333 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4334 new SparseArray<NetworkAgentInfo>();
4335
Paul Jensen31a94f42015-02-13 14:18:39 -05004336 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4337 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004338 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4339 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004340 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4341 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4342 // there may not be a strict 1:1 correlation between the two.
4343 @GuardedBy("mNetworkForNetId")
4344 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004345
Robert Greenwalt7b816022014-04-18 15:25:25 -07004346 // NetworkAgentInfo keyed off its connecting messenger
4347 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004348 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004349 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4350 new HashMap<Messenger, NetworkAgentInfo>();
4351
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004352 @GuardedBy("mBlockedAppUids")
4353 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4354
Paul Jensen2c311d62014-11-17 12:34:51 -05004355 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004356 private final NetworkRequest mDefaultRequest;
4357
Erik Klineda4bfa82015-04-30 12:58:40 +09004358 // Request used to optionally keep mobile data active even when higher
4359 // priority networks like Wi-Fi are active.
4360 private final NetworkRequest mDefaultMobileDataRequest;
4361
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004362 private NetworkAgentInfo getDefaultNetwork() {
4363 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4364 }
4365
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004366 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004367 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004368 }
4369
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004370 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4371 return nri.request.requestId == mDefaultRequest.requestId;
4372 }
4373
Paul Jensen31a94f42015-02-13 14:18:39 -05004374 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004375 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004376 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004377 enforceConnectivityInternalPermission();
4378
Paul Jensen2c311d62014-11-17 12:34:51 -05004379 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4380 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004381 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004382 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4383 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004384 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004385 synchronized (this) {
4386 nai.networkMonitor.systemReady = mSystemReady;
4387 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004388 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4389 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004390 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004391 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004392 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004393 }
4394
4395 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4396 if (VDBG) log("Got NetworkAgent Messenger");
4397 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004398 synchronized (mNetworkForNetId) {
4399 mNetworkForNetId.put(na.network.netId, na);
4400 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004401 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4402 NetworkInfo networkInfo = na.networkInfo;
4403 na.networkInfo = null;
4404 updateNetworkInfo(na, networkInfo);
4405 }
4406
4407 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4408 LinkProperties newLp = networkAgent.linkProperties;
4409 int netId = networkAgent.network.netId;
4410
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004411 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4412 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004413 if (networkAgent.clatd != null) {
4414 networkAgent.clatd.fixupLinkProperties(oldLp);
4415 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004416
Paul Jensen992f2522014-04-28 10:33:11 -04004417 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004418 updateMtu(newLp, oldLp);
4419 // TODO - figure out what to do for clat
4420// for (LinkProperties lp : newLp.getStackedLinks()) {
4421// updateMtu(lp, null);
4422// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004423 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004424
Erik Kline94887872016-04-05 13:30:49 +09004425 updateRoutes(newLp, oldLp, netId);
4426 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004427
Paul Jensen3b759822014-05-13 11:44:01 -04004428 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004429 if (isDefaultNetwork(networkAgent)) {
4430 handleApplyDefaultProxy(newLp.getHttpProxy());
4431 } else {
4432 updateProxy(newLp, oldLp, networkAgent);
4433 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004434 // TODO - move this check to cover the whole function
4435 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004436 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004437 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4438 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004439
4440 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004441 }
4442
Lorenzo Colitti95439462014-10-09 13:44:48 +09004443 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4444 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4445 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004446
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004447 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004448 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4449 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004450 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004451 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004452 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004453 }
Paul Jensen992f2522014-04-28 10:33:11 -04004454
4455 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4456 CompareResult<String> interfaceDiff = new CompareResult<String>();
4457 if (oldLp != null) {
4458 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4459 } else if (newLp != null) {
4460 interfaceDiff.added = newLp.getAllInterfaceNames();
4461 }
4462 for (String iface : interfaceDiff.added) {
4463 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004464 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004465 mNetd.addInterfaceToNetwork(iface, netId);
4466 } catch (Exception e) {
4467 loge("Exception adding interface: " + e);
4468 }
4469 }
4470 for (String iface : interfaceDiff.removed) {
4471 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004472 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004473 mNetd.removeInterfaceFromNetwork(iface, netId);
4474 } catch (Exception e) {
4475 loge("Exception removing interface: " + e);
4476 }
4477 }
4478 }
4479
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004480 /**
4481 * Have netd update routes from oldLp to newLp.
4482 * @return true if routes changed between oldLp and newLp
4483 */
4484 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004485 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4486 if (oldLp != null) {
4487 routeDiff = oldLp.compareAllRoutes(newLp);
4488 } else if (newLp != null) {
4489 routeDiff.added = newLp.getAllRoutes();
4490 }
4491
4492 // add routes before removing old in case it helps with continuous connectivity
4493
4494 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4495 for (RouteInfo route : routeDiff.added) {
4496 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004497 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004498 try {
4499 mNetd.addRoute(netId, route);
4500 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004501 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4502 loge("Exception in addRoute for non-gateway: " + e);
4503 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004504 }
4505 }
4506 for (RouteInfo route : routeDiff.added) {
4507 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004508 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004509 try {
4510 mNetd.addRoute(netId, route);
4511 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004512 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4513 loge("Exception in addRoute for gateway: " + e);
4514 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004515 }
4516 }
4517
4518 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004519 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 try {
4521 mNetd.removeRoute(netId, route);
4522 } catch (Exception e) {
4523 loge("Exception in removeRoute: " + e);
4524 }
4525 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004526 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004527 }
Erik Kline41368502015-06-17 13:19:54 +09004528
Erik Kline94887872016-04-05 13:30:49 +09004529 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4530 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4531 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 }
Erik Kline94887872016-04-05 13:30:49 +09004533
4534 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004535 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004536 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004537 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004538 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4539 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004540 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004541 }
Erik Kline94887872016-04-05 13:30:49 +09004542 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 }
4544
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004545 private String getNetworkPermission(NetworkCapabilities nc) {
4546 // TODO: make these permission strings AIDL constants instead.
4547 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4548 return NetworkManagementService.PERMISSION_SYSTEM;
4549 }
4550 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4551 return NetworkManagementService.PERMISSION_NETWORK;
4552 }
4553 return null;
4554 }
4555
Paul Jensen3d194ea2015-06-16 14:27:36 -04004556 /**
4557 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4558 * augmented with any stateful capabilities implied from {@code networkAgent}
4559 * (e.g., validated status and captive portal status).
4560 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004561 * @param oldScore score of the network before any of the changes that prompted us
4562 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004563 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004564 * @param networkCapabilities the new network capabilities.
4565 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004566 private void updateCapabilities(
4567 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004568 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4569 networkCapabilities)) {
4570 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4571 + nai.networkCapabilities + " -> " + networkCapabilities);
4572 }
4573
Paul Jensen3d194ea2015-06-16 14:27:36 -04004574 // Don't modify caller's NetworkCapabilities.
4575 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004576 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004577 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4578 } else {
4579 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4580 }
Paul Jensene0988542015-06-25 15:30:08 -04004581 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004582 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4583 } else {
4584 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4585 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004586 if (nai.isBackgroundNetwork()) {
4587 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4588 } else {
4589 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4590 }
4591
4592 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4593
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004594 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4595 final String newPermission = getNetworkPermission(networkCapabilities);
4596 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004597 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004598 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004599 } catch (RemoteException e) {
4600 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004601 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004602 }
4603
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004604 final NetworkCapabilities prevNc = nai.networkCapabilities;
4605 synchronized (nai) {
4606 nai.networkCapabilities = networkCapabilities;
4607 }
4608 if (nai.getCurrentScore() == oldScore &&
4609 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4610 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4611 // the change we're processing can't affect any requests, it can only affect the listens
4612 // on this network. We might have been called by rematchNetworkAndRequests when a
4613 // network changed foreground state.
4614 processListenRequests(nai, true);
4615 } else {
4616 // If the requestable capabilities have changed or the score changed, we can't have been
4617 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004618 rematchAllNetworksAndRequests(nai, oldScore);
4619 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004620 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004621 }
4622
Paul Jensenc8b9a742014-09-30 15:37:41 -04004623 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004624 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4625 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004626 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004627 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004628 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4629 }
4630 }
4631
Robert Greenwalt7b816022014-04-18 15:25:25 -07004632 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4633 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004634 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004635 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4636 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004637 }
4638 }
4639
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004640 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4641 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004642 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004643 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004644 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4645 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004646 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004647 sendIntent(nri.mPendingIntent, intent);
4648 }
4649 // else not handled
4650 }
4651
4652 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4653 mPendingIntentWakeLock.acquire();
4654 try {
4655 if (DBG) log("Sending " + pendingIntent);
4656 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4657 } catch (PendingIntent.CanceledException e) {
4658 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4659 mPendingIntentWakeLock.release();
4660 releasePendingNetworkRequest(pendingIntent);
4661 }
4662 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4663 }
4664
4665 @Override
4666 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4667 String resultData, Bundle resultExtras) {
4668 if (DBG) log("Finished sending " + pendingIntent);
4669 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004670 // Release with a delay so the receiving client has an opportunity to put in its
4671 // own request.
4672 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004673 }
4674
Robert Greenwalt9258c642014-03-26 16:47:06 -07004675 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004676 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004677 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004678 Bundle bundle = new Bundle();
4679 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4680 new NetworkRequest(nri.request));
4681 Message msg = Message.obtain();
4682 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4683 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4684 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4685 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004686 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004687 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004688 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004689 break;
4690 }
4691 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4692 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4693 new NetworkCapabilities(networkAgent.networkCapabilities));
4694 break;
4695 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004696 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004697 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4698 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004699 break;
4700 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004701 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004702 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004703 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004704 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004705 if (VDBG) {
4706 log("sending notification " + notifyTypeToName(notificationType) +
4707 " for " + nri.request);
4708 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004709 nri.messenger.send(msg);
4710 } catch (RemoteException e) {
4711 // may occur naturally in the race of binder death.
4712 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4713 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004714 }
4715
Paul Jensenc8b9a742014-09-30 15:37:41 -04004716 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004717 if (nai.numRequestNetworkRequests() != 0) {
4718 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4719 NetworkRequest nr = nai.requestAt(i);
4720 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004721 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004722 loge("Dead network still had at least " + nr);
4723 break;
4724 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004725 }
4726 nai.asyncChannel.disconnect();
4727 }
4728
Robert Greenwalt7b816022014-04-18 15:25:25 -07004729 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4730 if (oldNetwork == null) {
4731 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4732 return;
4733 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004734 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004735
4736 // If we get here it means that the last linger timeout for this network expired. So there
4737 // must be no other active linger timers, and we must stop lingering.
4738 oldNetwork.clearLingerState();
4739
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004740 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004741 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004742 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004743 } else {
4744 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004745 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4746 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004747 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004748 }
4749
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004750 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004751 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004752 setupDataActivityTracking(newNetwork);
4753 try {
4754 mNetd.setDefaultNetId(newNetwork.network.netId);
4755 } catch (Exception e) {
4756 loge("Exception setting default network :" + e);
4757 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004758 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004759 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004760 updateTcpBufferSizes(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004761 }
4762
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004763 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004764 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4765 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4766 NetworkRequest nr = nri.request;
4767 if (!nr.isListen()) continue;
4768 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4769 nai.removeRequest(nri.request.requestId);
4770 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4771 }
4772 }
4773
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004774 if (capabilitiesChanged) {
4775 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4776 }
4777
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004778 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4779 NetworkRequest nr = nri.request;
4780 if (!nr.isListen()) continue;
4781 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4782 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004783 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004784 }
4785 }
4786 }
4787
Paul Jensen2161a8e2014-09-11 11:00:39 -04004788 // Handles a network appearing or improving its score.
4789 //
4790 // - Evaluates all current NetworkRequests that can be
4791 // satisfied by newNetwork, and reassigns to newNetwork
4792 // any such requests for which newNetwork is the best.
4793 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004794 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004795 // needed. A network is needed if it is the best network for
4796 // one or more NetworkRequests, or if it is a VPN.
4797 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004798 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004799 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004800 //
4801 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4802 // networks that have no chance (i.e. even if validated)
4803 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004804 //
4805 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4806 // it does not remove NetworkRequests that other Networks could better satisfy.
4807 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4808 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4809 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004810 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004811 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004812 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4813 // performed to tear down unvalidated networks that have no chance (i.e. even if
4814 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004815 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004816 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004817 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004818 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004819 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004820 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004821
4822 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4823 final int score = newNetwork.getCurrentScore();
4824
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004825 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004826
Paul Jensen2161a8e2014-09-11 11:00:39 -04004827 // Find and migrate to this Network any NetworkRequests for
4828 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004829 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004830 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004831 NetworkCapabilities nc = newNetwork.networkCapabilities;
4832 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004833 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004834 // Process requests in the first pass and listens in the second pass. This allows us to
4835 // change a network's capabilities depending on which requests it has. This is only
4836 // correct if the change in capabilities doesn't affect whether the network satisfies
4837 // requests or not, and doesn't affect the network's score.
4838 if (nri.request.isListen()) continue;
4839
Paul Jensencf4c2c62015-07-01 14:16:32 -04004840 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4841 final boolean satisfies = newNetwork.satisfies(nri.request);
4842 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004843 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004844 log("Network " + newNetwork.name() + " was already satisfying" +
4845 " request " + nri.request.requestId + ". No change.");
4846 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004847 keep = true;
4848 continue;
4849 }
4850
4851 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004852 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004853 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004854 // next check if it's better than any current network we're using for
4855 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004856 if (VDBG) {
4857 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004858 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004859 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004860 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004861 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004862 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004863 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004864 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004865 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004866 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004867 affectedNetworks.add(currentNetwork);
4868 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004869 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004870 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004871 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004872 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004873 if (!newNetwork.addRequest(nri.request)) {
4874 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4875 }
4876 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004877 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004878 // Tell NetworkFactories about the new score, so they can stop
4879 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004880 // TODO - this could get expensive if we have alot of requests for this
4881 // network. Think about if there is a way to reduce this. Push
4882 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004883 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004884 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004885 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004886 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004887 if (currentNetwork != null) {
4888 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4889 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004890 }
4891 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004892 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004893 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4894 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004895 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004896 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4897 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4898 // This means this code doesn't have to handle the case where "currentNetwork" no
4899 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4900 if (DBG) {
4901 log("Network " + newNetwork.name() + " stopped satisfying" +
4902 " request " + nri.request.requestId);
4903 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004904 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004905 if (currentNetwork == newNetwork) {
4906 mNetworkForRequestId.remove(nri.request.requestId);
4907 sendUpdatedScoreToFactories(nri.request, 0);
4908 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004909 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4910 newNetwork.name() +
4911 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004912 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004913 // TODO: Technically, sending CALLBACK_LOST here is
4914 // incorrect if there is a replacement network currently
4915 // connected that can satisfy nri, which is a request
4916 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004917 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4918 // so this code is only incorrect for a network that loses
4919 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004920 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004921 }
4922 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004923 if (isNewDefault) {
4924 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004925 makeDefault(newNetwork);
4926 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4927 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004928 synchronized (ConnectivityService.this) {
4929 // have a new default network, release the transition wakelock in
4930 // a second if it's held. The second pause is to allow apps
4931 // to reconnect over the new network
4932 if (mNetTransitionWakeLock.isHeld()) {
4933 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4934 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4935 mNetTransitionWakeLockSerialNumber, 0),
4936 1000);
4937 }
4938 }
4939 }
4940
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004941 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4942 Slog.wtf(TAG, String.format(
4943 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4944 nc, newNetwork.networkCapabilities));
4945 }
4946 if (newNetwork.getCurrentScore() != score) {
4947 Slog.wtf(TAG, String.format(
4948 "BUG: %s changed score during rematch: %d -> %d",
4949 score, newNetwork.getCurrentScore()));
4950 }
4951
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004952 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004953 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4954 // If the network went from background to foreground or vice versa, we need to update
4955 // its foreground state. It is safe to do this after rematching the requests because
4956 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4957 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004958 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004959 } else {
4960 processListenRequests(newNetwork, false);
4961 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004962
Paul Jensencf4c2c62015-07-01 14:16:32 -04004963 // do this after the default net is switched, but
4964 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004965 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004966
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004967 // Linger any networks that are no longer needed. This should be done after sending the
4968 // available callback for newNetwork.
4969 for (NetworkAgentInfo nai : affectedNetworks) {
4970 updateLingerState(nai, now);
4971 }
4972 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4973 // does not need to be done in any particular order.
4974 updateLingerState(newNetwork, now);
4975
Paul Jensencf4c2c62015-07-01 14:16:32 -04004976 if (isNewDefault) {
4977 // Maintain the illusion: since the legacy API only
4978 // understands one network at a time, we must pretend
4979 // that the current default network disconnected before
4980 // the new one connected.
4981 if (oldDefaultNetwork != null) {
4982 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4983 oldDefaultNetwork, true);
4984 }
4985 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4986 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4987 notifyLockdownVpn(newNetwork);
4988 }
4989
Robert Greenwalt7b816022014-04-18 15:25:25 -07004990 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004991 // Notify battery stats service about this network, both the normal
4992 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004993 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004994 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004995 final IBatteryStats bs = BatteryStatsService.getService();
4996 final int type = newNetwork.networkInfo.getType();
4997
4998 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4999 bs.noteNetworkInterfaceType(baseIface, type);
5000 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5001 final String stackedIface = stacked.getInterfaceName();
5002 bs.noteNetworkInterfaceType(stackedIface, type);
5003 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5004 }
5005 } catch (RemoteException ignored) {
5006 }
5007
Robert Greenwalt152ed372014-12-17 17:19:53 -08005008 // This has to happen after the notifyNetworkCallbacks as that tickles each
5009 // ConnectivityManager instance so that legacy requests correctly bind dns
5010 // requests to this network. The legacy users are listening for this bcast
5011 // and will generally do a dns request so they can ensureRouteToHost and if
5012 // they do that before the callbacks happen they'll use the default network.
5013 //
5014 // TODO: Is there still a race here? We send the broadcast
5015 // after sending the callback, but if the app can receive the
5016 // broadcast before the callback, it might still break.
5017 //
5018 // This *does* introduce a race where if the user uses the new api
5019 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5020 // they may get old info. Reverse this after the old startUsing api is removed.
5021 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005022 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5023 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005024 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005025 // legacy type tracker filters out repeat adds
5026 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5027 }
5028 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005029
5030 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5031 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5032 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5033 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5034 if (newNetwork.isVPN()) {
5035 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5036 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005037 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005038 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5039 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005040 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005041 if (nai.getLingerExpiry() > 0) {
5042 // This network has active linger timers and no requests, but is not
5043 // lingering. Linger it.
5044 //
5045 // One way (the only way?) this can happen if this network is unvalidated
5046 // and became unneeded due to another network improving its score to the
5047 // point where this network will no longer be able to satisfy any requests
5048 // even if it validates.
5049 updateLingerState(nai, now);
5050 } else {
5051 if (DBG) log("Reaping " + nai.name());
5052 teardownUnneededNetwork(nai);
5053 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005054 }
5055 }
5056 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005057 }
5058
Paul Jensen1c7ba022015-06-16 14:27:36 -04005059 /**
5060 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5061 * being disconnected.
5062 * @param changed If only one Network's score or capabilities have been modified since the last
5063 * time this function was called, pass this Network in this argument, otherwise pass
5064 * null.
5065 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5066 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5067 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5068 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5069 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005070 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005071 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005072 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5073 // to avoid the slowness. It is not simply enough to process just "changed", for
5074 // example in the case where "changed"'s score decreases and another network should begin
5075 // satifying a NetworkRequest that "changed" currently satisfies.
5076
5077 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5078 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5079 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005080 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005081 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005082 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005083 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005084 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5085 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5086 // Rematch higher scoring networks first to prevent requests first matching a lower
5087 // scoring network and then a higher scoring network, which could produce multiple
5088 // callbacks and inadvertently unlinger networks.
5089 Arrays.sort(nais);
5090 for (NetworkAgentInfo nai : nais) {
5091 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005092 // Only reap the last time through the loop. Reaping before all rematching
5093 // is complete could incorrectly teardown a network that hasn't yet been
5094 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005095 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005096 : ReapUnvalidatedNetworks.REAP,
5097 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005098 }
5099 }
5100 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005101
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005102 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005103 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005104 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005105 // For now only update icons for default connection.
5106 // TODO: Update WiFi and cellular icons separately. b/17237507
5107 if (!isDefaultNetwork(nai)) return;
5108
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005109 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005110 // Don't repeat publish.
5111 if (newInetCondition == mDefaultInetConditionPublished) return;
5112
5113 mDefaultInetConditionPublished = newInetCondition;
5114 sendInetConditionBroadcast(nai.networkInfo);
5115 }
5116
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005117 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5118 if (mLockdownTracker != null) {
5119 if (nai != null && nai.isVPN()) {
5120 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5121 } else {
5122 mLockdownTracker.onNetworkInfoChanged();
5123 }
5124 }
5125 }
5126
Robert Greenwalt7b816022014-04-18 15:25:25 -07005127 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005128 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005129 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005130 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005131 synchronized (networkAgent) {
5132 oldInfo = networkAgent.networkInfo;
5133 networkAgent.networkInfo = newInfo;
5134 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005135 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005136
5137 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005138 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5139 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5140 notifyIfacesChangedForNetworkStats();
5141 } else if (VDBG) log("ignoring duplicate network state non-change");
5142 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005143 return;
5144 }
5145 if (DBG) {
5146 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5147 (oldInfo == null ? "null" : oldInfo.getState()) +
5148 " to " + state);
5149 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005150
Robin Lee585e2482016-05-01 23:00:00 +01005151 if (!networkAgent.created
5152 && (state == NetworkInfo.State.CONNECTED
5153 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005154
5155 // A network that has just connected has zero requests and is thus a foreground network.
5156 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5157
Robert Greenwalt7b816022014-04-18 15:25:25 -07005158 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005159 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005160 if (networkAgent.isVPN()) {
5161 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005162 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5163 (networkAgent.networkMisc == null ||
5164 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005165 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005166 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005167 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005168 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005169 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005170 loge("Error creating network " + networkAgent.network.netId + ": "
5171 + e.getMessage());
5172 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005173 }
Paul Jenseneec75412014-08-04 12:21:19 -04005174 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005175 }
5176
5177 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5178 networkAgent.everConnected = true;
5179
Robert Greenwalt7b816022014-04-18 15:25:25 -07005180 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005181 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005182
Paul Jensenca8f16a2014-05-09 12:47:55 -04005183 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005184 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005185
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005186 if (networkAgent.isVPN()) {
5187 // Temporarily disable the default proxy (not global).
5188 synchronized (mProxyLock) {
5189 if (!mDefaultProxyDisabled) {
5190 mDefaultProxyDisabled = true;
5191 if (mGlobalProxy == null && mDefaultProxy != null) {
5192 sendProxyBroadcast(null);
5193 }
5194 }
5195 }
5196 // TODO: support proxy per network.
5197 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005198
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005199 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5200 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5201 // capabilities, so it only needs to be done once on initial connect, not every time the
5202 // network's capabilities change. Note that we do this before rematching the network,
5203 // so we could decide to tear it down immediately afterwards. That's fine though - on
5204 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5205 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005206 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005207
Paul Jensen2161a8e2014-09-11 11:00:39 -04005208 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005209 final long now = SystemClock.elapsedRealtime();
5210 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005211
5212 // This has to happen after matching the requests, because callbacks are just requests.
5213 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005214 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005215 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005216 if (networkAgent.isVPN()) {
5217 synchronized (mProxyLock) {
5218 if (mDefaultProxyDisabled) {
5219 mDefaultProxyDisabled = false;
5220 if (mGlobalProxy == null && mDefaultProxy != null) {
5221 sendProxyBroadcast(mDefaultProxy);
5222 }
5223 }
5224 }
5225 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005226 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5227 state == NetworkInfo.State.SUSPENDED) {
5228 // going into or coming out of SUSPEND: rescore and notify
5229 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005230 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005231 }
5232 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5233 ConnectivityManager.CALLBACK_SUSPENDED :
5234 ConnectivityManager.CALLBACK_RESUMED));
5235 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005236 }
5237 }
5238
Robert Greenwaltac96c522014-06-03 16:43:57 -07005239 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005240 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005241 if (score < 0) {
5242 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5243 "). Bumping score to min of 0");
5244 score = 0;
5245 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005246
Paul Jensen2161a8e2014-09-11 11:00:39 -04005247 final int oldScore = nai.getCurrentScore();
5248 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005249
Paul Jensen85cf78e2015-06-25 13:25:07 -04005250 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005251
Paul Jensenc8b9a742014-09-30 15:37:41 -04005252 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005253 }
5254
Erik Klinec75d4fa2017-02-15 19:59:17 +09005255 // Notify only this one new request of the current state. Transfer all the
5256 // current state by calling NetworkCapabilities and LinkProperties callbacks
5257 // so that callers can be guaranteed to have as close to atomicity in state
5258 // transfer as can be supported by this current API.
5259 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohenbf3b1ba2016-10-27 15:05:50 -07005260 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005261 if (nri.mPendingIntent != null) {
5262 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5263 // Attempt no subsequent state pushes where intents are involved.
5264 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005265 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005266
5267 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5268 // Whether a network is currently suspended is also an important
5269 // element of state to be transferred (it would not otherwise be
5270 // delivered by any currently available mechanism).
5271 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5272 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5273 }
5274 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5275 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005276 }
5277
Robert Greenwalt8d482522015-06-24 13:23:42 -07005278 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005279 // The NetworkInfo we actually send out has no bearing on the real
5280 // state of affairs. For example, if the default connection is mobile,
5281 // and a request for HIPRI has just gone away, we need to pretend that
5282 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5283 // the state to DISCONNECTED, even though the network is of type MOBILE
5284 // and is still connected.
5285 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5286 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005287 if (state != DetailedState.DISCONNECTED) {
5288 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005289 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005290 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005291 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005292 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5293 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5294 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5295 if (info.isFailover()) {
5296 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5297 nai.networkInfo.setFailover(false);
5298 }
5299 if (info.getReason() != null) {
5300 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5301 }
5302 if (info.getExtraInfo() != null) {
5303 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5304 }
5305 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005306 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005307 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005308 if (newDefaultAgent != null) {
5309 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5310 newDefaultAgent.networkInfo);
5311 } else {
5312 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5313 }
5314 }
5315 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5316 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005317 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005318 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005319 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005320 }
5321 }
5322 }
5323
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005324 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005325 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005326 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5327 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005328 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5329 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005330 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5331 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005332 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005333 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005334 } else {
5335 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5336 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005337 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005338 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005339
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005340 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5341 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5342 }
5343
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005344 private String notifyTypeToName(int notifyType) {
5345 switch (notifyType) {
5346 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5347 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5348 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5349 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5350 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5351 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5352 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5353 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5354 }
5355 return "UNKNOWN";
5356 }
5357
Jeff Sharkey69736342014-12-08 14:50:12 -08005358 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005359 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5360 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005361 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005362 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005363 try {
5364 mStatsService.forceUpdateIfaces();
5365 } catch (Exception ignored) {
5366 }
5367 }
5368
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005369 @Override
5370 public boolean addVpnAddress(String address, int prefixLength) {
5371 throwIfLockdownEnabled();
5372 int user = UserHandle.getUserId(Binder.getCallingUid());
5373 synchronized (mVpns) {
5374 return mVpns.get(user).addAddress(address, prefixLength);
5375 }
5376 }
5377
5378 @Override
5379 public boolean removeVpnAddress(String address, int prefixLength) {
5380 throwIfLockdownEnabled();
5381 int user = UserHandle.getUserId(Binder.getCallingUid());
5382 synchronized (mVpns) {
5383 return mVpns.get(user).removeAddress(address, prefixLength);
5384 }
5385 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005386
5387 @Override
5388 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5389 throwIfLockdownEnabled();
5390 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005391 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005392 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005393 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005394 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005395 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005396 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005397 }
5398 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005399 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005400
5401 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005402 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005403 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005404 }
5405
5406 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005407 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5408 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5409 enforceKeepalivePermission();
5410 mKeepaliveTracker.startNattKeepalive(
5411 getNetworkAgentInfoForNetwork(network),
5412 intervalSeconds, messenger, binder,
5413 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5414 }
5415
5416 @Override
5417 public void stopKeepalive(Network network, int slot) {
5418 mHandler.sendMessage(mHandler.obtainMessage(
5419 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5420 }
5421
5422 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005423 public void factoryReset() {
5424 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005425
5426 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5427 return;
5428 }
5429
Robin Lee3b3dd942015-05-12 18:14:58 +01005430 final int userId = UserHandle.getCallingUserId();
5431
Stuart Scottf1fb3972015-04-02 18:00:02 -07005432 // Turn airplane mode off
5433 setAirplaneMode(false);
5434
Stuart Scotte3e314d2015-04-20 14:07:45 -07005435 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5436 // Untether
5437 for (String tether : getTetheredIfaces()) {
5438 untether(tether);
5439 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005440 }
5441
Stuart Scotte3e314d2015-04-20 14:07:45 -07005442 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005443 // Remove always-on package
5444 synchronized (mVpns) {
5445 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5446 if (alwaysOnPackage != null) {
5447 setAlwaysOnVpnPackage(userId, null, false);
5448 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5449 }
5450 }
5451
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005452 // Turn Always-on VPN off
5453 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5454 final long ident = Binder.clearCallingIdentity();
5455 try {
5456 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5457 mLockdownEnabled = false;
5458 setLockdownTracker(null);
5459 } finally {
5460 Binder.restoreCallingIdentity(ident);
5461 }
5462 }
5463
Stuart Scotte3e314d2015-04-20 14:07:45 -07005464 // Turn VPN off
5465 VpnConfig vpnConfig = getVpnConfig(userId);
5466 if (vpnConfig != null) {
5467 if (vpnConfig.legacy) {
5468 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5469 } else {
5470 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5471 // in the future without user intervention.
5472 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005473
Victor Changb04a5ea2016-05-30 20:36:30 +01005474 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005475 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005476 }
5477 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005478
5479 Settings.Global.putString(mContext.getContentResolver(),
5480 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005481 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005482
5483 @VisibleForTesting
5484 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5485 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5486 return new NetworkMonitor(context, handler, nai, defaultRequest);
5487 }
Erik Kline48f12f22016-04-14 17:30:59 +09005488
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005489 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005490 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5491 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005492 }
5493
5494 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005495 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5496 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5497 }
5498
Hugo Benichicfddd682016-05-31 16:28:06 +09005499 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005500 int newNetid = NETID_UNSET;
5501 int prevNetid = NETID_UNSET;
5502 int[] transports = new int[0];
5503 boolean hadIPv4 = false;
5504 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005505
Hugo Benichi5f16f762016-04-20 12:09:33 +09005506 if (newNai != null) {
5507 newNetid = newNai.network.netId;
5508 transports = newNai.networkCapabilities.getTransportTypes();
5509 }
5510 if (prevNai != null) {
5511 prevNetid = prevNai.network.netId;
5512 final LinkProperties lp = prevNai.linkProperties;
5513 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5514 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5515 }
5516
Hugo Benichicfddd682016-05-31 16:28:06 +09005517 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5518 }
5519
5520 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5521 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523}