blob: 0f217967db6a4911dc0e84256e01460aa49fd5b3 [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;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080036import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070059import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070064import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090074import android.net.metrics.DefaultNetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080076import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070077import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040078import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070080import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070082import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Looper;
84import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070085import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070087import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070088import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080090import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070092import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040093import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070095import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070096import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070097import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070099import android.util.LocalLog;
100import android.util.LocalLog.ReadOnlyLocalLog;
101import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700103import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500104import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700105import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700106import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400109import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400110import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700112import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700114import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800115import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700116import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700117import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700118import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900119import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700120import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700121import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400122import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900123import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900124import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900125import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700126import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400127import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400128import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700129import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800130import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700131import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700132import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700133import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700134import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700135import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700136
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700137import org.xmlpull.v1.XmlPullParser;
138import org.xmlpull.v1.XmlPullParserException;
139
140import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700142import java.io.FileNotFoundException;
143import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700144import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700146import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700147import java.net.InetAddress;
148import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700149import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700150import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700151import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700152import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700153import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700154import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900155import java.util.SortedSet;
156import java.util.TreeSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700157import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700158import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700159import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161/**
162 * @hide
163 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800164public class ConnectivityService extends IConnectivityManager.Stub
165 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700166 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900168 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700169 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Jake Hamby786e71a2014-02-06 14:43:50 -0800171 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900172 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700173
Jeff Sharkey899223b2012-08-04 15:24:58 -0700174 // TODO: create better separation between radio types and network types
175
Robert Greenwalt42acef32009-08-12 16:08:25 -0700176 // how long to wait before switching back to a radio's default network
177 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
178 // system property that can override the above value
179 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
180 "android.telephony.apn-restore";
181
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900182 // How long to wait before putting up a "This network doesn't have an Internet connection,
183 // connect anyway?" dialog after the user selects a network that doesn't validate.
184 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
185
Jeremy Joslin79294842014-12-03 17:15:28 -0800186 // How long to delay to removal of a pending intent based request.
187 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
188 private final int mReleasePendingIntentDelayMs;
189
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800190 private Tethering mTethering;
191
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700192 private final PermissionMonitor mPermissionMonitor;
193
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700194 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700195
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700196 @GuardedBy("mVpns")
197 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700198
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700199 private boolean mLockdownEnabled;
200 private LockdownVpnTracker mLockdownTracker;
201
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700202 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
203 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700204 /** Currently active network rules by UID. */
205 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700206 /** Set of ifaces that are costly. */
207 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700208
Erik Klineda4bfa82015-04-30 12:58:40 +0900209 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700211 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700212 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800214 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
216 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700217 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700219 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800220 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700221 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700222
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700223 private String mCurrentTcpBufferSizes;
224
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700225 private static final int ENABLED = 1;
226 private static final int DISABLED = 0;
227
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900228 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
229 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
230
Paul Jensenb10e37f2014-11-25 12:33:08 -0500231 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400232 // Tear down networks that have no chance (e.g. even if validated) of becoming
233 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500234 // all networks have been rematched against all NetworkRequests.
235 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400236 // Don't reap networks. This should be passed when some networks have not yet been
237 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500238 DONT_REAP
239 };
240
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700242 * used internally to change our mobile data enabled flag
243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700245
246 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700248 * from one net to another. Clear happens when we get a new
249 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
250 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700251 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700252 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700253
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254 /**
255 * used internally to reload global proxy settings
256 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700257 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700258
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700259 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400260 * PAC manager has received new port.
261 */
262 private static final int EVENT_PROXY_HAS_CHANGED = 16;
263
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 /**
265 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700266 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700267 */
268 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
269
Robert Greenwalt7b816022014-04-18 15:25:25 -0700270 /**
271 * used internally when registering NetworkAgents
272 * obj = Messenger
273 */
274 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
275
Robert Greenwalt9258c642014-03-26 16:47:06 -0700276 /**
277 * used to add a network request
278 * includes a NetworkRequestInfo
279 */
280 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
281
282 /**
283 * indicates a timeout period is over - check if we had a network yet or not
284 * and if not, call the timeout calback (but leave the request live until they
285 * cancel it.
286 * includes a NetworkRequestInfo
287 */
288 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
289
290 /**
291 * used to add a network listener - no request
292 * includes a NetworkRequestInfo
293 */
294 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
295
296 /**
297 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400298 * arg1 = UID of caller
299 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 */
301 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
302
Robert Greenwalta67be032014-05-16 15:49:14 -0700303 /**
304 * used internally when registering NetworkFactories
305 * obj = Messenger
306 */
307 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
308
Robert Greenwalt27711812014-06-25 16:45:57 -0700309 /**
310 * used internally to expire a wakelock when transitioning
311 * from one net to another. Expire happens when we fail to find
312 * a new network (typically after 1 minute) -
313 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
314 * a replacement network.
315 */
316 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
317
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700318 /**
319 * Used internally to indicate the system is ready.
320 */
321 private static final int EVENT_SYSTEM_READY = 25;
322
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800323 /**
324 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400325 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800326 */
327 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
328
329 /**
330 * used to remove a pending intent and its associated network request.
331 * arg1 = UID of caller
332 * obj = PendingIntent
333 */
334 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
335
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900336 /**
337 * used to specify whether a network should be used even if unvalidated.
338 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
339 * arg2 = whether to remember this choice in the future (1 or 0)
340 * obj = network
341 */
342 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
343
344 /**
345 * used to ask the user to confirm a connection to an unvalidated network.
346 * obj = network
347 */
348 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700349
Erik Klineda4bfa82015-04-30 12:58:40 +0900350 /**
351 * used internally to (re)configure mobile data always-on settings.
352 */
353 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
354
Paul Jensen694f2b82015-06-17 14:15:39 -0400355 /**
356 * used to add a network listener with a pending intent
357 * obj = NetworkRequestInfo
358 */
359 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
360
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900361 /** Handler thread used for both of the handlers below. */
362 @VisibleForTesting
363 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700364 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700365 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700366 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700367 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700368
Mike Lockwood0f79b542009-08-14 14:18:49 -0400369 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800370 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400371
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700372 private PowerManager.WakeLock mNetTransitionWakeLock;
373 private String mNetTransitionWakeLockCausedBy = "";
374 private int mNetTransitionWakeLockSerialNumber;
375 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800376 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700377
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700378 // used in DBG mode to track inet condition reports
379 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
380 private ArrayList mInetLog;
381
Robert Greenwalt434203a2010-10-11 16:00:27 -0700382 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400383 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700384 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700385 private boolean mDefaultProxyDisabled = false;
386
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400388 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Jason Monk602b2322013-07-03 17:04:33 -0400390 private PacManager mPacManager = null;
391
Erik Klineda4bfa82015-04-30 12:58:40 +0900392 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400394 private UserManager mUserManager;
395
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700396 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700397 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700398
Robert Greenwalt50393202011-06-21 17:26:14 -0700399 // the set of network types that can only be enabled by system/sig apps
400 List mProtectedNetworks;
401
John Spurlockbf991a82013-06-24 14:20:23 -0400402 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700403
Wink Savilleab9321d2013-06-29 21:10:57 -0700404 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400405
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900406 private KeepaliveTracker mKeepaliveTracker;
407
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700408 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
409 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700410 private final static int MAX_NET_ID = 65535;
411 private int mNextNetId = MIN_NET_ID;
412
Robert Greenwalt34524f02014-05-18 16:22:10 -0700413 // sequence number of NetworkRequests
414 private int mNextNetworkRequestId = 1;
415
Erik Kline7523eb32015-07-09 18:24:03 +0900416 // NetworkRequest activity String log entries.
417 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
418 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
419
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700420 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
421 private static final int MAX_VALIDATION_LOGS = 10;
422 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
423 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
424
425 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
426 synchronized(mValidationLogs) {
427 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
428 mValidationLogs.removeLast();
429 }
430 mValidationLogs.addFirst(new Pair(network, log));
431 }
432 }
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900453 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900454 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900455
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700456 /**
457 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
458 * Each list holds references to all NetworkAgentInfos that are used to
459 * satisfy requests for that network type.
460 *
461 * This array is built out at startup such that an unsupported network
462 * doesn't get an ArrayList instance, making this a tristate:
463 * unsupported, supported but not active and active.
464 *
465 * The actual lists are populated when we scan the network types that
466 * are supported on this device.
467 */
468 private ArrayList<NetworkAgentInfo> mTypeLists[];
469
470 public LegacyTypeTracker() {
471 mTypeLists = (ArrayList<NetworkAgentInfo>[])
472 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
473 }
474
475 public void addSupportedType(int type) {
476 if (mTypeLists[type] != null) {
477 throw new IllegalStateException(
478 "legacy list for type " + type + "already initialized");
479 }
480 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
481 }
482
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700483 public boolean isTypeSupported(int type) {
484 return isNetworkTypeValid(type) && mTypeLists[type] != null;
485 }
486
487 public NetworkAgentInfo getNetworkForType(int type) {
488 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
489 return mTypeLists[type].get(0);
490 } else {
491 return null;
492 }
493 }
494
Robert Greenwalt8d482522015-06-24 13:23:42 -0700495 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900496 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900497 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700498 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900499 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900500 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900501 }
502 }
503
504 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700505 public void add(int type, NetworkAgentInfo nai) {
506 if (!isTypeSupported(type)) {
507 return; // Invalid network type.
508 }
509 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
510
511 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
512 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700513 return;
514 }
515
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900516 list.add(nai);
517
518 // 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 +0900519 final boolean isDefaultNetwork = isDefaultNetwork(nai);
520 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700521 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
522 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700523 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
525
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900527 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900528 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
529 if (list == null || list.isEmpty()) {
530 return;
531 }
532
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534
535 if (!list.remove(nai)) {
536 return;
537 }
538
Robert Greenwalt8d482522015-06-24 13:23:42 -0700539 final DetailedState state = DetailedState.DISCONNECTED;
540
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900541 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700542 maybeLogBroadcast(nai, state, type, wasDefault);
543 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900544 }
545
546 if (!list.isEmpty() && wasFirstNetwork) {
547 if (DBG) log("Other network available for type " + type +
548 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900549 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700550 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
551 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552 }
553 }
554
555 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900556 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
557 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700558 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900559 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 }
561 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700562
Robert Greenwalt8d482522015-06-24 13:23:42 -0700563 // send out another legacy broadcast - currently only used for suspend/unsuspend
564 // toggle
565 public void update(NetworkAgentInfo nai) {
566 final boolean isDefault = isDefaultNetwork(nai);
567 final DetailedState state = nai.networkInfo.getDetailedState();
568 for (int type = 0; type < mTypeLists.length; type++) {
569 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700570 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700571 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700572 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700573 maybeLogBroadcast(nai, state, type, isDefault);
574 sendLegacyNetworkBroadcast(nai, state, type);
575 }
576 }
577 }
578
Lorenzo Colittia793a672014-07-31 23:20:17 +0900579 private String naiToString(NetworkAgentInfo nai) {
580 String name = (nai != null) ? nai.name() : "null";
581 String state = (nai.networkInfo != null) ?
582 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
583 "???/???";
584 return name + " " + state;
585 }
586
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700587 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900588 pw.println("mLegacyTypeTracker:");
589 pw.increaseIndent();
590 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700591 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900592 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700593 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900594 pw.println();
595 pw.println("Current state:");
596 pw.increaseIndent();
597 for (int type = 0; type < mTypeLists.length; type++) {
598 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
599 for (NetworkAgentInfo nai : mTypeLists[type]) {
600 pw.println(type + " " + naiToString(nai));
601 }
602 }
603 pw.decreaseIndent();
604 pw.decreaseIndent();
605 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700606 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700607 }
608 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
609
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900610 @VisibleForTesting
611 protected HandlerThread createHandlerThread() {
612 return new HandlerThread("ConnectivityServiceThread");
613 }
614
Jeff Sharkey899223b2012-08-04 15:24:58 -0700615 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700616 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800617 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800618
Erik Klineda4bfa82015-04-30 12:58:40 +0900619 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900620 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900621 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900622 mNetworkRequests.put(mDefaultRequest, defaultNRI);
623 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900624
625 mDefaultMobileDataRequest = createInternetRequestForTransport(
626 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700627
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900628 mHandlerThread = createHandlerThread();
629 mHandlerThread.start();
630 mHandler = new InternalHandler(mHandlerThread.getLooper());
631 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700632
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800633 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800634 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
635 String id = Settings.Secure.getString(context.getContentResolver(),
636 Settings.Secure.ANDROID_ID);
637 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700638 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800639 SystemProperties.set("net.hostname", name);
640 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800641 }
642
Jeremy Joslin79294842014-12-03 17:15:28 -0800643 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
644 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
645
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700646 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700647 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800648 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700649 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700650 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700651 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700652
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700653 try {
654 mPolicyManager.registerListener(mPolicyListener);
655 } catch (RemoteException e) {
656 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700657 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700658 }
659
660 final PowerManager powerManager = (PowerManager) context.getSystemService(
661 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700662 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
663 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
664 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800665 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700666
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700667 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700668
Wink Saville51f456f2013-04-23 14:26:51 -0700669 // TODO: What is the "correct" way to do determine if this is a wifi only device?
670 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
671 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700672 String[] naStrings = context.getResources().getStringArray(
673 com.android.internal.R.array.networkAttributes);
674 for (String naString : naStrings) {
675 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700676 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700677 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700678 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800679 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700680 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700681 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700682 }
Wink Saville51f456f2013-04-23 14:26:51 -0700683 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
684 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
685 n.type);
686 continue;
687 }
Wink Saville975c8482011-04-07 14:23:45 -0700688 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800689 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700690 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700691 continue;
692 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700693 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700694
Wink Saville975c8482011-04-07 14:23:45 -0700695 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700696 mNetworksDefined++;
697 } catch(Exception e) {
698 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700699 }
700 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700701
702 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
703 if (mNetConfigs[TYPE_VPN] == null) {
704 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
705 // don't need to add TYPE_VPN to mNetConfigs.
706 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
707 mNetworksDefined++; // used only in the log() statement below.
708 }
709
Wink Saville5e56bc52013-07-29 15:00:57 -0700710 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700711
Robert Greenwalt50393202011-06-21 17:26:14 -0700712 mProtectedNetworks = new ArrayList<Integer>();
713 int[] protectedNetworks = context.getResources().getIntArray(
714 com.android.internal.R.array.config_protectedNetworks);
715 for (int p : protectedNetworks) {
716 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
717 mProtectedNetworks.add(p);
718 } else {
719 if (DBG) loge("Ignoring protectedNetwork " + p);
720 }
721 }
722
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700723 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
724 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700725
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800726 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800727
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700728 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
729
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700730 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700731 IntentFilter intentFilter = new IntentFilter();
732 intentFilter.addAction(Intent.ACTION_USER_STARTING);
733 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700734 intentFilter.addAction(Intent.ACTION_USER_ADDED);
735 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000736 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700737 mContext.registerReceiverAsUser(
738 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900739
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700740 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700741 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700742 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700743 } catch (RemoteException e) {
744 loge("Error registering observer :" + e);
745 }
746
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700747 if (DBG) {
748 mInetLog = new ArrayList();
749 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700750
Erik Klineda4bfa82015-04-30 12:58:40 +0900751 mSettingsObserver = new SettingsObserver(mContext, mHandler);
752 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800753
John Spurlockbf991a82013-06-24 14:20:23 -0400754 mDataConnectionStats = new DataConnectionStats(mContext);
755 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400756
Jason Monkdecd2952013-10-10 14:02:51 -0400757 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700758
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400759 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900760
761 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700763
Erik Klineda4bfa82015-04-30 12:58:40 +0900764 private NetworkRequest createInternetRequestForTransport(int transportType) {
765 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900766 netCap.addCapability(NET_CAPABILITY_INTERNET);
767 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900768 if (transportType > -1) {
769 netCap.addTransportType(transportType);
770 }
771 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
772 }
773
774 private void handleMobileDataAlwaysOn() {
775 final boolean enable = (Settings.Global.getInt(
776 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
777 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
778 if (enable == isEnabled) {
779 return; // Nothing to do.
780 }
781
782 if (enable) {
783 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900784 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900785 } else {
786 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
787 }
788 }
789
790 private void registerSettingsCallbacks() {
791 // Watch for global HTTP proxy changes.
792 mSettingsObserver.observe(
793 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
794 EVENT_APPLY_GLOBAL_HTTP_PROXY);
795
796 // Watch for whether or not to keep mobile data always on.
797 mSettingsObserver.observe(
798 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
799 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
800 }
801
Robert Greenwalt34524f02014-05-18 16:22:10 -0700802 private synchronized int nextNetworkRequestId() {
803 return mNextNetworkRequestId++;
804 }
805
Paul Jensen67b0b072015-06-10 11:22:17 -0400806 @VisibleForTesting
807 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400808 synchronized (mNetworkForNetId) {
809 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
810 int netId = mNextNetId;
811 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
812 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500813 if (!mNetIdInUse.get(netId)) {
814 mNetIdInUse.put(netId, true);
815 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400816 }
817 }
818 }
819 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700820 }
821
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800822 private NetworkState getFilteredNetworkState(int networkType, int uid) {
823 NetworkInfo info = null;
824 LinkProperties lp = null;
825 NetworkCapabilities nc = null;
826 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800827 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800828
829 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
830 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
831 if (nai != null) {
832 synchronized (nai) {
833 info = new NetworkInfo(nai.networkInfo);
834 lp = new LinkProperties(nai.linkProperties);
835 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400836 // Network objects are outwardly immutable so there is no point to duplicating.
837 // Duplicating also precludes sharing socket factories and connection pools.
838 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800839 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800840 }
841 info.setType(networkType);
842 } else {
843 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
844 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
845 info.setIsAvailable(true);
846 lp = new LinkProperties();
847 nc = new NetworkCapabilities();
848 network = null;
849 }
850 info = getFilteredNetworkInfo(info, lp, uid);
851 }
852
Jeff Sharkey32566012014-12-02 18:30:14 -0800853 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400854 }
855
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800856 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
857 if (network == null) {
858 return null;
859 }
860 synchronized (mNetworkForNetId) {
861 return mNetworkForNetId.get(network.netId);
862 }
863 };
864
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900865 private Network[] getVpnUnderlyingNetworks(int uid) {
866 if (!mLockdownEnabled) {
867 int user = UserHandle.getUserId(uid);
868 synchronized (mVpns) {
869 Vpn vpn = mVpns.get(user);
870 if (vpn != null && vpn.appliesToUid(uid)) {
871 return vpn.getUnderlyingNetworks();
872 }
873 }
874 }
875 return null;
876 }
877
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800878 private NetworkState getUnfilteredActiveNetworkState(int uid) {
879 NetworkInfo info = null;
880 LinkProperties lp = null;
881 NetworkCapabilities nc = null;
882 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800883 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800884
Paul Jensen85cf78e2015-06-25 13:25:07 -0400885 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800886
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900887 final Network[] networks = getVpnUnderlyingNetworks(uid);
888 if (networks != null) {
889 // getUnderlyingNetworks() returns:
890 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
891 // empty array => the VPN explicitly said "no default network".
892 // non-empty array => the VPN specified one or more default networks; we use the
893 // first one.
894 if (networks.length > 0) {
895 nai = getNetworkAgentInfoForNetwork(networks[0]);
896 } else {
897 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800898 }
899 }
900
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800901 if (nai != null) {
902 synchronized (nai) {
903 info = new NetworkInfo(nai.networkInfo);
904 lp = new LinkProperties(nai.linkProperties);
905 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400906 // Network objects are outwardly immutable so there is no point to duplicating.
907 // Duplicating also precludes sharing socket factories and connection pools.
908 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800909 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800910 }
911 }
912
Jeff Sharkey32566012014-12-02 18:30:14 -0800913 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400914 }
915
916 /**
917 * Check if UID should be blocked from using the network with the given LinkProperties.
918 */
919 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700920 final boolean networkCostly;
921 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700922
Robert Greenwalt12e67352014-05-13 21:41:06 -0700923 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700924 synchronized (mRulesLock) {
925 networkCostly = mMeteredIfaces.contains(iface);
926 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700927 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700928
Jeff Sharkeydc988062015-09-14 10:09:47 -0700929 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700930 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700931 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
932 return true;
933 } else {
934 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700935 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700936 }
937
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900938 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
939 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
940 boolean removed = false;
941 boolean added = false;
942 synchronized (mBlockedAppUids) {
943 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
944 added = true;
945 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
946 removed = true;
947 }
948 }
949 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
950 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
951 }
952
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700953 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700954 * Return a filtered {@link NetworkInfo}, potentially marked
955 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800956 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700957 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800958 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
959 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400960 // network is blocked; clone and override state
961 info = new NetworkInfo(info);
962 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700963 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700965 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900966 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700967 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700968 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700969 }
970
971 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 * Return NetworkInfo for the active (i.e., connected) network interface.
973 * It is assumed that at most one network is active at a time. If more
974 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700975 * @return the info for the active network, or {@code null} if none is
976 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700980 enforceAccessPermission();
981 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900983 NetworkInfo ni = getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
984 maybeLogBlockedNetworkInfo(ni, uid);
985 return ni;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
987
Paul Jensen31a94f42015-02-13 14:18:39 -0500988 @Override
989 public Network getActiveNetwork() {
990 enforceAccessPermission();
Robin Leed2baf792016-03-24 12:07:00 +0000991 return getActiveNetworkForUidInternal(Binder.getCallingUid());
992 }
993
994 @Override
995 public Network getActiveNetworkForUid(int uid) {
996 enforceConnectivityInternalPermission();
997 return getActiveNetworkForUidInternal(uid);
998 }
999
1000 private Network getActiveNetworkForUidInternal(final int uid) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001001 final int user = UserHandle.getUserId(uid);
1002 int vpnNetId = NETID_UNSET;
1003 synchronized (mVpns) {
1004 final Vpn vpn = mVpns.get(user);
1005 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1006 }
1007 NetworkAgentInfo nai;
1008 if (vpnNetId != NETID_UNSET) {
1009 synchronized (mNetworkForNetId) {
1010 nai = mNetworkForNetId.get(vpnNetId);
1011 }
1012 if (nai != null) return nai.network;
1013 }
1014 nai = getDefaultNetwork();
1015 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1016 return nai != null ? nai.network : null;
1017 }
1018
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001019 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1020 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001021 final int uid = Binder.getCallingUid();
1022 NetworkState state = getUnfilteredActiveNetworkState(uid);
1023 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001024 }
1025
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001026 @Override
1027 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1028 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 NetworkState state = getUnfilteredActiveNetworkState(uid);
1030 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001031 }
1032
1033 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 public NetworkInfo getNetworkInfo(int networkType) {
1035 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001036 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001037 if (getVpnUnderlyingNetworks(uid) != null) {
1038 // A VPN is active, so we may need to return one of its underlying networks. This
1039 // information is not available in LegacyTypeTracker, so we have to get it from
1040 // getUnfilteredActiveNetworkState.
1041 NetworkState state = getUnfilteredActiveNetworkState(uid);
1042 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1043 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1044 }
1045 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 NetworkState state = getFilteredNetworkState(networkType, uid);
1047 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 }
1049
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 @Override
1051 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1052 enforceAccessPermission();
1053 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001055 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1056 if (nai != null) {
1057 synchronized (nai) {
1058 info = new NetworkInfo(nai.networkInfo);
1059 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 }
1061 }
1062 return info;
1063 }
1064
1065 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 public NetworkInfo[] getAllNetworkInfo() {
1067 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001068 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001069 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1070 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001071 NetworkInfo info = getNetworkInfo(networkType);
1072 if (info != null) {
1073 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001076 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001079 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001080 public Network getNetworkForType(int networkType) {
1081 enforceAccessPermission();
1082 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001083 NetworkState state = getFilteredNetworkState(networkType, uid);
1084 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1085 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001086 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001087 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001088 }
1089
1090 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 public Network[] getAllNetworks() {
1092 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001093 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001094 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001095 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001096 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001098 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001099 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001100 }
1101
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001102 @Override
1103 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1104 // The basic principle is: if an app's traffic could possibly go over a
1105 // network, without the app doing anything multinetwork-specific,
1106 // (hence, by "default"), then include that network's capabilities in
1107 // the array.
1108 //
1109 // In the normal case, app traffic only goes over the system's default
1110 // network connection, so that's the only network returned.
1111 //
1112 // With a VPN in force, some app traffic may go into the VPN, and thus
1113 // over whatever underlying networks the VPN specifies, while other app
1114 // traffic may go over the system default network (e.g.: a split-tunnel
1115 // VPN, or an app disallowed by the VPN), so the set of networks
1116 // returned includes the VPN's underlying networks and the system
1117 // default.
1118 enforceAccessPermission();
1119
1120 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1121
1122 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001123 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001124 if (nc != null) {
1125 result.put(nai.network, nc);
1126 }
1127
1128 if (!mLockdownEnabled) {
1129 synchronized (mVpns) {
1130 Vpn vpn = mVpns.get(userId);
1131 if (vpn != null) {
1132 Network[] networks = vpn.getUnderlyingNetworks();
1133 if (networks != null) {
1134 for (Network network : networks) {
1135 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001136 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001137 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001138 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001139 }
1140 }
1141 }
1142 }
1143 }
1144 }
1145
1146 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1147 out = result.values().toArray(out);
1148 return out;
1149 }
1150
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001151 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001152 public boolean isNetworkSupported(int networkType) {
1153 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001154 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001155 }
1156
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001157 /**
1158 * Return LinkProperties for the active (i.e., connected) default
1159 * network interface. It is assumed that at most one default network
1160 * is active at a time. If more than one is active, it is indeterminate
1161 * which will be returned.
1162 * @return the ip properties for the active network, or {@code null} if
1163 * none is active
1164 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001165 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001166 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 enforceAccessPermission();
1168 final int uid = Binder.getCallingUid();
1169 NetworkState state = getUnfilteredActiveNetworkState(uid);
1170 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001171 }
1172
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001174 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001175 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001176 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1177 if (nai != null) {
1178 synchronized (nai) {
1179 return new LinkProperties(nai.linkProperties);
1180 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001181 }
1182 return null;
1183 }
1184
Robert Greenwalt12e67352014-05-13 21:41:06 -07001185 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001186 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001187 public LinkProperties getLinkProperties(Network network) {
1188 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001189 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001190 if (nai != null) {
1191 synchronized (nai) {
1192 return new LinkProperties(nai.linkProperties);
1193 }
1194 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001195 return null;
1196 }
1197
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001198 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001199 if (nai != null) {
1200 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001201 if (nai.networkCapabilities != null) {
1202 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001203 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001204 }
1205 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001206 return null;
1207 }
1208
1209 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001210 public NetworkCapabilities getNetworkCapabilities(Network network) {
1211 enforceAccessPermission();
1212 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1213 }
1214
1215 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001216 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001217 // Require internal since we're handing out IMSI details
1218 enforceConnectivityInternalPermission();
1219
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001220 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001221 for (Network network : getAllNetworks()) {
1222 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1223 if (nai != null) {
1224 synchronized (nai) {
1225 final String subscriberId = (nai.networkMisc != null)
1226 ? nai.networkMisc.subscriberId : null;
1227 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1228 nai.networkCapabilities, network, subscriberId, null));
1229 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001230 }
1231 }
1232 return result.toArray(new NetworkState[result.size()]);
1233 }
1234
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001235 @Override
1236 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1237 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001238 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001239 final long token = Binder.clearCallingIdentity();
1240 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001241 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1242 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001243 try {
1244 return mPolicyManager.getNetworkQuotaInfo(state);
1245 } catch (RemoteException e) {
1246 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001247 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001248 return null;
1249 } finally {
1250 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001251 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001252 }
1253
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001254 @Override
1255 public boolean isActiveNetworkMetered() {
1256 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001258 final long token = Binder.clearCallingIdentity();
1259 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001260 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001261 } finally {
1262 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001263 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001264 }
1265
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001266 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1267 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1268 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001269 try {
1270 return mPolicyManager.isNetworkMetered(state);
1271 } catch (RemoteException e) {
1272 }
1273 }
1274 return false;
1275 }
1276
Jeff Sharkey216c1812012-08-05 14:29:23 -07001277 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1278 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001279 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001280 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001281 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001282 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001283 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001284
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001285 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 * Ensure that a network route exists to deliver traffic to the specified
1287 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001288 * @param networkType the type of the network over which traffic to the
1289 * specified host is to be routed
1290 * @param hostAddress the IP address of the host to which the route is
1291 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 * @return {@code true} on success, {@code false} on failure
1293 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001294 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001296 if (mProtectedNetworks.contains(networkType)) {
1297 enforceConnectivityInternalPermission();
1298 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001299
Chad Brubakerc0234532014-02-14 13:24:29 -08001300 InetAddress addr;
1301 try {
1302 addr = InetAddress.getByAddress(hostAddress);
1303 } catch (UnknownHostException e) {
1304 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1305 return false;
1306 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001309 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 return false;
1311 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001312
1313 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1314 if (nai == null) {
1315 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1316 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1317 } else {
1318 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1319 }
1320 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001321 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001322
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001323 DetailedState netState;
1324 synchronized (nai) {
1325 netState = nai.networkInfo.getDetailedState();
1326 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001327
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001328 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001329 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001330 log("requestRouteToHostAddress on down network "
1331 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001332 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001333 }
1334 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001336
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001337 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001338 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001339 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001340 LinkProperties lp;
1341 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001342 synchronized (nai) {
1343 lp = nai.linkProperties;
1344 netId = nai.network.netId;
1345 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001346 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001347 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1348 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001349 } finally {
1350 Binder.restoreCallingIdentity(token);
1351 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001352 }
1353
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001354 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001355 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001356 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001357 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001358 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001359 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001360 if (bestRoute.getGateway().equals(addr)) {
1361 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001362 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001363 } else {
1364 // if we will connect to this through another route, add a direct route
1365 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001366 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001367 }
1368 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001369 if (DBG) log("Adding legacy route " + bestRoute +
1370 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001371 try {
1372 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1373 } catch (Exception e) {
1374 // never crash - catch them all
1375 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001376 return false;
1377 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001378 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 }
1380
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001381 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1382 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001383 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001384 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001385 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001386 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001387 }
1388
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001389 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001390 // skip update when we've already applied rules
1391 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1392 if (oldRules == uidRules) return;
1393
1394 mUidRules.put(uid, uidRules);
1395 }
1396
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001397 // TODO: notify UID when it has requested targeted updates
1398 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001399
1400 @Override
1401 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001402 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001403 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001404 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001405 }
1406
1407 synchronized (mRulesLock) {
1408 mMeteredIfaces.clear();
1409 for (String iface : meteredIfaces) {
1410 mMeteredIfaces.add(iface);
1411 }
1412 }
1413 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001414
1415 @Override
1416 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1417 // caller is NPMS, since we only register with them
1418 if (LOGD_RULES) {
1419 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1420 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001421 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001422
1423 @Override
1424 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1425 if (LOGD_RULES) {
1426 // caller is NPMS, since we only register with them
1427 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1428 + whitelisted + ")");
1429 }
1430 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001431 };
1432
Robin Lee3b3dd942015-05-12 18:14:58 +01001433 /**
1434 * Require that the caller is either in the same user or has appropriate permission to interact
1435 * across users.
1436 *
1437 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1438 */
1439 private void enforceCrossUserPermission(int userId) {
1440 if (userId == UserHandle.getCallingUserId()) {
1441 // Not a cross-user call.
1442 return;
1443 }
1444 mContext.enforceCallingOrSelfPermission(
1445 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1446 "ConnectivityService");
1447 }
1448
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001449 private void enforceInternetPermission() {
1450 mContext.enforceCallingOrSelfPermission(
1451 android.Manifest.permission.INTERNET,
1452 "ConnectivityService");
1453 }
1454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001456 mContext.enforceCallingOrSelfPermission(
1457 android.Manifest.permission.ACCESS_NETWORK_STATE,
1458 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 }
1460
1461 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001462 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
1464
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001465 private void enforceTetherAccessPermission() {
1466 mContext.enforceCallingOrSelfPermission(
1467 android.Manifest.permission.ACCESS_NETWORK_STATE,
1468 "ConnectivityService");
1469 }
1470
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001471 private void enforceConnectivityInternalPermission() {
1472 mContext.enforceCallingOrSelfPermission(
1473 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1474 "ConnectivityService");
1475 }
1476
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001477 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001478 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001479 }
1480
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001481 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001482 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001483 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001484 }
1485
1486 private void sendInetConditionBroadcast(NetworkInfo info) {
1487 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1488 }
1489
Wink Saville628b0852011-08-04 15:01:58 -07001490 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001491 if (mLockdownTracker != null) {
1492 info = mLockdownTracker.augmentNetworkInfo(info);
1493 }
1494
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001495 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001496 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001497 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 if (info.isFailover()) {
1499 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1500 info.setFailover(false);
1501 }
1502 if (info.getReason() != null) {
1503 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1504 }
1505 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001506 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1507 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001509 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001510 return intent;
1511 }
1512
1513 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1514 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1515 }
1516
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001517 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001518 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1519 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1520 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001521 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001522 final long ident = Binder.clearCallingIdentity();
1523 try {
1524 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1525 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1526 } finally {
1527 Binder.restoreCallingIdentity(ident);
1528 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001529 }
1530
Mike Lockwood0f79b542009-08-14 14:18:49 -04001531 private void sendStickyBroadcast(Intent intent) {
1532 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001533 if (!mSystemReady) {
1534 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001535 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001536 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001537 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001538 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001539 }
1540
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001541 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001542 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001543 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001544 final NetworkInfo ni = intent.getParcelableExtra(
1545 ConnectivityManager.EXTRA_NETWORK_INFO);
1546 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1547 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1548 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001549 } else {
1550 BroadcastOptions opts = BroadcastOptions.makeBasic();
1551 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1552 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001553 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001554 final IBatteryStats bs = BatteryStatsService.getService();
1555 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001556 bs.noteConnectivityChanged(intent.getIntExtra(
1557 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1558 ni != null ? ni.getState().toString() : "?");
1559 } catch (RemoteException e) {
1560 }
1561 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001562 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001563 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001564 } finally {
1565 Binder.restoreCallingIdentity(ident);
1566 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001567 }
1568 }
1569
1570 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001571 loadGlobalProxy();
1572
Mike Lockwood0f79b542009-08-14 14:18:49 -04001573 synchronized(this) {
1574 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001575 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001576 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001577 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001578 }
1579 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001580 // load the global proxy at startup
1581 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001582
Robin Lee244ce8e2016-01-05 18:03:46 +00001583 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1584 // for user to unlock device too.
1585 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001586
Erik Klineda4bfa82015-04-30 12:58:40 +09001587 // Configure whether mobile data is always on.
1588 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1589
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001590 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001591
1592 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 }
1594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001596 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001597 *
1598 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001599 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001600 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001601 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1602 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001603
1604 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001605 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001606
Robert Greenwalt7b816022014-04-18 15:25:25 -07001607 if (networkAgent.networkCapabilities.hasTransport(
1608 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001609 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1610 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001611 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001612 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001613 } else if (networkAgent.networkCapabilities.hasTransport(
1614 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001615 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1616 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001617 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001618 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001619 } else {
1620 // do not track any other networks
1621 timeout = 0;
1622 }
1623
Robert Greenwalt7b816022014-04-18 15:25:25 -07001624 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001625 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001626 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001627 } catch (Exception e) {
1628 // You shall not crash!
1629 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001630 }
1631 }
1632 }
1633
1634 /**
1635 * Remove data activity tracking when network disconnects.
1636 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001637 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1638 final String iface = networkAgent.linkProperties.getInterfaceName();
1639 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001640
Robert Greenwalt7b816022014-04-18 15:25:25 -07001641 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1642 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001643 try {
1644 // the call fails silently if no idletimer setup for this interface
1645 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001646 } catch (Exception e) {
1647 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001648 }
1649 }
1650 }
1651
1652 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001653 * Reads the network specific MTU size from reources.
1654 * and set it on it's iface.
1655 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001656 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1657 final String iface = newLp.getInterfaceName();
1658 final int mtu = newLp.getMtu();
1659 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1660 if (VDBG) log("identical MTU - not setting");
1661 return;
1662 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001663
Robert Greenwalt43074032014-08-15 17:53:05 -07001664 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001665 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001666 return;
1667 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001668
w1997615afd812014-08-05 15:18:11 -07001669 // Cannot set MTU without interface name
1670 if (TextUtils.isEmpty(iface)) {
1671 loge("Setting MTU size with null iface.");
1672 return;
1673 }
1674
Robert Greenwalt7b816022014-04-18 15:25:25 -07001675 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001676 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001677 mNetd.setMtu(iface, mtu);
1678 } catch (Exception e) {
1679 Slog.e(TAG, "exception in setMtu()" + e);
1680 }
1681 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001682
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001683 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001684 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1685
1686 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001687 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001688 protected int getDefaultTcpRwnd() {
1689 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1690 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001691
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001692 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1693 if (isDefaultNetwork(nai) == false) {
1694 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001695 }
1696
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001697 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1698 String[] values = null;
1699 if (tcpBufferSizes != null) {
1700 values = tcpBufferSizes.split(",");
1701 }
1702
1703 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001704 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001705 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1706 values = tcpBufferSizes.split(",");
1707 }
1708
1709 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1710
1711 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001712 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001713
1714 final String prefix = "/sys/kernel/ipv4/tcp_";
1715 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1716 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1717 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1718 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1719 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1720 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1721 mCurrentTcpBufferSizes = tcpBufferSizes;
1722 } catch (IOException e) {
1723 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001724 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001725
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001726 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001727 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001728 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1729 if (rwndValue != 0) {
1730 SystemProperties.set(sysctlKey, rwndValue.toString());
1731 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001732 }
1733
Mattias Falk8b47b362011-08-23 14:15:13 +02001734 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001735 /*
1736 * Tell the VMs to toss their DNS caches
1737 */
1738 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1739 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001740 /*
1741 * Connectivity events can happen before boot has completed ...
1742 */
1743 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001744 final long ident = Binder.clearCallingIdentity();
1745 try {
1746 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1747 } finally {
1748 Binder.restoreCallingIdentity(ident);
1749 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001750 }
1751
Robert Greenwalt562cc542014-05-15 18:07:26 -07001752 @Override
1753 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001754 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1755 NETWORK_RESTORE_DELAY_PROP_NAME);
1756 if(restoreDefaultNetworkDelayStr != null &&
1757 restoreDefaultNetworkDelayStr.length() != 0) {
1758 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001759 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001760 } catch (NumberFormatException e) {
1761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001763 // if the system property isn't set, use the value for the apn type
1764 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1765
1766 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1767 (mNetConfigs[networkType] != null)) {
1768 ret = mNetConfigs[networkType].restoreTime;
1769 }
1770 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 }
1772
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001773 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001774 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001775 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001776 }
1777 return false;
1778 }
1779
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001780 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1781 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1782 final long DIAG_TIME_MS = 5000;
1783 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1784 // Start gathering diagnostic information.
1785 netDiags.add(new NetworkDiagnostics(
1786 nai.network,
1787 new LinkProperties(nai.linkProperties), // Must be a copy.
1788 DIAG_TIME_MS));
1789 }
1790
1791 for (NetworkDiagnostics netDiag : netDiags) {
1792 pw.println();
1793 netDiag.waitForMeasurements();
1794 netDiag.dump(pw);
1795 }
1796 }
1797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001798 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001799 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1800 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001801 if (mContext.checkCallingOrSelfPermission(
1802 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001804 pw.println("Permission Denial: can't dump ConnectivityService " +
1805 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1806 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 return;
1808 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001809
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001810 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001811 dumpNetworkDiagnostics(pw);
1812 return;
1813 }
Erik Kline379747a2015-06-05 17:47:34 +09001814
Lorenzo Colittie3805462015-06-03 11:18:24 +09001815 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001816 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001817 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001818 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001819 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001820 pw.println();
1821
Paul Jensen85cf78e2015-06-25 13:25:07 -04001822 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001823 pw.print("Active default network: ");
1824 if (defaultNai == null) {
1825 pw.println("none");
1826 } else {
1827 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001829 pw.println();
1830
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001831 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001832 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001833 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1834 pw.println(nai.toString());
1835 pw.increaseIndent();
1836 pw.println("Requests:");
1837 pw.increaseIndent();
1838 for (int i = 0; i < nai.networkRequests.size(); i++) {
1839 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001840 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001841 pw.decreaseIndent();
1842 pw.println("Lingered:");
1843 pw.increaseIndent();
1844 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1845 pw.decreaseIndent();
1846 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001847 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001848 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001849 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001850
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001851 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001852 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001853 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1854 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001855 }
1856 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001857 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001858
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001859 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001860
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001861 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001862 pw.print("mNetTransitionWakeLock: currently " +
1863 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1864 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1865 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1866 } else {
1867 pw.println(", last requested never");
1868 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001869 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001870
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001871 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001872 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001873
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001874 pw.println();
1875 mKeepaliveTracker.dump(pw);
1876
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001877 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001878
Lorenzo Colittie3805462015-06-03 11:18:24 +09001879 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001880 pw.println();
1881 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001882 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001883 for(int i = 0; i < mInetLog.size(); i++) {
1884 pw.println(mInetLog.get(i));
1885 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001886 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001887 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001888
1889 if (argsContain(args, "--short") == false) {
1890 pw.println();
1891 synchronized (mValidationLogs) {
1892 pw.println("mValidationLogs (most recent first):");
1893 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1894 pw.println(p.first);
1895 pw.increaseIndent();
1896 p.second.dump(fd, pw, args);
1897 pw.decreaseIndent();
1898 }
1899 }
Erik Kline7523eb32015-07-09 18:24:03 +09001900
1901 pw.println();
1902 pw.println("mNetworkRequestInfoLogs (most recent first):");
1903 pw.increaseIndent();
1904 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1905 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
1908
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001909 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001910 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001911 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001912 if (officialNai != null && officialNai.equals(nai)) return true;
1913 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001914 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001915 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001916 " - " + nai);
1917 }
1918 return false;
1919 }
1920
Paul Jensenc8b9a742014-09-30 15:37:41 -04001921 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001922 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001923 }
1924
Robert Greenwalt42acef32009-08-12 16:08:25 -07001925 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001926 private class NetworkStateTrackerHandler extends Handler {
1927 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001928 super(looper);
1929 }
1930
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001931 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001933 default:
1934 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001935 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001936 handleAsyncChannelHalfConnect(msg);
1937 break;
1938 }
1939 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1940 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1941 if (nai != null) nai.asyncChannel.disconnect();
1942 break;
1943 }
1944 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1945 handleAsyncChannelDisconnected(msg);
1946 break;
1947 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001948 }
1949 return true;
1950 }
1951
1952 private void maybeHandleNetworkAgentMessage(Message msg) {
1953 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1954 if (nai == null) {
1955 if (VDBG) {
1956 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
1957 log(String.format("%s from unknown NetworkAgent", what));
1958 }
1959 return;
1960 }
1961
1962 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001963 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001964 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
1965 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1966 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1967 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07001968 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001969 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1970 networkCapabilities)) {
1971 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1972 + nai.networkCapabilities + " -> " + networkCapabilities);
1973 }
1974 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001975 break;
1976 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001977 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001978 if (VDBG) {
1979 log("Update of LinkProperties for " + nai.name() +
1980 "; created=" + nai.created);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001981 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001982 LinkProperties oldLp = nai.linkProperties;
1983 synchronized (nai) {
1984 nai.linkProperties = (LinkProperties)msg.obj;
1985 }
1986 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001987 break;
1988 }
1989 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001990 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001991 updateNetworkInfo(nai, info);
1992 break;
1993 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001994 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07001995 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001996 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001997 break;
1998 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001999 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002000 try {
2001 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002002 } catch (Exception e) {
2003 // Never crash!
2004 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002005 }
2006 break;
2007 }
2008 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002009 try {
2010 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002011 } catch (Exception e) {
2012 // Never crash!
2013 loge("Exception in removeVpnUidRanges: " + e);
2014 }
2015 break;
2016 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002017 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002018 if (nai.created && !nai.networkMisc.explicitlySelected) {
2019 loge("ERROR: created network explicitly selected.");
2020 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002021 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002022 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002023 break;
2024 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002025 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002026 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2027 break;
2028 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002029 }
2030 }
2031
2032 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2033 switch (msg.what) {
2034 default:
2035 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002036 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002037 final NetworkAgentInfo nai;
2038 synchronized (mNetworkForNetId) {
2039 nai = mNetworkForNetId.get(msg.arg2);
2040 }
2041 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002042 final boolean valid =
2043 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002044 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2045 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002046 if (valid != nai.lastValidated) {
2047 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002048 nai.lastValidated = valid;
2049 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002050 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002051 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2052 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002053 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002054 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002055 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002056 Bundle redirectUrlBundle = new Bundle();
2057 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002058 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002059 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002060 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002061 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002062 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002063 break;
2064 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002065 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002066 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002067 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002068 handleLingerComplete(nai);
2069 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002070 break;
2071 }
Paul Jensen869868be2014-05-15 10:33:05 -04002072 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002073 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002074 final boolean visible = (msg.arg1 != 0);
2075 final NetworkAgentInfo nai;
2076 synchronized (mNetworkForNetId) {
2077 nai = mNetworkForNetId.get(netId);
2078 }
2079 // If captive portal status has changed, update capabilities.
2080 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2081 nai.lastCaptivePortalDetected = visible;
2082 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002083 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002084 }
2085 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002086 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002087 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002088 if (nai == null) {
2089 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2090 break;
2091 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002092 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002093 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2094 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002095 }
Paul Jensen869868be2014-05-15 10:33:05 -04002096 break;
2097 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002098 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002099 return true;
2100 }
2101
2102 @Override
2103 public void handleMessage(Message msg) {
2104 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2105 maybeHandleNetworkAgentMessage(msg);
2106 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002107 }
2108 }
2109
Paul Jensen85cf78e2015-06-25 13:25:07 -04002110 private void linger(NetworkAgentInfo nai) {
2111 nai.lingering = true;
2112 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2113 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2114 }
2115
Paul Jensen0cc17322014-11-25 15:26:53 -05002116 // Cancel any lingering so the linger timeout doesn't teardown a network.
2117 // This should be called when a network begins satisfying a NetworkRequest.
2118 // Note: depending on what state the NetworkMonitor is in (e.g.,
2119 // if it's awaiting captive portal login, or if validation failed), this
2120 // may trigger a re-evaluation of the network.
2121 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002122 nai.networkLingered.clear();
2123 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002124 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002125 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002126 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2127 }
2128
Robert Greenwalt7b816022014-04-18 15:25:25 -07002129 private void handleAsyncChannelHalfConnect(Message msg) {
2130 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002131 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2133 if (VDBG) log("NetworkFactory connected");
2134 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002135 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002136 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002137 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002138 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002139 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 }
2141 } else {
2142 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002143 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 }
2145 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2146 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2147 if (VDBG) log("NetworkAgent connected");
2148 // A network agent has requested a connection. Establish the connection.
2149 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2150 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2151 } else {
2152 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002153 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002154 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002155 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002156 synchronized (mNetworkForNetId) {
2157 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002158 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002159 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002160 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002161 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002162 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 }
2164 }
2165 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002166
Robert Greenwalt7b816022014-04-18 15:25:25 -07002167 private void handleAsyncChannelDisconnected(Message msg) {
2168 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2169 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002170 if (DBG) {
2171 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2172 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002174 // TODO - if we move the logic to the network agent (have them disconnect
2175 // because they lost all their requests or because their score isn't good)
2176 // then they would disconnect organically, report their new state and then
2177 // disconnect the channel.
2178 if (nai.networkInfo.isConnected()) {
2179 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2180 null, null);
2181 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002182 final boolean wasDefault = isDefaultNetwork(nai);
2183 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002184 mDefaultInetConditionPublished = 0;
2185 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002186 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002187 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2188 // by other networks that are already connected. Perhaps that can be done by
2189 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2190 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002191 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002192 mKeepaliveTracker.handleStopAllKeepalives(nai,
2193 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002194 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002195 mNetworkAgentInfos.remove(msg.replyTo);
2196 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002197 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002198 // Remove the NetworkAgent, but don't mark the netId as
2199 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002200 mNetworkForNetId.remove(nai.network.netId);
2201 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002202 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002203 for (int i = 0; i < nai.networkRequests.size(); i++) {
2204 NetworkRequest request = nai.networkRequests.valueAt(i);
2205 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2206 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2207 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002208 sendUpdatedScoreToFactories(request, 0);
2209 }
2210 }
2211 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2212 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002213 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002214 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002215 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002216 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002217 rematchAllNetworksAndRequests(null, 0);
Pierre Imai04e222252016-04-12 18:02:58 +09002218 if (wasDefault && getDefaultNetwork() == null) {
2219 // Log that we lost the default network and there is no replacement.
Hugo Benichi5f16f762016-04-20 12:09:33 +09002220 logDefaultNetworkEvent(null, nai);
Pierre Imai04e222252016-04-12 18:02:58 +09002221 }
Paul Jensen62d30802015-06-17 14:42:30 -04002222 if (nai.created) {
2223 // Tell netd to clean up the configuration for this network
2224 // (routing rules, DNS, etc).
2225 // This may be slow as it requires a lot of netd shelling out to ip and
2226 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2227 // after we've rematched networks with requests which should make a potential
2228 // fallback network the default or requested a new network from the
2229 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2230 // long time.
2231 try {
2232 mNetd.removeNetwork(nai.network.netId);
2233 } catch (Exception e) {
2234 loge("Exception removing network: " + e);
2235 }
2236 }
2237 synchronized (mNetworkForNetId) {
2238 mNetIdInUse.delete(nai.network.netId);
2239 }
2240 } else {
2241 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2242 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002243 }
2244 }
2245
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002246 // If this method proves to be too slow then we can maintain a separate
2247 // pendingIntent => NetworkRequestInfo map.
2248 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2249 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2250 Intent intent = pendingIntent.getIntent();
2251 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2252 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2253 if (existingPendingIntent != null &&
2254 existingPendingIntent.getIntent().filterEquals(intent)) {
2255 return entry.getValue();
2256 }
2257 }
2258 return null;
2259 }
2260
2261 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2262 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2263
2264 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2265 if (existingRequest != null) { // remove the existing request.
2266 if (DBG) log("Replacing " + existingRequest.request + " with "
2267 + nri.request + " because their intents matched.");
2268 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2269 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002270 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002271 }
2272
Erik Klineda4bfa82015-04-30 12:58:40 +09002273 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002274 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002275 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002276 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002277 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002278 if (nri.request.networkCapabilities.hasSignalStrength() &&
2279 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2280 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002281 }
2282 }
2283 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002284 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002285 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002286 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002287 }
2288 }
2289
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002290 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2291 int callingUid) {
2292 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2293 if (nri != null) {
2294 handleReleaseNetworkRequest(nri.request, callingUid);
2295 }
2296 }
2297
Paul Jensen99364842014-12-09 11:43:45 -05002298 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002299 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2300 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002301 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002302 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002303 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2304 // If this Network is already the highest scoring Network for a request, or if
2305 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002306 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002307 (nai.networkRequests.get(nri.request.requestId) != null ||
2308 // Note that this catches two important cases:
2309 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2310 // is currently satisfying the request. This is desirable when
2311 // cellular ends up validating but WiFi does not.
2312 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002313 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002314 // WiFi ends up validating and out scoring cellular.
2315 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2316 nai.getCurrentScoreAsValidated())) {
2317 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002318 }
2319 }
Paul Jensene0988542015-06-25 15:30:08 -04002320 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002321 }
2322
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002323 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2324 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002325 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002326 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002327 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2328 return;
2329 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002330 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002331 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002332 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002333 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002334 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002335 // Find all networks that are satisfying this request and remove the request
2336 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002337 // TODO - it's my understanding that for a request there is only a single
2338 // network satisfying it, so this loop is wasteful
2339 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002340 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2341 if (nai.networkRequests.get(nri.request.requestId) != null) {
2342 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002343 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002344 log(" Removing from current network " + nai.name() +
2345 ", leaving " + nai.networkRequests.size() +
2346 " requests.");
2347 }
Paul Jensen99364842014-12-09 11:43:45 -05002348 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002349 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002350 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002351 } else {
2352 // suspect there should only be one pass through here
2353 // but if any were kept do the check below
2354 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002355 }
2356 }
2357 }
2358
Robert Greenwalt51481852015-01-08 14:43:31 -08002359 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2360 if (nai != null) {
2361 mNetworkForRequestId.remove(nri.request.requestId);
2362 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002363 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002364 // that a network connected to serve it, even though the network was already
2365 // connected. Now that this request has gone away, we might have to pretend
2366 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002367 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002368 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2369 boolean doRemove = true;
2370 if (wasKept) {
2371 // check if any of the remaining requests for this network are for the
2372 // same legacy type - if so, don't remove the nai
2373 for (int i = 0; i < nai.networkRequests.size(); i++) {
2374 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2375 if (otherRequest.legacyType == nri.request.legacyType &&
2376 isRequest(otherRequest)) {
2377 if (DBG) log(" still have other legacy request - leaving");
2378 doRemove = false;
2379 }
2380 }
2381 }
2382
2383 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002384 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002385 }
2386 }
2387
Robert Greenwalta67be032014-05-16 15:49:14 -07002388 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002389 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2390 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002391 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002392 } else {
2393 // listens don't have a singular affectedNetwork. Check all networks to see
2394 // if this listen request applies and remove it.
2395 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2396 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002397 if (nri.request.networkCapabilities.hasSignalStrength() &&
2398 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2399 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002400 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002401 }
2402 }
2403 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2404 }
2405 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002406
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002407 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2408 enforceConnectivityInternalPermission();
2409 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2410 accept ? 1 : 0, always ? 1: 0, network));
2411 }
2412
2413 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2414 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2415 " accept=" + accept + " always=" + always);
2416
2417 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2418 if (nai == null) {
2419 // Nothing to do.
2420 return;
2421 }
2422
2423 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002424 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002425 return;
2426 }
2427
2428 if (!nai.networkMisc.explicitlySelected) {
2429 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2430 }
2431
2432 if (accept != nai.networkMisc.acceptUnvalidated) {
2433 int oldScore = nai.getCurrentScore();
2434 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002435 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002436 sendUpdatedScoreToFactories(nai);
2437 }
2438
2439 if (always) {
2440 nai.asyncChannel.sendMessage(
2441 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2442 }
2443
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002444 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002445 // Tell the NetworkAgent to not automatically reconnect to the network.
2446 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2447 // Teardown the nework.
2448 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002449 }
2450
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002451 }
2452
2453 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002454 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002455 mHandler.sendMessageDelayed(
2456 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2457 PROMPT_UNVALIDATED_DELAY_MS);
2458 }
2459
2460 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002461 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002462 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2463
2464 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2465 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002466 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002467 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002468 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2469 return;
2470 }
2471
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002472 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002473 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002474 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2475 intent.setClassName("com.android.settings",
2476 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002477
2478 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2479 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2480 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002481 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002482 }
2483
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002484 private class InternalHandler extends Handler {
2485 public InternalHandler(Looper looper) {
2486 super(looper);
2487 }
2488
2489 @Override
2490 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002491 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002492 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002493 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002494 String causedBy = null;
2495 synchronized (ConnectivityService.this) {
2496 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2497 mNetTransitionWakeLock.isHeld()) {
2498 mNetTransitionWakeLock.release();
2499 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002500 } else {
2501 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002502 }
2503 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002504 if (VDBG) {
2505 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2506 log("Failed to find a new network - expiring NetTransition Wakelock");
2507 } else {
2508 log("NetTransition Wakelock (" +
2509 (causedBy == null ? "unknown" : causedBy) +
2510 " cleared because we found a replacement network");
2511 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002512 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002513 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002514 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002515 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002516 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002517 break;
2518 }
Jason Monkdecd2952013-10-10 14:02:51 -04002519 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002520 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002521 break;
2522 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002523 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002524 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2525 break;
2526 }
2527 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2528 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002529 break;
2530 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002531 case EVENT_REGISTER_NETWORK_AGENT: {
2532 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2533 break;
2534 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002535 case EVENT_REGISTER_NETWORK_REQUEST:
2536 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002537 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002538 break;
2539 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002540 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2541 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002542 handleRegisterNetworkRequestWithIntent(msg);
2543 break;
2544 }
2545 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2546 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2547 break;
2548 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002549 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002550 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002551 break;
2552 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002553 case EVENT_SET_ACCEPT_UNVALIDATED: {
2554 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2555 break;
2556 }
2557 case EVENT_PROMPT_UNVALIDATED: {
2558 handlePromptUnvalidated((Network) msg.obj);
2559 break;
2560 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002561 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2562 handleMobileDataAlwaysOn();
2563 break;
2564 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002565 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2566 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2567 mKeepaliveTracker.handleStartKeepalive(msg);
2568 break;
2569 }
2570 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2571 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2572 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2573 int slot = msg.arg1;
2574 int reason = msg.arg2;
2575 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2576 break;
2577 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002578 case EVENT_SYSTEM_READY: {
2579 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2580 nai.networkMonitor.systemReady = true;
2581 }
2582 break;
2583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 }
2585 }
2586 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002587
2588 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002589 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002590 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002591 if (isTetheringSupported()) {
2592 return mTethering.tether(iface);
2593 } else {
2594 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2595 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002596 }
2597
2598 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002599 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002600 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002601
2602 if (isTetheringSupported()) {
2603 return mTethering.untether(iface);
2604 } else {
2605 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2606 }
2607 }
2608
2609 // javadoc from interface
2610 public int getLastTetherError(String iface) {
2611 enforceTetherAccessPermission();
2612
2613 if (isTetheringSupported()) {
2614 return mTethering.getLastTetherError(iface);
2615 } else {
2616 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2617 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002618 }
2619
2620 // TODO - proper iface API for selection by property, inspection, etc
2621 public String[] getTetherableUsbRegexs() {
2622 enforceTetherAccessPermission();
2623 if (isTetheringSupported()) {
2624 return mTethering.getTetherableUsbRegexs();
2625 } else {
2626 return new String[0];
2627 }
2628 }
2629
2630 public String[] getTetherableWifiRegexs() {
2631 enforceTetherAccessPermission();
2632 if (isTetheringSupported()) {
2633 return mTethering.getTetherableWifiRegexs();
2634 } else {
2635 return new String[0];
2636 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002637 }
2638
Danica Chang6fdd0c62010-08-11 14:54:43 -07002639 public String[] getTetherableBluetoothRegexs() {
2640 enforceTetherAccessPermission();
2641 if (isTetheringSupported()) {
2642 return mTethering.getTetherableBluetoothRegexs();
2643 } else {
2644 return new String[0];
2645 }
2646 }
2647
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002648 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002649 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002650 if (isTetheringSupported()) {
2651 return mTethering.setUsbTethering(enable);
2652 } else {
2653 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2654 }
2655 }
2656
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002657 // TODO - move iface listing, queries, etc to new module
2658 // javadoc from interface
2659 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002660 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002661 return mTethering.getTetherableIfaces();
2662 }
2663
2664 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002665 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002666 return mTethering.getTetheredIfaces();
2667 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002668
Robert Greenwalt5a735062010-03-02 17:25:02 -08002669 public String[] getTetheringErroredIfaces() {
2670 enforceTetherAccessPermission();
2671 return mTethering.getErroredIfaces();
2672 }
2673
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002674 public String[] getTetheredDhcpRanges() {
2675 enforceConnectivityInternalPermission();
2676 return mTethering.getTetheredDhcpRanges();
2677 }
2678
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002679 // if ro.tether.denied = true we default to no tethering
2680 // gservices could set the secure setting to 1 though to enable it on a build where it
2681 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002682 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002683 public boolean isTetheringSupported() {
2684 enforceTetherAccessPermission();
2685 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002686 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002687 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2688 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002689 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2690 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002691 mTethering.getTetherableWifiRegexs().length != 0 ||
2692 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2693 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002694 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002695
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002696 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002697 public void startTethering(int type, ResultReceiver receiver,
2698 boolean showProvisioningUi) {
2699 ConnectivityManager.enforceTetherChangePermission(mContext);
2700 if (!isTetheringSupported()) {
2701 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2702 return;
2703 }
2704 mTethering.startTethering(type, receiver, showProvisioningUi);
2705 }
2706
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002707 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002708 public void stopTethering(int type) {
2709 ConnectivityManager.enforceTetherChangePermission(mContext);
2710 mTethering.stopTethering(type);
2711 }
2712
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002713 // Called when we lose the default network and have no replacement yet.
2714 // This will automatically be cleared after X seconds or a new default network
2715 // becomes CONNECTED, whichever happens first. The timer is started by the
2716 // first caller and not restarted by subsequent callers.
2717 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002718 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002719 synchronized (this) {
2720 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002721 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002722 mNetTransitionWakeLock.acquire();
2723 mNetTransitionWakeLockCausedBy = forWhom;
2724 }
2725 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002726 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002727 mNetTransitionWakeLockTimeout);
2728 return;
2729 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002730
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002731 // 100 percent is full good, 0 is full bad.
2732 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002733 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002734 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002735 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002736 }
2737
Paul Jensenbfd17b72015-04-07 12:43:13 -04002738 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002739 enforceAccessPermission();
2740 enforceInternetPermission();
2741
Paul Jensenbfd17b72015-04-07 12:43:13 -04002742 NetworkAgentInfo nai;
2743 if (network == null) {
2744 nai = getDefaultNetwork();
2745 } else {
2746 nai = getNetworkAgentInfoForNetwork(network);
2747 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002748 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2749 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2750 return;
2751 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002752 // Revalidate if the app report does not match our current validated state.
2753 if (hasConnectivity == nai.lastValidated) return;
2754 final int uid = Binder.getCallingUid();
2755 if (DBG) {
2756 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2757 ") by " + uid);
2758 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002759 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002760 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2761 // which isn't meant to work on uncreated networks.
2762 if (!nai.created) return;
2763
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002764 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002765
2766 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2767 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002768 }
2769
Paul Jensencee9b512015-05-06 07:32:40 -04002770 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002771 // this information is already available as a world read/writable jvm property
2772 // so this API change wouldn't have a benifit. It also breaks the passing
2773 // of proxy info to all the JVMs.
2774 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002775 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002776 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002777 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2778 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002779 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002780 }
2781
Paul Jensencee9b512015-05-06 07:32:40 -04002782 public ProxyInfo getProxyForNetwork(Network network) {
2783 if (network == null) return getDefaultProxy();
2784 final ProxyInfo globalProxy = getGlobalProxy();
2785 if (globalProxy != null) return globalProxy;
2786 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2787 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2788 // caller may not have.
2789 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2790 if (nai == null) return null;
2791 synchronized (nai) {
2792 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2793 if (proxyInfo == null) return null;
2794 return new ProxyInfo(proxyInfo);
2795 }
2796 }
2797
Paul Jensene0bef712014-12-10 15:12:18 -05002798 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2799 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2800 // proxy is null then there is no proxy in place).
2801 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2802 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2803 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2804 proxy = null;
2805 }
2806 return proxy;
2807 }
2808
2809 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2810 // better for determining if a new proxy broadcast is necessary:
2811 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2812 // avoid unnecessary broadcasts.
2813 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2814 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2815 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2816 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2817 // all set.
2818 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2819 a = canonicalizeProxyInfo(a);
2820 b = canonicalizeProxyInfo(b);
2821 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2822 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2823 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2824 }
2825
Jason Monk207900c2014-04-25 15:00:09 -04002826 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002827 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002828
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002829 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002830 if (proxyProperties == mGlobalProxy) return;
2831 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2832 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2833
2834 String host = "";
2835 int port = 0;
2836 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002837 String pacFileUrl = "";
2838 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002839 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002840 if (!proxyProperties.isValid()) {
2841 if (DBG)
2842 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2843 return;
2844 }
Jason Monk207900c2014-04-25 15:00:09 -04002845 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002846 host = mGlobalProxy.getHost();
2847 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002848 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002849 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002850 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002851 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002852 } else {
2853 mGlobalProxy = null;
2854 }
2855 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002856 final long token = Binder.clearCallingIdentity();
2857 try {
2858 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2859 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2860 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2861 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002862 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002863 } finally {
2864 Binder.restoreCallingIdentity(token);
2865 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002866
Jason Monkcf0f97a2014-10-02 15:39:38 -04002867 if (mGlobalProxy == null) {
2868 proxyProperties = mDefaultProxy;
2869 }
2870 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002871 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002872 }
2873
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002874 private void loadGlobalProxy() {
2875 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002876 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2877 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2878 String exclList = Settings.Global.getString(res,
2879 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002880 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2881 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002882 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002883 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002884 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002885 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002886 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002887 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002888 if (!proxyProperties.isValid()) {
2889 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2890 return;
2891 }
2892
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002893 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002894 mGlobalProxy = proxyProperties;
2895 }
2896 }
2897 }
2898
Jason Monk207900c2014-04-25 15:00:09 -04002899 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002900 // this information is already available as a world read/writable jvm property
2901 // so this API change wouldn't have a benifit. It also breaks the passing
2902 // of proxy info to all the JVMs.
2903 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002904 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002905 return mGlobalProxy;
2906 }
2907 }
2908
Jason Monk207900c2014-04-25 15:00:09 -04002909 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002910 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002911 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002912 proxy = null;
2913 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002914 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002916 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002917 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002918 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2919 return;
2920 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002921
2922 // This call could be coming from the PacManager, containing the port of the local
2923 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2924 // global (to get the correct local port), and send a broadcast.
2925 // TODO: Switch PacManager to have its own message to send back rather than
2926 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002927 if ((mGlobalProxy != null) && (proxy != null)
2928 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002929 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2930 mGlobalProxy = proxy;
2931 sendProxyBroadcast(mGlobalProxy);
2932 return;
2933 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002934 mDefaultProxy = proxy;
2935
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002936 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002937 if (!mDefaultProxyDisabled) {
2938 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002939 }
2940 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002941 }
2942
Paul Jensene0bef712014-12-10 15:12:18 -05002943 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2944 // This method gets called when any network changes proxy, but the broadcast only ever contains
2945 // the default proxy (even if it hasn't changed).
2946 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2947 // world where an app might be bound to a non-default network.
2948 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2949 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2950 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2951
2952 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2953 sendProxyBroadcast(getDefaultProxy());
2954 }
2955 }
2956
Robert Greenwalt434203a2010-10-11 16:00:27 -07002957 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002958 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2959 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002960 if (!TextUtils.isEmpty(proxy)) {
2961 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002962 if (data.length == 0) {
2963 return;
2964 }
2965
Robert Greenwalt434203a2010-10-11 16:00:27 -07002966 String proxyHost = data[0];
2967 int proxyPort = 8080;
2968 if (data.length > 1) {
2969 try {
2970 proxyPort = Integer.parseInt(data[1]);
2971 } catch (NumberFormatException e) {
2972 return;
2973 }
2974 }
Jason Monk207900c2014-04-25 15:00:09 -04002975 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002976 setGlobalProxy(p);
2977 }
2978 }
2979
Jason Monk207900c2014-04-25 15:00:09 -04002980 private void sendProxyBroadcast(ProxyInfo proxy) {
2981 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002982 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002983 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002984 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002985 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2986 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002987 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002988 final long ident = Binder.clearCallingIdentity();
2989 try {
2990 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2991 } finally {
2992 Binder.restoreCallingIdentity(ident);
2993 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002994 }
2995
2996 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002997 final private HashMap<Uri, Integer> mUriEventMap;
2998 final private Context mContext;
2999 final private Handler mHandler;
3000
3001 SettingsObserver(Context context, Handler handler) {
3002 super(null);
3003 mUriEventMap = new HashMap<Uri, Integer>();
3004 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003005 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003006 }
3007
Erik Klineda4bfa82015-04-30 12:58:40 +09003008 void observe(Uri uri, int what) {
3009 mUriEventMap.put(uri, what);
3010 final ContentResolver resolver = mContext.getContentResolver();
3011 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003012 }
3013
3014 @Override
3015 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003016 Slog.wtf(TAG, "Should never be reached.");
3017 }
3018
3019 @Override
3020 public void onChange(boolean selfChange, Uri uri) {
3021 final Integer what = mUriEventMap.get(uri);
3022 if (what != null) {
3023 mHandler.obtainMessage(what.intValue()).sendToTarget();
3024 } else {
3025 loge("No matching event to send for URI=" + uri);
3026 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003027 }
3028 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003029
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003030 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003031 Slog.d(TAG, s);
3032 }
3033
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003034 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003035 Slog.e(TAG, s);
3036 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003037
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003038 private static <T> T checkNotNull(T value, String message) {
3039 if (value == null) {
3040 throw new NullPointerException(message);
3041 }
3042 return value;
3043 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003044
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003045 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003046 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003047 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3048 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3049 *
3050 * @param oldPackage Package name of the application which currently controls VPN, which will
3051 * be replaced. If there is no such application, this should should either be
3052 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3053 * @param newPackage Package name of the application which should gain control of VPN, or
3054 * {@code null} to disable.
3055 * @param userId User for whom to prepare the new VPN.
3056 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003057 * @hide
3058 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003059 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003060 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3061 int userId) {
3062 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003063 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003064
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003065 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003066 Vpn vpn = mVpns.get(userId);
3067 if (vpn != null) {
3068 return vpn.prepare(oldPackage, newPackage);
3069 } else {
3070 return false;
3071 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003072 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003073 }
3074
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003075 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003076 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3077 * This method is used by system-privileged apps.
3078 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3079 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3080 *
3081 * @param packageName The package for which authorization state should change.
3082 * @param userId User for whom {@code packageName} is installed.
3083 * @param authorized {@code true} if this app should be able to start a VPN connection without
3084 * explicit user approval, {@code false} if not.
3085 *
Jeff Davidson05542602014-08-11 14:07:27 -07003086 * @hide
3087 */
3088 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003089 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3090 enforceCrossUserPermission(userId);
3091
Jeff Davidson05542602014-08-11 14:07:27 -07003092 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003093 Vpn vpn = mVpns.get(userId);
3094 if (vpn != null) {
3095 vpn.setPackageAuthorization(packageName, authorized);
3096 }
Jeff Davidson05542602014-08-11 14:07:27 -07003097 }
3098 }
3099
3100 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003101 * Configure a TUN interface and return its file descriptor. Parameters
3102 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003103 * and not available in ConnectivityManager. Permissions are checked in
3104 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003105 * @hide
3106 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003107 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003108 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003109 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003110 int user = UserHandle.getUserId(Binder.getCallingUid());
3111 synchronized(mVpns) {
3112 return mVpns.get(user).establish(config);
3113 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003114 }
3115
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003116 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003117 * Start legacy VPN, controlling native daemons as needed. Creates a
3118 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003119 */
3120 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003121 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003122 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003123 final LinkProperties egress = getActiveLinkProperties();
3124 if (egress == null) {
3125 throw new IllegalStateException("Missing active network connection");
3126 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003127 int user = UserHandle.getUserId(Binder.getCallingUid());
3128 synchronized(mVpns) {
3129 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3130 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003131 }
3132
3133 /**
3134 * Return the information of the ongoing legacy VPN. This method is used
3135 * by VpnSettings and not available in ConnectivityManager. Permissions
3136 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003137 */
3138 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003139 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3140 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003141 if (mLockdownEnabled) {
3142 return null;
3143 }
3144
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003145 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003146 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003147 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003148 }
3149
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003150 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003151 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3152 * and not available in ConnectivityManager.
3153 */
3154 @Override
3155 public VpnInfo[] getAllVpnInfo() {
3156 enforceConnectivityInternalPermission();
3157 if (mLockdownEnabled) {
3158 return new VpnInfo[0];
3159 }
3160
3161 synchronized(mVpns) {
3162 List<VpnInfo> infoList = new ArrayList<>();
3163 for (int i = 0; i < mVpns.size(); i++) {
3164 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3165 if (info != null) {
3166 infoList.add(info);
3167 }
3168 }
3169 return infoList.toArray(new VpnInfo[infoList.size()]);
3170 }
3171 }
3172
3173 /**
3174 * @return VPN information for accounting, or null if we can't retrieve all required
3175 * information, e.g primary underlying iface.
3176 */
3177 @Nullable
3178 private VpnInfo createVpnInfo(Vpn vpn) {
3179 VpnInfo info = vpn.getVpnInfo();
3180 if (info == null) {
3181 return null;
3182 }
3183 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3184 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3185 // the underlyingNetworks list.
3186 if (underlyingNetworks == null) {
3187 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3188 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3189 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3190 }
3191 } else if (underlyingNetworks.length > 0) {
3192 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3193 if (linkProperties != null) {
3194 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3195 }
3196 }
3197 return info.primaryUnderlyingIface == null ? null : info;
3198 }
3199
3200 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003201 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3202 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003203 * Permissions are checked in Vpn class.
3204 * @hide
3205 */
3206 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003207 public VpnConfig getVpnConfig(int userId) {
3208 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003209 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003210 Vpn vpn = mVpns.get(userId);
3211 if (vpn != null) {
3212 return vpn.getVpnConfig();
3213 } else {
3214 return null;
3215 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003216 }
3217 }
3218
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003219 @Override
3220 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003221 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3222 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3223 return false;
3224 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003225
3226 // Tear down existing lockdown if profile was removed
3227 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3228 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003229 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3230 final VpnProfile profile = VpnProfile.decode(
3231 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003232 if (profile == null) {
3233 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3234 setLockdownTracker(null);
3235 return true;
3236 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003237 int user = UserHandle.getUserId(Binder.getCallingUid());
3238 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003239 Vpn vpn = mVpns.get(user);
3240 if (vpn == null) {
3241 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3242 return false;
3243 }
3244 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003245 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003246 } else {
3247 setLockdownTracker(null);
3248 }
3249
3250 return true;
3251 }
3252
3253 /**
3254 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3255 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3256 */
3257 private void setLockdownTracker(LockdownVpnTracker tracker) {
3258 // Shutdown any existing tracker
3259 final LockdownVpnTracker existing = mLockdownTracker;
3260 mLockdownTracker = null;
3261 if (existing != null) {
3262 existing.shutdown();
3263 }
3264
3265 try {
3266 if (tracker != null) {
3267 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003268 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003269 mLockdownTracker = tracker;
3270 mLockdownTracker.init();
3271 } else {
3272 mNetd.setFirewallEnabled(false);
3273 }
3274 } catch (RemoteException e) {
3275 // ignored; NMS lives inside system_server
3276 }
3277 }
3278
3279 private void throwIfLockdownEnabled() {
3280 if (mLockdownEnabled) {
3281 throw new IllegalStateException("Unavailable in lockdown mode");
3282 }
3283 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003284
Robin Lee244ce8e2016-01-05 18:03:46 +00003285 /**
3286 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3287 *
3288 * @return {@code false} in case of errors; {@code true} otherwise.
3289 */
3290 private boolean updateAlwaysOnVpn(int user) {
3291 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3292 if (lockdownPackage == null) {
3293 return true;
3294 }
3295
3296 // Create an intent to start the VPN service declared in the app's manifest.
3297 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3298 serviceIntent.setPackage(lockdownPackage);
3299
3300 try {
3301 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3302 } catch (RuntimeException e) {
3303 return false;
3304 }
3305 }
3306
3307 @Override
3308 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3309 enforceConnectivityInternalPermission();
3310 enforceCrossUserPermission(userId);
3311
3312 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3313 if (LockdownVpnTracker.isEnabled()) {
3314 return false;
3315 }
3316
3317 // If the current VPN package is the same as the new one, this is a no-op
3318 final String oldPackage = getAlwaysOnVpnPackage(userId);
3319 if (TextUtils.equals(oldPackage, packageName)) {
3320 return true;
3321 }
3322
3323 synchronized (mVpns) {
3324 Vpn vpn = mVpns.get(userId);
3325 if (vpn == null) {
3326 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3327 return false;
3328 }
3329 if (!vpn.setAlwaysOnPackage(packageName)) {
3330 return false;
3331 }
3332 if (!updateAlwaysOnVpn(userId)) {
3333 vpn.setAlwaysOnPackage(null);
3334 return false;
3335 }
3336 }
3337 return true;
3338 }
3339
3340 @Override
3341 public String getAlwaysOnVpnPackage(int userId) {
3342 enforceConnectivityInternalPermission();
3343 enforceCrossUserPermission(userId);
3344
3345 synchronized (mVpns) {
3346 Vpn vpn = mVpns.get(userId);
3347 if (vpn == null) {
3348 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3349 return null;
3350 }
3351 return vpn.getAlwaysOnPackage();
3352 }
3353 }
3354
Wink Savilleab9321d2013-06-29 21:10:57 -07003355 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003356 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003357 // TODO: Remove? Any reason to trigger a provisioning check?
3358 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003359 }
3360
3361 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003362 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003363
Paul Jensen89e0f092014-09-15 15:59:36 -04003364 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003365 Intent intent = new Intent(action);
3366 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003367 // Concatenate the range of types onto the range of NetIDs.
3368 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003369 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003370 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003371 }
3372
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003373 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003374 * Show or hide network provisioning notifications.
3375 *
3376 * We use notifications for two purposes: to notify that a network requires sign in
3377 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3378 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3379 * particular network we can display the notification type that was most recently requested.
3380 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3381 * might first display NO_INTERNET, and then when the captive portal check completes, display
3382 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003383 *
3384 * @param id an identifier that uniquely identifies this notification. This must match
3385 * between show and hide calls. We use the NetID value but for legacy callers
3386 * we concatenate the range of types with the range of NetIDs.
3387 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003388 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003389 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3390 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003391 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003392 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3393 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003394 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003395 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003396
3397 Resources r = Resources.getSystem();
3398 NotificationManager notificationManager = (NotificationManager) mContext
3399 .getSystemService(Context.NOTIFICATION_SERVICE);
3400
3401 if (visible) {
3402 CharSequence title;
3403 CharSequence details;
3404 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003405 if (notifyType == NotificationType.NO_INTERNET &&
3406 networkType == ConnectivityManager.TYPE_WIFI) {
3407 title = r.getString(R.string.wifi_no_internet, 0);
3408 details = r.getString(R.string.wifi_no_internet_detailed);
3409 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3410 } else if (notifyType == NotificationType.SIGN_IN) {
3411 switch (networkType) {
3412 case ConnectivityManager.TYPE_WIFI:
3413 title = r.getString(R.string.wifi_available_sign_in, 0);
3414 details = r.getString(R.string.network_available_sign_in_detailed,
3415 extraInfo);
3416 icon = R.drawable.stat_notify_wifi_in_range;
3417 break;
3418 case ConnectivityManager.TYPE_MOBILE:
3419 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3420 title = r.getString(R.string.network_available_sign_in, 0);
3421 // TODO: Change this to pull from NetworkInfo once a printable
3422 // name has been added to it
3423 details = mTelephonyManager.getNetworkOperatorName();
3424 icon = R.drawable.stat_notify_rssi_in_range;
3425 break;
3426 default:
3427 title = r.getString(R.string.network_available_sign_in, 0);
3428 details = r.getString(R.string.network_available_sign_in_detailed,
3429 extraInfo);
3430 icon = R.drawable.stat_notify_rssi_in_range;
3431 break;
3432 }
3433 } else {
3434 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3435 + getNetworkTypeName(networkType));
3436 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003437 }
3438
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003439 Notification notification = new Notification.Builder(mContext)
3440 .setWhen(0)
3441 .setSmallIcon(icon)
3442 .setAutoCancel(true)
3443 .setTicker(title)
3444 .setColor(mContext.getColor(
3445 com.android.internal.R.color.system_notification_accent_color))
3446 .setContentTitle(title)
3447 .setContentText(details)
3448 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003449 .setLocalOnly(true)
3450 .setPriority(highPriority ?
3451 Notification.PRIORITY_HIGH :
3452 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003453 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003454 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003455 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003456
Wink Saville948282b2013-08-29 08:55:16 -07003457 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003458 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003459 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003460 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003461 npe.printStackTrace();
3462 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003463 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003464 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003465 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003466 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003467 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003468 npe.printStackTrace();
3469 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003470 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003471 }
3472
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003473 /** Location to an updatable file listing carrier provisioning urls.
3474 * An example:
3475 *
3476 * <?xml version="1.0" encoding="utf-8"?>
3477 * <provisioningUrls>
3478 * <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 -07003479 * </provisioningUrls>
3480 */
3481 private static final String PROVISIONING_URL_PATH =
3482 "/data/misc/radio/provisioning_urls.xml";
3483 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003484
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003485 /** XML tag for root element. */
3486 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3487 /** XML tag for individual url */
3488 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003489 /** XML attribute for mcc */
3490 private static final String ATTR_MCC = "mcc";
3491 /** XML attribute for mnc */
3492 private static final String ATTR_MNC = "mnc";
3493
Paul Jensen434dde82015-06-11 09:43:30 -04003494 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003495 FileReader fileReader = null;
3496 XmlPullParser parser = null;
3497 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003498
3499 try {
3500 fileReader = new FileReader(mProvisioningUrlFile);
3501 parser = Xml.newPullParser();
3502 parser.setInput(fileReader);
3503 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3504
3505 while (true) {
3506 XmlUtils.nextElement(parser);
3507
3508 String element = parser.getName();
3509 if (element == null) break;
3510
Paul Jensen434dde82015-06-11 09:43:30 -04003511 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003512 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3513 try {
3514 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3515 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3516 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3517 parser.next();
3518 if (parser.getEventType() == XmlPullParser.TEXT) {
3519 return parser.getText();
3520 }
3521 }
3522 }
3523 } catch (NumberFormatException e) {
3524 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3525 }
3526 }
3527 }
3528 return null;
3529 } catch (FileNotFoundException e) {
3530 loge("Carrier Provisioning Urls file not found");
3531 } catch (XmlPullParserException e) {
3532 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3533 } catch (IOException e) {
3534 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3535 } finally {
3536 if (fileReader != null) {
3537 try {
3538 fileReader.close();
3539 } catch (IOException e) {}
3540 }
3541 }
3542 return null;
3543 }
3544
Wink Saville42d4f082013-07-20 20:31:59 -07003545 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003546 public String getMobileProvisioningUrl() {
3547 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003548 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003549 if (TextUtils.isEmpty(url)) {
3550 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003551 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003552 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003553 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003554 }
Wink Saville8cf35602013-07-10 23:00:07 -07003555 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003556 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003557 String phoneNumber = mTelephonyManager.getLine1Number();
3558 if (TextUtils.isEmpty(phoneNumber)) {
3559 phoneNumber = "0000000000";
3560 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003561 url = String.format(url,
3562 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3563 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003564 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003565 }
3566
Wink Savilleab9321d2013-06-29 21:10:57 -07003567 return url;
3568 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003569
Wink Saville948282b2013-08-29 08:55:16 -07003570 @Override
3571 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003572 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003573 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003574 final long ident = Binder.clearCallingIdentity();
3575 try {
3576 setProvNotificationVisible(visible, networkType, action);
3577 } finally {
3578 Binder.restoreCallingIdentity(ident);
3579 }
Wink Saville948282b2013-08-29 08:55:16 -07003580 }
Wink Saville7788c612013-08-29 14:57:08 -07003581
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003582 @Override
3583 public void setAirplaneMode(boolean enable) {
3584 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003585 final long ident = Binder.clearCallingIdentity();
3586 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003587 final ContentResolver cr = mContext.getContentResolver();
3588 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3589 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3590 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003591 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003592 } finally {
3593 Binder.restoreCallingIdentity(ident);
3594 }
3595 }
3596
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003597 private void onUserStart(int userId) {
3598 synchronized(mVpns) {
3599 Vpn userVpn = mVpns.get(userId);
3600 if (userVpn != null) {
3601 loge("Starting user already has a VPN");
3602 return;
3603 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003604 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003605 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003606 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003607 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3608 updateLockdownVpn();
3609 } else {
3610 updateAlwaysOnVpn(userId);
3611 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003612 }
3613
3614 private void onUserStop(int userId) {
3615 synchronized(mVpns) {
3616 Vpn userVpn = mVpns.get(userId);
3617 if (userVpn == null) {
3618 loge("Stopping user has no VPN");
3619 return;
3620 }
3621 mVpns.delete(userId);
3622 }
3623 }
3624
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003625 private void onUserAdded(int userId) {
3626 synchronized(mVpns) {
3627 final int vpnsSize = mVpns.size();
3628 for (int i = 0; i < vpnsSize; i++) {
3629 Vpn vpn = mVpns.valueAt(i);
3630 vpn.onUserAdded(userId);
3631 }
3632 }
3633 }
3634
3635 private void onUserRemoved(int userId) {
3636 synchronized(mVpns) {
3637 final int vpnsSize = mVpns.size();
3638 for (int i = 0; i < vpnsSize; i++) {
3639 Vpn vpn = mVpns.valueAt(i);
3640 vpn.onUserRemoved(userId);
3641 }
3642 }
3643 }
3644
Robin Lee89e7a692016-02-29 14:38:17 +00003645 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003646 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3647 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3648 updateLockdownVpn();
3649 } else {
3650 updateAlwaysOnVpn(userId);
3651 }
3652 }
3653
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003654 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3655 @Override
3656 public void onReceive(Context context, Intent intent) {
3657 final String action = intent.getAction();
3658 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3659 if (userId == UserHandle.USER_NULL) return;
3660
3661 if (Intent.ACTION_USER_STARTING.equals(action)) {
3662 onUserStart(userId);
3663 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3664 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003665 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3666 onUserAdded(userId);
3667 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3668 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003669 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3670 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003671 }
3672 }
3673 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003674
Robert Greenwalta67be032014-05-16 15:49:14 -07003675 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3676 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003677 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3678 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003679
Robert Greenwalta67be032014-05-16 15:49:14 -07003680 private static class NetworkFactoryInfo {
3681 public final String name;
3682 public final Messenger messenger;
3683 public final AsyncChannel asyncChannel;
3684
3685 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3686 this.name = name;
3687 this.messenger = messenger;
3688 this.asyncChannel = asyncChannel;
3689 }
3690 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003691
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003692 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003693 * A NetworkRequest as registered by an application can be one of three
3694 * types:
3695 *
3696 * - "listen", for which the framework will issue callbacks about any
3697 * and all networks that match the specified NetworkCapabilities,
3698 *
3699 * - "request", capable of causing a specific network to be created
3700 * first (e.g. a telephony DUN request), the framework will issue
3701 * callbacks about the single, highest scoring current network
3702 * (if any) that matches the specified NetworkCapabilities, or
3703 *
3704 * - "track the default network", a hybrid of the two designed such
3705 * that the framework will issue callbacks for the single, highest
3706 * scoring current network (if any) that matches the capabilities of
3707 * the default Internet request (mDefaultRequest), but which cannot
3708 * cause the framework to either create or retain the existence of
3709 * any specific network.
3710 *
3711 */
3712 private static enum NetworkRequestType {
3713 LISTEN,
3714 TRACK_DEFAULT,
3715 REQUEST
3716 };
3717
3718 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003719 * Tracks info about the requester.
3720 * Also used to notice when the calling process dies so we can self-expire
3721 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003722 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003723 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003724 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003725 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003726 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003727 final int mPid;
3728 final int mUid;
3729 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003730 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003731
Erik Kline371c7b72016-03-22 17:04:20 +09003732 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003733 request = r;
3734 mPendingIntent = pi;
3735 messenger = null;
3736 mBinder = null;
3737 mPid = getCallingPid();
3738 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003739 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003740 }
3741
Erik Kline371c7b72016-03-22 17:04:20 +09003742 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003743 super();
3744 messenger = m;
3745 request = r;
3746 mBinder = binder;
3747 mPid = getCallingPid();
3748 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003749 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003750 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003751
3752 try {
3753 mBinder.linkToDeath(this, 0);
3754 } catch (RemoteException e) {
3755 binderDied();
3756 }
3757 }
3758
Erik Kline371c7b72016-03-22 17:04:20 +09003759 private String typeString() {
3760 switch (mType) {
3761 case LISTEN: return "Listen";
3762 case REQUEST: return "Request";
3763 case TRACK_DEFAULT: return "Track default";
3764 default:
3765 return "unknown type";
3766 }
3767 }
3768
Robert Greenwalt9258c642014-03-26 16:47:06 -07003769 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003770 if (mBinder != null) {
3771 mBinder.unlinkToDeath(this, 0);
3772 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003773 }
3774
3775 public void binderDied() {
3776 log("ConnectivityService NetworkRequestInfo binderDied(" +
3777 request + ", " + mBinder + ")");
3778 releaseNetworkRequest(request);
3779 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003780
Erik Kline371c7b72016-03-22 17:04:20 +09003781 /**
3782 * Returns true iff. the contained NetworkRequest is one that:
3783 *
3784 * - should be associated with at most one satisfying network
3785 * at a time;
3786 *
3787 * - should cause a network to be kept up if it is the only network
3788 * which can satisfy the NetworkReqeust.
3789 *
3790 * For full detail of how isRequest() is used for pairing Networks with
3791 * NetworkRequests read rematchNetworkAndRequests().
3792 *
3793 * TODO: Rename to something more properly descriptive.
3794 */
3795 public boolean isRequest() {
3796 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3797 (mType == NetworkRequestType.REQUEST);
3798 }
3799
Robert Greenwalta67be032014-05-16 15:49:14 -07003800 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003801 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003802 " from uid/pid:" + mUid + "/" + mPid +
3803 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003804 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003805 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003806 }
3807
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003808 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3809 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3810 if (badCapability != null) {
3811 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003812 }
3813 }
3814
Erik Kline9d598e12015-07-13 16:37:51 +09003815 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003816 final SortedSet<Integer> thresholds = new TreeSet();
3817 synchronized (nai) {
3818 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3819 if (nri.request.networkCapabilities.hasSignalStrength() &&
3820 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3821 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3822 }
3823 }
3824 }
Erik Kline9d598e12015-07-13 16:37:51 +09003825 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003826 }
3827
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003828 private void updateSignalStrengthThresholds(
3829 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3830 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003831 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003832 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3833
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003834 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003835 String detail;
3836 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3837 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3838 } else {
3839 detail = reason;
3840 }
3841 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3842 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3843 }
3844
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003845 nai.asyncChannel.sendMessage(
3846 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003847 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003848 }
3849
Robert Greenwalt9258c642014-03-26 16:47:06 -07003850 @Override
3851 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003852 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003853 final NetworkRequestType type = (networkCapabilities == null)
3854 ? NetworkRequestType.TRACK_DEFAULT
3855 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003856 // If the requested networkCapabilities is null, take them instead from
3857 // the default network request. This allows callers to keep track of
3858 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003859 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003860 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3861 enforceAccessPermission();
3862 } else {
3863 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3864 enforceNetworkRequestPermissions(networkCapabilities);
3865 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003866 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003867 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003868
Robert Greenwalt6078b502014-06-11 16:05:07 -07003869 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003870 throw new IllegalArgumentException("Bad timeout specified");
3871 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003872
Etan Cohenddb9ef02015-11-18 10:56:15 -08003873 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3874 .equals(networkCapabilities.getNetworkSpecifier())) {
3875 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3876 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3877 }
3878
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003879 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3880 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003881 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003882 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003883
3884 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003885 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003886 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003887 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003888 }
3889 return networkRequest;
3890 }
3891
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003892 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003893 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003894 enforceConnectivityInternalPermission();
3895 } else {
3896 enforceChangePermission();
3897 }
3898 }
3899
fenglub15e72b2015-03-20 11:29:56 -07003900 @Override
fengludb571472015-04-21 17:12:05 -07003901 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003902 enforceAccessPermission();
3903 NetworkAgentInfo nai = null;
3904 if (network == null) {
3905 return false;
3906 }
3907 synchronized (mNetworkForNetId) {
3908 nai = mNetworkForNetId.get(network.netId);
3909 }
3910 if (nai != null) {
3911 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3912 return true;
3913 }
3914 return false;
3915 }
3916
3917
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003918 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3919 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003920 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003921 final int uidRules;
3922 final int uid = Binder.getCallingUid();
3923 synchronized(mRulesLock) {
3924 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3925 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003926 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003927 // we could silently fail or we can filter the available nets to only give
3928 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003929 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003930 }
3931 }
3932 }
3933
Robert Greenwalt9258c642014-03-26 16:47:06 -07003934 @Override
3935 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3936 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003937 checkNotNull(operation, "PendingIntent cannot be null.");
3938 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3939 enforceNetworkRequestPermissions(networkCapabilities);
3940 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003941 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003942
3943 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3944 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003945 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003946 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003947 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003948 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3949 nri));
3950 return networkRequest;
3951 }
3952
Jeremy Joslin79294842014-12-03 17:15:28 -08003953 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3954 mHandler.sendMessageDelayed(
3955 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3956 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3957 }
3958
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003959 @Override
3960 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003961 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003962 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3963 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003964 }
3965
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003966 // In order to implement the compatibility measure for pre-M apps that call
3967 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3968 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3969 // This ensures it has permission to do so.
3970 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3971 if (nc == null) {
3972 return false;
3973 }
3974 int[] transportTypes = nc.getTransportTypes();
3975 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3976 return false;
3977 }
3978 try {
3979 mContext.enforceCallingOrSelfPermission(
3980 android.Manifest.permission.ACCESS_WIFI_STATE,
3981 "ConnectivityService");
3982 } catch (SecurityException e) {
3983 return false;
3984 }
3985 return true;
3986 }
3987
Robert Greenwalt9258c642014-03-26 16:47:06 -07003988 @Override
3989 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3990 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003991 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3992 enforceAccessPermission();
3993 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994
Erik Kline7523eb32015-07-09 18:24:03 +09003995 NetworkRequest networkRequest = new NetworkRequest(
3996 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003997 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09003998 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003999 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004000
4001 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4002 return networkRequest;
4003 }
4004
4005 @Override
4006 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4007 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004008 checkNotNull(operation, "PendingIntent cannot be null.");
4009 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4010 enforceAccessPermission();
4011 }
4012
Erik Kline7523eb32015-07-09 18:24:03 +09004013 NetworkRequest networkRequest = new NetworkRequest(
4014 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004015 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004016 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004017 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004018
4019 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004020 }
4021
4022 @Override
4023 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004024 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4025 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004026 }
4027
4028 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004029 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004030 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004031 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4032 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004033 }
4034
Robert Greenwalta67be032014-05-16 15:49:14 -07004035 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004036 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004037 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4038 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4039 }
4040
4041 @Override
4042 public void unregisterNetworkFactory(Messenger messenger) {
4043 enforceConnectivityInternalPermission();
4044 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4045 }
4046
4047 private void handleUnregisterNetworkFactory(Messenger messenger) {
4048 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4049 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004050 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004051 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004052 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004053 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004054 }
4055
Robert Greenwalt7b816022014-04-18 15:25:25 -07004056 /**
4057 * NetworkAgentInfo supporting a request by requestId.
4058 * These have already been vetted (their Capabilities satisfy the request)
4059 * and the are the highest scored network available.
4060 * the are keyed off the Requests requestId.
4061 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004062 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004063 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4064 new SparseArray<NetworkAgentInfo>();
4065
Paul Jensen31a94f42015-02-13 14:18:39 -05004066 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4067 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004068 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4069 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004070 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4071 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4072 // there may not be a strict 1:1 correlation between the two.
4073 @GuardedBy("mNetworkForNetId")
4074 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004075
Robert Greenwalt7b816022014-04-18 15:25:25 -07004076 // NetworkAgentInfo keyed off its connecting messenger
4077 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004078 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004079 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4080 new HashMap<Messenger, NetworkAgentInfo>();
4081
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004082 @GuardedBy("mBlockedAppUids")
4083 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4084
Paul Jensen2c311d62014-11-17 12:34:51 -05004085 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004086 private final NetworkRequest mDefaultRequest;
4087
Erik Klineda4bfa82015-04-30 12:58:40 +09004088 // Request used to optionally keep mobile data active even when higher
4089 // priority networks like Wi-Fi are active.
4090 private final NetworkRequest mDefaultMobileDataRequest;
4091
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004092 private NetworkAgentInfo getDefaultNetwork() {
4093 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4094 }
4095
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004096 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004097 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004098 }
4099
Paul Jensen31a94f42015-02-13 14:18:39 -05004100 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004101 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004102 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004103 enforceConnectivityInternalPermission();
4104
Paul Jensen2c311d62014-11-17 12:34:51 -05004105 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4106 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004107 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004108 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4109 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004110 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004111 synchronized (this) {
4112 nai.networkMonitor.systemReady = mSystemReady;
4113 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004114 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004115 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004116 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004117 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004118 }
4119
4120 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4121 if (VDBG) log("Got NetworkAgent Messenger");
4122 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004123 synchronized (mNetworkForNetId) {
4124 mNetworkForNetId.put(na.network.netId, na);
4125 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004126 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4127 NetworkInfo networkInfo = na.networkInfo;
4128 na.networkInfo = null;
4129 updateNetworkInfo(na, networkInfo);
4130 }
4131
4132 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4133 LinkProperties newLp = networkAgent.linkProperties;
4134 int netId = networkAgent.network.netId;
4135
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004136 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4137 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004138 if (networkAgent.clatd != null) {
4139 networkAgent.clatd.fixupLinkProperties(oldLp);
4140 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004141
Paul Jensen992f2522014-04-28 10:33:11 -04004142 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004143 updateMtu(newLp, oldLp);
4144 // TODO - figure out what to do for clat
4145// for (LinkProperties lp : newLp.getStackedLinks()) {
4146// updateMtu(lp, null);
4147// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004148 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004149
Erik Kline94887872016-04-05 13:30:49 +09004150 updateRoutes(newLp, oldLp, netId);
4151 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004152
Paul Jensen3b759822014-05-13 11:44:01 -04004153 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004154 if (isDefaultNetwork(networkAgent)) {
4155 handleApplyDefaultProxy(newLp.getHttpProxy());
4156 } else {
4157 updateProxy(newLp, oldLp, networkAgent);
4158 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004159 // TODO - move this check to cover the whole function
4160 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004161 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004162 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4163 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004164
4165 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004166 }
4167
Lorenzo Colitti95439462014-10-09 13:44:48 +09004168 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4169 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4170 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004171
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004172 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004173 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4174 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004175 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004176 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004177 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004178 }
Paul Jensen992f2522014-04-28 10:33:11 -04004179
4180 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4181 CompareResult<String> interfaceDiff = new CompareResult<String>();
4182 if (oldLp != null) {
4183 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4184 } else if (newLp != null) {
4185 interfaceDiff.added = newLp.getAllInterfaceNames();
4186 }
4187 for (String iface : interfaceDiff.added) {
4188 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004189 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004190 mNetd.addInterfaceToNetwork(iface, netId);
4191 } catch (Exception e) {
4192 loge("Exception adding interface: " + e);
4193 }
4194 }
4195 for (String iface : interfaceDiff.removed) {
4196 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004197 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004198 mNetd.removeInterfaceFromNetwork(iface, netId);
4199 } catch (Exception e) {
4200 loge("Exception removing interface: " + e);
4201 }
4202 }
4203 }
4204
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004205 /**
4206 * Have netd update routes from oldLp to newLp.
4207 * @return true if routes changed between oldLp and newLp
4208 */
4209 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004210 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4211 if (oldLp != null) {
4212 routeDiff = oldLp.compareAllRoutes(newLp);
4213 } else if (newLp != null) {
4214 routeDiff.added = newLp.getAllRoutes();
4215 }
4216
4217 // add routes before removing old in case it helps with continuous connectivity
4218
4219 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4220 for (RouteInfo route : routeDiff.added) {
4221 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004222 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004223 try {
4224 mNetd.addRoute(netId, route);
4225 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004226 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4227 loge("Exception in addRoute for non-gateway: " + e);
4228 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 }
4230 }
4231 for (RouteInfo route : routeDiff.added) {
4232 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004233 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004234 try {
4235 mNetd.addRoute(netId, route);
4236 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004237 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4238 loge("Exception in addRoute for gateway: " + e);
4239 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004240 }
4241 }
4242
4243 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004244 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004245 try {
4246 mNetd.removeRoute(netId, route);
4247 } catch (Exception e) {
4248 loge("Exception in removeRoute: " + e);
4249 }
4250 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004251 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004252 }
Erik Kline41368502015-06-17 13:19:54 +09004253
Erik Kline94887872016-04-05 13:30:49 +09004254 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4255 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4256 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004257 }
Erik Kline94887872016-04-05 13:30:49 +09004258
4259 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004260 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004261 try {
4262 mNetd.setDnsServersForNetwork(
4263 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4264 } catch (Exception e) {
4265 loge("Exception in setDnsServersForNetwork: " + e);
4266 }
4267 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4268 if (defaultNai != null && defaultNai.network.netId == netId) {
4269 setDefaultDnsSystemProperties(dnses);
4270 }
4271 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004272 }
4273
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004274 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4275 int last = 0;
4276 for (InetAddress dns : dnses) {
4277 ++last;
4278 String key = "net.dns" + last;
4279 String value = dns.getHostAddress();
4280 SystemProperties.set(key, value);
4281 }
4282 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4283 String key = "net.dns" + i;
4284 SystemProperties.set(key, "");
4285 }
4286 mNumDnsEntries = last;
4287 }
4288
Paul Jensen3d194ea2015-06-16 14:27:36 -04004289 /**
4290 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4291 * augmented with any stateful capabilities implied from {@code networkAgent}
4292 * (e.g., validated status and captive portal status).
4293 *
Paul Jensene0988542015-06-25 15:30:08 -04004294 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004295 * @param networkCapabilities the new network capabilities.
4296 */
Paul Jensene0988542015-06-25 15:30:08 -04004297 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004298 // Don't modify caller's NetworkCapabilities.
4299 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004300 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004301 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4302 } else {
4303 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4304 }
Paul Jensene0988542015-06-25 15:30:08 -04004305 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004306 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4307 } else {
4308 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4309 }
Paul Jensene0988542015-06-25 15:30:08 -04004310 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4311 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004312 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4313 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4314 try {
4315 mNetd.setNetworkPermission(nai.network.netId,
4316 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4317 null : NetworkManagementService.PERMISSION_SYSTEM);
4318 } catch (RemoteException e) {
4319 loge("Exception in setNetworkPermission: " + e);
4320 }
4321 }
Paul Jensene0988542015-06-25 15:30:08 -04004322 synchronized (nai) {
4323 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004324 }
Paul Jensene0988542015-06-25 15:30:08 -04004325 rematchAllNetworksAndRequests(nai, oldScore);
4326 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004327 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004328 }
4329
Paul Jensenc8b9a742014-09-30 15:37:41 -04004330 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4331 for (int i = 0; i < nai.networkRequests.size(); i++) {
4332 NetworkRequest nr = nai.networkRequests.valueAt(i);
4333 // Don't send listening requests to factories. b/17393458
4334 if (!isRequest(nr)) continue;
4335 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4336 }
4337 }
4338
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4340 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004341 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004342 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4343 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004344 }
4345 }
4346
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004347 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4348 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004349 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004350 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004351 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4352 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004353 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004354 sendIntent(nri.mPendingIntent, intent);
4355 }
4356 // else not handled
4357 }
4358
4359 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4360 mPendingIntentWakeLock.acquire();
4361 try {
4362 if (DBG) log("Sending " + pendingIntent);
4363 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4364 } catch (PendingIntent.CanceledException e) {
4365 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4366 mPendingIntentWakeLock.release();
4367 releasePendingNetworkRequest(pendingIntent);
4368 }
4369 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4370 }
4371
4372 @Override
4373 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4374 String resultData, Bundle resultExtras) {
4375 if (DBG) log("Finished sending " + pendingIntent);
4376 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004377 // Release with a delay so the receiving client has an opportunity to put in its
4378 // own request.
4379 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004380 }
4381
Robert Greenwalt9258c642014-03-26 16:47:06 -07004382 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004383 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004384 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004385 Bundle bundle = new Bundle();
4386 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4387 new NetworkRequest(nri.request));
4388 Message msg = Message.obtain();
4389 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4390 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4391 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4392 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004393 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004394 case ConnectivityManager.CALLBACK_LOSING: {
4395 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4396 break;
4397 }
4398 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4399 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4400 new NetworkCapabilities(networkAgent.networkCapabilities));
4401 break;
4402 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004403 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004404 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4405 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004406 break;
4407 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004408 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004409 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004410 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004411 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004412 if (VDBG) {
4413 log("sending notification " + notifyTypeToName(notificationType) +
4414 " for " + nri.request);
4415 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004416 nri.messenger.send(msg);
4417 } catch (RemoteException e) {
4418 // may occur naturally in the race of binder death.
4419 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4420 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004421 }
4422
Paul Jensenc8b9a742014-09-30 15:37:41 -04004423 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4424 for (int i = 0; i < nai.networkRequests.size(); i++) {
4425 NetworkRequest nr = nai.networkRequests.valueAt(i);
4426 // Ignore listening requests.
4427 if (!isRequest(nr)) continue;
4428 loge("Dead network still had at least " + nr);
4429 break;
4430 }
4431 nai.asyncChannel.disconnect();
4432 }
4433
Robert Greenwalt7b816022014-04-18 15:25:25 -07004434 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4435 if (oldNetwork == null) {
4436 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4437 return;
4438 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004439 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4440 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004441 }
4442
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004443 private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004444 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004445 setupDataActivityTracking(newNetwork);
4446 try {
4447 mNetd.setDefaultNetId(newNetwork.network.netId);
4448 } catch (Exception e) {
4449 loge("Exception setting default network :" + e);
4450 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004451 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004452 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004453 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004454 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Hugo Benichi5f16f762016-04-20 12:09:33 +09004455 logDefaultNetworkEvent(newNetwork, prevNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004456 }
4457
Paul Jensen2161a8e2014-09-11 11:00:39 -04004458 // Handles a network appearing or improving its score.
4459 //
4460 // - Evaluates all current NetworkRequests that can be
4461 // satisfied by newNetwork, and reassigns to newNetwork
4462 // any such requests for which newNetwork is the best.
4463 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004464 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004465 // needed. A network is needed if it is the best network for
4466 // one or more NetworkRequests, or if it is a VPN.
4467 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004468 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004469 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004470 //
4471 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4472 // networks that have no chance (i.e. even if validated)
4473 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004474 //
4475 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4476 // it does not remove NetworkRequests that other Networks could better satisfy.
4477 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4478 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4479 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004480 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004481 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004482 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4483 // performed to tear down unvalidated networks that have no chance (i.e. even if
4484 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004485 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004486 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004487 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004488 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004489 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004490 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004491 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004492 // Find and migrate to this Network any NetworkRequests for
4493 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004494 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004495 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004496 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004497 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004498 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4499 final boolean satisfies = newNetwork.satisfies(nri.request);
4500 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004501 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004502 log("Network " + newNetwork.name() + " was already satisfying" +
4503 " request " + nri.request.requestId + ". No change.");
4504 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004505 keep = true;
4506 continue;
4507 }
4508
4509 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004510 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004511 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004512 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004513 // This is not a request, it's a callback listener.
4514 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004515 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004516 continue;
4517 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004518
Robert Greenwalt7b816022014-04-18 15:25:25 -07004519 // next check if it's better than any current network we're using for
4520 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004521 if (VDBG) {
4522 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004523 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4524 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 }
4526 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004527 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004528 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004529 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004530 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004531 currentNetwork.networkRequests.remove(nri.request.requestId);
4532 currentNetwork.networkLingered.add(nri.request);
4533 affectedNetworks.add(currentNetwork);
4534 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004535 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004536 }
Paul Jensen573a0352015-01-08 10:49:34 -05004537 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004538 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004539 if (!newNetwork.addRequest(nri.request)) {
4540 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4541 }
4542 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004544 // Tell NetworkFactories about the new score, so they can stop
4545 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004546 // TODO - this could get expensive if we have alot of requests for this
4547 // network. Think about if there is a way to reduce this. Push
4548 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004549 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004550 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004551 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004552 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004553 }
4554 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004555 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4556 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4557 // mark it as no longer satisfying "nri". Because networks are processed by
4558 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4559 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4560 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4561 // This means this code doesn't have to handle the case where "currentNetwork" no
4562 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4563 if (DBG) {
4564 log("Network " + newNetwork.name() + " stopped satisfying" +
4565 " request " + nri.request.requestId);
4566 }
4567 newNetwork.networkRequests.remove(nri.request.requestId);
4568 if (currentNetwork == newNetwork) {
4569 mNetworkForRequestId.remove(nri.request.requestId);
4570 sendUpdatedScoreToFactories(nri.request, 0);
4571 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004572 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004573 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4574 newNetwork.name() +
4575 " without updating mNetworkForRequestId or factories!");
4576 }
4577 }
4578 // TODO: technically, sending CALLBACK_LOST here is
4579 // incorrect if nri is a request (not a listen) and there
4580 // is a replacement network currently connected that can
4581 // satisfy it. However, the only capability that can both
4582 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4583 // so this code is only incorrect for a network that loses
4584 // the TRUSTED capability, which is a rare case.
4585 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004586 }
4587 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004588 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004589 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004590 if (nai.lingering) {
4591 // Already lingered. Nothing to do. This can only happen if "nai" is in
4592 // "affectedNetworks" twice. The reasoning being that to get added to
4593 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4594 // (i.e. not lingered) so it could have only been lingered by this loop.
4595 // unneeded(nai) will be false and we'll call unlinger() below which would
4596 // be bad, so handle it here.
4597 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004598 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004599 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004600 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004601 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004602 }
4603 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004604 if (isNewDefault) {
4605 // Notify system services that this network is up.
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004606 makeDefault(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004607 synchronized (ConnectivityService.this) {
4608 // have a new default network, release the transition wakelock in
4609 // a second if it's held. The second pause is to allow apps
4610 // to reconnect over the new network
4611 if (mNetTransitionWakeLock.isHeld()) {
4612 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4613 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4614 mNetTransitionWakeLockSerialNumber, 0),
4615 1000);
4616 }
4617 }
4618 }
4619
4620 // do this after the default net is switched, but
4621 // before LegacyTypeTracker sends legacy broadcasts
4622 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4623
4624 if (isNewDefault) {
4625 // Maintain the illusion: since the legacy API only
4626 // understands one network at a time, we must pretend
4627 // that the current default network disconnected before
4628 // the new one connected.
4629 if (oldDefaultNetwork != null) {
4630 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4631 oldDefaultNetwork, true);
4632 }
4633 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4634 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4635 notifyLockdownVpn(newNetwork);
4636 }
4637
Robert Greenwalt7b816022014-04-18 15:25:25 -07004638 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004639 // Notify battery stats service about this network, both the normal
4640 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004641 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004642 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004643 final IBatteryStats bs = BatteryStatsService.getService();
4644 final int type = newNetwork.networkInfo.getType();
4645
4646 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4647 bs.noteNetworkInterfaceType(baseIface, type);
4648 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4649 final String stackedIface = stacked.getInterfaceName();
4650 bs.noteNetworkInterfaceType(stackedIface, type);
4651 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4652 }
4653 } catch (RemoteException ignored) {
4654 }
4655
Robert Greenwalt152ed372014-12-17 17:19:53 -08004656 // This has to happen after the notifyNetworkCallbacks as that tickles each
4657 // ConnectivityManager instance so that legacy requests correctly bind dns
4658 // requests to this network. The legacy users are listening for this bcast
4659 // and will generally do a dns request so they can ensureRouteToHost and if
4660 // they do that before the callbacks happen they'll use the default network.
4661 //
4662 // TODO: Is there still a race here? We send the broadcast
4663 // after sending the callback, but if the app can receive the
4664 // broadcast before the callback, it might still break.
4665 //
4666 // This *does* introduce a race where if the user uses the new api
4667 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4668 // they may get old info. Reverse this after the old startUsing api is removed.
4669 // This is on top of the multiple intent sequencing referenced in the todo above.
4670 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4671 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4672 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4673 // legacy type tracker filters out repeat adds
4674 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4675 }
4676 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004677
4678 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4679 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4680 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4681 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4682 if (newNetwork.isVPN()) {
4683 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4684 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004685 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004686 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4687 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004688 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004689 if (DBG) log("Reaping " + nai.name());
4690 teardownUnneededNetwork(nai);
4691 }
4692 }
4693 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004694 }
4695
Paul Jensen1c7ba022015-06-16 14:27:36 -04004696 /**
4697 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4698 * being disconnected.
4699 * @param changed If only one Network's score or capabilities have been modified since the last
4700 * time this function was called, pass this Network in this argument, otherwise pass
4701 * null.
4702 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4703 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4704 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4705 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4706 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004707 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004708 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004709 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4710 // to avoid the slowness. It is not simply enough to process just "changed", for
4711 // example in the case where "changed"'s score decreases and another network should begin
4712 // satifying a NetworkRequest that "changed" currently satisfies.
4713
4714 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4715 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4716 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004717 if (changed != null && oldScore < changed.getCurrentScore()) {
4718 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004719 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004720 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4721 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4722 // Rematch higher scoring networks first to prevent requests first matching a lower
4723 // scoring network and then a higher scoring network, which could produce multiple
4724 // callbacks and inadvertently unlinger networks.
4725 Arrays.sort(nais);
4726 for (NetworkAgentInfo nai : nais) {
4727 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004728 // Only reap the last time through the loop. Reaping before all rematching
4729 // is complete could incorrectly teardown a network that hasn't yet been
4730 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004731 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004732 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004733 }
4734 }
4735 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004736
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004737 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004738 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004739 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004740 // For now only update icons for default connection.
4741 // TODO: Update WiFi and cellular icons separately. b/17237507
4742 if (!isDefaultNetwork(nai)) return;
4743
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004744 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004745 // Don't repeat publish.
4746 if (newInetCondition == mDefaultInetConditionPublished) return;
4747
4748 mDefaultInetConditionPublished = newInetCondition;
4749 sendInetConditionBroadcast(nai.networkInfo);
4750 }
4751
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004752 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4753 if (mLockdownTracker != null) {
4754 if (nai != null && nai.isVPN()) {
4755 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4756 } else {
4757 mLockdownTracker.onNetworkInfoChanged();
4758 }
4759 }
4760 }
4761
Robert Greenwalt7b816022014-04-18 15:25:25 -07004762 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4763 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004764 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004765 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004766 synchronized (networkAgent) {
4767 oldInfo = networkAgent.networkInfo;
4768 networkAgent.networkInfo = newInfo;
4769 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004770 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004771
4772 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004773 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4774 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4775 notifyIfacesChangedForNetworkStats();
4776 } else if (VDBG) log("ignoring duplicate network state non-change");
4777 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004778 return;
4779 }
4780 if (DBG) {
4781 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4782 (oldInfo == null ? "null" : oldInfo.getState()) +
4783 " to " + state);
4784 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004785
Paul Jenseneec75412014-08-04 12:21:19 -04004786 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004787 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004788 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004789 if (networkAgent.isVPN()) {
4790 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004791 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4792 (networkAgent.networkMisc == null ||
4793 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004794 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004795 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4796 networkAgent.networkCapabilities.hasCapability(
4797 NET_CAPABILITY_NOT_RESTRICTED) ?
4798 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004799 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004800 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004801 loge("Error creating network " + networkAgent.network.netId + ": "
4802 + e.getMessage());
4803 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004804 }
Paul Jenseneec75412014-08-04 12:21:19 -04004805 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004806 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004807 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004808
Paul Jensenca8f16a2014-05-09 12:47:55 -04004809 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004810 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004811
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004812 if (networkAgent.isVPN()) {
4813 // Temporarily disable the default proxy (not global).
4814 synchronized (mProxyLock) {
4815 if (!mDefaultProxyDisabled) {
4816 mDefaultProxyDisabled = true;
4817 if (mGlobalProxy == null && mDefaultProxy != null) {
4818 sendProxyBroadcast(null);
4819 }
4820 }
4821 }
4822 // TODO: support proxy per network.
4823 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004824
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004825 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4826 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4827 // capabilities, so it only needs to be done once on initial connect, not every time the
4828 // network's capabilities change. Note that we do this before rematching the network,
4829 // so we could decide to tear it down immediately afterwards. That's fine though - on
4830 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4831 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004832 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004833
Paul Jensen2161a8e2014-09-11 11:00:39 -04004834 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004835 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004836
4837 // This has to happen after matching the requests, because callbacks are just requests.
4838 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004839 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004840 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004841 if (networkAgent.isVPN()) {
4842 synchronized (mProxyLock) {
4843 if (mDefaultProxyDisabled) {
4844 mDefaultProxyDisabled = false;
4845 if (mGlobalProxy == null && mDefaultProxy != null) {
4846 sendProxyBroadcast(mDefaultProxy);
4847 }
4848 }
4849 }
4850 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004851 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4852 state == NetworkInfo.State.SUSPENDED) {
4853 // going into or coming out of SUSPEND: rescore and notify
4854 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004855 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004856 }
4857 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4858 ConnectivityManager.CALLBACK_SUSPENDED :
4859 ConnectivityManager.CALLBACK_RESUMED));
4860 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004861 }
4862 }
4863
Robert Greenwaltac96c522014-06-03 16:43:57 -07004864 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004865 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004866 if (score < 0) {
4867 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4868 "). Bumping score to min of 0");
4869 score = 0;
4870 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004871
Paul Jensen2161a8e2014-09-11 11:00:39 -04004872 final int oldScore = nai.getCurrentScore();
4873 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004874
Paul Jensen85cf78e2015-06-25 13:25:07 -04004875 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004876
Paul Jensenc8b9a742014-09-30 15:37:41 -04004877 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004878 }
4879
Robert Greenwalt9258c642014-03-26 16:47:06 -07004880 // notify only this one new request of the current state
4881 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4882 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4883 // TODO - read state from monitor to decide what to send.
4884// if (nai.networkMonitor.isLingering()) {
4885// notifyType = NetworkCallbacks.LOSING;
4886// } else if (nai.networkMonitor.isEvaluating()) {
4887// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4888// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004889 if (nri.mPendingIntent == null) {
4890 callCallbackForRequest(nri, nai, notifyType);
4891 } else {
4892 sendPendingIntentForRequest(nri, nai, notifyType);
4893 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004894 }
4895
Robert Greenwalt8d482522015-06-24 13:23:42 -07004896 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004897 // The NetworkInfo we actually send out has no bearing on the real
4898 // state of affairs. For example, if the default connection is mobile,
4899 // and a request for HIPRI has just gone away, we need to pretend that
4900 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4901 // the state to DISCONNECTED, even though the network is of type MOBILE
4902 // and is still connected.
4903 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4904 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004905 if (state != DetailedState.DISCONNECTED) {
4906 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004907 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004908 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004909 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004910 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4911 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4912 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4913 if (info.isFailover()) {
4914 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4915 nai.networkInfo.setFailover(false);
4916 }
4917 if (info.getReason() != null) {
4918 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4919 }
4920 if (info.getExtraInfo() != null) {
4921 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4922 }
4923 NetworkAgentInfo newDefaultAgent = null;
4924 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004925 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004926 if (newDefaultAgent != null) {
4927 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4928 newDefaultAgent.networkInfo);
4929 } else {
4930 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4931 }
4932 }
4933 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4934 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004935 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004936 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004937 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004938 }
4939 }
4940 }
4941
Robert Greenwalt7b816022014-04-18 15:25:25 -07004942 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004943 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004944 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004945 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4946 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4947 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004948 if (nri.mPendingIntent == null) {
4949 callCallbackForRequest(nri, networkAgent, notifyType);
4950 } else {
4951 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4952 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004953 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004954 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004955
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004956 private String notifyTypeToName(int notifyType) {
4957 switch (notifyType) {
4958 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4959 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4960 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4961 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4962 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4963 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4964 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4965 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4966 }
4967 return "UNKNOWN";
4968 }
4969
Jeff Sharkey69736342014-12-08 14:50:12 -08004970 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004971 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
4972 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08004973 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004974 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08004975 try {
4976 mStatsService.forceUpdateIfaces();
4977 } catch (Exception ignored) {
4978 }
4979 }
4980
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004981 @Override
4982 public boolean addVpnAddress(String address, int prefixLength) {
4983 throwIfLockdownEnabled();
4984 int user = UserHandle.getUserId(Binder.getCallingUid());
4985 synchronized (mVpns) {
4986 return mVpns.get(user).addAddress(address, prefixLength);
4987 }
4988 }
4989
4990 @Override
4991 public boolean removeVpnAddress(String address, int prefixLength) {
4992 throwIfLockdownEnabled();
4993 int user = UserHandle.getUserId(Binder.getCallingUid());
4994 synchronized (mVpns) {
4995 return mVpns.get(user).removeAddress(address, prefixLength);
4996 }
4997 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004998
4999 @Override
5000 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5001 throwIfLockdownEnabled();
5002 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005003 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005004 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005005 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005006 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005007 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005008 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005009 }
5010 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005011 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005012
5013 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005014 public String getCaptivePortalServerUrl() {
5015 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5016 }
5017
5018 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005019 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5020 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5021 enforceKeepalivePermission();
5022 mKeepaliveTracker.startNattKeepalive(
5023 getNetworkAgentInfoForNetwork(network),
5024 intervalSeconds, messenger, binder,
5025 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5026 }
5027
5028 @Override
5029 public void stopKeepalive(Network network, int slot) {
5030 mHandler.sendMessage(mHandler.obtainMessage(
5031 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5032 }
5033
5034 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005035 public void factoryReset() {
5036 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005037
5038 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5039 return;
5040 }
5041
Robin Lee3b3dd942015-05-12 18:14:58 +01005042 final int userId = UserHandle.getCallingUserId();
5043
Stuart Scottf1fb3972015-04-02 18:00:02 -07005044 // Turn airplane mode off
5045 setAirplaneMode(false);
5046
Stuart Scotte3e314d2015-04-20 14:07:45 -07005047 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5048 // Untether
5049 for (String tether : getTetheredIfaces()) {
5050 untether(tether);
5051 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005052 }
5053
Stuart Scotte3e314d2015-04-20 14:07:45 -07005054 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5055 // Turn VPN off
5056 VpnConfig vpnConfig = getVpnConfig(userId);
5057 if (vpnConfig != null) {
5058 if (vpnConfig.legacy) {
5059 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5060 } else {
5061 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5062 // in the future without user intervention.
5063 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005064
Stuart Scotte3e314d2015-04-20 14:07:45 -07005065 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5066 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005067 }
5068 }
5069 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005070
5071 @VisibleForTesting
5072 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5073 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5074 return new NetworkMonitor(context, handler, nai, defaultRequest);
5075 }
Erik Kline48f12f22016-04-14 17:30:59 +09005076
Hugo Benichi5f16f762016-04-20 12:09:33 +09005077 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5078 int newNetid = NETID_UNSET;
5079 int prevNetid = NETID_UNSET;
5080 int[] transports = new int[0];
5081 boolean hadIPv4 = false;
5082 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005083
Hugo Benichi5f16f762016-04-20 12:09:33 +09005084 if (newNai != null) {
5085 newNetid = newNai.network.netId;
5086 transports = newNai.networkCapabilities.getTransportTypes();
5087 }
5088 if (prevNai != null) {
5089 prevNetid = prevNai.network.netId;
5090 final LinkProperties lp = prevNai.linkProperties;
5091 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5092 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5093 }
5094
5095 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097}