blob: 50c1ca09f683e04240c710bc1d46b9c90b4ec0f6 [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 Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060032import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -070033import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
34import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
Felipe Leme46c4fc32016-05-04 09:21:43 -070035import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070037import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060038import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070039import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060040
Wenchao Tongf5ea3402015-03-04 13:26:38 -080041import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080042import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.Notification;
44import android.app.NotificationManager;
45import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070046import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.ContentResolver;
48import android.content.Context;
49import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070050import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070052import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090053import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070054import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090056import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070058import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070059import android.net.INetworkPolicyListener;
60import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070061import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080062import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070063import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070064import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070065import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070067import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070069import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070070import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070071import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070072import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070073import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070074import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070075import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040076import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070077import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040078import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040079import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090080import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090081import android.net.metrics.NetworkEvent;
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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070099import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400100import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700102import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700103import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700104import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600106import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700107import android.util.LocalLog;
108import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600109import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700110import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800111import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700112import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500113import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700115import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400119import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700121import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700123import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800124import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700125import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700126import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700127import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900128import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700129import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700130import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400131import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900132import com.android.server.connectivity.KeepaliveTracker;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900133import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700134import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600135import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400136import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400137import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700138import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800139import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700140import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700141import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700142import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600143
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700144import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700145
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700146import org.xmlpull.v1.XmlPullParser;
147import org.xmlpull.v1.XmlPullParserException;
148
149import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700151import java.io.FileNotFoundException;
152import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700153import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700155import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700156import java.net.InetAddress;
157import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700158import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700159import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700160import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700161import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700162import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700163import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700165import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700166import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600167import java.util.SortedSet;
168import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170/**
171 * @hide
172 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800173public class ConnectivityService extends IConnectivityManager.Stub
174 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900177 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700178 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Jake Hamby786e71a2014-02-06 14:43:50 -0800180 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900181 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700182
Jeff Sharkey899223b2012-08-04 15:24:58 -0700183 // TODO: create better separation between radio types and network types
184
Robert Greenwalt42acef32009-08-12 16:08:25 -0700185 // how long to wait before switching back to a radio's default network
186 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
187 // system property that can override the above value
188 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
189 "android.telephony.apn-restore";
190
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900191 // How long to wait before putting up a "This network doesn't have an Internet connection,
192 // connect anyway?" dialog after the user selects a network that doesn't validate.
193 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
194
Jeremy Joslin79294842014-12-03 17:15:28 -0800195 // How long to delay to removal of a pending intent based request.
196 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
197 private final int mReleasePendingIntentDelayMs;
198
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800199 private Tethering mTethering;
200
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700201 private final PermissionMonitor mPermissionMonitor;
202
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700203 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700204
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700205 @GuardedBy("mVpns")
206 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700207
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700208 private boolean mLockdownEnabled;
209 private LockdownVpnTracker mLockdownTracker;
210
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700211 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
212 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700213 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600214 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700215 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700216 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600217 @GuardedBy("mRulesLock")
218 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
219 /** Flag indicating if background data is restricted. */
220 @GuardedBy("mRulesLock")
221 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222
Erik Klineda4bfa82015-04-30 12:58:40 +0900223 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700225 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700226 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800228 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
230 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700231 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700233 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800234 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700236
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700237 private String mCurrentTcpBufferSizes;
238
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700239 private static final int ENABLED = 1;
240 private static final int DISABLED = 0;
241
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900242 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
243 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
244
Paul Jensenb10e37f2014-11-25 12:33:08 -0500245 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400246 // Tear down networks that have no chance (e.g. even if validated) of becoming
247 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500248 // all networks have been rematched against all NetworkRequests.
249 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400250 // Don't reap networks. This should be passed when some networks have not yet been
251 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500252 DONT_REAP
253 };
254
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700255 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256 * used internally to change our mobile data enabled flag
257 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700258 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700259
260 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700261 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700262 * from one net to another. Clear happens when we get a new
263 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
264 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700265 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700266 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700267
Robert Greenwalt434203a2010-10-11 16:00:27 -0700268 /**
269 * used internally to reload global proxy settings
270 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700271 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700272
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700273 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400274 * PAC manager has received new port.
275 */
276 private static final int EVENT_PROXY_HAS_CHANGED = 16;
277
Robert Greenwalte049c232014-04-11 15:53:27 -0700278 /**
279 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700280 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700281 */
282 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
283
Robert Greenwalt7b816022014-04-18 15:25:25 -0700284 /**
285 * used internally when registering NetworkAgents
286 * obj = Messenger
287 */
288 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
289
Robert Greenwalt9258c642014-03-26 16:47:06 -0700290 /**
291 * used to add a network request
292 * includes a NetworkRequestInfo
293 */
294 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
295
296 /**
297 * indicates a timeout period is over - check if we had a network yet or not
298 * and if not, call the timeout calback (but leave the request live until they
299 * cancel it.
300 * includes a NetworkRequestInfo
301 */
302 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
303
304 /**
305 * used to add a network listener - no request
306 * includes a NetworkRequestInfo
307 */
308 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
309
310 /**
311 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400312 * arg1 = UID of caller
313 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700314 */
315 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
316
Robert Greenwalta67be032014-05-16 15:49:14 -0700317 /**
318 * used internally when registering NetworkFactories
319 * obj = Messenger
320 */
321 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
322
Robert Greenwalt27711812014-06-25 16:45:57 -0700323 /**
324 * used internally to expire a wakelock when transitioning
325 * from one net to another. Expire happens when we fail to find
326 * a new network (typically after 1 minute) -
327 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
328 * a replacement network.
329 */
330 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
331
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700332 /**
333 * Used internally to indicate the system is ready.
334 */
335 private static final int EVENT_SYSTEM_READY = 25;
336
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800337 /**
338 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400339 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800340 */
341 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
342
343 /**
344 * used to remove a pending intent and its associated network request.
345 * arg1 = UID of caller
346 * obj = PendingIntent
347 */
348 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
349
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900350 /**
351 * used to specify whether a network should be used even if unvalidated.
352 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
353 * arg2 = whether to remember this choice in the future (1 or 0)
354 * obj = network
355 */
356 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
357
358 /**
359 * used to ask the user to confirm a connection to an unvalidated network.
360 * obj = network
361 */
362 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700363
Erik Klineda4bfa82015-04-30 12:58:40 +0900364 /**
365 * used internally to (re)configure mobile data always-on settings.
366 */
367 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
368
Paul Jensen694f2b82015-06-17 14:15:39 -0400369 /**
370 * used to add a network listener with a pending intent
371 * obj = NetworkRequestInfo
372 */
373 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
374
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900375 /** Handler thread used for both of the handlers below. */
376 @VisibleForTesting
377 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700378 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700379 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700380 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700381 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700382
Mike Lockwood0f79b542009-08-14 14:18:49 -0400383 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800384 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400385
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700386 private PowerManager.WakeLock mNetTransitionWakeLock;
387 private String mNetTransitionWakeLockCausedBy = "";
388 private int mNetTransitionWakeLockSerialNumber;
389 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800390 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700391
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700392 // used in DBG mode to track inet condition reports
393 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
394 private ArrayList mInetLog;
395
Robert Greenwalt434203a2010-10-11 16:00:27 -0700396 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400397 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700398 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700399 private boolean mDefaultProxyDisabled = false;
400
Robert Greenwalt434203a2010-10-11 16:00:27 -0700401 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400402 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700403
Jason Monk602b2322013-07-03 17:04:33 -0400404 private PacManager mPacManager = null;
405
Erik Klineda4bfa82015-04-30 12:58:40 +0900406 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700407
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400408 private UserManager mUserManager;
409
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700410 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700411 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700412
Robert Greenwalt50393202011-06-21 17:26:14 -0700413 // the set of network types that can only be enabled by system/sig apps
414 List mProtectedNetworks;
415
John Spurlockbf991a82013-06-24 14:20:23 -0400416 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700417
Wink Savilleab9321d2013-06-29 21:10:57 -0700418 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400419
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900420 private KeepaliveTracker mKeepaliveTracker;
421
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700422 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
423 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700424 private final static int MAX_NET_ID = 65535;
425 private int mNextNetId = MIN_NET_ID;
426
Robert Greenwalt34524f02014-05-18 16:22:10 -0700427 // sequence number of NetworkRequests
428 private int mNextNetworkRequestId = 1;
429
Erik Kline7523eb32015-07-09 18:24:03 +0900430 // NetworkRequest activity String log entries.
431 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
432 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
433
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700434 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
435 private static final int MAX_VALIDATION_LOGS = 10;
436 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
437 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
438
439 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
440 synchronized(mValidationLogs) {
441 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
442 mValidationLogs.removeLast();
443 }
444 mValidationLogs.addFirst(new Pair(network, log));
445 }
446 }
447
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700448 /**
449 * Implements support for the legacy "one network per network type" model.
450 *
451 * We used to have a static array of NetworkStateTrackers, one for each
452 * network type, but that doesn't work any more now that we can have,
453 * for example, more that one wifi network. This class stores all the
454 * NetworkAgentInfo objects that support a given type, but the legacy
455 * API will only see the first one.
456 *
457 * It serves two main purposes:
458 *
459 * 1. Provide information about "the network for a given type" (since this
460 * API only supports one).
461 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
462 * the first network for a given type changes, or if the default network
463 * changes.
464 */
465 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900466
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900467 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900468 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900469
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700470 /**
471 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
472 * Each list holds references to all NetworkAgentInfos that are used to
473 * satisfy requests for that network type.
474 *
475 * This array is built out at startup such that an unsupported network
476 * doesn't get an ArrayList instance, making this a tristate:
477 * unsupported, supported but not active and active.
478 *
479 * The actual lists are populated when we scan the network types that
480 * are supported on this device.
481 */
482 private ArrayList<NetworkAgentInfo> mTypeLists[];
483
484 public LegacyTypeTracker() {
485 mTypeLists = (ArrayList<NetworkAgentInfo>[])
486 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
487 }
488
489 public void addSupportedType(int type) {
490 if (mTypeLists[type] != null) {
491 throw new IllegalStateException(
492 "legacy list for type " + type + "already initialized");
493 }
494 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
495 }
496
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700497 public boolean isTypeSupported(int type) {
498 return isNetworkTypeValid(type) && mTypeLists[type] != null;
499 }
500
501 public NetworkAgentInfo getNetworkForType(int type) {
502 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
503 return mTypeLists[type].get(0);
504 } else {
505 return null;
506 }
507 }
508
Robert Greenwalt8d482522015-06-24 13:23:42 -0700509 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900510 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900511 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700512 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900514 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515 }
516 }
517
518 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 public void add(int type, NetworkAgentInfo nai) {
520 if (!isTypeSupported(type)) {
521 return; // Invalid network type.
522 }
523 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
524
525 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
526 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700527 return;
528 }
529
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900530 list.add(nai);
531
532 // 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 +0900533 final boolean isDefaultNetwork = isDefaultNetwork(nai);
534 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700535 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
536 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700537 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538 }
539
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900541 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900542 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
543 if (list == null || list.isEmpty()) {
544 return;
545 }
546
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900547 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548
549 if (!list.remove(nai)) {
550 return;
551 }
552
Robert Greenwalt8d482522015-06-24 13:23:42 -0700553 final DetailedState state = DetailedState.DISCONNECTED;
554
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900555 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700556 maybeLogBroadcast(nai, state, type, wasDefault);
557 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900558 }
559
560 if (!list.isEmpty() && wasFirstNetwork) {
561 if (DBG) log("Other network available for type " + type +
562 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900563 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
565 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900566 }
567 }
568
569 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900570 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
571 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900573 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 }
575 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700576
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 // send out another legacy broadcast - currently only used for suspend/unsuspend
578 // toggle
579 public void update(NetworkAgentInfo nai) {
580 final boolean isDefault = isDefaultNetwork(nai);
581 final DetailedState state = nai.networkInfo.getDetailedState();
582 for (int type = 0; type < mTypeLists.length; type++) {
583 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700584 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700585 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700586 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700587 maybeLogBroadcast(nai, state, type, isDefault);
588 sendLegacyNetworkBroadcast(nai, state, type);
589 }
590 }
591 }
592
Lorenzo Colittia793a672014-07-31 23:20:17 +0900593 private String naiToString(NetworkAgentInfo nai) {
594 String name = (nai != null) ? nai.name() : "null";
595 String state = (nai.networkInfo != null) ?
596 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
597 "???/???";
598 return name + " " + state;
599 }
600
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700601 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900602 pw.println("mLegacyTypeTracker:");
603 pw.increaseIndent();
604 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700605 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900606 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900608 pw.println();
609 pw.println("Current state:");
610 pw.increaseIndent();
611 for (int type = 0; type < mTypeLists.length; type++) {
612 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
613 for (NetworkAgentInfo nai : mTypeLists[type]) {
614 pw.println(type + " " + naiToString(nai));
615 }
616 }
617 pw.decreaseIndent();
618 pw.decreaseIndent();
619 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700620 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700621 }
622 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
623
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900624 @VisibleForTesting
625 protected HandlerThread createHandlerThread() {
626 return new HandlerThread("ConnectivityServiceThread");
627 }
628
Jeff Sharkey899223b2012-08-04 15:24:58 -0700629 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700630 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800631 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800632
Erik Klineda4bfa82015-04-30 12:58:40 +0900633 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900634 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900635 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900636 mNetworkRequests.put(mDefaultRequest, defaultNRI);
637 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900638
639 mDefaultMobileDataRequest = createInternetRequestForTransport(
640 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700641
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900642 mHandlerThread = createHandlerThread();
643 mHandlerThread.start();
644 mHandler = new InternalHandler(mHandlerThread.getLooper());
645 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700646
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800647 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800648 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
649 String id = Settings.Secure.getString(context.getContentResolver(),
650 Settings.Secure.ANDROID_ID);
651 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700652 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800653 SystemProperties.set("net.hostname", name);
654 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800655 }
656
Jeremy Joslin79294842014-12-03 17:15:28 -0800657 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
658 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
659
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700660 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700661 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800662 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700663 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700664 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700665 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700666
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700667 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600668 mPolicyManager.setConnectivityListener(mPolicyListener);
669 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700670 } catch (RemoteException e) {
671 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700672 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700673 }
674
675 final PowerManager powerManager = (PowerManager) context.getSystemService(
676 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700677 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
678 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
679 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800680 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700681
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700682 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700683
Wink Saville51f456f2013-04-23 14:26:51 -0700684 // TODO: What is the "correct" way to do determine if this is a wifi only device?
685 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
686 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700687 String[] naStrings = context.getResources().getStringArray(
688 com.android.internal.R.array.networkAttributes);
689 for (String naString : naStrings) {
690 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700691 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700692 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700693 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800694 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700695 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700696 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700697 }
Wink Saville51f456f2013-04-23 14:26:51 -0700698 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
699 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
700 n.type);
701 continue;
702 }
Wink Saville975c8482011-04-07 14:23:45 -0700703 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800704 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700705 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700706 continue;
707 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700708 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700709
Wink Saville975c8482011-04-07 14:23:45 -0700710 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700711 mNetworksDefined++;
712 } catch(Exception e) {
713 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700714 }
715 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700716
717 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
718 if (mNetConfigs[TYPE_VPN] == null) {
719 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
720 // don't need to add TYPE_VPN to mNetConfigs.
721 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
722 mNetworksDefined++; // used only in the log() statement below.
723 }
724
Wink Saville5e56bc52013-07-29 15:00:57 -0700725 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700726
Robert Greenwalt50393202011-06-21 17:26:14 -0700727 mProtectedNetworks = new ArrayList<Integer>();
728 int[] protectedNetworks = context.getResources().getIntArray(
729 com.android.internal.R.array.config_protectedNetworks);
730 for (int p : protectedNetworks) {
731 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
732 mProtectedNetworks.add(p);
733 } else {
734 if (DBG) loge("Ignoring protectedNetwork " + p);
735 }
736 }
737
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700738 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
739 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700740
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800741 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800742
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700743 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
744
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700745 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700746 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100747 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700748 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700749 intentFilter.addAction(Intent.ACTION_USER_ADDED);
750 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000751 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700752 mContext.registerReceiverAsUser(
753 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900754
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700755 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700756 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700757 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700758 } catch (RemoteException e) {
759 loge("Error registering observer :" + e);
760 }
761
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700762 if (DBG) {
763 mInetLog = new ArrayList();
764 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700765
Erik Klineda4bfa82015-04-30 12:58:40 +0900766 mSettingsObserver = new SettingsObserver(mContext, mHandler);
767 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800768
John Spurlockbf991a82013-06-24 14:20:23 -0400769 mDataConnectionStats = new DataConnectionStats(mContext);
770 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400771
Jason Monkdecd2952013-10-10 14:02:51 -0400772 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700773
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400774 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900775
776 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700778
Erik Klineda4bfa82015-04-30 12:58:40 +0900779 private NetworkRequest createInternetRequestForTransport(int transportType) {
780 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900781 netCap.addCapability(NET_CAPABILITY_INTERNET);
782 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900783 if (transportType > -1) {
784 netCap.addTransportType(transportType);
785 }
786 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
787 }
788
789 private void handleMobileDataAlwaysOn() {
790 final boolean enable = (Settings.Global.getInt(
791 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
792 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
793 if (enable == isEnabled) {
794 return; // Nothing to do.
795 }
796
797 if (enable) {
798 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900799 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900800 } else {
801 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
802 }
803 }
804
805 private void registerSettingsCallbacks() {
806 // Watch for global HTTP proxy changes.
807 mSettingsObserver.observe(
808 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
809 EVENT_APPLY_GLOBAL_HTTP_PROXY);
810
811 // Watch for whether or not to keep mobile data always on.
812 mSettingsObserver.observe(
813 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
814 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
815 }
816
Robert Greenwalt34524f02014-05-18 16:22:10 -0700817 private synchronized int nextNetworkRequestId() {
818 return mNextNetworkRequestId++;
819 }
820
Paul Jensen67b0b072015-06-10 11:22:17 -0400821 @VisibleForTesting
822 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400823 synchronized (mNetworkForNetId) {
824 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
825 int netId = mNextNetId;
826 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
827 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500828 if (!mNetIdInUse.get(netId)) {
829 mNetIdInUse.put(netId, true);
830 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400831 }
832 }
833 }
834 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700835 }
836
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600837 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800838 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600839 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
840 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600842 state = nai.getNetworkState();
843 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800844 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600845 final NetworkInfo info = new NetworkInfo(networkType, 0,
846 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
848 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600849 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
850 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800851 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600852 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600853 return state;
854 } else {
855 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800856 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400857 }
858
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
860 if (network == null) {
861 return null;
862 }
863 synchronized (mNetworkForNetId) {
864 return mNetworkForNetId.get(network.netId);
865 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600866 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800867
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900868 private Network[] getVpnUnderlyingNetworks(int uid) {
869 if (!mLockdownEnabled) {
870 int user = UserHandle.getUserId(uid);
871 synchronized (mVpns) {
872 Vpn vpn = mVpns.get(user);
873 if (vpn != null && vpn.appliesToUid(uid)) {
874 return vpn.getUnderlyingNetworks();
875 }
876 }
877 }
878 return null;
879 }
880
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800881 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400882 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800883
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900884 final Network[] networks = getVpnUnderlyingNetworks(uid);
885 if (networks != null) {
886 // getUnderlyingNetworks() returns:
887 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
888 // empty array => the VPN explicitly said "no default network".
889 // non-empty array => the VPN specified one or more default networks; we use the
890 // first one.
891 if (networks.length > 0) {
892 nai = getNetworkAgentInfoForNetwork(networks[0]);
893 } else {
894 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800895 }
896 }
897
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800898 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600899 return nai.getNetworkState();
900 } else {
901 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800902 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400903 }
904
905 /**
906 * Check if UID should be blocked from using the network with the given LinkProperties.
907 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600908 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
909 boolean ignoreBlocked) {
910 // Networks aren't blocked when ignoring blocked status
911 if (ignoreBlocked) return false;
912 // Networks are never blocked for system services
913 if (uid < Process.FIRST_APPLICATION_UID) return false;
914
915 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700916 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700917
Robin Lee17e61832016-05-09 13:46:28 +0100918 synchronized (mVpns) {
919 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
920 if (vpn != null && vpn.isBlockingUid(uid)) {
921 return true;
922 }
923 }
924
Robert Greenwalt12e67352014-05-13 21:41:06 -0700925 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700926 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600927 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -0700928 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700929 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700930
Felipe Lemed31a97f2016-05-06 14:53:50 -0700931 boolean allowed = true;
932 // Check Data Saver Mode first...
933 if (networkMetered) {
934 if ((uidRules & RULE_REJECT_METERED) != 0) {
935 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
936 // Explicitly blacklisted.
937 allowed = false;
938 } else {
939 allowed = !mRestrictBackground
940 || (uidRules & RULE_ALLOW_METERED) != 0
941 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
942 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
943 + " mRestrictBackground=" + mRestrictBackground
944 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
945 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
946 + ": " + allowed);
947 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700948 }
Felipe Leme781ba142016-05-09 16:24:48 -0700949 // ...then power restrictions.
950 if (allowed) {
951 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -0700952 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -0700953 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -0700954 }
955 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 }
957
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900958 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
959 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
960 boolean removed = false;
961 boolean added = false;
962 synchronized (mBlockedAppUids) {
963 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
964 added = true;
965 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
966 removed = true;
967 }
968 }
969 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
970 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
971 }
972
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700973 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600974 * Apply any relevant filters to {@link NetworkState} for the given UID. For
975 * example, this may mark the network as {@link DetailedState#BLOCKED} based
976 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
977 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600979 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600980 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
981
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600982 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600983 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700984 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600985 if (mLockdownTracker != null) {
986 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700987 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600988
989 // TODO: apply metered state closer to NetworkAgentInfo
990 final long token = Binder.clearCallingIdentity();
991 try {
992 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
993 } catch (RemoteException e) {
994 } finally {
995 Binder.restoreCallingIdentity(token);
996 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700997 }
998
999 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 * Return NetworkInfo for the active (i.e., connected) network interface.
1001 * It is assumed that at most one network is active at a time. If more
1002 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001003 * @return the info for the active network, or {@code null} if none is
1004 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001006 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001008 enforceAccessPermission();
1009 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001010 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001011 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001012 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1013 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 }
1015
Paul Jensen31a94f42015-02-13 14:18:39 -05001016 @Override
1017 public Network getActiveNetwork() {
1018 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001019 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001020 }
1021
1022 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001023 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001024 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001025 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001026 }
1027
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001028 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001029 final int user = UserHandle.getUserId(uid);
1030 int vpnNetId = NETID_UNSET;
1031 synchronized (mVpns) {
1032 final Vpn vpn = mVpns.get(user);
1033 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1034 }
1035 NetworkAgentInfo nai;
1036 if (vpnNetId != NETID_UNSET) {
1037 synchronized (mNetworkForNetId) {
1038 nai = mNetworkForNetId.get(vpnNetId);
1039 }
1040 if (nai != null) return nai.network;
1041 }
1042 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001043 if (nai != null
1044 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1045 nai = null;
1046 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001047 return nai != null ? nai.network : null;
1048 }
1049
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001050 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1051 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001052 final int uid = Binder.getCallingUid();
1053 NetworkState state = getUnfilteredActiveNetworkState(uid);
1054 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001055 }
1056
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001058 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001059 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001060 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001061 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001062 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001063 }
1064
1065 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 public NetworkInfo getNetworkInfo(int networkType) {
1067 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001069 if (getVpnUnderlyingNetworks(uid) != null) {
1070 // A VPN is active, so we may need to return one of its underlying networks. This
1071 // information is not available in LegacyTypeTracker, so we have to get it from
1072 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001073 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001074 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001075 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001076 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001077 }
1078 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001079 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001080 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001083 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001084 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001085 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001086 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001087 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001088 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001089 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001090 return state.networkInfo;
1091 } else {
1092 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001093 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001094 }
1095
1096 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 public NetworkInfo[] getAllNetworkInfo() {
1098 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001099 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001100 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1101 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001102 NetworkInfo info = getNetworkInfo(networkType);
1103 if (info != null) {
1104 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001107 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001110 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001111 public Network getNetworkForType(int networkType) {
1112 enforceAccessPermission();
1113 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001114 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1115 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001116 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001117 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001118 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001119 }
1120
1121 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001122 public Network[] getAllNetworks() {
1123 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001124 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001125 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001126 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001127 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001128 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001129 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001130 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001131 }
1132
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001133 @Override
1134 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1135 // The basic principle is: if an app's traffic could possibly go over a
1136 // network, without the app doing anything multinetwork-specific,
1137 // (hence, by "default"), then include that network's capabilities in
1138 // the array.
1139 //
1140 // In the normal case, app traffic only goes over the system's default
1141 // network connection, so that's the only network returned.
1142 //
1143 // With a VPN in force, some app traffic may go into the VPN, and thus
1144 // over whatever underlying networks the VPN specifies, while other app
1145 // traffic may go over the system default network (e.g.: a split-tunnel
1146 // VPN, or an app disallowed by the VPN), so the set of networks
1147 // returned includes the VPN's underlying networks and the system
1148 // default.
1149 enforceAccessPermission();
1150
1151 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1152
1153 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001154 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001155 if (nc != null) {
1156 result.put(nai.network, nc);
1157 }
1158
1159 if (!mLockdownEnabled) {
1160 synchronized (mVpns) {
1161 Vpn vpn = mVpns.get(userId);
1162 if (vpn != null) {
1163 Network[] networks = vpn.getUnderlyingNetworks();
1164 if (networks != null) {
1165 for (Network network : networks) {
1166 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001167 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001168 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001169 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001170 }
1171 }
1172 }
1173 }
1174 }
1175 }
1176
1177 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1178 out = result.values().toArray(out);
1179 return out;
1180 }
1181
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001182 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001183 public boolean isNetworkSupported(int networkType) {
1184 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001186 }
1187
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001188 /**
1189 * Return LinkProperties for the active (i.e., connected) default
1190 * network interface. It is assumed that at most one default network
1191 * is active at a time. If more than one is active, it is indeterminate
1192 * which will be returned.
1193 * @return the ip properties for the active network, or {@code null} if
1194 * none is active
1195 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001196 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001197 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001198 enforceAccessPermission();
1199 final int uid = Binder.getCallingUid();
1200 NetworkState state = getUnfilteredActiveNetworkState(uid);
1201 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001202 }
1203
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001204 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001205 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001206 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001207 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1208 if (nai != null) {
1209 synchronized (nai) {
1210 return new LinkProperties(nai.linkProperties);
1211 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001212 }
1213 return null;
1214 }
1215
Robert Greenwalt12e67352014-05-13 21:41:06 -07001216 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001217 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001218 public LinkProperties getLinkProperties(Network network) {
1219 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001221 if (nai != null) {
1222 synchronized (nai) {
1223 return new LinkProperties(nai.linkProperties);
1224 }
1225 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001226 return null;
1227 }
1228
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001229 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001230 if (nai != null) {
1231 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001232 if (nai.networkCapabilities != null) {
1233 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001234 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001235 }
1236 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001237 return null;
1238 }
1239
1240 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001241 public NetworkCapabilities getNetworkCapabilities(Network network) {
1242 enforceAccessPermission();
1243 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1244 }
1245
1246 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001247 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001248 // Require internal since we're handing out IMSI details
1249 enforceConnectivityInternalPermission();
1250
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001251 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001252 for (Network network : getAllNetworks()) {
1253 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1254 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001255 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001256 }
1257 }
1258 return result.toArray(new NetworkState[result.size()]);
1259 }
1260
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001261 @Override
1262 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1263 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001264 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001265 final long token = Binder.clearCallingIdentity();
1266 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001267 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1268 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001269 try {
1270 return mPolicyManager.getNetworkQuotaInfo(state);
1271 } catch (RemoteException e) {
1272 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001273 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001274 return null;
1275 } finally {
1276 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001277 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001278 }
1279
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001280 @Override
1281 public boolean isActiveNetworkMetered() {
1282 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001283
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001284 final NetworkInfo info = getActiveNetworkInfo();
1285 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001286 }
1287
Jeff Sharkey216c1812012-08-05 14:29:23 -07001288 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1289 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001290 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001291 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001292 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001293 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001294 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001295
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001296 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 * Ensure that a network route exists to deliver traffic to the specified
1298 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001299 * @param networkType the type of the network over which traffic to the
1300 * specified host is to be routed
1301 * @param hostAddress the IP address of the host to which the route is
1302 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 * @return {@code true} on success, {@code false} on failure
1304 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001305 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001307 if (mProtectedNetworks.contains(networkType)) {
1308 enforceConnectivityInternalPermission();
1309 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001310
Chad Brubakerc0234532014-02-14 13:24:29 -08001311 InetAddress addr;
1312 try {
1313 addr = InetAddress.getByAddress(hostAddress);
1314 } catch (UnknownHostException e) {
1315 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1316 return false;
1317 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001320 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 return false;
1322 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001323
1324 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1325 if (nai == null) {
1326 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1327 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1328 } else {
1329 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1330 }
1331 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001332 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001333
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001334 DetailedState netState;
1335 synchronized (nai) {
1336 netState = nai.networkInfo.getDetailedState();
1337 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001338
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001339 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001340 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001341 log("requestRouteToHostAddress on down network "
1342 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001343 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001344 }
1345 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001347
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001348 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001349 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001350 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001351 LinkProperties lp;
1352 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001353 synchronized (nai) {
1354 lp = nai.linkProperties;
1355 netId = nai.network.netId;
1356 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001357 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001358 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1359 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001360 } finally {
1361 Binder.restoreCallingIdentity(token);
1362 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001363 }
1364
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001365 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001366 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001367 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001368 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001369 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001370 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001371 if (bestRoute.getGateway().equals(addr)) {
1372 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001373 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001374 } else {
1375 // if we will connect to this through another route, add a direct route
1376 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001377 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001378 }
1379 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001380 if (DBG) log("Adding legacy route " + bestRoute +
1381 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001382 try {
1383 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1384 } catch (Exception e) {
1385 // never crash - catch them all
1386 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001387 return false;
1388 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001389 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
1391
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001392 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1393 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001394 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001395 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001396 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001397 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001398 }
1399
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001400 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001401 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001402 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001403 if (oldRules == uidRules) return;
1404
Felipe Leme781ba142016-05-09 16:24:48 -07001405 if (uidRules == RULE_NONE) {
1406 mUidRules.delete(uid);
1407 } else {
1408 mUidRules.put(uid, uidRules);
1409 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001410 }
1411
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001412 // TODO: notify UID when it has requested targeted updates
1413 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001414
1415 @Override
1416 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001417 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001418 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001419 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001420 }
1421
1422 synchronized (mRulesLock) {
1423 mMeteredIfaces.clear();
1424 for (String iface : meteredIfaces) {
1425 mMeteredIfaces.add(iface);
1426 }
1427 }
1428 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001429
1430 @Override
1431 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1432 // caller is NPMS, since we only register with them
1433 if (LOGD_RULES) {
1434 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1435 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001436
1437 synchronized (mRulesLock) {
1438 mRestrictBackground = restrictBackground;
1439 }
1440
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001441 if (restrictBackground) {
1442 log("onRestrictBackgroundChanged(true): disabling tethering");
1443 mTethering.untetherAll();
1444 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001445 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001446
1447 @Override
1448 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1449 if (LOGD_RULES) {
1450 // caller is NPMS, since we only register with them
1451 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1452 + whitelisted + ")");
1453 }
1454 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001455 @Override
1456 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1457 if (LOGD_RULES) {
1458 // caller is NPMS, since we only register with them
1459 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1460 + blacklisted + ")");
1461 }
1462 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001463 };
1464
Robin Lee3b3dd942015-05-12 18:14:58 +01001465 /**
1466 * Require that the caller is either in the same user or has appropriate permission to interact
1467 * across users.
1468 *
1469 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1470 */
1471 private void enforceCrossUserPermission(int userId) {
1472 if (userId == UserHandle.getCallingUserId()) {
1473 // Not a cross-user call.
1474 return;
1475 }
1476 mContext.enforceCallingOrSelfPermission(
1477 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1478 "ConnectivityService");
1479 }
1480
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001481 private void enforceInternetPermission() {
1482 mContext.enforceCallingOrSelfPermission(
1483 android.Manifest.permission.INTERNET,
1484 "ConnectivityService");
1485 }
1486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001488 mContext.enforceCallingOrSelfPermission(
1489 android.Manifest.permission.ACCESS_NETWORK_STATE,
1490 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492
1493 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001494 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001497 private void enforceTetherAccessPermission() {
1498 mContext.enforceCallingOrSelfPermission(
1499 android.Manifest.permission.ACCESS_NETWORK_STATE,
1500 "ConnectivityService");
1501 }
1502
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001503 private void enforceConnectivityInternalPermission() {
1504 mContext.enforceCallingOrSelfPermission(
1505 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1506 "ConnectivityService");
1507 }
1508
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001509 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001510 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001511 }
1512
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001513 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001514 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001515 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001516 }
1517
1518 private void sendInetConditionBroadcast(NetworkInfo info) {
1519 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1520 }
1521
Wink Saville628b0852011-08-04 15:01:58 -07001522 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001523 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001524 info = new NetworkInfo(info);
1525 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001526 }
1527
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001528 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001529 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001530 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 if (info.isFailover()) {
1532 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1533 info.setFailover(false);
1534 }
1535 if (info.getReason() != null) {
1536 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1537 }
1538 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001539 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1540 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001542 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001543 return intent;
1544 }
1545
1546 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1547 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1548 }
1549
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001550 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001551 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1552 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1553 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001554 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001555 final long ident = Binder.clearCallingIdentity();
1556 try {
1557 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1558 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1559 } finally {
1560 Binder.restoreCallingIdentity(ident);
1561 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001562 }
1563
Mike Lockwood0f79b542009-08-14 14:18:49 -04001564 private void sendStickyBroadcast(Intent intent) {
1565 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001566 if (!mSystemReady) {
1567 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001568 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001569 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001570 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001571 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001572 }
1573
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001574 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001575 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001576 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001577 final NetworkInfo ni = intent.getParcelableExtra(
1578 ConnectivityManager.EXTRA_NETWORK_INFO);
1579 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1580 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1581 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001582 } else {
1583 BroadcastOptions opts = BroadcastOptions.makeBasic();
1584 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1585 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001586 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001587 final IBatteryStats bs = BatteryStatsService.getService();
1588 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001589 bs.noteConnectivityChanged(intent.getIntExtra(
1590 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1591 ni != null ? ni.getState().toString() : "?");
1592 } catch (RemoteException e) {
1593 }
1594 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001595 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001596 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001597 } finally {
1598 Binder.restoreCallingIdentity(ident);
1599 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001600 }
1601 }
1602
1603 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001604 loadGlobalProxy();
1605
Mike Lockwood0f79b542009-08-14 14:18:49 -04001606 synchronized(this) {
1607 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001608 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001609 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001610 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001611 }
1612 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001613 // load the global proxy at startup
1614 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001615
Robin Lee244ce8e2016-01-05 18:03:46 +00001616 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1617 // for user to unlock device too.
1618 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001619
Erik Klineda4bfa82015-04-30 12:58:40 +09001620 // Configure whether mobile data is always on.
1621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1622
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001623 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001624
1625 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001629 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001630 *
1631 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001632 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001633 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001634 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1635 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001636
1637 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001638 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001639
Robert Greenwalt7b816022014-04-18 15:25:25 -07001640 if (networkAgent.networkCapabilities.hasTransport(
1641 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001642 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1643 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001644 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001645 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001646 } else if (networkAgent.networkCapabilities.hasTransport(
1647 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001648 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1649 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001650 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001652 } else {
1653 // do not track any other networks
1654 timeout = 0;
1655 }
1656
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001658 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001659 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001660 } catch (Exception e) {
1661 // You shall not crash!
1662 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001663 }
1664 }
1665 }
1666
1667 /**
1668 * Remove data activity tracking when network disconnects.
1669 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001670 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1671 final String iface = networkAgent.linkProperties.getInterfaceName();
1672 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001673
Robert Greenwalt7b816022014-04-18 15:25:25 -07001674 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1675 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001676 try {
1677 // the call fails silently if no idletimer setup for this interface
1678 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001679 } catch (Exception e) {
1680 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001681 }
1682 }
1683 }
1684
1685 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001686 * Reads the network specific MTU size from reources.
1687 * and set it on it's iface.
1688 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001689 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1690 final String iface = newLp.getInterfaceName();
1691 final int mtu = newLp.getMtu();
1692 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1693 if (VDBG) log("identical MTU - not setting");
1694 return;
1695 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001696
Robert Greenwalt43074032014-08-15 17:53:05 -07001697 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001698 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001699 return;
1700 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001701
w1997615afd812014-08-05 15:18:11 -07001702 // Cannot set MTU without interface name
1703 if (TextUtils.isEmpty(iface)) {
1704 loge("Setting MTU size with null iface.");
1705 return;
1706 }
1707
Robert Greenwalt7b816022014-04-18 15:25:25 -07001708 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001709 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001710 mNetd.setMtu(iface, mtu);
1711 } catch (Exception e) {
1712 Slog.e(TAG, "exception in setMtu()" + e);
1713 }
1714 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001715
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001716 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001717 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1718
1719 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001720 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001721 protected int getDefaultTcpRwnd() {
1722 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1723 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001724
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001725 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1726 if (isDefaultNetwork(nai) == false) {
1727 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001728 }
1729
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001730 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1731 String[] values = null;
1732 if (tcpBufferSizes != null) {
1733 values = tcpBufferSizes.split(",");
1734 }
1735
1736 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001737 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001738 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1739 values = tcpBufferSizes.split(",");
1740 }
1741
1742 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1743
1744 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001745 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001746
1747 final String prefix = "/sys/kernel/ipv4/tcp_";
1748 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1749 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1750 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1751 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1752 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1753 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1754 mCurrentTcpBufferSizes = tcpBufferSizes;
1755 } catch (IOException e) {
1756 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001757 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001758
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001759 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001760 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001761 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1762 if (rwndValue != 0) {
1763 SystemProperties.set(sysctlKey, rwndValue.toString());
1764 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001765 }
1766
Mattias Falk8b47b362011-08-23 14:15:13 +02001767 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001768 /*
1769 * Tell the VMs to toss their DNS caches
1770 */
1771 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1772 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001773 /*
1774 * Connectivity events can happen before boot has completed ...
1775 */
1776 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001777 final long ident = Binder.clearCallingIdentity();
1778 try {
1779 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1780 } finally {
1781 Binder.restoreCallingIdentity(ident);
1782 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001783 }
1784
Robert Greenwalt562cc542014-05-15 18:07:26 -07001785 @Override
1786 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001787 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1788 NETWORK_RESTORE_DELAY_PROP_NAME);
1789 if(restoreDefaultNetworkDelayStr != null &&
1790 restoreDefaultNetworkDelayStr.length() != 0) {
1791 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001792 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001793 } catch (NumberFormatException e) {
1794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001796 // if the system property isn't set, use the value for the apn type
1797 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1798
1799 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1800 (mNetConfigs[networkType] != null)) {
1801 ret = mNetConfigs[networkType].restoreTime;
1802 }
1803 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 }
1805
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001806 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001807 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001808 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001809 }
1810 return false;
1811 }
1812
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001813 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1814 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1815 final long DIAG_TIME_MS = 5000;
1816 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1817 // Start gathering diagnostic information.
1818 netDiags.add(new NetworkDiagnostics(
1819 nai.network,
1820 new LinkProperties(nai.linkProperties), // Must be a copy.
1821 DIAG_TIME_MS));
1822 }
1823
1824 for (NetworkDiagnostics netDiag : netDiags) {
1825 pw.println();
1826 netDiag.waitForMeasurements();
1827 netDiag.dump(pw);
1828 }
1829 }
1830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001832 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1833 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001834 if (mContext.checkCallingOrSelfPermission(
1835 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001837 pw.println("Permission Denial: can't dump ConnectivityService " +
1838 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1839 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 return;
1841 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001842
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001843 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001844 dumpNetworkDiagnostics(pw);
1845 return;
1846 }
Erik Kline379747a2015-06-05 17:47:34 +09001847
Lorenzo Colittie3805462015-06-03 11:18:24 +09001848 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001849 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001850 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001851 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001852 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001853 pw.println();
1854
Paul Jensen85cf78e2015-06-25 13:25:07 -04001855 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001856 pw.print("Active default network: ");
1857 if (defaultNai == null) {
1858 pw.println("none");
1859 } else {
1860 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001862 pw.println();
1863
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001864 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001865 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001866 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1867 pw.println(nai.toString());
1868 pw.increaseIndent();
1869 pw.println("Requests:");
1870 pw.increaseIndent();
1871 for (int i = 0; i < nai.networkRequests.size(); i++) {
1872 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001873 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001874 pw.decreaseIndent();
1875 pw.println("Lingered:");
1876 pw.increaseIndent();
1877 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1878 pw.decreaseIndent();
1879 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001880 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001881 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001882 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001883
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001884 pw.println("Metered Interfaces:");
1885 pw.increaseIndent();
1886 for (String value : mMeteredIfaces) {
1887 pw.println(value);
1888 }
1889 pw.decreaseIndent();
1890 pw.println();
1891
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001892 pw.print("Restrict background: ");
1893 pw.println(mRestrictBackground);
1894 pw.println();
1895
Felipe Leme46c4fc32016-05-04 09:21:43 -07001896 pw.println("Status for known UIDs:");
1897 pw.increaseIndent();
1898 final int size = mUidRules.size();
1899 for (int i = 0; i < size; i++) {
1900 final int uid = mUidRules.keyAt(i);
1901 pw.print("UID=");
1902 pw.print(uid);
1903 final int uidRules = mUidRules.get(uid, RULE_NONE);
1904 pw.print(" rules=");
1905 pw.print(uidRulesToString(uidRules));
1906 pw.println();
1907 }
1908 pw.println();
1909 pw.decreaseIndent();
1910
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001911 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001912 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001913 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1914 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001915 }
1916 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001917 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001918
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001919 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001920
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001921 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001922 pw.print("mNetTransitionWakeLock: currently " +
1923 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1924 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1925 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1926 } else {
1927 pw.println(", last requested never");
1928 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001929 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001930
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001931 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001932 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001933
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001934 pw.println();
1935 mKeepaliveTracker.dump(pw);
1936
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001937 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001938
Lorenzo Colittie3805462015-06-03 11:18:24 +09001939 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001940 pw.println();
1941 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001942 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001943 for(int i = 0; i < mInetLog.size(); i++) {
1944 pw.println(mInetLog.get(i));
1945 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001946 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001947 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001948
1949 if (argsContain(args, "--short") == false) {
1950 pw.println();
1951 synchronized (mValidationLogs) {
1952 pw.println("mValidationLogs (most recent first):");
1953 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1954 pw.println(p.first);
1955 pw.increaseIndent();
1956 p.second.dump(fd, pw, args);
1957 pw.decreaseIndent();
1958 }
1959 }
Erik Kline7523eb32015-07-09 18:24:03 +09001960
1961 pw.println();
1962 pw.println("mNetworkRequestInfoLogs (most recent first):");
1963 pw.increaseIndent();
1964 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1965 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
1968
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001969 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001970 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001971 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001972 if (officialNai != null && officialNai.equals(nai)) return true;
1973 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001974 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001975 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001976 " - " + nai);
1977 }
1978 return false;
1979 }
1980
Paul Jensenc8b9a742014-09-30 15:37:41 -04001981 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001982 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001983 }
1984
Robert Greenwalt42acef32009-08-12 16:08:25 -07001985 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001986 private class NetworkStateTrackerHandler extends Handler {
1987 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001988 super(looper);
1989 }
1990
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001991 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001993 default:
1994 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001995 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001996 handleAsyncChannelHalfConnect(msg);
1997 break;
1998 }
1999 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2000 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2001 if (nai != null) nai.asyncChannel.disconnect();
2002 break;
2003 }
2004 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2005 handleAsyncChannelDisconnected(msg);
2006 break;
2007 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002008 }
2009 return true;
2010 }
2011
2012 private void maybeHandleNetworkAgentMessage(Message msg) {
2013 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2014 if (nai == null) {
2015 if (VDBG) {
2016 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2017 log(String.format("%s from unknown NetworkAgent", what));
2018 }
2019 return;
2020 }
2021
2022 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002023 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002024 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2025 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2026 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2027 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002028 }
Robin Lee585e2482016-05-01 23:00:00 +01002029 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002030 networkCapabilities)) {
2031 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2032 + nai.networkCapabilities + " -> " + networkCapabilities);
2033 }
2034 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002035 break;
2036 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002037 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002038 if (VDBG) {
2039 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002040 "; created=" + nai.created +
2041 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002042 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002043 LinkProperties oldLp = nai.linkProperties;
2044 synchronized (nai) {
2045 nai.linkProperties = (LinkProperties)msg.obj;
2046 }
Robin Lee585e2482016-05-01 23:00:00 +01002047 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002048 break;
2049 }
2050 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002051 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002052 updateNetworkInfo(nai, info);
2053 break;
2054 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002055 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002056 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002057 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002058 break;
2059 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002060 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002061 try {
2062 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002063 } catch (Exception e) {
2064 // Never crash!
2065 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002066 }
2067 break;
2068 }
2069 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002070 try {
2071 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002072 } catch (Exception e) {
2073 // Never crash!
2074 loge("Exception in removeVpnUidRanges: " + e);
2075 }
2076 break;
2077 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002078 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002079 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2080 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002081 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002082 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002083 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002084 break;
2085 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002086 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002087 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2088 break;
2089 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002090 }
2091 }
2092
2093 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2094 switch (msg.what) {
2095 default:
2096 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002097 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002098 final NetworkAgentInfo nai;
2099 synchronized (mNetworkForNetId) {
2100 nai = mNetworkForNetId.get(msg.arg2);
2101 }
2102 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002103 final boolean valid =
2104 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002105 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2106 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002107 if (valid != nai.lastValidated) {
2108 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002109 nai.lastValidated = valid;
2110 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002111 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002112 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2113 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002114 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002115 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002116 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002117 Bundle redirectUrlBundle = new Bundle();
2118 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002119 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002120 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002121 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002122 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002123 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002124 break;
2125 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002126 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002127 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002128 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002129 handleLingerComplete(nai);
2130 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002131 break;
2132 }
Paul Jensen869868be2014-05-15 10:33:05 -04002133 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002134 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002135 final boolean visible = (msg.arg1 != 0);
2136 final NetworkAgentInfo nai;
2137 synchronized (mNetworkForNetId) {
2138 nai = mNetworkForNetId.get(netId);
2139 }
2140 // If captive portal status has changed, update capabilities.
2141 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2142 nai.lastCaptivePortalDetected = visible;
2143 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002144 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002145 }
2146 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002147 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002148 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002149 if (nai == null) {
2150 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2151 break;
2152 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002153 if (!nai.networkMisc.provisioningNotificationDisabled) {
2154 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
2155 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2156 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
2157 }
Paul Jensen869868be2014-05-15 10:33:05 -04002158 }
Paul Jensen869868be2014-05-15 10:33:05 -04002159 break;
2160 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002161 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002162 return true;
2163 }
2164
2165 @Override
2166 public void handleMessage(Message msg) {
2167 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2168 maybeHandleNetworkAgentMessage(msg);
2169 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002170 }
2171 }
2172
Paul Jensen85cf78e2015-06-25 13:25:07 -04002173 private void linger(NetworkAgentInfo nai) {
2174 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002175 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002176 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2177 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2178 }
2179
Paul Jensen0cc17322014-11-25 15:26:53 -05002180 // Cancel any lingering so the linger timeout doesn't teardown a network.
2181 // This should be called when a network begins satisfying a NetworkRequest.
2182 // Note: depending on what state the NetworkMonitor is in (e.g.,
2183 // if it's awaiting captive portal login, or if validation failed), this
2184 // may trigger a re-evaluation of the network.
2185 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002186 nai.networkLingered.clear();
2187 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002188 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002189 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002190 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002191 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2192 }
2193
Robert Greenwalt7b816022014-04-18 15:25:25 -07002194 private void handleAsyncChannelHalfConnect(Message msg) {
2195 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002196 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002197 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2198 if (VDBG) log("NetworkFactory connected");
2199 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002200 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002201 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002202 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002203 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002204 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002205 }
2206 } else {
2207 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002208 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002209 }
2210 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2211 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2212 if (VDBG) log("NetworkAgent connected");
2213 // A network agent has requested a connection. Establish the connection.
2214 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2215 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2216 } else {
2217 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002218 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002219 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002220 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002221 synchronized (mNetworkForNetId) {
2222 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002223 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002224 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002225 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002226 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002227 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002228 }
2229 }
2230 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002231
Robert Greenwalt7b816022014-04-18 15:25:25 -07002232 private void handleAsyncChannelDisconnected(Message msg) {
2233 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2234 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002235 if (DBG) {
2236 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2237 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002238 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002239 // TODO - if we move the logic to the network agent (have them disconnect
2240 // because they lost all their requests or because their score isn't good)
2241 // then they would disconnect organically, report their new state and then
2242 // disconnect the channel.
2243 if (nai.networkInfo.isConnected()) {
2244 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2245 null, null);
2246 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002247 final boolean wasDefault = isDefaultNetwork(nai);
2248 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002249 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002250 // Log default network disconnection before required book-keeping.
2251 // Let rematchAllNetworksAndRequests() below record a new default network event
2252 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2253 // whose timestamps tell how long it takes to recover a default network.
2254 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002255 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002256 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002257 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2258 // by other networks that are already connected. Perhaps that can be done by
2259 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2260 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002261 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002262 mKeepaliveTracker.handleStopAllKeepalives(nai,
2263 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002264 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002265 mNetworkAgentInfos.remove(msg.replyTo);
2266 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002267 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002268 // Remove the NetworkAgent, but don't mark the netId as
2269 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002270 mNetworkForNetId.remove(nai.network.netId);
2271 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002272 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002273 for (int i = 0; i < nai.networkRequests.size(); i++) {
2274 NetworkRequest request = nai.networkRequests.valueAt(i);
2275 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2276 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2277 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002278 sendUpdatedScoreToFactories(request, 0);
2279 }
2280 }
2281 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2282 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002283 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002284 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002285 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002286 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002287 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002288 if (nai.created) {
2289 // Tell netd to clean up the configuration for this network
2290 // (routing rules, DNS, etc).
2291 // This may be slow as it requires a lot of netd shelling out to ip and
2292 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2293 // after we've rematched networks with requests which should make a potential
2294 // fallback network the default or requested a new network from the
2295 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2296 // long time.
2297 try {
2298 mNetd.removeNetwork(nai.network.netId);
2299 } catch (Exception e) {
2300 loge("Exception removing network: " + e);
2301 }
2302 }
2303 synchronized (mNetworkForNetId) {
2304 mNetIdInUse.delete(nai.network.netId);
2305 }
2306 } else {
2307 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2308 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002309 }
2310 }
2311
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002312 // If this method proves to be too slow then we can maintain a separate
2313 // pendingIntent => NetworkRequestInfo map.
2314 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2315 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2316 Intent intent = pendingIntent.getIntent();
2317 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2318 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2319 if (existingPendingIntent != null &&
2320 existingPendingIntent.getIntent().filterEquals(intent)) {
2321 return entry.getValue();
2322 }
2323 }
2324 return null;
2325 }
2326
2327 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2328 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2329
2330 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2331 if (existingRequest != null) { // remove the existing request.
2332 if (DBG) log("Replacing " + existingRequest.request + " with "
2333 + nri.request + " because their intents matched.");
2334 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2335 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002336 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002337 }
2338
Erik Klineda4bfa82015-04-30 12:58:40 +09002339 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002340 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002341 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002342 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002343 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002344 if (nri.request.networkCapabilities.hasSignalStrength() &&
2345 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2346 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002347 }
2348 }
2349 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002350 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002351 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002352 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002353 }
2354 }
2355
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002356 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2357 int callingUid) {
2358 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2359 if (nri != null) {
2360 handleReleaseNetworkRequest(nri.request, callingUid);
2361 }
2362 }
2363
Paul Jensen99364842014-12-09 11:43:45 -05002364 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002365 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2366 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002367 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002368 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002369 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2370 // If this Network is already the highest scoring Network for a request, or if
2371 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002372 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002373 (nai.networkRequests.get(nri.request.requestId) != null ||
2374 // Note that this catches two important cases:
2375 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2376 // is currently satisfying the request. This is desirable when
2377 // cellular ends up validating but WiFi does not.
2378 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002379 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002380 // WiFi ends up validating and out scoring cellular.
2381 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2382 nai.getCurrentScoreAsValidated())) {
2383 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002384 }
2385 }
Paul Jensene0988542015-06-25 15:30:08 -04002386 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002387 }
2388
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002389 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2390 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002391 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002392 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002393 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2394 return;
2395 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002396 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002397 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002398 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002399 synchronized (mUidToNetworkRequestCount) {
2400 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2401 if (requests < 1) {
2402 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2403 nri.mUid);
2404 } else if (requests == 1) {
2405 mUidToNetworkRequestCount.removeAt(
2406 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2407 } else {
2408 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2409 }
2410 }
Erik Kline7523eb32015-07-09 18:24:03 +09002411 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002412 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002413 // Find all networks that are satisfying this request and remove the request
2414 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002415 // TODO - it's my understanding that for a request there is only a single
2416 // network satisfying it, so this loop is wasteful
2417 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002418 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2419 if (nai.networkRequests.get(nri.request.requestId) != null) {
2420 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002421 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002422 log(" Removing from current network " + nai.name() +
2423 ", leaving " + nai.networkRequests.size() +
2424 " requests.");
2425 }
Paul Jensen99364842014-12-09 11:43:45 -05002426 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002427 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002428 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002429 } else {
2430 // suspect there should only be one pass through here
2431 // but if any were kept do the check below
2432 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002433 }
2434 }
2435 }
2436
Robert Greenwalt51481852015-01-08 14:43:31 -08002437 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2438 if (nai != null) {
2439 mNetworkForRequestId.remove(nri.request.requestId);
2440 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002441 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002442 // that a network connected to serve it, even though the network was already
2443 // connected. Now that this request has gone away, we might have to pretend
2444 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002445 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002446 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2447 boolean doRemove = true;
2448 if (wasKept) {
2449 // check if any of the remaining requests for this network are for the
2450 // same legacy type - if so, don't remove the nai
2451 for (int i = 0; i < nai.networkRequests.size(); i++) {
2452 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2453 if (otherRequest.legacyType == nri.request.legacyType &&
2454 isRequest(otherRequest)) {
2455 if (DBG) log(" still have other legacy request - leaving");
2456 doRemove = false;
2457 }
2458 }
2459 }
2460
2461 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002462 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002463 }
2464 }
2465
Robert Greenwalta67be032014-05-16 15:49:14 -07002466 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002467 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2468 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002469 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002470 } else {
2471 // listens don't have a singular affectedNetwork. Check all networks to see
2472 // if this listen request applies and remove it.
2473 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2474 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002475 if (nri.request.networkCapabilities.hasSignalStrength() &&
2476 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2477 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002478 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002479 }
2480 }
2481 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2482 }
2483 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002484
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002485 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2486 enforceConnectivityInternalPermission();
2487 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2488 accept ? 1 : 0, always ? 1: 0, network));
2489 }
2490
2491 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2492 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2493 " accept=" + accept + " always=" + always);
2494
2495 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2496 if (nai == null) {
2497 // Nothing to do.
2498 return;
2499 }
2500
2501 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002502 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002503 return;
2504 }
2505
2506 if (!nai.networkMisc.explicitlySelected) {
2507 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2508 }
2509
2510 if (accept != nai.networkMisc.acceptUnvalidated) {
2511 int oldScore = nai.getCurrentScore();
2512 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002513 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002514 sendUpdatedScoreToFactories(nai);
2515 }
2516
2517 if (always) {
2518 nai.asyncChannel.sendMessage(
2519 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2520 }
2521
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002522 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002523 // Tell the NetworkAgent to not automatically reconnect to the network.
2524 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2525 // Teardown the nework.
2526 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002527 }
2528
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002529 }
2530
2531 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002532 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002533 mHandler.sendMessageDelayed(
2534 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2535 PROMPT_UNVALIDATED_DELAY_MS);
2536 }
2537
2538 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002539 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002540 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2541
2542 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2543 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002544 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002545 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002546 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2547 return;
2548 }
2549
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002550 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002551 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002552 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2553 intent.setClassName("com.android.settings",
2554 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002555
2556 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2557 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
fionaxu1bf6ec22016-05-23 16:33:16 -07002558
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002559 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002560 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002561 }
2562
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002563 private class InternalHandler extends Handler {
2564 public InternalHandler(Looper looper) {
2565 super(looper);
2566 }
2567
2568 @Override
2569 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002570 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002571 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002572 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002573 String causedBy = null;
2574 synchronized (ConnectivityService.this) {
2575 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2576 mNetTransitionWakeLock.isHeld()) {
2577 mNetTransitionWakeLock.release();
2578 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002579 } else {
2580 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002581 }
2582 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002583 if (VDBG) {
2584 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2585 log("Failed to find a new network - expiring NetTransition Wakelock");
2586 } else {
2587 log("NetTransition Wakelock (" +
2588 (causedBy == null ? "unknown" : causedBy) +
2589 " cleared because we found a replacement network");
2590 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002591 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002592 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002593 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002594 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002595 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002596 break;
2597 }
Jason Monkdecd2952013-10-10 14:02:51 -04002598 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002599 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002600 break;
2601 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002602 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002603 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2604 break;
2605 }
2606 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2607 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002608 break;
2609 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002610 case EVENT_REGISTER_NETWORK_AGENT: {
2611 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2612 break;
2613 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002614 case EVENT_REGISTER_NETWORK_REQUEST:
2615 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002616 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002617 break;
2618 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002619 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2620 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002621 handleRegisterNetworkRequestWithIntent(msg);
2622 break;
2623 }
2624 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2625 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2626 break;
2627 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002628 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002629 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002630 break;
2631 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002632 case EVENT_SET_ACCEPT_UNVALIDATED: {
2633 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2634 break;
2635 }
2636 case EVENT_PROMPT_UNVALIDATED: {
2637 handlePromptUnvalidated((Network) msg.obj);
2638 break;
2639 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002640 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2641 handleMobileDataAlwaysOn();
2642 break;
2643 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002644 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2645 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2646 mKeepaliveTracker.handleStartKeepalive(msg);
2647 break;
2648 }
2649 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2650 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2651 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2652 int slot = msg.arg1;
2653 int reason = msg.arg2;
2654 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2655 break;
2656 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002657 case EVENT_SYSTEM_READY: {
2658 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2659 nai.networkMonitor.systemReady = true;
2660 }
2661 break;
2662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664 }
2665 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002666
2667 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002668 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002669 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002670 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002671 final int status = mTethering.tether(iface);
2672 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2673 try {
2674 mPolicyManager.onTetheringChanged(iface, true);
2675 } catch (RemoteException e) {
2676 }
2677 }
2678 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002679 } else {
2680 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2681 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002682 }
2683
2684 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002685 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002686 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002687
2688 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002689 final int status = mTethering.untether(iface);
2690 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2691 try {
2692 mPolicyManager.onTetheringChanged(iface, false);
2693 } catch (RemoteException e) {
2694 }
2695 }
2696 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002697 } else {
2698 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2699 }
2700 }
2701
2702 // javadoc from interface
2703 public int getLastTetherError(String iface) {
2704 enforceTetherAccessPermission();
2705
2706 if (isTetheringSupported()) {
2707 return mTethering.getLastTetherError(iface);
2708 } else {
2709 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2710 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002711 }
2712
2713 // TODO - proper iface API for selection by property, inspection, etc
2714 public String[] getTetherableUsbRegexs() {
2715 enforceTetherAccessPermission();
2716 if (isTetheringSupported()) {
2717 return mTethering.getTetherableUsbRegexs();
2718 } else {
2719 return new String[0];
2720 }
2721 }
2722
2723 public String[] getTetherableWifiRegexs() {
2724 enforceTetherAccessPermission();
2725 if (isTetheringSupported()) {
2726 return mTethering.getTetherableWifiRegexs();
2727 } else {
2728 return new String[0];
2729 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002730 }
2731
Danica Chang6fdd0c62010-08-11 14:54:43 -07002732 public String[] getTetherableBluetoothRegexs() {
2733 enforceTetherAccessPermission();
2734 if (isTetheringSupported()) {
2735 return mTethering.getTetherableBluetoothRegexs();
2736 } else {
2737 return new String[0];
2738 }
2739 }
2740
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002741 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002742 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002743 if (isTetheringSupported()) {
2744 return mTethering.setUsbTethering(enable);
2745 } else {
2746 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2747 }
2748 }
2749
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002750 // TODO - move iface listing, queries, etc to new module
2751 // javadoc from interface
2752 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002753 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002754 return mTethering.getTetherableIfaces();
2755 }
2756
2757 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002758 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002759 return mTethering.getTetheredIfaces();
2760 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002761
Robert Greenwalt5a735062010-03-02 17:25:02 -08002762 public String[] getTetheringErroredIfaces() {
2763 enforceTetherAccessPermission();
2764 return mTethering.getErroredIfaces();
2765 }
2766
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002767 public String[] getTetheredDhcpRanges() {
2768 enforceConnectivityInternalPermission();
2769 return mTethering.getTetheredDhcpRanges();
2770 }
2771
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002772 // if ro.tether.denied = true we default to no tethering
2773 // gservices could set the secure setting to 1 though to enable it on a build where it
2774 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002775 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002776 public boolean isTetheringSupported() {
2777 enforceTetherAccessPermission();
2778 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002779 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002780 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2781 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002782 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2783 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002784 mTethering.getTetherableWifiRegexs().length != 0 ||
2785 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2786 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002787 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002788
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002789 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002790 public void startTethering(int type, ResultReceiver receiver,
2791 boolean showProvisioningUi) {
2792 ConnectivityManager.enforceTetherChangePermission(mContext);
2793 if (!isTetheringSupported()) {
2794 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2795 return;
2796 }
2797 mTethering.startTethering(type, receiver, showProvisioningUi);
2798 }
2799
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002800 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002801 public void stopTethering(int type) {
2802 ConnectivityManager.enforceTetherChangePermission(mContext);
2803 mTethering.stopTethering(type);
2804 }
2805
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002806 // Called when we lose the default network and have no replacement yet.
2807 // This will automatically be cleared after X seconds or a new default network
2808 // becomes CONNECTED, whichever happens first. The timer is started by the
2809 // first caller and not restarted by subsequent callers.
2810 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002811 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002812 synchronized (this) {
2813 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002814 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002815 mNetTransitionWakeLock.acquire();
2816 mNetTransitionWakeLockCausedBy = forWhom;
2817 }
2818 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002819 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002820 mNetTransitionWakeLockTimeout);
2821 return;
2822 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002823
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002824 // 100 percent is full good, 0 is full bad.
2825 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002826 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002827 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002828 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002829 }
2830
Paul Jensenbfd17b72015-04-07 12:43:13 -04002831 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002832 enforceAccessPermission();
2833 enforceInternetPermission();
2834
Paul Jensenbfd17b72015-04-07 12:43:13 -04002835 NetworkAgentInfo nai;
2836 if (network == null) {
2837 nai = getDefaultNetwork();
2838 } else {
2839 nai = getNetworkAgentInfoForNetwork(network);
2840 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002841 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2842 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2843 return;
2844 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002845 // Revalidate if the app report does not match our current validated state.
2846 if (hasConnectivity == nai.lastValidated) return;
2847 final int uid = Binder.getCallingUid();
2848 if (DBG) {
2849 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2850 ") by " + uid);
2851 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002852 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002853 // Validating a network that has not yet connected could result in a call to
2854 // rematchNetworkAndRequests() which is not meant to work on such networks.
2855 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002856
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002857 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002858
2859 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2860 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002861 }
2862
Paul Jensencee9b512015-05-06 07:32:40 -04002863 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002864 // this information is already available as a world read/writable jvm property
2865 // so this API change wouldn't have a benifit. It also breaks the passing
2866 // of proxy info to all the JVMs.
2867 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002868 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002869 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002870 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2871 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002872 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002873 }
2874
Paul Jensencee9b512015-05-06 07:32:40 -04002875 public ProxyInfo getProxyForNetwork(Network network) {
2876 if (network == null) return getDefaultProxy();
2877 final ProxyInfo globalProxy = getGlobalProxy();
2878 if (globalProxy != null) return globalProxy;
2879 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2880 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2881 // caller may not have.
2882 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2883 if (nai == null) return null;
2884 synchronized (nai) {
2885 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2886 if (proxyInfo == null) return null;
2887 return new ProxyInfo(proxyInfo);
2888 }
2889 }
2890
Paul Jensene0bef712014-12-10 15:12:18 -05002891 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2892 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2893 // proxy is null then there is no proxy in place).
2894 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2895 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2896 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2897 proxy = null;
2898 }
2899 return proxy;
2900 }
2901
2902 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2903 // better for determining if a new proxy broadcast is necessary:
2904 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2905 // avoid unnecessary broadcasts.
2906 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2907 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2908 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2909 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2910 // all set.
2911 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2912 a = canonicalizeProxyInfo(a);
2913 b = canonicalizeProxyInfo(b);
2914 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2915 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2916 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2917 }
2918
Jason Monk207900c2014-04-25 15:00:09 -04002919 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002920 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002921
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002922 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002923 if (proxyProperties == mGlobalProxy) return;
2924 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2925 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2926
2927 String host = "";
2928 int port = 0;
2929 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002930 String pacFileUrl = "";
2931 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002932 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002933 if (!proxyProperties.isValid()) {
2934 if (DBG)
2935 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2936 return;
2937 }
Jason Monk207900c2014-04-25 15:00:09 -04002938 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002939 host = mGlobalProxy.getHost();
2940 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002941 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002942 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002943 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002944 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002945 } else {
2946 mGlobalProxy = null;
2947 }
2948 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002949 final long token = Binder.clearCallingIdentity();
2950 try {
2951 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2952 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2953 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2954 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002955 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002956 } finally {
2957 Binder.restoreCallingIdentity(token);
2958 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002959
Jason Monkcf0f97a2014-10-02 15:39:38 -04002960 if (mGlobalProxy == null) {
2961 proxyProperties = mDefaultProxy;
2962 }
2963 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002964 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002965 }
2966
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002967 private void loadGlobalProxy() {
2968 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002969 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2970 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2971 String exclList = Settings.Global.getString(res,
2972 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002973 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2974 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002975 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002976 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002977 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002978 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002979 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002980 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002981 if (!proxyProperties.isValid()) {
2982 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2983 return;
2984 }
2985
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002986 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002987 mGlobalProxy = proxyProperties;
2988 }
2989 }
2990 }
2991
Jason Monk207900c2014-04-25 15:00:09 -04002992 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002993 // this information is already available as a world read/writable jvm property
2994 // so this API change wouldn't have a benifit. It also breaks the passing
2995 // of proxy info to all the JVMs.
2996 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002997 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002998 return mGlobalProxy;
2999 }
3000 }
3001
Jason Monk207900c2014-04-25 15:00:09 -04003002 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003003 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003004 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003005 proxy = null;
3006 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003007 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003008 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003009 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003010 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003011 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3012 return;
3013 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003014
3015 // This call could be coming from the PacManager, containing the port of the local
3016 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3017 // global (to get the correct local port), and send a broadcast.
3018 // TODO: Switch PacManager to have its own message to send back rather than
3019 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003020 if ((mGlobalProxy != null) && (proxy != null)
3021 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003022 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3023 mGlobalProxy = proxy;
3024 sendProxyBroadcast(mGlobalProxy);
3025 return;
3026 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003027 mDefaultProxy = proxy;
3028
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003029 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003030 if (!mDefaultProxyDisabled) {
3031 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003032 }
3033 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003034 }
3035
Paul Jensene0bef712014-12-10 15:12:18 -05003036 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3037 // This method gets called when any network changes proxy, but the broadcast only ever contains
3038 // the default proxy (even if it hasn't changed).
3039 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3040 // world where an app might be bound to a non-default network.
3041 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3042 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3043 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3044
3045 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3046 sendProxyBroadcast(getDefaultProxy());
3047 }
3048 }
3049
Robert Greenwalt434203a2010-10-11 16:00:27 -07003050 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003051 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3052 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003053 if (!TextUtils.isEmpty(proxy)) {
3054 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003055 if (data.length == 0) {
3056 return;
3057 }
3058
Robert Greenwalt434203a2010-10-11 16:00:27 -07003059 String proxyHost = data[0];
3060 int proxyPort = 8080;
3061 if (data.length > 1) {
3062 try {
3063 proxyPort = Integer.parseInt(data[1]);
3064 } catch (NumberFormatException e) {
3065 return;
3066 }
3067 }
Jason Monk207900c2014-04-25 15:00:09 -04003068 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003069 setGlobalProxy(p);
3070 }
3071 }
3072
Jason Monk207900c2014-04-25 15:00:09 -04003073 private void sendProxyBroadcast(ProxyInfo proxy) {
3074 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003075 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003076 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003077 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003078 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3079 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003080 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003081 final long ident = Binder.clearCallingIdentity();
3082 try {
3083 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3084 } finally {
3085 Binder.restoreCallingIdentity(ident);
3086 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003087 }
3088
3089 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003090 final private HashMap<Uri, Integer> mUriEventMap;
3091 final private Context mContext;
3092 final private Handler mHandler;
3093
3094 SettingsObserver(Context context, Handler handler) {
3095 super(null);
3096 mUriEventMap = new HashMap<Uri, Integer>();
3097 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003098 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003099 }
3100
Erik Klineda4bfa82015-04-30 12:58:40 +09003101 void observe(Uri uri, int what) {
3102 mUriEventMap.put(uri, what);
3103 final ContentResolver resolver = mContext.getContentResolver();
3104 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003105 }
3106
3107 @Override
3108 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003109 Slog.wtf(TAG, "Should never be reached.");
3110 }
3111
3112 @Override
3113 public void onChange(boolean selfChange, Uri uri) {
3114 final Integer what = mUriEventMap.get(uri);
3115 if (what != null) {
3116 mHandler.obtainMessage(what.intValue()).sendToTarget();
3117 } else {
3118 loge("No matching event to send for URI=" + uri);
3119 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003120 }
3121 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003122
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003123 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003124 Slog.d(TAG, s);
3125 }
3126
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003127 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003128 Slog.e(TAG, s);
3129 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003130
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003131 private static <T> T checkNotNull(T value, String message) {
3132 if (value == null) {
3133 throw new NullPointerException(message);
3134 }
3135 return value;
3136 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003137
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003138 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003139 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003140 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3141 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3142 *
3143 * @param oldPackage Package name of the application which currently controls VPN, which will
3144 * be replaced. If there is no such application, this should should either be
3145 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3146 * @param newPackage Package name of the application which should gain control of VPN, or
3147 * {@code null} to disable.
3148 * @param userId User for whom to prepare the new VPN.
3149 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003150 * @hide
3151 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003152 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003153 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3154 int userId) {
3155 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003156 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003157
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003158 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003159 Vpn vpn = mVpns.get(userId);
3160 if (vpn != null) {
3161 return vpn.prepare(oldPackage, newPackage);
3162 } else {
3163 return false;
3164 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003165 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003166 }
3167
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003168 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003169 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3170 * This method is used by system-privileged apps.
3171 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3172 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3173 *
3174 * @param packageName The package for which authorization state should change.
3175 * @param userId User for whom {@code packageName} is installed.
3176 * @param authorized {@code true} if this app should be able to start a VPN connection without
3177 * explicit user approval, {@code false} if not.
3178 *
Jeff Davidson05542602014-08-11 14:07:27 -07003179 * @hide
3180 */
3181 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003182 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3183 enforceCrossUserPermission(userId);
3184
Jeff Davidson05542602014-08-11 14:07:27 -07003185 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003186 Vpn vpn = mVpns.get(userId);
3187 if (vpn != null) {
3188 vpn.setPackageAuthorization(packageName, authorized);
3189 }
Jeff Davidson05542602014-08-11 14:07:27 -07003190 }
3191 }
3192
3193 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003194 * Configure a TUN interface and return its file descriptor. Parameters
3195 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003196 * and not available in ConnectivityManager. Permissions are checked in
3197 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003198 * @hide
3199 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003200 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003201 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003202 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003203 int user = UserHandle.getUserId(Binder.getCallingUid());
3204 synchronized(mVpns) {
3205 return mVpns.get(user).establish(config);
3206 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003207 }
3208
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003209 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003210 * Start legacy VPN, controlling native daemons as needed. Creates a
3211 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003212 */
3213 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003214 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003215 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003216 final LinkProperties egress = getActiveLinkProperties();
3217 if (egress == null) {
3218 throw new IllegalStateException("Missing active network connection");
3219 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003220 int user = UserHandle.getUserId(Binder.getCallingUid());
3221 synchronized(mVpns) {
3222 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3223 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003224 }
3225
3226 /**
3227 * Return the information of the ongoing legacy VPN. This method is used
3228 * by VpnSettings and not available in ConnectivityManager. Permissions
3229 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003230 */
3231 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003232 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3233 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003234
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003235 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003236 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003237 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003238 }
3239
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003240 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003241 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3242 * and not available in ConnectivityManager.
3243 */
3244 @Override
3245 public VpnInfo[] getAllVpnInfo() {
3246 enforceConnectivityInternalPermission();
3247 if (mLockdownEnabled) {
3248 return new VpnInfo[0];
3249 }
3250
3251 synchronized(mVpns) {
3252 List<VpnInfo> infoList = new ArrayList<>();
3253 for (int i = 0; i < mVpns.size(); i++) {
3254 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3255 if (info != null) {
3256 infoList.add(info);
3257 }
3258 }
3259 return infoList.toArray(new VpnInfo[infoList.size()]);
3260 }
3261 }
3262
3263 /**
3264 * @return VPN information for accounting, or null if we can't retrieve all required
3265 * information, e.g primary underlying iface.
3266 */
3267 @Nullable
3268 private VpnInfo createVpnInfo(Vpn vpn) {
3269 VpnInfo info = vpn.getVpnInfo();
3270 if (info == null) {
3271 return null;
3272 }
3273 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3274 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3275 // the underlyingNetworks list.
3276 if (underlyingNetworks == null) {
3277 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3278 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3279 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3280 }
3281 } else if (underlyingNetworks.length > 0) {
3282 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3283 if (linkProperties != null) {
3284 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3285 }
3286 }
3287 return info.primaryUnderlyingIface == null ? null : info;
3288 }
3289
3290 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003291 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3292 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003293 * Permissions are checked in Vpn class.
3294 * @hide
3295 */
3296 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003297 public VpnConfig getVpnConfig(int userId) {
3298 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003299 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003300 Vpn vpn = mVpns.get(userId);
3301 if (vpn != null) {
3302 return vpn.getVpnConfig();
3303 } else {
3304 return null;
3305 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003306 }
3307 }
3308
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003309 @Override
3310 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003311 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3312 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3313 return false;
3314 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003315
3316 // Tear down existing lockdown if profile was removed
3317 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3318 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003319 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3320 final VpnProfile profile = VpnProfile.decode(
3321 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003322 if (profile == null) {
3323 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3324 setLockdownTracker(null);
3325 return true;
3326 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003327 int user = UserHandle.getUserId(Binder.getCallingUid());
3328 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003329 Vpn vpn = mVpns.get(user);
3330 if (vpn == null) {
3331 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3332 return false;
3333 }
3334 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003335 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003336 } else {
3337 setLockdownTracker(null);
3338 }
3339
3340 return true;
3341 }
3342
3343 /**
3344 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3345 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3346 */
3347 private void setLockdownTracker(LockdownVpnTracker tracker) {
3348 // Shutdown any existing tracker
3349 final LockdownVpnTracker existing = mLockdownTracker;
3350 mLockdownTracker = null;
3351 if (existing != null) {
3352 existing.shutdown();
3353 }
3354
3355 try {
3356 if (tracker != null) {
3357 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003358 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003359 mLockdownTracker = tracker;
3360 mLockdownTracker.init();
3361 } else {
3362 mNetd.setFirewallEnabled(false);
3363 }
3364 } catch (RemoteException e) {
3365 // ignored; NMS lives inside system_server
3366 }
3367 }
3368
3369 private void throwIfLockdownEnabled() {
3370 if (mLockdownEnabled) {
3371 throw new IllegalStateException("Unavailable in lockdown mode");
3372 }
3373 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003374
Robin Lee244ce8e2016-01-05 18:03:46 +00003375 /**
Robin Lee17e61832016-05-09 13:46:28 +01003376 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3377 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003378 *
Robin Lee17e61832016-05-09 13:46:28 +01003379 * @return {@code true} if the service was started, the service was already connected, or there
3380 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003381 */
Robin Lee17e61832016-05-09 13:46:28 +01003382 private boolean startAlwaysOnVpn(int userId) {
3383 final String alwaysOnPackage;
3384 synchronized (mVpns) {
3385 Vpn vpn = mVpns.get(userId);
3386 if (vpn == null) {
3387 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3388 // exists already.
3389 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3390 return false;
3391 }
3392 alwaysOnPackage = vpn.getAlwaysOnPackage();
3393 // Skip if there is no service to start.
3394 if (alwaysOnPackage == null) {
3395 return true;
3396 }
3397 // Skip if the service is already established. This isn't bulletproof: it's not bound
3398 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
3399 // which may restart the connection.
3400 if (vpn.getNetworkInfo().isConnected()) {
3401 return true;
3402 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003403 }
3404
Robin Lee17e61832016-05-09 13:46:28 +01003405 // Start the VPN service declared in the app's manifest.
Robin Lee244ce8e2016-01-05 18:03:46 +00003406 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
Robin Lee17e61832016-05-09 13:46:28 +01003407 serviceIntent.setPackage(alwaysOnPackage);
Robin Lee244ce8e2016-01-05 18:03:46 +00003408 try {
Robin Lee17e61832016-05-09 13:46:28 +01003409 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(userId)) != null;
Robin Lee244ce8e2016-01-05 18:03:46 +00003410 } catch (RuntimeException e) {
Robin Lee17e61832016-05-09 13:46:28 +01003411 Slog.w(TAG, "VpnService " + serviceIntent + " failed to start", e);
Robin Lee244ce8e2016-01-05 18:03:46 +00003412 return false;
3413 }
3414 }
3415
3416 @Override
Robin Leedc679712016-05-03 13:23:03 +01003417 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003418 enforceConnectivityInternalPermission();
3419 enforceCrossUserPermission(userId);
3420
3421 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3422 if (LockdownVpnTracker.isEnabled()) {
3423 return false;
3424 }
3425
Robin Lee244ce8e2016-01-05 18:03:46 +00003426 synchronized (mVpns) {
3427 Vpn vpn = mVpns.get(userId);
3428 if (vpn == null) {
3429 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3430 return false;
3431 }
Robin Lee17e61832016-05-09 13:46:28 +01003432 // If the current VPN package is the same as the new one, this is a no-op
3433 if (TextUtils.equals(packageName, vpn.getAlwaysOnPackage())) {
3434 return true;
3435 }
3436 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003437 return false;
3438 }
Robin Lee17e61832016-05-09 13:46:28 +01003439 if (!startAlwaysOnVpn(userId)) {
3440 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003441 return false;
3442 }
Robin Lee17e61832016-05-09 13:46:28 +01003443
3444 // Save the configuration
3445 final long token = Binder.clearCallingIdentity();
3446 try {
3447 final ContentResolver cr = mContext.getContentResolver();
3448 Settings.Secure.putStringForUser(cr, Settings.Secure.ALWAYS_ON_VPN_APP,
3449 packageName, userId);
3450 Settings.Secure.putIntForUser(cr, Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
3451 (lockdown ? 1 : 0), userId);
3452 } finally {
3453 Binder.restoreCallingIdentity(token);
3454 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003455 }
3456 return true;
3457 }
3458
3459 @Override
3460 public String getAlwaysOnVpnPackage(int userId) {
3461 enforceConnectivityInternalPermission();
3462 enforceCrossUserPermission(userId);
3463
3464 synchronized (mVpns) {
3465 Vpn vpn = mVpns.get(userId);
3466 if (vpn == null) {
3467 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3468 return null;
3469 }
3470 return vpn.getAlwaysOnPackage();
3471 }
3472 }
3473
Wink Savilleab9321d2013-06-29 21:10:57 -07003474 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003475 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003476 // TODO: Remove? Any reason to trigger a provisioning check?
3477 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003478 }
3479
3480 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003481 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003482
Paul Jensen89e0f092014-09-15 15:59:36 -04003483 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003484 Intent intent = new Intent(action);
3485 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003486 // Concatenate the range of types onto the range of NetIDs.
3487 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003488 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003489 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003490 }
3491
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003492 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003493 * Show or hide network provisioning notifications.
3494 *
3495 * We use notifications for two purposes: to notify that a network requires sign in
3496 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3497 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3498 * particular network we can display the notification type that was most recently requested.
3499 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3500 * might first display NO_INTERNET, and then when the captive portal check completes, display
3501 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003502 *
3503 * @param id an identifier that uniquely identifies this notification. This must match
3504 * between show and hide calls. We use the NetID value but for legacy callers
3505 * we concatenate the range of types with the range of NetIDs.
3506 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003507 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003508 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3509 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003510 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003511 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3512 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003513 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003514 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003515
3516 Resources r = Resources.getSystem();
3517 NotificationManager notificationManager = (NotificationManager) mContext
3518 .getSystemService(Context.NOTIFICATION_SERVICE);
3519
3520 if (visible) {
3521 CharSequence title;
3522 CharSequence details;
3523 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003524 if (notifyType == NotificationType.NO_INTERNET &&
3525 networkType == ConnectivityManager.TYPE_WIFI) {
3526 title = r.getString(R.string.wifi_no_internet, 0);
3527 details = r.getString(R.string.wifi_no_internet_detailed);
3528 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3529 } else if (notifyType == NotificationType.SIGN_IN) {
3530 switch (networkType) {
3531 case ConnectivityManager.TYPE_WIFI:
3532 title = r.getString(R.string.wifi_available_sign_in, 0);
3533 details = r.getString(R.string.network_available_sign_in_detailed,
3534 extraInfo);
3535 icon = R.drawable.stat_notify_wifi_in_range;
3536 break;
3537 case ConnectivityManager.TYPE_MOBILE:
3538 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3539 title = r.getString(R.string.network_available_sign_in, 0);
3540 // TODO: Change this to pull from NetworkInfo once a printable
3541 // name has been added to it
3542 details = mTelephonyManager.getNetworkOperatorName();
3543 icon = R.drawable.stat_notify_rssi_in_range;
3544 break;
3545 default:
3546 title = r.getString(R.string.network_available_sign_in, 0);
3547 details = r.getString(R.string.network_available_sign_in_detailed,
3548 extraInfo);
3549 icon = R.drawable.stat_notify_rssi_in_range;
3550 break;
3551 }
3552 } else {
3553 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3554 + getNetworkTypeName(networkType));
3555 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003556 }
3557
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003558 Notification notification = new Notification.Builder(mContext)
3559 .setWhen(0)
3560 .setSmallIcon(icon)
3561 .setAutoCancel(true)
3562 .setTicker(title)
3563 .setColor(mContext.getColor(
3564 com.android.internal.R.color.system_notification_accent_color))
3565 .setContentTitle(title)
3566 .setContentText(details)
3567 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003568 .setLocalOnly(true)
3569 .setPriority(highPriority ?
3570 Notification.PRIORITY_HIGH :
3571 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003572 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003573 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003574 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003575
Wink Saville948282b2013-08-29 08:55:16 -07003576 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003577 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003578 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003579 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003580 npe.printStackTrace();
3581 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003582 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003583 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003584 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003585 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003586 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003587 npe.printStackTrace();
3588 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003589 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003590 }
3591
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003592 /** Location to an updatable file listing carrier provisioning urls.
3593 * An example:
3594 *
3595 * <?xml version="1.0" encoding="utf-8"?>
3596 * <provisioningUrls>
3597 * <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 -07003598 * </provisioningUrls>
3599 */
3600 private static final String PROVISIONING_URL_PATH =
3601 "/data/misc/radio/provisioning_urls.xml";
3602 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003603
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003604 /** XML tag for root element. */
3605 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3606 /** XML tag for individual url */
3607 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003608 /** XML attribute for mcc */
3609 private static final String ATTR_MCC = "mcc";
3610 /** XML attribute for mnc */
3611 private static final String ATTR_MNC = "mnc";
3612
Paul Jensen434dde82015-06-11 09:43:30 -04003613 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003614 FileReader fileReader = null;
3615 XmlPullParser parser = null;
3616 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003617
3618 try {
3619 fileReader = new FileReader(mProvisioningUrlFile);
3620 parser = Xml.newPullParser();
3621 parser.setInput(fileReader);
3622 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3623
3624 while (true) {
3625 XmlUtils.nextElement(parser);
3626
3627 String element = parser.getName();
3628 if (element == null) break;
3629
Paul Jensen434dde82015-06-11 09:43:30 -04003630 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003631 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3632 try {
3633 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3634 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3635 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3636 parser.next();
3637 if (parser.getEventType() == XmlPullParser.TEXT) {
3638 return parser.getText();
3639 }
3640 }
3641 }
3642 } catch (NumberFormatException e) {
3643 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3644 }
3645 }
3646 }
3647 return null;
3648 } catch (FileNotFoundException e) {
3649 loge("Carrier Provisioning Urls file not found");
3650 } catch (XmlPullParserException e) {
3651 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3652 } catch (IOException e) {
3653 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3654 } finally {
3655 if (fileReader != null) {
3656 try {
3657 fileReader.close();
3658 } catch (IOException e) {}
3659 }
3660 }
3661 return null;
3662 }
3663
Wink Saville42d4f082013-07-20 20:31:59 -07003664 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003665 public String getMobileProvisioningUrl() {
3666 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003667 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003668 if (TextUtils.isEmpty(url)) {
3669 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003670 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003671 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003672 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003673 }
Wink Saville8cf35602013-07-10 23:00:07 -07003674 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003675 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003676 String phoneNumber = mTelephonyManager.getLine1Number();
3677 if (TextUtils.isEmpty(phoneNumber)) {
3678 phoneNumber = "0000000000";
3679 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003680 url = String.format(url,
3681 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3682 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003683 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003684 }
3685
Wink Savilleab9321d2013-06-29 21:10:57 -07003686 return url;
3687 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003688
Wink Saville948282b2013-08-29 08:55:16 -07003689 @Override
3690 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003691 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003692 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003693 final long ident = Binder.clearCallingIdentity();
3694 try {
3695 setProvNotificationVisible(visible, networkType, action);
3696 } finally {
3697 Binder.restoreCallingIdentity(ident);
3698 }
Wink Saville948282b2013-08-29 08:55:16 -07003699 }
Wink Saville7788c612013-08-29 14:57:08 -07003700
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003701 @Override
3702 public void setAirplaneMode(boolean enable) {
3703 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003704 final long ident = Binder.clearCallingIdentity();
3705 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003706 final ContentResolver cr = mContext.getContentResolver();
3707 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3708 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3709 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003710 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003711 } finally {
3712 Binder.restoreCallingIdentity(ident);
3713 }
3714 }
3715
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003716 private void onUserStart(int userId) {
3717 synchronized(mVpns) {
3718 Vpn userVpn = mVpns.get(userId);
3719 if (userVpn != null) {
3720 loge("Starting user already has a VPN");
3721 return;
3722 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003723 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003724 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003725
3726 final ContentResolver cr = mContext.getContentResolver();
3727 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3728 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3729 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3730 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3731 if (alwaysOnPackage != null) {
3732 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3733 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003734 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003735 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3736 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003737 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003738 }
3739
3740 private void onUserStop(int userId) {
3741 synchronized(mVpns) {
3742 Vpn userVpn = mVpns.get(userId);
3743 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003744 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003745 return;
3746 }
Robin Lee17e61832016-05-09 13:46:28 +01003747 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003748 mVpns.delete(userId);
3749 }
3750 }
3751
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003752 private void onUserAdded(int userId) {
3753 synchronized(mVpns) {
3754 final int vpnsSize = mVpns.size();
3755 for (int i = 0; i < vpnsSize; i++) {
3756 Vpn vpn = mVpns.valueAt(i);
3757 vpn.onUserAdded(userId);
3758 }
3759 }
3760 }
3761
3762 private void onUserRemoved(int userId) {
3763 synchronized(mVpns) {
3764 final int vpnsSize = mVpns.size();
3765 for (int i = 0; i < vpnsSize; i++) {
3766 Vpn vpn = mVpns.valueAt(i);
3767 vpn.onUserRemoved(userId);
3768 }
3769 }
3770 }
3771
Robin Lee89e7a692016-02-29 14:38:17 +00003772 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003773 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3774 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3775 updateLockdownVpn();
3776 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003777 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003778 }
3779 }
3780
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003781 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3782 @Override
3783 public void onReceive(Context context, Intent intent) {
3784 final String action = intent.getAction();
3785 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3786 if (userId == UserHandle.USER_NULL) return;
3787
Robin Lee323f29d2016-05-04 16:38:06 +01003788 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003789 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003790 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003791 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003792 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3793 onUserAdded(userId);
3794 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3795 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003796 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3797 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003798 }
3799 }
3800 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003801
Robert Greenwalta67be032014-05-16 15:49:14 -07003802 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3803 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003804 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3805 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003806
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003807 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3808 // Map from UID to number of NetworkRequests that UID has filed.
3809 @GuardedBy("mUidToNetworkRequestCount")
3810 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3811
Robert Greenwalta67be032014-05-16 15:49:14 -07003812 private static class NetworkFactoryInfo {
3813 public final String name;
3814 public final Messenger messenger;
3815 public final AsyncChannel asyncChannel;
3816
3817 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3818 this.name = name;
3819 this.messenger = messenger;
3820 this.asyncChannel = asyncChannel;
3821 }
3822 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003823
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003824 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003825 * A NetworkRequest as registered by an application can be one of three
3826 * types:
3827 *
3828 * - "listen", for which the framework will issue callbacks about any
3829 * and all networks that match the specified NetworkCapabilities,
3830 *
3831 * - "request", capable of causing a specific network to be created
3832 * first (e.g. a telephony DUN request), the framework will issue
3833 * callbacks about the single, highest scoring current network
3834 * (if any) that matches the specified NetworkCapabilities, or
3835 *
3836 * - "track the default network", a hybrid of the two designed such
3837 * that the framework will issue callbacks for the single, highest
3838 * scoring current network (if any) that matches the capabilities of
3839 * the default Internet request (mDefaultRequest), but which cannot
3840 * cause the framework to either create or retain the existence of
3841 * any specific network.
3842 *
3843 */
3844 private static enum NetworkRequestType {
3845 LISTEN,
3846 TRACK_DEFAULT,
3847 REQUEST
3848 };
3849
3850 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003851 * Tracks info about the requester.
3852 * Also used to notice when the calling process dies so we can self-expire
3853 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003854 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003855 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003856 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003857 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003858 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003859 final int mPid;
3860 final int mUid;
3861 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003862 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003863
Erik Kline371c7b72016-03-22 17:04:20 +09003864 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003865 request = r;
3866 mPendingIntent = pi;
3867 messenger = null;
3868 mBinder = null;
3869 mPid = getCallingPid();
3870 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003871 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003872 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003873 }
3874
Erik Kline371c7b72016-03-22 17:04:20 +09003875 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003876 super();
3877 messenger = m;
3878 request = r;
3879 mBinder = binder;
3880 mPid = getCallingPid();
3881 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003882 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003883 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003884 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003885
3886 try {
3887 mBinder.linkToDeath(this, 0);
3888 } catch (RemoteException e) {
3889 binderDied();
3890 }
3891 }
3892
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003893 private void enforceRequestCountLimit() {
3894 synchronized (mUidToNetworkRequestCount) {
3895 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3896 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3897 throw new IllegalArgumentException("Too many NetworkRequests filed");
3898 }
3899 mUidToNetworkRequestCount.put(mUid, networkRequests);
3900 }
3901 }
3902
Erik Kline371c7b72016-03-22 17:04:20 +09003903 private String typeString() {
3904 switch (mType) {
3905 case LISTEN: return "Listen";
3906 case REQUEST: return "Request";
3907 case TRACK_DEFAULT: return "Track default";
3908 default:
3909 return "unknown type";
3910 }
3911 }
3912
Robert Greenwalt9258c642014-03-26 16:47:06 -07003913 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003914 if (mBinder != null) {
3915 mBinder.unlinkToDeath(this, 0);
3916 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003917 }
3918
3919 public void binderDied() {
3920 log("ConnectivityService NetworkRequestInfo binderDied(" +
3921 request + ", " + mBinder + ")");
3922 releaseNetworkRequest(request);
3923 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003924
Erik Kline371c7b72016-03-22 17:04:20 +09003925 /**
3926 * Returns true iff. the contained NetworkRequest is one that:
3927 *
3928 * - should be associated with at most one satisfying network
3929 * at a time;
3930 *
3931 * - should cause a network to be kept up if it is the only network
3932 * which can satisfy the NetworkReqeust.
3933 *
3934 * For full detail of how isRequest() is used for pairing Networks with
3935 * NetworkRequests read rematchNetworkAndRequests().
3936 *
3937 * TODO: Rename to something more properly descriptive.
3938 */
3939 public boolean isRequest() {
3940 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3941 (mType == NetworkRequestType.REQUEST);
3942 }
3943
Robert Greenwalta67be032014-05-16 15:49:14 -07003944 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003945 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003946 " from uid/pid:" + mUid + "/" + mPid +
3947 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003948 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003949 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003950 }
3951
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003952 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3953 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3954 if (badCapability != null) {
3955 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003956 }
3957 }
3958
Erik Kline9d598e12015-07-13 16:37:51 +09003959 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003960 final SortedSet<Integer> thresholds = new TreeSet();
3961 synchronized (nai) {
3962 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3963 if (nri.request.networkCapabilities.hasSignalStrength() &&
3964 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3965 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3966 }
3967 }
3968 }
Erik Kline9d598e12015-07-13 16:37:51 +09003969 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003970 }
3971
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003972 private void updateSignalStrengthThresholds(
3973 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3974 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003975 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003976 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3977
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003978 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003979 String detail;
3980 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3981 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3982 } else {
3983 detail = reason;
3984 }
3985 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3986 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3987 }
3988
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003989 nai.asyncChannel.sendMessage(
3990 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003991 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003992 }
3993
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994 @Override
3995 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003996 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003997 final NetworkRequestType type = (networkCapabilities == null)
3998 ? NetworkRequestType.TRACK_DEFAULT
3999 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004000 // If the requested networkCapabilities is null, take them instead from
4001 // the default network request. This allows callers to keep track of
4002 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09004003 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004004 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4005 enforceAccessPermission();
4006 } else {
4007 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4008 enforceNetworkRequestPermissions(networkCapabilities);
4009 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004010 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004011 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004012
Robert Greenwalt6078b502014-06-11 16:05:07 -07004013 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004014 throw new IllegalArgumentException("Bad timeout specified");
4015 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004016
Etan Cohenddb9ef02015-11-18 10:56:15 -08004017 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4018 .equals(networkCapabilities.getNetworkSpecifier())) {
4019 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4020 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4021 }
4022
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004023 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4024 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09004025 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09004026 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004027
4028 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004029 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004030 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004031 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004032 }
4033 return networkRequest;
4034 }
4035
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004036 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004037 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004038 enforceConnectivityInternalPermission();
4039 } else {
4040 enforceChangePermission();
4041 }
4042 }
4043
fenglub15e72b2015-03-20 11:29:56 -07004044 @Override
fengludb571472015-04-21 17:12:05 -07004045 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004046 enforceAccessPermission();
4047 NetworkAgentInfo nai = null;
4048 if (network == null) {
4049 return false;
4050 }
4051 synchronized (mNetworkForNetId) {
4052 nai = mNetworkForNetId.get(network.netId);
4053 }
4054 if (nai != null) {
4055 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4056 return true;
4057 }
4058 return false;
4059 }
4060
4061
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004062 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
4063 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004064 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004065 final int uidRules;
4066 final int uid = Binder.getCallingUid();
4067 synchronized(mRulesLock) {
4068 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4069 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004070 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4071 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004072 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004073 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004074 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004075 }
4076 }
4077 }
4078
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 @Override
4080 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4081 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004082 checkNotNull(operation, "PendingIntent cannot be null.");
4083 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4084 enforceNetworkRequestPermissions(networkCapabilities);
4085 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004086 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004087
4088 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4089 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004090 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004091 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09004092 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004093 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4094 nri));
4095 return networkRequest;
4096 }
4097
Jeremy Joslin79294842014-12-03 17:15:28 -08004098 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4099 mHandler.sendMessageDelayed(
4100 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4101 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4102 }
4103
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004104 @Override
4105 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004106 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004107 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4108 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004109 }
4110
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004111 // In order to implement the compatibility measure for pre-M apps that call
4112 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4113 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4114 // This ensures it has permission to do so.
4115 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4116 if (nc == null) {
4117 return false;
4118 }
4119 int[] transportTypes = nc.getTransportTypes();
4120 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4121 return false;
4122 }
4123 try {
4124 mContext.enforceCallingOrSelfPermission(
4125 android.Manifest.permission.ACCESS_WIFI_STATE,
4126 "ConnectivityService");
4127 } catch (SecurityException e) {
4128 return false;
4129 }
4130 return true;
4131 }
4132
Robert Greenwalt9258c642014-03-26 16:47:06 -07004133 @Override
4134 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4135 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004136 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4137 enforceAccessPermission();
4138 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004139
Erik Kline7523eb32015-07-09 18:24:03 +09004140 NetworkRequest networkRequest = new NetworkRequest(
4141 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004142 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004143 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004144 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004145
4146 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4147 return networkRequest;
4148 }
4149
4150 @Override
4151 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4152 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004153 checkNotNull(operation, "PendingIntent cannot be null.");
4154 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4155 enforceAccessPermission();
4156 }
4157
Erik Kline7523eb32015-07-09 18:24:03 +09004158 NetworkRequest networkRequest = new NetworkRequest(
4159 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004160 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004161 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004162 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004163
4164 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004165 }
4166
4167 @Override
4168 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004169 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4170 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 }
4172
4173 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004174 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004175 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004176 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4177 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004178 }
4179
Robert Greenwalta67be032014-05-16 15:49:14 -07004180 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004181 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004182 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4183 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4184 }
4185
4186 @Override
4187 public void unregisterNetworkFactory(Messenger messenger) {
4188 enforceConnectivityInternalPermission();
4189 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4190 }
4191
4192 private void handleUnregisterNetworkFactory(Messenger messenger) {
4193 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4194 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004195 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004196 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004198 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004199 }
4200
Robert Greenwalt7b816022014-04-18 15:25:25 -07004201 /**
4202 * NetworkAgentInfo supporting a request by requestId.
4203 * These have already been vetted (their Capabilities satisfy the request)
4204 * and the are the highest scored network available.
4205 * the are keyed off the Requests requestId.
4206 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004207 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004208 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4209 new SparseArray<NetworkAgentInfo>();
4210
Paul Jensen31a94f42015-02-13 14:18:39 -05004211 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4212 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004213 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4214 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004215 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4216 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4217 // there may not be a strict 1:1 correlation between the two.
4218 @GuardedBy("mNetworkForNetId")
4219 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004220
Robert Greenwalt7b816022014-04-18 15:25:25 -07004221 // NetworkAgentInfo keyed off its connecting messenger
4222 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004223 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004224 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4225 new HashMap<Messenger, NetworkAgentInfo>();
4226
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004227 @GuardedBy("mBlockedAppUids")
4228 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4229
Paul Jensen2c311d62014-11-17 12:34:51 -05004230 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004231 private final NetworkRequest mDefaultRequest;
4232
Erik Klineda4bfa82015-04-30 12:58:40 +09004233 // Request used to optionally keep mobile data active even when higher
4234 // priority networks like Wi-Fi are active.
4235 private final NetworkRequest mDefaultMobileDataRequest;
4236
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004237 private NetworkAgentInfo getDefaultNetwork() {
4238 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4239 }
4240
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004241 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004242 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004243 }
4244
Paul Jensen31a94f42015-02-13 14:18:39 -05004245 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004246 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004247 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004248 enforceConnectivityInternalPermission();
4249
Paul Jensen2c311d62014-11-17 12:34:51 -05004250 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4251 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004252 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004253 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4254 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004255 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004256 synchronized (this) {
4257 nai.networkMonitor.systemReady = mSystemReady;
4258 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004259 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004260 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004261 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004262 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004263 }
4264
4265 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4266 if (VDBG) log("Got NetworkAgent Messenger");
4267 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004268 synchronized (mNetworkForNetId) {
4269 mNetworkForNetId.put(na.network.netId, na);
4270 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4272 NetworkInfo networkInfo = na.networkInfo;
4273 na.networkInfo = null;
4274 updateNetworkInfo(na, networkInfo);
4275 }
4276
4277 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4278 LinkProperties newLp = networkAgent.linkProperties;
4279 int netId = networkAgent.network.netId;
4280
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004281 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4282 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004283 if (networkAgent.clatd != null) {
4284 networkAgent.clatd.fixupLinkProperties(oldLp);
4285 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004286
Paul Jensen992f2522014-04-28 10:33:11 -04004287 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004288 updateMtu(newLp, oldLp);
4289 // TODO - figure out what to do for clat
4290// for (LinkProperties lp : newLp.getStackedLinks()) {
4291// updateMtu(lp, null);
4292// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004293 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004294
Erik Kline94887872016-04-05 13:30:49 +09004295 updateRoutes(newLp, oldLp, netId);
4296 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004297
Paul Jensen3b759822014-05-13 11:44:01 -04004298 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004299 if (isDefaultNetwork(networkAgent)) {
4300 handleApplyDefaultProxy(newLp.getHttpProxy());
4301 } else {
4302 updateProxy(newLp, oldLp, networkAgent);
4303 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004304 // TODO - move this check to cover the whole function
4305 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004306 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004307 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4308 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004309
4310 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004311 }
4312
Lorenzo Colitti95439462014-10-09 13:44:48 +09004313 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4314 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4315 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004316
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004317 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004318 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4319 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004320 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004321 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004322 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004323 }
Paul Jensen992f2522014-04-28 10:33:11 -04004324
4325 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4326 CompareResult<String> interfaceDiff = new CompareResult<String>();
4327 if (oldLp != null) {
4328 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4329 } else if (newLp != null) {
4330 interfaceDiff.added = newLp.getAllInterfaceNames();
4331 }
4332 for (String iface : interfaceDiff.added) {
4333 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004334 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004335 mNetd.addInterfaceToNetwork(iface, netId);
4336 } catch (Exception e) {
4337 loge("Exception adding interface: " + e);
4338 }
4339 }
4340 for (String iface : interfaceDiff.removed) {
4341 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004342 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004343 mNetd.removeInterfaceFromNetwork(iface, netId);
4344 } catch (Exception e) {
4345 loge("Exception removing interface: " + e);
4346 }
4347 }
4348 }
4349
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004350 /**
4351 * Have netd update routes from oldLp to newLp.
4352 * @return true if routes changed between oldLp and newLp
4353 */
4354 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004355 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4356 if (oldLp != null) {
4357 routeDiff = oldLp.compareAllRoutes(newLp);
4358 } else if (newLp != null) {
4359 routeDiff.added = newLp.getAllRoutes();
4360 }
4361
4362 // add routes before removing old in case it helps with continuous connectivity
4363
4364 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4365 for (RouteInfo route : routeDiff.added) {
4366 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004367 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004368 try {
4369 mNetd.addRoute(netId, route);
4370 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004371 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4372 loge("Exception in addRoute for non-gateway: " + e);
4373 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004374 }
4375 }
4376 for (RouteInfo route : routeDiff.added) {
4377 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004378 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004379 try {
4380 mNetd.addRoute(netId, route);
4381 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004382 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4383 loge("Exception in addRoute for gateway: " + e);
4384 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004385 }
4386 }
4387
4388 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004389 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004390 try {
4391 mNetd.removeRoute(netId, route);
4392 } catch (Exception e) {
4393 loge("Exception in removeRoute: " + e);
4394 }
4395 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004396 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004397 }
Erik Kline41368502015-06-17 13:19:54 +09004398
Erik Kline94887872016-04-05 13:30:49 +09004399 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4400 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4401 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004402 }
Erik Kline94887872016-04-05 13:30:49 +09004403
4404 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004405 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004406 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004407 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004408 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4409 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004410 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004411 }
4412 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4413 if (defaultNai != null && defaultNai.network.netId == netId) {
4414 setDefaultDnsSystemProperties(dnses);
4415 }
4416 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004417 }
4418
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004419 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4420 int last = 0;
4421 for (InetAddress dns : dnses) {
4422 ++last;
4423 String key = "net.dns" + last;
4424 String value = dns.getHostAddress();
4425 SystemProperties.set(key, value);
4426 }
4427 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4428 String key = "net.dns" + i;
4429 SystemProperties.set(key, "");
4430 }
4431 mNumDnsEntries = last;
4432 }
4433
Paul Jensen3d194ea2015-06-16 14:27:36 -04004434 /**
4435 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4436 * augmented with any stateful capabilities implied from {@code networkAgent}
4437 * (e.g., validated status and captive portal status).
4438 *
Paul Jensene0988542015-06-25 15:30:08 -04004439 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004440 * @param networkCapabilities the new network capabilities.
4441 */
Paul Jensene0988542015-06-25 15:30:08 -04004442 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004443 // Don't modify caller's NetworkCapabilities.
4444 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004445 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004446 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4447 } else {
4448 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4449 }
Paul Jensene0988542015-06-25 15:30:08 -04004450 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004451 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4452 } else {
4453 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4454 }
Paul Jensene0988542015-06-25 15:30:08 -04004455 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4456 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004457 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4458 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4459 try {
4460 mNetd.setNetworkPermission(nai.network.netId,
4461 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4462 null : NetworkManagementService.PERMISSION_SYSTEM);
4463 } catch (RemoteException e) {
4464 loge("Exception in setNetworkPermission: " + e);
4465 }
4466 }
Paul Jensene0988542015-06-25 15:30:08 -04004467 synchronized (nai) {
4468 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004469 }
Paul Jensene0988542015-06-25 15:30:08 -04004470 rematchAllNetworksAndRequests(nai, oldScore);
4471 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004472 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004473 }
4474
Paul Jensenc8b9a742014-09-30 15:37:41 -04004475 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4476 for (int i = 0; i < nai.networkRequests.size(); i++) {
4477 NetworkRequest nr = nai.networkRequests.valueAt(i);
4478 // Don't send listening requests to factories. b/17393458
4479 if (!isRequest(nr)) continue;
4480 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4481 }
4482 }
4483
Robert Greenwalt7b816022014-04-18 15:25:25 -07004484 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4485 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004486 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004487 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4488 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004489 }
4490 }
4491
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004492 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4493 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004494 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004495 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004496 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4497 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004498 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004499 sendIntent(nri.mPendingIntent, intent);
4500 }
4501 // else not handled
4502 }
4503
4504 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4505 mPendingIntentWakeLock.acquire();
4506 try {
4507 if (DBG) log("Sending " + pendingIntent);
4508 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4509 } catch (PendingIntent.CanceledException e) {
4510 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4511 mPendingIntentWakeLock.release();
4512 releasePendingNetworkRequest(pendingIntent);
4513 }
4514 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4515 }
4516
4517 @Override
4518 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4519 String resultData, Bundle resultExtras) {
4520 if (DBG) log("Finished sending " + pendingIntent);
4521 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004522 // Release with a delay so the receiving client has an opportunity to put in its
4523 // own request.
4524 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004525 }
4526
Robert Greenwalt9258c642014-03-26 16:47:06 -07004527 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004528 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004529 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004530 Bundle bundle = new Bundle();
4531 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4532 new NetworkRequest(nri.request));
4533 Message msg = Message.obtain();
4534 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4535 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4536 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4537 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004538 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004539 case ConnectivityManager.CALLBACK_LOSING: {
4540 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4541 break;
4542 }
4543 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4544 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4545 new NetworkCapabilities(networkAgent.networkCapabilities));
4546 break;
4547 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004548 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004549 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4550 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004551 break;
4552 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004553 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004554 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004555 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004556 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004557 if (VDBG) {
4558 log("sending notification " + notifyTypeToName(notificationType) +
4559 " for " + nri.request);
4560 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004561 nri.messenger.send(msg);
4562 } catch (RemoteException e) {
4563 // may occur naturally in the race of binder death.
4564 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4565 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004566 }
4567
Paul Jensenc8b9a742014-09-30 15:37:41 -04004568 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4569 for (int i = 0; i < nai.networkRequests.size(); i++) {
4570 NetworkRequest nr = nai.networkRequests.valueAt(i);
4571 // Ignore listening requests.
4572 if (!isRequest(nr)) continue;
4573 loge("Dead network still had at least " + nr);
4574 break;
4575 }
4576 nai.asyncChannel.disconnect();
4577 }
4578
Robert Greenwalt7b816022014-04-18 15:25:25 -07004579 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4580 if (oldNetwork == null) {
4581 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4582 return;
4583 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004584 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4585 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004586 }
4587
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004588 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004589 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004590 setupDataActivityTracking(newNetwork);
4591 try {
4592 mNetd.setDefaultNetId(newNetwork.network.netId);
4593 } catch (Exception e) {
4594 loge("Exception setting default network :" + e);
4595 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004596 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004597 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004598 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004599 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004600 }
4601
Paul Jensen2161a8e2014-09-11 11:00:39 -04004602 // Handles a network appearing or improving its score.
4603 //
4604 // - Evaluates all current NetworkRequests that can be
4605 // satisfied by newNetwork, and reassigns to newNetwork
4606 // any such requests for which newNetwork is the best.
4607 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004608 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004609 // needed. A network is needed if it is the best network for
4610 // one or more NetworkRequests, or if it is a VPN.
4611 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004612 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004613 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004614 //
4615 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4616 // networks that have no chance (i.e. even if validated)
4617 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004618 //
4619 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4620 // it does not remove NetworkRequests that other Networks could better satisfy.
4621 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4622 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4623 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004624 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004625 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004626 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4627 // performed to tear down unvalidated networks that have no chance (i.e. even if
4628 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004629 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004630 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004631 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004632 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004633 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004634 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004635 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004636 // Find and migrate to this Network any NetworkRequests for
4637 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004638 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004639 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004640 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004641 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004642 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4643 final boolean satisfies = newNetwork.satisfies(nri.request);
4644 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004645 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004646 log("Network " + newNetwork.name() + " was already satisfying" +
4647 " request " + nri.request.requestId + ". No change.");
4648 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004649 keep = true;
4650 continue;
4651 }
4652
4653 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004654 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004655 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004656 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004657 // This is not a request, it's a callback listener.
4658 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004659 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004660 continue;
4661 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004662
Robert Greenwalt7b816022014-04-18 15:25:25 -07004663 // next check if it's better than any current network we're using for
4664 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004665 if (VDBG) {
4666 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004667 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4668 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004669 }
4670 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004671 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004672 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004673 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004674 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004675 currentNetwork.networkRequests.remove(nri.request.requestId);
4676 currentNetwork.networkLingered.add(nri.request);
4677 affectedNetworks.add(currentNetwork);
4678 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004679 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004680 }
Paul Jensen573a0352015-01-08 10:49:34 -05004681 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004682 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004683 if (!newNetwork.addRequest(nri.request)) {
4684 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4685 }
4686 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004687 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004688 // Tell NetworkFactories about the new score, so they can stop
4689 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004690 // TODO - this could get expensive if we have alot of requests for this
4691 // network. Think about if there is a way to reduce this. Push
4692 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004693 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004694 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004695 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004696 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004697 }
4698 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004699 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4700 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4701 // mark it as no longer satisfying "nri". Because networks are processed by
4702 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4703 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4704 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4705 // This means this code doesn't have to handle the case where "currentNetwork" no
4706 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4707 if (DBG) {
4708 log("Network " + newNetwork.name() + " stopped satisfying" +
4709 " request " + nri.request.requestId);
4710 }
4711 newNetwork.networkRequests.remove(nri.request.requestId);
4712 if (currentNetwork == newNetwork) {
4713 mNetworkForRequestId.remove(nri.request.requestId);
4714 sendUpdatedScoreToFactories(nri.request, 0);
4715 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004716 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004717 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4718 newNetwork.name() +
4719 " without updating mNetworkForRequestId or factories!");
4720 }
4721 }
4722 // TODO: technically, sending CALLBACK_LOST here is
4723 // incorrect if nri is a request (not a listen) and there
4724 // is a replacement network currently connected that can
4725 // satisfy it. However, the only capability that can both
4726 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4727 // so this code is only incorrect for a network that loses
4728 // the TRUSTED capability, which is a rare case.
4729 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004730 }
4731 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004732 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004733 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004734 if (nai.lingering) {
4735 // Already lingered. Nothing to do. This can only happen if "nai" is in
4736 // "affectedNetworks" twice. The reasoning being that to get added to
4737 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4738 // (i.e. not lingered) so it could have only been lingered by this loop.
4739 // unneeded(nai) will be false and we'll call unlinger() below which would
4740 // be bad, so handle it here.
4741 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004742 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004743 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004744 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004745 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004746 }
4747 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004748 if (isNewDefault) {
4749 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004750 makeDefault(newNetwork);
4751 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4752 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004753 synchronized (ConnectivityService.this) {
4754 // have a new default network, release the transition wakelock in
4755 // a second if it's held. The second pause is to allow apps
4756 // to reconnect over the new network
4757 if (mNetTransitionWakeLock.isHeld()) {
4758 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4759 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4760 mNetTransitionWakeLockSerialNumber, 0),
4761 1000);
4762 }
4763 }
4764 }
4765
4766 // do this after the default net is switched, but
4767 // before LegacyTypeTracker sends legacy broadcasts
4768 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4769
4770 if (isNewDefault) {
4771 // Maintain the illusion: since the legacy API only
4772 // understands one network at a time, we must pretend
4773 // that the current default network disconnected before
4774 // the new one connected.
4775 if (oldDefaultNetwork != null) {
4776 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4777 oldDefaultNetwork, true);
4778 }
4779 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4780 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4781 notifyLockdownVpn(newNetwork);
4782 }
4783
Robert Greenwalt7b816022014-04-18 15:25:25 -07004784 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004785 // Notify battery stats service about this network, both the normal
4786 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004787 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004788 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004789 final IBatteryStats bs = BatteryStatsService.getService();
4790 final int type = newNetwork.networkInfo.getType();
4791
4792 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4793 bs.noteNetworkInterfaceType(baseIface, type);
4794 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4795 final String stackedIface = stacked.getInterfaceName();
4796 bs.noteNetworkInterfaceType(stackedIface, type);
4797 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4798 }
4799 } catch (RemoteException ignored) {
4800 }
4801
Robert Greenwalt152ed372014-12-17 17:19:53 -08004802 // This has to happen after the notifyNetworkCallbacks as that tickles each
4803 // ConnectivityManager instance so that legacy requests correctly bind dns
4804 // requests to this network. The legacy users are listening for this bcast
4805 // and will generally do a dns request so they can ensureRouteToHost and if
4806 // they do that before the callbacks happen they'll use the default network.
4807 //
4808 // TODO: Is there still a race here? We send the broadcast
4809 // after sending the callback, but if the app can receive the
4810 // broadcast before the callback, it might still break.
4811 //
4812 // This *does* introduce a race where if the user uses the new api
4813 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4814 // they may get old info. Reverse this after the old startUsing api is removed.
4815 // This is on top of the multiple intent sequencing referenced in the todo above.
4816 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4817 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4818 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4819 // legacy type tracker filters out repeat adds
4820 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4821 }
4822 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004823
4824 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4825 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4826 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4827 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4828 if (newNetwork.isVPN()) {
4829 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4830 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004831 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004832 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4833 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004834 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004835 if (DBG) log("Reaping " + nai.name());
4836 teardownUnneededNetwork(nai);
4837 }
4838 }
4839 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004840 }
4841
Paul Jensen1c7ba022015-06-16 14:27:36 -04004842 /**
4843 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4844 * being disconnected.
4845 * @param changed If only one Network's score or capabilities have been modified since the last
4846 * time this function was called, pass this Network in this argument, otherwise pass
4847 * null.
4848 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4849 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4850 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4851 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4852 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004853 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004854 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004855 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4856 // to avoid the slowness. It is not simply enough to process just "changed", for
4857 // example in the case where "changed"'s score decreases and another network should begin
4858 // satifying a NetworkRequest that "changed" currently satisfies.
4859
4860 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4861 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4862 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004863 if (changed != null && oldScore < changed.getCurrentScore()) {
4864 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004865 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004866 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4867 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4868 // Rematch higher scoring networks first to prevent requests first matching a lower
4869 // scoring network and then a higher scoring network, which could produce multiple
4870 // callbacks and inadvertently unlinger networks.
4871 Arrays.sort(nais);
4872 for (NetworkAgentInfo nai : nais) {
4873 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004874 // Only reap the last time through the loop. Reaping before all rematching
4875 // is complete could incorrectly teardown a network that hasn't yet been
4876 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004877 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004878 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004879 }
4880 }
4881 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004882
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004883 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004884 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004885 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004886 // For now only update icons for default connection.
4887 // TODO: Update WiFi and cellular icons separately. b/17237507
4888 if (!isDefaultNetwork(nai)) return;
4889
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004890 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004891 // Don't repeat publish.
4892 if (newInetCondition == mDefaultInetConditionPublished) return;
4893
4894 mDefaultInetConditionPublished = newInetCondition;
4895 sendInetConditionBroadcast(nai.networkInfo);
4896 }
4897
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004898 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4899 if (mLockdownTracker != null) {
4900 if (nai != null && nai.isVPN()) {
4901 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4902 } else {
4903 mLockdownTracker.onNetworkInfoChanged();
4904 }
4905 }
4906 }
4907
Robert Greenwalt7b816022014-04-18 15:25:25 -07004908 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4909 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004910 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004911 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004912 synchronized (networkAgent) {
4913 oldInfo = networkAgent.networkInfo;
4914 networkAgent.networkInfo = newInfo;
4915 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004916 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004917
4918 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004919 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4920 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4921 notifyIfacesChangedForNetworkStats();
4922 } else if (VDBG) log("ignoring duplicate network state non-change");
4923 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004924 return;
4925 }
4926 if (DBG) {
4927 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4928 (oldInfo == null ? "null" : oldInfo.getState()) +
4929 " to " + state);
4930 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004931
Robin Lee585e2482016-05-01 23:00:00 +01004932 if (!networkAgent.created
4933 && (state == NetworkInfo.State.CONNECTED
4934 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004935 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004936 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004937 if (networkAgent.isVPN()) {
4938 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004939 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4940 (networkAgent.networkMisc == null ||
4941 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004942 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004943 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4944 networkAgent.networkCapabilities.hasCapability(
4945 NET_CAPABILITY_NOT_RESTRICTED) ?
4946 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004947 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004948 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004949 loge("Error creating network " + networkAgent.network.netId + ": "
4950 + e.getMessage());
4951 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004952 }
Paul Jenseneec75412014-08-04 12:21:19 -04004953 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004954 }
4955
4956 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4957 networkAgent.everConnected = true;
4958
Robert Greenwalt7b816022014-04-18 15:25:25 -07004959 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004960 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004961
Paul Jensenca8f16a2014-05-09 12:47:55 -04004962 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004963 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004964
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004965 if (networkAgent.isVPN()) {
4966 // Temporarily disable the default proxy (not global).
4967 synchronized (mProxyLock) {
4968 if (!mDefaultProxyDisabled) {
4969 mDefaultProxyDisabled = true;
4970 if (mGlobalProxy == null && mDefaultProxy != null) {
4971 sendProxyBroadcast(null);
4972 }
4973 }
4974 }
4975 // TODO: support proxy per network.
4976 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004977
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004978 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4979 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4980 // capabilities, so it only needs to be done once on initial connect, not every time the
4981 // network's capabilities change. Note that we do this before rematching the network,
4982 // so we could decide to tear it down immediately afterwards. That's fine though - on
4983 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4984 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004985 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004986
Paul Jensen2161a8e2014-09-11 11:00:39 -04004987 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004988 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004989
4990 // This has to happen after matching the requests, because callbacks are just requests.
4991 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004992 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004993 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004994 if (networkAgent.isVPN()) {
4995 synchronized (mProxyLock) {
4996 if (mDefaultProxyDisabled) {
4997 mDefaultProxyDisabled = false;
4998 if (mGlobalProxy == null && mDefaultProxy != null) {
4999 sendProxyBroadcast(mDefaultProxy);
5000 }
5001 }
5002 }
5003 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005004 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5005 state == NetworkInfo.State.SUSPENDED) {
5006 // going into or coming out of SUSPEND: rescore and notify
5007 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005008 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005009 }
5010 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5011 ConnectivityManager.CALLBACK_SUSPENDED :
5012 ConnectivityManager.CALLBACK_RESUMED));
5013 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005014 }
5015 }
5016
Robert Greenwaltac96c522014-06-03 16:43:57 -07005017 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005018 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005019 if (score < 0) {
5020 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5021 "). Bumping score to min of 0");
5022 score = 0;
5023 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005024
Paul Jensen2161a8e2014-09-11 11:00:39 -04005025 final int oldScore = nai.getCurrentScore();
5026 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005027
Paul Jensen85cf78e2015-06-25 13:25:07 -04005028 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005029
Paul Jensenc8b9a742014-09-30 15:37:41 -04005030 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005031 }
5032
Robert Greenwalt9258c642014-03-26 16:47:06 -07005033 // notify only this one new request of the current state
5034 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5035 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5036 // TODO - read state from monitor to decide what to send.
5037// if (nai.networkMonitor.isLingering()) {
5038// notifyType = NetworkCallbacks.LOSING;
5039// } else if (nai.networkMonitor.isEvaluating()) {
5040// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5041// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005042 if (nri.mPendingIntent == null) {
5043 callCallbackForRequest(nri, nai, notifyType);
5044 } else {
5045 sendPendingIntentForRequest(nri, nai, notifyType);
5046 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005047 }
5048
Robert Greenwalt8d482522015-06-24 13:23:42 -07005049 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005050 // The NetworkInfo we actually send out has no bearing on the real
5051 // state of affairs. For example, if the default connection is mobile,
5052 // and a request for HIPRI has just gone away, we need to pretend that
5053 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5054 // the state to DISCONNECTED, even though the network is of type MOBILE
5055 // and is still connected.
5056 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5057 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005058 if (state != DetailedState.DISCONNECTED) {
5059 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005060 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005061 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005062 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005063 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5064 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5065 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5066 if (info.isFailover()) {
5067 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5068 nai.networkInfo.setFailover(false);
5069 }
5070 if (info.getReason() != null) {
5071 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5072 }
5073 if (info.getExtraInfo() != null) {
5074 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5075 }
5076 NetworkAgentInfo newDefaultAgent = null;
5077 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005078 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005079 if (newDefaultAgent != null) {
5080 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5081 newDefaultAgent.networkInfo);
5082 } else {
5083 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5084 }
5085 }
5086 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5087 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005088 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005089 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005090 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005091 }
5092 }
5093 }
5094
Robert Greenwalt7b816022014-04-18 15:25:25 -07005095 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005096 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005097 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005098 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5099 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5100 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005101 if (nri.mPendingIntent == null) {
5102 callCallbackForRequest(nri, networkAgent, notifyType);
5103 } else {
5104 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5105 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005106 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005107 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005108
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005109 private String notifyTypeToName(int notifyType) {
5110 switch (notifyType) {
5111 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5112 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5113 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5114 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5115 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5116 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5117 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5118 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5119 }
5120 return "UNKNOWN";
5121 }
5122
Jeff Sharkey69736342014-12-08 14:50:12 -08005123 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005124 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5125 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005126 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005127 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005128 try {
5129 mStatsService.forceUpdateIfaces();
5130 } catch (Exception ignored) {
5131 }
5132 }
5133
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005134 @Override
5135 public boolean addVpnAddress(String address, int prefixLength) {
5136 throwIfLockdownEnabled();
5137 int user = UserHandle.getUserId(Binder.getCallingUid());
5138 synchronized (mVpns) {
5139 return mVpns.get(user).addAddress(address, prefixLength);
5140 }
5141 }
5142
5143 @Override
5144 public boolean removeVpnAddress(String address, int prefixLength) {
5145 throwIfLockdownEnabled();
5146 int user = UserHandle.getUserId(Binder.getCallingUid());
5147 synchronized (mVpns) {
5148 return mVpns.get(user).removeAddress(address, prefixLength);
5149 }
5150 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005151
5152 @Override
5153 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5154 throwIfLockdownEnabled();
5155 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005156 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005157 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005158 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005159 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005160 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005161 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005162 }
5163 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005164 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005165
5166 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005167 public String getCaptivePortalServerUrl() {
5168 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5169 }
5170
5171 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005172 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5173 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5174 enforceKeepalivePermission();
5175 mKeepaliveTracker.startNattKeepalive(
5176 getNetworkAgentInfoForNetwork(network),
5177 intervalSeconds, messenger, binder,
5178 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5179 }
5180
5181 @Override
5182 public void stopKeepalive(Network network, int slot) {
5183 mHandler.sendMessage(mHandler.obtainMessage(
5184 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5185 }
5186
5187 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005188 public void factoryReset() {
5189 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005190
5191 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5192 return;
5193 }
5194
Robin Lee3b3dd942015-05-12 18:14:58 +01005195 final int userId = UserHandle.getCallingUserId();
5196
Stuart Scottf1fb3972015-04-02 18:00:02 -07005197 // Turn airplane mode off
5198 setAirplaneMode(false);
5199
Stuart Scotte3e314d2015-04-20 14:07:45 -07005200 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5201 // Untether
5202 for (String tether : getTetheredIfaces()) {
5203 untether(tether);
5204 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005205 }
5206
Stuart Scotte3e314d2015-04-20 14:07:45 -07005207 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5208 // Turn VPN off
5209 VpnConfig vpnConfig = getVpnConfig(userId);
5210 if (vpnConfig != null) {
5211 if (vpnConfig.legacy) {
5212 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5213 } else {
5214 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5215 // in the future without user intervention.
5216 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005217
Stuart Scotte3e314d2015-04-20 14:07:45 -07005218 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5219 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005220 }
5221 }
5222 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005223
5224 @VisibleForTesting
5225 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5226 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5227 return new NetworkMonitor(context, handler, nai, defaultRequest);
5228 }
Erik Kline48f12f22016-04-14 17:30:59 +09005229
Hugo Benichi5f16f762016-04-20 12:09:33 +09005230 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5231 int newNetid = NETID_UNSET;
5232 int prevNetid = NETID_UNSET;
5233 int[] transports = new int[0];
5234 boolean hadIPv4 = false;
5235 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005236
Hugo Benichi5f16f762016-04-20 12:09:33 +09005237 if (newNai != null) {
5238 newNetid = newNai.network.netId;
5239 transports = newNai.networkCapabilities.getTransportTypes();
5240 }
5241 if (prevNai != null) {
5242 prevNetid = prevNai.network.netId;
5243 final LinkProperties lp = prevNai.linkProperties;
5244 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5245 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5246 }
5247
5248 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250}